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.

test(security): SSRF edge-case coverage and weak-test cleanup (#4062)

LearningCircuit41ee83c54c3b
diff --git a/tests/security/test_ssrf_debug_hardening.py b/tests/security/test_ssrf_debug_hardening.py
index 6e37d81d99..b4d99e16e0 100644
--- a/tests/security/test_ssrf_debug_hardening.py
+++ b/tests/security/test_ssrf_debug_hardening.py
@@ -94,7 +94,13 @@ 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."""
+ """URLs that fail SSRF validation should be logged and not fetched.
+
+ Exercises the real ssrf_validator (no validate_url mock) so a
+ regression in metadata-IP blocking would surface here too. The
+ bad URL is an IP literal that is rejected without DNS, and the
+ good URL has socket.getaddrinfo mocked to a public IP.
+ """
from local_deep_research.web_search_engines.engines.full_search import (
FullSearchResults,
)
@@ -114,31 +120,32 @@ class TestFullSearchSSRFValidation:
False,
),
patch(
- "local_deep_research.web_search_engines.engines.full_search.validate_url"
- ) as mock_validate,
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
patch(
"local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract"
) as mock_batch,
):
- # First URL blocked, second passes
- mock_validate.side_effect = [False, True]
mock_batch.return_value = {
"http://example.com/good": "Safe content",
}
results = fs.run("test query")
- # batch_fetch_and_extract should only receive the safe URL
mock_batch.assert_called_once()
fetched_urls = mock_batch.call_args[0][0]
assert "http://169.254.169.254/secret" not in fetched_urls
assert "http://example.com/good" in fetched_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."""
+ """Blocked results must have full_content=None; safe results get real content.
+
+ Exercises the real ssrf_validator so removing the
+ ALWAYS_BLOCKED_METADATA_IPS check in ssrf_validator.py would
+ cause this test to fail (bad URL would no longer be blocked).
+ """
from local_deep_research.web_search_engines.engines.full_search import (
FullSearchResults,
)
@@ -158,13 +165,13 @@ class TestFullSearchSSRFValidation:
False,
),
patch(
- "local_deep_research.web_search_engines.engines.full_search.validate_url"
- ) as mock_validate,
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
patch(
"local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract"
) as mock_batch,
):
- mock_validate.side_effect = [False, True]
mock_batch.return_value = {
"http://example.com/good": "Safe content",
}
@@ -180,9 +187,7 @@ class TestFullSearchSSRFValidation:
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):
@@ -214,7 +219,11 @@ class TestFullSearchSSRFValidation:
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."""
+ """When all URLs are blocked, results are returned with full_content=None.
+
+ Uses a real private IP literal (10.0.0.1) so the real SSRF
+ validator does the blocking — no validate_url mock needed.
+ """
from local_deep_research.web_search_engines.engines.full_search import (
FullSearchResults,
)
@@ -228,19 +237,12 @@ class TestFullSearchSSRFValidation:
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,
- ),
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
):
results = fs.run("test query")
- # Results should still be returned with full_content=None
assert len(results) == 1
assert results[0]["full_content"] is None
diff --git a/tests/security/test_ssrf_redirect_bypass.py b/tests/security/test_ssrf_redirect_bypass.py
index c626bc8d6f..30c39f65e0 100644
--- a/tests/security/test_ssrf_redirect_bypass.py
+++ b/tests/security/test_ssrf_redirect_bypass.py
@@ -129,32 +129,44 @@ class TestSafeGetRedirectFollowing:
result = safe_get("https://example.com", allow_redirects=True)
assert result.status_code == 200, f"Failed for status {code}"
- def test_each_hop_validated(self, mock_validate_url):
- """Each redirect hop is validated against SSRF rules."""
+ def test_each_hop_validated(self):
+ """Each redirect hop is validated by the real SSRF validator.
+
+ Replaces a prior version that asserted only on a mocked
+ validate_url's call_count and call_args list — that pattern
+ passed even if per-hop validation was silently disabled, as long
+ as the mock was called the right number of times.
+
+ Here the first two hops resolve to public IPs (via DNS mock) and
+ the third hop is a private IP literal. A working per-hop
+ validator catches the third hop and raises before requests.get
+ is ever called for it.
+ """
resp1 = _make_response(
302, {"Location": "https://hop2.com"}, "https://example.com"
)
resp2 = _make_response(
- 302, {"Location": "https://hop3.com"}, "https://hop2.com"
+ 302, {"Location": "http://10.0.0.5/internal"}, "https://hop2.com"
)
- final = _make_response(200)
- with patch(
- "local_deep_research.security.safe_requests.requests.get",
- side_effect=[resp1, resp2, final],
+ with (
+ patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
+ patch(
+ "local_deep_research.security.safe_requests.requests.get",
+ side_effect=[resp1, resp2],
+ ) as mock_get,
):
- safe_get("https://example.com", allow_redirects=True)
+ with pytest.raises(
+ ValueError, match="Redirect target failed SSRF validation"
+ ):
+ safe_get("https://example.com", allow_redirects=True)
- # Initial URL + 2 redirect targets = 3 validate_url calls
- assert mock_validate_url.call_count == 3
- validated_urls = [
- call.args[0] for call in mock_validate_url.call_args_list
- ]
- assert validated_urls == [
- "https://example.com",
- "https://hop2.com",
- "https://hop3.com",
- ]
+ # Only the first two hops were fetched; the third was caught
+ # at validation time and never reached the wire.
+ assert mock_get.call_count == 2
def test_default_allow_redirects_follows(self, mock_validate_url):
"""Without explicit allow_redirects, safe_get follows redirects (default True)."""
@@ -473,30 +485,50 @@ class TestSafeSessionRedirectFollowing:
session.send(prep)
def test_send_respects_allow_localhost(self):
- """SafeSession.send() passes allow_localhost to validate_url."""
+ """SafeSession with allow_localhost=True actually lets a loopback
+ URL through to the underlying Session.send.
+
+ The previous version of this test mocked validate_url to always
+ return True, so the test could not detect a regression in the
+ allow_localhost code path inside ssrf_validator. Here we exercise
+ the real validator: 127.0.0.1 is an IP literal that is rejected
+ by default, allowed only when allow_localhost is honored.
+ """
session = SafeSession(allow_localhost=True)
prep = requests.PreparedRequest()
- prep.prepare_url("http://localhost:8080/api", {})
+ prep.prepare_url("http://127.0.0.1:8080/api", {})
prep.prepare_method("GET")
with patch.object(
- ssrf_validator,
- "validate_url",
- return_value=True,
- ) as mock_validate:
- with patch.object(
- requests.Session, "send", return_value=_make_response(200)
- ):
+ requests.Session, "send", return_value=_make_response(200)
+ ) as mock_send:
+ session.send(prep)
+ mock_send.assert_called_once()
+
+ def test_send_blocks_loopback_without_allow_localhost(self):
+ """Loopback must still be rejected when allow_localhost is False —
+ proves the previous test isn't passing just because Session.send
+ is mocked.
+ """
+ session = SafeSession() # default: allow_localhost=False
+
+ prep = requests.PreparedRequest()
+ prep.prepare_url("http://127.0.0.1:8080/api", {})
+ prep.prepare_method("GET")
+
+ with patch.object(
+ requests.Session, "send", return_value=_make_response(200)
+ ) as mock_send:
+ with pytest.raises(ValueError, match="SSRF"):
session.send(prep)
- mock_validate.assert_called_once_with(
- "http://localhost:8080/api",
- allow_localhost=True,
- allow_private_ips=False,
- )
+ mock_send.assert_not_called()
def test_send_respects_allow_private_ips(self):
- """SafeSession.send() passes allow_private_ips to validate_url."""
+ """SafeSession with allow_private_ips=True lets an RFC1918 URL
+ through to Session.send. Uses the real validator so a regression
+ in is_ip_blocked's allow_private_ips handling would surface.
+ """
session = SafeSession(allow_private_ips=True)
prep = requests.PreparedRequest()
@@ -504,19 +536,10 @@ class TestSafeSessionRedirectFollowing:
prep.prepare_method("GET")
with patch.object(
- ssrf_validator,
- "validate_url",
- return_value=True,
- ) as mock_validate:
- with patch.object(
- requests.Session, "send", return_value=_make_response(200)
- ):
- session.send(prep)
- mock_validate.assert_called_once_with(
- "http://192.168.1.1/api",
- allow_localhost=False,
- allow_private_ips=True,
- )
+ requests.Session, "send", return_value=_make_response(200)
+ ) as mock_send:
+ session.send(prep)
+ mock_send.assert_called_once()
def test_request_validates_initial_url(self):
"""SafeSession.request() validates the initial URL."""
@@ -764,32 +787,35 @@ class TestPostBodyNotForwardedOnConversion:
class TestSafePostPerHopValidation:
"""Verify validate_url is called for each hop in safe_post."""
- def test_each_hop_validated(self, mock_validate_url):
- """Each redirect hop in safe_post is validated against SSRF rules."""
+ def test_each_hop_validated(self):
+ """Each redirect hop in safe_post is validated by the real SSRF
+ validator. See ``TestSafeGetRedirectFollowing.test_each_hop_validated``
+ for the design rationale (real validator + private IP in the
+ third hop, so per-hop validation is actually exercised).
+ """
resp1 = _make_response(
307, {"Location": "https://hop2.com"}, "https://example.com"
)
resp2 = _make_response(
- 307, {"Location": "https://hop3.com"}, "https://hop2.com"
+ 307, {"Location": "http://10.0.0.5/internal"}, "https://hop2.com"
)
- final = _make_response(200)
- with patch(
- "local_deep_research.security.safe_requests.requests.post",
- side_effect=[resp1, resp2, final],
+ with (
+ patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
+ patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ side_effect=[resp1, resp2],
+ ) as mock_post,
):
- safe_post("https://example.com", allow_redirects=True)
+ with pytest.raises(
+ ValueError, match="Redirect target failed SSRF validation"
+ ):
+ safe_post("https://example.com", allow_redirects=True)
- # Initial URL + 2 redirect targets = 3 validate_url calls
- assert mock_validate_url.call_count == 3
- validated_urls = [
- call.args[0] for call in mock_validate_url.call_args_list
- ]
- assert validated_urls == [
- "https://example.com",
- "https://hop2.com",
- "https://hop3.com",
- ]
+ assert mock_post.call_count == 2
class TestRelativeRedirectURL:
diff --git a/tests/security/test_ssrf_validator.py b/tests/security/test_ssrf_validator.py
index d7347dee09..e4b9725008 100644
--- a/tests/security/test_ssrf_validator.py
+++ b/tests/security/test_ssrf_validator.py
@@ -1855,36 +1855,235 @@ class TestLegitimateUrlsStillPass:
assert validate_url("http://[2001:db8::1]/") is True
-class TestDocumentation:
- """Documentation tests explaining the security model."""
+# Security-model documentation lives in the module docstring at the top of
+# this file. The previous TestDocumentation class held a single skipped
+# placeholder test with no assertions; removed for clarity.
+
+
+# ===========================================================================
+# Edge-case coverage — gaps identified by a systematic review of the
+# validator's branches against the existing 7-file test suite. Each test
+# documents which production line(s) it pins and how it would fail under
+# the documented mutation.
+# ===========================================================================
+
+
+class TestUnspecifiedIPv4Blocked:
+ """validate_url end-to-end coverage for the 0.0.0.0/8 entry of
+ PRIVATE_IP_RANGES (ip_ranges.py:24). Prior tests covered
+ ``is_ip_blocked("0.0.0.0")`` but never the full URL path through the
+ parser, IP-literal branch (ssrf_validator.py:258-268), and
+ is_ip_blocked. Mutation: removing 0.0.0.0/8 from PRIVATE_IP_RANGES
+ flips all three parametrize cases to True.
+ """
- @pytest.mark.skip(reason="documentation/placeholder test - not implemented")
- def test_security_model_documentation(self):
- """
- Document the SSRF protection security model.
-
- WHY THIS EXISTS:
- - SSRF attacks can be used to access internal services
- - Attackers can steal credentials from cloud metadata endpoints
- - Internal services often have weaker security (no auth required)
-
- THE allow_private_ips PARAMETER:
- - Designed for trusted self-hosted services like SearXNG, Ollama
- - Service URLs are admin-configured, not arbitrary user input
- - Users intentionally run services on their local network or in containers
- - This is NOT the classic SSRF vector (user submits URL)
- - Covers RFC1918, CGNAT (Podman), link-local, IPv6 private ranges
-
- CRITICAL: AWS METADATA IS ALWAYS BLOCKED:
- - 169.254.169.254 is the #1 SSRF target for credential theft
- - Even with allow_private_ips=True, this endpoint is blocked
- - This protects against credential theft in cloud environments
-
- SECURITY MODEL:
- | Parameter | Localhost | RFC1918 | CGNAT (100.64.x) | Link-local | IPv6 Private | AWS Metadata |
- |---------------------|-----------|---------|------------------|------------|--------------|--------------|
- | (default) | Blocked | Blocked | Blocked | Blocked | Blocked | Blocked |
- | allow_localhost | Allowed | Blocked | Blocked | Blocked | Blocked | Blocked |
- | allow_private_ips | Allowed | Allowed | Allowed | Allowed | Allowed | BLOCKED |
- """
- assert True # Documentation test
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://0.0.0.0/",
+ "http://0.0.0.5/",
+ "http://0.255.255.254/",
+ ],
+ )
+ def test_unspecified_ipv4_literal_blocked(self, url):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(url) is False
+
+
+class TestDnsResolutionNonGaierror:
+ """The DNS-resolution block in validate_url has two except handlers:
+ a specific ``socket.gaierror`` (ssrf_validator.py:307-309) and a
+ generic ``except Exception`` (lines 310-312). The latter is hit when
+ getaddrinfo raises anything that is not a gaierror (PermissionError
+ from a restricted environment, UnicodeError from idna encoding of
+ oversized labels, etc.). Prior tests covered only gaierror.
+
+ Mutation: deleting lines 310-312 lets the exception propagate out
+ of validate_url. pytest reports the test as an ERROR (uncaught
+ exception), which still counts as a failure for these assertions.
+ """
+
+ @pytest.mark.parametrize(
+ "exc",
+ [PermissionError("eperm"), OSError("eio"), RuntimeError("boom")],
+ )
+ def test_non_gaierror_during_dns_fails_closed(self, exc, loguru_caplog):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch("socket.getaddrinfo", side_effect=exc):
+ with loguru_caplog.at_level("WARNING"):
+ result = validate_url("http://example.com/")
+
+ assert result is False
+ assert "Error during hostname resolution" in loguru_caplog.text
+
+
+class TestRfcForbiddenControlChars:
+ """RFC_FORBIDDEN_URL_CHARS_RE (ssrf_validator.py:63) is defined as
+ ``[\\\\s\\x00-\\x1f\\x7f]``. Prior tests heavily covered backslash
+ and ``\\x00``; this class pins the rest of the control-byte range
+ (low-range \\x01, mid-range \\x1f, and high-range \\x7f / DEL).
+
+ Mutation: narrowing the character class (e.g. dropping \\x7f or the
+ \\x01-\\x1f run) lets the corresponding URL pass through to urllib3
+ parsing — which may then disagree with the eventual HTTP client on
+ where the boundary between userinfo and host falls, the exact bug
+ class GHSA-g23j-2vwm-5c25 closed.
+ """
+
+ @pytest.mark.parametrize(
+ "ctrl_char",
+ ["\x01", "\x1f", "\x7f"],
+ )
+ def test_control_byte_in_url_rejected(self, ctrl_char):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ url = f"http://127.0.0.1{ctrl_char}@1.1.1.1"
+ assert validate_url(url) is False
+
+
+class TestAlternateIpHexForm:
+ """Single-DWORD hex notation (``0x7f000001``) is not parseable by
+ ``ipaddress.ip_address`` so the IP-literal branch raises ValueError
+ and the validator falls through to DNS resolution
+ (ssrf_validator.py:269-271 → 287-289). On Linux glibc, getaddrinfo
+ resolves the hex form to the canonical IPv4, which the post-DNS
+ is_ip_blocked check then catches.
+
+ This pins the load-bearing assumption that the IP-parse failure
+ correctly falls through, rather than short-circuiting to a wrong
+ outcome (e.g. returning True because no IP was matched).
+ """
+
+ def test_hex_dword_loopback_resolves_and_blocks(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ # 0x7f000001 == 127.0.0.1. glibc resolves this; non-glibc
+ # libc implementations may reject — the test mocks DNS to
+ # the canonical form so we exercise the post-DNS branch
+ # regardless of platform getaddrinfo behavior.
+ assert validate_url("http://0x7f000001/") is False
+
+
+class TestPortEdgeCases:
+ """Ports outside the legal range (>65535 and 0). 65536 trips
+ urllib3's ``parse_url`` and falls into the LocationParseError
+ handler (ssrf_validator.py:229-233). Port 0 parses successfully but
+ the host is still 127.0.0.1, which the IP-literal branch rejects.
+ """
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://127.0.0.1:65536/",
+ "http://127.0.0.1:0/",
+ ],
+ )
+ def test_port_edge_case_blocked(self, url):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(url) is False
+
+
+class TestMultipleAtSignsContract:
+ """RFC 3986 says when a URL contains multiple ``@`` characters the
+ LAST one delimits userinfo from host. ``http://a@[email protected]/`` parses
+ to host=``1.1.1.1``. urllib3 implements this; urllib.parse.urlparse
+ has historically agreed.
+
+ Validator behavior: when urllib3 reports a public host, validate_url
+ allows the URL (and a request library subsequently connects to the
+ same host). This test pins that contract. If urllib3 ever changes
+ its multi-@ handling, the explicit parse-url assertion catches the
+ drift.
+ """
+
+ def test_double_at_resolves_to_last_segment(self):
+ from urllib3.util import parse_url
+
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ url = "http://user:[email protected]@1.1.1.1/"
+ # Contract check — if this fails, urllib3 changed its multi-@
+ # semantics and the validator's assumption is no longer safe.
+ assert parse_url(url).host == "1.1.1.1"
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("1.1.1.1", 0))],
+ ):
+ assert validate_url(url) is True
+
+
+class TestUserinfoContainsIpShape:
+ """An IP-shaped string inside the userinfo portion of a URL is not
+ a bypass: urllib3 parses ``http://[email protected]/`` with
+ host=``evil.com``, and ``requests`` connects to the same host. The
+ validator therefore (correctly) allows it.
+
+ This test pins that the validator and urllib3 agree on this case,
+ which is essential to the parser-differential defense documented
+ at ssrf_validator.py:224-228.
+ """
+
+ def test_userinfo_ip_shape_is_not_a_bypass(self):
+ from urllib3.util import parse_url
+
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ url = "http://[email protected]/"
+ # The IP-shaped string is userinfo, not host.
+ assert parse_url(url).host == "evil.com"
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ assert validate_url(url) is True
+
+
+class TestIpv6ZoneIdBlocked:
+ """IPv6 link-local addresses with zone identifiers (RFC 6874 syntax)
+ must still be blocked because the host is in fe80::/10 regardless
+ of the trailing ``%zone`` part.
+
+ Python's ``ipaddress.ip_address`` accepts ``fe80::1%eth0`` since
+ 3.9; the validator's IP-literal branch (ssrf_validator.py:258-268)
+ therefore handles this directly via is_ip_blocked without falling
+ through to DNS. The percent-encoded variant (%25eth0) is the
+ URI-safe form that some clients emit; urllib3 may parse-fail it,
+ in which case the LocationParseError branch also returns False.
+ """
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://[fe80::1%eth0]/",
+ "http://[fe80::1%25eth0]/",
+ ],
+ )
+ def test_ipv6_zone_id_link_local_blocked(self, url):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(url) is False
diff --git a/tests/security/test_ssrf_validator_behavior.py b/tests/security/test_ssrf_validator_behavior.py
index ed0a8b1a26..4bd5784d06 100644
--- a/tests/security/test_ssrf_validator_behavior.py
+++ b/tests/security/test_ssrf_validator_behavior.py
@@ -4,6 +4,8 @@ Behavioral tests for ssrf_validator module.
Tests the SSRF (Server-Side Request Forgery) validation functions.
"""
+import pytest
+
class TestIsIPBlockedLoopback:
"""Tests for loopback address blocking."""
@@ -200,38 +202,47 @@ class TestIsIPBlockedZeroNetwork:
assert is_ip_blocked("0.1.2.3") is True
-class TestBlockedIPRanges:
- """Tests for BLOCKED_IP_RANGES constant."""
-
- def test_blocked_ranges_is_list(self):
- """BLOCKED_IP_RANGES is a list."""
- from local_deep_research.security.ssrf_validator import (
- BLOCKED_IP_RANGES,
- )
-
- assert isinstance(BLOCKED_IP_RANGES, list)
-
- def test_blocked_ranges_contains_loopback(self):
- """BLOCKED_IP_RANGES contains loopback."""
- import ipaddress
- from local_deep_research.security.ssrf_validator import (
- BLOCKED_IP_RANGES,
- )
-
- loopback = ipaddress.ip_network("127.0.0.0/8")
- assert loopback in BLOCKED_IP_RANGES
+class TestPrivateIpRangesBehavior:
+ """Verify is_ip_blocked rejects an interior address from every entry of
+ PRIVATE_IP_RANGES.
+
+ Replaces the prior TestBlockedIPRanges class, which asserted
+ ``ip_network("127.0.0.0/8") in BLOCKED_IP_RANGES`` — a tautology that
+ re-stated the constant rather than exercising blocking behavior. The
+ parametrized assertions here would fail if any range entry were
+ accidentally removed from PRIVATE_IP_RANGES in ip_ranges.py.
+ """
+
+ @pytest.mark.parametrize(
+ "ip,range_label",
+ [
+ ("127.0.0.5", "127.0.0.0/8 IPv4 loopback"),
+ ("::1", "::1/128 IPv6 loopback"),
+ ("10.0.0.5", "10.0.0.0/8 RFC1918 class A"),
+ ("172.16.0.5", "172.16.0.0/12 RFC1918 class B"),
+ ("172.31.255.254", "172.16.0.0/12 RFC1918 class B upper bound"),
+ ("192.168.0.5", "192.168.0.0/16 RFC1918 class C"),
+ ("100.64.0.5", "100.64.0.0/10 CGNAT"),
+ ("169.254.0.5", "169.254.0.0/16 link-local"),
+ ("fe80::1", "fe80::/10 IPv6 link-local"),
+ ("fc00::1", "fc00::/7 IPv6 ULA"),
+ ("0.0.0.5", "0.0.0.0/8 unspecified IPv4"),
+ ("::", "::/128 unspecified IPv6"),
+ ("2002:7f00:1::", "2002::/16 6to4 wrapping loopback"),
+ ("64:ff9b::a9fe:a9fe", "64:ff9b::/96 NAT64 well-known"),
+ ("64:ff9b:1::a9fe:a9fe", "64:ff9b:1::/48 NAT64 local-use"),
+ ("2001::1", "2001::/32 Teredo"),
+ ("100::1", "100::/64 discard"),
+ ("::7f00:1", "::/96 IPv4-compatible IPv6 wrapping loopback"),
+ ],
+ )
+ def test_interior_address_blocked(self, ip, range_label):
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
- def test_blocked_ranges_contains_rfc1918(self):
- """BLOCKED_IP_RANGES contains RFC1918 ranges."""
- import ipaddress
- from local_deep_research.security.ssrf_validator import (
- BLOCKED_IP_RANGES,
+ assert is_ip_blocked(ip) is True, (
+ f"Expected {ip} to be blocked because it falls in {range_label}"
)
- assert ipaddress.ip_network("10.0.0.0/8") in BLOCKED_IP_RANGES
- assert ipaddress.ip_network("172.16.0.0/12") in BLOCKED_IP_RANGES
- assert ipaddress.ip_network("192.168.0.0/16") in BLOCKED_IP_RANGES
-
class TestAllowedSchemes:
"""Tests for ALLOWED_SCHEMES constant."""
diff --git a/tests/security/test_ssrf_validator_extended.py b/tests/security/test_ssrf_validator_extended.py
index b12822cc15..0b5a1b07d6 100644
--- a/tests/security/test_ssrf_validator_extended.py
+++ b/tests/security/test_ssrf_validator_extended.py
@@ -38,10 +38,6 @@ class TestAlwaysBlockedMetadataIPsConstant:
assert "100.100.100.200" in ALWAYS_BLOCKED_METADATA_IPS
assert "169.254.0.23" in ALWAYS_BLOCKED_METADATA_IPS
- def test_is_frozenset(self):
- """Must be immutable so tests can't accidentally mutate it."""
- assert isinstance(ALWAYS_BLOCKED_METADATA_IPS, frozenset)
-
class TestAllowedSchemesConstant:
"""Verify the ALLOWED_SCHEMES constant."""
diff --git a/tests/security/test_ssrf_validator_high_value.py b/tests/security/test_ssrf_validator_high_value.py
index 76f41008c1..9d3fafb2bb 100644
--- a/tests/security/test_ssrf_validator_high_value.py
+++ b/tests/security/test_ssrf_validator_high_value.py
@@ -5,7 +5,6 @@ from unittest.mock import patch
import pytest
-from local_deep_research.security import ssrf_validator
from local_deep_research.security.ssrf_validator import (
is_ip_blocked,
@@ -252,20 +251,22 @@ class TestGetSafeUrl:
assert get_safe_url("", "fallback") == "fallback"
def test_safe_url_passes_through(self):
- with patch.object(
- ssrf_validator,
- "validate_url",
- return_value=True,
+ """Exercises real validate_url end-to-end. Mocking only DNS means
+ a regression in scheme/IP/host-extraction logic would surface
+ here, not just whichever code path the mock previously covered.
+ """
+ with patch(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
):
assert get_safe_url("http://example.com") == "http://example.com"
def test_unsafe_url_returns_default(self):
- with patch.object(
- ssrf_validator,
- "validate_url",
- return_value=False,
- ):
- assert get_safe_url("http://evil.internal", "safe") == "safe"
+ """Real-validator pass-through: the IP literal 10.0.0.5 is
+ rejected without DNS, so removing the RFC1918 entry from
+ PRIVATE_IP_RANGES would cause this test to fail.
+ """
+ assert get_safe_url("http://10.0.0.5/", "safe") == "safe"
def test_none_url_none_default(self):
assert get_safe_url(None) is None