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: SSRF & debug mode security hardening (#1961)

LearningCircuitfeb4b40b5325
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index d8858cfadc..5eabfae54e 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1,7 +1,7 @@
{
"app.debug": {
"category": "app_interface",
- "description": "Produces more informative errors when something goes wrong, but may expose sensitive data.",
+ "description": "Produces more informative errors when something goes wrong, but may expose sensitive data. This setting cannot be changed from the UI for security reasons. To enable debug mode, set the environment variable LDR_APP_DEBUG=true or edit server_config.json.",
"editable": false,
"max_value": null,
"min_value": null,
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index feed37fc7e..7528be2a70 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -12,7 +12,6 @@ from urllib.parse import urlparse
from typing import Optional
from loguru import logger
-from ..settings.env_registry import get_env_setting
from .ip_ranges import PRIVATE_IP_RANGES as BLOCKED_IP_RANGES
# AWS metadata endpoint (commonly targeted in SSRF attacks)
@@ -71,6 +70,11 @@ def is_ip_blocked(
try:
ip = ipaddress.ip_address(ip_str)
+ # Unwrap IPv4-mapped IPv6 addresses (e.g. ::ffff:127.0.0.1 → 127.0.0.1)
+ # These bypass IPv4 range checks if not converted.
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
+ ip = ip.ipv4_mapped
+
# ALWAYS block AWS metadata endpoint - critical SSRF target for credential theft
if str(ip) == AWS_METADATA_IP:
return True
@@ -129,21 +133,15 @@ def validate_url(
True if URL is safe, False otherwise
Note:
- SSRF validation can be disabled for testing by setting environment variables:
- - TESTING=true
- - PYTEST_CURRENT_TEST (automatically set by pytest)
- - LDR_SECURITY_SSRF_DISABLE_VALIDATION=true
+ SSRF validation is automatically bypassed during pytest runs via
+ the PYTEST_CURRENT_TEST environment variable (set by pytest).
"""
- # Bypass SSRF validation in test mode
- # Check environment variables at runtime (not import time) to ensure
- # pytest's PYTEST_CURRENT_TEST is captured when tests actually run
- disable_ssrf = get_env_setting(
- "security.ssrf.disable_validation", default=False
- )
- testing_mode = os.environ.get("TESTING", "").lower() in ("true", "1", "yes")
+ # Bypass SSRF validation only during pytest runs.
+ # PYTEST_CURRENT_TEST is set automatically by pytest and is not
+ # user-controllable in production environments.
pytest_current_test = os.environ.get("PYTEST_CURRENT_TEST")
- if testing_mode or pytest_current_test or disable_ssrf:
- logger.debug(f"SSRF validation bypassed in test mode for URL: {url}")
+ if pytest_current_test:
+ logger.debug(f"SSRF validation bypassed in pytest for URL: {url}")
return True
try:
diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.py
index c8c3d66c95..0bc6ec9c90 100644
--- a/src/local_deep_research/settings/env_definitions/security.py
+++ b/src/local_deep_research/settings/env_definitions/security.py
@@ -6,7 +6,7 @@ and CORS origin restrictions.
"""
import os
-from ..env_settings import BooleanSetting, StringSetting
+from ..env_settings import StringSetting
# External environment variables (set by pytest, CI systems)
@@ -16,11 +16,6 @@ PYTEST_CURRENT_TEST = os.environ.get("PYTEST_CURRENT_TEST")
# LDR Security settings (our application's security configuration)
SECURITY_SETTINGS = [
- BooleanSetting(
- key="security.ssrf.disable_validation", # gitleaks:allow
- description="Disable SSRF validation (test/dev only - NEVER in production)",
- default=False,
- ),
StringSetting(
key="security.cors.allowed_origins",
description=(
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index 39ac35e803..7e6643ebdf 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -8,6 +8,7 @@ from langchain_community.document_transformers import BeautifulSoupTransformer
from langchain_core.language_models import BaseLLM
from ...config.search_config import QUALITY_CHECK_DDG_URLS
+from ...security.ssrf_validator import validate_url
from ...utilities.json_utils import extract_json, get_llm_response_text
@@ -102,8 +103,31 @@ class FullSearchResults:
logger.error("\n === NO VALID LINKS ===\n")
return []
- # Step 3: Download the full HTML pages for filtered URLs
- loader = AsyncChromiumLoader(urls)
+ # Step 3: SSRF-validate URLs before passing to AsyncChromiumLoader
+ # (AsyncChromiumLoader doesn't use SafeSession, so validate here)
+ safe_urls = []
+ for url in urls:
+ if validate_url(url):
+ safe_urls.append(url)
+ else:
+ logger.warning(
+ f"SSRF validation blocked URL from full content fetch: {url}. "
+ "If this is a trusted internal/private resource, note that "
+ "full content fetching currently only supports public URLs."
+ )
+
+ if not safe_urls:
+ logger.warning(
+ "All URLs were blocked by SSRF validation — returning results "
+ "without full content. This can happen when search results "
+ "point to internal/private network addresses."
+ )
+ for result in filtered_results:
+ result["full_content"] = None
+ return filtered_results
+
+ # Download the full HTML pages for validated URLs
+ loader = AsyncChromiumLoader(safe_urls)
html_docs = loader.load()
# Step 4: Process the HTML using BeautifulSoupTransformer
diff --git a/tests/security/test_ssrf_debug_hardening.py b/tests/security/test_ssrf_debug_hardening.py
new file mode 100644
index 0000000000..70075503ea
--- /dev/null
+++ b/tests/security/test_ssrf_debug_hardening.py
@@ -0,0 +1,491 @@
+"""Tests for SSRF bypass simplification and debug hardening.
+
+Verifies:
+- Only PYTEST_CURRENT_TEST bypasses SSRF validation (behavioral)
+- Removed ssrf.disable_validation setting has no effect
+- Debug mode setting is non-editable in default_settings.json
+- Full search engine validates URLs via SSRF before fetching
+"""
+
+import json
+import os
+import socket
+from unittest.mock import patch, MagicMock
+
+
+from local_deep_research.security.ssrf_validator import (
+ validate_url,
+ is_ip_blocked,
+ get_safe_url,
+)
+
+
+class TestSSRFBypassBehavior:
+ """Verify SSRF bypass only activates via PYTEST_CURRENT_TEST."""
+
+ def test_pytest_current_test_bypasses_validation(self):
+ """When PYTEST_CURRENT_TEST is set, all URLs pass validation."""
+ # PYTEST_CURRENT_TEST is already set by pytest itself, so validate_url
+ # should return True for any URL (including internal IPs).
+ assert os.environ.get("PYTEST_CURRENT_TEST"), (
+ "This test must run under pytest (PYTEST_CURRENT_TEST should be set)"
+ )
+ assert validate_url("http://169.254.169.254/latest/meta-data") is True
+
+ def test_validation_enforced_without_pytest(self):
+ """When PYTEST_CURRENT_TEST is unset, SSRF validation blocks internal IPs."""
+ with patch.dict(os.environ, {}, clear=False):
+ # Remove PYTEST_CURRENT_TEST to test real validation
+ os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ # AWS metadata endpoint should be blocked
+ assert (
+ validate_url("http://169.254.169.254/latest/meta-data")
+ is False
+ )
+ # Normal public URLs should pass
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [
+ (2, 1, 6, "", ("93.184.216.34", 0))
+ ]
+ assert validate_url("http://example.com") is True
+ finally:
+ # Restore — pytest will also re-set this naturally
+ os.environ["PYTEST_CURRENT_TEST"] = (
+ "tests/security/test_ssrf_debug_hardening.py"
+ )
+
+ def test_testing_env_var_does_not_bypass(self):
+ """Setting TESTING=true should NOT bypass SSRF validation."""
+ with patch.dict(os.environ, {"TESTING": "true"}, clear=False):
+ os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ assert (
+ validate_url("http://169.254.169.254/latest/meta-data")
+ is False
+ )
+ finally:
+ os.environ["PYTEST_CURRENT_TEST"] = (
+ "tests/security/test_ssrf_debug_hardening.py"
+ )
+
+
+class TestRemovedSSRFDisableValidationSetting:
+ """Verify the removed ssrf.disable_validation setting has no effect."""
+
+ def test_ldr_ssrf_disable_validation_env_var_has_no_effect(self):
+ """LDR_SECURITY_SSRF_DISABLE_VALIDATION env var must not bypass validation."""
+ with patch.dict(
+ os.environ,
+ {"LDR_SECURITY_SSRF_DISABLE_VALIDATION": "true"},
+ clear=False,
+ ):
+ os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ assert (
+ validate_url("http://169.254.169.254/latest/meta-data")
+ is False
+ )
+ assert validate_url("http://192.168.1.1/admin") is False
+ finally:
+ os.environ["PYTEST_CURRENT_TEST"] = (
+ "tests/security/test_ssrf_debug_hardening.py"
+ )
+
+ def test_ssrf_disable_validation_key_not_in_registry(self):
+ """ssrf.disable_validation must not be registered in the env registry."""
+ from local_deep_research.settings.env_registry import registry
+
+ assert not registry.is_env_only("security.ssrf.disable_validation"), (
+ "security.ssrf.disable_validation must NOT be in the env registry"
+ )
+
+ def test_dns_failure_fails_closed(self):
+ """DNS resolution failure must block the URL (fail-closed)."""
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ side_effect=socket.gaierror("DNS resolution failed"),
+ ):
+ assert (
+ validate_url("http://nonexistent-host.example.com")
+ is False
+ )
+ finally:
+ os.environ["PYTEST_CURRENT_TEST"] = (
+ "tests/security/test_ssrf_debug_hardening.py"
+ )
+
+
+class TestDebugModeNonEditable:
+ """Verify debug mode setting cannot be changed by users."""
+
+ def test_debug_setting_not_editable(self):
+ """app.debug setting should have editable=false."""
+ settings_path = "src/local_deep_research/defaults/default_settings.json"
+ with open(settings_path) as f:
+ settings = json.load(f)
+
+ debug_setting = settings.get("app.debug", {})
+ assert debug_setting.get("editable") is False, (
+ "app.debug must not be editable from the UI"
+ )
+
+
+class TestFullSearchSSRFValidation:
+ """Verify full search engine validates URLs before fetching content."""
+
+ def test_ssrf_blocked_urls_logged_and_skipped(self):
+ """URLs that fail SSRF validation should be logged and not fetched."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = MagicMock()
+ mock_web_search = MagicMock()
+ mock_web_search.invoke.return_value = [
+ {"link": "http://169.254.169.254/secret", "title": "bad"},
+ {"link": "http://example.com/good", "title": "good"},
+ ]
+
+ fs = FullSearchResults(llm=mock_llm, web_search=[mock_web_search])
+ fs.web_search = mock_web_search
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url"
+ ) as mock_validate,
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader,
+ ):
+ # First URL blocked, second passes
+ mock_validate.side_effect = [False, True]
+ mock_doc = MagicMock()
+ mock_doc.metadata = {"source": "http://example.com/good"}
+ mock_doc.page_content = "<p>Content</p>"
+ mock_loader.return_value.load.return_value = [mock_doc]
+
+ results = fs.run("test query")
+
+ # AsyncChromiumLoader should only receive the safe URL
+ mock_loader.assert_called_once()
+ loaded_urls = mock_loader.call_args[0][0]
+ assert "http://169.254.169.254/secret" not in loaded_urls
+ assert "http://example.com/good" in loaded_urls
+
+ # Both results should be returned (blocked one gets full_content=None)
+ assert len(results) == 2
+
+ def test_blocked_url_gets_none_safe_url_gets_content(self):
+ """Blocked results must have full_content=None; safe results get real content."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = MagicMock()
+ mock_web_search = MagicMock()
+ mock_web_search.invoke.return_value = [
+ {"link": "http://169.254.169.254/secret", "title": "bad"},
+ {"link": "http://example.com/good", "title": "good"},
+ ]
+
+ fs = FullSearchResults(llm=mock_llm, web_search=[mock_web_search])
+ fs.web_search = mock_web_search
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url"
+ ) as mock_validate,
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader,
+ ):
+ mock_validate.side_effect = [False, True]
+
+ mock_doc = MagicMock()
+ mock_doc.metadata = {"source": "http://example.com/good"}
+ mock_doc.page_content = "<p>Safe content</p>"
+ mock_loader.return_value.load.return_value = [mock_doc]
+
+ results = fs.run("test query")
+
+ bad = next(
+ r
+ for r in results
+ if r["link"] == "http://169.254.169.254/secret"
+ )
+ good = next(
+ r for r in results if r["link"] == "http://example.com/good"
+ )
+
+ # Blocked URL must have None content
+ assert bad["full_content"] is None
+ # Safe URL must have content attached
+ assert good["full_content"] is not None
+
+ def test_validate_url_called_with_raw_url(self):
+ """validate_url must receive the exact URL from search results."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ raw_url = "http://169.254.169.254:80/secret"
+ mock_web_search = MagicMock()
+ mock_web_search.invoke.return_value = [
+ {"link": raw_url, "title": "bad"}
+ ]
+
+ fs = FullSearchResults(llm=MagicMock(), web_search=[MagicMock()])
+ fs.web_search = mock_web_search
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url"
+ ) as mock_validate,
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ),
+ ):
+ mock_validate.return_value = False
+ fs.run("test")
+ mock_validate.assert_called_once_with(raw_url)
+
+ def test_all_urls_blocked_returns_results_without_content(self):
+ """When all URLs are blocked, results are returned with full_content=None."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = MagicMock()
+ mock_web_search = MagicMock()
+ mock_web_search.invoke.return_value = [
+ {"link": "http://10.0.0.1/internal", "title": "internal"},
+ ]
+
+ fs = FullSearchResults(llm=mock_llm, web_search=[mock_web_search])
+ fs.web_search = mock_web_search
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader,
+ ):
+ results = fs.run("test query")
+
+ # Should NOT have called AsyncChromiumLoader
+ mock_loader.assert_not_called()
+ # Results should still be returned with full_content=None
+ assert len(results) == 1
+ assert results[0]["full_content"] is None
+
+
+# ---------------------------------------------------------------------------
+# Group 1: CRITICAL — IPv4-Mapped IPv6 Bypass
+# ---------------------------------------------------------------------------
+class TestIPv4MappedIPv6Bypass:
+ """IPv4-mapped IPv6 addresses (::ffff:x.x.x.x) must be unwrapped and blocked."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ """Run validate_url with PYTEST_CURRENT_TEST removed."""
+ saved = os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ return validate_url(url, **kwargs)
+ finally:
+ if saved is not None:
+ os.environ["PYTEST_CURRENT_TEST"] = saved
+
+ def test_ipv4_mapped_ipv6_aws_metadata_blocked(self):
+ """::ffff:169.254.169.254 must be blocked (AWS credential theft via IPv6)."""
+ assert is_ip_blocked("::ffff:169.254.169.254") is True
+
+ def test_ipv4_mapped_ipv6_loopback_blocked(self):
+ """::ffff:127.0.0.1 must be blocked (localhost SSRF via IPv6)."""
+ assert is_ip_blocked("::ffff:127.0.0.1") is True
+
+ def test_ipv4_mapped_ipv6_private_ip_blocked(self):
+ """::ffff:192.168.1.1 must be blocked (internal network via IPv6)."""
+ assert is_ip_blocked("::ffff:192.168.1.1") is True
+
+ def test_ipv4_mapped_ipv6_dns_resolution_blocked(self):
+ """DNS returning ::ffff:127.0.0.1 must be caught."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [
+ (socket.AF_INET6, 1, 6, "", ("::ffff:127.0.0.1", 0, 0, 0))
+ ]
+ assert (
+ self._validate_without_pytest("http://evil.example.com/")
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# Group 2: HIGH — Alternative IP Notation Defense-in-Depth
+# ---------------------------------------------------------------------------
+class TestAlternativeIPNotations:
+ """Alternative IP representations must not bypass SSRF checks."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ saved = os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ return validate_url(url, **kwargs)
+ finally:
+ if saved is not None:
+ os.environ["PYTEST_CURRENT_TEST"] = saved
+
+ def test_decimal_dword_loopback_blocked(self):
+ """Decimal/dword notation (2130706433 = 127.0.0.1) must be blocked."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("127.0.0.1", 0))]
+ assert self._validate_without_pytest("http://2130706433/") is False
+
+ def test_hex_ip_aws_metadata_blocked(self):
+ """Hex notation (0xa9fea9fe = 169.254.169.254) must be blocked."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("169.254.169.254", 0))]
+ assert self._validate_without_pytest("http://0xa9fea9fe/") is False
+
+ def test_octal_ip_loopback_blocked(self):
+ """Octal notation (0177.0.0.1 = 127.0.0.1) must be blocked."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("127.0.0.1", 0))]
+ assert self._validate_without_pytest("http://0177.0.0.1/") is False
+
+ def test_zero_address_blocked(self):
+ """http://0/ resolving to 0.0.0.0 must be blocked."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("0.0.0.0", 0))]
+ assert self._validate_without_pytest("http://0/") is False
+
+
+# ---------------------------------------------------------------------------
+# Group 3: MEDIUM — URL Parsing Edge Cases
+# ---------------------------------------------------------------------------
+class TestURLParsingEdgeCases:
+ """URL parsing quirks must not create SSRF bypass opportunities."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ saved = os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ return validate_url(url, **kwargs)
+ finally:
+ if saved is not None:
+ os.environ["PYTEST_CURRENT_TEST"] = saved
+
+ def test_leading_whitespace_blocked(self):
+ """Leading whitespace must not bypass validation (CVE-2023-24329 regression)."""
+ assert (
+ self._validate_without_pytest(" http://169.254.169.254/") is False
+ )
+
+ def test_scheme_case_insensitive(self):
+ """Mixed-case scheme (HTTP://) must still validate the IP."""
+ assert self._validate_without_pytest("HTTP://169.254.169.254/") is False
+
+ def test_url_without_scheme_rejected(self):
+ """Scheme-less URL (//host/path) must be rejected."""
+ assert (
+ self._validate_without_pytest("//169.254.169.254/latest") is False
+ )
+
+ def test_crlf_injection_blocked(self):
+ r"""URL with CRLF (\r\n) must be blocked."""
+ assert (
+ self._validate_without_pytest(
+ "http://169.254.169.254\r\nX-Injected: true"
+ )
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# Group 4: MEDIUM — Debug Mode Completeness
+# ---------------------------------------------------------------------------
+class TestDebugModeCompleteness:
+ """Additional debug mode setting integrity checks."""
+
+ def test_debug_setting_value_defaults_to_false(self):
+ """app.debug default value must be False."""
+ settings_path = "src/local_deep_research/defaults/default_settings.json"
+ with open(settings_path) as f:
+ settings = json.load(f)
+ assert settings["app.debug"]["value"] is False
+
+ def test_debug_description_mentions_env_var(self):
+ """app.debug description must mention the LDR_APP_DEBUG env var."""
+ settings_path = "src/local_deep_research/defaults/default_settings.json"
+ with open(settings_path) as f:
+ settings = json.load(f)
+ assert "LDR_APP_DEBUG" in settings["app.debug"]["description"]
+
+
+# ---------------------------------------------------------------------------
+# Group 5: LOW — get_safe_url Coverage
+# ---------------------------------------------------------------------------
+class TestGetSafeUrl:
+ """Coverage for the get_safe_url helper."""
+
+ def _validate_without_pytest(self, url, default=None):
+ saved = os.environ.pop("PYTEST_CURRENT_TEST", None)
+ try:
+ return get_safe_url(url, default=default)
+ finally:
+ if saved is not None:
+ os.environ["PYTEST_CURRENT_TEST"] = saved
+
+ def test_returns_default_for_blocked_url(self):
+ """Blocked URLs must return the default value."""
+ result = self._validate_without_pytest(
+ "http://169.254.169.254/", default="https://fallback.example.com"
+ )
+ assert result == "https://fallback.example.com"
+
+ def test_returns_url_for_safe_url(self):
+ """Safe URLs must be returned as-is."""
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+ ) as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("93.184.216.34", 0))]
+ result = self._validate_without_pytest("http://example.com/page")
+ assert result == "http://example.com/page"
+
+ def test_returns_default_for_none(self):
+ """None input must return the default without raising."""
+ result = self._validate_without_pytest(
+ None, default="https://default.com"
+ )
+ assert result == "https://default.com"
diff --git a/tests/security/test_ssrf_validator.py b/tests/security/test_ssrf_validator.py
index c47432a7b5..09138fed88 100644
--- a/tests/security/test_ssrf_validator.py
+++ b/tests/security/test_ssrf_validator.py
@@ -34,28 +34,19 @@ def disable_ssrf_test_bypass():
Disable the test mode bypass for SSRF validation.
The SSRF validator bypasses validation when PYTEST_CURRENT_TEST is set.
- We need to mock the os.environ.get calls to test the actual validation.
+ We need to mock os.environ.get to return None for PYTEST_CURRENT_TEST
+ so the actual validation logic runs.
"""
- with (
- patch(
- "local_deep_research.security.ssrf_validator.os.environ.get"
- ) as mock_env_get,
- patch(
- "local_deep_research.security.ssrf_validator.get_env_setting"
- ) as mock_get_env_setting,
- ):
- # Return empty string for test bypass checks (so .lower() works)
- # Return None for PYTEST_CURRENT_TEST (it's checked for truthiness)
+ with patch(
+ "local_deep_research.security.ssrf_validator.os.environ.get"
+ ) as mock_env_get:
+
def mock_environ_get(key, default=""):
- if key == "TESTING":
- return "" # Empty string so .lower() works
if key == "PYTEST_CURRENT_TEST":
return None # None is falsy, bypasses the check
return default
mock_env_get.side_effect = mock_environ_get
- # Return False for disable_validation setting
- mock_get_env_setting.return_value = False
yield