Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(notifications): surface validator reason + admin hint in test-URL error (#4002)

LearningCircuit923b8640b60a
diff --git a/changelog.d/+notification-blocked-url-hint.bugfix.md b/changelog.d/+notification-blocked-url-hint.bugfix.md
new file mode 100644
index 0000000000..388f2b21c4
--- /dev/null
+++ b/changelog.d/+notification-blocked-url-hint.bugfix.md
@@ -0,0 +1,16 @@
+When testing a notification webhook URL through the settings UI, the
+"Test" button now surfaces the validator's reason instead of a generic
+"Invalid notification service URL." message. For private/internal IP
+rejections that the operator can unblock (loopback, RFC1918, CGNAT,
+link-local, IPv6 private), the error message names
+`LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS`; for NAT64-wrapped non-metadata
+destinations on IPv6-only deployments (RFC 6052 well-known
+`64:ff9b::/96` or RFC 8215 local-use `64:ff9b:1::/48`) it names
+`LDR_SECURITY_ALLOW_NAT64` — the only flag that can unblock those, which
+the hint probes for independently. Cloud-metadata IPs are always blocked and
+the env-var hint is intentionally suppressed for them — neither flag
+re-opens metadata, so naming them would mislead the user.
+
+Also adds an "IPv6-only deployments (NAT64)" subsection to
+`docs/SearXNG-Setup.md` so operators routing IPv4 through NAT64 know
+about the opt-in.
diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md
index 4fa4b56b65..ee565c808e 100644
--- a/docs/NOTIFICATIONS.md
+++ b/docs/NOTIFICATIONS.md
@@ -289,6 +289,33 @@ except RateLimitError as e:
- **Cause**: Using database session in background thread (not thread-safe)
- **Fix**: Use settings snapshot pattern as shown in migration guide above
+### Webhook URL Was Rejected
+
+The "Test" button in the notifications settings page returns the validator's reason directly. Common categories and the fix:
+
+**"Blocked private/internal IP address: \<host\>"**
+- **Cause**: The URL resolves to a loopback (`127.0.0.1`, `::1`), RFC1918 (`10.x`, `172.16-31.x`, `192.168.x`), CGNAT (`100.64.0.0/10`), link-local (`169.254.0.0/16`), or IPv6 private (`fc00::/7`, `fe80::/10`) address. The default SSRF policy blocks these for outbound webhooks.
+- **Fix (operator-only, env-only)**: Set `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true` in the server environment. This is intentionally not exposed in the user-writable settings API. Only enable it if the notification endpoints are on a trusted local network.
+- **Fix (IPv6-only deployments using NAT64)**: If the host wraps IPv4 through `64:ff9b::/96` (RFC 6052 well-known) or `64:ff9b:1::/48` (RFC 8215 local-use), additionally set `LDR_SECURITY_ALLOW_NAT64=true`. The opt-in is scoped strictly to those two prefixes — 6to4 (`2002::/16`), Teredo (`2001::/32`), the discard prefix (`100::/64`), and the deprecated IPv4-Compatible IPv6 form (`::/96`) remain blocked.
+- **Note (cloud-metadata IPs)**: If `\<host\>` is a cloud-metadata IP (see the next bullet), the env-var hint above is intentionally **not** surfaced by the "Test" button — neither flag re-opens metadata, so the hint would mislead. The user-visible error is just the bare `"Blocked private/internal IP address: 169.254.169.254"`.
+
+**"Blocked cloud-metadata IP address: \<host\>"**
+- **Cause**: The URL uses an Apprise plugin scheme (`discord://`, `signal://`, `ntfy://`, etc.) whose host resolves to a cloud-metadata endpoint. Plugin schemes bypass the http/https private-IP check (their endpoints are typically LAN-local) but still hit the absolute cloud-metadata block.
+- **Always blocked**: AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud, Tencent — both as plain IPv4 and wrapped through any NAT64 prefix. No env var re-opens these. See [SECURITY.md](../SECURITY.md#cloud-metadata-endpoint-block-list).
+- **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.
+- **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)"**
+- **Cause**: Layer-1 defense against parser-differential SSRF bypasses (GHSA-g23j-2vwm-5c25) — RFC 3986 forbids these characters in URLs.
+- **Fix**: Remove the whitespace / backslash / control bytes. Percent-encode if a legitimate use case requires them.
+
+**"Outbound notifications are disabled. The server administrator must set LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true …"**
+- **Cause**: Server-level master switch is off. See the "Server-Side Opt-In Required" section at the top of this document for the rationale (DNS-rebinding TOCTOU window in Apprise).
+- **Fix (operator-only)**: Set `LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true` after reviewing the residual risk.
+
## See Also
- [Full Configuration Reference](CONFIGURATION.md) - All notification settings, defaults, and environment variables
diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.md
index b5e143bd28..0e645ca54e 100644
--- a/docs/SearXNG-Setup.md
+++ b/docs/SearXNG-Setup.md
@@ -113,6 +113,16 @@ This is intentional and secure because:
2. Private IPs are only accessible from your local network
3. **Cloud metadata endpoints** (AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud, Tencent Cloud — see `ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`) are always blocked to prevent credential theft in cloud environments
+### IPv6-only deployments (NAT64)
+
+The "private IPs allowed" exception above does **not** cover IPv6 transition prefixes. On IPv6-only Kubernetes / cloud deployments (AWS / GKE / Azure IPv6-only nodes) where outbound IPv4 traffic is synthesized through NAT64 (`64:ff9b::/96` RFC 6052 well-known or `64:ff9b:1::/48` RFC 8215 local-use), reaching a SearXNG instance through these prefixes is blocked by default. To opt in, set:
+
+```bash
+LDR_SECURITY_ALLOW_NAT64=true
+```
+
+The opt-in is scoped strictly to the two NAT64 prefixes — 6to4 (`2002::/16`), Teredo (`2001::/32`), the discard prefix (`100::/64`), and the deprecated IPv4-Compatible IPv6 form (`::/96`) remain blocked, and cloud-metadata IPs stay unreachable through any NAT64 wrap. See [SECURITY.md](../SECURITY.md#ipv6-transition-prefix-block-list) for the full rationale.
+
## Troubleshooting
If you encounter errors:
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 734bff25f1..3f86d46c75 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -22,6 +22,52 @@ 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
+
+
# Backward compatibility constants - now handled by Tenacity internally
MAX_RETRY_ATTEMPTS = 3
INITIAL_RETRY_DELAY = 0.5
@@ -293,9 +339,33 @@ class NotificationService:
f"Test service URL validation failed: {error_msg}. "
f"URL: {mask_sensitive_url(url)}"
)
+ # Surface the validator's reason so users know what to fix.
+ # The hostname/scheme echoed here was supplied by the user
+ # in the same request, so this is not a server-side leak.
+ # When the rejection is a recoverable private/internal IP —
+ # one that LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true OR
+ # LDR_SECURITY_ALLOW_NAT64=true would actually unblock —
+ # append the admin escape hatches; the user cannot fix this
+ # themselves. Suppress the hint for always-blocked categories
+ # (metadata, 6to4, Teredo, discard, IPv4-mapped IPv6 of
+ # 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'."
+ )
return {
"success": False,
- "error": "Invalid notification service URL.",
+ "error": user_error,
}
# Create temporary Apprise instance
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index 9918d5b4b8..2c56a41cfd 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -65,7 +65,9 @@ class NotificationURLValidator:
PRIVATE_IP_RANGES = _PRIVATE_IP_RANGES
@staticmethod
- def _ip_matches_blocked_range(ip, allow_private_ips: bool = False) -> bool:
+ def _ip_matches_blocked_range(
+ ip, allow_private_ips: bool = False, allow_nat64: Optional[bool] = None
+ ) -> bool:
"""Block-decision for a parsed IP, delegating to
``ssrf_validator.is_ip_blocked`` so the two validators share a
single source of truth.
@@ -74,6 +76,8 @@ class NotificationURLValidator:
- ALWAYS_BLOCKED_METADATA_IPS (cloud metadata, absolute)
- is_nat64_wrapped_metadata_ip (NAT64-wrapped IMDS, absolute)
- security.allow_nat64 env carve-out for the two NAT64 prefixes
+ (overridable via ``allow_nat64``: None reads env, an explicit
+ bool answers the "would NAT64 unblock this?" hint probe)
- allow_private_ips: when True, RFC1918 / CGNAT / loopback /
link-local / IPv6 ULA are allowed BUT the two absolute checks
above still fire. This closes the historical bypass where
@@ -82,10 +86,18 @@ class NotificationURLValidator:
"""
from .ssrf_validator import is_ip_blocked
- return is_ip_blocked(str(ip), allow_private_ips=allow_private_ips)
+ return is_ip_blocked(
+ str(ip),
+ allow_private_ips=allow_private_ips,
+ allow_nat64=allow_nat64,
+ )
@staticmethod
- def _is_private_ip(hostname: str, allow_private_ips: bool = False) -> bool:
+ def _is_private_ip(
+ hostname: str,
+ allow_private_ips: bool = False,
+ allow_nat64: Optional[bool] = None,
+ ) -> bool:
"""
Check if hostname resolves to a private IP address.
@@ -96,6 +108,11 @@ class NotificationURLValidator:
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
@@ -118,7 +135,9 @@ class NotificationURLValidator:
try:
ip = ipaddress.ip_address(hostname)
return NotificationURLValidator._ip_matches_blocked_range(
- ip, allow_private_ips=allow_private_ips
+ ip,
+ allow_private_ips=allow_private_ips,
+ allow_nat64=allow_nat64,
)
except ValueError:
# Hostname - resolve to IP and check.
@@ -161,7 +180,9 @@ class NotificationURLValidator:
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
+ ip,
+ allow_private_ips=allow_private_ips,
+ allow_nat64=allow_nat64,
):
return True
except (socket.gaierror, OSError, TimeoutError):
@@ -174,7 +195,9 @@ class NotificationURLValidator:
@staticmethod
def validate_service_url(
- url: str, allow_private_ips: bool = False
+ url: str,
+ allow_private_ips: bool = False,
+ allow_nat64: Optional[bool] = None,
) -> Tuple[bool, Optional[str]]:
"""
Validate a notification service URL for security issues.
@@ -186,6 +209,12 @@ class NotificationURLValidator:
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``.
Returns:
Tuple of (is_valid, error_message)
@@ -201,6 +230,29 @@ class NotificationURLValidator:
>>> validate_service_url("http://localhost:5000/webhook")
(False, "Blocked private/internal IP address: localhost")
+
+ 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
+ integration test ``test_test_service_ip_rejection_matrix``
+ in tests/web/services/test_notification_coverage.py locks
+ this contract end-to-end across every IP category — if the
+ wording here changes, that test fails and the call site
+ needs updating.
"""
if not url or not isinstance(url, str):
return False, "Service URL must be a non-empty string"
@@ -296,7 +348,9 @@ class NotificationURLValidator:
if scheme in ("http", "https"):
if hostname and NotificationURLValidator._is_private_ip(
- hostname, allow_private_ips=allow_private_ips
+ hostname,
+ allow_private_ips=allow_private_ips,
+ allow_nat64=allow_nat64,
):
logger.warning(
f"Blocked private/internal IP in notification URL: "
@@ -312,7 +366,7 @@ class NotificationURLValidator:
# the only active blocks in ``_is_private_ip`` — exactly the
# set we want to enforce regardless of operator flags.
if hostname and NotificationURLValidator._is_private_ip(
- hostname, allow_private_ips=True
+ hostname, allow_private_ips=True, allow_nat64=allow_nat64
):
logger.warning(
f"Blocked cloud-metadata IP in notification URL: {hostname}"
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index 5889f15292..7011374b31 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -64,7 +64,10 @@ RFC_FORBIDDEN_URL_CHARS_RE = re.compile(r"[\\\s\x00-\x1f\x7f]")
def is_ip_blocked(
- ip_str: str, allow_localhost: bool = False, allow_private_ips: bool = False
+ ip_str: str,
+ allow_localhost: bool = False,
+ allow_private_ips: bool = False,
+ allow_nat64: Optional[bool] = None,
) -> bool:
"""
Check if an IP address is in a blocked range.
@@ -80,6 +83,14 @@ def is_ip_blocked(
Note: cloud metadata endpoints in ``ALWAYS_BLOCKED_METADATA_IPS``
(AWS / Azure / OCI / DigitalOcean / AlibabaCloud / Tencent / ECS)
are ALWAYS blocked regardless of these flags.
+ allow_nat64: Override for the ``security.allow_nat64`` carve-out.
+ ``None`` (default) reads the env setting — the behavior every
+ existing caller relies on. An explicit ``bool`` answers a
+ hypothetical ("would enabling NAT64 unblock this?") without
+ mutating env; used by the notification "Test" admin hint to
+ decide whether to surface ``LDR_SECURITY_ALLOW_NAT64``. The
+ cloud-metadata always-block above fires first either way, so
+ this can never reopen IMDS.
Returns:
True if IP is blocked, False otherwise
@@ -138,9 +149,17 @@ def is_ip_blocked(
# value is not cached across env mutations. Cloud-metadata IPs are
# ALWAYS blocked above, so this carve-out cannot reopen IMDS via
# the IPv6-wrapped form.
- from ..settings.env_registry import get_env_setting
-
- nat64_allowed = bool(get_env_setting("security.allow_nat64", False))
+ #
+ # allow_nat64 overrides the env read: None (default) preserves every
+ # existing caller; an explicit bool lets the notification "Test"
+ # admin hint ask "would LDR_SECURITY_ALLOW_NAT64=true unblock this?"
+ # without touching process env.
+ if allow_nat64 is None:
+ from ..settings.env_registry import get_env_setting
+
+ nat64_allowed = bool(get_env_setting("security.allow_nat64", False))
+ else:
+ nat64_allowed = allow_nat64
# Check if IP is in any blocked range
for blocked_range in BLOCKED_IP_RANGES:
diff --git a/tests/notifications/test_service_edge_cases.py b/tests/notifications/test_service_edge_cases.py
index e367687deb..c142375513 100644
--- a/tests/notifications/test_service_edge_cases.py
+++ b/tests/notifications/test_service_edge_cases.py
@@ -14,13 +14,26 @@ class TestTestServiceErrorPaths:
@patch("local_deep_research.notifications.service.apprise.Apprise")
@patch(
"local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",
- return_value=(False, "blocked by SSRF check"),
+ return_value=(
+ False,
+ "Blocked private/internal IP address: 169.254.169.254",
+ ),
)
def test_ssrf_validation_fails(self, mock_validator, mock_apprise_class):
+ # The classic SSRF target — AWS IMDS at 169.254.169.254 — is the
+ # canonical fixture for this branch. The hint is intentionally
+ # NOT asserted here: this test pins only that the validator's
+ # reason reaches the user. Hint suppression for always-blocked
+ # categories (metadata, 6to4, Teredo, etc.) is pinned end-to-end
+ # by test_test_service_ip_rejection_matrix in
+ # test_notification_coverage.py.
service = NotificationService(outbound_allowed=True)
result = service.test_service("http://169.254.169.254/metadata")
assert result["success"] is False
- assert "Invalid" in result["error"]
+ # The validator's reason is surfaced verbatim — it echoes only
+ # the user-supplied hostname, so it is not a server-side leak.
+ assert "private/internal IP" in result["error"]
+ assert "169.254.169.254" in result["error"]
@patch("local_deep_research.notifications.service.apprise.Apprise")
@patch(
@@ -72,17 +85,29 @@ class TestTestServiceErrorPaths:
@patch("local_deep_research.notifications.service.apprise.Apprise")
@patch(
"local_deep_research.notifications.service.NotificationURLValidator.validate_service_url",
- return_value=(False, "internal DNS resolution error"),
+ return_value=(False, "Blocked unsafe protocol: javascript"),
)
- def test_validation_error_message_not_leaked(
+ def test_validation_reason_surfaced_without_internals(
self, mock_validator, mock_apprise_class
):
service = NotificationService(outbound_allowed=True)
- result = service.test_service("http://evil.com")
+ result = service.test_service("javascript://evil.com")
assert result["success"] is False
- # Internal error detail should NOT appear in the user-facing message
- assert "internal DNS" not in result["error"]
- assert "Invalid" in result["error"]
+ # The validator's reason IS surfaced (it echoes only the
+ # user-supplied scheme). What must NEVER appear is server-internal
+ # detail: stack traces, exception class names, DNS resolver
+ # internals. The validator's error_msg never contains these, but
+ # pin the contract so a future regression that smuggles them in
+ # fails this test.
+ assert "Blocked unsafe protocol" in result["error"]
+ for forbidden in (
+ "Traceback",
+ "socket.gaierror",
+ "Exception",
+ "internal DNS",
+ "raise ",
+ ):
+ assert forbidden not in result["error"]
class TestGetServiceTypePatterns:
diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.py
index 66a59f2fa5..dfec684ad3 100644
--- a/tests/web/services/test_notification_coverage.py
+++ b/tests/web/services/test_notification_coverage.py
@@ -417,6 +417,154 @@ class TestNotificationService:
assert result["success"] is False
assert "error" in result
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ def test_test_service_invalid_url_surfaces_validator_reason(
+ self, MockValidator
+ ):
+ # Validator's specific reason (e.g. "Blocked unsafe protocol: file")
+ # must reach the user so they can fix it instead of seeing a
+ # 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 = (
+ False,
+ "Blocked unsafe protocol: file",
+ )
+
+ svc = NotificationService(outbound_allowed=True)
+ result = svc.test_service("file:///etc/passwd")
+ assert result["success"] is False
+ assert "Blocked unsafe protocol: file" in result["error"]
+
+ # ------------------------------------------------------------------
+ # IP rejection matrix — single source of truth for which IPs trigger
+ # which user-visible behavior. Add new IP categories here rather
+ # than scattering fixtures across multiple tests. End-to-end against
+ # the REAL NotificationURLValidator (no mock) so validator wording
+ # drift fails here too — see NotificationURLValidator.validate_service_url
+ # docstring for the contract.
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "url,expect_hint",
+ [
+ # --- Always-blocked: admin hint MUST be suppressed ---
+ # (none of these are unblockable via LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS
+ # or LDR_SECURITY_ALLOW_NAT64, so naming those env vars
+ # would mislead the user.)
+ # Cloud-metadata IPv4 (AWS/Azure/OCI/DO IMDS, ECS, Tencent, Alibaba)
+ pytest.param(
+ "http://169.254.169.254/latest/meta-data/", False, id="aws-imds"
+ ),
+ pytest.param("http://169.254.170.2/", False, id="aws-ecs-v3"),
+ pytest.param("http://169.254.170.23/", False, id="aws-ecs-v4"),
+ pytest.param("http://169.254.0.23/", False, id="tencent-metadata"),
+ pytest.param(
+ "http://100.100.100.200/", False, id="alibaba-metadata"
+ ),
+ # NAT64-wrapped metadata
+ pytest.param(
+ "http://[64:ff9b::a9fe:a9fe]/",
+ False,
+ id="nat64-rfc6052-wrap-of-imds",
+ ),
+ pytest.param(
+ "http://[64:ff9b:1::a9fe:a9fe]/",
+ False,
+ id="nat64-rfc8215-wrap-of-imds",
+ ),
+ # IPv6 transition prefixes (non-NAT64, always blocked)
+ pytest.param(
+ "http://[2002:7f00:1::]/",
+ False,
+ id="6to4-wrap-of-loopback",
+ ),
+ pytest.param("http://[2001::]/", False, id="teredo-range"),
+ pytest.param("http://[100::]/", False, id="discard-prefix"),
+ pytest.param(
+ "http://[::ffff:169.254.169.254]/",
+ False,
+ id="ipv4-mapped-ipv6-of-imds",
+ ),
+ # Plugin-scheme metadata (different validator prefix)
+ pytest.param(
+ "signal://169.254.169.254:8080/path",
+ False,
+ id="plugin-scheme-signal-to-imds",
+ ),
+ pytest.param(
+ "discord://169.254.169.254/path",
+ False,
+ id="plugin-scheme-discord-to-imds",
+ ),
+ # --- Recoverable: admin hint MUST appear ---
+ # (LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true would actually
+ # unblock these, so the hint is actionable.)
+ pytest.param("http://127.0.0.1/", True, id="ipv4-loopback"),
+ pytest.param("http://10.0.0.1/", True, id="rfc1918-10"),
+ pytest.param("http://172.16.0.1/", True, id="rfc1918-172-16"),
+ pytest.param("http://192.168.1.1/", True, id="rfc1918-192-168"),
+ pytest.param("http://100.64.0.1/", True, id="cgnat-100-64"),
+ pytest.param("http://[::1]/", True, id="ipv6-loopback"),
+ pytest.param("http://[fc00::1]/", True, id="ula-fc00"),
+ pytest.param("http://[fe80::1]/", True, id="link-local-fe80"),
+ pytest.param("http://localhost/", True, id="localhost-dns"),
+ # NAT64-wrapped NON-metadata IPv4 — recoverable ONLY via
+ # LDR_SECURITY_ALLOW_NAT64=true (the private-IPs flag cannot
+ # unblock the NAT64 prefixes). 64:ff9b::5db8:d822 and the
+ # RFC8215 64:ff9b:1:: variant both wrap 93.184.216.34, a public
+ # IPv4. Guards against the NAT64 hint silently going dead — the
+ # exact IPv6-only/NAT64 deployment the hint exists to help.
+ pytest.param(
+ "http://[64:ff9b::5db8:d822]/",
+ True,
+ id="nat64-rfc6052-wrap-of-public",
+ ),
+ pytest.param(
+ "http://[64:ff9b:1::5db8:d822]/",
+ True,
+ id="nat64-rfc8215-wrap-of-public",
+ ),
+ ],
+ )
+ def test_test_service_ip_rejection_matrix(self, url, expect_hint):
+ """End-to-end against the REAL validator: pin the user-visible
+ behavior for every IP category. If ``expect_hint`` is True, the
+ URL targets a recoverable destination that
+ LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true (private IPs) or
+ LDR_SECURITY_ALLOW_NAT64=true (NAT64-wrapped non-metadata IPv4)
+ would unblock, so the admin hint MUST appear. If False, the URL
+ targets an
+ always-blocked category (cloud-metadata, 6to4, Teredo, discard,
+ IPv4-mapped IPv6 of metadata, NAT64-wrapped metadata,
+ plugin-scheme metadata) and the hint MUST be suppressed — the
+ env var cannot help.
+
+ Single source of truth: add new IP categories to this matrix
+ rather than scattering fixtures across multiple tests. See
+ NotificationURLValidator.validate_service_url docstring.
+ """
+ svc = NotificationService(outbound_allowed=True)
+ result = svc.test_service(url)
+ assert result["success"] is False, f"Expected block for {url}"
+ assert result["error"], f"Empty error for {url}"
+
+ if expect_hint:
+ assert "LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS" in result["error"], (
+ f"Expected admin hint for {url}, got: {result['error']!r}"
+ )
+ assert "LDR_SECURITY_ALLOW_NAT64" in result["error"], (
+ f"Expected NAT64 hint for {url}, got: {result['error']!r}"
+ )
+ else:
+ assert (
+ "LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS" not in result["error"]
+ ), f"Hint should be suppressed for {url}, got: {result['error']!r}"
+ assert "LDR_SECURITY_ALLOW_NAT64" not in result["error"], (
+ f"NAT64 hint should be suppressed for {url}, "
+ f"got: {result['error']!r}"
+ )
+
@patch("local_deep_research.notifications.service.NotificationURLValidator")
@patch("local_deep_research.notifications.service.apprise.Apprise")
def test_test_service_add_failure(self, MockApprise, MockValidator):
@@ -450,6 +598,32 @@ class TestNotificationService:
result = svc.test_service("discord://id/token")
assert result["success"] is False
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ def test_test_service_empty_error_msg_uses_fallback(self, MockValidator):
+ # Defensive fallback: if the validator ever returned (False, "")
+ # (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, "")
+
+ svc = NotificationService(outbound_allowed=True)
+ result = svc.test_service("https://example.com/hook")
+ assert result["success"] is False
+ assert result["error"] == "Invalid notification service URL."
+
+ def test_test_service_master_switch_off_short_circuits(self):
+ # When LDR_NOTIFICATIONS_ALLOW_OUTBOUND=False (the default),
+ # test_service must short-circuit BEFORE the URL is inspected by
+ # the validator. Pins the operator master-switch gate so a
+ # future refactor cannot accidentally route around it.
+ svc = NotificationService() # outbound_allowed defaults to False
+ result = svc.test_service("http://10.0.0.1/hook")
+ assert result["success"] is False
+ assert "LDR_NOTIFICATIONS_ALLOW_OUTBOUND" in result["error"]
+ # The URL itself was never inspected, so its details must not
+ # leak into the user-facing message:
+ assert "10.0.0.1" not in result["error"]
+
# -- SERVICE_PATTERNS --------------------------------------------------
def test_service_patterns_are_valid_regexes(self):