~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(search): strip URLs before the _is_valid_search_result gate (searxng + mojeek) (#4573)
LearningCircuit817816603a39
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.pyindex 602ea0475f..a9a111778b 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py@@ -157,7 +157,7 @@ class MojeekSearchEngine(BaseSearchEngine):raw_results = response_data.get("results", [])results = []for result in raw_results:- url = result.get("url", "")+ url = self._clean_result_url(result.get("url"))if not self._is_valid_search_result(url):continueresults.append(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex d3de802368..91bd1072fe 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -352,12 +352,7 @@ class SearXNGSearchEngine(BaseSearchEngine):url = ""if url_element and url_element.has_attr("href"):- # .strip() is defensive against HTML scrapes- # that include surrounding whitespace; the- # SSRF validator strips internally too, but- # cleaning here keeps URLs clean for logs- # and downstream consumers.- url = str(url_element["href"]).strip()+ url = self._clean_result_url(url_element["href"])elif url_element:url = url_element.get_text(strip=True)@@ -372,7 +367,7 @@ class SearXNGSearchEngine(BaseSearchEngine):and title_elementand title_element.has_attr("href")):- url = str(title_element["href"])+ url = self._clean_result_url(title_element["href"])logger.debug(f"Extracted result {idx}: title={title[:30]}..., url={url[:30]}..., content={content[:30]}..."@@ -462,9 +457,7 @@ class SearXNGSearchEngine(BaseSearchEngine):previews = []for i, result in enumerate(results):title = result.get("title", "")- # .strip() is defensive against API responses with surrounding- # whitespace; the SSRF validator strips internally too.- url = (result.get("url") or "").strip()+ url = self._clean_result_url(result.get("url"))content = result.get("content", "")preview = {@@ -547,7 +540,7 @@ class SearXNGSearchEngine(BaseSearchEngine):formatted_results.append({"title": result.get("title", ""),- "link": (result.get("url") or "").strip(),+ "link": self._clean_result_url(result.get("url")),"snippet": result.get("content", ""),})diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.pyindex f9308c212d..768b795d95 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py@@ -153,10 +153,7 @@ class TavilySearchEngine(BaseSearchEngine):# Format results as previewspreviews = []for i, result in enumerate(results):- # .strip() is defensive against API responses with- # surrounding whitespace; the SSRF validator strips- # internally too.- url = (result.get("url") or "").strip()+ url = self._clean_result_url(result.get("url"))preview = {"id": url or str(i), # Use URL as ID"title": result.get("title", ""),diff --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 f72b47f474..2f9b114202 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@@ -863,6 +863,34 @@ class BaseSearchEngine(ABC):except Exception:return fallback+ @staticmethod+ def _clean_result_url(value: Any) -> str:+ """Normalize a raw search-result URL for the validity gate.++ Coerces ``None`` (and any other falsy value) to ``""`` and any+ truthy value to ``str`` before stripping surrounding whitespace.++ The strip is **load-bearing**, not merely cosmetic: several engines+ gate the URL on a ``url.lower().startswith(("http://", "https://"))``+ prefix check (see ``_is_valid_search_result``) *before* it reaches+ the SSRF validator's own internal strip, so leading/trailing+ whitespace — common in HTML-scraped ``href`` attributes — would+ silently drop an otherwise-valid result. Cleaning once at extraction+ also keeps the URL tidy for logs and downstream consumers (preview+ ``id``/``link`` fields, etc.).++ Args:+ value: The raw URL value from a search result, e.g.+ ``result.get("url")`` or a parsed HTML ``href`` attribute.++ Returns:+ The whitespace-stripped URL string, or ``""`` if *value* is+ falsy (``None``, empty, etc.).+ """+ if not value:+ return ""+ return str(value).strip()+def _resolve_api_key(self,api_key: Optional[str],diff --git a/tests/search_engines/test_base_helpers.py b/tests/search_engines/test_base_helpers.pyindex 43ea335020..339ac68ad6 100644--- a/tests/search_engines/test_base_helpers.py+++ b/tests/search_engines/test_base_helpers.py@@ -90,6 +90,55 @@ class TestIsValidApiKey:assert BaseSearchEngine._is_valid_api_key("${API_KEY}") is False+class TestCleanResultUrl:+ """Tests for _clean_result_url static method."""++ def test_strips_surrounding_whitespace(self):+ """Leading/trailing whitespace is stripped."""+ assert (+ BaseSearchEngine._clean_result_url(" https://example.com ")+ == "https://example.com"+ )++ def test_strips_tabs_and_newlines(self):+ """Tabs and newlines (common in scraped hrefs) are stripped."""+ assert (+ BaseSearchEngine._clean_result_url("\thttps://example.com\n")+ == "https://example.com"+ )++ def test_clean_url_unchanged(self):+ """An already-clean URL passes through unchanged."""+ assert (+ BaseSearchEngine._clean_result_url("https://example.com")+ == "https://example.com"+ )++ def test_none_returns_empty_string(self):+ """None coerces to '' (does not raise, does not become 'None')."""+ assert BaseSearchEngine._clean_result_url(None) == ""++ def test_empty_string_returns_empty(self):+ """Empty string returns empty string."""+ assert BaseSearchEngine._clean_result_url("") == ""++ def test_whitespace_only_returns_empty(self):+ """Whitespace-only value strips down to empty string."""+ assert BaseSearchEngine._clean_result_url(" ") == ""++ def test_non_str_value_is_coerced(self):+ """Non-str truthy values (e.g. a parsed href object) are str()-ified."""++ class HrefLike:+ def __str__(self):+ return " https://example.com "++ assert (+ BaseSearchEngine._clean_result_url(HrefLike())+ == "https://example.com"+ )++class TestResolveApiKey:"""Tests for _resolve_api_key method."""diff --git a/tests/web_search_engines/engines/test_search_engine_mojeek.py b/tests/web_search_engines/engines/test_search_engine_mojeek.pyindex 3203ea846d..8a164067c8 100644--- a/tests/web_search_engines/engines/test_search_engine_mojeek.py+++ b/tests/web_search_engines/engines/test_search_engine_mojeek.py@@ -212,6 +212,47 @@ class TestGetSearchResults:assert results[0]["engine"] == "mojeek"assert results[0]["category"] == "Technology"+ def test_whitespace_padded_url_survives_validity_gate(self):+ """Regression: a URL with surrounding whitespace must NOT be+ silently dropped by _is_valid_search_result().++ The url is gated on a http(s):// *prefix* check that runs before the+ SSRF validator's internal strip, so without the extraction-time strip+ a padded url fails ``startswith("https://")`` and the whole result is+ dropped (len would be 0). See BaseSearchEngine._clean_result_url.+ """+ from local_deep_research.web_search_engines.engines.search_engine_mojeek import (+ MojeekSearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "response": {+ "status": "OK",+ "results": [+ {+ "title": "Padded",+ "url": " https://example.com/padded ",+ "desc": "d",+ "cats": "c",+ }+ ],+ }+ }++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_mojeek.safe_get",+ return_value=mock_response,+ ):+ engine = MojeekSearchEngine(+ api_key="test-api-key", include_full_content=False+ )+ results = engine._get_search_results("test query")++ assert len(results) == 1 # would be 0 before the strip fix+ assert results[0]["url"] == "https://example.com/padded"+def test_empty_results(self):"""Test empty results array."""from local_deep_research.web_search_engines.engines.search_engine_mojeek import (diff --git a/tests/web_search_engines/engines/test_search_engine_searxng_coverage.py b/tests/web_search_engines/engines/test_search_engine_searxng_coverage.pyindex 66656f67e5..f8befd5f84 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng_coverage.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng_coverage.py@@ -313,6 +313,39 @@ class TestGetSearchResultsURLFromTitleHref:# Fallback: title_element (.result-title) has href => url becomes that.assert results[0]["url"] == "https://example.com/from-title"+ def test_whitespace_padded_title_href_survives_gate(self):+ """Regression: a whitespace-padded title-href must survive the+ _is_valid_search_result() http(s):// prefix gate instead of being+ silently dropped.++ That gate runs before the SSRF validator's internal strip, so without+ the extraction-time strip the padded href fails the prefix check and+ the result is dropped (len would be 0). BeautifulSoup preserves the+ surrounding whitespace, so this exercises the real path.+ """+ engine = _make_engine()++ html = """+ <html><body>+ <article class="result">+ <a class="result-title" href=" https://example.com/padded ">Title</a>+ <span class="url"></span>+ <p class="content">content</p>+ </article>+ </body></html>+ """+ cookie_resp = Mock()+ cookie_resp.cookies = {}+ search_resp = _make_search_response(html)++ with patch(+ f"{MODULE}.safe_get", side_effect=[cookie_resp, search_resp]+ ):+ results = engine._get_search_results("test query")++ assert len(results) == 1 # would be 0 before the strip fix+ assert results[0]["url"] == "https://example.com/padded"+# ---------------------------------------------------------------------------# _get_full_content – snippets-only mode