~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: backstop NewsAPIException.to_dict() with the central client sanitizer (#4931)
LearningCircuit2f6c219de107
diff --git a/changelog.d/4931.security.md b/changelog.d/4931.security.mdnew file mode 100644index 0000000000..8ebe88c549--- /dev/null+++ b/changelog.d/4931.security.md@@ -0,0 +1 @@+`NewsAPIException.to_dict()` now redacts credential shapes from the fields it serializes to the client through the two `@errorhandler(NewsAPIException)` handlers: the human-readable `message` goes through the central `sanitize_error_for_client()`, and string leaves of `details` go through `sanitize_error_message()`. This is a defence-in-depth backstop at the response boundary — the primary defence stays at the `news/api.py` raise sites (curated generic messages, #4843) — so a future raise site, subclass, or external caller that lets a credential-bearing string into `message` or `details` (e.g. the caller-supplied search `query` forwarded in `details`) has it redacted before it ships. Redaction is credential-shape based (Bearer/`Authorization`, `?api_key=`-style params, known token prefixes, `http(s)` URL userinfo), so legitimate text is unchanged; `error_code` / `status_code` are left untouched. It does not attempt to catch DSN userinfo (`postgresql://user:pass@`), SQL, or filesystem paths — those remain the responsibility of the raise-site discipline.diff --git a/src/local_deep_research/news/exceptions.py b/src/local_deep_research/news/exceptions.pyindex 5da69710ac..e943e871df 100644--- a/src/local_deep_research/news/exceptions.py+++ b/src/local_deep_research/news/exceptions.py@@ -8,6 +8,8 @@ appropriate JSON responses.from typing import Optional, Dict, Any+from ..security import sanitize_error_for_client, sanitize_error_message+class NewsAPIException(Exception):"""Base exception for all news API related errors."""@@ -34,15 +36,79 @@ class NewsAPIException(Exception):self.error_code = error_code or self.__class__.__name__self.details = details or {}+ @staticmethod+ def _sanitize_details(value: Any) -> Any:+ """Recursively redact credential shapes from string leaves of ``details``.++ ``details`` can carry caller-supplied free text — e.g.+ ``SubscriptionCreationException`` forwards ``{"query": <user query>}``+ (``news/api.py``), and the base constructor accepts an arbitrary+ ``details`` dict from any caller. So the same "don't trust a future+ caller" premise that scrubs ``message`` applies here. This walks+ ``dict`` / ``list`` / ``tuple`` containers and runs each ``str`` leaf+ through ``sanitize_error_message`` (credential-shape redaction only —+ no length cap or control-char strip, so structured values such as IDs+ are preserved). Non-string leaves (ints, bools, ``None``) pass through+ untouched. Redaction is in place and shape-based, so it never removes a+ value by key name — a benign ``{"query": "reset my password"}`` is+ unchanged.+ """+ if isinstance(value, dict):+ return {+ k: NewsAPIException._sanitize_details(v)+ for k, v in value.items()+ }+ if isinstance(value, (list, tuple)):+ # Always rebuild as a plain list. ``details`` is about to be+ # jsonify-ed (a tuple already serializes to a JSON array), so tuple+ # identity is irrelevant downstream — and ``type(value)(<gen>)``+ # would raise on a namedtuple / tuple subclass whose constructor is+ # not ``(iterable) -> instance``, turning a clean structured error+ # response into a bare 500 from inside the error handler.+ return [NewsAPIException._sanitize_details(v) for v in value]+ if isinstance(value, str):+ return sanitize_error_message(value)+ return value+def to_dict(self) -> Dict[str, Any]:- """Convert exception to dictionary for JSON response."""+ """Convert exception to dictionary for JSON response.++ This dict is ``jsonify``-ed straight to the client by the two+ ``@errorhandler(NewsAPIException)`` handlers (``app_factory`` and+ ``news_routes``). The primary defence against leaking raw exception+ text is at the raise sites in ``news/api.py``, which pass curated+ generic messages instead of ``str(e)``. As a boundary backstop, the+ outgoing fields are scrubbed for credential shapes so that a future+ raise site, subclass, or external caller that lets a credential-bearing+ string in has it redacted before it ships:++ * ``message`` — through ``sanitize_error_for_client`` (credential+ redaction + control-char strip + 200-char cap; it is prose meant for+ display).+ * ``details`` string leaves — through ``sanitize_error_message`` (see+ ``_sanitize_details``).++ Redaction is credential-*shape* based (``Bearer``/``Authorization``,+ ``?api_key=``-style query params, known token prefixes, ``http(s)``+ URL userinfo), so legitimate text — an egress-policy rejection reason,+ a user's search ``query`` — is unchanged. It deliberately does NOT try+ to catch DSN userinfo (``postgresql://user:pass@``), SQL, schema, or+ filesystem paths; the reliable defence for raw DB errors is the+ curated-constant discipline at the raise sites (#4843), not this+ backstop.++ ``error_code`` / ``status_code`` are a machine-readable contract and+ are passed through untouched. The raw ``self.message`` / ``self.details``+ are not mutated — server-side diagnosis via ``logger.exception`` keeps+ the full text.+ """result = {- "error": self.message,+ "error": sanitize_error_for_client(self.message),"error_code": self.error_code,"status_code": self.status_code,}if self.details:- result["details"] = self.details+ result["details"] = self._sanitize_details(self.details)return resultdiff --git a/tests/news/test_exceptions_behavior.py b/tests/news/test_exceptions_behavior.pyindex 1dce85e997..a5518d489e 100644--- a/tests/news/test_exceptions_behavior.py+++ b/tests/news/test_exceptions_behavior.py@@ -82,6 +82,157 @@ class TestNewsAPIException:assert str(e) == "message here"+class TestToDictMessageSanitization:+ """`to_dict()` runs `message` through the central client sanitizer.++ This is a boundary backstop: the primary defence is curated messages at+ the `news/api.py` raise sites. These tests lock in that the backstop+ scrubs credential-bearing text while leaving legitimate messages — the+ class of content a denylist would have false-positived on — untouched.+ """++ def test_benign_message_passes_through_unchanged(self):+ # An egress-policy rejection reason is legitimate, user-facing text.+ # It must reach the client verbatim (the central sanitizer only+ # redacts credential patterns, so it does not fire here).+ msg = (+ "Failed to create subscription: search engine 'brave' is not "+ "permitted under the current egress policy"+ )+ assert NewsAPIException(msg).to_dict()["error"] == msg++ def test_credential_keyword_in_content_not_scrubbed(self):+ # Plain prose containing "password" is not a credential and must+ # survive — the denylist approach wrongly nuked this.+ msg = "how do I reset my password?"+ assert NewsAPIException(msg).to_dict()["error"] == msg++ def test_bearer_token_redacted(self):+ e = NewsAPIException(+ "auth failed: Authorization: Bearer sk-abc123DEF456ghi789"+ )+ error = e.to_dict()["error"]+ # The load-bearing assertion is that the secret is gone. The redaction+ # sentinel varies (`[REDACTED]` / `[REDACTED_KEY]`), so match on the+ # order-independent substring rather than an exact bracket form.+ assert "sk-abc123DEF456ghi789" not in error+ assert "REDACTED" in error++ def test_api_key_query_param_redacted(self):+ e = NewsAPIException(+ "call failed: ?api_key=AIzaSyD-EXAMPLE_KEY_1234567890abcd"+ )+ error = e.to_dict()["error"]+ assert "AIzaSyD-EXAMPLE_KEY_1234567890abcd" not in error+ assert "REDACTED" in error++ def test_long_message_truncated_to_client_cap(self):+ # sanitize_error_for_client caps the client-facing message at 200 chars.+ # Locks in that to_dict uses the truncating client sanitizer (not the+ # no-cap variant) so an over-long future message can't ship in full.+ msg = "A" * 300+ error = NewsAPIException(msg).to_dict()["error"]+ assert len(error) <= 200+ assert error.endswith("...")++ def test_stored_message_attribute_is_not_mutated(self):+ # Only the serialized output is scrubbed; the raw message stays intact+ # for server-side diagnosis via logger.exception.+ raw = "boom: Authorization: Bearer sk-secret999value000"+ e = NewsAPIException(raw)+ assert e.to_dict()["error"] != raw+ assert e.message == raw++ def test_error_code_and_status_code_untouched(self):+ e = NewsAPIException(+ "Bearer sk-abc123DEF456ghi789",+ status_code=502,+ error_code="UPSTREAM",+ )+ d = e.to_dict()+ assert d["error_code"] == "UPSTREAM"+ assert d["status_code"] == 502++ def test_benign_details_pass_through_unchanged(self):+ # Structured values (IDs, ints) and benign free text in details are+ # not credential shapes, so they survive verbatim.+ e = NewsAPIException(+ "err",+ details={+ "subscription_id": "abc-123",+ "min_limit": 1,+ "query": "how do I reset my password?",+ },+ )+ assert e.to_dict()["details"] == {+ "subscription_id": "abc-123",+ "min_limit": 1,+ "query": "how do I reset my password?",+ }++ def test_credential_in_details_string_leaf_redacted(self):+ # details can carry caller-supplied free text (e.g. the user query at+ # api.py:1071/1134); a credential shape in a string leaf is scrubbed.+ e = NewsAPIException(+ "err",+ details={+ "query": "Authorization: Bearer sk-abc123DEF456ghi789",+ "count": 3,+ },+ )+ d = e.to_dict()["details"]+ assert "sk-abc123DEF456ghi789" not in d["query"]+ assert "REDACTED" in d["query"]+ # Non-string leaves pass through untouched.+ assert d["count"] == 3++ def test_nested_details_are_sanitized_recursively(self):+ e = NewsAPIException(+ "err",+ details={+ "outer": {"inner": ["?api_key=AIzaSyD-EXAMPLE_1234567890"]}+ },+ )+ leaf = e.to_dict()["details"]["outer"]["inner"][0]+ assert "AIzaSyD-EXAMPLE_1234567890" not in leaf+ assert "REDACTED" in leaf++ def test_stored_details_attribute_is_not_mutated(self):+ raw = {"query": "Bearer sk-secret999value000"}+ e = NewsAPIException("err", details=raw)+ assert "REDACTED" in e.to_dict()["details"]["query"]+ assert e.details["query"] == "Bearer sk-secret999value000"++ def test_tuple_detail_normalizes_to_list(self):+ # A tuple leaf serializes to a JSON array anyway; sanitize returns a+ # plain list so identity is irrelevant downstream.+ e = NewsAPIException("err", details={"pair": ("a", "b")})+ assert e.to_dict()["details"]["pair"] == ["a", "b"]++ def test_namedtuple_detail_does_not_crash(self):+ # Regression guard: `type(value)(<generator>)` would raise on a+ # namedtuple (constructor isn't `(iterable) -> instance`), which inside+ # the error handler would degrade a structured error into a bare 500.+ from collections import namedtuple++ Pair = namedtuple("Pair", ["a", "b"])+ e = NewsAPIException(+ "err", details={"pair": Pair("Bearer sk-abc123DEF456ghi789", "x")}+ )+ d = e.to_dict()["details"]["pair"]+ assert d == ["Bearer [REDACTED]", "x"]++ def test_subclass_message_sanitized_via_inherited_to_dict(self):+ # A subclass that interpolates a caller-supplied string still gets the+ # backstop, because to_dict() is inherited.+ e = SubscriptionCreationException(+ "Authorization: Bearer sk-abc123DEF456ghi789"+ )+ error = e.to_dict()["error"]+ assert "sk-abc123DEF456ghi789" not in error+ assert error.startswith("Failed to create subscription:")++# --- Specific exceptions ---