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: remove PYTEST_CURRENT_TEST bypass from SSRF validate_url() (#2956)

LearningCircuit13faa9ddb045
diff --git a/pdm.lock b/pdm.lock
index d3e799cd95..69ad8709c4 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -1995,16 +1995,16 @@ files = [
[[package]]
name = "jaraco-context"
-version = "6.1.1"
-requires_python = ">=3.9"
+version = "6.1.2"
+requires_python = ">=3.10"
summary = "Useful decorators and context managers"
groups = ["default"]
dependencies = [
"backports-tarfile; python_version < \"3.12\"",
]
files = [
- {file = "jaraco_context-6.1.1-py3-none-any.whl", hash = "sha256:0df6a0287258f3e364072c3e40d5411b20cafa30cb28c4839d24319cecf9f808"},
- {file = "jaraco_context-6.1.1.tar.gz", hash = "sha256:bc046b2dc94f1e5532bd02402684414575cc11f565d929b6563125deb0a6e581"},
+ {file = "jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535"},
+ {file = "jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3"},
]
[[package]]
@@ -2127,13 +2127,13 @@ files = [
[[package]]
name = "jsonpointer"
-version = "3.0.0"
-requires_python = ">=3.7"
+version = "3.1.0"
+requires_python = ">=3.10"
summary = "Identify specific nodes in a JSON document (RFC 6901) "
groups = ["default"]
files = [
- {file = "jsonpointer-3.0.0-py2.py3-none-any.whl", hash = "sha256:13e088adc14fca8b6aa8177c044e12701e6ad4b28ff10e65f2267a90109c9942"},
- {file = "jsonpointer-3.0.0.tar.gz", hash = "sha256:2b2d729f2091522d61c3b31f82e11870f60b68f43fbc705cb76bf4b832af59ef"},
+ {file = "jsonpointer-3.1.0-py3-none-any.whl", hash = "sha256:f82aa0f745001f169b96473348370b43c3f581446889c41c807bab1db11c8e7b"},
+ {file = "jsonpointer-3.1.0.tar.gz", hash = "sha256:f9b39abd59ba8c1de8a4ff16141605d2a8dacc4dd6cf399672cf237bfe47c211"},
]
[[package]]
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index ed65162e16..2fd767a257 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -6,7 +6,6 @@ by blocking requests to internal/private networks and enforcing safe schemes.
"""
import ipaddress
-import os
import socket
from urllib.parse import urlparse
from typing import Optional
@@ -129,21 +128,7 @@ def validate_url(
Returns:
True if URL is safe, False otherwise
-
- Note:
- SSRF validation is automatically bypassed during pytest runs via
- the PYTEST_CURRENT_TEST environment variable (set by pytest).
"""
- # Security trade-off: This bypasses ALL SSRF validation during pytest
- # runs. PYTEST_CURRENT_TEST is set automatically by pytest and is not
- # expected in production. If this bypass is ever removed, tests that
- # call safe_get/safe_post with real URLs will need to mock
- # validate_url() or use responses/pytest-httpserver instead.
- pytest_current_test = os.environ.get("PYTEST_CURRENT_TEST")
- if pytest_current_test:
- logger.debug(f"SSRF validation bypassed in pytest for URL: {url}")
- return True
-
try:
parsed = urlparse(url)
diff --git a/tests/config/test_llm_config_providers.py b/tests/config/test_llm_config_providers.py
index fa0d7d2272..c3572d3abb 100644
--- a/tests/config/test_llm_config_providers.py
+++ b/tests/config/test_llm_config_providers.py
@@ -143,9 +143,9 @@ class TestProviderInstantiation:
),
patch(
"local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=lambda key, *a, **kw: str(bad_model)
- if "model_path" in key
- else None,
+ side_effect=lambda key, *a, **kw: (
+ str(bad_model) if "model_path" in key else None
+ ),
),
patch(
"local_deep_research.security.path_validator.PathValidator.validate_model_path",
diff --git a/tests/content_fetcher/test_mcp_integration.py b/tests/content_fetcher/test_mcp_integration.py
index 5cb66e9443..cfbcddb211 100644
--- a/tests/content_fetcher/test_mcp_integration.py
+++ b/tests/content_fetcher/test_mcp_integration.py
@@ -96,7 +96,13 @@ class TestMCPDownloadContentTool:
@patch(
"local_deep_research.content_fetcher.fetcher.ContentFetcher._get_downloader"
)
- def test_execute_download_content_timeout(self, mock_get_downloader):
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ def test_execute_download_content_timeout(
+ self, mock_validate, mock_get_downloader
+ ):
"""Test handling of timeout during download."""
mock_downloader = MagicMock()
mock_downloader.download_with_result.side_effect = TimeoutError(
diff --git a/tests/security/test_ssrf_debug_hardening.py b/tests/security/test_ssrf_debug_hardening.py
index 70075503ea..8976c64dcb 100644
--- a/tests/security/test_ssrf_debug_hardening.py
+++ b/tests/security/test_ssrf_debug_hardening.py
@@ -20,56 +20,27 @@ from local_deep_research.security.ssrf_validator import (
)
-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"
- )
+class TestSSRFValidationAlwaysActive:
+ """Verify SSRF validation is always active (no test bypass)."""
+
+ def test_aws_metadata_blocked(self):
+ """AWS metadata endpoint should be blocked."""
+ assert validate_url("http://169.254.169.254/latest/meta-data") is False
+
+ def test_public_url_allowed(self):
+ """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
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"
- )
+ assert (
+ validate_url("http://169.254.169.254/latest/meta-data") is False
+ )
class TestRemovedSSRFDisableValidationSetting:
@@ -82,17 +53,10 @@ class TestRemovedSSRFDisableValidationSetting:
{"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"
- )
+ assert (
+ validate_url("http://169.254.169.254/latest/meta-data") is False
+ )
+ assert validate_url("http://192.168.1.1/admin") is False
def test_ssrf_disable_validation_key_not_in_registry(self):
"""ssrf.disable_validation must not be registered in the env registry."""
@@ -104,21 +68,11 @@ class TestRemovedSSRFDisableValidationSetting:
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"
- )
+ 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
class TestDebugModeNonEditable:
@@ -310,15 +264,6 @@ class TestFullSearchSSRFValidation:
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
@@ -339,10 +284,7 @@ class TestIPv4MappedIPv6Bypass:
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
- )
+ assert validate_url("http://evil.example.com/") is False
# ---------------------------------------------------------------------------
@@ -351,21 +293,13 @@ class TestIPv4MappedIPv6Bypass:
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
+ assert validate_url("http://2130706433/") is False
def test_hex_ip_aws_metadata_blocked(self):
"""Hex notation (0xa9fea9fe = 169.254.169.254) must be blocked."""
@@ -373,7 +307,7 @@ class TestAlternativeIPNotations:
"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
+ assert validate_url("http://0xa9fea9fe/") is False
def test_octal_ip_loopback_blocked(self):
"""Octal notation (0177.0.0.1 = 127.0.0.1) must be blocked."""
@@ -381,7 +315,7 @@ class TestAlternativeIPNotations:
"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
+ assert validate_url("http://0177.0.0.1/") is False
def test_zero_address_blocked(self):
"""http://0/ resolving to 0.0.0.0 must be blocked."""
@@ -389,7 +323,7 @@ class TestAlternativeIPNotations:
"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
+ assert validate_url("http://0/") is False
# ---------------------------------------------------------------------------
@@ -398,37 +332,22 @@ class TestAlternativeIPNotations:
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
- )
+ assert validate_url(" 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
+ assert validate_url("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
- )
+ assert validate_url("//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
+ validate_url("http://169.254.169.254\r\nX-Injected: true") is False
)
@@ -459,17 +378,9 @@ class TestDebugModeCompleteness:
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(
+ result = get_safe_url(
"http://169.254.169.254/", default="https://fallback.example.com"
)
assert result == "https://fallback.example.com"
@@ -480,12 +391,10 @@ class TestGetSafeUrl:
"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")
+ result = get_safe_url("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"
- )
+ result = get_safe_url(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 09138fed88..8d886e0948 100644
--- a/tests/security/test_ssrf_validator.py
+++ b/tests/security/test_ssrf_validator.py
@@ -28,28 +28,6 @@ from tests.test_utils import add_src_to_path
add_src_to_path()
[email protected](autouse=True)
-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 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:
-
- def mock_environ_get(key, default=""):
- if key == "PYTEST_CURRENT_TEST":
- return None # None is falsy, bypasses the check
- return default
-
- mock_env_get.side_effect = mock_environ_get
- yield
-
-
class TestIsIpBlocked:
"""Test the is_ip_blocked function."""
diff --git a/tests/security/test_ssrf_validator_behavior.py b/tests/security/test_ssrf_validator_behavior.py
index 940672dd22..e4602cbf1b 100644
--- a/tests/security/test_ssrf_validator_behavior.py
+++ b/tests/security/test_ssrf_validator_behavior.py
@@ -270,10 +270,15 @@ class TestGetSafeUrl:
def test_returns_url_if_safe(self):
"""Returns URL if it's safe."""
+ from unittest.mock import patch
+
from local_deep_research.security.ssrf_validator import get_safe_url
- result = get_safe_url("https://example.com")
- # In test mode, SSRF validation is bypassed
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ result = get_safe_url("https://example.com")
assert result == "https://example.com"
def test_returns_none_for_empty(self):
@@ -298,26 +303,23 @@ class TestGetSafeUrl:
assert result is None
-class TestValidateUrlBypass:
- """Tests for validate_url test mode bypass."""
+class TestValidateUrlNoBypass:
+ """Tests that validate_url performs real validation (no test bypass)."""
- def test_bypassed_in_test_mode(self, monkeypatch):
- """validate_url is bypassed in test mode."""
+ def test_localhost_blocked_by_default(self):
+ """validate_url blocks localhost by default."""
from local_deep_research.security.ssrf_validator import validate_url
- # In test environment, validation should be bypassed
- # and return True for any URL
result = validate_url("http://127.0.0.1")
- # When PYTEST_CURRENT_TEST is set, returns True
- assert result is True
+ assert result is False
- def test_testing_env_bypasses(self, monkeypatch):
- """TESTING=true environment variable bypasses validation."""
+ def test_testing_env_does_not_bypass(self, monkeypatch):
+ """TESTING=true environment variable does NOT bypass validation."""
from local_deep_research.security.ssrf_validator import validate_url
monkeypatch.setenv("TESTING", "true")
result = validate_url("http://127.0.0.1")
- assert result is True
+ assert result is False
class TestAllowLocalhostFlag:
diff --git a/tests/security/test_ssrf_validator_extended.py b/tests/security/test_ssrf_validator_extended.py
index 296c3b87a9..fa04e1e2b3 100644
--- a/tests/security/test_ssrf_validator_extended.py
+++ b/tests/security/test_ssrf_validator_extended.py
@@ -1,13 +1,12 @@
"""
Extended tests for the SSRF validator module.
-Provides comprehensive coverage of is_ip_blocked, get_safe_url, and module
-constants (AWS_METADATA_IP, ALLOWED_SCHEMES). The validate_url function is
-bypassed when PYTEST_CURRENT_TEST is set, so its SSRF blocking logic is
-exercised indirectly through is_ip_blocked; the get_safe_url tests cover
-the None/empty handling path and the pass-through behaviour in test mode.
+Provides comprehensive coverage of is_ip_blocked, get_safe_url, validate_url,
+and module constants (AWS_METADATA_IP, ALLOWED_SCHEMES).
"""
+from unittest.mock import patch
+
import pytest
from local_deep_research.security.ssrf_validator import (
@@ -568,55 +567,64 @@ class TestGetSafeUrlNoneAndEmpty:
class TestGetSafeUrlPassthrough:
- """In test mode (PYTEST_CURRENT_TEST set), validate_url returns True
- so get_safe_url passes through non-empty URLs."""
+ """get_safe_url passes through valid URLs and blocks unsafe ones."""
def test_non_empty_url_returned(self):
- result = get_safe_url("https://example.com")
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ result = get_safe_url("https://example.com")
assert result == "https://example.com"
def test_http_url_returned(self):
- result = get_safe_url("http://example.com")
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ result = get_safe_url("http://example.com")
assert result == "http://example.com"
def test_url_with_path_returned(self):
- result = get_safe_url("https://example.com/path?q=1")
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ result = get_safe_url("https://example.com/path?q=1")
assert result == "https://example.com/path?q=1"
- def test_localhost_url_returned_in_test_mode(self):
- """validate_url is bypassed in test mode, so even localhost passes."""
- result = get_safe_url("http://127.0.0.1:8080")
- assert result == "http://127.0.0.1:8080"
+ def test_localhost_url_returns_default(self):
+ """validate_url blocks localhost, so get_safe_url returns default."""
+ result = get_safe_url("http://127.0.0.1:8080", default="safe")
+ assert result == "safe"
def test_default_not_used_for_valid_url(self):
- result = get_safe_url(
- "https://example.com", default="https://fallback.com"
- )
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ result = get_safe_url(
+ "https://example.com", default="https://fallback.com"
+ )
assert result == "https://example.com"
# ---------------------------------------------------------------------------
-# validate_url -- test mode bypass
+# validate_url -- real validation (no test bypass)
# ---------------------------------------------------------------------------
-class TestValidateUrlTestModeBypass:
- """Confirm validate_url is bypassed in the test environment."""
-
- def test_returns_true_for_public_url(self):
- """Public URL returns True in test mode."""
- assert validate_url("https://example.com") is True
+class TestValidateUrlRealValidation:
+ """Confirm validate_url performs real SSRF validation."""
- def test_returns_true_for_private_ip_url(self):
- """Private IP URL returns True in test mode (bypassed)."""
- assert validate_url("http://192.168.1.1") is True
+ def test_blocks_private_ip_url(self):
+ """Private IP URL is blocked."""
+ assert validate_url("http://192.168.1.1") is False
- def test_returns_true_for_localhost_url(self):
- """Localhost URL returns True in test mode (bypassed)."""
- assert validate_url("http://127.0.0.1") is True
+ def test_blocks_localhost_url(self):
+ """Localhost URL is blocked."""
+ assert validate_url("http://127.0.0.1") is False
- def test_returns_true_for_aws_metadata_url(self):
- """AWS metadata URL returns True in test mode (bypassed).
- This demonstrates why is_ip_blocked is the correct unit to test
- for SSRF blocking behaviour."""
- assert validate_url("http://169.254.169.254/latest/meta-data") is True
+ def test_blocks_aws_metadata_url(self):
+ """AWS metadata URL is blocked."""
+ assert validate_url("http://169.254.169.254/latest/meta-data") is False
diff --git a/tests/security/test_ssrf_validator_high_value.py b/tests/security/test_ssrf_validator_high_value.py
index 8a9478871a..5d22482333 100644
--- a/tests/security/test_ssrf_validator_high_value.py
+++ b/tests/security/test_ssrf_validator_high_value.py
@@ -1,6 +1,5 @@
"""High-value tests for security/ssrf_validator.py - SSRF Prevention."""
-import os
import socket
from unittest.mock import patch
@@ -139,103 +138,67 @@ class TestIsIpBlockedPublicAndInvalid:
class TestValidateUrlScheme:
"""Scheme validation."""
- def _validate_without_pytest(self, url, **kwargs):
- """Helper to validate without PYTEST_CURRENT_TEST bypass."""
- env = os.environ.copy()
- env.pop("PYTEST_CURRENT_TEST", None)
- with patch.dict(os.environ, env, clear=True):
- return validate_url(url, **kwargs)
-
def test_ftp_scheme_rejected(self):
- assert self._validate_without_pytest("ftp://example.com/file") is False
+ assert validate_url("ftp://example.com/file") is False
def test_file_scheme_rejected(self):
- assert self._validate_without_pytest("file:///etc/passwd") is False
+ assert validate_url("file:///etc/passwd") is False
def test_javascript_scheme_rejected(self):
- assert self._validate_without_pytest("javascript:alert(1)") is False
+ assert validate_url("javascript:alert(1)") is False
class TestValidateUrlHostname:
"""Hostname and IP-based URL validation."""
- def _validate_without_pytest(self, url, **kwargs):
- """Helper to validate without PYTEST_CURRENT_TEST bypass."""
- env = os.environ.copy()
- env.pop("PYTEST_CURRENT_TEST", None)
- with patch.dict(os.environ, env, clear=True):
- return validate_url(url, **kwargs)
-
def test_missing_hostname_rejected(self):
- assert self._validate_without_pytest("http://") is False
+ assert validate_url("http://") is False
def test_ip_loopback_url_blocked(self):
- assert self._validate_without_pytest("http://127.0.0.1/admin") is False
+ assert validate_url("http://127.0.0.1/admin") is False
def test_ip_private_url_blocked(self):
- assert self._validate_without_pytest("http://192.168.1.1/") is False
+ assert validate_url("http://192.168.1.1/") is False
def test_aws_metadata_url_blocked(self):
- assert (
- self._validate_without_pytest(
- "http://169.254.169.254/latest/meta-data/"
- )
- is False
- )
+ assert validate_url("http://169.254.169.254/latest/meta-data/") is False
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_hostname_resolving_to_public_ip_allowed(self, mock_dns):
mock_dns.return_value = [
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", 0))
]
- assert self._validate_without_pytest("http://example.com") is True
+ assert validate_url("http://example.com") is True
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_hostname_resolving_to_private_ip_blocked(self, mock_dns):
mock_dns.return_value = [
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0))
]
- assert self._validate_without_pytest("http://internal.corp") is False
+ assert validate_url("http://internal.corp") is False
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_dns_failure_blocks_url(self, mock_dns):
mock_dns.side_effect = socket.gaierror("Name resolution failed")
- assert self._validate_without_pytest("http://nonexistent.test") is False
+ assert validate_url("http://nonexistent.test") is False
class TestValidateUrlFlagPassthrough:
"""Flag pass-through to is_ip_blocked."""
- def _validate_without_pytest(self, url, **kwargs):
- """Helper to validate without PYTEST_CURRENT_TEST bypass."""
- env = os.environ.copy()
- env.pop("PYTEST_CURRENT_TEST", None)
- with patch.dict(os.environ, env, clear=True):
- return validate_url(url, **kwargs)
-
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_allow_localhost_passes_loopback(self, mock_dns):
mock_dns.return_value = [
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))
]
- assert (
- self._validate_without_pytest(
- "http://127.0.0.1/", allow_localhost=True
- )
- is True
- )
+ assert validate_url("http://127.0.0.1/", allow_localhost=True) is True
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_allow_private_ips_passes_private(self, mock_dns):
mock_dns.return_value = [
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0))
]
- assert (
- self._validate_without_pytest(
- "http://10.0.0.1/", allow_private_ips=True
- )
- is True
- )
+ assert validate_url("http://10.0.0.1/", allow_private_ips=True) is True
@patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
def test_multi_address_dns_one_private_blocked(self, mock_dns):
@@ -243,7 +206,7 @@ class TestValidateUrlFlagPassthrough:
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", 0)),
(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0)),
]
- assert self._validate_without_pytest("http://dual.example.com") is False
+ assert validate_url("http://dual.example.com") is False
class TestIsIpBlockedZeroNetwork:
@@ -257,20 +220,16 @@ class TestIsIpBlockedZeroNetwork:
assert is_ip_blocked("0.0.0.1", allow_private_ips=True) is True
-class TestValidateUrlPytestBypass:
- """PYTEST_CURRENT_TEST bypass logic."""
+class TestValidateUrlNoBypass:
+ """Verify validate_url performs real validation (no test bypass)."""
- def test_pytest_env_var_bypasses_validation(self):
- with patch.dict(
- os.environ, {"PYTEST_CURRENT_TEST": "test_foo.py::test_bar"}
- ):
- assert validate_url("ftp://evil.com") is True
+ def test_ftp_scheme_blocked(self):
+ assert validate_url("ftp://evil.com") is False
- def test_no_pytest_env_does_not_bypass(self):
- env = os.environ.copy()
- env.pop("PYTEST_CURRENT_TEST", None)
- with patch.dict(os.environ, env, clear=True):
- assert validate_url("ftp://evil.com") is False
+ def test_https_public_url_allowed(self):
+ with patch("socket.getaddrinfo") as mock_dns:
+ mock_dns.return_value = [(2, 1, 6, "", ("93.184.216.34", 0))]
+ assert validate_url("https://example.com") is True
# ---------------------------------------------------------------------------