~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): reject legacy numeric IPv4 host forms before DNS in URL validators (#5086)
LearningCircuit9946dbc87e58
diff --git a/changelog.d/+reject-legacy-ipv4-hosts.security.md b/changelog.d/+reject-legacy-ipv4-hosts.security.mdnew file mode 100644index 0000000000..e69d3d5a67--- /dev/null+++ b/changelog.d/+reject-legacy-ipv4-hosts.security.md@@ -0,0 +1 @@+Reject ambiguous legacy numeric IPv4 host forms before DNS resolution in webhook and notification URL validation.diff --git a/src/local_deep_research/security/legacy_ipv4.py b/src/local_deep_research/security/legacy_ipv4.pynew file mode 100644index 0000000000..5d6ba3450e--- /dev/null+++ b/src/local_deep_research/security/legacy_ipv4.py@@ -0,0 +1,107 @@+"""Recognize ambiguous historical IPv4 host syntax without network access."""++import ipaddress+from typing import Final+from urllib.parse import unquote_to_bytes+++AMBIGUOUS_NUMERIC_IPV4_HOST_ERROR: Final = "Ambiguous numeric IPv4 host"+ENCODED_NUMERIC_IPV4_HOST_ERROR: Final = "Encoded numeric IPv4 host"+_COMPONENT_MAXIMUMS: Final[tuple[tuple[int, ...], ...]] = (+ (0xFFFFFFFF,),+ (0xFF, 0xFFFFFF),+ (0xFF, 0xFF, 0xFFFF),+ (0xFF, 0xFF, 0xFF, 0xFF),+)+++def is_ambiguous_numeric_ipv4_host(hostname: str) -> bool:+ """Return whether ``hostname`` is a valid noncanonical historical IPv4 form.++ This recognizes the one-to-four-part inet_aton-style grammar using decimal,+ leading-zero octal, and ``0x`` hexadecimal components. It deliberately does+ not perform DNS or platform parsing.+ """+ try:+ _ = ipaddress.ip_address(hostname)+ except ValueError:+ components = hostname.split(".")+ else:+ return False++ if not 1 <= len(components) <= len(_COMPONENT_MAXIMUMS):+ return False++ maximums = _COMPONENT_MAXIMUMS[len(components) - 1]+ return all(+ _parse_component(component, maximum) is not None+ for component, maximum in zip(components, maximums, strict=True)+ )+++def is_percent_encoded_numeric_ipv4_host(hostname: str) -> bool:+ """Return whether one-pass percent decoding exposes an IPv4 address form."""+ decoded_hostname = _decode_percent_escapes(hostname)+ if decoded_hostname is None or decoded_hostname == hostname:+ return False+ classification_hostname = decoded_hostname.rstrip(".")++ try:+ parsed_ip = ipaddress.ip_address(classification_hostname)+ except ValueError:+ return is_ambiguous_numeric_ipv4_host(classification_hostname)+ return isinstance(parsed_ip, ipaddress.IPv4Address)+++def _decode_percent_escapes(hostname: str) -> str | None:+ """Decode only well-formed ASCII percent escapes without recursive decoding."""+ position = 0+ while (percent := hostname.find("%", position)) >= 0:+ if (+ percent + 2 >= len(hostname)+ or _digit_value(hostname[percent + 1]) is None+ or _digit_value(hostname[percent + 2]) is None+ ):+ return None+ position = percent + 3++ try:+ return unquote_to_bytes(hostname).decode("ascii")+ except UnicodeDecodeError:+ return None+++def _parse_component(component: str, maximum: int) -> int | None:+ """Parse one historical IPv4 component without integer overflow."""+ if not component:+ return None++ base = 10+ digits = component+ if component.startswith(("0x", "0X")):+ base = 16+ digits = component[2:]+ elif len(component) > 1 and component.startswith("0"):+ base = 8+ digits = component[1:]++ if not digits:+ return None++ value = 0+ for character in digits:+ digit = _digit_value(character)+ if digit is None or digit >= base or value > (maximum - digit) // base:+ return None+ value = value * base + digit+ return value+++def _digit_value(character: str) -> int | None:+ if "0" <= character <= "9":+ return ord(character) - ord("0")+ if "a" <= character <= "f":+ return ord(character) - ord("a") + 10+ if "A" <= character <= "F":+ return ord(character) - ord("A") + 10+ return Nonediff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex 2954fff77d..f9e894979f 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -9,7 +9,7 @@ import ipaddressimport reimport socketfrom concurrent.futures import ThreadPoolExecutor, TimeoutError-from typing import List, Optional, Tuple, Union+from typing import ClassVar, List, Optional, Tuple, Unionfrom urllib.parse import urlparsefrom loguru import logger@@ -17,6 +17,12 @@ from urllib3.exceptions import LocationParseErrorfrom urllib3.util import parse_urlfrom .ip_ranges import PRIVATE_IP_RANGES as _PRIVATE_IP_RANGES+from .legacy_ipv4 import (+ AMBIGUOUS_NUMERIC_IPV4_HOST_ERROR,+ ENCODED_NUMERIC_IPV4_HOST_ERROR,+ is_ambiguous_numeric_ipv4_host,+ is_percent_encoded_numeric_ipv4_host,+)from .ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE, redact_url_for_log# Type alias for resolved IP addresses (avoids referencing the private@@ -113,6 +119,27 @@ class NotificationURLValidator:"form", # Form-encoded webhooks)+ # Schemes whose authority identifies a network destination. Token-style+ # schemes such as discord and slack deliberately do not belong here.+ HOST_BEARING_PLUGIN_SCHEMES: ClassVar[frozenset[str]] = frozenset(+ {+ "signal",+ "gotify",+ "ntfy",+ "ntfys",+ "mattermost",+ "rocketchat",+ "matrix",+ "json",+ "xml",+ "form",+ "mailto",+ }+ )+ ADDRESS_BEARING_SCHEMES: ClassVar[frozenset[str]] = (+ frozenset({"http", "https"}) | HOST_BEARING_PLUGIN_SCHEMES+ )+# Reuse shared private IP range definitionsPRIVATE_IP_RANGES = _PRIVATE_IP_RANGES@@ -565,6 +592,23 @@ class NotificationURLValidator:"'scheme:///' is not allowed",)+ # ``tgram://`` is checked here, BEFORE host extraction, because its+ # authority is a CREDENTIAL (``<bot_id>:<token>``), not a network+ # destination: Apprise's Telegram plugin always dials the hardcoded+ # api.telegram.org endpoint. urllib3 cannot parse that authority at+ # all (it reads ``:<token>`` as a port and raises LocationParseError),+ # so the host-based checks below can never run for a valid tgram URL.+ #+ # ORDERING NOTE for future merges: this early return deliberately+ # precedes the numeric-IPv4 screening below, and that is safe ONLY+ # because ``tgram`` is not in ADDRESS_BEARING_SCHEMES. The regex below+ # is a strict allowlist that already rejects every legacy IPv4 host+ # form with a non-decimal component (``0x7f000001``, ``0177.0.0.1``,+ # ``127.1`` all fail ``[0-9]+``). The one remaining overlap — a bare+ # decimal integer such as ``2130706433`` — is exactly the shape of a+ # legitimate Telegram bot id, so it must NOT be rejected as an+ # ambiguous numeric IPv4 host. Any check that IS address-bearing must+ # be placed above this block, not below it.if scheme == "tgram":if not _APPRISE_TELEGRAM_URL_RE.match(url):return (@@ -574,7 +618,7 @@ class NotificationURLValidator:)return True, None- # Extract the host for any allowed scheme. We use urllib3 (the+ # Extract the host for address-bearing schemes. We use urllib3 (the# parser ``requests`` uses internally) instead of urlparse —# urlparse is vulnerable to parser-differential bypasses like# ``http://127.0.0.1\@1.1.1.1`` (GHSA-g23j-2vwm-5c25).@@ -631,6 +675,21 @@ class NotificationURLValidator:"is not allowed",)+ if (+ hostname+ and scheme in NotificationURLValidator.ADDRESS_BEARING_SCHEMES+ ):+ if is_percent_encoded_numeric_ipv4_host(hostname):+ logger.warning(+ "Blocked notification URL with encoded numeric IPv4 host"+ )+ return False, ENCODED_NUMERIC_IPV4_HOST_ERROR+ if is_ambiguous_numeric_ipv4_host(hostname):+ logger.warning(+ "Blocked notification URL with ambiguous numeric IPv4 host"+ )+ return False, AMBIGUOUS_NUMERIC_IPV4_HOST_ERROR+if scheme in ("http", "https"):if hostname and NotificationURLValidator._is_private_ip(hostname,@@ -646,7 +705,7 @@ class NotificationURLValidator:False,f"{NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX} {hostname}",)- else:+ elif scheme in NotificationURLValidator.HOST_BEARING_PLUGIN_SCHEMES:# Plugin-scheme IMDS guard. ``allow_private_ips=True`` leaves# ALWAYS_BLOCKED_METADATA_IPS and NAT64-wrapped metadata as# active blocks in ``_is_private_ip``; ``block_link_local=True``@@ -813,6 +872,11 @@ class NotificationURLValidator:# If the URL was rejected in Phase 1, no DNS was needed.if not is_valid:+ if error_msg in (+ AMBIGUOUS_NUMERIC_IPV4_HOST_ERROR,+ ENCODED_NUMERIC_IPV4_HOST_ERROR,+ ):+ return False, error_msg, Falseif not error_msg or not error_msg.startswith(NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX):diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex d4dd9a9f9c..61ea034128 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -16,6 +16,10 @@ from urllib3.util import parse_urlfrom .ip_ranges import PRIVATE_IP_RANGES as BLOCKED_IP_RANGESfrom .ip_ranges import NAT64_PREFIXES+from .legacy_ipv4 import (+ is_ambiguous_numeric_ipv4_host,+ is_percent_encoded_numeric_ipv4_host,+)# Cloud-provider metadata endpoints — always blocked, even with# allow_localhost=True or allow_private_ips=True. These IPs expose IAM /@@ -445,8 +449,12 @@ def validate_url()return Falseexcept ValueError:- # Not an IP address, it's a hostname - need to resolve it- pass+ if is_percent_encoded_numeric_ipv4_host(hostname):+ logger.warning("Blocked URL with encoded numeric IPv4 host")+ return False+ if is_ambiguous_numeric_ipv4_host(hostname):+ logger.warning("Blocked URL with ambiguous numeric IPv4 host")+ return False# Resolve hostname to IP and check.#diff --git a/tests/security/test_encoded_numeric_host.py b/tests/security/test_encoded_numeric_host.pynew file mode 100644index 0000000000..1ef3d50e30--- /dev/null+++ b/tests/security/test_encoded_numeric_host.py@@ -0,0 +1,237 @@+import ipaddress+import socket+from unittest.mock import patch++import pytest+import requests++from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+)+from local_deep_research.security.ssrf_validator import validate_url+++_PUBLIC_ADDRINFO = [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0)),+]+_PUBLIC_RESOLVED_IPS = [ipaddress.IPv4Address("93.184.216.34")]+_AMBIGUOUS_NUMERIC_IPV4_ERROR = "Ambiguous numeric IPv4 host"+_ENCODED_NUMERIC_IPV4_ERROR = "Encoded numeric IPv4 host"+_PRESERVED_PERCENT_ENCODED_URLS = (+ "https://ex%61mple.com/",+ "https://ex%61mple.com./",+ "https://127.0.0.1%252e/",+ "https://%32%31%33%30%37%30%36%34%33%[email protected]/",+ "https://public.example/%32%31%33%30%37%30%36%34%33%33",+)+_ENCODED_NUMERIC_IPV4_URLS = (+ (+ "http://%32%31%33%30%37%30%36%34%33%33/",+ "http://2130706433/",+ ),+ ("http://0x7f%2e0%2e0%2e1/", "http://0x7f.0.0.1/"),+ ("http://127%2e0%2e0%2e1/", "http://127.0.0.1/"),+)+_ENCODED_TRAILING_DOT_NUMERIC_IPV4_URLS = (+ ("http://127.0.0.1%2e/", "http://127.0.0.1./"),+ ("http://127.0.0.1%2E/", "http://127.0.0.1./"),+ ("http://2130706433%2e/", "http://2130706433./"),+ ("http://2130706433%2E/", "http://2130706433./"),+ ("http://0x7f000001%2e/", "http://0x7f000001./"),+ ("http://0x7f000001%2E/", "http://0x7f000001./"),+)+++def test_non_numeric_percent_encoded_hosts_preserve_current_outcomes():+ # Given: public DNS answers for nonnumeric authorities and public hosts.+ with (+ patch(+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",+ return_value=_PUBLIC_ADDRINFO,+ ),+ patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ),+ ):+ # When: percent escapes occur outside a numeric network authority.+ for url in _PRESERVED_PERCENT_ENCODED_URLS:+ # Then: both public validators retain their existing outcomes.+ assert validate_url(url) is True+ assert NotificationURLValidator.validate_service_url(url) == (+ True,+ None,+ )+++ "url",+ (+ "discord://%32%31%33%30%37%30%36%34%33%33/webhook-token",+ "discord://webhook-token%2e/",+ ),+)+def test_percent_encoded_opaque_plugin_authorities_preserve_current_outcome(+ url,+):+ # Given: an opaque token-style plugin authority with encoded digits.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: notification validation receives the opaque token URL.+ result = NotificationURLValidator.validate_service_url(url)++ # Then: it remains valid without host resolution.+ assert result == (True, None)+ assert resolver.call_count == 0+++def test_opaque_discord_authority_skips_host_resolution():+ # Given: a resolver guard that fails if an opaque token is treated as a host.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ side_effect=AssertionError("opaque Discord token must not resolve"),+ ):+ # When: hint-aware validation receives a numeric-looking Discord token.+ result = NotificationURLValidator.validate_service_url_with_hint(+ "discord://169.254.169.254/path"+ )++ # Then: the token remains valid without suggesting an operator setting.+ assert result == (True, None, False)+++def test_host_bearing_signal_metadata_authority_rejects_without_resolution():+ # Given: a resolver guard for a host-bearing Signal authority.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ side_effect=AssertionError(+ "metadata Signal host must reject before resolution"+ ),+ ):+ # When: notification validation receives a Signal metadata address.+ is_valid, _ = NotificationURLValidator.validate_service_url(+ "signal://169.254.169.254:8080/path"+ )++ # Then: canonical metadata IP rejection remains deterministic and network-free.+ assert is_valid is False+++def test_invalid_percent_escape_keeps_existing_parser_rejection():+ # Given: an authority that requests and urllib3 cannot parse.+ with (+ patch(+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",+ return_value=_PUBLIC_ADDRINFO,+ ) as general_resolver,+ patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as notification_resolver,+ ):+ # When: validators receive an invalid percent escape.+ general_result = validate_url("http://%zz/")+ service_result = NotificationURLValidator.validate_service_url(+ "http://%zz/"+ )+ hint_result = NotificationURLValidator.validate_service_url_with_hint(+ "http://%zz/"+ )++ # Then: existing parse rejection occurs before either resolver.+ assert general_result is False+ assert service_result == (False, "Invalid URL format (parser rejected)")+ assert hint_result == (False, "Invalid URL format (parser rejected)", False)+ assert general_resolver.call_count == 0+ assert notification_resolver.call_count == 0+++ ("url", "prepared_url"),+ _ENCODED_NUMERIC_IPV4_URLS + _ENCODED_TRAILING_DOT_NUMERIC_IPV4_URLS,+)+def test_encoded_numeric_authority_matches_requests_and_rejects_before_dns(+ url, prepared_url+):+ # Given: public resolver answers that must not be used for encoded numeric hosts.+ with (+ patch(+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",+ return_value=_PUBLIC_ADDRINFO,+ ) as general_resolver,+ patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as notification_resolver,+ ):+ # When: requests prepares and validators receive an encoded numeric authority.+ downstream_url = requests.Request("GET", url).prepare().url+ general_result = validate_url(url)+ service_result = NotificationURLValidator.validate_service_url(url)++ # Then: downstream normalization and deterministic rejection agree.+ assert downstream_url == prepared_url+ assert general_result is False+ assert service_result == (False, _ENCODED_NUMERIC_IPV4_ERROR)+ assert general_resolver.call_count == 0+ assert notification_resolver.call_count == 0+++ ("url", "reason"),+ (("http://2130706433/", _AMBIGUOUS_NUMERIC_IPV4_ERROR),)+ + tuple(+ (url, _ENCODED_NUMERIC_IPV4_ERROR)+ for url, _ in _ENCODED_NUMERIC_IPV4_URLS+ + _ENCODED_TRAILING_DOT_NUMERIC_IPV4_URLS+ ),+)[email protected]("allow_private_ips", (False, True))+def test_structural_numeric_rejections_never_offer_private_ip_hint(+ url, reason, allow_private_ips+):+ # Given: a structural numeric-host rejection under either private-IP policy.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: hint-aware notification validation evaluates the URL.+ result = NotificationURLValidator.validate_service_url_with_hint(+ url, allow_private_ips=allow_private_ips+ )++ # Then: no operator setting is advertised and no DNS runs.+ assert result == (False, reason, False)+ assert resolver.call_count == 0+++ "url",+ (+ "signal://0x7f%2e0%2e0%2e1/+15551234567/+15557654321",+ "signal://0x7f000001%2e/+15551234567/+15557654321",+ "signal://0x7f000001%2E/+15551234567/+15557654321",+ ),+)+def test_encoded_numeric_host_plugin_rejects_before_dns(url):+ # Given: a host-bearing plugin URL with an encoded legacy IPv4 authority.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: notification validation evaluates the plugin URL.+ result = NotificationURLValidator.validate_service_url(url)++ # Then: it is structurally rejected before host resolution.+ assert result == (False, _ENCODED_NUMERIC_IPV4_ERROR)+ assert resolver.call_count == 0diff --git a/tests/security/test_numeric_host.py b/tests/security/test_numeric_host.pynew file mode 100644index 0000000000..cfb373a45e--- /dev/null+++ b/tests/security/test_numeric_host.py@@ -0,0 +1,226 @@+import ipaddress+import socket+from unittest.mock import patch++import pytest++from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+)+from local_deep_research.security.legacy_ipv4 import (+ is_ambiguous_numeric_ipv4_host,+)+from local_deep_research.security.ssrf_validator import validate_url+++_PUBLIC_ADDRINFO = [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0)),+]+_PUBLIC_RESOLVED_IPS = [ipaddress.IPv4Address("93.184.216.34")]+_AMBIGUOUS_NUMERIC_IPV4_ERROR = "Ambiguous numeric IPv4 host"+_LEGACY_NUMERIC_IPV4_HOSTS = (+ "2130706433",+ "0x7f000001",+ "0X7F000001",+ "0177.0.0.1",+ "127.1",+ "127.0.1",+ "0x7f.1",+ "0x7f.0.0.1",+ "2852039166",+ "0xa9fea9fe",+ "0XA9FEA9FE",+ "0251.0376.0251.0376",+ "0xa9.0xfe.0251.0376",+)+++def test_validators_preserve_canonical_and_nonlegacy_hosts():+ # Given: public DNS answers for inputs that use hostname resolution.+ with (+ patch(+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",+ return_value=_PUBLIC_ADDRINFO,+ ),+ patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ),+ ):+ # When: canonical addresses, DNS names, and malformed lookalikes validate.+ for url in (+ "https://8.8.8.8/",+ "https://[2001:4860:4860::8888]/",+ "https://example.com/",+ "https://0xZZ/",+ ):+ # Then: the existing public-destination outcome is preserved.+ assert validate_url(url) is True+ assert NotificationURLValidator.validate_service_url(url) == (+ True,+ None,+ )++ # When: a token-style plugin uses an opaque numeric-looking token.+ is_valid, error = NotificationURLValidator.validate_service_url(+ "discord://2130706433/webhook-token"+ )++ # Then: it remains a valid plugin URL.+ assert (is_valid, error) == (True, None)++[email protected]("host", _LEGACY_NUMERIC_IPV4_HOSTS)+def test_validate_url_rejects_legacy_numeric_ipv4_before_dns(host):+ # Given: a resolver that would otherwise classify the host as public.+ with patch(+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",+ return_value=_PUBLIC_ADDRINFO,+ ) as resolver:+ # When: general SSRF validation receives a legacy numeric IPv4 host.+ is_valid = validate_url(f"https://{host}/")++ # Then: it is rejected without invoking the resolver.+ assert is_valid is False+ assert resolver.call_count == 0++[email protected]("host", _LEGACY_NUMERIC_IPV4_HOSTS)+def test_service_url_rejects_legacy_numeric_ipv4_before_dns(host):+ # Given: a resolver that would otherwise classify the host as public.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: notification validation receives a legacy numeric IPv4 host.+ result = NotificationURLValidator.validate_service_url(+ f"https://{host}/"+ )++ # Then: it returns the stable rejection reason without resolution.+ assert result == (False, _AMBIGUOUS_NUMERIC_IPV4_ERROR)+ assert resolver.call_count == 0++[email protected]("host", _LEGACY_NUMERIC_IPV4_HOSTS)+def test_service_url_hint_rejects_legacy_numeric_ipv4_before_dns(host):+ # Given: a resolver that would otherwise classify the host as public.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: hint-aware notification validation receives a legacy host.+ result = NotificationURLValidator.validate_service_url_with_hint(+ f"https://{host}/"+ )++ # Then: the structural rejection has no DNS or operator-setting hint.+ assert result == (False, _AMBIGUOUS_NUMERIC_IPV4_ERROR, False)+ assert resolver.call_count == 0++[email protected]("host", _LEGACY_NUMERIC_IPV4_HOSTS)+def test_host_plugin_rejects_legacy_numeric_ipv4_before_dns(host):+ # Given: a resolver that would otherwise classify the host as public.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: a host-bearing plugin receives a legacy numeric IPv4 host.+ result = NotificationURLValidator.validate_service_url(+ f"signal://{host}/+15551234567/+15557654321"+ )++ # Then: it is rejected without changing plugin LAN reachability policy.+ assert result == (False, _AMBIGUOUS_NUMERIC_IPV4_ERROR)+ assert resolver.call_count == 0+++ "scheme", sorted(NotificationURLValidator.HOST_BEARING_PLUGIN_SCHEMES)+)+def test_each_host_plugin_rejects_legacy_numeric_ipv4_before_dns(scheme):+ # Given: every plugin scheme that identifies a network host.+ host = "0xa9fea9fe"+ url = (+ f"mailto://user@{host}/recipient"+ if scheme == "mailto"+ else f"{scheme}://{host}/path"+ )+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: the plugin receives an ambiguous metadata-address form.+ result = NotificationURLValidator.validate_service_url(url)++ # Then: the shared address grammar rejects it before resolution.+ assert result == (False, _AMBIGUOUS_NUMERIC_IPV4_ERROR)+ assert resolver.call_count == 0+++ "url",+ (+ "discord://2130706433/webhook-token",+ "slack://2130706433/token-a/token-b",+ # tgram authority is a bot CREDENTIAL (<bot_id>:<token>), and a+ # bare numeric bot id is indistinguishable from a legacy numeric+ # IPv4 host, so it must stay exempt from the address grammar.+ "tgram://2130706433:AAexample_token/123456789",+ "pushover://2130706433/application-token",+ "teams://2130706433/token-a/token-b/token-c",+ ),+)+def test_token_plugins_numeric_hosts_skip_address_checks(url):+ # Given: a token-style plugin with an opaque numeric-looking token.+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=_PUBLIC_RESOLVED_IPS,+ ) as resolver:+ # When: notification validation receives the token-style URL.+ result = NotificationURLValidator.validate_service_url(url)++ # Then: no host-address grammar or resolution is applied.+ assert result == (True, None)+ assert resolver.call_count == 0+++ ("host", "expected"),+ (+ ("0xffffffff", True),+ ("0xff.0xffffff", True),+ ("0xff.0xff.0xffff", True),+ ("0xff.0xff.0xff.0xff", True),+ ("4294967296", False),+ ("0x100000000", False),+ ("256.0", False),+ ("255.16777216", False),+ ("255.256.0", False),+ ("255.255.65536", False),+ ("255.255.255.256", False),+ ("0x", False),+ ("0xGG", False),+ ("08", False),+ ("0x7g.1", False),+ ("", False),+ (".", False),+ ("1..1", False),+ ("1.2.3.4.5", False),+ ("123.example.com", False),+ ),+)+def test_legacy_numeric_ipv4_parser_honors_grammar_bounds(host, expected):+ # Given: a possible legacy address form or numeric-looking DNS name.+ # When: the pure historical IPv4 parser evaluates it.+ actual = is_ambiguous_numeric_ipv4_host(host)++ # Then: only bounded one-to-four-part grammar is recognized.+ assert actual is expecteddiff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.pyindex 56dc74b794..c56a695973 100644--- a/tests/web/services/test_notification_coverage.py+++ b/tests/web/services/test_notification_coverage.py@@ -559,11 +559,10 @@ class TestNotificationService:False,id="plugin-scheme-signal-to-imds",),- pytest.param(- "discord://169.254.169.254/path",- False,- id="plugin-scheme-discord-to-imds",- ),+ # Legacy IPv4 forms are structurally rejected and cannot be unblocked.+ pytest.param("http://0177.0.0.1/", False, id="octal-loopback"),+ pytest.param("http://2130706433/", False, id="decimal-loopback"),+ pytest.param("http://0x7f000001/", False, id="hex-loopback"),# --- Recoverable: admin hint MUST appear ---# (LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true would actually# unblock these, so the hint is actionable.)@@ -606,15 +605,6 @@ class TestNotificationService:True,id="ipv4-mapped-ipv6-of-rfc1918",),- # Decimal / octal / hex IPv4 encodings of loopback. These- # reach the validator as hostnames but ipaddress parses them- # as IPs (octal/hex via from_string ambiguity, decimal via- # int). Pin that they're blocked AND recoverable so a- # future refactor cannot regress to "unparseable hostname →- # allow".- pytest.param("http://0177.0.0.1/", True, id="octal-loopback"),- pytest.param("http://2130706433/", True, id="decimal-loopback"),- pytest.param("http://0x7f000001/", True, id="hex-loopback"),],)def test_test_service_ip_rejection_matrix(self, url, expect_hint):