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.

fix(security): stop leaking raw exception text in news, egress & research API responses (CWE-209) (#4843)

LearningCircuitcd450981f9c9
diff --git a/changelog.d/4843.security.md b/changelog.d/4843.security.md
new file mode 100644
index 0000000000..70287aeafb
--- /dev/null
+++ b/changelog.d/4843.security.md
@@ -0,0 +1 @@
+**API error responses no longer leak raw exception text or server config (CWE-209).** Several response paths embedded internal exception detail into messages returned to the client: the `/api/news/*` endpoints (database/SQLAlchemy errors), the start-research and news-subscription egress prechecks (raw `ValueError`s), the research failure handler (unrecognized exceptions *and* LLM/search/provider "configuration error" detail — including server-level endpoints and file paths, since settings can come from `LDR_*` environment overrides) via `/api/research/<id>/status` and the persisted error report, and the benchmark status endpoint (`GET /benchmark/api/status/<id>`, which returned a failed run's raw `str(e)`). All now return generic, category-appropriate messages with an actionable hint where one applies, while the full cause is retained server-side in the logs — hardening shared/multi-user deployments where a non-admin user must not see another tenant's or the server's internal configuration.
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 4e7950e8d5..d1090df4ce 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -26,6 +26,19 @@ from ..graders import extract_answer_from_response, grade_single_result
from ..runners import format_query
from ...database.thread_local_session import thread_cleanup
+# Generic failure message surfaced to API clients in place of the raw benchmark
+# exception. ``benchmark_run.error_message`` is set from ``str(e)`` of the
+# benchmark run (LLM calls, search engines, grading — the same stack as
+# research) and returned by get_benchmark_status() via
+# GET /benchmark/api/status/<id>. The raw text can carry server-level LLM
+# endpoints / hosts / filesystem paths (settings_snapshot includes LDR_* env
+# overrides), so it must not reach the client (CWE-209). Full detail stays in
+# the logger.exception calls at the failure sites.
+_GENERIC_BENCHMARK_ERROR = (
+ "Benchmark run failed due to an internal error. "
+ "Check the server logs for details."
+)
+
class BenchmarkTaskStatus(Enum):
"""Status values for benchmark tasks in the queue tracker."""
@@ -1338,7 +1351,14 @@ class BenchmarkService:
"end_time": benchmark_run.end_time.isoformat()
if benchmark_run.end_time
else None,
- "error_message": benchmark_run.error_message,
+ # Genericized at this boundary (CWE-209) — see
+ # _GENERIC_BENCHMARK_ERROR. Returns None when there is no
+ # failure so non-error states are unaffected.
+ "error_message": (
+ _GENERIC_BENCHMARK_ERROR
+ if benchmark_run.error_message
+ else None
+ ),
# Add all per-dataset accuracies dynamically
**dataset_accuracies,
}
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index a1cbf21a06..08eb572601 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -26,6 +26,13 @@ from ..constants import DEFAULT_SEARCH_TOOL
# Removed welcome feed import - no placeholders
# get_db_setting not available in merged codebase
+# Generic detail surfaced to API clients in place of a raw exception string.
+# These messages are returned to the client via NewsAPIException.to_dict(), so
+# echoing str(e) would leak DB/driver internals (SQL, schema, paths) to callers
+# on shared/multi-user deployments (CWE-209). The real cause is always captured
+# server-side by the adjacent logger.exception(...) for diagnosis.
+_GENERIC_ERROR_DETAIL = "an internal error occurred"
+
def _notify_scheduler_about_subscription_change(
action: str, user_id: Optional[str] = None
@@ -422,7 +429,7 @@ def get_news_feed(
except Exception as db_error:
logger.exception(f"Database error in research history: {db_error}")
raise DatabaseAccessException(
- "research_history_query", str(db_error)
+ "research_history_query", _GENERIC_ERROR_DETAIL
)
# If no news items found, return empty list
@@ -451,9 +458,11 @@ def get_news_feed(
except NewsAPIException:
# Re-raise our custom exceptions
raise
- except Exception as e:
+ except Exception:
logger.exception("Error getting news feed")
- raise NewsFeedGenerationException(str(e), user_id=user_id)
+ raise NewsFeedGenerationException(
+ _GENERIC_ERROR_DETAIL, user_id=user_id
+ )
def get_subscription_history(
@@ -612,9 +621,11 @@ def get_subscription_history(
except NewsAPIException:
# Re-raise our custom exceptions
raise
- except Exception as e:
+ except Exception:
logger.exception("Error getting subscription history")
- raise DatabaseAccessException("get_subscription_history", str(e))
+ raise DatabaseAccessException(
+ "get_subscription_history", _GENERIC_ERROR_DETAIL
+ )
def _format_time_ago(timestamp: str) -> str:
@@ -705,9 +716,9 @@ def get_subscription(subscription_id: str) -> Optional[Dict[str, Any]]:
except NewsAPIException:
# Re-raise our custom exceptions
raise
- except Exception as e:
+ except Exception:
logger.exception(f"Error getting subscription {subscription_id}")
- raise DatabaseAccessException("get_subscription", str(e))
+ raise DatabaseAccessException("get_subscription", _GENERIC_ERROR_DETAIL)
def get_subscriptions(user_id: str) -> Dict[str, Any]:
@@ -779,9 +790,11 @@ def get_subscriptions(user_id: str) -> Dict[str, Any]:
return {"subscriptions": sub_list, "total": len(sub_list)}
- except Exception as e:
+ except Exception:
logger.exception("Error getting subscriptions")
- raise DatabaseAccessException("get_subscriptions", str(e))
+ raise DatabaseAccessException(
+ "get_subscriptions", _GENERIC_ERROR_DETAIL
+ )
def update_subscription(
@@ -918,9 +931,11 @@ def update_subscription(
except NewsAPIException:
# Re-raise our custom exceptions
raise
- except Exception as e:
+ except Exception:
logger.exception("Error updating subscription")
- raise SubscriptionUpdateException(subscription_id, str(e))
+ raise SubscriptionUpdateException(
+ subscription_id, _GENERIC_ERROR_DETAIL
+ )
def _validate_subscription_policy(
@@ -964,12 +979,18 @@ def _validate_subscription_policy(
return f"egress policy refused: {exc.decision.reason}"
except ValueError as exc:
# An incoherent egress config makes context_from_snapshot
- # raise ValueError.
- # Surface it as a validation failure at subscription create/update
- # time instead of letting the outer except silently skip the
- # check — otherwise the subscription persists and only fails at
- # execution time.
- return f"egress policy is misconfigured: {exc}"
+ # raise ValueError. Surface it as a validation failure at
+ # subscription create/update time instead of letting the outer
+ # except silently skip the check — otherwise the subscription
+ # persists and only fails at execution time. Do not echo the raw
+ # ValueError to the client (CWE-209): it can carry policy-config
+ # internals; log it server-side instead. Mirrors the same fix in
+ # web/routes/research_routes.py's start-research precheck.
+ logger.bind(policy_audit=True).warning(
+ "Subscription egress policy misconfigured",
+ reason=str(exc),
+ )
+ return "egress policy is misconfigured"
if search_engine:
decision = evaluate_engine(
@@ -1108,10 +1129,11 @@ def create_subscription(
# Already a structured creation error (e.g. the N14 policy
# rejection) — propagate as-is instead of re-wrapping.
raise
- except Exception as e:
+ except Exception:
logger.exception("Error creating subscription")
raise SubscriptionCreationException(
- str(e), {"query": query, "type": subscription_type}
+ _GENERIC_ERROR_DETAIL,
+ {"query": query, "type": subscription_type},
)
@@ -1147,9 +1169,11 @@ def delete_subscription(subscription_id: str) -> Dict[str, Any]:
except NewsAPIException:
# Re-raise our custom exceptions
raise
- except Exception as e:
+ except Exception:
logger.exception("Error deleting subscription")
- raise SubscriptionDeletionException(subscription_id, str(e))
+ raise SubscriptionDeletionException(
+ subscription_id, _GENERIC_ERROR_DETAIL
+ )
def get_votes_for_cards(card_ids: list, user_id: str) -> Dict[str, Any]:
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 69b7056179..5b066174af 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -281,11 +281,18 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
"POST /api/start_research policy precheck rejected",
reason=str(exc),
)
+ # Return a generic reason to the client — the raw ValueError text
+ # can carry policy-config internals and is already captured in the
+ # policy_audit warning above (CWE-209). Unlike the PolicyDeniedError
+ # branch, this path has no curated, user-safe decision reason.
return (
jsonify(
{
"status": "error",
- "message": (f"Egress policy refused this run: {exc}"),
+ "message": (
+ "Egress policy refused this run due to an "
+ "invalid policy configuration."
+ ),
}
),
400,
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 032c877841..1abc59015a 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -2383,54 +2383,105 @@ def run_research_process(research_id, query, mode, **kwargs):
"solution": "Ensure Ollama or your API service is running and accessible."
}
elif "Error type: api_error" in user_friendly_error:
- # Keep the original error message as it's already improved
+ user_friendly_error = (
+ "The language model API rejected the request."
+ )
error_context = {
"solution": "Check API configuration and credentials."
}
# OpenAI-compatible runtime tokens (#3878). The friendly message
- # built by friendly_openai_compatible_error() already names the
- # provider, base URL, and model -- keep it as-is.
+ # built by friendly_openai_compatible_error() names the provider,
+ # base URL and model and appends the raw provider error (only
+ # credential-scrubbed). The base URL can be a server-level endpoint
+ # (settings_snapshot bakes in LDR_* env overrides) and the appended
+ # detail can carry internal hosts/paths, so it must not reach the
+ # client (CWE-209). Replace it with a safe category message; full
+ # detail stays in the logs above and the actionable hint is in
+ # ``solution``.
elif "Error type: openai_connection_refused" in user_friendly_error:
+ user_friendly_error = (
+ "Could not connect to the configured LLM server."
+ )
error_context = {
"solution": "Start your LLM server (LM Studio / vLLM / llama.cpp server) and verify the base URL in Settings -> LLM Providers."
}
elif "Error type: openai_timeout" in user_friendly_error:
+ user_friendly_error = "The configured LLM server timed out."
error_context = {
"solution": "The server is reachable but slow -- it may be loading a model. Retry, or increase the request timeout."
}
elif "Error type: openai_auth" in user_friendly_error:
+ user_friendly_error = (
+ "Authentication with the configured LLM provider failed."
+ )
error_context = {
"solution": "Set or correct the API key for this provider in Settings -> LLM Providers. Local servers usually accept any non-empty key."
}
elif "Error type: openai_permission_denied" in user_friendly_error:
+ user_friendly_error = (
+ "The configured LLM provider denied access to the model."
+ )
error_context = {
"solution": "Your API key is valid but lacks access to this model. Pick a model your account/server is permitted to use."
}
elif "Error type: openai_model_not_found" in user_friendly_error:
+ user_friendly_error = (
+ "The configured model was not found on the LLM server."
+ )
error_context = {
"solution": "The model id is not loaded on this server. Pick a currently-loaded model in the provider's UI/config."
}
elif "Error type: openai_bad_request" in user_friendly_error:
+ user_friendly_error = "The LLM server rejected the request."
error_context = {
"solution": "The server rejected the request. Check the model id and any provider-specific parameters."
}
elif "Error type: openai_unknown" in user_friendly_error:
+ user_friendly_error = (
+ "The configured LLM provider returned an error."
+ )
error_context = {
"solution": "Check the provider's logs for the full error and verify the base URL / model id."
}
elif "Error type: openai_rate_limit" in user_friendly_error:
+ user_friendly_error = (
+ "The LLM provider rate-limited the request."
+ )
error_context = {
"solution": "The provider rate-limited the request. Wait a moment and retry, or enable LLM Rate Limiting in Settings."
}
elif "LLM Configuration Error:" in user_friendly_error:
- # Surface the raw config detail to the operator (which model
- # path / .gguf / endpoint is misconfigured) rather than hiding
- # it behind a generic message: this is a self-hosted tool, so
- # the operator needs the specifics to fix their own setup.
- # Keep ``user_friendly_error`` as-is and just attach a hint.
+ # The raw text here is str(e) from LLM setup and can carry
+ # server-level endpoints/paths (settings_snapshot includes
+ # LDR_* env overrides), so it must not be surfaced to the client
+ # (CWE-209) -- it is captured in the logs above. Keep only the
+ # safe category + actionable hint.
+ user_friendly_error = (
+ "There was a problem with the LLM configuration."
+ )
+ error_context = {
+ "solution": "Review your LLM model settings (or, on a shared server, contact your administrator) and ensure they are correct."
+ }
+ elif "Search Engine Configuration Error" in user_friendly_error:
+ # Same rationale as the LLM config branch above.
+ user_friendly_error = (
+ "There was a problem with the search engine configuration."
+ )
error_context = {
- "solution": "Review your LLM model settings and ensure they are correct."
+ "solution": "Review your search engine settings (or, on a shared server, contact your administrator) and ensure they are correct."
}
+ else:
+ # Unrecognized exception. The raw str(e) here is server-side
+ # internal detail (file paths, DB/driver text, Python tracebacks)
+ # with no curated, user-actionable form, so it must not be
+ # surfaced to the client (CWE-209) — it is already captured by
+ # the logger.exception above. The branches above classify known
+ # errors and replace the message with a safe category string +
+ # hint; this branch handles everything that wasn't classified.
+ user_friendly_error = (
+ "Research failed due to an unexpected error. Contact your "
+ "administrator or check the server logs for details."
+ )
# Generate enhanced error report for failed research
enhanced_report_content = None
@@ -2445,7 +2496,12 @@ def run_research_process(research_id, query, mode, **kwargs):
# ErrorReportGenerator does not use LLM (kept for compat)
error_generator = ErrorReportGenerator()
enhanced_report_content = error_generator.generate_error_report(
- error_message=f"Research failed: {e!s}",
+ # Use the sanitized user_friendly_error (curated for known
+ # errors, generic for unexpected ones) instead of raw {e!s}:
+ # this report is persisted and retrievable via the report
+ # routes, so embedding raw exception text would leak server
+ # internals (CWE-209). Full detail stays in the logs.
+ error_message=f"Research failed: {user_friendly_error}",
query=query,
partial_results=partial_results,
search_iterations=search_iterations,
diff --git a/tests/benchmarks/test_benchmark_service.py b/tests/benchmarks/test_benchmark_service.py
index 4aafa13171..d5750a8e2c 100644
--- a/tests/benchmarks/test_benchmark_service.py
+++ b/tests/benchmarks/test_benchmark_service.py
@@ -1186,6 +1186,54 @@ class TestBenchmarkServiceGetBenchmarkStatus:
params = list(sig.parameters.keys())
assert "benchmark_run_id" in params
+ def test_get_benchmark_status_does_not_leak_raw_error(self):
+ """A failed run's raw error_message (which can carry server-level LLM
+ endpoints / filesystem paths) must NOT be returned by
+ get_benchmark_status — it is replaced with a generic message (CWE-209).
+ """
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ BenchmarkStatus,
+ _GENERIC_BENCHMARK_ERROR,
+ )
+
+ secret = "Connection refused to http://internal-llm:8000/v1 /srv/secret"
+ mock_run = Mock()
+ mock_run.id = 1
+ mock_run.run_name = "run"
+ mock_run.status = BenchmarkStatus.FAILED
+ mock_run.completed_examples = 0
+ mock_run.total_examples = 10
+ mock_run.failed_examples = 1
+ mock_run.overall_accuracy = None
+ mock_run.processing_rate = None
+ mock_run.created_at = None
+ mock_run.start_time = None # skips the timing-calculation block
+ mock_run.end_time = None
+ mock_run.error_message = secret
+
+ service = BenchmarkService(socket_service=Mock())
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = Mock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+ mock_get_session.return_value = mock_session
+
+ q = mock_session.query.return_value
+ q.filter.return_value.first.return_value = mock_run
+ q.filter.return_value.all.return_value = []
+ q.filter.return_value.filter.return_value.all.return_value = []
+
+ result = service.get_benchmark_status(1)
+
+ assert result is not None
+ assert result["error_message"] == _GENERIC_BENCHMARK_ERROR
+ assert secret not in str(result)
+ assert "internal-llm" not in str(result)
+
class TestBenchmarkServiceTaskQueue:
"""Tests for task queue creation."""
diff --git a/tests/news/test_api_exceptions.py b/tests/news/test_api_exceptions.py
index 2b1c3918c3..78d4ba207e 100644
--- a/tests/news/test_api_exceptions.py
+++ b/tests/news/test_api_exceptions.py
@@ -43,7 +43,11 @@ class TestGetNewsFeedExceptions:
assert exc_info.value.status_code == 500
assert "research_history_query" in exc_info.value.details["operation"]
- assert "Connection failed" in exc_info.value.message
+ # Raw exception text must NOT reach the client-facing message/response
+ # (CWE-209) — it is logged server-side instead. See _GENERIC_ERROR_DETAIL.
+ assert "Connection failed" not in exc_info.value.message
+ assert "Connection failed" not in exc_info.value.to_dict()["error"]
+ assert "an internal error occurred" in exc_info.value.message
class TestSubscriptionExceptions:
@@ -110,7 +114,10 @@ class TestSubscriptionExceptions:
)
assert exc_info.value.status_code == 500
- assert "Constraint violation" in exc_info.value.message
+ # Raw exception text must NOT reach the client-facing message (CWE-209).
+ assert "Constraint violation" not in exc_info.value.message
+ assert "Constraint violation" not in exc_info.value.to_dict()["error"]
+ assert "an internal error occurred" in exc_info.value.message
assert exc_info.value.details["query"] == "test query"
@@ -165,4 +172,7 @@ class TestSubscriptionHistoryExceptions:
news_api.get_subscription_history("sub-123")
assert "get_subscription_history" in exc_info.value.details["operation"]
- assert "Query timeout" in exc_info.value.message
+ # Raw exception text must NOT reach the client-facing message (CWE-209).
+ assert "Query timeout" not in exc_info.value.message
+ assert "Query timeout" not in exc_info.value.to_dict()["error"]
+ assert "an internal error occurred" in exc_info.value.message
diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.py
index 806c6e3ddc..29c410759f 100644
--- a/tests/web/routes/test_research_routes_policy.py
+++ b/tests/web/routes/test_research_routes_policy.py
@@ -102,6 +102,9 @@ class TestPrecheckEnginePolicy:
result = _precheck_engine_policy(mgr, {}, "arxiv", "user")
assert result is not None
assert result[1] == 400
+ # This hits the PolicyDeniedError branch, which surfaces the curated
+ # decision.reason code (safe), not raw exception text.
+ assert "garbage" not in result[0].get_json()["message"]
def test_non_dict_snapshot_returns_none(self, app_ctx):
# No real snapshot => skip precheck (factory PEP backstops).
@@ -116,6 +119,14 @@ class TestPrecheckEnginePolicy:
result = _precheck_engine_policy(mgr, {}, "arxiv", "user")
assert result is not None
assert result[1] == 400
+ body = result[0].get_json()
+ assert (
+ body["message"]
+ == "Egress policy refused this run due to an invalid policy configuration."
+ )
+ # Raw resolver detail (e.g. "no primary search engine configured ...")
+ # must not reach the client.
+ assert "search engine configured" not in body["message"]
def test_per_research_override_tightens_scope(self, app_ctx):
# Saved scope is permissive (both) but the form overrides to
diff --git a/tests/web/services/test_research_service_coverage_gaps.py b/tests/web/services/test_research_service_coverage_gaps.py
index 3d40aceafe..1bf1fe51ce 100644
--- a/tests/web/services/test_research_service_coverage_gaps.py
+++ b/tests/web/services/test_research_service_coverage_gaps.py
@@ -405,38 +405,46 @@ class TestLLMConfigErrorRaisesValueError:
return mock_qp
def test_llamacpp_keyword_triggers_config_error(self):
- """'llamacpp' in error message triggers ValueError with config prefix."""
+ """'llamacpp' is classified as an LLM config problem, but the raw
+ exception text must not reach the client (CWE-209)."""
mock_qp = self._run_with_llm_error("llamacpp model failed to load")
# Error is caught by outer handler and queued
mock_qp.queue_error_update.assert_called_once()
- call_kwargs = mock_qp.queue_error_update.call_args
- assert "LLM Configuration Error" in str(call_kwargs)
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ # Classified as an LLM config problem -> safe generic message...
+ assert "There was a problem with the LLM configuration" in call_kwargs
+ # ...with the raw exception detail stripped (it can carry server paths).
+ assert "llamacpp model failed to load" not in call_kwargs
def test_model_path_keyword_triggers_config_error(self):
- """'model path' in error message triggers ValueError with config prefix."""
+ """'model path' -> LLM config category; raw path not leaked."""
mock_qp = self._run_with_llm_error("model path /foo/bar does not exist")
mock_qp.queue_error_update.assert_called_once()
- assert "LLM Configuration Error" in str(
- mock_qp.queue_error_update.call_args
- )
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ assert "There was a problem with the LLM configuration" in call_kwargs
+ assert "/foo/bar" not in call_kwargs
def test_gguf_keyword_triggers_config_error(self):
- """'.gguf' in error message triggers ValueError with config prefix."""
+ """'.gguf' -> LLM config category; raw detail not leaked."""
mock_qp = self._run_with_llm_error("please provide a valid .gguf file")
mock_qp.queue_error_update.assert_called_once()
- assert "LLM Configuration Error" in str(
- mock_qp.queue_error_update.call_args
- )
-
- def test_non_config_llm_error_re_raises_directly(self):
- """Errors without config keywords are re-raised as-is (not wrapped)."""
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ assert "There was a problem with the LLM configuration" in call_kwargs
+ assert "please provide a valid .gguf file" not in call_kwargs
+
+ def test_non_config_llm_error_is_genericized(self):
+ """An unrecognized LLM error (no config keyword) reaches the central
+ handler's `else` branch: the raw exception text must NOT reach the
+ client (CWE-209) — only the generic 'unexpected error' message."""
mock_qp = self._run_with_llm_error(
- "unexpected null pointer in inference"
+ "unexpected null pointer in inference at 0xdeadbeef"
)
mock_qp.queue_error_update.assert_called_once()
- # Should NOT contain "LLM Configuration Error" prefix
error_str = str(mock_qp.queue_error_update.call_args)
assert "LLM Configuration Error" not in error_str
+ # The genuine fix: the raw exception text is genericized.
+ assert "null pointer in inference" not in error_str
+ assert "unexpected error" in error_str.lower()
# ---------------------------------------------------------------------------
@@ -479,39 +487,53 @@ class TestSearchEngineConfigError:
return mock_qp
def test_searxng_keyword_triggers_config_error(self):
- """'searxng' in error message triggers Search Engine Configuration Error."""
+ """'searxng' -> search config category; raw detail not leaked (CWE-209)."""
mock_qp = self._run_with_search_error("SearXNG instance unreachable")
mock_qp.queue_error_update.assert_called_once()
- assert "Search Engine Configuration Error" in str(
- mock_qp.queue_error_update.call_args
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ assert (
+ "There was a problem with the search engine configuration"
+ in call_kwargs
)
+ assert "instance unreachable" not in call_kwargs
def test_api_key_keyword_triggers_config_error(self):
- """'api_key' in error message triggers Search Engine Configuration Error."""
+ """'api_key' -> search config category; raw detail not leaked."""
mock_qp = self._run_with_search_error(
"Missing api_key for search provider"
)
mock_qp.queue_error_update.assert_called_once()
- assert "Search Engine Configuration Error" in str(
- mock_qp.queue_error_update.call_args
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ assert (
+ "There was a problem with the search engine configuration"
+ in call_kwargs
)
+ assert "Missing api_key for search provider" not in call_kwargs
def test_connection_keyword_triggers_config_error(self):
- """'connection' in error message triggers Search Engine Configuration Error."""
+ """'connection' -> search config category; raw detail not leaked."""
mock_qp = self._run_with_search_error(
"Connection refused by search backend"
)
mock_qp.queue_error_update.assert_called_once()
- assert "Search Engine Configuration Error" in str(
- mock_qp.queue_error_update.call_args
+ call_kwargs = str(mock_qp.queue_error_update.call_args)
+ assert (
+ "There was a problem with the search engine configuration"
+ in call_kwargs
)
+ assert "Connection refused by search backend" not in call_kwargs
- def test_non_config_search_error_re_raises(self):
- """Errors without config keywords are re-raised as-is."""
- mock_qp = self._run_with_search_error("some random internal crash")
+ def test_non_config_search_error_is_genericized(self):
+ """An unrecognized search error reaches the `else` branch: raw text
+ must NOT reach the client (CWE-209)."""
+ mock_qp = self._run_with_search_error(
+ "some random internal crash at /srv/internal"
+ )
mock_qp.queue_error_update.assert_called_once()
error_str = str(mock_qp.queue_error_update.call_args)
assert "Search Engine Configuration Error" not in error_str
+ assert "/srv/internal" not in error_str
+ assert "unexpected error" in error_str.lower()
# ---------------------------------------------------------------------------
@@ -584,13 +606,19 @@ class TestSearchErrorClassification:
assert "ollama pull" in call_kwargs["metadata"]["solution"]
def test_other_status_code_classified_as_api_error(self):
- """Other HTTP status codes are classified as api_error by lines 715-719,
- then matched by 'Error type: api_error' in the outer handler (line 1484)."""
+ """Other HTTP status codes are classified as api_error; the client
+ message is genericized and must not carry the raw status-line tail
+ (CWE-209), while the solution hint is preserved."""
mock_qp = self._run_with_analyze_error(
- "Request failed with status code: 429"
+ "Request failed with status code: 429 LEAKED-INTERNAL-DETAIL"
)
mock_qp.queue_error_update.assert_called_once()
call_kwargs = mock_qp.queue_error_update.call_args[1]
+ assert (
+ call_kwargs["error_message"]
+ == "The language model API rejected the request."
+ )
+ assert "LEAKED-INTERNAL-DETAIL" not in str(call_kwargs)
assert "solution" in call_kwargs["metadata"]
assert "API" in call_kwargs["metadata"]["solution"]
@@ -605,15 +633,19 @@ class TestSearchErrorClassification:
assert "Connection error" in call_kwargs["error_message"]
assert "solution" in call_kwargs["metadata"]
- def test_unknown_error_preserves_original_message(self):
- """Errors without known patterns keep error_type=unknown in the re-raised
- exception, and the outer handler does not match any rewrite pattern."""
+ def test_unknown_error_is_genericized(self):
+ """Errors without known patterns keep error_type=unknown and match no
+ rewrite tier, so they reach the central handler's `else` branch: the raw
+ text must be genericized (CWE-209) and no solution hint is added."""
mock_qp = self._run_with_analyze_error(
- "something completely unexpected happened"
+ "something completely unexpected at /srv/secret happened"
)
mock_qp.queue_error_update.assert_called_once()
call_kwargs = mock_qp.queue_error_update.call_args[1]
- # No solution context is added for unknown errors
+ # The raw text is not surfaced; a generic message is used instead.
+ assert "/srv/secret" not in str(call_kwargs)
+ assert "unexpected error" in call_kwargs["error_message"].lower()
+ # No solution context is added for unrecognized errors
assert "solution" not in call_kwargs["metadata"]
@@ -817,3 +849,65 @@ class TestCancelResearchOuterException:
assert result is True
mock_handle.assert_called_once_with(10, "user1")
+
+
+# ---------------------------------------------------------------------------
+# CWE-209: the persisted error REPORT must not embed raw exception text
+# ---------------------------------------------------------------------------
+
+
+class TestUnexpectedFailureDoesNotLeakRawException:
+ """The enhanced error report is persisted and retrievable via the report
+ routes, so its error_message must be the sanitized user_friendly_error, not
+ raw str(e) (CWE-209). This guards the report sink specifically (the
+ queue/status surface is guarded by the TestLLMConfigError /
+ TestSearchEngineConfigError ``_is_genericized`` cases)."""
+
+ def test_unexpected_exception_text_is_not_in_error_report(self):
+ # Keyword-free so it is NOT classified as a config/known error and
+ # reaches the central handler's generic `else` branch.
+ secret = "ZZSECRETZZ /opt/internal raw traceback frame 0xdeadbeef"
+
+ captured = {}
+
+ def _capture_report(*args, **kwargs):
+ captured["error_message"] = kwargs.get("error_message", "")
+ return "error report"
+
+ mock_generator = MagicMock()
+ mock_generator.generate_error_report.side_effect = _capture_report
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.ErrorReportGenerator"] = MagicMock(
+ return_value=mock_generator
+ )
+ # search.tool in the snapshot gets the run past the egress precheck so
+ # the secret-bearing exception actually reaches the failure handler.
+ patches[f"{MODULE}.get_search"] = MagicMock(
+ side_effect=Exception(secret)
+ )
+
+ func = _get_raw_run_research_process()
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test query",
+ "quick",
+ username="testuser",
+ search_engine="searxng",
+ settings_snapshot={"search.tool": "searxng"},
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ assert "error_message" in captured, (
+ "error report was not generated; the except handler was not reached"
+ )
+ assert secret not in captured["error_message"]
+ assert "unexpected error" in captured["error_message"].lower()