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.

security: harden redirect and exception response boundaries (#6198)

LearningCircuit614bf5788c38
diff --git a/changelog.d/+runtime-security-hardening.breaking.md b/changelog.d/+runtime-security-hardening.breaking.md
new file mode 100644
index 0000000000..cce2ce71da
--- /dev/null
+++ b/changelog.d/+runtime-security-hardening.breaking.md
@@ -0,0 +1,17 @@
+**Some error response bodies changed, and two status codes moved.** The
+`/notes/*` JSON APIs, `POST /library/api/rag/test-embedding`, and the Zotero
+endpoints now return fixed error messages instead of the underlying exception
+text — a client that matched on those strings should match on the status code
+instead. The nine LLM-backed notes AI routes (`summarize`,
+`research-questions`, `suggest-tags`, `key-concepts`, `fact-check`,
+`fact-check/<id>/grade`, `synthesize/preview`, `synthesize`,
+`versions/semantic-diff`) now answer **400** with `"error_type":
+"model_not_configured"` and "LLM is not configured. Open Settings and choose a
+provider and model." when no LLM provider/model is configured; eight of them
+previously answered 500 "An internal error occurred". `suggest-tags` already
+gave an accurate message, but as a 400 — the same status it uses for a
+malformed request — so a client couldn't tell "LLM not configured" apart
+from "your request body was invalid" without parsing the text.
+`GET /redirect-static/<path>` now answers **404** rather than redirecting when
+the path contains `.`, `..` or empty segments, a backslash, or a control
+character; ordinary legacy paths such as `css/styles.css` still redirect.
diff --git a/changelog.d/+runtime-security-hardening.security.md b/changelog.d/+runtime-security-hardening.security.md
new file mode 100644
index 0000000000..e0a9348d03
--- /dev/null
+++ b/changelog.d/+runtime-security-hardening.security.md
@@ -0,0 +1,4 @@
+Error responses from the notes API, the RAG embedding test, and the Zotero
+integration no longer echo exception text, and the legacy
+`/redirect-static/<path>` shim rejects paths that a client or proxy could
+normalize outside `/static/`.
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 05a706e21d..84b5b119f8 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -5,7 +5,7 @@ from langchain_core.messages import AIMessage
from loguru import logger
from ..llm import get_llm_from_registry, is_llm_registered
-from ..security.log_sanitizer import scrub_error
+from ..security.log_sanitizer import sanitize_for_log, scrub_error
from ..utilities.search_utilities import remove_think_tags
# Import providers module to trigger auto-discovery. get_llm() has no
@@ -17,6 +17,33 @@ from ..llm.providers.base import normalize_provider
from .thread_settings import get_setting_from_snapshot
+class LLMNotConfiguredError(ValueError):
+ """``get_llm`` could not build an LLM because none is CONFIGURED.
+
+ Raised for the "the user has not set this up yet" failures — no
+ provider, an unknown provider, no ``llm.model``, a provider that
+ auto-discovery did not register. It is deliberately a ``ValueError``
+ subclass so every existing ``except ValueError`` around ``get_llm``
+ keeps behaving exactly as before.
+
+ It exists so an HTTP boundary can tell a configuration failure apart
+ from a request-validation failure *by type* — the alternative is
+ matching on the exception text, which is what the fixed-message
+ boundary rule forbids. Without it, a route that maps ``ValueError`` to
+ "your request was invalid" tells a fresh install with no ``llm.model``
+ that its perfectly valid request was malformed.
+ """
+
+
+# The fixed text a route may show for the above. A constant, never
+# ``str(exc)``: the exception messages are setup guidance written for a log
+# reader, not a boundary contract, and a future raise site could put an
+# endpoint URL or a settings path in one.
+LLM_NOT_CONFIGURED_CLIENT_MESSAGE = (
+ "LLM is not configured. Open Settings and choose a provider and model."
+)
+
+
def get_selected_llm_provider(settings_snapshot=None):
return normalize_provider(
get_setting_from_snapshot(
@@ -313,8 +340,26 @@ def get_llm(
for option in get_discovered_provider_options()
} | {"none"}
if provider not in valid_providers:
- logger.error(f"Invalid provider in settings: {provider}")
- raise ValueError(
+ # ``provider`` is a user-settable value (``llm.provider``) reaching a
+ # log sink. The process-wide ``sanitize_log_record`` patcher already
+ # strips control characters (\x00-\x1f, \x7f) from every loguru
+ # record's message, so ``sanitize_for_log`` isn't newline/ANSI
+ # defence here -- it adds the length cap plus the ``None`` guard
+ # below. The exception text is a different audience (it never
+ # reaches a client -- boundaries answer with
+ # LLM_NOT_CONFIGURED_CLIENT_MESSAGE) and is left intact so
+ # `match="Invalid provider: <name>"` assertions and the operator's
+ # "which value did I actually set?" question survive.
+ # ``str()`` first: ``normalize_provider`` returns None for an
+ # empty/whitespace-only ``llm.provider``, and that None reaches here
+ # (the ``if provider:`` gates above all skipped). ``sanitize_for_log``
+ # takes a str, so the bare call would turn this configuration error
+ # into a TypeError. ``str(None)`` renders "None", exactly what the
+ # previous f-string logged.
+ logger.error(
+ f"Invalid provider in settings: {sanitize_for_log(str(provider))}"
+ )
+ raise LLMNotConfiguredError(
f"Invalid provider: {provider}. "
f"Must be one of: {sorted(valid_providers)}"
)
@@ -325,7 +370,7 @@ def get_llm(
# substitution to a hardcoded default model.
if not model_name or not model_name.strip():
logger.error("llm.model is not configured (empty/None after lookup)")
- raise ValueError(
+ raise LLMNotConfiguredError(
"LLM model not configured. Please open Settings, choose an LLM "
"provider, and select a model name (e.g. 'gpt-4o-mini' for "
"OpenAI, 'claude-3-5-sonnet-20241022' for Anthropic, "
@@ -360,11 +405,11 @@ def get_llm(
# import time. Two specific guards preserve the user-facing error
# messages for known-bad cases.
if provider == "none":
- raise ValueError(
+ raise LLMNotConfiguredError(
"No LLM provider configured. Please set llm.provider in settings "
"to a valid provider (e.g., 'ollama', 'openai', 'anthropic')."
)
- raise ValueError(
+ raise LLMNotConfiguredError(
f"Provider '{provider}' was not registered by auto-discovery. "
f"This usually indicates an import error during startup — check the "
f"logs for 'Error loading provider from <module>' messages. "
diff --git a/src/local_deep_research/research_library/zotero/__init__.py b/src/local_deep_research/research_library/zotero/__init__.py
index fa85f15045..9904410c3d 100644
--- a/src/local_deep_research/research_library/zotero/__init__.py
+++ b/src/local_deep_research/research_library/zotero/__init__.py
@@ -11,9 +11,15 @@ from .client import (
ZoteroAuthError,
ZoteroTransientError,
)
-from .sync_service import ZoteroSyncService
+from .sync_service import (
+ client_safe_zotero_message,
+ CLIENT_SAFE_ZOTERO_MESSAGES,
+ ZoteroSyncService,
+)
__all__ = [
+ "client_safe_zotero_message",
+ "CLIENT_SAFE_ZOTERO_MESSAGES",
"ZoteroClient",
"ZoteroError",
"ZoteroAuthError",
diff --git a/src/local_deep_research/research_library/zotero/client.py b/src/local_deep_research/research_library/zotero/client.py
index 9d95b4415a..aacb1eb0a0 100644
--- a/src/local_deep_research/research_library/zotero/client.py
+++ b/src/local_deep_research/research_library/zotero/client.py
@@ -66,6 +66,40 @@ _MAX_RETRIES = 4
_MAX_BACKOFF_SECONDS = 60
+# ---------------------------------------------------------------------------
+# Client-safe diagnostics.
+#
+# Each of these is author-written constant text: no upstream response body, no
+# filesystem path, no credential, no caller input. They exist as names rather
+# than inline literals because the HTTP layer forwards a Zotero failure to the
+# browser only if its text is one of them — see
+# ``CLIENT_SAFE_ZOTERO_MESSAGES`` in ``sync_service.py``, which maps each
+# message to ITSELF, so what a client receives is always one of these module
+# constants and never the exception's own string.
+#
+# The consequence is the useful one: every other raise site in this package —
+# including the ones that interpolate an HTTP status, a retry count or an
+# exception class name — is replaced with a generic message automatically,
+# and a future raise site cannot leak upstream detail by being forgotten.
+# ---------------------------------------------------------------------------
+ZOTERO_KEY_REJECTED_MESSAGE = (
+ "Zotero rejected the API key (HTTP 403). Check the key and that it has "
+ "read access to this library."
+)
+ZOTERO_RESOURCE_NOT_FOUND_MESSAGE = (
+ "Zotero resource not found (HTTP 404). Check the library id / collection "
+ "key."
+)
+# The most common Zotero misconfiguration by far, and unguessable from a bare
+# "request failed": the library-ID setting holds a username instead of the
+# numeric ID. Dropping this text costs the user the one hint that resolves it.
+ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE = (
+ "Zotero rejected the request (HTTP 400). This usually means the library "
+ "ID is not the NUMERIC userID / group ID from zotero.org/settings/keys "
+ "(e.g. a username was entered instead)."
+)
+
+
class ZoteroError(Exception):
"""Base error for Zotero API interactions."""
@@ -308,15 +342,9 @@ class ZoteroClient:
status = response.status_code
if status == 403:
- raise ZoteroAuthError(
- "Zotero rejected the API key (HTTP 403). Check the key "
- "and that it has read access to this library."
- )
+ raise ZoteroAuthError(ZOTERO_KEY_REJECTED_MESSAGE)
if status == 404:
- raise ZoteroError(
- "Zotero resource not found (HTTP 404). Check the library "
- "id / collection key."
- )
+ raise ZoteroError(ZOTERO_RESOURCE_NOT_FOUND_MESSAGE)
if status in (429, 500, 502, 503, 504):
logger.warning(
f"Zotero transient HTTP {status} (attempt {attempt})"
@@ -334,12 +362,7 @@ class ZoteroClient:
if status == 400:
# The most common cause by far: a username (or other
# non-numeric value) in the library-ID setting.
- raise ZoteroError(
- "Zotero rejected the request (HTTP 400). This usually "
- "means the library ID is not the NUMERIC userID / group "
- "ID from zotero.org/settings/keys (e.g. a username was "
- "entered instead)."
- )
+ raise ZoteroError(ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE)
if not (200 <= status < 300):
raise ZoteroError(f"Zotero request failed (HTTP {status})")
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index 98e95c325a..09411762c7 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -55,8 +55,8 @@ from ...database.models.library import (
from ...database.models.zotero import ZoteroItemMap, ZoteroSyncState
from ...database.session_context import get_user_db_session, safe_rollback
from ...security import (
- sanitize_error_for_client,
sanitize_filename,
+ scrub_error,
UnsafeFilenameError,
)
from ...settings.manager import SettingsManager
@@ -69,6 +69,9 @@ from ..services.pdf_storage_manager import (
)
from ..utils import apply_user_subdir, ensure_in_collection
from .client import (
+ ZOTERO_KEY_REJECTED_MESSAGE,
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ ZOTERO_RESOURCE_NOT_FOUND_MESSAGE,
ZoteroClient,
ZoteroError,
ZoteroItem,
@@ -76,6 +79,69 @@ from .client import (
)
+# Configuration guidance. Like the three in ``client.py`` these are constant,
+# author-written text — they are not derived from an exception at all; the two
+# below are ordinary return values of ``_resolve_library_id``.
+ZOTERO_API_KEY_REQUIRED_MESSAGE = (
+ "A Zotero API key is required (unless using the local API)."
+)
+ZOTERO_GROUP_ID_REQUIRED_MESSAGE = (
+ "Zotero group libraries need the numeric group ID — use the group "
+ "picker, or the number in the group's URL on zotero.org."
+)
+ZOTERO_USER_ID_UNRESOLVED_MESSAGE = (
+ "Could not determine the Zotero userID from the API key — check the key, "
+ "or enter the numeric userID shown at zotero.org/settings/keys."
+)
+
+# The set of messages that may be shown to a browser. It is written as a
+# dict mapping each message to ITSELF so ``client_safe_zotero_message`` can
+# look an exception's text up and hand back THIS module's constant rather
+# than the string it was looked up with — no exception-derived value crosses
+# the HTTP boundary. A miss — every message that interpolates an HTTP status,
+# a retry count, an item count or an exception class name, and anything a
+# future raise site invents — yields nothing and the caller substitutes a
+# generic message.
+#
+# Not all six are reachable as lookup KEYS, and the difference matters when
+# reading this file. Five of them do travel inside an exception:
+# ``ZOTERO_KEY_REJECTED_MESSAGE`` / ``ZOTERO_RESOURCE_NOT_FOUND_MESSAGE`` /
+# ``ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE`` are raised by ``client._request``,
+# and ``ZOTERO_GROUP_ID_REQUIRED_MESSAGE`` /
+# ``ZOTERO_USER_ID_UNRESOLVED_MESSAGE`` are returned by
+# ``_resolve_library_id`` and re-raised as ``ZoteroError`` by
+# ``list_collections`` / ``list_groups``. ``ZOTERO_API_KEY_REQUIRED_MESSAGE``
+# never is: ``test_connection`` returns it as a dict value, which the router
+# forwards via ``result.get("error")`` without a lookup. It is listed here
+# because this collection doubles as the inventory of client-visible Zotero
+# strings, not because anything looks it up.
+CLIENT_SAFE_ZOTERO_MESSAGES = {
+ message: message
+ for message in (
+ ZOTERO_KEY_REJECTED_MESSAGE,
+ ZOTERO_RESOURCE_NOT_FOUND_MESSAGE,
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ ZOTERO_API_KEY_REQUIRED_MESSAGE,
+ ZOTERO_GROUP_ID_REQUIRED_MESSAGE,
+ ZOTERO_USER_ID_UNRESOLVED_MESSAGE,
+ )
+}
+
+
+def client_safe_zotero_message(exc: BaseException, fallback: str) -> str:
+ """Return the curated text for ``exc``, or ``fallback``.
+
+ The return value is always either a module constant from
+ ``CLIENT_SAFE_ZOTERO_MESSAGES`` or the caller's own literal — never the
+ exception's string — so this is a boundary, not a scrubber.
+ """
+ try:
+ text = str(exc)
+ except Exception:
+ return fallback
+ return CLIENT_SAFE_ZOTERO_MESSAGES.get(text) or fallback
+
+
@dataclass
class ZoteroConfig:
"""Snapshot of the user's Zotero settings."""
@@ -229,11 +295,7 @@ class ZoteroSyncService:
lid = cfg.library_id
if cfg.library_type == "group":
if not lid.isdigit():
- return (
- "Zotero group libraries need the numeric group ID — use "
- "the group picker, or the number in the group's URL on "
- "zotero.org."
- )
+ return ZOTERO_GROUP_ID_REQUIRED_MESSAGE
return None
if cfg.use_local_api:
if not lid:
@@ -267,11 +329,7 @@ class ZoteroSyncService:
)
cfg.library_id = self._resolved_user_id
return None
- return (
- "Could not determine the Zotero userID from the API key — check "
- "the key, or enter the numeric userID shown at "
- "zotero.org/settings/keys."
- )
+ return ZOTERO_USER_ID_UNRESOLVED_MESSAGE
def _library_root(self) -> Path:
# Per-user library root (issue #5521), mirroring the DownloadService
@@ -303,8 +361,7 @@ class ZoteroSyncService:
if not cfg.use_local_api and not cfg.api_key:
return {
"success": False,
- "error": "A Zotero API key is required (unless using the "
- "local API).",
+ "error": ZOTERO_API_KEY_REQUIRED_MESSAGE,
}
resolve_error = self._resolve_library_id(cfg)
if resolve_error:
@@ -319,9 +376,38 @@ class ZoteroSyncService:
"collection_count": len(collections),
}
except ZoteroError as exc:
+ # The exception's TEXT is safe to log here, unlike in the
+ # bare-Exception arms elsewhere: every `ZoteroError` in this
+ # package is constructed from author-written text whose only
+ # interpolations are an HTTP status, a retry count, an item
+ # count, `_MAX_PAGES` or `type(exc).__name__` — never an upstream
+ # response body, a filesystem path or the API key. Logging only
+ # the class name would leave an operator unable to tell "HTTP
+ # 400, the library ID looks like a username" from "HTTP 404" once
+ # the client-facing message has fallen back to the generic one.
+ #
+ # It still goes through `scrub_error` and into a local rather
+ # than being interpolated straight from `exc`: the scrub is a
+ # no-op on this text, but it is the repo-wide catch-site idiom
+ # and `.pre-commit-hooks/check-sensitive-logging.py` rejects an
+ # except-variable inside a `logger.warning` outright, so nobody
+ # has to re-argue per-site safety.
+ #
+ # Still no traceback: `cfg` is a local of this frame and its
+ # dataclass repr renders `api_key`, which loguru's `diagnose`
+ # would print for every frame in an attached traceback.
+ safe_msg = scrub_error(exc, cfg.api_key, self.password)
+ logger.warning(
+ f"Zotero: connection test failed "
+ f"({type(exc).__name__}): {safe_msg}"
+ )
return {
"success": False,
- "error": sanitize_error_for_client(str(exc)),
+ "error": client_safe_zotero_message(
+ exc,
+ "Zotero connection failed. Check the configured API key "
+ "and library settings.",
+ ),
}
def list_collections(self) -> List[Dict]:
@@ -808,14 +894,52 @@ class ZoteroSyncService:
session.commit()
except ZoteroError as exc:
stats["status"] = "failed"
- stats["error"] = sanitize_error_for_client(str(exc))
+ stats["error"] = client_safe_zotero_message(
+ exc, "Zotero request failed. Check the integration settings."
+ )
+ # The exception's text is safe here for the same reason as in
+ # `test_connection`, and reaches the log the same way (scrubbed
+ # into a local): every `ZoteroError` message in this package is
+ # author-written, interpolating at most an HTTP status, a retry
+ # count, an item count or an exception class name. Without it the
+ # log records only "ZoteroError" whenever the allowlist misses
+ # and the client sees the generic fallback — exactly the case an
+ # operator needs the detail for. No traceback: `cfg` is a
+ # parameter of this frame and renders `api_key`.
+ safe_msg = scrub_error(exc, cfg.api_key, self.password)
+ logger.warning(
+ f"Zotero: sync failed for collection "
+ f"{collection_key or 'ALL'} ({type(exc).__name__}): "
+ f"{safe_msg}"
+ )
self._mark_failed(cfg, collection_key, stats["error"])
return stats
except Exception as exc:
stats["status"] = "failed"
- stats["error"] = sanitize_error_for_client(str(exc))
- logger.exception(
- f"Zotero: sync failed for collection {collection_key or 'ALL'}"
+ stats["error"] = "Zotero sync failed. See server logs for details."
+ # This handler is the one that flattens the client-visible
+ # message, so the server-side record has to carry the cause.
+ # Deliberately not logger.exception: `cfg` is a parameter of this
+ # method and ZoteroConfig's dataclass repr renders `api_key`,
+ # while `self.password` (the SQLCipher passphrase handed to
+ # get_user_db_session inside this try) is live in the frame too.
+ # An attached traceback renders both under loguru's `diagnose`.
+ # That is a narrow window — only the ephemeral stderr sink can
+ # have `diagnose` on, and only when LDR_APP_DEBUG *and*
+ # LDR_LOGURU_DIAGNOSE are both set; the database, frontend and
+ # file sinks are pinned to `diagnose=False`
+ # (utilities/log_utils.py) — but an operator debugging a failing
+ # sync is precisely who turns those on. Same shape as the
+ # credential-frame handlers in web/queue/processor_v2.py: scrub
+ # against the known secrets, then log without the traceback
+ # chain. `scrub_error` (not bare `redact_secrets`) so the
+ # credential-shape pass runs too and cannot drift from the other
+ # catch sites — compare scheduler/background.py's Zotero handler.
+ safe_msg = scrub_error(exc, cfg.api_key, self.password)
+ logger.warning(
+ f"Zotero: sync failed for collection "
+ f"{collection_key or 'ALL'} ({type(exc).__name__}): "
+ f"{safe_msg}"
)
self._mark_failed(cfg, collection_key, stats["error"])
return stats
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
index c2dd73eb62..9452048950 100644
--- a/src/local_deep_research/security/log_sanitizer.py
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -440,8 +440,36 @@ def sanitize_error_for_client(message: str, max_length: int = 200) -> str:
the ``max_length`` boundary cannot be split by truncation and slip past
the regexes.
- Use this for any exception text surfaced to the browser (API/JSON/SSE
- responses); keep the raw exception server-side via ``logger.exception``.
+ Scope, because it is easy to over-trust: this removes credential
+ *shapes*. It does NOT remove server filesystem paths, SQL text, provider
+ endpoints or dependency internals. Use it on a message an author already
+ knows to be safe apart from a possible embedded secret — not as a filter
+ that makes an arbitrary exception safe to show.
+
+ Where an exception can carry those other kinds of detail, do not pass its
+ text through here at all. Two worked examples, and they are NOT the same
+ technique:
+
+ * ``web/routers/rag.py``'s ``_format_test_embedding_error`` withholds the
+ text entirely — it uses the exception's module and class only to SELECT
+ one of a fixed set of messages, and interpolates neither.
+ * ``web/routers/zotero.py``'s ``_zotero_error_response`` forwards text,
+ but only text that is already one of the package's author-written
+ constants: ``client_safe_zotero_message`` looks ``str(exc)`` up in
+ ``CLIENT_SAFE_ZOTERO_MESSAGES`` and returns the module constant it
+ found (or the caller's own fallback literal), so the value in the
+ response never comes from the exception object.
+
+ Keep the detail server-side. ``logger.exception`` is the default, but it
+ is not unconditional: loguru's ``diagnose`` renders every frame-local in
+ an attached traceback, so in a handler whose frames hold credentials (an
+ API key, the SQLCipher password) log without the traceback instead —
+ ``logger.warning(scrub_error(exc, *known_secrets))``. See the Zotero sync
+ handler in ``research_library/zotero/sync_service.py`` and the
+ credential-frame handlers in ``web/queue/processor_v2.py``. Only the
+ stderr sink can have ``diagnose`` on, and only behind two explicit
+ opt-ins (``utilities/log_utils.py``), but that is exactly the
+ configuration an operator debugging such a failure runs.
"""
return sanitize_for_log(
sanitize_error_message(message), max_length=max_length
diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.py
index 52df1639aa..2848590957 100644
--- a/src/local_deep_research/web/routers/notes.py
+++ b/src/local_deep_research/web/routers/notes.py
@@ -2,8 +2,21 @@
Notes Routes - API endpoints and pages for the notes feature (FastAPI).
Ported from the Flask ``web/routes/notes_routes.py`` blueprint (``notes_bp``,
-url_prefix ``/notes``). Every endpoint is mirrored exactly — same paths,
-methods, status codes, service calls, validation, and error messages.
+url_prefix ``/notes``). Every endpoint preserves the same paths, methods,
+and service calls. Three deliberate divergences from the Flask blueprint:
+
+ * error responses use fixed client-safe messages rather than
+ exception-derived detail;
+ * ``link_research_to_note`` checks that the note exists both before
+ calling the service and again when the service raises (the Flask route
+ recovered that 404 by matching "not found" in the exception text, which
+ the fixed messages no longer allow; the second check covers a note
+ deleted between the first check and the call);
+ * the nine LLM-backed AI routes classify an unconfigured LLM separately
+ from an invalid request and from a server fault -- 400 with
+ ``error_type: model_not_configured`` via
+ ``_llm_not_configured_response``, where Flask answered a generic 500
+ (and, on ``suggest-tags``, a request-validation 400).
Notes on the port:
* ``@login_required`` → ``Depends(require_auth)``; the per-route manual
@@ -32,6 +45,10 @@ from loguru import logger
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import load_only
+from ...config.llm_config import (
+ LLM_NOT_CONFIGURED_CLIENT_MESSAGE,
+ LLMNotConfiguredError,
+)
from ...research_library.notes.services.note_ai_service import NoteAIService
from ...research_library.notes.services.note_service import (
MAX_TAG_LENGTH,
@@ -80,8 +97,22 @@ def _clamp_text_query(value, name, max_len=MAX_SEARCH_LEN):
"""Return value or raise ValueError if it exceeds the cap.
``None``/empty pass through unchanged so optional params behave the
- same as before. The caller wraps this in ``try`` and lets
- ``handle_api_error`` produce the 4xx response.
+ same as before. The caller maps the failure to a fixed 400 response.
+
+ Two distinct failures share the ``ValueError``: a non-string value and
+ an over-length one. A caller that passes ``request.query_params.get(...)``
+ can only ever hit the length branch (Starlette's query params are always
+ ``str``), so a single fixed length message is truthful there. A caller
+ reading a JSON body must decide by type BEFORE calling this — see
+ ``resolve_link`` — because the body is an uncoerced ``dict``.
+
+ That makes the non-string branch DEAD at every current call site (three
+ query-param readers plus ``resolve_link``, which type-checks first). It
+ is kept as a defensive guard, not as live behaviour: without it a future
+ caller that forgets the type check would reach ``len(value)`` and raise
+ ``TypeError``, which no caller here catches, turning a bad body into a
+ 500 instead of a 400. Any new call site that can pass a non-string must
+ still do its own type check so its fixed message stays truthful.
"""
if value is None:
return value
@@ -343,6 +374,48 @@ def _bound_dict_shaped_walk(value: Any, _depth: int) -> tuple[Any, bool]:
return value, False
+def _llm_not_configured_response(operation: str) -> JSONResponse:
+ """400 for a notes AI route whose LLM is not configured.
+
+ Nine routes in this file run an LLM (``summarize``,
+ ``research-questions``, ``suggest-tags``, ``key-concepts``,
+ ``fact-check``, ``fact-check/.../grade``, ``synthesize/preview``,
+ ``synthesize``, ``versions/semantic-diff``). Every one of them reaches
+ ``NoteAIService._get_llm`` -> ``config.llm_config.get_llm``, which raises
+ ``LLMNotConfiguredError`` when the user has not chosen a provider/model
+ yet -- and on a fresh install that is the FIRST thing these endpoints
+ hit. Left to ``handle_api_error`` they answer 500 "contact support"; in
+ ``suggest_tags``, whose handler also maps ``ValueError`` to a
+ request-validation 400, it came back as a bad-request verdict on a body
+ that was perfectly fine. Both send the user looking in the wrong place.
+
+ 400 with ``error_type: model_not_configured`` is this repository's
+ existing answer for an unconfigured LLM, not a 5xx: see
+ ``web/routers/api.py::check_ollama_model`` (the same ``error_type`` for
+ an empty ``llm.model``), ``web/routers/followup.py::start_followup``
+ (400 before any DB write when ``llm.model`` is empty), and
+ ``web/routers/zotero.py::_not_configured_response`` -- "that is a
+ client-state problem, not a server error". The 503s in ``rag.py`` and
+ ``settings.py`` are NOT the precedent: those are egress-policy
+ ``settings_unavailable`` arms, a different condition.
+
+ One helper rather than nine copies so the status, the message and the
+ ``error_type`` cannot drift apart route by route. ``operation`` names
+ the route in the server-side log only; it never reaches the client, and
+ the client message is always the module constant -- never ``str(exc)``,
+ whose setup guidance can carry a settings path.
+ """
+ logger.warning("Notes AI: {} refused, LLM not configured", operation)
+ return JSONResponse(
+ {
+ "success": False,
+ "error": LLM_NOT_CONFIGURED_CLIENT_MESSAGE,
+ "error_type": "model_not_configured",
+ },
+ status_code=400,
+ )
+
+
# 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
@@ -602,9 +675,16 @@ def list_notes(
search = _clamp_text_query(
request.query_params.get("search"), "search"
)
- except ValueError as exc:
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(exc)}, status_code=400
+ {
+ "success": False,
+ "error": (
+ f"search exceeds maximum length "
+ f"({MAX_SEARCH_LEN} chars)"
+ ),
+ },
+ status_code=400,
)
pinned_only = (
request.query_params.get("pinned_only", "").lower() == "true"
@@ -734,11 +814,12 @@ def create_note(
return JSONResponse({"success": True, "id": note_id}, status_code=201)
- except ValueError as e:
- # Validation failures (content size, tag shape) — surface the
- # actual message so the client can fix and retry.
+ except ValueError:
+ # Never serialize exception text at the HTTP boundary. Even callers
+ # that normally raise fixed validation messages can regress to an
+ # exception containing paths, SQL, credentials, or library internals.
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid note data"}, status_code=400
)
except Exception as e:
return handle_api_error("creating note", e)
@@ -773,9 +854,13 @@ def semantic_search_notes(
try:
try:
query = _clamp_text_query(request.query_params.get("q", ""), "q")
- except ValueError as exc:
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(exc)}, status_code=400
+ {
+ "success": False,
+ "error": f"q exceeds maximum length ({MAX_SEARCH_LEN} chars)",
+ },
+ status_code=400,
)
query = (query or "").strip()
if not query:
@@ -863,9 +948,15 @@ def search_notes_for_linking(
query = _clamp_text_query(
request.query_params.get("query", ""), "query"
)
- except ValueError as exc:
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(exc)}, status_code=400
+ {
+ "success": False,
+ "error": (
+ f"query exceeds maximum length ({MAX_SEARCH_LEN} chars)"
+ ),
+ },
+ status_code=400,
)
if not query:
return {"success": True, "notes": []}
@@ -959,11 +1050,10 @@ def update_note(
tags=data.get("tags"),
favorite=pinned,
)
- except ValueError as e:
- # Validation failures (content size, tag shape) — surface the
- # actual message so the client can fix and retry.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid note data"},
+ status_code=400,
)
if not success:
@@ -1124,11 +1214,13 @@ def remove_note_from_collection(
return {"success": True}
- except ValueError as e:
- # Guard failures (e.g. unlinking from the system Notes collection,
- # which is every note's persistent home) — surface the message.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {
+ "success": False,
+ "error": "Note cannot be removed from this collection",
+ },
+ status_code=400,
)
except Exception as e:
return handle_api_error("removing note from collection", e)
@@ -1188,6 +1280,10 @@ def link_research_to_note(
)
service = NoteService(username)
+ if not service.note_exists(note_id):
+ return JSONResponse(
+ {"success": False, "error": "Note not found"}, status_code=404
+ )
link_id = service.link_research_to_note(
note_id=note_id,
research_id=data["research_id"],
@@ -1195,16 +1291,32 @@ def link_research_to_note(
return JSONResponse({"success": True, "id": link_id}, status_code=201)
- except ValueError as e:
- # A missing/non-note id surfaces as ValueError("... not found") — a
- # 404 like every sibling note route; the research-per-note cap is a
- # client-fixable 400.
- if "not found" in str(e).lower():
- return JSONResponse(
- {"success": False, "error": str(e)}, status_code=404
+ except ValueError:
+ # The pre-check above answers 404 for an id that was already unknown.
+ # A note DELETED between that check and the service call lands here
+ # instead (the service raises ValueError("... not found")), so re-run
+ # the existence check to keep that narrow race answering 404 rather
+ # than a misleading "cannot be linked" 400. Best-effort: this runs
+ # inside an except handler, so a failure of the re-check itself must
+ # not replace the 400 with a 500.
+ try:
+ if not NoteService(username).note_exists(note_id):
+ return JSONResponse(
+ {"success": False, "error": "Note not found"},
+ status_code=404,
+ )
+ except Exception:
+ logger.warning(
+ "notes_api: note_exists re-check failed while classifying a "
+ "link-research failure (user={!r})",
+ username,
)
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {
+ "success": False,
+ "error": "Research cannot be linked to this note",
+ },
+ status_code=400,
)
except IntegrityError as exc:
# Only the (document_id, research_id) uniqueness collision means the
@@ -1345,11 +1457,10 @@ def reorder_note_research(
)
return {"success": True}
- except ValueError as e:
- # Validation failures (research-per-note cap) — surface the
- # actual message so the client can fix and retry.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid research order"},
+ status_code=400,
)
except Exception as e:
return handle_api_error("reordering note research", e)
@@ -1429,11 +1540,9 @@ def create_research_note(
{"success": True, "note_id": note_id}, status_code=201
)
- except ValueError as e:
- # Validation failures (title/content caps, tag shape) — surface
- # the actual message so the client can fix and retry.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid note data"}, status_code=400
)
except Exception as e:
return handle_api_error("creating note for research", e)
@@ -1545,12 +1654,13 @@ def save_research_as_note(
{"success": True, "note_id": note_id}, status_code=201
)
- except ValueError as e:
- # Validation failures — most likely the report exceeding the note
- # content cap. Client-fixable only in the sense that the user
- # should know why it refused; surface the message.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {
+ "success": False,
+ "error": "Research cannot be saved as a note",
+ },
+ status_code=400,
)
except Exception as e:
return handle_api_error("saving research as note", e)
@@ -1741,11 +1851,10 @@ def create_research_annotation(
return JSONResponse(
{"success": False, "error": "Research not found"}, status_code=404
)
- except ValueError as e:
- # Validation failures (missing/oversized fields) — surface the
- # actual message so the client can fix and retry.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid annotation data"},
+ status_code=400,
)
except Exception as e:
return handle_api_error("creating research annotation", e)
@@ -1838,11 +1947,10 @@ def create_document_note(
{"success": True, "note_id": note_id}, status_code=201
)
- except ValueError as e:
- # Validation failures (caps, or trying to annotate a note —
- # mutable content, anchors would drift) — surface the message.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid document note data"},
+ status_code=400,
)
except Exception as e:
return handle_api_error("creating note for document", e)
@@ -1937,9 +2045,10 @@ def create_document_annotation(
return JSONResponse(
{"success": False, "error": "Document not found"}, status_code=404
)
- except ValueError as e:
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid annotation data"},
+ status_code=400,
)
except Exception as e:
return handle_api_error("creating document annotation", e)
@@ -2121,6 +2230,11 @@ async def summarize_note(
return {"success": True, "summary": summary}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("summarize")
except Exception as e:
return handle_api_error("summarizing note", e)
@@ -2148,6 +2262,11 @@ async def extract_research_questions(
return {"success": True, "questions": questions}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("research-questions")
except Exception as e:
return handle_api_error("extracting research questions", e)
@@ -2225,9 +2344,17 @@ async def suggest_tags(
return {"success": True, "tags": tags}
- except ValueError as e:
+ except LLMNotConfiguredError:
+ # MUST precede the ValueError arm: this is a ValueError subclass, so
+ # ordering is what separates "you have not configured a model" from
+ # "your request body was invalid" here. See
+ # ``_llm_not_configured_response`` for why the answer is a 400 with
+ # ``error_type: model_not_configured``.
+ return _llm_not_configured_response("suggest-tags")
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {"success": False, "error": "Invalid tag request"},
+ status_code=400,
)
except Exception as e:
return handle_api_error("suggesting tags", e)
@@ -2256,6 +2383,11 @@ async def extract_key_concepts(
return {"success": True, "concepts": concepts}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("key-concepts")
except Exception as e:
return handle_api_error("extracting key concepts", e)
@@ -2387,12 +2519,13 @@ def accept_suggested_link(
return {"success": True, "note": result}
- except ValueError as e:
- # A real write failure surfaced by the service (e.g. the appended link
- # pushed the note past the content-size cap) is a client-fixable 400,
- # not the generic 500 handle_api_error would otherwise return.
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(e)}, status_code=400
+ {
+ "success": False,
+ "error": "Suggested link cannot be accepted",
+ },
+ status_code=400,
)
except Exception as e:
return handle_api_error("accepting suggested link", e)
@@ -2523,6 +2656,11 @@ async def fact_check_note(
query = ai.synthesize_factcheck_query(claims)
return {"success": True, "claims": claims, "query": query}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("fact-check")
except Exception as e:
return handle_api_error("starting note fact-check", e)
@@ -2718,6 +2856,11 @@ async def grade_note_fact_check(
)
return JSONResponse(payload, status_code=status_code)
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("fact-check grade")
except Exception as e:
return handle_api_error("grading note fact-check", e)
@@ -2745,13 +2888,32 @@ def resolve_link(
{"success": False, "error": "link_text is required"},
status_code=400,
)
+ link_text = data["link_text"]
+ # ``_NotesBody`` is a plain parsed-JSON dict with no per-field
+ # coercion, so ``link_text`` can be any JSON type. Select the fixed
+ # 400 message by TYPE rather than by matching the exception text:
+ # ``_clamp_text_query`` raises for two different reasons and only
+ # one of them is a length problem, so reporting "exceeds maximum
+ # length" for ``{"link_text": 123}`` would be false.
+ if not isinstance(link_text, str):
+ return JSONResponse(
+ {"success": False, "error": "link_text must be a string"},
+ status_code=400,
+ )
try:
link_text = _clamp_text_query(
- data["link_text"], "link_text", max_len=MAX_LINK_TEXT_LEN
+ link_text, "link_text", max_len=MAX_LINK_TEXT_LEN
)
- except ValueError as exc:
+ except ValueError:
return JSONResponse(
- {"success": False, "error": str(exc)}, status_code=400
+ {
+ "success": False,
+ "error": (
+ f"link_text exceeds maximum length "
+ f"({MAX_LINK_TEXT_LEN} chars)"
+ ),
+ },
+ status_code=400,
)
service = NoteService(username)
@@ -2837,6 +2999,11 @@ async def preview_synthesis(
return {"success": True, "result": preview}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("synthesize preview")
except Exception as e:
return handle_api_error("previewing synthesis", e)
@@ -2994,6 +3161,11 @@ async def synthesize_notes(
{"success": True, "result": result}, status_code=status_code
)
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("synthesize")
except Exception as e:
return handle_api_error("synthesizing notes", e)
@@ -3207,6 +3379,11 @@ async def get_semantic_diff(
return {"success": True, "diff": diff}
+ except LLMNotConfiguredError:
+ # Same contract as suggest-tags: an unconfigured LLM is a
+ # client-state problem, not a 500. See
+ # ``_llm_not_configured_response``.
+ return _llm_not_configured_response("semantic-diff")
except Exception as e:
return handle_api_error("getting semantic diff", e)
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 903591a547..fb51012ad4 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -63,7 +63,6 @@ from ...constants import (
FILE_PATH_TEXT_ONLY,
)
from ...security.log_sanitizer import (
- sanitize_error_for_client,
sanitize_error_message,
)
from ...utilities.db_utils import get_settings_manager
@@ -337,6 +336,24 @@ _UPSTREAM_MODULE_PREFIXES = (
"anthropic",
)
+# Upstream exception classes that mean "the request never reached the
+# provider, or never got an answer" as opposed to "the provider answered and
+# refused". Told apart by class NAME across the MRO so no provider SDK has to
+# be imported here, and matched only inside the upstream branch below — a
+# builtins ``ConnectionError`` is still default-denied. The name is used to
+# pick between two fixed messages; it is not part of either one.
+_CONNECTION_FAILURE_CLASS_NAMES = frozenset(
+ {
+ "APIConnectionError", # openai (APITimeoutError subclasses it)
+ "ConnectError", # httpx
+ "ConnectionError", # requests.exceptions
+ "ConnectTimeout", # httpx
+ "ConnectTimeoutError", # urllib3
+ "NewConnectionError", # urllib3
+ "ProxyError", # httpx / requests / urllib3
+ }
+)
+
def _module_matches(type_module: str, prefix: str) -> bool:
"""True if ``type_module`` is ``prefix`` itself or one of its submodules."""
@@ -354,21 +371,26 @@ def _format_test_embedding_error(exc: Exception, model: str) -> str:
``NoSettingsContextError`` surfaced as a misleading "try a dedicated
embedding model" suggestion.
- Echoing the exception text at all is *opt-in* (CWE-209 / CodeQL alert
- 8001). Only the allowlisted upstream-provider modules get their detail
- surfaced; every other module is treated the way LDR-internal exceptions
- already were — class name only. ``sanitize_error_message`` removes
- credential *shapes*, not server filesystem paths, SQL text or dependency
- internals, and those are exactly what a ``sqlalchemy.exc.*`` or
- ``builtins.OSError`` raised under ``get_embedding_function`` carries.
-
- The detail that *is* surfaced goes through
- :func:`sanitize_error_for_client` (credential redaction, control-char
- strip and a length cap) rather than the bare credential scrubber, so a
- provider cannot replay a multi-kilobyte body into the response.
+ Exception text never crosses the HTTP boundary here. The exception's
+ module and class are used only to SELECT one of the fixed messages below;
+ neither is interpolated into the result, and the full detail stays in the
+ server-side log (``logger.exception`` at the call site).
+
+ Why not simply scrub the text and echo it, which is what
+ :func:`~...security.log_sanitizer.sanitize_error_for_client` is for
+ elsewhere in the tree: that function removes credential *shapes* plus
+ control characters, and caps the length. It does not remove server
+ filesystem paths, SQL text or dependency internals — and those are
+ exactly what the exceptions reachable from this ``try`` block carry. The
+ block opens the user's SQLCipher database and constructs an embedding
+ manager, so a ``sqlalchemy.exc.OperationalError`` (driver text plus
+ ``[SQL: ...]`` and ``[parameters: ...]``), a ``builtins.OSError``
+ (absolute server path and OS account name) or a provider response body
+ are all in range. ``sanitize_error_for_client`` remains the right tool
+ for a message an author already knows to be safe; it is not a filter that
+ makes an arbitrary exception safe, which is why this function does not
+ use it.
"""
- raw_message = str(exc).strip() or type(exc).__name__
- type_name = type(exc).__name__
type_module = type(exc).__module__ or ""
if _module_matches(type_module, _INTERNAL_MODULE_PREFIX):
@@ -379,7 +401,7 @@ def _format_test_embedding_error(exc: Exception, model: str) -> str:
# attach.
return (
f"Embedding test failed for model '{model}' due to an "
- f"internal LDR error ({type_name}). This is a bug in LDR, "
+ "internal LDR error. This is a bug in LDR, "
"not your configuration. Please report it on GitHub with "
"the server logs."
)
@@ -388,9 +410,22 @@ def _format_test_embedding_error(exc: Exception, model: str) -> str:
_module_matches(type_module, prefix)
for prefix in _UPSTREAM_MODULE_PREFIXES
):
+ if _CONNECTION_FAILURE_CLASS_NAMES.intersection(
+ klass.__name__ for klass in type(exc).__mro__
+ ):
+ # Nothing was rejected — the connection never completed. Saying
+ # "the provider rejected the request" here sends the user to
+ # check credentials for what is almost always a wrong host, a
+ # stopped Ollama, or a firewall.
+ return (
+ f"Embedding test failed for model '{model}'. Could not "
+ "connect to the provider; check the URL and that it is "
+ "reachable. The full error is in the server logs."
+ )
return (
- f"Embedding test failed for model '{model}'. The provider "
- f"returned an error: {sanitize_error_for_client(raw_message)}"
+ f"Embedding test failed for model '{model}'. The request to the "
+ "provider failed. Check its URL, credentials, and model name; "
+ "the full error is in the server logs."
)
# Default-deny. Everything outside the upstream allowlist reaches here:
@@ -399,19 +434,18 @@ def _format_test_embedding_error(exc: Exception, model: str) -> str:
# [parameters: ...]), builtins.OSError/PermissionError/FileNotFoundError
# (absolute server paths and the OS account name), chromadb,
# sentence_transformers, langchain_core, botocore... None of that is
- # touched by the credential-shape scrubber, so the detail is withheld and
- # only the class name — a fixed identifier, not reflected input — is
- # returned. The full text is in the server logs (logger.exception at the
- # call site).
+ # touched by the credential-shape scrubber, so no exception-derived detail
+ # is returned. The full text is in the server logs (logger.exception at
+ # the call site).
#
# Worded deliberately unlike the internal-LDR branch above: a bare
# TypeError from langchain's response parser is not an LDR bug, and
# steering the user to "report it on GitHub" for it is the misleading
# guidance #4208 removed.
return (
- f"Embedding test failed for model '{model}' ({type_name}). "
- "Check the provider URL and model name; the full error is in the "
- "server logs."
+ f"Embedding test failed for model '{model}' due to an unexpected "
+ "error. Check the provider URL and model name; the full error is "
+ "in the server logs."
)
@@ -796,14 +830,8 @@ async def test_embedding(
)
logger.exception("Error during testing embedding")
user_message = _format_test_embedding_error(e, model)
- # CWE-209 (CodeQL "Information exposure through an exception"):
- # user_message is exception-derived, but _format_test_embedding_error()
- # echoes exception text only for the allowlisted upstream-provider
- # modules, and only after sanitize_error_for_client(). Every other
- # exception — LDR-internal, sqlalchemy.exc.*, OSError, chromadb... —
- # is reduced to its class name, so no server path, SQL fragment or
- # dependency internal reaches this response. See that function's
- # docstring for the full rationale.
+ # The formatter uses exception type metadata only to select a fixed
+ # message. Raw exception text stays in the server log above.
return JSONResponse(
{"success": False, "error": user_message}, status_code=500
)
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 2ff43408f8..b207d56a5b 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -130,12 +130,37 @@ def redirect_static(path: str):
"""
# Quote so a `?` or `#` in a legacy filename cannot truncate the target
# into a query or fragment. `safe="/"` keeps directory separators intact.
- # The result always begins with the literal "/static/", so it cannot be
- # turned into a protocol-relative (`//host`) off-site redirect.
+ #
+ # `lstrip("/")` plus the fixed `/static/` prefix already kept the target
+ # on this origin (a protocol-relative `//host` needs a leading `//`, and
+ # both slashes are stripped) — that part is unchanged. What the guard
+ # below adds is canonicalisation: `..` and `.` segments normalize out of
+ # `/static` in the client, and clients/proxies do not all treat
+ # backslashes, empty segments and control characters identically. Reject
+ # those ambiguous forms so every accepted target is a canonical static
+ # path.
from urllib.parse import quote
+ path = path.lstrip("/")
+ segments = path.split("/")
+ if (
+ not path
+ or "\\" in path
+ or any(segment in {"", ".", ".."} for segment in segments)
+ or any(
+ ord(character) < 32 or ord(character) == 127 for character in path
+ )
+ ):
+ # Raise rather than returning a body: the app's `@app.exception_
+ # handler(404)` (fastapi_app.py) is what renders a missing resource,
+ # and it serves HTML to browser navigations and JSON only to API
+ # callers. This route exists for bookmarked browser URLs, so a
+ # hand-rolled JSON envelope here would show a raw JSON body in the
+ # browser to the one audience the route has.
+ raise HTTPException(status_code=404, detail="Not found")
+
return RedirectResponse(
- url=f"/static/{quote(path.lstrip('/'), safe='/')}", status_code=302
+ url=f"/static/{quote(path, safe='/')}", status_code=302
)
diff --git a/src/local_deep_research/web/routers/zotero.py b/src/local_deep_research/web/routers/zotero.py
index 9753a71ea7..81a703fb38 100644
--- a/src/local_deep_research/web/routers/zotero.py
+++ b/src/local_deep_research/web/routers/zotero.py
@@ -23,12 +23,13 @@ from ...database.session_passwords import session_password_store
from ...database.thread_local_session import thread_cleanup
from ...research_library.utils import handle_api_error
from ...research_library.zotero import (
+ client_safe_zotero_message,
ZoteroAuthError,
ZoteroError,
ZoteroSyncService,
ZoteroTransientError,
)
-from ...security import sanitize_error_for_client
+from ...security import scrub_error
from ..dependencies.auth import require_auth
from ..template_config import templates
from typing import Annotated
@@ -46,15 +47,37 @@ def _zotero_error_status(exc: ZoteroError) -> int:
def _zotero_error_response(exc: ZoteroError) -> JSONResponse:
- """Zotero-side rejections carry actionable, static messages (bad library
- ID, revoked key, …) — surface them instead of a 500, with a status code
- matching the failure class."""
- # CWE-209 (CodeQL "Information exposure through an exception"):
- # ``str(exc)`` is exception-derived, but sanitize_error_for_client()
- # (credential redaction + control-char strip + length cap) is applied
- # before it leaves this function — a deliberate choice, not a leak.
+ """Map a Zotero failure to a client-safe body and a status code.
+
+ The message is never ``str(exc)``. ``client_safe_zotero_message`` looks
+ the failure text up in the package's allowlist of author-written
+ diagnostics and returns THAT constant, or the fallback below — so the
+ guidance a user actually needs survives (the HTTP 400 "your library ID is
+ a username, not the numeric ID" hint is the one Zotero misconfiguration
+ that is unguessable from a generic message) while nothing exception-
+ derived reaches the response.
+ """
+ if isinstance(exc, ZoteroAuthError):
+ fallback = "Zotero authentication failed. Check the configured API key."
+ elif isinstance(exc, ZoteroTransientError):
+ fallback = "Zotero is temporarily unavailable. Please try again later."
+ else:
+ fallback = "Zotero request failed. Check the integration settings."
+ # Log the text as well as the class. Every ``ZoteroError`` in the
+ # research_library.zotero package is built from author-written strings
+ # whose only interpolations are an HTTP status, a retry count, an item
+ # count, the pagination cap or ``type(exc).__name__`` — no upstream
+ # response body, no filesystem path, no API key (the client reduces a
+ # transport failure to its exception TYPE before raising). So the text is
+ # safe here, and it is the only server-side record of WHICH failure
+ # produced a generic fallback body. It goes through ``scrub_error``
+ # anyway (a no-op on this text) so this catch site matches the
+ # repo-wide idiom. No traceback: this runs on the request path, where
+ # the caller's frames hold the SQLCipher password.
+ safe_msg = scrub_error(exc)
+ logger.warning(f"Zotero request failed ({type(exc).__name__}): {safe_msg}")
return JSONResponse(
- {"success": False, "error": sanitize_error_for_client(str(exc))},
+ {"success": False, "error": client_safe_zotero_message(exc, fallback)},
status_code=_zotero_error_status(exc),
)
@@ -134,14 +157,32 @@ def test_connection(
return _session_expired_response()
try:
result = ZoteroSyncService(username, password).test_connection()
- # CWE-209 (CodeQL "Information exposure through an exception"):
- # ``result`` can carry an exception-derived ``error`` string, but
- # ZoteroSyncService.test_connection() already ran it through
- # sanitize_error_for_client() (or it's one of its own static
- # messages, e.g. from _resolve_library_id) before returning —
- # nothing raw reaches this JSONResponse.
+ # Rebuild the body from an explicit key allowlist rather than
+ # forwarding the service's dict: a field added to the service result
+ # later (a config echo, a resolved id) would otherwise ship to the
+ # browser silently. The `error` value is the service's own curated
+ # text — every failure branch of `test_connection` returns either a
+ # module constant from `CLIENT_SAFE_ZOTERO_MESSAGES` or its own
+ # literal, and none of them is derived from an exception.
+ if not result.get("success"):
+ return JSONResponse(
+ {
+ "success": False,
+ "error": result.get("error")
+ or (
+ "Zotero connection failed. Check the configured API "
+ "key and library settings."
+ ),
+ },
+ status_code=400,
+ )
return JSONResponse(
- result, status_code=(200 if result.get("success") else 400)
+ {
+ "success": True,
+ "library_version": result.get("library_version"),
+ "collection_count": result.get("collection_count"),
+ },
+ status_code=200,
)
except Exception as e:
return handle_api_error("testing Zotero connection", e)
@@ -252,8 +293,16 @@ def sync_now(request: Request, username: Annotated[str, Depends(require_auth)]):
reprocess_skipped=True
)
logger.info(f"Zotero manual sync finished: {result}")
- except Exception:
- logger.exception("Zotero manual sync failed")
+ except Exception as exc:
+ # Not logger.exception: this closure's own `password` and
+ # the sync code's `cfg.api_key` are both live further down
+ # this call stack, and an attached traceback would render
+ # them under loguru's diagnose. Same pattern as
+ # ZoteroSyncService._sync_one's bare-Exception arm
+ # (sync_service.py) -- scrub the known secrets into a local,
+ # then log without the traceback chain.
+ safe_msg = scrub_error(exc, password, cfg.api_key)
+ logger.warning(f"Zotero manual sync failed: {safe_msg}")
threading.Thread(
target=_run, name=f"zotero-sync-{username}", daemon=True
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7967a8e8b3..c8f2e2a830 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -10,7 +10,7 @@ from pathlib import Path
from loguru import logger
from ...exceptions import DuplicateResearchError, ResearchTerminatedException
-from ...config.llm_config import get_llm
+from ...config.llm_config import get_llm, LLMNotConfiguredError
from ...settings.manager import (
SnapshotSettingsContext,
apply_environment_overrides_to_snapshot,
@@ -1520,8 +1520,34 @@ def run_research_process(research_id, query, mode, **kwargs):
keyword in error_msg.lower()
for keyword in config_error_keywords
):
- # This is a configuration error the user can fix
- raise ValueError(
+ # This is a configuration error the user can fix.
+ #
+ # Preserve ``LLMNotConfiguredError`` when that is what
+ # ``get_llm`` raised. The keyword match below is a
+ # string test over ``str(e)``, and re-raising a plain
+ # ``ValueError`` threw the subclass away: a caller that
+ # distinguishes "no model configured" from "bad request"
+ # BY TYPE (see web/routers/notes.py's
+ # ``_llm_not_configured_response``) could no longer tell
+ # them apart downstream of this wrapper, and a fresh
+ # install's missing ``llm.model`` -- which matches the
+ # "not configured" keyword -- was exactly the case that
+ # lost it.
+ #
+ # Only *preserved*, never *added*: several keywords here
+ # ("cannot connect", "server", "not responding") match
+ # runtime failures of a provider that IS configured, and
+ # promoting those to ``LLMNotConfiguredError`` would make
+ # a boundary answer "open Settings and choose a model" to
+ # a user whose model is already chosen. Both branches
+ # stay ``ValueError`` instances, so every existing
+ # ``except ValueError`` caller is unaffected.
+ error_type = (
+ LLMNotConfiguredError
+ if isinstance(e, LLMNotConfiguredError)
+ else ValueError
+ )
+ raise error_type(
f"LLM Configuration Error: {error_msg}"
) from e
# For other errors, re-raise to avoid silent failures
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.py
index 086b07093e..0fbab48d94 100644
--- a/tests/config/test_llm_config.py
+++ b/tests/config/test_llm_config.py
@@ -722,3 +722,157 @@ class TestDiscoveredProviderOptions:
assert isinstance(available, list)
available_values = {o["value"].lower() for o in available}
assert available_values <= all_values
+
+
+class TestLLMNotConfiguredErrorType:
+ """The four "not configured" raise sites must be TYPED, not text-matched.
+
+ HTTP boundaries that map ``ValueError`` to "your request was invalid"
+ need to tell an LLM-configuration gap apart from a bad request without
+ parsing the exception message (``web/routers/notes.py::suggest_tags``
+ is the first caller). These tests pin the exception CLASS at each site,
+ so replacing ``LLMNotConfiguredError`` with a bare ``ValueError`` at any
+ of them silently re-breaks that caller and is caught here instead.
+
+ ``LLMNotConfiguredError`` subclasses ``ValueError`` on purpose: every
+ pre-existing ``except ValueError`` / ``pytest.raises(ValueError)`` around
+ ``get_llm`` keeps working unchanged.
+ """
+
+ def test_subclasses_value_error(self):
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ assert issubclass(LLMNotConfiguredError, ValueError)
+
+ def test_invalid_provider_raises_the_typed_error(self):
+ import pytest
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "test-model",
+ "llm.temperature": 0.7,
+ "llm.provider": "invalid_provider",
+ }.get(key, default)
+
+ with pytest.raises(
+ LLMNotConfiguredError, match="Invalid provider"
+ ):
+ get_llm(settings_snapshot={"search.tool": "searxng"})
+
+ def test_empty_provider_setting_raises_typed_error_not_type_error(self):
+ """``llm.provider`` as an empty string normalizes to ``None`` (via
+ ``normalize_provider``) before reaching
+ ``sanitize_for_log(str(provider))``. Catches a regression to a bare
+ ``sanitize_for_log(provider)``: ``sanitize_for_log`` requires a
+ ``str``, so calling it directly on ``None`` raises ``TypeError``
+ here instead of the intended ``LLMNotConfiguredError`` -- turning an
+ ordinary "you haven't configured an LLM yet" state into an unhandled
+ crash. Also pins that the diagnostic actually reaches the log.
+ """
+ import pytest
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "test-model",
+ "llm.temperature": 0.7,
+ "llm.provider": "",
+ }.get(key, default)
+
+ with patch(
+ "local_deep_research.config.llm_config.logger"
+ ) as mock_logger:
+ with pytest.raises(
+ LLMNotConfiguredError, match="Invalid provider: None"
+ ):
+ get_llm(settings_snapshot={"search.tool": "searxng"})
+
+ mock_logger.error.assert_called_once()
+ assert (
+ "Invalid provider in settings"
+ in mock_logger.error.call_args.args[0]
+ )
+
+ def test_missing_model_raises_the_typed_error(self):
+ import pytest
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "",
+ "llm.temperature": 0.7,
+ "llm.provider": "ollama",
+ }.get(key, default)
+
+ with pytest.raises(
+ LLMNotConfiguredError, match="LLM model not configured"
+ ):
+ get_llm()
+
+ def test_provider_none_raises_the_typed_error(self):
+ import pytest
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ with pytest.raises(
+ LLMNotConfiguredError, match="No LLM provider configured"
+ ):
+ get_llm(
+ model_name="x",
+ provider="none",
+ settings_snapshot={"search.tool": "searxng"},
+ )
+
+ def test_unregistered_discovered_provider_raises_the_typed_error(self):
+ """The fourth site: a provider auto-discovery advertises but never
+ registered (an import error at startup, or a cleared registry)."""
+ import pytest
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[{"value": "ghost_provider"}],
+ ):
+ with pytest.raises(
+ LLMNotConfiguredError,
+ match="was not registered by auto-discovery",
+ ):
+ get_llm(
+ model_name="x",
+ provider="ghost_provider",
+ settings_snapshot={"search.tool": "searxng"},
+ )
diff --git a/tests/notes/test_notes_api.py b/tests/notes/test_notes_api.py
index e9a2a6e75a..991f3a84d2 100644
--- a/tests/notes/test_notes_api.py
+++ b/tests/notes/test_notes_api.py
@@ -711,7 +711,12 @@ class TestAcceptLinkRouteErrorMapping:
assert status == 400
assert payload["success"] is False
- assert "maximum length" in payload["error"]
+ # The route no longer forwards the service's ValueError text: the
+ # same exception type can carry a filesystem path or SQL fragment
+ # from deeper in the write path. The fixed message keeps the 400/404
+ # distinction below meaningful without the detail.
+ assert payload["error"] == "Suggested link cannot be accepted"
+ assert "Content exceeds maximum length" not in payload["error"]
def test_accept_link_404s_when_service_returns_none(
self, monkeypatch, db_session, note_source_type
@@ -1324,3 +1329,258 @@ class TestNotesBodySizeCap:
escaped_ratio = len(_json.dumps(ctrl)) - 2 # minus the two quotes
assert escaped_ratio >= 6
assert escaped_ratio * NOTE_CONTENT_MAX_BYTES > _MAX_JSON_BODY_BYTES
+
+
+class TestFixedErrorMessagesAreTrueAndComplete:
+ """The flattened 4xx messages on ``web/routers/notes.py``.
+
+ Two properties, both of which a revert breaks:
+
+ * the message must be TRUE for the branch that produced it -- a fixed
+ string is worse than an exception echo if it misreports the cause;
+ * the exception's own text must not appear in the body, since the same
+ ``ValueError`` type is raised from service and validator layers that
+ can carry a filesystem path, a SQL fragment or a note's content.
+
+ Each test names the specific revert it catches.
+ """
+
+ # -- resolve_link: the two ValueErrors of _clamp_text_query -------------
+
+ def test_non_string_link_text_is_not_reported_as_a_length_problem(
+ self, monkeypatch, db_session
+ ):
+ """``_clamp_text_query`` raises for a non-string OR an over-long
+ value, and ``resolve_link`` is the only caller whose input is not a
+ query param -- ``_NotesBody`` is an uncoerced parsed-JSON dict.
+
+ Catches the revert to a single hardcoded "exceeds maximum length"
+ message for both branches, which answered
+ ``{"link_text": 123}`` with a factually false 400 telling the user
+ their 3-character value was over a 500-character cap.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+
+ payload, status = _call(
+ "/notes/api/notes/resolve-link",
+ notes_routes.resolve_link,
+ method="POST",
+ json={"link_text": 123},
+ )
+
+ assert status == 400
+ assert payload["success"] is False
+ assert payload["error"] == "link_text must be a string"
+ assert "maximum length" not in payload["error"]
+
+ def test_over_long_link_text_still_reports_the_length_cap(
+ self, monkeypatch, db_session
+ ):
+ """Non-vacuity control for the test above: the length branch is
+ still reachable and still names the cap, so the type check did not
+ simply swallow both cases into one message.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+
+ payload, status = _call(
+ "/notes/api/notes/resolve-link",
+ notes_routes.resolve_link,
+ method="POST",
+ json={"link_text": "x" * 501},
+ )
+
+ assert status == 400
+ assert payload["error"] == (
+ "link_text exceeds maximum length (500 chars)"
+ )
+
+ # -- link_research_to_note ---------------------------------------------
+
+ def test_link_research_value_error_returns_the_fixed_message(
+ self, monkeypatch, db_session, note_source_type
+ ):
+ """Catches the revert of ``link_research_to_note``'s
+ ``except ValueError`` arm to ``{"error": str(e)}``. The service
+ raises this from the research-per-note cap check, but the same
+ handler catches every other ``ValueError`` raised under
+ ``NoteService.link_research_to_note`` -- including ones from the
+ note-content and session layers below it.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+ note = _seed_note(db_session, note_source_type)
+
+ def _raise(self, note_id, research_id):
+ raise ValueError(
+ "private validation detail /srv/ldr-data/victim.db"
+ )
+
+ monkeypatch.setattr(
+ notes_routes.NoteService, "link_research_to_note", _raise
+ )
+
+ payload, status = _call(
+ f"/notes/api/notes/{note.id}/research",
+ notes_routes.link_research_to_note,
+ note.id,
+ method="POST",
+ json={"research_id": str(uuid.uuid4())},
+ )
+
+ assert status == 400
+ assert payload["success"] is False
+ assert payload["error"] == "Research cannot be linked to this note"
+ assert "private validation detail" not in payload["error"]
+ assert "/srv/ldr-data" not in payload["error"]
+
+ def test_link_research_to_unknown_note_is_still_404(
+ self, monkeypatch, db_session, note_source_type
+ ):
+ """The 404 for a missing note must survive the message flattening.
+
+ Before the flattening, this route recovered the 404 by matching
+ ``"not found" in str(e).lower()`` on the service's ``ValueError``.
+ With the text no longer read, two ``note_exists`` calls keep a
+ missing note out of the sibling 400: a pre-check before the service
+ call, and a re-check in the ``except ValueError`` arm for a note
+ deleted in between. Delete both and this test goes red while every
+ other assertion in this class stays green.
+
+ The status assertion alone would survive deleting the PRE-check (the
+ re-check would answer 404 too), so this also asserts the service was
+ never reached -- that is the leg that pins the pre-check specifically.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+
+ service_calls = []
+
+ def _raise(self, note_id, research_id):
+ service_calls.append(note_id)
+ raise ValueError(f"Note {note_id} not found")
+
+ monkeypatch.setattr(
+ notes_routes.NoteService, "link_research_to_note", _raise
+ )
+
+ missing_note_id = str(uuid.uuid4())
+ payload, status = _call(
+ f"/notes/api/notes/{missing_note_id}/research",
+ notes_routes.link_research_to_note,
+ missing_note_id,
+ method="POST",
+ json={"research_id": str(uuid.uuid4())},
+ )
+
+ assert status == 404, payload
+ assert payload["error"] == "Note not found"
+ assert missing_note_id not in payload["error"]
+ assert service_calls == [], (
+ "an already-missing note must 404 from the pre-check, before "
+ "the service runs"
+ )
+
+ def test_link_research_note_deleted_mid_call_is_404_not_400(
+ self, monkeypatch, db_session, note_source_type
+ ):
+ """TOCTOU: the note is deleted between the pre-check and the call.
+
+ The pre-check sees the note, the service then raises because the row
+ is gone. Without the re-check in the ``except ValueError`` arm the
+ client gets 400 "Research cannot be linked to this note" for what is
+ really a 404 -- the same misclassification the pre-check exists to
+ prevent, just one instant later. ``note_exists`` is answered True
+ then False to stage exactly that interleaving; removing the re-check
+ turns this into a 400.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+
+ answers = [True, False]
+
+ def _exists(self, note_id):
+ return answers.pop(0)
+
+ def _raise(self, note_id, research_id):
+ raise ValueError(f"Note {note_id} not found")
+
+ monkeypatch.setattr(notes_routes.NoteService, "note_exists", _exists)
+ monkeypatch.setattr(
+ notes_routes.NoteService, "link_research_to_note", _raise
+ )
+
+ note_id = str(uuid.uuid4())
+ payload, status = _call(
+ f"/notes/api/notes/{note_id}/research",
+ notes_routes.link_research_to_note,
+ note_id,
+ method="POST",
+ json={"research_id": str(uuid.uuid4())},
+ )
+
+ assert status == 404, payload
+ assert payload["error"] == "Note not found"
+ assert answers == [], (
+ "both note_exists calls must have run (pre-check, then re-check)"
+ )
+
+ # -- remove_note_from_collection ---------------------------------------
+
+ def test_remove_from_collection_value_error_returns_fixed_message(
+ self, monkeypatch, db_session, note_source_type
+ ):
+ """Catches the revert of ``remove_note_from_collection``'s
+ ``except ValueError`` arm to ``{"error": str(e)}``. The guard it
+ reports is "you cannot unlink a note from the system Notes
+ collection", but the handler wraps the whole service call.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+ note = _seed_note(db_session, note_source_type)
+
+ def _raise(self, note_id, collection_id):
+ raise ValueError("private guard detail /srv/ldr-data/victim.db")
+
+ monkeypatch.setattr(
+ notes_routes.NoteService, "remove_from_collection", _raise
+ )
+
+ payload, status = _call(
+ f"/notes/api/notes/{note.id}/collections/{uuid.uuid4()}",
+ notes_routes.remove_note_from_collection,
+ note.id,
+ str(uuid.uuid4()),
+ method="DELETE",
+ )
+
+ assert status == 400
+ assert payload["success"] is False
+ assert payload["error"] == (
+ "Note cannot be removed from this collection"
+ )
+ assert "private guard detail" not in payload["error"]
+ assert "/srv/ldr-data" not in payload["error"]
+
+ # -- create_research_annotation ----------------------------------------
+
+ def test_annotation_validation_error_returns_fixed_message(
+ self, monkeypatch, db_session
+ ):
+ """Catches the revert of ``create_research_annotation``'s
+ ``except ValueError`` arm to ``{"error": str(e)}``.
+
+ The branch is driven through the real validator
+ (``_validated_annotation_fields``), so this also pins that the
+ rejection still happens BEFORE the research-existence lookup -- a
+ 400, not the 404 a missing research id would give.
+ """
+ notes_routes = _route_ctx(monkeypatch, db_session)
+
+ payload, status = _call(
+ f"/notes/api/research/{uuid.uuid4()}/annotations",
+ notes_routes.create_research_annotation,
+ str(uuid.uuid4()),
+ method="POST",
+ json={"quote": "only a quote"},
+ )
+
+ assert status == 400, payload
+ assert payload["success"] is False
+ assert payload["error"] == "Invalid annotation data"
+ assert "comment is required" not in payload["error"]
diff --git a/tests/notes/test_notes_router_fastapi.py b/tests/notes/test_notes_router_fastapi.py
index 40b6670a25..936441da5a 100644
--- a/tests/notes/test_notes_router_fastapi.py
+++ b/tests/notes/test_notes_router_fastapi.py
@@ -597,7 +597,9 @@ class TestResearchAndDocuments:
headers={"X-CSRFToken": _csrf(client)},
)
assert r.status_code == 400
- assert r.json()["error"] == "comment is required"
+ # Validator text is no longer forwarded; the 400 still separates a
+ # malformed annotation from the 404 above.
+ assert r.json()["error"] == "Invalid annotation data"
def test_get_document_notes_unknown_document_404(self, client):
r = client.get(f"/notes/api/documents/{_rand_id()}/notes")
diff --git a/tests/notes/test_notes_routes_review_fixes.py b/tests/notes/test_notes_routes_review_fixes.py
index 7443db0017..6bc0b5b1ea 100644
--- a/tests/notes/test_notes_routes_review_fixes.py
+++ b/tests/notes/test_notes_routes_review_fixes.py
@@ -43,7 +43,7 @@ import asyncio
import inspect
import json as _json
import uuid
-from contextlib import contextmanager
+from contextlib import ExitStack, contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -510,14 +510,15 @@ class TestReorderResearchRouteBoundary:
def _raise(svc):
svc.note_exists.return_value = True
svc.reorder_note_research.side_effect = ValueError(
- "too many linked researches (max 50)"
+ "private validation detail"
)
payload, status = self._call_reorder(
{"research_ids": ["a", "b"]}, patch_service=_raise
)
assert status == 400, payload
- assert "too many linked researches" in payload["error"]
+ assert payload["error"] == "Invalid research order"
+ assert "private validation detail" not in payload["error"]
def test_reorder_service_mismatch_returns_400_with_distinct_message(self):
"""Positive control for the above: the ok==False branch keeps its own
@@ -645,9 +646,78 @@ class TestSuggestTagsRouteValidation:
status, payload, mock_ai = self._call_suggest({"content": 123})
assert status == 400, payload
assert payload["success"] is False
- assert "content must be a string" in payload["error"]
+ assert payload["error"] == "Invalid tag request"
mock_ai.suggest_tags.assert_not_called()
+ def test_suggest_tags_unconfigured_llm_is_reported_as_model_not_configured_not_as_invalid_input(
+ self,
+ ):
+ """A fresh install with no ``llm.model`` must not be told its request
+ was invalid.
+
+ ``NoteAIService.suggest_tags`` -> ``_get_llm`` -> ``get_llm`` raises
+ ``LLMNotConfiguredError`` (a ``ValueError`` subclass) for every
+ LLM-configuration failure, so a perfectly valid body fell into the
+ ``except ValueError`` arm and came back as a request-validation 400
+ carrying the exception's own setup text -- rendered verbatim by
+ note-detail.js -- sending the user hunting through a body that was
+ fine.
+
+ The status stays 400 (an unconfigured integration is client state,
+ not a server fault -- the same call ``web/routers/api.py``,
+ ``followup.py`` and ``zotero.py`` make); what changes is that the
+ body now SAYS which kind of 400 it is, via a fixed message and
+ ``error_type: model_not_configured``. Deleting the
+ ``except LLMNotConfiguredError`` arm makes this exception fall into
+ the ``except ValueError`` arm below it: the status still matches, so
+ the ``error``/``error_type`` assertions are the ones carrying this
+ test.
+ """
+ from local_deep_research.config.llm_config import (
+ LLM_NOT_CONFIGURED_CLIENT_MESSAGE,
+ LLMNotConfiguredError,
+ )
+
+ leak = (
+ "LLM model not configured; snapshot loaded from "
+ "/srv/ldr-data/users/alice/settings.db"
+ )
+ status, payload, mock_ai = self._call_suggest(
+ {"content": "some note"},
+ ai_setup=lambda ai: setattr(
+ ai.suggest_tags, "side_effect", LLMNotConfiguredError(leak)
+ ),
+ )
+ assert status == 400, payload
+ assert payload["success"] is False
+ assert payload["error"] == LLM_NOT_CONFIGURED_CLIENT_MESSAGE
+ assert payload["error_type"] == "model_not_configured"
+ # A fixed constant, not the (path-bearing) exception text.
+ assert "/srv/ldr-data" not in payload["error"]
+ assert "settings.db" not in payload["error"]
+
+ def test_suggest_tags_service_value_error_stays_a_bad_request(self):
+ """Non-vacuity control for the branch above: an ordinary
+ ``ValueError`` from the service is still the request-validation 400,
+ with no exception text in the body. Without this, widening the
+ configuration arm to catch every ``ValueError`` would go unnoticed.
+ """
+ leak = "tag row rejected: /srv/ldr-data/users/alice/library.db"
+ status, payload, mock_ai = self._call_suggest(
+ {"content": "some note"},
+ ai_setup=lambda ai: setattr(
+ ai.suggest_tags, "side_effect", ValueError(leak)
+ ),
+ )
+ assert status == 400, payload
+ assert payload["success"] is False
+ assert payload["error"] == "Invalid tag request"
+ # Both arms answer 400, so the classification -- not the status --
+ # is what separates them. An ordinary ValueError must NOT be
+ # labelled a configuration problem.
+ assert "error_type" not in payload
+ assert "/srv/ldr-data" not in payload["error"]
+
def test_suggest_tags_valid_existing_tags_passes_to_service(self):
"""Positive control: the guard doesn't false-positive on valid input
-- valid existing_tags reach the service and 200 is returned."""
@@ -665,6 +735,282 @@ class TestSuggestTagsRouteValidation:
)
+# Every LLM-backed route in web/routers/notes.py, i.e. every route whose
+# body transitively reaches ``NoteAIService._get_llm`` ->
+# ``config.llm_config.get_llm``. Derived by hand from the service methods
+# that call ``_get_llm`` (summarize_note, extract_research_questions,
+# suggest_tags, extract_key_concepts, extract_claims, grade_all_claims,
+# semantic_diff, synthesize_notes) and the routes that call them; keep the
+# two in step when a new AI route lands.
+#
+# ``raise_at`` says where the typed error is injected:
+# "service" -- on the ``NoteAIService`` method the route calls, which
+# is exactly where the real ``_get_llm`` raises;
+# "grade_helper" -- on ``notes._grade_note_claims``, the module helper that
+# owns the ``ai.grade_all_claims()`` call for the grade
+# route. Driving that helper for real needs a completed
+# research row, a link row and a stored report; the arm
+# under test here is the route's, and the helper is the
+# unit that raises through it.
+_LLM_BACKED_NOTES_ROUTES = [
+ (
+ "summarize",
+ "/notes/api/notes/n1/summarize",
+ "summarize_note",
+ ("n1",),
+ {},
+ "service",
+ ),
+ (
+ "research-questions",
+ "/notes/api/notes/n1/research-questions",
+ "extract_research_questions",
+ ("n1",),
+ {},
+ "service",
+ ),
+ (
+ "suggest-tags",
+ "/notes/api/notes/suggest-tags",
+ "suggest_tags",
+ (),
+ {"content": "some note"},
+ "service",
+ ),
+ (
+ "key-concepts",
+ "/notes/api/notes/n1/key-concepts",
+ "extract_key_concepts",
+ ("n1",),
+ {},
+ "service",
+ ),
+ (
+ "fact-check",
+ "/notes/api/notes/n1/fact-check",
+ "fact_check_note",
+ ("n1",),
+ {},
+ "service",
+ ),
+ (
+ "fact-check-grade",
+ "/notes/api/notes/n1/fact-check/r1/grade",
+ "grade_note_fact_check",
+ ("n1", "r1"),
+ {"claims": ["the report says the sky is blue"]},
+ "grade_helper",
+ ),
+ (
+ "synthesize-preview",
+ "/notes/api/notes/synthesize/preview",
+ "preview_synthesis",
+ (),
+ {"note_ids": ["a", "b"], "synthesis_type": "merge"},
+ "service",
+ ),
+ (
+ "synthesize",
+ "/notes/api/notes/synthesize",
+ "synthesize_notes",
+ (),
+ {"note_ids": ["a", "b"], "synthesis_type": "merge"},
+ "service",
+ ),
+ (
+ "semantic-diff",
+ "/notes/api/notes/n1/versions/semantic-diff?version1=v1&version2=current",
+ "get_semantic_diff",
+ ("n1",),
+ None,
+ "service",
+ ),
+]
+
+# The ``NoteAIService`` methods that call ``_get_llm``.
+_AI_METHODS_USING_THE_LLM = (
+ "summarize_note",
+ "extract_research_questions",
+ "suggest_tags",
+ "extract_key_concepts",
+ "extract_claims",
+ "grade_all_claims",
+ "semantic_diff",
+ "synthesize_notes",
+)
+
+
+class TestUnconfiguredLLMIsClassifiedOnEveryNotesAIRoute:
+ """No LLM configured must read the same on ALL nine LLM-backed routes.
+
+ ``suggest-tags`` was the only route with a typed arm; its eight siblings
+ let ``LLMNotConfiguredError`` fall into ``except Exception`` and answered
+ 500 "An internal error occurred. Please try again or contact support."
+ -- a server-fault message for a fresh install that has simply not chosen
+ a model yet, and one that gives the user nothing to act on.
+
+ The property: every route that can reach ``get_llm`` answers 400 with the
+ fixed ``LLM_NOT_CONFIGURED_CLIENT_MESSAGE`` and
+ ``error_type: model_not_configured``. Deleting the shared
+ ``_llm_not_configured_response`` arm from any one route turns that row
+ red (500 + "contact support"), and changing the status, message or
+ ``error_type`` in the helper turns all nine red at once -- which is the
+ point of routing them through one helper.
+ """
+
+ @pytest.fixture
+ def unconfigured(self, monkeypatch):
+ """Real routes, mocked service/session layer, ``get_llm`` unusable."""
+ from local_deep_research.config.llm_config import (
+ LLMNotConfiguredError,
+ )
+
+ leak = (
+ "LLM model not configured; snapshot loaded from "
+ "/srv/ldr-data/users/alice/settings.db"
+ )
+
+ @contextmanager
+ def _fake_session(username=None, password=None):
+ yield MagicMock()
+
+ # semantic-diff reads the Document/NoteVersion rows itself before it
+ # ever builds the AI service.
+ monkeypatch.setattr(
+ "local_deep_research.database.session_context.get_user_db_session",
+ _fake_session,
+ )
+ return leak, LLMNotConfiguredError
+
+ @pytest.mark.parametrize(
+ "path, handler_name, args, body, raise_at",
+ [row[1:] for row in _LLM_BACKED_NOTES_ROUTES],
+ ids=[row[0] for row in _LLM_BACKED_NOTES_ROUTES],
+ )
+ def test_route_answers_model_not_configured(
+ self, unconfigured, path, handler_name, args, body, raise_at
+ ):
+ from local_deep_research.config.llm_config import (
+ LLM_NOT_CONFIGURED_CLIENT_MESSAGE,
+ )
+ from local_deep_research.research_library.notes.services.note_ai_service import (
+ NoteAIService as RealNoteAIService,
+ )
+ from local_deep_research.web.routers import notes as notes_routes
+
+ leak, error_cls = unconfigured
+
+ ai = MagicMock()
+ for method in _AI_METHODS_USING_THE_LLM:
+ getattr(ai, method).side_effect = error_cls(leak)
+
+ note_service = MagicMock()
+ note_service.note_exists.return_value = True
+ note_service._is_note.return_value = True
+
+ with ExitStack() as patches:
+ service_cls = patches.enter_context(
+ patch.object(notes_routes, "NoteAIService", return_value=ai)
+ )
+ # The grade route slices its claim list with
+ # ``NoteAIService.MAX_CLAIMS_PER_NOTE``; a MagicMock attribute
+ # there is a TypeError, not a slice. Keep the real bound.
+ service_cls.MAX_CLAIMS_PER_NOTE = (
+ RealNoteAIService.MAX_CLAIMS_PER_NOTE
+ )
+ patches.enter_context(
+ patch.object(
+ notes_routes, "NoteService", return_value=note_service
+ )
+ )
+ if raise_at == "grade_helper":
+ patches.enter_context(
+ patch.object(
+ notes_routes,
+ "_grade_note_claims",
+ side_effect=error_cls(leak),
+ )
+ )
+ payload, status = _call(
+ path,
+ getattr(notes_routes, handler_name),
+ *args,
+ method="GET" if body is None else "POST",
+ json=body,
+ )
+
+ assert status == 400, payload
+ assert payload["success"] is False
+ assert payload["error"] == LLM_NOT_CONFIGURED_CLIENT_MESSAGE
+ assert payload["error_type"] == "model_not_configured"
+ # Never the exception's own setup text, which carries a settings path.
+ assert "/srv/ldr-data" not in payload["error"]
+ assert "settings.db" not in payload["error"]
+
+
+class TestUnconfiguredLLMThroughTheRealServiceChain:
+ """End-to-end over the chain the route actually runs.
+
+ Every other test here injects at a mocked ``NoteAIService``, which pins
+ the route's ``except`` arm but assumes the service really does let
+ ``LLMNotConfiguredError`` out of ``suggest_tags``. It does not: each AI
+ method wraps its body in ``except Exception: logger.exception(...);
+ raise``, and a future ``except ValueError: return []`` there would
+ swallow the configuration failure and hand the user an empty tag list
+ with a 200 -- with every mocked-service test still green.
+
+ So this one patches only ``config.llm_config.get_llm`` (plus the DB
+ session and settings manager that ``_build_settings_snapshot`` needs)
+ and drives the REAL ``NoteAIService`` through the real route.
+ """
+
+ def test_real_note_ai_service_surfaces_the_typed_error_to_the_route(
+ self, monkeypatch
+ ):
+ from local_deep_research.config import llm_config
+ from local_deep_research.web.routers import notes as notes_routes
+
+ leak = (
+ "LLM model not configured. Please open Settings, choose an LLM "
+ "provider, and select a model name. Snapshot read from "
+ "/srv/ldr-data/users/alice/settings.db"
+ )
+
+ def _unconfigured_get_llm(*args, **kwargs):
+ raise llm_config.LLMNotConfiguredError(leak)
+
+ monkeypatch.setattr(llm_config, "get_llm", _unconfigured_get_llm)
+
+ # Only the DB/session layer is mocked: _build_settings_snapshot opens
+ # the per-user encrypted DB to build the snapshot it hands get_llm.
+ @contextmanager
+ def _fake_session(username=None, password=None):
+ yield MagicMock()
+
+ monkeypatch.setattr(
+ "local_deep_research.research_library.notes.services."
+ "note_ai_service.get_user_db_session",
+ _fake_session,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.settings.manager.SettingsManager",
+ lambda session: MagicMock(get_settings_snapshot=lambda: {}),
+ )
+
+ payload, status = _call(
+ "/notes/api/notes/suggest-tags",
+ notes_routes.suggest_tags,
+ method="POST",
+ json={"content": "a genuinely valid note body"},
+ )
+
+ assert status == 400, payload
+ assert payload["success"] is False
+ assert payload["error"] == llm_config.LLM_NOT_CONFIGURED_CLIENT_MESSAGE
+ assert payload["error_type"] == "model_not_configured"
+ assert "/srv/ldr-data" not in payload["error"]
+
+
class TestCreateCollectionTypeAllowlist:
"""``POST /library/api/collections`` must reject system collection types.
@@ -975,3 +1321,107 @@ class TestGetNoteVersionsOffsetPagination:
f"found {checked}. The structural probe stopped observing the "
"clause it was written to guard."
)
+
+
+class TestFlattenedValueErrorArmsWithholdServiceText:
+ """Three route arms replace a service ``ValueError`` with a fixed string.
+
+ ``create_note`` and ``update_note`` -> "Invalid note data";
+ ``create_document_annotation`` -> "Invalid annotation data". Each used to
+ return ``{"error": str(e)}``, so whatever the service raised -- a
+ SQLAlchemy constraint message carrying an absolute DB path, or any future
+ exception that reaches those handlers -- went straight to the browser.
+
+ Why these three need their own tests: the same two strings are asserted
+ elsewhere in the suite, but always against a DIFFERENT route
+ (``create_research_note`` in ``test_research_notes_routes.py``,
+ ``create_research_annotation`` in ``test_notes_router_fastapi.py``,
+ ``create_document_note`` in ``test_notes_api.py``). Reverting any ONE of
+ the three arms below to ``str(e)`` left the whole suite green.
+
+ Each test drives the arm through the service call it guards, so restoring
+ ``{"error": str(e)}`` on that arm fails both the equality assertion and
+ the leak assertions.
+ """
+
+ # Deliberately shaped like the exception the arms are meant to contain:
+ # a server path, SQL text and a credential in one message.
+ LEAK = (
+ "IntegrityError at /srv/ldr-data/users/alice/library.db "
+ "[SQL: INSERT INTO documents] sql credentials password=hunter2"
+ )
+
+ def _assert_withheld(self, payload, status, expected):
+ assert status == 400, payload
+ assert payload == {"success": False, "error": expected}
+ assert "/srv/ldr-data" not in payload["error"]
+ assert "INSERT INTO" not in payload["error"]
+ assert "hunter2" not in payload["error"]
+
+ def test_create_note_withholds_service_exception_text(self):
+ from local_deep_research.web.routers import notes as notes_routes
+
+ with patch.object(notes_routes, "NoteService") as cls:
+ cls.return_value.create_note.side_effect = ValueError(self.LEAK)
+ payload, status = _call(
+ "/notes/api/notes",
+ notes_routes.create_note,
+ method="POST",
+ json={"title": "T", "content": "C"},
+ )
+
+ self._assert_withheld(payload, status, "Invalid note data")
+
+ def test_update_note_withholds_service_exception_text(self):
+ from local_deep_research.web.routers import notes as notes_routes
+
+ note_id = str(uuid.uuid4())
+ with patch.object(notes_routes, "NoteService") as cls:
+ cls.return_value.update_note.side_effect = ValueError(self.LEAK)
+ payload, status = _call(
+ f"/notes/api/notes/{note_id}",
+ notes_routes.update_note,
+ note_id,
+ method="PUT",
+ json={"content": "C"},
+ )
+
+ self._assert_withheld(payload, status, "Invalid note data")
+
+ def test_create_document_annotation_withholds_service_exception_text(
+ self, monkeypatch
+ ):
+ from local_deep_research.web.routers import notes as notes_routes
+
+ document_id = str(uuid.uuid4())
+
+ class _Row:
+ id = document_id
+ title = "A Document"
+
+ @contextmanager
+ def _fake_session(username=None, password=None):
+ db = MagicMock()
+ db.query.return_value.filter_by.return_value.first.return_value = (
+ _Row()
+ )
+ yield db
+
+ monkeypatch.setattr(
+ "local_deep_research.database.session_context.get_user_db_session",
+ _fake_session,
+ )
+
+ with patch.object(notes_routes, "NoteService") as cls:
+ cls.return_value.create_note_for_document.side_effect = ValueError(
+ self.LEAK
+ )
+ payload, status = _call(
+ f"/notes/api/documents/{document_id}/annotations",
+ notes_routes.create_document_annotation,
+ document_id,
+ method="POST",
+ json={"comment": "a comment", "quote": "a quote"},
+ )
+
+ self._assert_withheld(payload, status, "Invalid annotation data")
diff --git a/tests/notes/test_research_notes_routes.py b/tests/notes/test_research_notes_routes.py
index 3d5571e0f5..0f444e6ced 100644
--- a/tests/notes/test_research_notes_routes.py
+++ b/tests/notes/test_research_notes_routes.py
@@ -160,10 +160,11 @@ class TestCreateResearchNote:
def test_validation_error_maps_to_400(self):
(payload, status), _ = self._call(
- side_effect=ValueError("title exceeds maximum length")
+ side_effect=ValueError("private validation detail")
)
assert status == 400
- assert "maximum length" in payload["error"]
+ assert payload["error"] == "Invalid note data"
+ assert "private validation detail" not in payload["error"]
class TestSaveResearchAsNote:
@@ -250,10 +251,11 @@ class TestSaveResearchAsNote:
def test_content_cap_violation_maps_to_400(self):
(payload, status), _ = self._call(
research=self._completed_research(),
- create_side_effect=ValueError("content exceeds maximum size"),
+ create_side_effect=ValueError("private validation detail"),
)
assert status == 400
- assert "maximum size" in payload["error"]
+ assert payload["error"] == "Research cannot be saved as a note"
+ assert "private validation detail" not in payload["error"]
class TestResearchAnnotations:
@@ -463,7 +465,7 @@ class TestDocumentNotesRoutes:
def test_create_document_note_maps_value_error_to_400(self):
def raise_ve(*a, **k):
- raise ValueError("notes cannot be annotated")
+ raise ValueError("private validation detail")
(payload, status), _ = self._run(
notes_routes.create_document_note,
@@ -477,7 +479,8 @@ class TestDocumentNotesRoutes:
),
)
assert status == 400
- assert "annotated" in payload["error"]
+ assert payload["error"] == "Invalid document note data"
+ assert "private validation detail" not in payload["error"]
def test_create_document_annotation_builds_comment_note(self):
doc_row = MagicMock()
diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
index 442efc23d5..d00d797946 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
@@ -69,8 +69,9 @@ per-class docstrings for the successor named in each case):
test_stdlib_exception_no_longer_echoes_verbatim_detail`` (``"bug in LDR"
not in message``); the "surfaced verbatim" half was DELIBERATELY REVERSED
on this branch by the CWE-209 / CodeQL-8001 hardening of
- ``_format_test_embedding_error`` (stdlib exceptions now yield the class
- name only), and that reversal has its own dedicated coverage in
+ ``_format_test_embedding_error`` (stdlib exceptions now yield a fixed
+ message with no exception-derived text, class name included), and that
+ reversal has its own dedicated coverage in
``tests/web/routers/test_rag_embedding_error_sanitisation.py``. Porting
the verbatim assertion would assert a property the branch intentionally
removed for security reasons, not a regression.
diff --git a/tests/research_library/routes/test_rag_routes_deep_main_port.py b/tests/research_library/routes/test_rag_routes_deep_main_port.py
index 899936dca6..eed2dea61a 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
@@ -53,16 +53,16 @@ guard is deleted -- verified by reading each successor's assertions):
- ``TestTestEmbeddingErrorCategorization`` -- 7 of its 8 tests. The three
``*_falls_through_to_verbatim`` tests assert that a stdlib exception's
text is echoed BACK to the browser; this branch deliberately inverted
- that (default-deny, class name only) for CodeQL alert 8001 / CWE-209 --
+ that (default-deny, fixed messages only) for CodeQL alert 8001 / CWE-209 --
see ``_format_test_embedding_error``'s docstring in ``web/routers/rag.py``
and ``tests/web/routers/test_rag_embedding_error_sanitisation.py``, which
pins the hardened contract while KEEPING main's #4208 guard (``"bug in
LDR" not in message``). ``tests/security/test_library_rag_security_fastapi.py::
TestFormatTestEmbeddingErrorUnit::test_stdlib_exception_no_longer_echoes_verbatim_detail``
- documents the inversion explicitly. The internal-LDR, provider-passthrough
+ documents the inversion explicitly. The internal-LDR and provider-category
and key-redaction tests are superseded by that file's
``test_internal_exception_detail_is_suppressed_entirely`` /
- ``test_upstream_provider_error_is_surfaced_but_key_redacted`` and, at HTTP
+ ``test_upstream_provider_error_withholds_exception_text`` and, at HTTP
level, ``TestTestEmbeddingEndpointDoesNotLeak``. Only the builtin-subclass
routing test below has no successor and is ported.
"""
@@ -735,7 +735,8 @@ class TestTestEmbeddingErrorCategorization:
_FakeOpenAIKeyError("data"), "some-model"
)
- assert "provider returned an error" in message
+ assert "The request to the provider failed" in message
+ assert "data" not in message
assert "internal LDR error" not in message
diff --git a/tests/research_library/test_zotero_sync_contracts.py b/tests/research_library/test_zotero_sync_contracts.py
index 9925989e4d..3c20b40bbe 100644
--- a/tests/research_library/test_zotero_sync_contracts.py
+++ b/tests/research_library/test_zotero_sync_contracts.py
@@ -777,9 +777,15 @@ def test_local_api_client_never_attaches_the_api_key_header():
def test_request_errors_never_carry_the_api_key_or_the_request_url():
"""``_request`` reduces an underlying failure to its exception TYPE.
- That is what keeps ``sanitize_error_for_client`` from having to redact a
- bare 24-character Zotero key (which matches none of its credential-shape
- patterns) out of ``stats["error"]`` / ``ZoteroSyncState.last_error``.
+ This is the property the whole Zotero message boundary rests on. Because
+ the raised text is author-written (only an exception class name here),
+ ``client_safe_zotero_message`` can safely allowlist a fixed set of those
+ strings for the browser, and the catch sites can log ``str(exc)`` --
+ neither would be defensible if a transport failure's own message, which
+ can carry the request URL and a bare 24-character Zotero key, survived
+ into ``stats["error"]`` / ``ZoteroSyncState.last_error``. (A bare Zotero
+ key matches none of the credential-shape patterns in
+ ``sanitize_error_message``, so no downstream scrubber would catch it.)
"""
class LeakyTransportError(Exception):
diff --git a/tests/research_library/zotero/test_sync_service.py b/tests/research_library/zotero/test_sync_service.py
index 8dbea9a507..abf36a3703 100644
--- a/tests/research_library/zotero/test_sync_service.py
+++ b/tests/research_library/zotero/test_sync_service.py
@@ -12,6 +12,7 @@ from datetime import date, datetime, UTC
from unittest.mock import MagicMock
import pytest
+from loguru import logger as loguru_logger
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@@ -1531,10 +1532,221 @@ def test_sync_one_marks_state_failed_on_version_fetch_error(
stats = svc._sync_one(client, cfg, "")
assert stats["status"] == "failed"
- assert stats["error"]
+ assert stats["error"] == (
+ "Zotero request failed. Check the integration settings."
+ )
+ assert "rate limited" not in stats["error"]
state = db_session.query(ZoteroSyncState).one()
assert state.last_status == "failed"
- assert state.last_error
+ assert state.last_error == stats["error"]
+
+
+def _sync_one_with_version_fetch_error(
+ db_session, monkeypatch, tmp_path, error
+):
+ """Drive ``_sync_one`` to its outer handler and return ``stats``.
+
+ Shares the wiring of
+ ``test_sync_one_marks_state_failed_on_version_fetch_error``; the only
+ variable is which exception the version fetch raises, which is what
+ selects between the two outer handlers.
+ """
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="zotero-api-key-abcdefghijklmnop",
+ library_id="1",
+ pdf_storage_mode="none",
+ )
+
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = error
+ return svc._sync_one(client, cfg, "")
+
+
+def test_sync_one_bare_exception_does_not_return_the_exception_text(
+ db_session, monkeypatch, tmp_path
+):
+ """The non-ZoteroError outer handler must return its fixed string.
+
+ Catches the revert of ``sync_service.py``'s
+ ``except Exception:`` arm back to
+ ``stats["error"] = sanitize_error_for_client(str(exc))``. That scrubber
+ removes credential SHAPES only, so the server path and the OS account
+ name below would ship to the browser through ``get_sync_status`` -- and
+ ``state.last_error`` persists them for every later page load.
+ """
+ leaky = OSError(
+ "[Errno 13] Permission denied: "
+ "/srv/ldr-data/encrypted_databases/victim_user.db"
+ )
+
+ stats = _sync_one_with_version_fetch_error(
+ db_session, monkeypatch, tmp_path, leaky
+ )
+
+ assert stats["status"] == "failed"
+ assert stats["error"] == "Zotero sync failed. See server logs for details."
+ assert "/srv/ldr-data" not in stats["error"]
+ assert "victim_user" not in stats["error"]
+ assert "Permission denied" not in stats["error"]
+ # Persisted state is a second client-visible copy of the same string.
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_error == stats["error"]
+
+
+def test_sync_one_forwards_curated_zotero_guidance(
+ db_session, monkeypatch, tmp_path
+):
+ """The author-written HTTP 400 diagnostic must survive to the caller.
+
+ Catches the revert that replaces every ``ZoteroError`` message with one
+ generic string: this text is the only place the product tells a user that
+ their library-ID setting holds a username instead of the numeric ID, which
+ is the most common Zotero misconfiguration and unguessable from "Zotero
+ request failed".
+
+ It does NOT catch a revert to ``sanitize_error_for_client(str(exc))``:
+ that scrubber returns a curated constant unchanged, so this assertion
+ would still pass. ``test_sync_one_uncurated_zotero_message_falls_back``
+ below is the leg that goes red on that revert.
+ """
+ from local_deep_research.research_library.zotero.client import (
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ ZoteroError,
+ )
+
+ stats = _sync_one_with_version_fetch_error(
+ db_session,
+ monkeypatch,
+ tmp_path,
+ ZoteroError(ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE),
+ )
+
+ assert stats["status"] == "failed"
+ assert stats["error"] == ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE
+ assert "NUMERIC userID" in stats["error"]
+
+
+def test_sync_one_uncurated_zotero_message_falls_back(
+ db_session, monkeypatch, tmp_path
+):
+ """Non-vacuity control for the test above: the allowlist is a whitelist,
+ not a passthrough. A ``ZoteroError`` whose text is not one of the module
+ constants gets the generic message, so the previous test cannot pass by
+ the router simply echoing ``str(exc)``.
+ """
+ from local_deep_research.research_library.zotero.client import ZoteroError
+
+ stats = _sync_one_with_version_fetch_error(
+ db_session,
+ monkeypatch,
+ tmp_path,
+ ZoteroError("Zotero said: token sk-live-ABCDEFGHIJKLMNOPQRSTUV"),
+ )
+
+ assert stats["error"] == (
+ "Zotero request failed. Check the integration settings."
+ )
+ assert "sk-live" not in stats["error"]
+
+
+@contextmanager
+def _capture_loguru(level="DEBUG"):
+ """Collect this package's loguru records as text.
+
+ ``caplog`` sees nothing here: loguru does not write through the stdlib
+ ``logging`` handlers pytest installs, and the package is
+ ``logger.disable``d by default. Same pattern as
+ ``tests/web/routers/test_zotero_router_contracts.py``.
+ """
+ records = []
+ loguru_logger.enable("local_deep_research")
+ sink_id = loguru_logger.add(
+ lambda message: records.append(str(message)), level=level
+ )
+ try:
+ yield records
+ finally:
+ loguru_logger.remove(sink_id)
+ loguru_logger.disable("local_deep_research")
+
+
+def test_sync_one_bare_exception_log_has_no_traceback_and_no_secrets(
+ db_session, monkeypatch, tmp_path
+):
+ """Revert guard for the ``_sync_one`` bare-``Exception`` arm's LOG call.
+
+ ``test_sync_one_bare_exception_does_not_return_the_exception_text``
+ above only pins the client-visible ``stats["error"]`` string. This test
+ pins the server-side log record instead: the handler must stay
+ ``logger.warning(safe_msg)``, not ``logger.exception(...)``. Both ``cfg``
+ (whose dataclass repr renders ``api_key``) and ``self.password`` (the
+ SQLCipher passphrase) are live in this frame, so an attached traceback
+ would render them under loguru's default ``diagnose=True`` even though
+ the logged MESSAGE is already scrubbed. Revert this arm's
+ ``logger.warning`` back to ``logger.exception`` (the site the security
+ hardening changed) and this test goes red on both the traceback header
+ and the leaked secrets.
+ """
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ api_key = "zotero-sentinel-api-key-QWERTY123456"
+ db_password = "sentinel-sqlcipher-passphrase-998877" # gitleaks:allow
+
+ svc = ZoteroSyncService("user", db_password)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True, api_key=api_key, library_id="1", pdf_storage_mode="none"
+ )
+
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = RuntimeError(
+ f"connection reset (key={api_key} pw={db_password})"
+ )
+
+ with _capture_loguru() as records:
+ stats = svc._sync_one(client, cfg, "")
+
+ text = "".join(records)
+ assert stats["status"] == "failed"
+ assert "Zotero: sync failed for collection ALL (RuntimeError):" in text
+ assert "Traceback (most recent call last)" not in text
+ assert api_key not in text
+ assert db_password not in text
def test_sync_one_skipped_no_pdf_item_not_reprocessed(
@@ -2632,6 +2844,69 @@ def test_connection_resolves_username_in_library_id(monkeypatch):
assert cfg.library_id == "20971466"
+def test_connection_withholds_zotero_exception_detail(monkeypatch):
+ from local_deep_research.research_library.zotero.client import ZoteroError
+
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="1")
+ monkeypatch.setattr(ZoteroSyncService, "get_config", lambda self: cfg)
+
+ fake_client = MagicMock()
+ fake_client.__enter__.return_value = fake_client
+ fake_client.test_connection.side_effect = ZoteroError(
+ "private upstream response"
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_make_client", lambda _cfg: fake_client)
+
+ result = svc.test_connection()
+
+ assert result == {
+ "success": False,
+ "error": (
+ "Zotero connection failed. Check the configured API key and "
+ "library settings."
+ ),
+ }
+ assert "private upstream response" not in result["error"]
+
+
+def test_connection_forwards_curated_zotero_guidance(monkeypatch):
+ """``test_connection``'s ``except ZoteroError:`` arm must keep the
+ curated text. Catches the revert that hardcodes a single generic
+ "connection failed" string for every Zotero failure, which loses the
+ numeric-library-ID hint on the endpoint the settings UI calls first.
+
+ It does NOT catch a revert to ``sanitize_error_for_client(str(exc))`` --
+ that scrubber leaves a curated constant unchanged.
+ ``test_connection_withholds_zotero_exception_detail`` above is the leg
+ that fails on that revert.
+ """
+ from local_deep_research.research_library.zotero.client import (
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ ZoteroError,
+ )
+
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="1")
+ monkeypatch.setattr(ZoteroSyncService, "get_config", lambda self: cfg)
+
+ fake_client = MagicMock()
+ fake_client.__enter__.return_value = fake_client
+ fake_client.test_connection.side_effect = ZoteroError(
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_make_client", lambda _cfg: fake_client)
+
+ result = svc.test_connection()
+
+ assert result == {
+ "success": False,
+ "error": ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ }
+
+
def test_config_configured_without_library_id_for_user_library():
"""A personal cloud library is configured with just key+enabled; a group
library still requires an explicit ID."""
diff --git a/tests/security/test_library_rag_security_fastapi.py b/tests/security/test_library_rag_security_fastapi.py
index 912ef807f7..1d0ead026d 100644
--- a/tests/security/test_library_rag_security_fastapi.py
+++ b/tests/security/test_library_rag_security_fastapi.py
@@ -34,11 +34,10 @@ COVERAGE AREA 3 -- ``web/routers/rag.py::_format_test_embedding_error``.
were deleted); this file now pins its branches. This is the CWE-209 error
boundary on
``POST /library/api/rag/test-embedding``: the function's output goes
- straight into the response body. Three branches matter -- the internal-LDR
- suppression (rag.py:333-344, which exists *precisely because* internal
- exceptions carry filesystem paths / SQL fragments that
- ``sanitize_error_message()`` does not pattern-match), the upstream-provider
- branch (redaction only), and the verbatim ``str(exc)`` fallback.
+ straight into the response body. Three branches matter -- internal LDR,
+ upstream provider, and unexpected failures. Every branch returns a fixed
+ category message because exception text can carry filesystem paths, SQL,
+ response bodies, or credentials.
``tests/web/routers/test_rag_hostile_input.py::
test_test_embedding_does_not_leak_decoder_message`` covers only the
malformed-body 400, which returns before this function is ever reached.
@@ -611,7 +610,8 @@ class TestFormatTestEmbeddingErrorUnit:
# Positive first: the caller still gets a useful, correctly
# categorised message (so the absence checks below are not vacuous).
- assert "internal LDR error (NoSettingsContextError)" in message
+ assert "internal LDR error" in message
+ assert "NoSettingsContextError" not in message
assert "nomic-embed-text" in message
assert "report it on GitHub" in message
# And the detail -- including the server filesystem path -- is gone.
@@ -631,12 +631,8 @@ class TestFormatTestEmbeddingErrorUnit:
assert "internal LDR error" in message
assert _FAKE_API_KEY not in message
- def test_upstream_provider_error_is_surfaced_but_key_redacted(self):
- """The upstream branch keeps the provider's detail (the user needs it
- to fix their own configuration) but only after
- ``sanitize_error_message``. An API key echoed back in a provider error
- must not survive.
- """
+ def test_upstream_provider_error_withholds_exception_text(self):
+ """Provider failures retain guidance without reflecting detail."""
from local_deep_research.web.routers.rag import (
_format_test_embedding_error,
)
@@ -646,19 +642,16 @@ class TestFormatTestEmbeddingErrorUnit:
"text-embedding-3-small",
)
- # Positive: categorised as a provider error and the useful part of the
- # detail survived.
- assert "The provider returned an error" in message
- assert "Incorrect API key provided" in message
+ assert "The request to the provider failed" in message
assert "text-embedding-3-small" in message
- # Negative: the key itself did not.
+ assert "Incorrect API key provided" not in message
assert _FAKE_API_KEY not in message
- assert "[REDACTED_KEY]" in message
+ assert "[REDACTED_KEY]" not in message
def test_stdlib_exception_no_longer_echoes_verbatim_detail(self):
"""The final fallback. An exception from neither the internal nor an
- upstream module prefix now gets its class name only -- ``str(exc)`` is
- no longer echoed.
+ upstream module prefix now gets a fixed category message -- neither
+ ``str(exc)`` nor exception type metadata is echoed.
HARDENED for CodeQL alert 8001 (CWE-209). This branch previously
returned ``f"Embedding test failed for model '{model}': {detail}"``
@@ -675,15 +668,15 @@ class TestFormatTestEmbeddingErrorUnit:
RuntimeError("Connection refused by embedding backend"), "m"
)
- # Positive: still correctly categorised, and still names the model
- # and the exception class, so the absence checks are not vacuous.
+ # Positive: still correctly categorised and names the model.
assert "Embedding test failed for model 'm'" in message
- assert "RuntimeError" in message
+ assert "unexpected error" in message
+ assert "RuntimeError" not in message
# Negative: the exception text itself no longer reaches the caller.
assert "Connection refused by embedding backend" not in message
# Not miscategorised as an LDR bug -- the #4208 regression.
assert "bug in LDR" not in message
- assert "The provider returned an error" not in message
+ assert "The request to the provider failed" not in message
def test_stdlib_exception_branch_withholds_the_detail_entirely(self):
"""Credential redaction used to be the only mitigation on this branch.
@@ -699,7 +692,8 @@ class TestFormatTestEmbeddingErrorUnit:
RuntimeError(f"auth failed for {_FAKE_API_KEY}"), "m"
)
- assert "RuntimeError" in message
+ assert "unexpected error" in message
+ assert "RuntimeError" not in message
assert "auth failed for" not in message
assert _FAKE_API_KEY not in message
@@ -711,7 +705,7 @@ class TestFormatTestEmbeddingErrorUnit:
raised anywhere under ``get_embedding_function`` used to put a server
path in the HTTP 500 body -- exactly the disclosure the
internal-module branch exists to prevent, one branch further down.
- The fallback now returns the class name only.
+ The fallback now returns a fixed category message.
"""
from local_deep_research.web.routers.rag import (
_format_test_embedding_error,
@@ -724,16 +718,15 @@ class TestFormatTestEmbeddingErrorUnit:
# Positive control first.
assert "Embedding test failed for model 'm'" in message
- assert "FileNotFoundError" in message
+ assert "unexpected error" in message
+ assert "FileNotFoundError" not in message
# The disclosure.
assert _SERVER_PATH not in message
assert "encrypted_databases" not in message
assert "No such file or directory" not in message
- def test_empty_exception_message_falls_back_to_the_class_name(self):
- """``str(exc).strip() or type(exc).__name__`` -- an exception with no
- message must still produce a non-empty, non-misleading result.
- """
+ def test_empty_exception_message_still_returns_a_category(self):
+ """An exception with no message still produces useful guidance."""
from local_deep_research.web.routers.rag import (
_format_test_embedding_error,
)
@@ -741,7 +734,8 @@ class TestFormatTestEmbeddingErrorUnit:
message = _format_test_embedding_error(ValueError(""), "m")
assert "Embedding test failed for model 'm'" in message
- assert "ValueError" in message
+ assert "unexpected error" in message
+ assert "ValueError" not in message
def test_module_prefix_match_is_boundary_anchored(self):
"""``_module_matches`` must not treat ``local_deep_research_evil`` (or
@@ -802,15 +796,16 @@ class TestTestEmbeddingEndpointDoesNotLeak:
# Positive control FIRST: the response really is the formatted
# internal-error message, so the absence assertions below cannot be
# satisfied by an empty body, a 401, or an unrelated error page.
- assert "internal LDR error (NoSettingsContextError)" in body["error"], (
+ assert "internal LDR error" in body["error"], (
f"expected the internal-error wording, got: {body!r}"
)
+ assert "NoSettingsContextError" not in body["error"]
# Now the disclosure check.
assert _SERVER_PATH not in resp.text
assert "encrypted_databases" not in resp.text
assert "could not open" not in resp.text
- def test_provider_error_reaches_the_browser_with_the_key_redacted(
+ def test_provider_error_reaches_the_browser_without_exception_text(
self, library_client
):
client, _, _ = library_client
@@ -831,12 +826,10 @@ class TestTestEmbeddingEndpointDoesNotLeak:
assert resp.status_code == 500, resp.text
body = resp.json()
- # Positive: the actionable provider detail did survive to the browser.
- assert "The provider returned an error" in body["error"]
- assert "Incorrect API key provided" in body["error"]
- # Negative: the credential did not.
+ assert "The request to the provider failed" in body["error"]
+ assert "Incorrect API key provided" not in body["error"]
assert _FAKE_API_KEY not in resp.text
- assert "[REDACTED_KEY]" in body["error"]
+ assert "[REDACTED_KEY]" not in body["error"]
def test_successful_embedding_still_returns_200(self, library_client):
"""Non-vacuity control for the two tests above: with the same patch
diff --git a/tests/web/routers/test_error_response_leakage.py b/tests/web/routers/test_error_response_leakage.py
index 740781323b..07c6988b8d 100644
--- a/tests/web/routers/test_error_response_leakage.py
+++ b/tests/web/routers/test_error_response_leakage.py
@@ -510,15 +510,20 @@ BROAD_BODY_LEAK_ALLOWLIST: dict[str, str] = {
# is gated by a runtime isinstance check that the static scanner
# cannot see across. The justification here mirrors the comment on
# the call site: ``e.decision.reason`` is curated client-facing text
- # produced by the egress policy module (not raw exception data); the
- # non-PolicyDeniedError path uses ``_format_test_embedding_error``,
- # which is documented at the call site as going through
- # sanitize_error_for_client() and reduces everything else to its
- # class name.
+ # produced by the egress policy module (not raw exception data).
+ # Every other exception goes to ``_format_test_embedding_error``, which
+ # does NOT scrub-and-echo: it reads the exception's module and class to
+ # SELECT one of a fixed set of literals and interpolates neither, so no
+ # exception-derived string reaches the body on that path. (It used to be
+ # described as going through ``sanitize_error_for_client``; that is no
+ # longer true, and the function's own docstring now explains why echoing
+ # scrubbed text would be wrong here -- the reachable exceptions carry SQL
+ # text and absolute server paths, which that scrubber does not remove.)
"src/local_deep_research/web/routers/rag.py::test_embedding": (
"broad except Exception gates the e.decision.reason response on "
- "isinstance(e, PolicyDeniedError); non-PolicyDeniedError paths "
- "use sanitize_error_for_client via _format_test_embedding_error"
+ "isinstance(e, PolicyDeniedError); every other path calls "
+ "_format_test_embedding_error, which selects a fixed message from "
+ "the exception's type and never interpolates its text"
),
}
diff --git a/tests/web/routers/test_notes_branch_edges.py b/tests/web/routers/test_notes_branch_edges.py
index e49533dcd1..b7c55e12c6 100644
--- a/tests/web/routers/test_notes_branch_edges.py
+++ b/tests/web/routers/test_notes_branch_edges.py
@@ -290,20 +290,35 @@ def test_comment_title_truncates_long_single_line():
assert len(title) == len("Comment: ") + 60
+# route | service method | kwargs JSON | fixed client-safe message the
+# route answers with. The service's own ValueError text is logged at the
+# route and never echoed to the client.
VALIDATION_ERROR_CASES = [
- 'create_note|create_note|{"body":{"title":"t","content":"c"}}',
- 'update_note|update_note|{"note_id":"n","body":{"title":"t"}}',
- 'remove_note_from_collection|remove_from_collection|{"note_id":"n","collection_id":"c"}',
- 'reorder_note_research|reorder_note_research|{"note_id":"n","body":{"research_ids":["r"]}}',
- 'create_research_note|create_note_for_research|{"research_id":"r","body":{}}',
- 'create_document_note|create_note_for_document|{"document_id":"d","body":{}}',
- 'accept_suggested_link|accept_suggested_link|{"note_id":"n","body":{"target_note_id":"t"}}',
+ 'create_note|create_note|{"body":{"title":"t","content":"c"}}'
+ "|Invalid note data",
+ 'update_note|update_note|{"note_id":"n","body":{"title":"t"}}'
+ "|Invalid note data",
+ "remove_note_from_collection|remove_from_collection"
+ '|{"note_id":"n","collection_id":"c"}'
+ "|Note cannot be removed from this collection",
+ "reorder_note_research|reorder_note_research"
+ '|{"note_id":"n","body":{"research_ids":["r"]}}'
+ "|Invalid research order",
+ "create_research_note|create_note_for_research"
+ '|{"research_id":"r","body":{}}'
+ "|Invalid note data",
+ "create_document_note|create_note_for_document"
+ '|{"document_id":"d","body":{}}'
+ "|Invalid document note data",
+ "accept_suggested_link|accept_suggested_link"
+ '|{"note_id":"n","body":{"target_note_id":"t"}}'
+ "|Suggested link cannot be accepted",
]
@pytest.mark.parametrize("case", VALIDATION_ERROR_CASES)
def test_service_validation_errors_are_client_errors(monkeypatch, case):
- name, method, raw_kwargs = case.split("|", 2)
+ name, method, raw_kwargs, expected_message = case.split("|", 3)
service = MagicMock()
getattr(service, method).side_effect = ValueError("invalid note data")
service.note_exists.return_value = True
@@ -314,7 +329,9 @@ def test_service_validation_errors_are_client_errors(monkeypatch, case):
)
assert response.status_code == 400
- assert _payload(response)["error"] == "invalid note data"
+ payload = _payload(response)
+ assert payload["error"] == expected_message
+ assert "invalid note data" not in payload["error"]
def test_link_research_integrity_error_classification(monkeypatch):
diff --git a/tests/web/routers/test_rag_embedding_error_sanitisation.py b/tests/web/routers/test_rag_embedding_error_sanitisation.py
index e712d7f57b..334994ec58 100644
--- a/tests/web/routers/test_rag_embedding_error_sanitisation.py
+++ b/tests/web/routers/test_rag_embedding_error_sanitisation.py
@@ -1,27 +1,12 @@
-"""CWE-209 regression coverage for
-``web/routers/rag.py::_format_test_embedding_error``.
-
-CodeQL alert 8001 (``py/stack-trace-exposure``, ``rag.py`` catch-all branch)
-was upheld: the function's final branch echoed
-``sanitize_error_message(str(exc))`` for every exception whose class module
-was outside the five-entry upstream allowlist. That set includes
-``sqlalchemy.exc.*`` (the route's ``try`` block opens the user's SQLCipher
-database, and a ``DBAPIError``'s ``str()`` renders the driver message plus
-``[SQL: ...]`` / ``[parameters: ...]``) and ``builtins.OSError`` (absolute
-server paths, OS account name). ``sanitize_error_message`` is a
-credential-*shape* scrubber: it redacts ``sk-``/``Bearer``/URL userinfo and
-nothing else, so those paths and SQL fragments reached the HTTP 500 body of
-``POST /library/api/rag/test-embedding`` verbatim — the exact disclosure the
-LDR-internal branch immediately above it exists to prevent.
-
-The fix inverts the default: detail is echoed only for the allowlisted
-upstream-provider modules (and only through ``sanitize_error_for_client``,
-which adds the control-char strip and length cap the bare scrubber lacks);
-everything else is reduced to its exception class name.
-
-These tests are structured as leak checks with a positive control each, so
-an assertion cannot pass vacuously (empty string, wrong branch, import
-failure).
+"""CWE-209 regression coverage for the RAG embedding-test error boundary.
+
+Exception messages may contain response bodies, credentials, filesystem
+paths, or SQL. The public formatter therefore returns fixed category messages
+for internal, provider (connect-failure or answered-with-an-error), and
+unexpected failures. Every test below pairs its leak checks with a positive
+assertion naming the category it expects, so a formatter that started
+returning an empty or unrelated string could not pass by having "no leak" in
+it.
"""
import pytest
@@ -66,7 +51,7 @@ def _sqlalchemy_exception(message):
class TestUnrecognisedModulesDoNotReflectExceptionText:
"""The leak path. ``type(exc).__module__`` outside the allowlist must
- yield a fixed message plus the class name — never the exception text.
+ yield a fixed message without exception text or type metadata.
"""
def test_oserror_server_path_is_not_reflected(self):
@@ -77,11 +62,9 @@ class TestUnrecognisedModulesDoNotReflectExceptionText:
"nomic-embed-text",
)
- # Positive control: the caller still gets a real, correctly shaped
- # message naming the model and the exception class, so the absence
- # assertions below cannot pass on an empty or unrelated string.
+ # Positive control: the caller still gets a useful category message.
assert "Embedding test failed for model 'nomic-embed-text'" in message
- assert "FileNotFoundError" in message
+ assert "unexpected error" in message
# The disclosure itself.
assert _SERVER_PATH not in message
assert "encrypted_databases" not in message
@@ -105,7 +88,7 @@ class TestUnrecognisedModulesDoNotReflectExceptionText:
message = _format_test_embedding_error(exc, "m")
assert "Embedding test failed for model 'm'" in message
- assert "OperationalError" in message
+ assert "unexpected error" in message
assert _SQL_FRAGMENT not in message
assert "SELECT" not in message
assert "[SQL:" not in message
@@ -119,7 +102,7 @@ class TestUnrecognisedModulesDoNotReflectExceptionText:
)
assert "Embedding test failed for model 'm'" in message
- assert "RuntimeError" in message
+ assert "unexpected error" in message
assert "Connection refused" not in message
assert "embedding backend" not in message
@@ -132,57 +115,70 @@ class TestUnrecognisedModulesDoNotReflectExceptionText:
OSError(f"permission denied: {_SERVER_PATH}"), "m"
)
second = _format_test_embedding_error(
- OSError(f"totally different text {_SQL_FRAGMENT}"), "m"
+ RuntimeError(f"totally different text {_SQL_FRAGMENT}"), "m"
)
assert first == second
- assert "OSError" in first
+ assert "unexpected error" in first
+ assert "OSError" not in first
+ assert "RuntimeError" not in first
- def test_empty_exception_message_still_yields_the_class_name(self):
+ def test_empty_exception_message_still_yields_a_useful_message(self):
message = _format_test_embedding_error(ValueError(""), "m")
- assert "ValueError" in message
assert "Embedding test failed for model 'm'" in message
+ assert "unexpected error" in message
+ assert "ValueError" not in message
-class TestRecognisedProvidersKeepTheirDetail:
- """Positive control for the fix: the actionable upstream-provider
- messages that users need to fix their own configuration are preserved.
- """
+class TestRecognisedProvidersWithholdTheirDetail:
+ """Provider failures retain actionable guidance, not exception detail."""
- def test_openai_provider_detail_survives_with_the_key_redacted(self):
+ def test_openai_provider_detail_is_withheld(self):
message = _format_test_embedding_error(
_upstream_exception(f"Incorrect API key provided: {_FAKE_API_KEY}"),
"text-embedding-3-small",
)
- assert "The provider returned an error" in message
- assert "Incorrect API key provided" in message
+ assert "The request to the provider failed" in message
assert "text-embedding-3-small" in message
+ assert "Incorrect API key provided" not in message
assert _FAKE_API_KEY not in message
- assert "[REDACTED_KEY]" in message
+ assert "[REDACTED_KEY]" not in message
- def test_httpx_connect_error_detail_survives(self):
+ def test_httpx_connect_error_says_connect_not_rejected(self):
+ """A connect failure means nothing was rejected. Sending the user to
+ check credentials for an unreachable host is the misleading-guidance
+ class #4208 removed, so this branch has its own fixed message.
+ """
import httpx
message = _format_test_embedding_error(
httpx.ConnectError("All connection attempts failed"), "m"
)
- assert "The provider returned an error" in message
- assert "All connection attempts failed" in message
+ assert "Could not connect to the provider" in message
+ assert "reachable" in message
+ assert "rejected" not in message
+ assert "credentials" not in message
+ assert "All connection attempts failed" not in message
- def test_provider_detail_is_length_capped(self):
- """``sanitize_error_for_client`` (not the bare credential scrubber)
- now runs on the echoed detail, so a provider cannot replay a
- multi-kilobyte body into the response.
- """
- message = _format_test_embedding_error(
+ def test_provider_message_is_constant_across_payloads(self):
+ first = _format_test_embedding_error(
_upstream_exception("x" * 5000), "m"
)
+ second = _format_test_embedding_error(
+ _upstream_exception("different private detail"), "m"
+ )
- assert len(message) < 400
- assert "..." in message
+ assert first == second
+ # Category assertion, not just "the two are equal": an
+ # AuthenticationError is an answered request, so it must select the
+ # provider branch rather than the connect-failure or default-deny
+ # wording.
+ assert "The request to the provider failed" in first
+ assert "unexpected error" not in first
+ assert len(first) < 300
class TestInternalExceptionsAreStillSuppressed:
@@ -199,7 +195,8 @@ class TestInternalExceptionsAreStillSuppressed:
NoSettingsContextError(f"could not open {_SERVER_PATH}"), "m"
)
- assert "internal LDR error (NoSettingsContextError)" in message
+ assert "internal LDR error" in message
+ assert "NoSettingsContextError" not in message
assert "report it on GitHub" in message
assert _SERVER_PATH not in message
assert "could not open" not in message
@@ -220,5 +217,10 @@ def test_no_unrecognised_exception_family_reflects_a_server_path(exc):
"""
message = _format_test_embedding_error(exc, "m")
- assert "Embedding test failed" in message # positive control
+ # Positive control, category included: each of these classes is outside
+ # both allowlists, so the default-deny branch is the one that must run.
+ assert "Embedding test failed for model 'm'" in message
+ assert "unexpected error" in message
+ assert "bug in LDR" not in message
assert _SERVER_PATH not in message
+ assert type(exc).__name__ not in message
diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.py
index c6c43adb39..1fc48a4f1e 100644
--- a/tests/web/routers/test_rag_indexing_pipeline.py
+++ b/tests/web/routers/test_rag_indexing_pipeline.py
@@ -748,8 +748,9 @@ class TestIndexStatusErrorDisclosure:
def test_test_embedding_route_withholds_the_same_detail(self):
"""Control: the hardened surface, given the SAME exception, returns
- the class name only. The difference from the xfails below is a
- real inconsistency between two surfaces, not a property of the
+ a fixed message carrying nothing from it -- not even the class
+ name. The difference from the xfails below is a real
+ inconsistency between two surfaces, not a property of the
exception text."""
from local_deep_research.web.routers.rag import (
_format_test_embedding_error,
@@ -759,7 +760,17 @@ class TestIndexStatusErrorDisclosure:
_LEAKY_BACKEND_ERROR, "nomic-embed-text"
)
- assert "OSError" in message
+ # Byte-exact, so this stays a positive control: it proves the
+ # default-deny branch really ran for this exception (an OSError is
+ # outside both the LDR-internal and the upstream-provider
+ # allowlists) rather than passing because some unrelated string
+ # happened not to contain the secrets.
+ assert message == (
+ "Embedding test failed for model 'nomic-embed-text' due to an "
+ "unexpected error. Check the provider URL and model name; the "
+ "full error is in the server logs."
+ )
+ assert "OSError" not in message
assert "/srv/ldr-data/models" not in message
assert "embed-internal.corp.example" not in message
@@ -777,7 +788,7 @@ class TestIndexStatusErrorDisclosure:
"the embedding-manager construction boundary that was hardened "
"on the other route. Fix by routing this sink through the same "
"module-allowlist formatter (or storing the class name only) "
- "and keeping the full text in the server log."
+ "and keeping the full text in the server log. Tracked as #6273."
),
)
def test_backend_failure_detail_does_not_reach_the_task_error(
@@ -821,7 +832,7 @@ class TestIndexStatusErrorDisclosure:
"get_index_status returns. A DBAPIError renders driver text "
"plus [SQL: ...] and [parameters: ...] (the exact example "
"_format_test_embedding_error cites when refusing to echo "
- "sqlalchemy.exc.*). Fix as above."
+ "sqlalchemy.exc.*). Fix as above. Tracked as #6273."
),
)
def test_reconciliation_failure_detail_does_not_reach_the_task(
diff --git a/tests/web/routers/test_redirect_static.py b/tests/web/routers/test_redirect_static.py
index ce3e417b5e..fa0f3bdef9 100644
--- a/tests/web/routers/test_redirect_static.py
+++ b/tests/web/routers/test_redirect_static.py
@@ -75,3 +75,58 @@ def test_query_and_fragment_characters_cannot_truncate_the_target(client):
f"unencoded query/fragment character survived into the redirect "
f"target: {location!r}"
)
+
+
+ "legacy_path",
+ [
+ "../outside.invalid/x.css",
+ "css/../../outside.invalid/x.css",
+ "css//outside.invalid/x.css",
+ r"..\outside.invalid\x.css",
+ "css/./styles.css",
+ "css/styles.css\x00ignored",
+ ],
+)
+def test_redirect_rejects_paths_clients_can_normalize_out_of_static(
+ legacy_path,
+):
+ """No attacker-controlled path can normalize outside ``/static/``.
+
+ Call the handler directly because HTTP clients normalize dot segments
+ before sending a request, which would otherwise test the client rather
+ than the redirect boundary.
+ """
+ from fastapi import HTTPException
+
+ from local_deep_research.web.routers.research import redirect_static
+
+ with pytest.raises(HTTPException) as excinfo:
+ redirect_static(legacy_path)
+
+ assert excinfo.value.status_code == 404
+
+
+def test_rejected_path_renders_through_the_app_404_handler(client):
+ """The rejection must use the app's shared 404, not its own envelope.
+
+ Catches a revert to ``return JSONResponse({"status": "error", ...},
+ 404)``: this route exists for bookmarked BROWSER URLs, and
+ ``fastapi_app.py``'s ``@app.exception_handler(404)`` is what decides a
+ browser gets ``text/html`` while only an API caller gets JSON. A body
+ returned from the handler bypasses that decision and shows a raw JSON
+ document in the browser -- a third 404 shape on top of the two
+ ``tests/web/test_exception_handler_contract.py`` pins.
+
+ An empty captured path is used because HTTP clients normalise the dot
+ segments the other cases rely on before the request is sent.
+ """
+ resp = client.get(
+ "/redirect-static/",
+ follow_redirects=False,
+ headers={"Accept": "text/html"},
+ )
+
+ assert resp.status_code == 404
+ assert resp.headers["content-type"].startswith("text/html")
+ assert resp.text == "Not found"
diff --git a/tests/web/routers/test_zotero_router_contracts.py b/tests/web/routers/test_zotero_router_contracts.py
index ee6b47fe16..b79e25e930 100644
--- a/tests/web/routers/test_zotero_router_contracts.py
+++ b/tests/web/routers/test_zotero_router_contracts.py
@@ -6,12 +6,13 @@ configured Zotero account, typed client failure, or background thread without
opening an encrypted database or contacting Zotero.
"""
-from contextlib import nullcontext
+from contextlib import contextmanager, nullcontext
from json import loads
from types import SimpleNamespace
from unittest.mock import Mock, call, patch
import pytest
+from loguru import logger as loguru_logger
from starlette.requests import Request
from local_deep_research.research_library.zotero import (
@@ -19,6 +20,12 @@ from local_deep_research.research_library.zotero import (
ZoteroError,
ZoteroTransientError,
)
+from local_deep_research.research_library.zotero.client import (
+ ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+)
+from local_deep_research.research_library.zotero.sync_service import (
+ ZOTERO_GROUP_ID_REQUIRED_MESSAGE,
+)
from local_deep_research.web.routers import zotero
@@ -94,31 +101,138 @@ def test_expired_session_short_circuits_every_database_endpoint(endpoint):
@pytest.mark.parametrize(
- ("exc", "status"),
+ ("exc", "status", "message"),
[
- (ZoteroAuthError("revoked key"), 401),
- (ZoteroTransientError("rate limited"), 503),
- (ZoteroError("bad library"), 400),
+ (
+ ZoteroAuthError("revoked key"),
+ 401,
+ "Zotero authentication failed. Check the configured API key.",
+ ),
+ (
+ ZoteroTransientError("rate limited"),
+ 503,
+ "Zotero is temporarily unavailable. Please try again later.",
+ ),
+ (
+ ZoteroError("bad library"),
+ 400,
+ "Zotero request failed. Check the integration settings.",
+ ),
],
ids=["auth", "transient", "client"],
)
-def test_zotero_errors_map_to_stable_http_statuses(exc, status):
+def test_zotero_errors_map_to_stable_http_statuses(exc, status, message):
response = zotero._zotero_error_response(exc)
assert response.status_code == status
- assert _body(response) == {"success": False, "error": str(exc)}
+ assert _body(response) == {"success": False, "error": message}
+
+
+def test_zotero_error_response_forwards_curated_guidance():
+ """The author-written HTTP 400 diagnostic must reach the browser.
+
+ Catches the revert that replaces every ``ZoteroError`` message with one
+ generic string. This text is the only place the product explains the
+ most common Zotero misconfiguration (a username in the library-ID
+ setting).
+
+ What this test does NOT catch: a revert to
+ ``sanitize_error_for_client(str(exc))``. That scrubber leaves a curated
+ constant byte-for-byte unchanged, so this assertion passes either way.
+ ``test_zotero_error_response_withholds_exception_text`` below is the leg
+ that fails on that revert -- it feeds a message that is not in the
+ allowlist and requires the generic fallback. The two are a pair: this one
+ pins that curated guidance survives, that one pins that nothing else does.
+ """
+ response = zotero._zotero_error_response(
+ ZoteroError(ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE)
+ )
+
+ assert response.status_code == 400
+ assert _body(response) == {
+ "success": False,
+ "error": ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
+ }
+ assert "NUMERIC userID" in _body(response)["error"]
-def test_zotero_error_response_sanitizes_exception_text():
+def test_zotero_error_response_withholds_exception_text():
secret = "sk-ABCDEFGHIJKLMNOPQRSTUV"
response = zotero._zotero_error_response(
ZoteroError(f"bad key {secret}\nforbidden control\x00" + "x" * 500)
)
error = _body(response)["error"]
+ assert error == "Zotero request failed. Check the integration settings."
assert secret not in error
- assert "\n" not in error and "\x00" not in error
- assert len(error) <= 200
+ assert "bad key" not in error
+
+
+@contextmanager
+def _capture_loguru(level="DEBUG"):
+ """Collect this package's loguru records as text.
+
+ ``caplog`` sees nothing here: loguru does not write through the stdlib
+ ``logging`` handlers pytest installs, and the package is ``logger.disable``d
+ by default. Same pattern as
+ ``tests/research_library/test_zotero_sync_contracts.py``.
+ """
+ records = []
+ loguru_logger.enable("local_deep_research")
+ sink_id = loguru_logger.add(
+ lambda message: records.append(str(message)), level=level
+ )
+ try:
+ yield records
+ finally:
+ loguru_logger.remove(sink_id)
+ loguru_logger.disable("local_deep_research")
+
+
+def test_zotero_error_response_logs_the_curated_text_it_withholds():
+ """The generic body is only safe if the server still records WHICH
+ failure produced it.
+
+ ``_zotero_error_response`` answers a non-allowlisted ``ZoteroError`` with
+ "Zotero request failed. Check the integration settings." -- a string that
+ is identical for an unroutable proxy, a deleted collection and a
+ malformed library id. The exception class and its author-written text are
+ the only thing left that tells those apart, so they must reach the log.
+ Deleting the ``logger.warning`` (the state this file's subject was in
+ before) leaves nothing on either side: the operator sees a generic body
+ and an empty log.
+
+ Note what is asserted about the traceback: this runs on the request path,
+ where the caller's frames hold ``cfg.api_key`` and the SQLCipher
+ password, so the site must stay ``logger.warning`` -- ``logger.exception``
+ would render those frames under loguru's ``diagnose``.
+
+ The call happens inside a real ``except`` block (raised and caught, not
+ invoked bare) so the traceback assertion is falsifiable: with no active
+ exception (``sys.exc_info() == (None, None, None)``), loguru 0.7.3's
+ ``logger.exception(...)`` emits ``"NoneType: None"`` and no traceback
+ header at all, so a bare call to the helper would pass this assertion
+ whether the revert landed or not.
+ """
+ detail = "collection ABC vanished between the listing and the fetch"
+
+ with _capture_loguru() as records:
+ try:
+ raise ZoteroTransientError(detail)
+ except ZoteroTransientError as exc:
+ response = zotero._zotero_error_response(exc)
+
+ text = "".join(records)
+ assert "ZoteroTransientError" in text, text
+ assert detail in text, text
+ # The client got the generic fallback; the log got the specific text.
+ assert (
+ _body(response)["error"]
+ == "Zotero is temporarily unavailable. Please try again later."
+ )
+ assert detail not in _body(response)["error"]
+ # A traceback would render the API-key-bearing frames under diagnose.
+ assert "Traceback (most recent call last)" not in text
def test_configured_summary_exposes_presence_but_never_the_api_key():
@@ -178,20 +292,32 @@ def test_configured_remote_lists_are_returned(
ids=["collections", "groups"],
)
@pytest.mark.parametrize(
- ("exc_type", "status"),
+ ("exc_type", "status", "message"),
[
- (ZoteroAuthError, 401),
- (ZoteroTransientError, 503),
- (ZoteroError, 400),
+ (
+ ZoteroAuthError,
+ 401,
+ "Zotero authentication failed. Check the configured API key.",
+ ),
+ (
+ ZoteroTransientError,
+ 503,
+ "Zotero is temporarily unavailable. Please try again later.",
+ ),
+ (
+ ZoteroError,
+ 400,
+ "Zotero request failed. Check the integration settings.",
+ ),
],
ids=["auth", "transient", "client"],
)
def test_remote_list_endpoints_map_typed_client_failures(
- endpoint, method, exc_type, status
+ endpoint, method, exc_type, status, message
):
service = Mock()
service.get_config.return_value = _configured()
- getattr(service, method).side_effect = exc_type("safe failure")
+ getattr(service, method).side_effect = exc_type("private failure detail")
with (
patch.object(zotero, "_db_password", return_value="db-password"),
@@ -200,18 +326,10 @@ def test_remote_list_endpoints_map_typed_client_failures(
response = endpoint(_request(), username="alice")
assert response.status_code == status
- assert _body(response) == {"success": False, "error": "safe failure"}
+ assert _body(response) == {"success": False, "error": message}
- ("service_result", "status"),
- [
- ({"success": True, "message": "Connected"}, 200),
- ({"success": False, "error": "Not authorized"}, 400),
- ],
- ids=["success", "rejected"],
-)
-def test_connection_result_controls_http_status(service_result, status):
+def _test_connection_response(service_result):
service = Mock()
service.test_connection.return_value = service_result
@@ -219,10 +337,93 @@ def test_connection_result_controls_http_status(service_result, status):
patch.object(zotero, "_db_password", return_value="db-password"),
patch.object(zotero, "ZoteroSyncService", return_value=service),
):
- response = zotero.test_connection(_request(), username="alice")
+ return zotero.test_connection(_request(), username="alice")
+
+
+ ("service_result", "status", "expected"),
+ [
+ (
+ {
+ "success": True,
+ "library_version": 42,
+ "collection_count": 3,
+ },
+ 200,
+ {
+ "success": True,
+ "library_version": 42,
+ "collection_count": 3,
+ },
+ ),
+ (
+ # The service's own guidance for a misconfigured group library.
+ # It is a module constant, not exception-derived, and the route
+ # must pass it through rather than replacing it: this is the
+ # only text that tells the user WHICH setting is wrong.
+ {"success": False, "error": ZOTERO_GROUP_ID_REQUIRED_MESSAGE},
+ 400,
+ {"success": False, "error": ZOTERO_GROUP_ID_REQUIRED_MESSAGE},
+ ),
+ ],
+ ids=["success", "rejected"],
+)
+def test_connection_result_controls_http_status(
+ service_result, status, expected
+):
+ response = _test_connection_response(service_result)
+
+ assert response.status_code == status
+ assert _body(response) == expected
+
+
+ ("service_result", "status"),
+ [
+ (
+ {
+ "success": True,
+ "library_version": 42,
+ "collection_count": 3,
+ "debug": "sk-live-ABCDEFGHIJKLMNOPQRSTUV",
+ "api_key": "secret-key",
+ },
+ 200,
+ ),
+ (
+ {
+ "success": False,
+ "error": ZOTERO_GROUP_ID_REQUIRED_MESSAGE,
+ "debug": "sk-live-ABCDEFGHIJKLMNOPQRSTUV",
+ "api_key": "secret-key",
+ },
+ 400,
+ ),
+ ],
+ ids=["success", "rejected"],
+)
+def test_connection_body_is_built_from_a_key_allowlist(service_result, status):
+ """Only the four known keys may reach the browser.
+
+ Catches the revert to ``JSONResponse(result, status_code=...)``, which
+ forwarded the service dict wholesale -- so any field a future
+ ``test_connection`` adds (a config echo, a resolved id, a debug blob)
+ would ship to the client with nobody deciding it should.
+ """
+ response = _test_connection_response(service_result)
+ body = _body(response)
assert response.status_code == status
- assert _body(response) == service_result
+ assert set(body) <= {
+ "success",
+ "error",
+ "library_version",
+ "collection_count",
+ }
+ assert "debug" not in body
+ assert "api_key" not in body
+ assert "sk-live-ABCDEFGHIJKLMNOPQRSTUV" not in response.body.decode()
+ assert "secret-key" not in response.body.decode()
def test_status_combines_stored_state_with_live_progress():
@@ -330,6 +531,16 @@ def test_manual_sync_thread_reprocesses_skips_and_cleans_up():
def test_manual_sync_thread_contains_worker_failure_and_still_cleans_up():
+ """The background thread's failure log must not carry a traceback.
+
+ ``front.get_config()`` returns a real ``api_key`` and the daemon thread's
+ own ``password`` closure variable is live in this frame -- both would
+ render under loguru's ``diagnose`` if the handler used
+ ``logger.exception`` instead of the scrubbed ``logger.warning`` this
+ fixes it to. See ``_zotero_error_response`` and
+ ``ZoteroSyncService._sync_one``'s bare-``Exception`` arm for the same
+ shape.
+ """
front = Mock()
front.get_config.return_value = _configured()
worker = Mock()
@@ -344,7 +555,7 @@ def test_manual_sync_thread_contains_worker_failure_and_still_cleans_up():
zotero, "thread_cleanup", return_value=nullcontext()
) as cleanup,
patch.object(zotero.threading, "Thread") as thread_class,
- patch.object(zotero.logger, "exception") as log_exception,
+ patch.object(zotero, "logger") as mock_logger,
):
zotero.sync_now(_request(), username="alice")
thread_class.call_args.kwargs["target"]()
@@ -354,4 +565,9 @@ def test_manual_sync_thread_contains_worker_failure_and_still_cleans_up():
call("alice", "db-password"),
]
cleanup.assert_called_once_with()
- log_exception.assert_called_once_with("Zotero manual sync failed")
+ mock_logger.exception.assert_not_called()
+ mock_logger.warning.assert_called_once()
+ warning_text = mock_logger.warning.call_args.args[0]
+ assert warning_text.startswith("Zotero manual sync failed:")
+ assert "sync failed" in warning_text
+ assert "secret-key" not in warning_text
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index 23445c80c0..ffcd8bb64e 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -1674,6 +1674,20 @@ EXPECTED_STATUS_CODES_GAINED = {
# web/routers/rag.py:_validated_collection_id.
("GET", "/library/collections/{}"): [404],
("GET", "/library/collections/{}/upload"): [404],
+ # Not a behaviour change. Flask returned the same 400 from
+ # `jsonify(result), (200 if result.get("success") else 400)` -- a ternary
+ # the AST scan cannot read as a constant, so the Flask side records only
+ # its 401. The port spells the two branches out (it rebuilds the body
+ # from a key allowlist instead of forwarding the service dict), which is
+ # what makes the 400 visible to the scan. web/routers/zotero.py.
+ ("POST", "/library/api/zotero/test"): [400],
+ # The legacy static-URL shim now rejects paths that a client or proxy
+ # could normalize outside `/static/` (dot/empty segments, backslashes,
+ # control characters) instead of redirecting them. Flask redirected
+ # unconditionally, so this 404 is new; ordinary legacy paths such as
+ # `css/styles.css` still 302. Raised as `HTTPException(404)` so the app's
+ # shared 404 handler renders it. web/routers/research.py:redirect_static.
+ ("GET", "/redirect-static/{:path}"): [404],
# An explicit `is_configured` pre-check before any Zotero network call.
# Two edge cases change outcome: a personal library with a missing API
# key used to surface as 401 (ZoteroAuthError) and is now 400, and