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.

refactor: deduplicate private IP ranges and metadata parsing (#1966)

LearningCircuit0c37944d2b84
diff --git a/src/local_deep_research/security/ip_ranges.py b/src/local_deep_research/security/ip_ranges.py
new file mode 100644
index 0000000000..af4e709e97
--- /dev/null
+++ b/src/local_deep_research/security/ip_ranges.py
@@ -0,0 +1,25 @@
+"""
+Shared private/internal IP range constants for security validation.
+
+Used by SSRF validation and notification URL validation to avoid
+duplicating IP range definitions.
+"""
+
+import ipaddress
+
+# RFC1918 private networks + loopback + link-local + CGNAT + IPv6 equivalents
+# nosec B104 - These hardcoded IPs are intentional for security validation
+PRIVATE_IP_RANGES = [
+ ipaddress.ip_network("127.0.0.0/8"), # IPv4 loopback
+ ipaddress.ip_network("::1/128"), # IPv6 loopback
+ ipaddress.ip_network("10.0.0.0/8"), # RFC1918 Class A private
+ ipaddress.ip_network("172.16.0.0/12"), # RFC1918 Class B private
+ ipaddress.ip_network("192.168.0.0/16"), # RFC1918 Class C private
+ ipaddress.ip_network(
+ "100.64.0.0/10"
+ ), # CGNAT - used by Podman/rootless containers
+ ipaddress.ip_network("169.254.0.0/16"), # Link-local
+ ipaddress.ip_network("fe80::/10"), # IPv6 link-local
+ ipaddress.ip_network("fc00::/7"), # IPv6 unique local
+ ipaddress.ip_network("0.0.0.0/8"), # "This" network
+]
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index 4970a8aa30..cf32d41de3 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -10,6 +10,8 @@ from typing import Optional, Tuple
from urllib.parse import urlparse
from loguru import logger
+from .ip_ranges import PRIVATE_IP_RANGES as _PRIVATE_IP_RANGES
+
class NotificationURLValidationError(ValueError):
"""Raised when a notification service URL fails security validation."""
@@ -52,20 +54,8 @@ class NotificationURLValidator:
"form", # Form-encoded webhooks
)
- # Private IP ranges (RFC 1918 + loopback + link-local + CGNAT)
- PRIVATE_IP_RANGES = [
- ipaddress.ip_network("127.0.0.0/8"), # Loopback
- ipaddress.ip_network("10.0.0.0/8"), # Private
- ipaddress.ip_network("172.16.0.0/12"), # Private
- ipaddress.ip_network("192.168.0.0/16"), # Private
- ipaddress.ip_network(
- "100.64.0.0/10"
- ), # CGNAT - used by Podman/rootless containers
- ipaddress.ip_network("169.254.0.0/16"), # Link-local
- ipaddress.ip_network("::1/128"), # IPv6 loopback
- ipaddress.ip_network("fc00::/7"), # IPv6 unique local
- ipaddress.ip_network("fe80::/10"), # IPv6 link-local
- ]
+ # Reuse shared private IP range definitions
+ PRIVATE_IP_RANGES = _PRIVATE_IP_RANGES
@staticmethod
def _is_private_ip(hostname: str) -> bool:
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index ee9ffe9e98..feed37fc7e 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -13,22 +13,7 @@ from typing import Optional
from loguru import logger
from ..settings.env_registry import get_env_setting
-
-
-# Blocked IP ranges (RFC1918 private networks, localhost, link-local, etc.)
-# nosec B104 - These hardcoded IPs are intentional for SSRF prevention (blocking private networks)
-BLOCKED_IP_RANGES = [
- ipaddress.ip_network("127.0.0.0/8"), # Loopback
- ipaddress.ip_network("::1/128"), # IPv6 loopback
- ipaddress.ip_network("10.0.0.0/8"), # Private network
- ipaddress.ip_network("172.16.0.0/12"), # Private network
- ipaddress.ip_network("192.168.0.0/16"), # Private network
- ipaddress.ip_network("169.254.0.0/16"), # Link-local
- ipaddress.ip_network("fe80::/10"), # IPv6 link-local
- ipaddress.ip_network("fc00::/7"), # IPv6 unique local
- ipaddress.ip_network("0.0.0.0/8"), # "This" network
- ipaddress.ip_network("100.64.0.0/10"), # Shared address space
-]
+from .ip_ranges import PRIVATE_IP_RANGES as BLOCKED_IP_RANGES
# AWS metadata endpoint (commonly targeted in SSRF attacks)
# nosec B104 - Hardcoded IP is intentional for SSRF prevention (blocking AWS metadata endpoint)
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index c8379829fa..959dd5008c 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -28,6 +28,19 @@ from .socket_service import SocketIOService
OUTPUT_DIR = get_research_outputs_directory()
+def _parse_research_metadata(research_meta) -> dict:
+ """Parse research_meta into a dict, handling both dict and JSON string types."""
+ if isinstance(research_meta, dict):
+ return dict(research_meta)
+ if isinstance(research_meta, str):
+ try:
+ return json.loads(research_meta)
+ except json.JSONDecodeError:
+ logger.exception("Failed to parse research_meta as JSON")
+ return {}
+ return {}
+
+
def get_citation_formatter():
"""Get citation formatter with settings from thread context."""
# Import here to avoid circular imports
@@ -965,24 +978,10 @@ def run_research_process(
)
# Preserve existing metadata and update with new values
- logger.info(
- f"Existing research_meta type: {type(research.research_meta)}"
+ metadata = _parse_research_metadata(
+ research.research_meta
)
- # Handle both dict and string types for research_meta
- if isinstance(research.research_meta, dict):
- metadata = dict(research.research_meta)
- elif isinstance(research.research_meta, str):
- try:
- metadata = json.loads(research.research_meta)
- except json.JSONDecodeError:
- logger.exception(
- f"Failed to parse research_meta as JSON: {research.research_meta}"
- )
- metadata = {}
- else:
- metadata = {}
-
metadata.update(
{
"iterations": results["iterations"],
@@ -1248,23 +1247,7 @@ def run_research_process(
)
# Preserve existing metadata and merge with report metadata
- logger.info(
- f"Full report - Existing research_meta type: {type(research.research_meta)}"
- )
-
- # Handle both dict and string types for research_meta
- if isinstance(research.research_meta, dict):
- metadata = dict(research.research_meta)
- elif isinstance(research.research_meta, str):
- try:
- metadata = json.loads(research.research_meta)
- except json.JSONDecodeError:
- logger.exception(
- f"Failed to parse research_meta as JSON: {research.research_meta}"
- )
- metadata = {}
- else:
- metadata = {}
+ metadata = _parse_research_metadata(research.research_meta)
metadata.update(final_report["metadata"])
metadata["iterations"] = results["iterations"]
diff --git a/tests/security/test_ip_ranges.py b/tests/security/test_ip_ranges.py
new file mode 100644
index 0000000000..7c9858a5db
--- /dev/null
+++ b/tests/security/test_ip_ranges.py
@@ -0,0 +1,182 @@
+"""
+Tests for security/ip_ranges.py
+
+Tests cover:
+- PRIVATE_IP_RANGES constant contains expected networks
+- Private IP detection works correctly
+- IPv4 and IPv6 address validation
+"""
+
+import ipaddress
+
+
+class TestPrivateIPRanges:
+ """Tests for PRIVATE_IP_RANGES constant."""
+
+ def test_private_ip_ranges_is_list(self):
+ """PRIVATE_IP_RANGES should be a list."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ assert isinstance(PRIVATE_IP_RANGES, list)
+
+ def test_private_ip_ranges_not_empty(self):
+ """PRIVATE_IP_RANGES should not be empty."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ assert len(PRIVATE_IP_RANGES) > 0
+
+ def test_private_ip_ranges_contains_ip_networks(self):
+ """All entries should be ip_network objects."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ for network in PRIVATE_IP_RANGES:
+ assert isinstance(
+ network, (ipaddress.IPv4Network, ipaddress.IPv6Network)
+ )
+
+ def test_contains_loopback_ipv4(self):
+ """Should contain IPv4 loopback (127.0.0.0/8)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ loopback = ipaddress.ip_network("127.0.0.0/8")
+ assert loopback in PRIVATE_IP_RANGES
+
+ def test_contains_loopback_ipv6(self):
+ """Should contain IPv6 loopback (::1/128)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ loopback = ipaddress.ip_network("::1/128")
+ assert loopback in PRIVATE_IP_RANGES
+
+ def test_contains_rfc1918_class_a(self):
+ """Should contain RFC1918 Class A private (10.0.0.0/8)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ private_a = ipaddress.ip_network("10.0.0.0/8")
+ assert private_a in PRIVATE_IP_RANGES
+
+ def test_contains_rfc1918_class_b(self):
+ """Should contain RFC1918 Class B private (172.16.0.0/12)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ private_b = ipaddress.ip_network("172.16.0.0/12")
+ assert private_b in PRIVATE_IP_RANGES
+
+ def test_contains_rfc1918_class_c(self):
+ """Should contain RFC1918 Class C private (192.168.0.0/16)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ private_c = ipaddress.ip_network("192.168.0.0/16")
+ assert private_c in PRIVATE_IP_RANGES
+
+ def test_contains_cgnat(self):
+ """Should contain CGNAT range (100.64.0.0/10)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ cgnat = ipaddress.ip_network("100.64.0.0/10")
+ assert cgnat in PRIVATE_IP_RANGES
+
+ def test_contains_link_local_ipv4(self):
+ """Should contain IPv4 link-local (169.254.0.0/16)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ link_local = ipaddress.ip_network("169.254.0.0/16")
+ assert link_local in PRIVATE_IP_RANGES
+
+ def test_contains_link_local_ipv6(self):
+ """Should contain IPv6 link-local (fe80::/10)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ link_local = ipaddress.ip_network("fe80::/10")
+ assert link_local in PRIVATE_IP_RANGES
+
+ def test_contains_ipv6_unique_local(self):
+ """Should contain IPv6 unique local (fc00::/7)."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ unique_local = ipaddress.ip_network("fc00::/7")
+ assert unique_local in PRIVATE_IP_RANGES
+
+
+class TestPrivateIPDetection:
+ """Tests for using PRIVATE_IP_RANGES to detect private IPs."""
+
+ def _is_private(self, ip_str: str) -> bool:
+ """Helper to check if IP is in private ranges."""
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ try:
+ ip = ipaddress.ip_address(ip_str)
+ return any(ip in network for network in PRIVATE_IP_RANGES)
+ except ValueError:
+ return False
+
+ def test_localhost_is_private(self):
+ """127.0.0.1 should be detected as private."""
+ assert self._is_private("127.0.0.1") is True
+
+ def test_localhost_ipv6_is_private(self):
+ """::1 should be detected as private."""
+ assert self._is_private("::1") is True
+
+ def test_10_network_is_private(self):
+ """10.x.x.x addresses should be detected as private."""
+ assert self._is_private("10.0.0.1") is True
+ assert self._is_private("10.255.255.255") is True
+
+ def test_172_16_network_is_private(self):
+ """172.16-31.x.x addresses should be detected as private."""
+ assert self._is_private("172.16.0.1") is True
+ assert self._is_private("172.31.255.255") is True
+
+ def test_172_32_is_not_private(self):
+ """172.32.x.x should NOT be detected as private."""
+ assert self._is_private("172.32.0.1") is False
+
+ def test_192_168_network_is_private(self):
+ """192.168.x.x addresses should be detected as private."""
+ assert self._is_private("192.168.0.1") is True
+ assert self._is_private("192.168.255.255") is True
+
+ def test_cgnat_is_private(self):
+ """100.64.x.x CGNAT addresses should be detected as private."""
+ assert self._is_private("100.64.0.1") is True
+ assert self._is_private("100.127.255.255") is True
+
+ def test_link_local_is_private(self):
+ """169.254.x.x link-local addresses should be detected as private."""
+ assert self._is_private("169.254.1.1") is True
+
+ def test_public_ip_is_not_private(self):
+ """Public IPs should NOT be detected as private."""
+ assert self._is_private("8.8.8.8") is False
+ assert self._is_private("1.1.1.1") is False
+ assert self._is_private("93.184.216.34") is False # example.com
+
+ def test_ipv6_public_is_not_private(self):
+ """Public IPv6 addresses should NOT be detected as private."""
+ assert self._is_private("2001:4860:4860::8888") is False # Google DNS
+
+
+class TestIPRangesUsedByValidators:
+ """Tests to verify PRIVATE_IP_RANGES is correctly imported by validators."""
+
+ def test_ssrf_validator_uses_shared_ranges(self):
+ """SSRF validator should import BLOCKED_IP_RANGES from ip_ranges."""
+ from local_deep_research.security.ssrf_validator import (
+ BLOCKED_IP_RANGES,
+ )
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ # Should be the same object (imported, not copied)
+ assert BLOCKED_IP_RANGES is PRIVATE_IP_RANGES
+
+ def test_notification_validator_uses_shared_ranges(self):
+ """Notification validator should use shared ranges."""
+ from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ )
+ from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGES
+
+ # Should be the same object
+ assert NotificationURLValidator.PRIVATE_IP_RANGES is PRIVATE_IP_RANGES
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
index d7796f5029..af22067a62 100644
--- a/tests/web/services/test_research_service.py
+++ b/tests/web/services/test_research_service.py
@@ -909,3 +909,131 @@ URL: https://example.com/1
# Should succeed - PDF formats should not prepend if content starts with #
assert content.startswith(b"%PDF")
+
+
+class TestParseResearchMetadata:
+ """Tests for _parse_research_metadata function."""
+
+ def test_parse_dict_returns_copy(self):
+ """_parse_research_metadata returns copy when given dict."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ original = {"key": "value", "number": 42}
+ result = _parse_research_metadata(original)
+
+ assert result == original
+ # Should be a copy, not the same object
+ assert result is not original
+
+ def test_parse_dict_with_nested_data(self):
+ """_parse_research_metadata handles nested dict data."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ original = {
+ "iterations": 5,
+ "metadata": {"model": "gpt-4", "search_engine": "google"},
+ "sources": ["source1", "source2"],
+ }
+ result = _parse_research_metadata(original)
+
+ assert result == original
+ assert result["metadata"]["model"] == "gpt-4"
+
+ def test_parse_valid_json_string(self):
+ """_parse_research_metadata parses valid JSON string."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ json_str = '{"key": "value", "number": 42}'
+ result = _parse_research_metadata(json_str)
+
+ assert result == {"key": "value", "number": 42}
+
+ def test_parse_complex_json_string(self):
+ """_parse_research_metadata parses complex JSON string."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ json_str = '{"iterations": 5, "metadata": {"model": "gpt-4"}, "sources": ["a", "b"]}'
+ result = _parse_research_metadata(json_str)
+
+ assert result["iterations"] == 5
+ assert result["metadata"]["model"] == "gpt-4"
+ assert result["sources"] == ["a", "b"]
+
+ def test_parse_invalid_json_string_returns_empty_dict(self):
+ """_parse_research_metadata returns empty dict for invalid JSON."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ invalid_json = "not valid json {{"
+ result = _parse_research_metadata(invalid_json)
+
+ assert result == {}
+
+ def test_parse_empty_json_string(self):
+ """_parse_research_metadata handles empty JSON object string."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata("{}")
+
+ assert result == {}
+
+ def test_parse_none_returns_empty_dict(self):
+ """_parse_research_metadata returns empty dict for None."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata(None)
+
+ assert result == {}
+
+ def test_parse_empty_string_returns_empty_dict(self):
+ """_parse_research_metadata returns empty dict for empty string."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata("")
+
+ assert result == {}
+
+ def test_parse_integer_returns_empty_dict(self):
+ """_parse_research_metadata returns empty dict for integer."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata(42)
+
+ assert result == {}
+
+ def test_parse_list_returns_empty_dict(self):
+ """_parse_research_metadata returns empty dict for list."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata([1, 2, 3])
+
+ assert result == {}
+
+ def test_parse_empty_dict_returns_empty_dict(self):
+ """_parse_research_metadata handles empty dict."""
+ from local_deep_research.web.services.research_service import (
+ _parse_research_metadata,
+ )
+
+ result = _parse_research_metadata({})
+
+ assert result == {}