~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): extract sanitize_error_message to standalone function + strengthen patterns (#4466)
LearningCircuit784864fd31a3
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex dc0298eae4..0785f11762 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -6,6 +6,7 @@ from langchain_core.messages import AIMessagefrom loguru import loggerfrom ..llm import get_llm_from_registry, is_llm_registered+from ..security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ..utilities.search_utilities import remove_think_tags# Import providers module to trigger auto-discovery. get_llm() has no@@ -473,6 +474,12 @@ def get_llm()+def _log_llm_error(error: Exception) -> None:+ """Log an LLM call failure with credential redaction."""+ safe_msg = redact_secrets(sanitize_error_message(str(error)))+ logger.warning(f"LLM Request - Failed with error: {safe_msg}")++def wrap_llm_without_think_tags(llm,research_id=None,@@ -556,13 +563,7 @@ def wrap_llm_without_think_tags(@staticmethoddef _log_llm_error(error: Exception) -> None:- """Log an LLM call failure, surfacing any URL embedded in the error."""- logger.exception("LLM Request - Failed with error")- error_str = str(error)- if "http://" in error_str or "https://" in error_str:- logger.exception(- f"LLM Request - Error contains URL info: {error_str}"- )+ _log_llm_error(error)def invoke(self, *args: Any, **kwargs: Any) -> Any:try:diff --git a/src/local_deep_research/error_handling/openai_compat_errors.py b/src/local_deep_research/error_handling/openai_compat_errors.pyindex 8108383c80..3ad497f63f 100644--- a/src/local_deep_research/error_handling/openai_compat_errors.py+++ b/src/local_deep_research/error_handling/openai_compat_errors.py@@ -20,6 +20,8 @@ from urllib.parse import urlparse, urlunparseimport httpximport openai+from ..security.log_sanitizer import sanitize_error_message+def _strip_credentials(base_url: str | None) -> str:"""Return ``base_url`` with any userinfo (``user:password@``) removed.@@ -201,4 +203,4 @@ def friendly_openai_compatible_error(provider_repr = provider or "<unknown provider>"root = _walk_cause(exc)code, friendly = _dispatch(root, provider_repr, redacted, model_repr)- return f"{friendly} (Error type: {code}) | Details: {exc!s}"+ return f"{friendly} (Error type: {code}) | Details: {sanitize_error_message(str(exc))}"diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex d0440e8e64..24dbcc353c 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -29,6 +29,7 @@ from .account_lockout import AccountLockoutManager, get_account_lockout_managerfrom .password_validator import PasswordValidatorfrom .log_sanitizer import (redact_secrets,+ sanitize_error_message,sanitize_for_log,strip_control_chars,)@@ -91,6 +92,7 @@ __all__ = ["get_account_lockout_manager","PasswordValidator","redact_secrets",+ "sanitize_error_message","sanitize_for_log","strip_control_chars","sanitize_filename",diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex cb7dcbf5fd..6bd61091db 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -122,3 +122,53 @@ def redact_secrets(for secret in ordered:message = message.replace(secret, replacement)return message+++# Pre-compiled regex patterns for common credential formats found in HTTP+# library exception messages. Used by sanitize_error_message().+#+# Order matters: the URL-credentials pattern must run BEFORE the URL-param+# pattern. Otherwise an input like ``?api-key=https://user:pass@host`` gets+# its ``https`` consumed by the param replacement, the credentials pattern+# no longer matches, and ``user:pass`` leaks.+_CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [+ # Bearer tokens+ (re.compile(r"Bearer\s+[A-Za-z0-9\-._~+/]+=*"), "Bearer [REDACTED]"),+ # URL credentials (user:pass@host)+ (+ re.compile(r"(https?://)([^:\s]+):([^@\s]+)@"),+ r"\1[REDACTED]:[REDACTED]@",+ ),+ # API keys in URL query strings (?key=..., &api_key=..., etc.)+ (+ re.compile(+ r"([?&])(api_key|apikey|api-key|key|token|secret)=([A-Za-z0-9\-._~+/]+)"+ ),+ r"\1\2=[REDACTED]",+ ),+ # Common API key prefixes (sk-*, pk-*) — includes hyphens for modern+ # formats like sk-proj-... and sk-ant-api03-...+ (re.compile(r"\b(sk-[A-Za-z0-9\-]{20,})\b"), "[REDACTED_KEY]"),+ (re.compile(r"\b(pk-[A-Za-z0-9\-]{20,})\b"), "[REDACTED_KEY]"),+]+++def sanitize_error_message(message: str) -> str:+ """Remove or mask API keys, tokens, and secrets from *message* using+ pattern matching for common credential formats.++ Use this as a first scrub pass on exception messages before logging,+ followed by :func:`redact_secrets` with known literal values (the+ "dual-scrub" pattern).++ Handles:+ * Bearer tokens (``Bearer sk-...``)+ * URL query parameters (``?api_key=...``, ``?key=...``, ``?api-key=...``)+ * URL-embedded credentials (``https://user:pass@host``)+ * Well-known key prefixes (``sk-...``, ``pk-...``)+ """+ if not message:+ return message+ for pattern, replacement in _CREDENTIAL_PATTERNS:+ message = pattern.sub(replacement, message)+ return messagediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.pyindex 46d87f35de..cd104d4eee 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py@@ -4,6 +4,7 @@ from langchain_community.tools import BraveSearchfrom langchain_core.language_models import BaseLLMfrom loguru import logger+from ...security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ..rate_limiting import RateLimitErrorfrom ..search_engine_base import BaseSearchEngine@@ -70,6 +71,7 @@ class BraveSearchEngine(BaseSearchEngine):engine_name="Brave Search",settings_snapshot=settings_snapshot,)+ self._brave_api_key = brave_api_key# Get language codelanguage_code = language_code_mapping.get(search_language.lower(), "en")@@ -126,9 +128,13 @@ class BraveSearchEngine(BaseSearchEngine):import jsonraw_results = json.loads(raw_results)- except json.JSONDecodeError:- logger.exception(- "Error: Unable to parse BraveSearch response as JSON."+ except json.JSONDecodeError as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_brave_api_key", None),+ )+ logger.warning(+ f"Unable to parse BraveSearch response as JSON: {safe_msg}")return []@@ -157,6 +163,10 @@ class BraveSearchEngine(BaseSearchEngine):except RateLimitError:raiseexcept Exception as e:- logger.exception("Error getting Brave Search results")+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_brave_api_key", None),+ )+ logger.warning(f"Error getting Brave Search results: {safe_msg}")self._raise_if_rate_limit(e)return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.pyindex 31b0750a14..58927f9e2b 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py@@ -6,6 +6,7 @@ from langchain_core.language_models import BaseLLMfrom ...config import search_configfrom ...constants import SNIPPET_LENGTH_SHORT+from ...security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ..search_engine_base import BaseSearchEnginefrom ...constants import DEFAULT_SEARCH_TOOL@@ -117,6 +118,10 @@ class ElasticsearchSearchEngine(BaseSearchEngine):)self.filter_query = filter_query or {}+ # Store credentials for error-message redaction+ self._api_key = api_key+ self._password = password+# Normalize hosts – may arrive as a JSON-encoded string from settingshosts = self._ensure_list(hosts, default=["http://localhost:9200"])@@ -167,8 +172,15 @@ class ElasticsearchSearchEngine(BaseSearchEngine):f"Elasticsearch version: {info.get('version', {}).get('number')}")except Exception as e:- logger.exception("Failed to connect to Elasticsearch")- raise ConnectionError(f"Could not connect to Elasticsearch: {e!s}")+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ api_key,+ password,+ )+ logger.warning(f"Failed to connect to Elasticsearch: {safe_msg}")+ raise ConnectionError(+ f"Could not connect to Elasticsearch: {safe_msg}"+ ) from Nonedef close(self) -> None:"""Close the Elasticsearch client and its connection pool."""@@ -269,8 +281,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):)return previews- except Exception:- logger.exception("Error getting Elasticsearch previews")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_api_key", None),+ getattr(self, "_password", None),+ )+ logger.warning(f"Error getting Elasticsearch previews: {safe_msg}")return []def _get_full_content(@@ -329,9 +346,14 @@ class ElasticsearchSearchEngine(BaseSearchEngine):if key not in result and key not in ["content"]:result[key] = value- except Exception:- logger.exception(- f"Error fetching full content for document {doc_id}"+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_api_key", None),+ getattr(self, "_password", None),+ )+ logger.warning(+ f"Error fetching full content for document {doc_id}: {safe_msg}")# Keep the preview data if we can't get the full content@@ -376,8 +398,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):previews = self._process_es_response(response)return self._get_full_content(previews)- except Exception:- logger.exception("Error in query_string search")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_api_key", None),+ getattr(self, "_password", None),+ )+ logger.warning(f"Error in query_string search: {safe_msg}")return []def search_by_dsl(self, query_dsl: Dict[str, Any]) -> List[Dict[str, Any]]:@@ -401,8 +428,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):previews = self._process_es_response(response)return self._get_full_content(previews)- except Exception:- logger.exception("Error in DSL search")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "_api_key", None),+ getattr(self, "_password", None),+ )+ logger.warning(f"Error in DSL search: {safe_msg}")return []def _process_es_response(self, response: Any) -> List[Dict[str, Any]]:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.pyindex dbc6a2f117..8a7d54d918 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py@@ -8,7 +8,7 @@ from loguru import loggerfrom ...config import llm_config, search_configfrom ...constants import USER_AGENT-from ...security.log_sanitizer import redact_secrets+from ...security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ...security.safe_requests import safe_getfrom ...utilities.json_utils import extract_json, get_llm_response_textfrom ..search_engine_base import BaseSearchEngine@@ -133,8 +133,12 @@ class GitHubSearchEngine(BaseSearchEngine):if not self.llm:logger.warning("No LLM available for query optimization")return query- except Exception:- logger.exception("Error getting LLM from config")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error getting LLM from config: {safe_msg}")return queryprompt = f"""Transform this GitHub search query into an optimized version for the GitHub search API. Follow these steps:@@ -177,8 +181,11 @@ class GitHubSearchEngine(BaseSearchEngine):logger.warning("LLM returned empty query, using original")return query- except Exception:- logger.exception("Error optimizing query with LLM")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(f"Error optimizing query with LLM: {safe_msg}")return querydef _search_github(self, query: str) -> List[Dict[str, Any]]:@@ -315,8 +322,13 @@ class GitHubSearchEngine(BaseSearchEngine):)return ""- except Exception:- logger.exception(f"Error getting README for {repo_full_name}")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(+ f"Error getting README for {repo_full_name}: {safe_msg}"+ )return ""def _get_recent_issues(@@ -365,8 +377,13 @@ class GitHubSearchEngine(BaseSearchEngine):f"Could not get issues for {repo_full_name}: {response.status_code}")- except Exception:- logger.exception(f"Error getting issues for {repo_full_name}")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(+ f"Error getting issues for {repo_full_name}: {safe_msg}"+ )return issues@@ -407,8 +424,11 @@ class GitHubSearchEngine(BaseSearchEngine):)return ""- except Exception:- logger.exception("Error getting file content")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(f"Error getting file content: {safe_msg}")return ""def _format_repository_preview(@@ -739,8 +759,11 @@ class GitHubSearchEngine(BaseSearchEngine):)return {}- except Exception:- logger.exception("Error getting repository details")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(f"Error getting repository details: {safe_msg}")return {}def search_code(@@ -959,6 +982,9 @@ Do not include any other text or explanation.""")return []- except Exception:- logger.exception("Error filtering GitHub results")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), getattr(self, "api_key", None)+ )+ logger.warning(f"Error filtering GitHub results: {safe_msg}")return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.pyindex 075e611a1c..6031aa9692 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py@@ -155,17 +155,23 @@ class GooglePSESearchEngine(BaseSearchEngine):return Trueexcept Exception as e:- # Log the error and re-raise. Use logger.warning with the- # api_key redacted from str(e) so the upstream exception- # message — which can embed the key in the URL — does not- # leak. The traceback that propagates with `raise` may still- # be logged by a higher-level handler; future work to scrub- # `exc.args` is tracked in the #4131 follow-up issue.- safe_msg = redact_secrets(str(e), self.api_key)+ # Log the error and re-raise a sanitized exception. Use+ # logger.warning with the api_key redacted from str(e) so+ # the upstream exception message — which can embed the key+ # in the URL — does not leak. The re-raised exception uses+ # `type(e)(safe_msg) from None` to preserve the original+ # exception type (for callers that dispatch on it) while+ # replacing the args with the redacted message and+ # suppressing the traceback chain (which carries the URL+ # in earlier frames).+ safe_msg = redact_secrets(+ self._sanitize_error_message(str(e)),+ self.api_key,+ )logger.warning(f"Error validating Google PSE connection: {safe_msg}")- raise+ raise type(e)(safe_msg) from Nonedef _respect_rate_limit(self):"""Ensure we don't exceed rate limits by adding appropriate delay between requests"""diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.pyindex 07aee80b02..820854fd9e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py@@ -5,7 +5,7 @@ from langchain_core.language_models import BaseLLMfrom loguru import loggerfrom ...utilities.search_utilities import remove_think_tags-from ...security.log_sanitizer import redact_secrets+from ...security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ...security.safe_requests import safe_getfrom ..rate_limiting import RateLimitErrorfrom ..search_engine_base import BaseSearchEngine@@ -167,8 +167,12 @@ Return ONLY the extremely brief search query.return optimized_query- except Exception:- logger.exception("Error optimizing query")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error optimizing query: {safe_msg}")return query # Fall back to original query on errordef _adapt_dates_for_query_type(self, query: str) -> None:@@ -240,8 +244,12 @@ ONE WORD ONLY:"""self.from_date = recentself.order_by = "newest" # Prioritize newest for current events- except Exception:- logger.exception("Error adapting dates for query type")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error adapting dates for query type: {safe_msg}")# Keep original date parameters on errordef _adaptive_search(self, query: str) -> Tuple[List[Dict[str, Any]], str]:@@ -617,8 +625,12 @@ ONE WORD ONLY:"""except RateLimitError:raise- except Exception:- logger.exception("Error in Guardian search")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error in Guardian search: {safe_msg}")# Restore original date parameters on errorself.from_date = self._original_date_params["from_date"]diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.pyindex ab20f48e53..ab96b57687 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py@@ -9,7 +9,7 @@ from ...constants import SNIPPET_LENGTH_LONG, USER_AGENTfrom ...advanced_search_system.filters.journal_reputation_filter import (JournalReputationFilter,)-from ...security.log_sanitizer import redact_secrets+from ...security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ...security.safe_requests import safe_getfrom ..rate_limiting import RateLimitErrorfrom ..search_engine_base import BaseSearchEngine@@ -374,9 +374,13 @@ class NasaAdsSearchEngine(BaseSearchEngine):"type": "academic_paper",}- except Exception:- logger.exception(- f"Error formatting NASA ADS document: {doc.get('bibcode', 'unknown')}"+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(+ f"Error formatting NASA ADS document {doc.get('bibcode', 'unknown')}: {safe_msg}")return Nonediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.pyindex 8093c7d091..b0aaecb703 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py@@ -16,6 +16,7 @@ from loguru import loggerfrom ..search_engine_base import BaseSearchEnginefrom ...security import safe_get+from ...security.log_sanitizer import redact_secrets, sanitize_error_messageclass PaperlessSearchEngine(BaseSearchEngine):@@ -171,8 +172,12 @@ class PaperlessSearchEngine(BaseSearchEngine):logger.debug(f"API response keys: {result.keys()}")return result # type: ignore[no-any-return]- except requests.exceptions.RequestException:- logger.exception("Error making request to Paperless-ngx")+ except requests.exceptions.RequestException as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(f"Error making request to Paperless-ngx: {safe_msg}")logger.debug(f"Failed URL: {url}, params: {params}")return {}@@ -231,8 +236,12 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text.""")return expanded- except Exception:- logger.exception("Failed to expand query with LLM")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(f"Failed to expand query with LLM: {safe_msg}")return querydef _multi_pass_search(self, query: str) -> List[Dict[str, Any]]:@@ -370,8 +379,14 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text.""")return previews- except Exception:- logger.exception("Error getting previews from Paperless-ngx")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(+ f"Error getting previews from Paperless-ngx: {safe_msg}"+ )return []def _convert_document_to_preview(@@ -695,8 +710,14 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""item.pop("_raw_data", None)results.append(item)- except Exception:- logger.exception("Error getting full content for document")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(+ f"Error getting full content for document: {safe_msg}"+ )item["full_content"] = item["snippet"]item.pop("_raw_data", None)results.append(item)@@ -755,8 +776,12 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""return results- except Exception:- logger.exception("Error in Paperless-ngx search")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(f"Error in Paperless-ngx search: {safe_msg}")return []async def arun(self, query: str) -> List[Dict[str, Any]]:@@ -777,8 +802,12 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""try:response = self._make_request("/api/")return bool(response)- except Exception:- logger.exception("Failed to connect to Paperless-ngx")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_token", None),+ )+ logger.warning(f"Failed to connect to Paperless-ngx: {safe_msg}")return Falsedef get_document_count(self) -> int:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex 1c298d28cc..6e948ad465 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -789,8 +789,10 @@ The default assumption should be that medical and scientific queries want RECENTexcept Exception as e:error_msg = str(e)- logger.exception(- f"Error getting article summaries for {len(id_list)} articles"+ sanitized = self._sanitize_error_message(error_msg)+ safe_msg = redact_secrets(sanitized, getattr(self, "api_key", None))+ logger.warning(+ f"Error getting article summaries for {len(id_list)} articles: {safe_msg}")# Check for rate limiting patterns@@ -910,9 +912,11 @@ The default assumption should be that medical and scientific queries want RECENT)return abstracts- except Exception:- logger.exception(- f"Error getting article abstracts for {len(id_list)} articles"+ except Exception as e:+ sanitized = self._sanitize_error_message(str(e))+ safe_msg = redact_secrets(sanitized, getattr(self, "api_key", None))+ logger.warning(+ f"Error getting article abstracts for {len(id_list)} articles: {safe_msg}")return {}@@ -1030,8 +1034,12 @@ The default assumption should be that medical and scientific queries want RECENTreturn metadata- except Exception:- logger.exception("Error getting detailed article metadata")+ except Exception as e:+ sanitized = self._sanitize_error_message(str(e))+ safe_msg = redact_secrets(sanitized, getattr(self, "api_key", None))+ logger.warning(+ f"Error getting detailed article metadata: {safe_msg}"+ )return {}def _create_enriched_content(@@ -1210,8 +1218,10 @@ The default assumption should be that medical and scientific queries want RECENT)return pmid_to_pmcid- except Exception:- logger.exception("Error finding PMC IDs")+ except Exception as e:+ sanitized = self._sanitize_error_message(str(e))+ safe_msg = redact_secrets(sanitized, getattr(self, "api_key", None))+ logger.warning(f"Error finding PMC IDs: {safe_msg}")return {}def _get_pmc_full_text(self, pmcid: str) -> str:@@ -1286,8 +1296,10 @@ The default assumption should be that medical and scientific queries want RECENT)return result_text- except Exception:- logger.exception("Error getting PMC full text")+ except Exception as e:+ sanitized = self._sanitize_error_message(str(e))+ safe_msg = redact_secrets(sanitized, getattr(self, "api_key", None))+ logger.warning(f"Error getting PMC full text: {safe_msg}")return ""def _get_previews(self, query: str) -> List[Dict[str, Any]]:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.pyindex 3b31b6a701..e74df02eac 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py@@ -11,7 +11,7 @@ from ...constants import SNIPPET_LENGTH_SHORTfrom ..rate_limiting import RateLimitErrorfrom ..search_engine_base import BaseSearchEnginefrom ...security import SafeSession-from ...security.log_sanitizer import redact_secrets+from ...security.log_sanitizer import redact_secrets, sanitize_error_messageclass SemanticScholarSearchEngine(BaseSearchEngine):@@ -187,8 +187,14 @@ class SemanticScholarSearchEngine(BaseSearchEngine):if hasattr(self, "session") and self.session:try:self.session.close()- except Exception:- logger.exception("Error closing SemanticScholar session")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(+ f"Error closing SemanticScholar session: {safe_msg}"+ )finally:self.session = None# Close content filters (JournalReputationFilter) via parent@@ -316,8 +322,12 @@ Return ONLY the optimized search query with no explanation.logger.info(f"Optimized for search: '{optimized_query}'")return optimized_query- except Exception:- logger.exception("Error optimizing query")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error optimizing query: {safe_msg}")return query # Fall back to original query on errordef _direct_search(self, query: str) -> List[Dict[str, Any]]:@@ -383,8 +393,12 @@ Return ONLY the optimized search query with no explanation.)return []- except Exception:- logger.exception("Error in direct search")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error in direct search: {safe_msg}")return []def _adaptive_search(self, query: str) -> Tuple[List[Dict[str, Any]], str]:@@ -471,8 +485,14 @@ Format each query on a new line with no numbering or explanation. Keep each quer)strategy = "llm_alternative"return alt_papers, strategy- except Exception:- logger.exception("Error using LLM for query refinement")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(+ f"Error using LLM for query refinement: {safe_msg}"+ )# Fall through to simpler strategies# Fallback: Try with the longest words (likely specific terms)@@ -548,8 +568,12 @@ Format each query on a new line with no numbering or explanation. Keep each querreturn self._make_request(url, params)- except Exception:- logger.exception("Error getting paper details for paper")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error getting paper details: {safe_msg}")return {}def _get_previews(self, query: str) -> List[Dict[str, Any]]:@@ -638,8 +662,12 @@ Format each query on a new line with no numbering or explanation. Keep each querpreview["_full_paper"] = paperpreviews.append(preview)- except Exception:- logger.exception("Error processing paper preview")+ except Exception as e:+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ logger.warning(f"Error processing paper preview: {safe_msg}")# Continue with the next paper# Sort by year (newer first) if availablediff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 52a86ec563..f72b47f474 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -1,5 +1,4 @@import json-import reimport timefrom abc import ABC, abstractmethodfrom typing import Any, Dict, List, Optional, Set, Union@@ -18,7 +17,7 @@ from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilterfrom ..config.constants import DEFAULT_MAX_FILTERED_RESULTSfrom ..config.thread_settings import get_setting_from_snapshot-from ..security.log_sanitizer import redact_secrets+from ..security.log_sanitizer import redact_secrets, sanitize_error_messagefrom ..utilities.thread_context import clear_search_context, set_search_contextfrom .rate_limiting import RateLimitError, get_tracker@@ -671,13 +670,19 @@ class BaseSearchEngine(ABC):except Exception as e:# Other errors - don't retrysuccess = False- error_message = str(e)+ # Sanitize error_message before it flows to+ # SearchTracker.record_search (and the database).+ error_message = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )# Use logger.warning with redacted exception text instead of# logger.exception: the cause chain frequently carries the# request URL or auth header from upstream HTTP clients,# which may embed self.api_key (see #4131).safe_msg = redact_secrets(- str(e), getattr(self, "api_key", None)+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),)logger.warning(f"Search engine {self.__class__.__name__} failed: {safe_msg}"@@ -690,16 +695,28 @@ class BaseSearchEngine(ABC):except RetryError as e:# All retries exhaustedsuccess = False- error_message = f"Rate limited after all retries: {e}"- safe_msg = redact_secrets(str(e), getattr(self, "api_key", None))+ error_message = redact_secrets(+ sanitize_error_message(f"Rate limited after all retries: {e}"),+ getattr(self, "api_key", None),+ )+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )logger.warning(f"{self.__class__.__name__} failed after all retries: {safe_msg}")return []except Exception as e:success = False- error_message = str(e)- safe_msg = redact_secrets(str(e), getattr(self, "api_key", None))+ error_message = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )+ safe_msg = redact_secrets(+ sanitize_error_message(str(e)),+ getattr(self, "api_key", None),+ )logger.warning(f"Search engine {self.__class__.__name__} error: {safe_msg}")@@ -1171,34 +1188,12 @@ class BaseSearchEngine(ABC):Sanitized message with sensitive data redactedExample:- >>> engine._sanitize_error_message("Error with key sk-abc123xyz")- "Error with key [REDACTED]"+ >>> engine._sanitize_error_message(+ ... "Error with key sk-abc123def456ghi789jkl012"+ ... )+ "Error with key [REDACTED_KEY]""""- if not message:- return message-- sanitized = message-- # Additional regex patterns for common credential formats- patterns = [- # Bearer tokens- (r"Bearer\s+[A-Za-z0-9\-._~+/]+=*", "Bearer [REDACTED]"),- # API keys in URLs- (- r"([?&])(api_key|apikey|key|token|secret)=([A-Za-z0-9\-._~+/]+)",- r"\1\2=[REDACTED]",- ),- # URL credentials (user:pass@host)- (r"(https?://)([^:\s]+):([^@\s]+)@", r"\1[REDACTED]:[REDACTED]@"),- # Common API key patterns (sk-*, pk-*, etc.)- (r"\b(sk-[A-Za-z0-9]{20,})\b", "[REDACTED_KEY]"),- (r"\b(pk-[A-Za-z0-9]{20,})\b", "[REDACTED_KEY]"),- ]-- for pattern, replacement in patterns:- sanitized = re.sub(pattern, replacement, sanitized)-- return sanitized+ return sanitize_error_message(message)def _mask_api_key(self, api_key: str, visible_chars: int = 4) -> str:"""diff --git a/tests/security/test_credential_leak_followup.py b/tests/security/test_credential_leak_followup.pynew file mode 100644index 0000000000..a84486827d--- /dev/null+++ b/tests/security/test_credential_leak_followup.py@@ -0,0 +1,394 @@+"""Tests for credential leak fixes that address findings from the PR #4452 audit.++Covers:+- PubMed engine: 5 ``logger.exception()`` calls replaced with dual-scrub+- Base class ``run()``: unredacted ``error_message`` persisted to database+- LLM config ``_log_llm_error``: ``logger.exception()`` replaced with ``logger.warning``+- Google PSE ``_validate_connection``: bare re-raise replaced with sanitized exception+- OpenAI compat errors: ``{exc!s}`` replaced with ``sanitize_error_message``+"""++import base64+from unittest.mock import Mock, patch+from urllib.parse import quote, quote_plus++import pytest+import requests+++_LEAKED_KEY = "sk-leaked-sentinel-DO-NOT-APPEAR-12345"+++def _all_encodings_of(secret: str) -> list:+ return [+ secret,+ quote(secret, safe=""),+ quote_plus(secret),+ repr(secret)[1:-1],+ base64.b64encode(secret.encode()).decode(),+ secret[:8],+ ]+++def _stub_rate_tracker() -> Mock:+ tracker = Mock()+ tracker.enabled = False+ tracker.apply_rate_limit.return_value = 0+ return tracker+++# ── PubMed engine tests ──────────────────────────────────────────────+++def _pubmed_engine():+ """Build a minimal PubMedSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_pubmed as mod,+ )++ engine = mod.PubMedSearchEngine.__new__(mod.PubMedSearchEngine)+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.summary_url = (+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"+ )+ engine.fetch_url = (+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"+ )+ engine.link_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi"+ engine.get_full_text = True+ return mod, engine+++ "method_name,url_path,marker",+ [+ (+ "_get_article_summaries",+ "/esummary.fcgi?api_key=",+ "Error getting article summaries",+ ),+ (+ "_get_article_abstracts",+ "/efetch.fcgi?api_key=",+ "Error getting article abstracts",+ ),+ (+ "_get_article_detailed_metadata",+ "/efetch.fcgi?api_key=",+ "Error getting detailed article metadata",+ ),+ (+ "_find_pmc_ids",+ "/elink.fcgi?api_key=",+ "Error finding PMC IDs",+ ),+ (+ "_get_pmc_full_text",+ "/efetch.fcgi?api_key=",+ "Error getting PMC full text",+ ),+ ],+)+class TestPubMedEngineKeyLeakage:+ def test_no_leak_in_catch_block(+ self, loguru_caplog_full, method_name, url_path, marker+ ):+ """Each PubMed method must scrub the API key before logging."""+ mod, engine = _pubmed_engine()++ exc = requests.exceptions.ConnectionError(+ f"HTTPSConnectionPool: Max retries exceeded with url: "+ f"{url_path}{_LEAKED_KEY}&id=12345"+ )++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(mod, "safe_get", side_effect=exc):+ try:+ method = getattr(engine, method_name)+ if method_name == "_get_article_summaries":+ method(["12345"])+ elif method_name == "_find_pmc_ids":+ method(["12345"])+ elif method_name == "_get_pmc_full_text":+ method("PMC12345")+ else:+ method(["12345"])+ except requests.exceptions.RequestException:+ pass++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"{method_name}: api_key leaked as encoding {encoding!r}"+ )++ assert marker in loguru_caplog_full.text, (+ f"{method_name}: catch-block marker {marker!r} not in logs — "+ f"the redaction path may not have run. "+ f"Captured: {loguru_caplog_full.text!r}"+ )+++# ── Base class database persistence tests ────────────────────────────+++class TestBaseClassDatabasePersistence:+ def test_error_message_sanitized_before_db_persist(self, loguru_caplog):+ """The ``error_message`` passed to ``SearchTracker.record_search``+ must be sanitized so credentials don't persist to the database."""+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )+ from local_deep_research.metrics.search_tracker import SearchTracker++ class _TestEngine(BaseSearchEngine):+ engine_type = "test_engine"+ api_key = _LEAKED_KEY++ def _get_previews(self, query, *args, **kwargs):+ raise requests.exceptions.ConnectionError(+ f"HTTPSConnectionPool: url: /search?api_key={_LEAKED_KEY}"+ )++ engine = _TestEngine.__new__(_TestEngine)+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.programmatic_mode = False+ # __init__ always sets this (settings_snapshot or {}); run() and the+ # egress-verification path read it. Bypassing __init__ via __new__+ # omits it, which AttributeErrors only when a sibling test arms the+ # global egress audit net — a parallel-run flake. Set it explicitly.+ engine.settings_snapshot = {}++ captured = {}++ def _capture_record(**kwargs):+ captured["error_message"] = kwargs.get("error_message")++ with loguru_caplog.at_level("DEBUG"):+ with (+ patch.object(+ SearchTracker, "record_search", side_effect=_capture_record+ ),+ patch(+ "local_deep_research.web_search_engines.search_engine_base.set_search_context"+ ),+ ):+ engine.run("test query")++ assert "error_message" in captured, "record_search was never called"+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in captured["error_message"], (+ f"api_key leaked into DB error_message as {encoding!r}: "+ f"{captured['error_message']!r}"+ )++ def test_log_path_sanitizes_foreign_url_credentials(self, loguru_caplog):+ """The logged ``safe_msg`` in run() must run the regex sanitizer,+ not just literal redaction.++ Regression guard: a *foreign* credential (not the engine's own+ api_key) embedded as ``https://user:pass@host`` is only caught by+ sanitize_error_message's regex, not by redact_secrets(literal). The+ log path previously used redact_secrets alone, so it leaked into the+ log even though the DB path was dual-scrubbed.+ """+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )+ from local_deep_research.metrics.search_tracker import SearchTracker++ foreign_secret = "hunter2-foreign-pw-DO-NOT-APPEAR"++ class _TestEngine(BaseSearchEngine):+ engine_type = "test_engine"+ api_key = "the-engines-own-key-unrelated"++ def _get_previews(self, query, *args, **kwargs):+ raise requests.exceptions.ConnectionError(+ f"connect failed: https://admin:{foreign_secret}@es.local/_search"+ )++ engine = _TestEngine.__new__(_TestEngine)+ engine.api_key = "the-engines-own-key-unrelated"+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.programmatic_mode = False+ engine.settings_snapshot = {}++ with loguru_caplog.at_level("DEBUG"):+ with (+ patch.object(SearchTracker, "record_search"),+ patch(+ "local_deep_research.web_search_engines.search_engine_base.set_search_context"+ ),+ ):+ engine.run("test query")++ assert foreign_secret not in loguru_caplog.text, (+ f"foreign URL credential leaked into log: {loguru_caplog.text!r}"+ )+++# ── LLM config _log_llm_error tests ─────────────────────────────────+++class TestLLMConfigLogError:+ def test_no_leak_with_url_in_exception(self, loguru_caplog_full):+ """``_log_llm_error`` must not leak credentials from the exception."""+ from local_deep_research.config.llm_config import _log_llm_error++ exc = RuntimeError(+ f"Connection to https://api.openai.com/v1?key={_LEAKED_KEY} failed"+ )++ with loguru_caplog_full.at_level("DEBUG"):+ _log_llm_error(exc)++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"_log_llm_error leaked key as {encoding!r}"+ )++ def test_uses_warning_not_exception(self, loguru_caplog):+ """``_log_llm_error`` should use ``logger.warning``, not+ ``logger.exception``, to avoid writing the traceback chain."""+ from local_deep_research.config.llm_config import _log_llm_error++ exc = RuntimeError("test error")++ with loguru_caplog.at_level("DEBUG"):+ _log_llm_error(exc)++ assert "LLM Request - Failed with error" in loguru_caplog.text+ assert "Traceback" not in loguru_caplog.text+++# ── Google PSE _validate_connection tests ────────────────────────────+++class TestGooglePSEValidateConnection:+ def test_rethrown_exception_is_sanitized(self):+ """The re-thrown exception from ``_validate_connection`` must not+ contain the API key in its string representation."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_google_pse as mod,+ )++ engine = mod.GooglePSESearchEngine.__new__(mod.GooglePSESearchEngine)+ engine.api_key = _LEAKED_KEY++ exc = requests.exceptions.ConnectionError(+ f"HTTPSConnectionPool: url: /v1?key={_LEAKED_KEY}"+ )+ engine._make_request = Mock(side_effect=exc)++ caught = None+ try:+ engine._validate_connection()+ except Exception as e:+ caught = e++ assert caught is not None+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in str(caught), (+ f"Re-thrown exception leaks key as {encoding!r}: {str(caught)!r}"+ )++ def test_exception_chain_suppressed(self):+ """``from None`` should suppress the original exception chain."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_google_pse as mod,+ )++ engine = mod.GooglePSESearchEngine.__new__(mod.GooglePSESearchEngine)+ engine.api_key = _LEAKED_KEY++ exc = ValueError("original")+ engine._make_request = Mock(side_effect=exc)++ caught = None+ try:+ engine._validate_connection()+ except Exception as e:+ caught = e++ assert caught is not None+ assert caught.__cause__ is None++ def test_log_output_sanitized(self, loguru_caplog_full):+ """The warning log from ``_validate_connection`` must not leak."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_google_pse as mod,+ )++ engine = mod.GooglePSESearchEngine.__new__(mod.GooglePSESearchEngine)+ engine.api_key = _LEAKED_KEY++ exc = requests.exceptions.ConnectionError(+ f"HTTPSConnectionPool: url: /v1?key={_LEAKED_KEY}"+ )+ engine._make_request = Mock(side_effect=exc)++ with loguru_caplog_full.at_level("DEBUG"):+ try:+ engine._validate_connection()+ except Exception:+ pass++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"_validate_connection log leaked key as {encoding!r}"+ )+++# ── OpenAI compat errors tests ───────────────────────────────────────+++class TestOpenAICompatErrorDetails:+ def test_details_with_url_key_redacted(self):+ """The ``Details:`` suffix must not contain URL query credentials."""+ from local_deep_research.error_handling.openai_compat_errors import (+ friendly_openai_compatible_error,+ )++ exc = RuntimeError(+ f"Connection to https://api.host/v1?key={_LEAKED_KEY} failed"+ )+ result = friendly_openai_compatible_error(+ exc, provider="test", base_url="https://api.host/v1", model="gpt-4"+ )++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in result, (+ f"Details leaked key as {encoding!r}: {result!r}"+ )++ def test_details_with_bearer_redacted(self):+ """Bearer tokens must be scrubbed from the Details suffix."""+ from local_deep_research.error_handling.openai_compat_errors import (+ friendly_openai_compatible_error,+ )++ exc = RuntimeError(f"Bearer {_LEAKED_KEY} rejected")+ result = friendly_openai_compatible_error(+ exc, provider="test", base_url="https://api.host/v1", model="gpt-4"+ )++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in result++ def test_no_secrets_preserves_details(self):+ """Non-sensitive details should be preserved."""+ from local_deep_research.error_handling.openai_compat_errors import (+ friendly_openai_compatible_error,+ )++ exc = RuntimeError("connection refused on port 443")+ result = friendly_openai_compatible_error(+ exc, provider="test", base_url="https://api.host/v1", model="gpt-4"+ )++ assert "connection refused on port 443" in resultdiff --git a/tests/security/test_credential_leak_phase3.py b/tests/security/test_credential_leak_phase3.pynew file mode 100644index 0000000000..147150670f--- /dev/null+++ b/tests/security/test_credential_leak_phase3.py@@ -0,0 +1,644 @@+"""Tests for credential leak fixes across additional search engines.++Covers:+- GitHub engine: 7 ``logger.exception()`` calls replaced with dual-scrub+- Elasticsearch: ``logger.exception`` + unsanitized ``raise ConnectionError``+- Paperless: 5 ``logger.exception()`` calls replaced with dual-scrub+- Semantic Scholar: 6 ``logger.exception()`` calls replaced with dual-scrub+- Brave: 2 ``logger.exception()`` calls replaced with dual-scrub+- NASA ADS: 1 ``logger.exception()`` call replaced with dual-scrub+- Guardian: 3 ``logger.exception()`` calls replaced with dual-scrub+"""++from unittest.mock import Mock, patch++import pytest+import requests+++_LEAKED_KEY = "sk-phase3-sentinel-DO-NOT-APPEAR-IN-LOGS-9999"+_LEAKED_TOKEN = "tok-paperless-sentinel-DO-NOT-APPEAR-8888"+_LEAKED_PASSWORD = "pw-phase3-sentinel-DO-NOT-APPEAR-7777"+++def _all_encodings_of(secret: str) -> list:+ import base64+ from urllib.parse import quote, quote_plus++ return [+ secret,+ quote(secret, safe=""),+ quote_plus(secret),+ repr(secret)[1:-1],+ base64.b64encode(secret.encode()).decode(),+ secret[:8],+ ]+++def _stub_rate_tracker() -> Mock:+ tracker = Mock()+ tracker.enabled = False+ tracker.apply_rate_limit.return_value = 0+ return tracker+++# ── GitHub engine tests ──────────────────────────────────────────────+++def _github_engine():+ """Build a minimal GitHubSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_github as mod,+ )++ engine = mod.GitHubSearchEngine.__new__(mod.GitHubSearchEngine)+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.api_base = "https://api.github.com"+ engine.headers = {+ "Authorization": f"token {_LEAKED_KEY}",+ "Accept": "application/vnd.github.v3+json",+ }+ return mod, engine+++ "method_name,method_args,marker",+ [+ (+ "_get_readme_content",+ ("owner/repo",),+ "Error getting README",+ ),+ (+ "_get_recent_issues",+ ("owner/repo",),+ "Error getting issues",+ ),+ (+ "_get_file_content",+ ("https://api.github.com/some/url",),+ "Error getting file content",+ ),+ (+ "search_repository",+ ("owner", "repo"),+ "Error getting repository details",+ ),+ (+ "_filter_for_relevance",+ ([{"title": "test"}], "query"),+ "Error filtering GitHub results",+ ),+ ],+)+class TestGitHubEngineKeyLeakage:+ def test_no_leak_in_catch_block(+ self, loguru_caplog_full, method_name, method_args, marker+ ):+ """Each GitHub method must scrub the API key before logging."""+ mod, engine = _github_engine()++ exc = requests.exceptions.ConnectionError(+ f"HTTPSConnectionPool: Max retries exceeded with url: "+ f"/repos/owner/repo?key={_LEAKED_KEY}"+ )++ with loguru_caplog_full.at_level("DEBUG"):+ if method_name == "_filter_for_relevance":+ # _filter_for_relevance uses self.llm, not safe_get+ engine.llm = Mock()+ engine.llm.invoke = Mock(side_effect=exc)+ try:+ getattr(engine, method_name)(*method_args)+ except Exception:+ pass+ else:+ with patch.object(mod, "safe_get", side_effect=exc):+ try:+ getattr(engine, method_name)(*method_args)+ except Exception:+ pass++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"{method_name}: api_key leaked as encoding {encoding!r}"+ )++ assert marker in loguru_caplog_full.text, (+ f"{method_name}: catch-block marker {marker!r} not in logs — "+ f"the redaction path may not have run. "+ f"Captured: {loguru_caplog_full.text!r}"+ )+++class TestGitHubLLMMethods:+ def test_optimize_query_no_leak(self, loguru_caplog_full):+ """``_optimize_github_query`` must not leak the API key."""+ mod, engine = _github_engine()++ exc = RuntimeError(f"LLM error with key={_LEAKED_KEY}")+ engine.llm = Mock()+ engine.llm.invoke = Mock(side_effect=exc)++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._optimize_github_query("test query")++ assert result == "test query"+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"_optimize_github_query leaked key as {encoding!r}"+ )+++# ── Elasticsearch tests ──────────────────────────────────────────────+++class TestElasticsearchKeyLeakage:+ def test_init_connection_error_sanitized(self):+ """The ``ConnectionError`` raised from ``__init__`` must not+ contain the API key."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_elasticsearch as mod,+ )++ with patch.object(+ mod.Elasticsearch,+ "__init__",+ side_effect=Exception(+ f"Connection to https://es.host:9200?key={_LEAKED_KEY} failed"+ ),+ ):+ # Elasticsearch.__init__ is patched to raise, so the mock+ # won't call super().__init__ — make the constructor safe.+ mod.Elasticsearch.__init__ = lambda self, *a, **kw: None+ engine = mod.ElasticsearchSearchEngine.__new__(+ mod.ElasticsearchSearchEngine+ )+ # Manually invoke the connection test portion+ engine._api_key = _LEAKED_KEY+ engine._password = None++ caught = None+ try:+ # Simulate the connection check block+ raise Exception(+ f"Connection to https://es.host:9200?key={_LEAKED_KEY} failed"+ )+ except Exception as e:+ from local_deep_research.security.log_sanitizer import (+ redact_secrets,+ sanitize_error_message,+ )++ safe_msg = redact_secrets(+ sanitize_error_message(str(e)), engine._api_key+ )+ caught = ConnectionError(+ f"Could not connect to Elasticsearch: {safe_msg}"+ )++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in str(caught), (+ f"Elasticsearch ConnectionError leaked key as {encoding!r}"+ )++ def test_previews_no_leak(self, loguru_caplog_full):+ """``_get_previews`` must not leak the API key."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_elasticsearch as mod,+ )++ engine = mod.ElasticsearchSearchEngine.__new__(+ mod.ElasticsearchSearchEngine+ )+ engine._api_key = _LEAKED_KEY+ engine._password = None+ engine.client = Mock()+ engine.client.search = Mock(+ side_effect=Exception(+ f"Search failed: https://es.host?key={_LEAKED_KEY}"+ )+ )+ engine.highlight_fields = ["content"]+ engine.search_fields = ["content"]+ engine.filter_query = {}+ engine.max_results = 10+ engine.index_name = "test"++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._get_previews("test")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text, (+ f"Elasticsearch _get_previews leaked key as {encoding!r}"+ )++ def test_query_string_search_no_leak(self, loguru_caplog_full):+ """``search_by_query_string`` must not leak the API key."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_elasticsearch as mod,+ )++ engine = mod.ElasticsearchSearchEngine.__new__(+ mod.ElasticsearchSearchEngine+ )+ engine._api_key = _LEAKED_KEY+ engine._password = None+ engine.client = Mock()+ engine.client.search = Mock(+ side_effect=Exception(f"Error with key={_LEAKED_KEY}")+ )+ engine.highlight_fields = ["content"]+ engine.search_fields = ["content"]+ engine.max_results = 10+ engine.index_name = "test"++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine.search_by_query_string("test")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_query_string_and_dsl_search_no_password_leak(+ self, loguru_caplog_full+ ):+ """``search_by_query_string`` / ``search_by_dsl`` must redact the+ basic-auth password, not just the API key.++ Regression guard: these two catch blocks originally passed only+ ``_api_key`` to ``redact_secrets`` while the other ES catch blocks+ also passed ``_password``. A password surfaced in the client error+ (e.g. a basic-auth failure) would have leaked here.+ """+ from local_deep_research.web_search_engines.engines import (+ search_engine_elasticsearch as mod,+ )++ for method, arg in (+ ("search_by_query_string", "test"),+ ("search_by_dsl", {"query": {"match_all": {}}}),+ ):+ engine = mod.ElasticsearchSearchEngine.__new__(+ mod.ElasticsearchSearchEngine+ )+ engine._api_key = None+ engine._password = _LEAKED_PASSWORD+ engine.client = Mock()+ engine.client.search = Mock(+ side_effect=Exception(+ f"auth failed for user:{_LEAKED_PASSWORD}@host"+ )+ )+ engine.highlight_fields = ["content"]+ engine.search_fields = ["content"]+ engine.max_results = 10+ engine.index_name = "test"++ with loguru_caplog_full.at_level("DEBUG"):+ result = getattr(engine, method)(arg)++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_PASSWORD):+ assert encoding not in loguru_caplog_full.text, (+ f"password leaked via {method}"+ )+++# ── Paperless engine tests ───────────────────────────────────────────+++def _paperless_engine():+ """Build a minimal PaperlessSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_paperless as mod,+ )++ engine = mod.PaperlessSearchEngine.__new__(mod.PaperlessSearchEngine)+ engine.api_token = _LEAKED_TOKEN+ engine.api_url = "http://localhost:8000"+ engine.headers = {"Authorization": f"Token {_LEAKED_TOKEN}"}+ engine.timeout = 30+ engine.verify_ssl = True+ engine.max_results = 10+ engine.llm = None+ engine.rate_tracker = _stub_rate_tracker()+ engine.engine_type = "test_engine"+ return mod, engine+++class TestPaperlessEngineKeyLeakage:+ def test_make_request_no_leak(self, loguru_caplog_full):+ """``_make_request`` must not leak the API token."""+ mod, engine = _paperless_engine()++ exc = requests.exceptions.ConnectionError(+ f"Connection to http://localhost:8000?key={_LEAKED_TOKEN} failed"+ )++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(mod, "safe_get", side_effect=exc):+ result = engine._make_request("/api/documents/")++ assert result == {}+ for encoding in _all_encodings_of(_LEAKED_TOKEN):+ assert encoding not in loguru_caplog_full.text, (+ f"Paperless _make_request leaked token as {encoding!r}"+ )++ def test_get_previews_no_leak(self, loguru_caplog_full):+ """``_get_previews`` must not leak the API token."""+ mod, engine = _paperless_engine()++ exc = RuntimeError(f"Error: token={_LEAKED_TOKEN}")++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(engine, "_multi_pass_search", side_effect=exc):+ result = engine._get_previews("query")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_TOKEN):+ assert encoding not in loguru_caplog_full.text++ def test_get_full_content_no_leak(self, loguru_caplog_full):+ """``_get_full_content`` must not leak the API token."""+ mod, engine = _paperless_engine()+ engine.include_content = True++ item = {+ "_raw_data": {},+ "snippet": "test snippet",+ "metadata": {"doc_id": "123"},+ }++ exc = RuntimeError(f"Error: token={_LEAKED_TOKEN}")++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(engine, "_make_request", side_effect=exc):+ result = engine._get_full_content([item])++ assert len(result) == 1+ for encoding in _all_encodings_of(_LEAKED_TOKEN):+ assert encoding not in loguru_caplog_full.text++ def test_run_no_leak(self, loguru_caplog_full):+ """``run()`` must not leak the API token."""+ mod, engine = _paperless_engine()++ exc = RuntimeError(f"Error: token={_LEAKED_TOKEN}")++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(engine, "_get_previews", side_effect=exc):+ result = engine.run("query")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_TOKEN):+ assert encoding not in loguru_caplog_full.text++ def test_test_connection_no_leak(self, loguru_caplog_full):+ """``test_connection`` must not leak the API token."""+ mod, engine = _paperless_engine()++ exc = RuntimeError(f"Error: token={_LEAKED_TOKEN}")++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(engine, "_make_request", side_effect=exc):+ result = engine.test_connection()++ assert result is False+ for encoding in _all_encodings_of(_LEAKED_TOKEN):+ assert encoding not in loguru_caplog_full.text+++# ── Semantic Scholar tests ───────────────────────────────────────────+++def _semantic_scholar_engine():+ """Build a minimal SemanticScholarSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_semantic_scholar as mod,+ )++ engine = mod.SemanticScholarSearchEngine.__new__(+ mod.SemanticScholarSearchEngine+ )+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.session = Mock()+ engine.search_url = "https://api.semanticscholar.org/graph/v1/paper/search"+ engine.paper_details_url = "https://api.semanticscholar.org/graph/v1/paper"+ engine.get_abstracts = True+ engine.get_references = False+ engine.get_citations = False+ engine.get_embeddings = False+ engine.get_tldr = True+ engine.citation_limit = 10+ engine.reference_limit = 10+ engine.max_results = 10+ engine.optimize_queries = True+ engine.llm = None+ return mod, engine+++class TestSemanticScholarKeyLeakage:+ def test_direct_search_no_leak(self, loguru_caplog_full):+ """``_direct_search`` must not leak the API key."""+ mod, engine = _semantic_scholar_engine()++ exc = requests.exceptions.ConnectionError(+ f"Connection to https://api.semanticscholar.org?key={_LEAKED_KEY}"+ )+ engine.session.get = Mock(side_effect=exc)++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._direct_search("test query")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_get_paper_details_no_leak(self, loguru_caplog_full):+ """``_get_paper_details`` must not leak the API key."""+ mod, engine = _semantic_scholar_engine()++ exc = requests.exceptions.ConnectionError(f"Error: key={_LEAKED_KEY}")+ engine.session.get = Mock(side_effect=exc)++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._get_paper_details("paper123")++ assert result == {}+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_optimize_query_no_leak(self, loguru_caplog_full):+ """``_optimize_query`` must not leak the API key."""+ mod, engine = _semantic_scholar_engine()+ engine.llm = Mock()+ engine.llm.invoke = Mock(+ side_effect=RuntimeError(f"LLM error key={_LEAKED_KEY}")+ )++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._optimize_query("test query")++ assert result == "test query"+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_close_no_leak(self, loguru_caplog_full):+ """``close()`` must not leak the API key."""+ mod, engine = _semantic_scholar_engine()++ engine.session = Mock()+ engine.session.close = Mock(+ side_effect=RuntimeError(f"Error: key={_LEAKED_KEY}")+ )++ with loguru_caplog_full.at_level("DEBUG"):+ engine.close()++ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text+++# ── Brave engine tests ───────────────────────────────────────────────+++def _brave_engine():+ """Build a minimal BraveSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_brave as mod,+ )++ engine = mod.BraveSearchEngine.__new__(mod.BraveSearchEngine)+ engine._brave_api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.engine = Mock()+ return mod, engine+++class TestBraveEngineKeyLeakage:+ def test_get_previews_no_leak(self, loguru_caplog_full):+ """``_get_previews`` must not leak the API key."""+ mod, engine = _brave_engine()++ exc = RuntimeError(f"Brave API error: key={_LEAKED_KEY}")+ engine.engine.run = Mock(side_effect=exc)++ # Mock _raise_if_rate_limit to re-raise non-rate-limit exceptions+ engine._raise_if_rate_limit = Mock()++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._get_previews("test query")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_json_parse_error_no_leak(self, loguru_caplog_full):+ """JSON parse error in ``_get_previews`` must not leak the API key."""+ mod, engine = _brave_engine()++ # Return a non-JSON string to trigger JSONDecodeError path+ engine.engine.run = Mock(return_value="not json {{{}}}")++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._get_previews("test query")++ assert result == []+++# ── NASA ADS tests ───────────────────────────────────────────────────+++def _nasa_ads_engine():+ """Build a minimal NasaAdsSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_nasa_ads as mod,+ )++ engine = mod.NasaAdsSearchEngine.__new__(mod.NasaAdsSearchEngine)+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ return mod, engine+++class TestNasaAdsKeyLeakage:+ def test_format_doc_preview_no_leak(self, loguru_caplog_full):+ """``_format_doc_preview`` must not leak the API key."""+ mod, engine = _nasa_ads_engine()++ # Pass a doc that will cause a formatting error+ bad_doc = {"bibcode": None}++ with loguru_caplog_full.at_level("DEBUG"):+ engine._format_doc_preview(bad_doc)++ # Result is None on error+ # The main thing is no key in logs regardless+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text+++# ── Guardian tests ───────────────────────────────────────────────────+++def _guardian_engine():+ """Build a minimal GuardianSearchEngine for testing."""+ from local_deep_research.web_search_engines.engines import (+ search_engine_guardian as mod,+ )++ engine = mod.GuardianSearchEngine.__new__(mod.GuardianSearchEngine)+ engine.api_key = _LEAKED_KEY+ engine.engine_type = "test_engine"+ engine.rate_tracker = _stub_rate_tracker()+ engine.api_url = "https://content.guardianapis.com"+ engine.llm = None+ engine.optimize_queries = True+ return mod, engine+++class TestGuardianKeyLeakage:+ def test_optimize_query_no_leak(self, loguru_caplog_full):+ """``_optimize_query_for_guardian`` must not leak the API key."""+ mod, engine = _guardian_engine()+ engine.llm = Mock()+ engine.llm.invoke = Mock(+ side_effect=RuntimeError(f"LLM error key={_LEAKED_KEY}")+ )++ with loguru_caplog_full.at_level("DEBUG"):+ result = engine._optimize_query_for_guardian("test query")++ assert result == "test query"+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.text++ def test_run_catch_all_no_leak(self, loguru_caplog_full):+ """The catch-all in ``run()`` must not leak the API key."""+ mod, engine = _guardian_engine()++ exc = RuntimeError(f"Unexpected error: key={_LEAKED_KEY}")++ with loguru_caplog_full.at_level("DEBUG"):+ with patch.object(engine, "_get_previews", side_effect=exc):+ engine._original_date_params = {+ "from_date": None,+ "to_date": None,+ }+ engine.from_date = None+ engine.to_date = None+ engine.programmatic_mode = False+ result = engine.run("test query")++ assert result == []+ for encoding in _all_encodings_of(_LEAKED_KEY):+ assert encoding not in loguru_caplog_full.textdiff --git a/tests/security/test_sanitize_error_message.py b/tests/security/test_sanitize_error_message.pynew file mode 100644index 0000000000..aaa7e7e70f--- /dev/null+++ b/tests/security/test_sanitize_error_message.py@@ -0,0 +1,159 @@+"""Tests for the standalone ``sanitize_error_message`` function.++Verifies that the regex-based sanitizer catches common credential formats+in exception messages. This function was extracted from+``BaseSearchEngine._sanitize_error_message`` so it can be used outside the+search-engine inheritance tree (e.g. in LLM config and error handling).+"""++from local_deep_research.security.log_sanitizer import sanitize_error_message+++class TestSanitizeErrorMessageStandalone:+ """Unit tests for the pattern-based credential sanitizer."""++ def test_bearer_token_redacted(self):+ msg = 'Error: Connection refused, token="Bearer sk-proj-abc123xyz456def789ghi012"'+ result = sanitize_error_message(msg)+ assert "sk-proj-abc123xyz456def789ghi012" not in result+ assert "Bearer [REDACTED]" in result++ def test_url_query_api_key_redacted(self):+ msg = "HTTPSConnectionPool: Max retries exceeded with url: /v1/models?api_key=sk-secret-key-value-12345&q=test"+ result = sanitize_error_message(msg)+ assert "sk-secret-key-value-12345" not in result+ assert "api_key=[REDACTED]" in result++ def test_url_query_apikey_no_underscore_redacted(self):+ msg = "?apikey=my-secret-api-key-value-here&format=json"+ result = sanitize_error_message(msg)+ assert "my-secret-api-key-value-here" not in result+ assert "apikey=[REDACTED]" in result++ def test_url_query_api_key_hyphenated_redacted(self):+ """Guardian uses ``api-key`` (with hyphen) as the param name."""+ msg = "?api-key=guardian-secret-key-value-here&q=test"+ result = sanitize_error_message(msg)+ assert "guardian-secret-key-value-here" not in result+ assert "api-key=[REDACTED]" in result++ def test_url_query_key_redacted(self):+ """Google PSE uses ``key`` as the param name."""+ msg = "?key=google-pse-secret-key-value&q=test"+ result = sanitize_error_message(msg)+ assert "google-pse-secret-key-value" not in result+ assert "key=[REDACTED]" in result++ def test_url_query_token_redacted(self):+ msg = "?token=secret-token-value-1234567890&page=1"+ result = sanitize_error_message(msg)+ assert "secret-token-value-1234567890" not in result+ assert "token=[REDACTED]" in result++ def test_url_query_secret_redacted(self):+ msg = "&secret=super-secret-value-abcde12345&format=json"+ result = sanitize_error_message(msg)+ assert "super-secret-value-abcde12345" not in result+ assert "secret=[REDACTED]" in result++ def test_url_credentials_redacted(self):+ msg = "Connection to https://admin:[email protected] failed"+ result = sanitize_error_message(msg)+ assert "admin" not in result+ assert "supersecretpassword" not in result+ assert "[REDACTED]:[REDACTED]@" in result++ def test_url_credentials_inside_api_key_param_value(self):+ """URL-embedded credentials must survive being an api-key param value.++ Regression test for pattern ordering: when the param value is itself+ a URL with embedded credentials, the param pattern used to consume+ the ``https`` scheme first (``api-key=[REDACTED]://user:pass@...``),+ leaving the credentials unredacted. The URL-credentials pattern now+ runs before the URL-param pattern.+ """+ msg = "Request failed for ?api-key=https://admin:[email protected]/v1"+ result = sanitize_error_message(msg)+ assert "supersecret" not in result+ assert "admin" not in result++ def test_url_credentials_inside_key_param_value(self):+ """Same ordering interaction via the ``key=`` spelling."""+ msg = "?key=https://user:[email protected]/path"+ result = sanitize_error_message(msg)+ assert "hunter2" not in result+ assert "user:" not in result++ def test_url_credentials_inside_token_param_value(self):+ """Same ordering interaction via the ``token=`` spelling."""+ msg = "retry failed: &token=http://svc:[email protected]:8080/auth"+ result = sanitize_error_message(msg)+ assert "p4ssw0rd" not in result+ assert "svc:" not in result++ def test_sk_prefix_redacted(self):+ """OpenAI-style key with modern hyphenated format (sk-proj-...)."""+ msg = "Invalid API key: sk-proj-abc123xyz456def789ghi012jkl"+ result = sanitize_error_message(msg)+ assert "sk-proj-abc123xyz456def789ghi012jkl" not in result+ assert "[REDACTED_KEY]" in result++ def test_sk_prefix_pure_alphanumeric(self):+ """Old-style OpenAI key (pure alphanumeric after sk-)."""+ msg = "key: sk-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+ result = sanitize_error_message(msg)+ assert "sk-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" not in result+ assert "[REDACTED_KEY]" in result++ def test_pk_prefix_redacted(self):+ msg = "public key pk-test-abc123xyz456def789ghi012jkl345"+ result = sanitize_error_message(msg)+ assert "pk-test-abc123xyz456def789ghi012jkl345" not in result+ assert "[REDACTED_KEY]" in result++ def test_empty_string_passthrough(self):+ assert sanitize_error_message("") == ""++ def test_no_secrets_unchanged(self):+ msg = (+ "Connection timeout after 10s for https://api.example.com/v1/models"+ )+ assert sanitize_error_message(msg) == msg++ def test_multiple_secrets_in_one_message(self):+ msg = (+ "Bearer sk-proj-abc123xyz456def789ghi012 "+ "with ?api_key=my-secret-key-12345&token=another-secret-value-67890"+ )+ result = sanitize_error_message(msg)+ assert "sk-proj-abc123xyz456def789ghi012" not in result+ assert "my-secret-key-12345" not in result+ assert "another-secret-value-67890" not in result+ assert "Bearer [REDACTED]" in result+ assert "api_key=[REDACTED]" in result+ assert "token=[REDACTED]" in result++ def test_sk_prefix_too_short_not_redacted(self):+ """Short strings like ``sk-abc`` should NOT be redacted (false positive risk)."""+ msg = "prefix: sk-abc"+ assert sanitize_error_message(msg) == msg++ def test_delegate_preserves_backward_compat(self):+ """The BaseSearchEngine method delegates to the standalone function,+ so this test verifies the output matches the old inline behavior+ for a representative message."""+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ msg = "Error: ?api_key=secret12345678&key=mykey1234567890123456"+ expected = sanitize_error_message(msg)++ # Create a minimal subclass instance to call the instance method.+ class _MinimalEngine(BaseSearchEngine):+ def _get_previews(self, query, *args, **kwargs):+ return []++ engine = _MinimalEngine.__new__(_MinimalEngine)+ actual = engine._sanitize_error_message(msg)+ assert actual == expected