~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(notifications): close DNS-rebinding TOCTOU in hint decision (#4002 follow-up) (#4986)
LearningCircuit4071ef8c5483
diff --git a/changelog.d/+notification-hint-toctou-fix.security.md b/changelog.d/+notification-hint-toctou-fix.security.mdnew file mode 100644index 0000000000..ac7e6447be--- /dev/null+++ b/changelog.d/+notification-hint-toctou-fix.security.md@@ -0,0 +1,4 @@+The notification "Test" button's admin-hint decision now shares a+single DNS-resolution pass with the default-level URL rejection,+closing a DNS-rebinding TOCTOU window that the previous two-call+pattern opened between the rejection and the hint check.diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex ee565c808e..194cba4c1f 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -305,7 +305,7 @@ The "Test" button in the notifications settings page returns the validator's rea- **Fix**: Choose a different webhook destination. Metadata endpoints expose IAM/instance credentials and are never legitimate webhook targets.**"Blocked unsafe protocol: \<scheme\>"** / **"Unsupported protocol: \<scheme\>"**-- **Cause**: The URL uses a scheme that is either denylisted (`file`, `ftp`, `data`, `javascript`, `vbscript`, `about`, `blob`) or not in the Apprise-supported allowlist.+- **Cause**: The URL uses a scheme that is either denylisted (`file`, `ftp`, `ftps`, `data`, `javascript`, `vbscript`, `about`, `blob`) or not in the Apprise-supported allowlist.- **Fix**: Use one of the allowed schemes — `http`, `https`, `mailto`, `discord`, `slack`, `telegram`, `gotify`, `pushover`, `ntfy`, `ntfys`, `signal`, `matrix`, `mattermost`, `rocketchat`, `teams`, `json`, `xml`, `form`. Prefer Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, etc.) over raw `http(s)://` webhooks — they hardcode their endpoints and have no SSRF surface.**"URL contains characters that are not allowed (whitespace, backslash, or control bytes)"**diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.pyindex 3f86d46c75..9113d1f2bc 100644--- a/src/local_deep_research/notifications/service.py+++ b/src/local_deep_research/notifications/service.py@@ -22,50 +22,9 @@ from ..security.notification_validator import (NotificationURLValidator,)--# Prefix emitted by NotificationURLValidator when an http(s) URL targets a-# private/internal IP. Pinned as a constant so the call site and the-# validator stay in lockstep — see NotificationURLValidator.validate_service_url-# docstring. The lockstep integration test-# ``test_test_service_ip_rejection_matrix`` in-# tests/web/services/test_notification_coverage.py guards the wording.-PRIVATE_IP_REJECTION_PREFIX = "Blocked private/internal IP address:"---def _admin_hint_would_help(url: str) -> bool:- """True iff some operator escape hatch would actually unblock ``url``.-- The admin hint names two env vars, and each unblocks a *disjoint* set- of destinations, so both must be probed:-- - ``LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true`` unblocks RFC1918 / CGNAT- / loopback / link-local / IPv6 ULA — probed via ``allow_private_ips``.- - ``LDR_SECURITY_ALLOW_NAT64=true`` unblocks the two NAT64 prefixes- (``64:ff9b::/96``, ``64:ff9b:1::/48``) wrapping a non-metadata IPv4 —- probed via ``allow_nat64``. The NAT64 prefixes live in the blocked- set but NOT in the private/loopback ranges, so the private-IPs probe- alone can NEVER unblock them; without this second probe the- NAT64 half of the hint would be dead for the very URLs it documents.-- If NEITHER probe unblocks ``url`` it targets an always-blocked category- (cloud-metadata IPs, 6to4, Teredo, discard prefix, IPv4-mapped IPv6 of- metadata, NAT64-wrapped metadata) and the hint would mislead, so it is- suppressed.-- Delegating to the validator (which re-resolves DNS) keeps a single- source of truth — any future always-blocked category is handled- automatically — and covers NAT64 reached via DNS64, not just literal- NAT64 addresses.- """- private_would_unblock, _ = NotificationURLValidator.validate_service_url(- url, allow_private_ips=True- )- if private_would_unblock:- return True- nat64_would_unblock, _ = NotificationURLValidator.validate_service_url(- url, allow_nat64=True- )- return nat64_would_unblock+PRIVATE_IP_REJECTION_PREFIX = (+ NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX+)# Backward compatibility constants - now handled by Tenacity internally@@ -329,9 +288,16 @@ class NotificationService:}try:- # Validate service URL for security (SSRF prevention)- is_valid, error_msg = NotificationURLValidator.validate_service_url(- url, allow_private_ips=self.allow_private_ips+ # Validate service URL for security (SSRF prevention) and,+ # in the same pass, compute whether the admin env-var hint+ # would actually unblock a recoverable private-IP rejection.+ # Single-pass avoids a DNS-rebinding TOCTOU window between+ # the default-level validation and the elevated-level hint+ # decision — see NotificationURLValidator.validate_service_url_with_hint.+ is_valid, error_msg, hint_would_help = (+ NotificationURLValidator.validate_service_url_with_hint(+ url, allow_private_ips=self.allow_private_ips+ ))if not is_valid:@@ -351,18 +317,15 @@ class NotificationService:# metadata, NAT64-wrapped metadata): no env var can help, so# naming one would mislead.user_error = error_msg or "Invalid notification service URL."- if error_msg and error_msg.startswith(- PRIVATE_IP_REJECTION_PREFIX- ):- if _admin_hint_would_help(url):- user_error += (- ". To unblock this destination, ask the server "- "administrator to set "- "LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true "- "(IPv6-only NAT64 deployments also need "- "LDR_SECURITY_ALLOW_NAT64=true). "- "See SECURITY.md 'Notification Webhook SSRF'."- )+ if hint_would_help:+ user_error += (+ ". To unblock this destination, ask the server "+ "administrator to set "+ "LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true "+ "(IPv6-only NAT64 deployments also need "+ "LDR_SECURITY_ALLOW_NAT64=true). "+ "See SECURITY.md 'Notification Webhook SSRF'."+ )return {"success": False,"error": user_error,diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex 6dfa175e4c..2795942a85 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -8,7 +8,7 @@ to prevent Server-Side Request Forgery (SSRF) attacks and other security issues.import ipaddressimport socketfrom concurrent.futures import ThreadPoolExecutor, TimeoutError-from typing import Optional, Tuple+from typing import List, Optional, Tuple, Unionfrom urllib.parse import urlparsefrom loguru import loggerfrom urllib3.exceptions import LocationParseError@@ -17,6 +17,10 @@ from urllib3.util import parse_urlfrom .ip_ranges import PRIVATE_IP_RANGES as _PRIVATE_IP_RANGESfrom .ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE, redact_url_for_log+# Type alias for resolved IP addresses (avoids referencing the private+# ipaddress._BaseAddress API).+ResolvedIP = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]+class NotificationURLValidationError(ValueError):"""Raised when a notification service URL fails security validation."""@@ -64,6 +68,12 @@ class NotificationURLValidator:# Reuse shared private IP range definitionsPRIVATE_IP_RANGES = _PRIVATE_IP_RANGES+ # Prefix emitted by validate_service_url when an http(s) URL targets a+ # private/internal IP. Pinned as a class-level constant so the+ # validator, the hint logic, and the call site (service.py) share a+ # single source of truth.+ PRIVATE_IP_REJECTION_PREFIX = "Blocked private/internal IP address:"+@staticmethoddef _ip_matches_blocked_range(ip, allow_private_ips: bool = False, allow_nat64: Optional[bool] = None@@ -93,30 +103,79 @@ class NotificationURLValidator:)@staticmethod- def _is_private_ip(+ def _resolve_hostname_ips(+ hostname: str,+ ) -> Optional[List[ResolvedIP]]:+ """Resolve hostname to a list of ipaddress objects, with a 5s+ timeout. Returns None on resolution failure or timeout.++ Extracted from ``_is_private_ip`` so multiple policy decisions+ can share a single resolution pass — see+ ``validate_service_url_with_hint`` for the single-pass call+ site that closes a DNS-rebinding TOCTOU window between the+ default-level and elevated-level decisions.+ """+ # NOTE: best-effort, validation-time check. Apprise re-resolves+ # the hostname when it actually sends the request (via+ # requests/urllib3), so an attacker controlling DNS can serve a+ # public IP here and a private IP at send time — a classic DNS+ # rebinding TOCTOU window. Apprise exposes no Session/adapter/+ # DNS hook to close this in code without fragile monkey-patching+ # of its plugin internals.+ #+ # Because the window cannot be closed cleanly in code, the+ # whole outbound-notification path is gated behind an env-only+ # master switch (LDR_NOTIFICATIONS_ALLOW_OUTBOUND, default off);+ # turning it on is the operator's explicit risk-acceptance. See+ # SECURITY.md "Notification Webhook SSRF". Operators wanting to+ # avoid the window entirely should prefer plugin schemes+ # (discord://, slack://, ntfy://, ntfys://, gotify://,+ # telegram://, mattermost://, etc.) that hardcode their+ # endpoints instead of raw http(s):// webhooks.+ #+ # concurrent.futures for thread-safe timeout instead of+ # socket.setdefaulttimeout() which is process-global.+ try:+ executor = ThreadPoolExecutor(max_workers=1)+ try:+ future = executor.submit(+ socket.getaddrinfo,+ hostname,+ None,+ socket.AF_UNSPEC,+ socket.SOCK_STREAM,+ )+ resolved_ips = future.result(timeout=5)+ finally:+ executor.shutdown(wait=False, cancel_futures=True)+ return [+ ipaddress.ip_address(sockaddr[0])+ for _family, _, _, _, sockaddr in resolved_ips+ ]+ except (socket.gaierror, OSError, TimeoutError, ValueError):+ logger.warning(+ "DNS resolution failed for hostname {} — "+ "allowing request (unable to determine if private)",+ hostname,+ )+ return None++ @staticmethod+ def _host_blocks_at_level(hostname: str,allow_private_ips: bool = False,allow_nat64: Optional[bool] = None,+ resolved_ips: Optional[List[ResolvedIP]] = None,) -> bool:- """- Check if hostname resolves to a private IP address.-- Args:- hostname: Hostname to check- allow_private_ips: When True, RFC1918 / CGNAT / loopback /- link-local / IPv6 ULA are NOT considered private. Cloud- metadata IPs and NAT64-wrapped metadata IPs are blocked- regardless — the operator opt-in cannot license IMDS- exposure.- allow_nat64: Override for the ``security.allow_nat64`` carve-out- forwarded to ``is_ip_blocked``. None (default) reads env; an- explicit bool drives the "would NAT64 unblock this?" hint- probe. Because this resolves DNS first, the probe also covers- NAT64 reached via DNS64, not just literal NAT64 addresses.-- Returns:- True if hostname is a private IP or localhost (subject to- allow_private_ips), or wraps a metadata IP unconditionally+ """Decide whether ``hostname`` is blocked at the given+ ``allow_private_ips`` / ``allow_nat64`` level, optionally reusing+ a prior DNS resolution.++ Pre-resolved IPs can be passed via ``resolved_ips`` to share a+ single resolution across multiple policy decisions, closing+ DNS-rebinding TOCTOU windows between calls. If ``resolved_ips``+ is None and ``hostname`` is not an IP literal, DNS is resolved+ via ``_resolve_hostname_ips``."""# Localhost-string shortcuts only apply when the operator hasn't# opted into private-IP reachability. With allow_private_ips=True@@ -131,7 +190,7 @@ class NotificationURLValidator:):return True- # Try to parse as IP address+ # Try to parse as IP address first.try:ip = ipaddress.ip_address(hostname)return NotificationURLValidator._ip_matches_blocked_range(@@ -140,58 +199,81 @@ class NotificationURLValidator:allow_nat64=allow_nat64,)except ValueError:- # Hostname - resolve to IP and check.- #- # NOTE: This is a best-effort, validation-time check. Apprise- # re-resolves the hostname when it actually sends the request- # (via requests/urllib3), so an attacker controlling DNS can- # serve a public IP here and a private IP at send time -- a- # classic DNS rebinding TOCTOU window. Apprise exposes no- # Session/adapter/DNS hook to close this in code without- # fragile monkey-patching of its plugin internals.- #- # Because the window cannot be closed cleanly in code, the- # whole outbound-notification path is gated behind an- # env-only master switch (LDR_NOTIFICATIONS_ALLOW_OUTBOUND,- # default off); turning it on is the operator's explicit- # risk-acceptance. See SECURITY.md "Notification Webhook- # SSRF" for details.- # Operators wanting to avoid the window entirely should- # prefer plugin schemes (discord://, slack://, ntfy://, ntfys://,- # gotify://, telegram://, mattermost://, etc.) that hardcode- # their endpoints instead of raw http(s):// webhooks.- #- # Use concurrent.futures for thread-safe timeout instead of- # socket.setdefaulttimeout() which is process-global and not- # thread-safe.- try:- executor = ThreadPoolExecutor(max_workers=1)- try:- future = executor.submit(- socket.getaddrinfo,- hostname,- None,- socket.AF_UNSPEC,- socket.SOCK_STREAM,- )- resolved_ips = future.result(timeout=5)- finally:- executor.shutdown(wait=False, cancel_futures=True)- for _family, _, _, _, sockaddr in resolved_ips:- ip = ipaddress.ip_address(sockaddr[0])- if NotificationURLValidator._ip_matches_blocked_range(- ip,- allow_private_ips=allow_private_ips,- allow_nat64=allow_nat64,- ):- return True- except (socket.gaierror, OSError, TimeoutError):- logger.warning(- "DNS resolution failed for hostname {} — "- "allowing request (unable to determine if private)",- hostname,- )+ pass++ # Hostname — use pre-resolved IPs if provided, otherwise resolve.+ if resolved_ips is None:+ resolved_ips = NotificationURLValidator._resolve_hostname_ips(+ hostname+ )+ if resolved_ips is None:+ # DNS failed — allow (matches the historical behaviour).return False+ for ip in resolved_ips:+ if NotificationURLValidator._ip_matches_blocked_range(+ ip,+ allow_private_ips=allow_private_ips,+ allow_nat64=allow_nat64,+ ):+ return True+ return False++ @staticmethod+ def _extract_host(url: str) -> Optional[str]:+ """Extract the raw hostname from ``url`` using urllib3's+ ``parse_url`` (the same parser requests uses internally).+ Returns None if urllib3 rejects the URL.+ """+ try:+ u3 = parse_url(url)+ except LocationParseError:+ return None+ return u3.host++ @staticmethod+ def _normalize_host(hostname: Optional[str]) -> str:+ """Normalize a raw hostname from ``parse_url``: strip IPv6+ bracket notation and trailing dots. Shared by+ ``validate_service_url`` and ``validate_service_url_with_hint``+ so the two call sites cannot drift.+ """+ if hostname and hostname.startswith("[") and hostname.endswith("]"):+ hostname = hostname[1:-1]+ if hostname:+ hostname = hostname.rstrip(".")+ return hostname or ""++ @staticmethod+ def _is_private_ip(+ hostname: str,+ allow_private_ips: bool = False,+ allow_nat64: Optional[bool] = None,+ _resolved_ips: Optional[List[ResolvedIP]] = None,+ ) -> bool:+ """+ Check if hostname resolves to a private IP address.++ Args:+ hostname: Hostname to check+ allow_private_ips: When True, RFC1918 / CGNAT / loopback /+ link-local / IPv6 ULA are NOT considered private. Cloud+ metadata IPs and NAT64-wrapped metadata IPs are blocked+ regardless — the operator opt-in cannot license IMDS+ exposure.+ allow_nat64: Override for the ``security.allow_nat64`` carve-out.+ None (default) reads the env setting; an explicit bool+ answers the hint probe.++ Returns:+ True if hostname is a private IP or localhost (subject to+ allow_private_ips), or wraps a metadata IP unconditionally+ """+ return NotificationURLValidator._host_blocks_at_level(+ hostname,+ allow_private_ips=allow_private_ips,+ allow_nat64=allow_nat64,+ resolved_ips=_resolved_ips,+ )@staticmethoddef validate_service_url(@@ -199,22 +281,43 @@ class NotificationURLValidator:allow_private_ips: bool = False,allow_nat64: Optional[bool] = None,) -> Tuple[bool, Optional[str]]:- """- Validate a notification service URL for security issues.+ """Validate a notification service URL for security issues.- This function prevents SSRF attacks by validating that service URLs- use safe protocols and don't target private/internal infrastructure.+ Thin public wrapper around ``_validate_service_url_impl``.+ Always performs its own DNS resolution (no caller-supplied+ resolution state).Args:url: Service URL to validate (e.g., "discord://webhook_id/token")allow_private_ips: Whether to allow private IPs (default: False)Set to True for development/testing environments- allow_nat64: Override for the ``security.allow_nat64`` carve-out- (default None = read env). An explicit True asks- "would enabling NAT64 unblock this URL?", used by- the notification "Test" admin hint (see- ``_admin_hint_would_help``) to decide whether to- surface ``LDR_SECURITY_ALLOW_NAT64``.+ allow_nat64: Override for the ``security.allow_nat64``+ carve-out. None (default) reads the env setting;+ an explicit bool overrides it.++ Returns:+ Tuple of (is_valid, error_message)+ """+ return NotificationURLValidator._validate_service_url_impl(+ url,+ allow_private_ips=allow_private_ips,+ allow_nat64=allow_nat64,+ )++ @staticmethod+ def _validate_service_url_impl(+ url: str,+ allow_private_ips: bool = False,+ allow_nat64: Optional[bool] = None,+ resolved_ips: Optional[List[ResolvedIP]] = None,+ ) -> Tuple[bool, Optional[str]]:+ """Internal validation with optional pre-resolved DNS state.++ ``resolved_ips`` is trusted internal state used by+ ``validate_service_url_with_hint`` to share a single DNS+ resolution across multiple policy decisions. Must NEVER be+ exposed on the public API — callers could pass ``[]`` to+ bypass hostname resolution and private-IP checks.Returns:Tuple of (is_valid, error_message)@@ -233,21 +336,18 @@ class NotificationURLValidator:Caller contract:``notifications.service.NotificationService.test_service``- matches the prefix ``"Blocked private/internal IP address:"``- (pinned as ``PRIVATE_IP_REJECTION_PREFIX`` in service.py) to- decide whether to append the- LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS / LDR_SECURITY_ALLOW_NAT64- admin hint. The decision is delegated back to this validator- via ``_admin_hint_would_help(url)``, which probes each operator- escape hatch independently: a call with ``allow_private_ips=True``- asks whether that flag would unblock the URL, and a call with- ``allow_nat64=True`` asks the same for the NAT64 carve-out (the- only flag that can unblock a NAT64-wrapped non-metadata- destination). If NEITHER unblocks it, the URL targets an- always-blocked category (cloud-metadata IPs, 6to4, Teredo,- discard prefix, IPv4-mapped IPv6 of metadata, NAT64-wrapped- metadata) and the hint is suppressed because naming the env- var would mislead. The parametrized+ calls ``validate_service_url_with_hint`` (single-pass sibling+ below) to obtain the validation result AND, when the URL is+ rejected, a ``hint_would_help`` flag indicating whether the+ rejection targets a recoverable destination — one that+ ``LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true`` (for RFC1918 /+ CGNAT / loopback / link-local / IPv6 ULA, plus NAT64-wrapped+ non-metadata destinations via the NAT64 carve-out) would+ actually unblock. If ``hint_would_help`` is False the URL+ targets an always-blocked category (cloud-metadata IPs, 6to4,+ Teredo, discard prefix, IPv4-mapped IPv6 of metadata,+ NAT64-wrapped metadata) and the hint is suppressed because+ naming the env var would mislead. The parametrizedintegration test ``test_test_service_ip_rejection_matrix``in tests/web/services/test_notification_coverage.py locksthis contract end-to-end across every IP category — if the@@ -348,15 +448,13 @@ class NotificationURLValidator:"Blocked notification URL with non-ASCII / control bytes in host")return False, "URL host contains disallowed characters"- if hostname and hostname.startswith("[") and hostname.endswith("]"):- hostname = hostname[1:-1]- if hostname:- hostname = hostname.rstrip(".")+ hostname = NotificationURLValidator._normalize_host(hostname)if scheme in ("http", "https"):if hostname and NotificationURLValidator._is_private_ip(hostname,allow_private_ips=allow_private_ips,+ _resolved_ips=resolved_ips,allow_nat64=allow_nat64,):logger.warning(@@ -365,15 +463,21 @@ class NotificationURLValidator:)return (False,- f"Blocked private/internal IP address: {hostname}",+ f"{NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX} {hostname}",)else:# Plugin-scheme IMDS guard. ``allow_private_ips=True`` leaves# ALWAYS_BLOCKED_METADATA_IPS and NAT64-wrapped metadata as# the only active blocks in ``_is_private_ip`` — exactly the# set we want to enforce regardless of operator flags.+ #+ # resolved_ips is intentionally NOT forwarded here: the+ # plugin-scheme guard must always perform its own resolution+ # (it cannot rely on http(s)-centric pre-resolution).if hostname and NotificationURLValidator._is_private_ip(- hostname, allow_private_ips=True, allow_nat64=allow_nat64+ hostname,+ allow_private_ips=True,+ allow_nat64=allow_nat64,):logger.warning(f"Blocked cloud-metadata IP in notification URL: {hostname}"@@ -386,6 +490,217 @@ class NotificationURLValidator:# Passed all security checksreturn True, None+ @staticmethod+ def _compute_hint(+ hostname: str,+ resolved_ips: Optional[List[ResolvedIP]],+ ) -> bool:+ """Return True iff the combined elevated policy+ (LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true AND+ LDR_SECURITY_ALLOW_NAT64=true) would unblock every resolved+ IP. Probing both flags jointly — rather than each in+ isolation — is required for mixed address lists where+ neither flag alone unblocks every IP (e.g. 10.0.0.1 needs+ the private-IPs flag, 64:ff9b::5db8:d822 needs the NAT64+ flag).+ """+ hint = not NotificationURLValidator._host_blocks_at_level(+ hostname,+ allow_private_ips=True,+ allow_nat64=True,+ resolved_ips=resolved_ips,+ )+ if not hint:+ logger.debug(+ "hint suppressed: {} targets an always-blocked "+ "category (metadata / 6to4 / Teredo / discard / "+ "NAT64-wrapped metadata)",+ hostname,+ )+ return hint++ @staticmethod+ def validate_service_url_with_hint(+ url: str, allow_private_ips: bool = False+ ) -> Tuple[bool, Optional[str], bool]:+ """Validate URL and compute the admin-hint decision, using a+ two-phase approach to ensure DNS is only queried for URLs that+ pass ALL deterministic (non-network) checks.++ Phase 1 — structural validation (no DNS):+ Calls ``_validate_service_url_impl`` with ``resolved_ips=[]``, which+ suppresses DNS for the http(s) private-IP check. IP literals+ are still evaluated directly. Plugin-scheme IMDS guard resolves+ internally. This means bad schemes, illegal characters, parse+ errors, and malformed URLs are all rejected WITHOUT network+ activity.++ Phase 2 — DNS resolution + IP policy (http(s) hostnames only):+ Only reached for http(s) URLs with non-literal hostnames that+ passed Phase 1. Resolves DNS ONCE and shares the result across+ the default-level rejection and the combined elevated-policy hint check,+ closing the DNS-rebinding TOCTOU window. When DNS fails, the+ failure is authoritative (``[]`` sentinel prevents retries).++ For IP literals there is no DNS to rebind.++ Args:+ url: Service URL to validate+ allow_private_ips: Operator-level flag. When True, the+ private address categories (RFC1918 / CGNAT / loopback+ / link-local / IPv6 ULA) are already permitted at this+ level. ``hint_would_help`` may still be True for a+ rejected NAT64-wrapped non-metadata destination,+ because the NAT64 carve-out is governed by the separate+ ``allow_nat64`` path rather than this flag.++ Returns:+ ``(is_valid, error_msg, hint_would_help)``:++ * ``is_valid`` — True iff URL passes at the requested+ ``allow_private_ips`` level.+ * ``error_msg`` — None on success, the validator's reason+ on rejection (identical to ``validate_service_url``).+ * ``hint_would_help`` — True iff enabling the documented+ escape hatches together+ (``LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS`` for+ RFC1918/CGNAT/loopback/link-local/IPv6 ULA, and+ ``LDR_SECURITY_ALLOW_NAT64`` for NAT64-wrapped+ non-metadata destinations) would unblock all resolved+ addresses — covering cases needing one or both flags.+ Always False when ``is_valid`` is True. May still be+ True under ``allow_private_ips=True`` for a rejected+ NAT64-wrapped non-metadata destination, because the+ NAT64 carve-out is governed by the separate+ ``allow_nat64`` path. Only meaningful when+ ``error_msg`` starts with+ ``PRIVATE_IP_REJECTION_PREFIX`` (i.e., the URL was+ rejected for an http(s) private-IP target).++ Caller contract:+ ``notifications.service.NotificationService.test_service``+ calls this to surface the validator's reason AND decide+ whether to append the admin env-var hint in a single pass.+ The previous design called ``validate_service_url`` two to+ three times (once at the default level, then one or two+ more via the former ``_admin_hint_would_help`` helper for+ the private-IPs and NAT64 probes), opening a DNS-rebinding+ window between the resolutions. The parametrized test+ ``test_test_service_ip_rejection_matrix`` and the direct+ contract test+ ``test_validate_service_url_with_hint_contract`` in+ tests/web/services/test_notification_coverage.py pin this+ end-to-end.+ """+ if not url or not isinstance(url, str):+ return False, "Service URL must be a non-empty string", False++ url = url.strip()++ if allow_private_ips and not url:+ return (+ False,+ "Service URL must have a protocol (e.g., https://)",+ False,+ )++ # ------------------------------------------------------------------+ # Phase 1: structural validation (no DNS for http(s) hostnames).+ #+ # resolved_ips=[] suppresses DNS in the http(s) private-IP check+ # (_host_blocks_at_level treats [] as "no blocked IPs"). IP+ # literals are still checked directly. Plugin-scheme IMDS guard+ # resolves internally (does not use resolved_ips). This means+ # ALL deterministic rejections (bad scheme, illegal chars, parse+ # errors, non-ASCII host, invalid structure) complete before any+ # attacker-controlled DNS query.+ # ------------------------------------------------------------------+ is_valid, error_msg = (+ NotificationURLValidator._validate_service_url_impl(+ url,+ allow_private_ips=allow_private_ips,+ resolved_ips=[],+ )+ )++ # If the URL was rejected in Phase 1, no DNS was needed.+ if not is_valid:+ if not error_msg or not error_msg.startswith(+ NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX+ ):+ logger.debug(+ "hint suppressed: non-private-IP rejection ({})",+ error_msg[:60] if error_msg else "<none>",+ )+ return False, error_msg, False+ # Private-IP rejection — must be an IP literal (hostnames+ # weren't resolved in Phase 1). Compute hint without DNS.+ hostname = NotificationURLValidator._normalize_host(+ NotificationURLValidator._extract_host(url)+ )+ if not hostname:+ return False, error_msg, False+ return (+ False,+ error_msg,+ NotificationURLValidator._compute_hint(hostname, None),+ )++ # URL passed Phase 1. For non-http(s) URLs or IP literals,+ # validation is complete.+ try:+ parsed_scheme = urlparse(url).scheme.lower()+ except Exception:+ parsed_scheme = ""++ hostname = NotificationURLValidator._normalize_host(+ NotificationURLValidator._extract_host(url)+ )++ is_http_hostname = False+ if hostname and parsed_scheme in ("http", "https"):+ try:+ ipaddress.ip_address(hostname)+ except ValueError:+ is_http_hostname = True++ if not is_http_hostname:+ # Non-http(s) or IP literal — fully validated in Phase 1.+ return True, None, False++ # ------------------------------------------------------------------+ # Phase 2: resolve DNS ONCE for the http(s) hostname and run the+ # real IP check. resolved_ips is authoritative for the rejection+ # and hint check — no additional DNS lookups.+ #+ # [] = DNS attempted and failed (fail-open, no retry).+ # [...] = resolved IPs shared across all policy decisions.+ # ------------------------------------------------------------------+ dns_result = NotificationURLValidator._resolve_hostname_ips(hostname)+ resolved_ips: Optional[List[ResolvedIP]] = (+ dns_result if dns_result is not None else []+ )++ is_valid, error_msg = (+ NotificationURLValidator._validate_service_url_impl(+ url,+ allow_private_ips=allow_private_ips,+ resolved_ips=resolved_ips,+ )+ )+ if is_valid:+ return True, None, False+ if not error_msg or not error_msg.startswith(+ NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX+ ):+ return False, error_msg, False++ return (+ False,+ error_msg,+ NotificationURLValidator._compute_hint(hostname, resolved_ips),+ )+@staticmethoddef validate_service_url_strict(url: str, allow_private_ips: bool = Falsediff --git a/tests/notifications/test_service_edge_cases.py b/tests/notifications/test_service_edge_cases.pyindex c142375513..12d383af39 100644--- a/tests/notifications/test_service_edge_cases.py+++ b/tests/notifications/test_service_edge_cases.py@@ -13,10 +13,11 @@ class TestTestServiceErrorPaths:@patch("local_deep_research.notifications.service.apprise.Apprise")@patch(- "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",+ "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url_with_hint",return_value=(False,"Blocked private/internal IP address: 169.254.169.254",+ False,),)def test_ssrf_validation_fails(self, mock_validator, mock_apprise_class):@@ -37,8 +38,8 @@ class TestTestServiceErrorPaths:@patch("local_deep_research.notifications.service.apprise.Apprise")@patch(- "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",- return_value=(True, None),+ "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url_with_hint",+ return_value=(True, None, False),)def test_apprise_add_fails(self, mock_validator, mock_apprise_class):mock_instance = MagicMock()@@ -52,8 +53,8 @@ class TestTestServiceErrorPaths:@patch("local_deep_research.notifications.service.apprise.Apprise")@patch(- "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",- return_value=(True, None),+ "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url_with_hint",+ return_value=(True, None, False),)def test_apprise_notify_fails(self, mock_validator, mock_apprise_class):mock_instance = MagicMock()@@ -68,8 +69,8 @@ class TestTestServiceErrorPaths:@patch("local_deep_research.notifications.service.apprise.Apprise")@patch(- "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",- return_value=(True, None),+ "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url_with_hint",+ return_value=(True, None, False),)def test_success_path(self, mock_validator, mock_apprise_class):mock_instance = MagicMock()@@ -84,8 +85,8 @@ class TestTestServiceErrorPaths:@patch("local_deep_research.notifications.service.apprise.Apprise")@patch(- "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",- return_value=(False, "Blocked unsafe protocol: javascript"),+ "local_deep_research.notifications.service.NotificationURLValidator.validate_service_url_with_hint",+ return_value=(False, "Blocked unsafe protocol: javascript", False),)def test_validation_reason_surfaced_without_internals(self, mock_validator, mock_apprise_class@@ -137,3 +138,22 @@ class TestGetServiceTypePatterns:def test_smtps_detection(self):service = NotificationService(outbound_allowed=True)assert service.get_service_type("smtps://user:[email protected]") == "smtp"+++class TestCompatibilityExports:+ def test_private_ip_rejection_prefix_aliases_validator_constant(self):+ # Given: the validator's canonical prefix.+ from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+ )++ # When: callers import the legacy service-level name.+ from local_deep_research.notifications.service import (+ PRIVATE_IP_REJECTION_PREFIX,+ )++ # Then: it is the validator's canonical constant.+ assert (+ PRIVATE_IP_REJECTION_PREFIX+ is NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX+ )diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.pyindex dfec684ad3..a6b5d84ac0 100644--- a/tests/web/services/test_notification_coverage.py+++ b/tests/web/services/test_notification_coverage.py@@ -13,6 +13,7 @@ Covers:- Exception hierarchy"""+import ipaddressimport threadingfrom collections import dequefrom datetime import datetime, timedelta, timezone@@ -399,7 +400,11 @@ class TestNotificationService:@patch("local_deep_research.notifications.service.NotificationURLValidator")@patch("local_deep_research.notifications.service.apprise.Apprise")def test_test_service_success(self, MockApprise, MockValidator):- MockValidator.validate_service_url.return_value = (True, None)+ MockValidator.validate_service_url_with_hint.return_value = (+ True,+ None,+ False,+ )mock_instance = MockApprise.return_valuemock_instance.add.return_value = Truemock_instance.notify.return_value = True@@ -410,7 +415,11 @@ class TestNotificationService:@patch("local_deep_research.notifications.service.NotificationURLValidator")def test_test_service_invalid_url(self, MockValidator):- MockValidator.validate_service_url.return_value = (False, "blocked")+ MockValidator.validate_service_url_with_hint.return_value = (+ False,+ "blocked",+ False,+ )svc = NotificationService(outbound_allowed=True)result = svc.test_service("file:///etc/passwd")@@ -426,9 +435,10 @@ class TestNotificationService:# generic "Invalid notification service URL." Without this, an# IPv6-only operator hitting the NAT64 block has no signal at# all that there's a server-side opt-in to flip.- MockValidator.validate_service_url.return_value = (+ MockValidator.validate_service_url_with_hint.return_value = (False,"Blocked unsafe protocol: file",+ False,)svc = NotificationService(outbound_allowed=True)@@ -486,6 +496,21 @@ class TestNotificationService:False,id="ipv4-mapped-ipv6-of-imds",),+ pytest.param(+ "http://[::169.254.169.254]/",+ False,+ id="ipv4-compat-ipv6-of-imds",+ ),+ # NAT64-wrapped metadata beyond AWS IMDS — every metadata IP+ # in ALWAYS_BLOCKED_METADATA_IPS is supposed to be caught+ # through NAT64. Pin Alibaba (100.100.100.200) so a+ # regression in is_nat64_wrapped_metadata_ip for non-IMDS+ # metadata IPs cannot slip through.+ pytest.param(+ "http://[64:ff9b::6464:64c8]/",+ False,+ id="nat64-rfc6052-wrap-of-alibaba-metadata",+ ),# Plugin-scheme metadata (different validator prefix)pytest.param("signal://169.254.169.254:8080/path",@@ -525,6 +550,29 @@ class TestNotificationService:True,id="nat64-rfc8215-wrap-of-public",),+ # IPv4-mapped IPv6 of recoverable IPv4 — the validator's+ # ipv4_mapped unwrap path must classify these as recoverable,+ # not always-blocked (only IPv4-mapped of metadata is+ # always-blocked).+ pytest.param(+ "http://[::ffff:127.0.0.1]/",+ True,+ id="ipv4-mapped-ipv6-of-loopback",+ ),+ pytest.param(+ "http://[::ffff:10.0.0.1]/",+ 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):@@ -565,10 +613,452 @@ class TestNotificationService:f"got: {result['error']!r}")+ # ------------------------------------------------------------------+ # validate_service_url_with_hint — direct unit tests on the hint+ # decision (third tuple element).+ #+ # The matrix above exercises this end-to-end via test_service for+ # http(s) URLs. Plugin-scheme URLs reach test_service via a+ # different validator prefix ("Blocked cloud-metadata IP+ # address:") and the prefix guard inside+ # validate_service_url_with_hint short-circuits before the hint+ # decision is reached — meaning the plugin-scheme rows in the+ # matrix pass via the prefix-guard fall-through, not via the hint+ # decision. These direct unit tests pin the hint decision so the+ # prefix guard cannot mask a regression in the hint logic itself.+ # ------------------------------------------------------------------++ @pytest.mark.parametrize(+ "url,expected",+ [+ # Recoverable: env var WOULD unblock → True+ ("http://127.0.0.1/", True),+ ("http://10.0.0.1/", True),+ ("http://192.168.1.1/", True),+ ("http://100.64.0.1/", True),+ ("http://[::1]/", True),+ ("http://[fc00::1]/", True),+ ("http://[fe80::1]/", True),+ ("http://localhost/", True),+ # NAT64-wrapped NON-metadata IPv4 — hint is True ONLY via+ # the NAT64 carve-out probe, not the private-IPs probe.+ ("http://[64:ff9b::5db8:d822]/", True),+ ("http://[64:ff9b:1::5db8:d822]/", True),+ # Always-blocked: env var CANNOT unblock → False+ ("http://169.254.169.254/", False),+ ("http://169.254.170.2/", False),+ ("http://100.100.100.200/", False),+ ("http://[64:ff9b::a9fe:a9fe]/", False),+ ("http://[64:ff9b::6464:64c8]/", False),+ ("http://[2002:7f00:1::]/", False),+ ("http://[2001::]/", False),+ ("http://[100::]/", False),+ ("http://[::169.254.169.254]/", False),+ ("http://[::ffff:169.254.169.254]/", False),+ # Plugin-scheme metadata — never reaches the hint branch via+ # test_service (prefix guard short-circuits earlier) but pin+ # the decision directly in case a future caller uses it.+ ("signal://169.254.169.254/", False),+ ],+ )+ def test_validate_service_url_with_hint_contract(self, url, expected):+ """Pin validate_service_url_with_hint's hint decision so the+ prefix-guard fall-through cannot mask a regression in the+ hint logic itself."""+ _is_valid, _error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(url)+ )+ assert hint is expected, f"Expected hint={expected} for {url}"++ # ------------------------------------------------------------------+ # validate_service_url_with_hint — single-pass DNS, branch coverage+ # ------------------------------------------------------------------++ def test_with_hint_resolves_dns_exactly_once_for_hostname(self):+ """The single-pass DNS claim: _resolve_hostname_ips must be+ called exactly once for a hostname URL, not per-probe. The+ rejection AND the hint must both fire — otherwise call_count==1+ is vacuous (the hint path was skipped, not shared)."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=[ipaddress.ip_address("10.0.0.1")],+ ) as mock_resolve:+ is_valid, error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://private.example.com/"+ )+ )+ assert is_valid is False, (+ "URL must be rejected; otherwise the hint path is never "+ "reached and call_count==1 is meaningless"+ )+ assert hint is True, "Hint must fire for RFC1918 10.0.0.1"+ assert mock_resolve.call_count == 1, (+ f"Expected exactly 1 DNS resolution, got {mock_resolve.call_count}"+ )++ @pytest.mark.parametrize(+ "allow_private_ips",+ [False, True],+ ids=["allow_private_ips-False", "allow_private_ips-True"],+ )+ def test_with_hint_mixed_private_and_nat64_combined_hint(+ self, monkeypatch, allow_private_ips+ ):+ """A DNS resolution returning BOTH an RFC1918 private IPv4+ (10.0.0.1) AND a NAT64-wrapped public IPv6+ (64:ff9b::5db8:d822) must still surface the admin hint.+ Neither single escape hatch alone unblocks the mixed list —+ LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true leaves the NAT64 IP+ blocked, and LDR_SECURITY_ALLOW_NAT64=true leaves the+ RFC1918 IP blocked — but setting BOTH together would.+ _compute_hint must evaluate the combined elevated policy+ against the shared resolved_ips. Also pins: DNS is queried+ exactly once for the hostname, and the URL is rejected at+ the default level for both allow_private_ips values."""+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "false")+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=[+ ipaddress.ip_address("10.0.0.1"),+ ipaddress.ip_address("64:ff9b::5db8:d822"),+ ],+ ) as mock_resolve:+ is_valid, _error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://mixed.example.com/",+ allow_private_ips=allow_private_ips,+ )+ )+ assert is_valid is False, (+ "URL must be rejected; otherwise the hint path is never reached"+ )+ assert hint is True, (+ "Hint must fire for mixed private+NAT64 list — the "+ "combined elevated policy (both env vars) would unblock "+ "both IPs"+ )+ mock_resolve.assert_called_once_with("mixed.example.com")++ def test_with_hint_allow_private_ips_private_ip_no_hint(self):+ """With allow_private_ips=True, an RFC1918 private IP is+ allowed and the hint is False — the operator already opted in,+ so no private-IP escape hatch is left to suggest."""+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://192.168.1.1/hook", allow_private_ips=True+ )+ )+ assert is_valid is True+ assert error is None+ assert hint is False++ def test_with_hint_allow_private_ips_metadata_blocks_no_hint(self):+ """With allow_private_ips=True, cloud-metadata IPs are still+ blocked (always-blocked category) and the hint is False —+ no operator escape hatch exists for metadata."""+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://169.254.169.254/", allow_private_ips=True+ )+ )+ assert is_valid is False+ assert hint is False++ def test_with_hint_allow_private_ips_nat64_hint_fires(self):+ """With allow_private_ips=True, NAT64-wrapped non-metadata IPs+ are still blocked (NAT64 prefixes sit outside private ranges)+ and the hint fires to suggest LDR_SECURITY_ALLOW_NAT64."""+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://[64:ff9b::5db8:d822]/", allow_private_ips=True+ )+ )+ assert is_valid is False, (+ "NAT64-wrapped URL must be blocked even with allow_private_ips"+ )+ assert hint is True, (+ "Hint must fire for NAT64-wrapped URL even with "+ "allow_private_ips=True"+ )++ def test_with_hint_allow_private_ips_whitespace_only_skips_dns(self):+ """Preserves the allow_private_ips=True protocol-error contract+ for whitespace-only input: returns the protocol-missing error+ and skips DNS — there is no hostname to resolve, so+ _resolve_hostname_ips must never be called."""+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as mock_resolve:+ result = NotificationURLValidator.validate_service_url_with_hint(+ " ", allow_private_ips=True+ )+ assert result == (+ False,+ "Service URL must have a protocol (e.g., https://)",+ False,+ )+ mock_resolve.assert_not_called()++ def test_with_hint_valid_url_returns_no_hint(self):+ """A valid URL returns (True, None, False)."""+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://8.8.8.8/"+ )+ )+ assert (is_valid, error, hint) == (True, None, False)++ def test_with_hint_dns_failure_attempted_exactly_once(self):+ """When DNS fails, the failure is authoritative — no retry+ inside validate_service_url or the hint probes. The URL is+ allowed (fail-open) and _resolve_hostname_ips is called+ exactly once. This is the sentinel design: an empty list+ distinguishes 'DNS attempted and failed' from 'not supplied'."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=None,+ ) as mock_resolve:+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://flaky.example.com/"+ )+ )+ assert mock_resolve.call_count == 1, (+ f"Expected exactly 1 DNS resolution on failure, got "+ f"{mock_resolve.call_count}"+ )+ assert is_valid is True, (+ "DNS failure must fail-open (allow), not retry-and-reject"+ )+ assert error is None+ assert hint is False++ def test_with_hint_leading_whitespace_preserves_hint(self):+ """Leading whitespace must not suppress the hint — the URL+ is stripped before host extraction."""+ is_valid, error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ " http://10.0.0.1/ "+ )+ )+ assert is_valid is False+ assert hint is True++ def test_with_hint_rfc_illegal_url_skips_dns(self):+ """URLs with RFC-illegal characters (backslash, control bytes)+ must NOT trigger DNS pre-resolution — they are deterministically+ rejected by validate_service_url without network activity."""+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as mock_resolve:+ is_valid, _error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://evil.com\\@127.0.0.1/"+ )+ )+ assert is_valid is False+ assert hint is False+ mock_resolve.assert_not_called()++ @pytest.mark.parametrize(+ "url",+ [+ "http://example.com:99999/",+ "http://[::1",+ "http://",+ ],+ ids=["invalid-port", "malformed-ipv6", "empty-host"],+ )+ def test_with_hint_malformed_url_skips_dns(self, url):+ """Malformed HTTP(S) URLs that parse_url rejects must NOT trigger+ DNS pre-resolution. _extract_host returns None on+ LocationParseError, so hostname is empty and DNS is skipped."""+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as mock_resolve:+ NotificationURLValidator.validate_service_url_with_hint(url)+ mock_resolve.assert_not_called()++ def test_with_hint_credential_url_ip_literal_skips_dns(self):+ """Credential-bearing HTTP(S) URLs with IP-literal hosts must+ NOT trigger DNS — the IP is checked directly. The URL is+ rejected (private IP) without any network activity."""+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as mock_resolve:+ is_valid, _error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://user:[email protected]/"+ )+ )+ assert is_valid is False+ assert hint is True+ mock_resolve.assert_not_called()++ def test_with_hint_credential_url_hostname_needs_dns(self):+ """Credential-bearing HTTP(S) URLs with hostname hosts DO+ require DNS — the URL is syntactically valid (RFC 3986 allows+ userinfo) and the IP check cannot complete without resolving+ the hostname. DNS here is correct, not a bug."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=[ipaddress.ip_address("10.0.0.1")],+ ) as mock_resolve:+ is_valid, _error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://user:[email protected]/"+ )+ )+ assert is_valid is False+ assert hint is True+ assert mock_resolve.call_count == 1++ def test_with_hint_allow_private_ips_nat64_hostname_single_dns(+ self, monkeypatch+ ):+ """hostname + allow_private_ips=True + NAT64 rejection must+ resolve DNS exactly once. The unified two-phase flow shares+ the resolution across rejection and hint probes. The env is+ pinned to NAT64-disabled so the rejection + hint are+ deterministic regardless of any ambient+ LDR_SECURITY_ALLOW_NAT64."""+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "false")+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=[ipaddress.ip_address("64:ff9b::5db8:d822")],+ ) as mock_resolve:+ is_valid, _error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://nat64.example.com/", allow_private_ips=True+ )+ )+ assert mock_resolve.call_count == 1, (+ f"Expected 1 DNS call, got {mock_resolve.call_count}"+ )+ assert is_valid is False, (+ "NAT64-wrapped must block even with private IPs"+ )+ assert hint is True, "NAT64 hint must fire"++ def test_validate_service_url_allow_nat64_true_unblocks_nat64(self):+ """allow_nat64=True forwarded through _is_private_ip must+ unblock NAT64-wrapped non-metadata IPv4 that is otherwise+ blocked."""+ is_valid_default, _ = NotificationURLValidator.validate_service_url(+ "http://[64:ff9b::5db8:d822]/"+ )+ assert is_valid_default is False, "NAT64 prefix must block by default"+ is_valid_nat64, _ = NotificationURLValidator.validate_service_url(+ "http://[64:ff9b::5db8:d822]/", allow_nat64=True+ )+ assert is_valid_nat64 is True, "allow_nat64=True must unblock NAT64"++ def test_validate_service_url_allow_nat64_false_overrides_env(+ self, monkeypatch+ ):+ """allow_nat64=False must override an enabled env setting,+ blocking NAT64-wrapped destinations even when the env var+ says to allow them."""+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")+ is_valid, _ = NotificationURLValidator.validate_service_url(+ "http://[64:ff9b::5db8:d822]/", allow_nat64=False+ )+ assert is_valid is False, (+ "allow_nat64=False must override env and block NAT64"+ )++ def test_validate_service_url_positional_allow_nat64_compat(self):+ """The third positional argument must be allow_nat64 (not+ _resolved_ips) to preserve backwards compatibility with+ callers using positional args: validate_service_url(url, False, True)."""+ is_valid, _ = NotificationURLValidator.validate_service_url(+ "http://[64:ff9b::5db8:d822]/", False, True+ )+ assert is_valid is True, (+ "Positional (url, False, True) must pass allow_nat64=True"+ )++ def test_validate_service_url_plugin_scheme_forwards_allow_nat64(+ self, monkeypatch+ ):+ """Plugin-scheme IMDS guard must forward allow_nat64 so callers+ can override the env setting for plugin URLs too."""+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")+ is_valid, _ = NotificationURLValidator.validate_service_url(+ "signal://[64:ff9b::5db8:d822]/", allow_nat64=False+ )+ assert is_valid is False, (+ "Plugin-scheme must forward allow_nat64=False to block NAT64"+ )++ def test_with_hint_dual_stack_one_private_blocks(self):+ """A hostname resolving to BOTH a public and a private IP must+ be BLOCKED — the loop in _host_blocks_at_level checks every+ resolved IP. This is the real-world dual-stack case where a+ short-circuit regression would create an SSRF bypass."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=[+ ipaddress.ip_address("93.184.216.34"),+ ipaddress.ip_address("10.0.0.1"),+ ],+ ) as mock_resolve:+ is_valid, _error, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://dual-stack.example.com/"+ )+ )+ assert mock_resolve.call_count == 1+ assert is_valid is False, (+ "Dual-stack with one private IP must be blocked"+ )+ assert hint is True++ def test_with_hint_consistent_dns_failure_fails_open(self):+ """When DNS consistently fails (all resolutions return None),+ the URL is ALLOWED (fail-open). This is the documented+ historical behaviour. A future change to fail-closed must be+ a deliberate decision, not a silent regression."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=None,+ ):+ is_valid, error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ "http://unresolvable.example.com/"+ )+ )+ assert is_valid is True, "Consistent DNS failure must fail-open (allow)"+ assert error_msg is None+ assert hint is False++ @pytest.mark.parametrize("bad_input", [None, 123, "", " "])+ def test_with_hint_non_string_returns_tuple_not_crash(self, bad_input):+ """validate_service_url_with_hint must return a (False, msg,+ False) tuple for non-string / empty input, never raise."""+ is_valid, error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(bad_input)+ )+ assert is_valid is False+ assert error_msg is not None+ assert hint is False+@patch("local_deep_research.notifications.service.NotificationURLValidator")@patch("local_deep_research.notifications.service.apprise.Apprise")def test_test_service_add_failure(self, MockApprise, MockValidator):- MockValidator.validate_service_url.return_value = (True, None)+ MockValidator.validate_service_url_with_hint.return_value = (+ True,+ None,+ False,+ )mock_instance = MockApprise.return_valuemock_instance.add.return_value = False@@ -580,7 +1070,11 @@ class TestNotificationService:@patch("local_deep_research.notifications.service.NotificationURLValidator")@patch("local_deep_research.notifications.service.apprise.Apprise")def test_test_service_notify_failure(self, MockApprise, MockValidator):- MockValidator.validate_service_url.return_value = (True, None)+ MockValidator.validate_service_url_with_hint.return_value = (+ True,+ None,+ False,+ )mock_instance = MockApprise.return_valuemock_instance.add.return_value = Truemock_instance.notify.return_value = False@@ -592,7 +1086,9 @@ class TestNotificationService:@patch("local_deep_research.notifications.service.NotificationURLValidator")def test_test_service_exception(self, MockValidator):- MockValidator.validate_service_url.side_effect = RuntimeError("boom")+ MockValidator.validate_service_url_with_hint.side_effect = RuntimeError(+ "boom"+ )svc = NotificationService(outbound_allowed=True)result = svc.test_service("discord://id/token")@@ -604,7 +1100,11 @@ class TestNotificationService:# (today it never does — every False branch sets a reason), the# user still sees an actionable message rather than an empty# string. Pins the `error_msg or "Invalid..."` guard.- MockValidator.validate_service_url.return_value = (False, "")+ MockValidator.validate_service_url_with_hint.return_value = (+ False,+ "",+ False,+ )svc = NotificationService(outbound_allowed=True)result = svc.test_service("https://example.com/hook")