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): validate every URL in test_service (#5120) (#5132)

LearningCircuit14ddbfd4b581
diff --git a/changelog.d/5120.security.md b/changelog.d/5120.security.md
new file mode 100644
index 0000000000..ce6090c3f6
--- /dev/null
+++ b/changelog.d/5120.security.md
@@ -0,0 +1,9 @@
+The notification test endpoint (`/api/notifications/test-url`) now
+validates every URL in a comma/space-separated multi-URL string
+individually. Previously the input was validated as a single URL —
+commas are legal URL characters, so only the leading entry was checked
+while Apprise's own scheme-aware splitter still registered and notified
+the rest, letting an unvetted destination (e.g. a cloud-metadata
+address) receive the test notification. The number of parsed targets is
+now also capped, and the test is refused outright if Apprise registers
+more services than were validated.
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index e045deb479..4562e593b1 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -36,6 +36,12 @@ MAX_RETRY_ATTEMPTS = 3
INITIAL_RETRY_DELAY = 0.5
RETRY_BACKOFF_MULTIPLIER = 2
+# Maximum number of notification targets Apprise may parse out of one
+# test/configured URL string. Prevents an authenticated caller from
+# triggering unbounded DNS resolution work (and an unbounded fan-out of
+# outbound requests) via a comma/space-separated hostname list.
+MAX_NOTIFICATION_TARGETS = 20
+
class NotificationService:
"""
@@ -645,48 +651,96 @@ class NotificationService:
}
try:
- # 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:
+ # ``url`` is a single form field, but Apprise's own
+ # scheme-aware splitter treats it as a LIST — and commas are
+ # legal URL characters. Validating ``url`` as ONE url
+ # therefore checked only the leading entry while Apprise
+ # still registered, and notified, every other entry:
+ # ``discord://valid/tok,json://<cloud-metadata-host>/x``
+ # passed validation on the discord entry alone and the
+ # cloud-metadata target received the test notification
+ # unvetted. Partition the input with the shared scheme-aware
+ # parser — the same one the configured-send path uses via
+ # ``validate_multiple_urls`` — and vet EVERY entry.
+ url_entries, invalid_fragment = parse_notification_url_list(url)
+ if invalid_fragment is not None:
+ # A URL-like fragment with no scheme: Apprise may repair
+ # it or absorb it into a neighbouring entry, so refuse the
+ # whole input rather than dispatch the parseable subset.
+ # Mirrors validate_multiple_urls. The fragment fails the
+ # validation loop below, which sources the user message.
+ url_entries = [invalid_fragment]
+ if not url_entries:
+ return {
+ "success": False,
+ "error": "Invalid notification service URL.",
+ }
+ if len(url_entries) > MAX_NOTIFICATION_TARGETS:
logger.warning(
- f"Test service URL validation failed: {error_msg}"
+ f"Test notification refused: {len(url_entries)} targets "
+ f"exceeds the cap of {MAX_NOTIFICATION_TARGETS}."
)
- # 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 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,
+ "error": (
+ f"Too many notification targets "
+ f"({len(url_entries)}). Maximum is "
+ f"{MAX_NOTIFICATION_TARGETS}."
+ ),
}
+ for entry in url_entries:
+ # Validate each entry 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(
+ entry, allow_private_ips=self.allow_private_ips
+ )
+ )
+
+ if not is_valid:
+ # Never log the entry itself — an Apprise service URL
+ # carries credentials (bot tokens, webhook secrets).
+ # #5576 removed the masked-URL echo from this line for
+ # exactly that reason; keep it out of the per-entry
+ # loop too.
+ logger.warning(
+ f"Test service URL validation failed: {error_msg}"
+ )
+ # 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 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,
+ }
+
# Create temporary Apprise instance (synchronous so the pin +
# block-private window below applies in this thread).
temp_apprise = self._new_apprise()
@@ -698,6 +752,26 @@ class NotificationService:
"error": "Failed to add service URL",
}
+ # Fail closed on a parser differential: if Apprise registered
+ # MORE targets than we validated, at least one destination
+ # would be notified without ever passing the SSRF validator.
+ # Fewer is harmless (Apprise dropped an entry), so only the
+ # smuggling direction is refused.
+ if len(temp_apprise) > len(url_entries):
+ logger.warning(
+ f"Test notification refused: Apprise registered "
+ f"{len(temp_apprise)} targets but only "
+ f"{len(url_entries)} were validated."
+ )
+ return {
+ "success": False,
+ "error": (
+ "Notification service URL could not be parsed "
+ "unambiguously; refusing to send. Configure one "
+ "service URL per test."
+ ),
+ }
+
# Send the test through the SAME guarded dispatch core as the real
# send path (:meth:`_guarded_notify`) — fail-closed invariants,
# per-plugin redirect-disable, and the pin + block-private window
@@ -706,18 +780,26 @@ class NotificationService:
# validator's per-scheme policy: the operator flag for http/https,
# True (metadata-only) for plugin / raw-webhook schemes. tag is
# always None here.
- scheme = url.strip().split(":", 1)[0].lower() if ":" in url else ""
- is_plugin_scheme = scheme not in ("http", "https")
- allow_private = (
- self.allow_private_ips if not is_plugin_scheme else True
- )
+ #
+ # With multi-entry input the batch takes the STRICTEST policy of
+ # the schemes present: deriving it from the leading entry alone
+ # would let ``json://…,http://…`` run the http target under the
+ # plugin batch's allow_private_ips=True.
+ schemes = {
+ entry.split(":", 1)[0].lower()
+ for entry in url_entries
+ if ":" in entry
+ }
+ has_http = bool(schemes & {"http", "https"})
+ is_plugin_scheme = not schemes or bool(schemes - {"http", "https"})
+ allow_private = self.allow_private_ips if has_http else True
# Plugin/raw-webhook schemes run with allow_private_ips=True but
# must still block the whole link-local range (metadata territory
# beyond the always-blocked literals). Mirrors _dispatch's lenient
# partition and the validator's plugin-scheme IMDS guard.
guard_factory = functools.partial(
dns_pinning.pinned_notification_send,
- [url.strip()],
+ list(url_entries),
allow_localhost=False,
allow_private_ips=allow_private,
block_link_local=is_plugin_scheme,
diff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.py
index 3451222307..c3b93b2951 100644
--- a/tests/notifications/test_service.py
+++ b/tests/notifications/test_service.py
@@ -7,12 +7,16 @@ from unittest.mock import patch, MagicMock
from local_deep_research.notifications.service import (
NotificationService,
+ MAX_NOTIFICATION_TARGETS,
MAX_RETRY_ATTEMPTS,
INITIAL_RETRY_DELAY,
RETRY_BACKOFF_MULTIPLIER,
)
from local_deep_research.notifications.templates import EventType
-from local_deep_research.notifications.exceptions import SendError
+from local_deep_research.notifications.exceptions import (
+ SendError,
+ ServiceError,
+)
class TestNotificationServiceInit:
@@ -296,6 +300,306 @@ class TestTestService:
assert len(result["error"]) > 0
+class TestTestServiceMultiUrl:
+ """``test_service()`` must validate EVERY entry of a multi-URL input,
+ not the joined string as a single URL (issue #5120).
+
+ ``url`` is one form field, but Apprise's own scheme-aware splitter
+ treats it as a list, and commas are legal URL characters. Validating
+ it as a single URL checked only the leading entry while Apprise still
+ registered — and notified — the rest.
+ """
+
+ ATTACK_URL = (
+ "discord://123456789012345678/abcdefghijklmnop"
+ ",json://169.254.169.254/metadata"
+ )
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise.notify")
+ def test_comma_smuggled_metadata_url_is_rejected(self, mock_notify):
+ """A single-URL validator sees only the valid-looking discord
+ entry and lets the smuggled cloud-metadata URL through to
+ Apprise. It must be rejected before Apprise is asked to notify.
+ """
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(self.ATTACK_URL)
+
+ assert result["success"] is False
+ assert "169.254.169.254" in result["error"]
+ mock_notify.assert_not_called()
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise.notify")
+ def test_space_smuggled_metadata_url_is_rejected(self, mock_notify):
+ """Whitespace is a separator for Apprise too, so it must be one
+ for the validator."""
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(self.ATTACK_URL.replace(",", " "))
+
+ assert result["success"] is False
+ assert "169.254.169.254" in result["error"]
+ mock_notify.assert_not_called()
+
+ def test_single_invalid_url_still_fails_with_validator_message(self):
+ """Single-URL behavior is unchanged: a lone cloud-metadata URL
+ fails with the real validator's message."""
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service("json://169.254.169.254/metadata")
+
+ assert result["success"] is False
+ assert "169.254.169.254" in result["error"]
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_all_valid_multi_url_passes_and_sends(self, mock_apprise_class):
+ """Per-entry validation must not regress the legitimate
+ multi-URL case: when every entry is a valid vendor URL the test
+ notification is still sent."""
+ mock_apprise_instance = MagicMock()
+ mock_apprise_instance.add.return_value = True
+ mock_apprise_instance.notify.return_value = True
+ # A bare MagicMock reports len() == 0, which would make the
+ # parser-differential guard below compare ``0 > 2`` and pass
+ # vacuously. Report the honest registered-target count so this
+ # test exercises the guard's non-differential branch for real.
+ mock_apprise_instance.__len__.return_value = 2
+ mock_apprise_class.return_value = mock_apprise_instance
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(
+ "discord://123456789012345678/abcdefghijklmnop"
+ ",mailto://[email protected]"
+ )
+
+ assert result["success"] is True
+ mock_apprise_instance.notify.assert_called_once()
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint",
+ return_value=(True, None, False),
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_comma_inside_one_url_is_not_split(
+ self, mock_apprise_class, mock_validate
+ ):
+ """A comma that is part of a single service URL must not be
+ treated as a separator — that is what made the naive split
+ unusable in the first place."""
+ mock_apprise_instance = MagicMock()
+ mock_apprise_instance.add.return_value = True
+ mock_apprise_instance.notify.return_value = True
+ # See the note in the multi-URL happy path: without an explicit
+ # __len__ the parser-differential guard is not exercised at all.
+ mock_apprise_instance.__len__.return_value = 1
+ mock_apprise_class.return_value = mock_apprise_instance
+
+ service = NotificationService(outbound_allowed=True)
+
+ result = service.test_service("discord://webhook/token?fields=a,b")
+
+ assert result["success"] is True
+ # One entry -> one validation call, with the comma preserved.
+ mock_validate.assert_called_once()
+ assert "a,b" in mock_validate.call_args[0][0]
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise.notify")
+ def test_target_count_is_capped(self, mock_notify):
+ """An unbounded target list would let one authenticated request
+ trigger unbounded DNS resolution / outbound fan-out."""
+ service = NotificationService(outbound_allowed=True)
+
+ many = ",".join(
+ f"discord://12345678901234567{n}/abcdefghijklmnop"
+ for n in range(MAX_NOTIFICATION_TARGETS + 1)
+ )
+ result = service.test_service(many)
+
+ assert result["success"] is False
+ assert "Too many notification targets" in result["error"]
+ mock_notify.assert_not_called()
+
+
+class TestTestServiceParserDifferential:
+ """``test_service()`` fails closed when Apprise registers MORE
+ targets than were validated (issue #5120).
+
+ Regression guard for a VACUOUS test: a bare ``MagicMock`` reports
+ ``len() == 0``, so ``len(temp_apprise) > len(url_entries)`` compares
+ ``0 > N`` and the fail-closed branch is never entered. Every test
+ here sets ``__len__`` explicitly so the comparison is real, and the
+ equal/fewer cases pin the guard to ``>`` (an inversion to ``>=`` or
+ ``<`` breaks them).
+
+ The validator is stubbed so these tests isolate the differential
+ guard itself: every entry is treated as having passed SSRF
+ validation, which is exactly the state in which a smuggled extra
+ Apprise target would otherwise be notified unvetted.
+ """
+
+ TWO_VALID_URLS = (
+ "discord://123456789012345678/abcdefghijklmnop"
+ ",discord://223456789012345678/abcdefghijklmnop"
+ )
+
+ @staticmethod
+ def _mock_apprise(mock_apprise_class, registered_targets):
+ instance = MagicMock()
+ instance.add.return_value = True
+ instance.notify.return_value = True
+ instance.__len__.return_value = registered_targets
+ mock_apprise_class.return_value = instance
+ return instance
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint",
+ return_value=(True, None, False),
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_more_registered_than_validated_is_refused(
+ self, mock_apprise_class, mock_validate
+ ):
+ """Apprise registering a third target for a two-entry input means
+ one destination never passed the SSRF validator. Refuse the send.
+ """
+ mock_apprise = self._mock_apprise(mock_apprise_class, 3)
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(self.TWO_VALID_URLS)
+
+ assert result["success"] is False
+ assert "could not be parsed unambiguously" in result["error"]
+ mock_apprise.notify.assert_not_called()
+ # Two entries went to the validator; Apprise claimed three.
+ assert mock_validate.call_count == 2
+ assert len(mock_apprise) == 3
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint",
+ return_value=(True, None, False),
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_single_entry_expanded_by_apprise_is_refused(
+ self, mock_apprise_class, mock_validate
+ ):
+ """The smuggling shape the guard exists for: one validated entry,
+ two registered targets."""
+ mock_apprise = self._mock_apprise(mock_apprise_class, 2)
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(
+ "discord://123456789012345678/abcdefghijklmnop"
+ )
+
+ assert result["success"] is False
+ assert "could not be parsed unambiguously" in result["error"]
+ mock_apprise.notify.assert_not_called()
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint",
+ return_value=(True, None, False),
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_equal_counts_still_send(self, mock_apprise_class, mock_validate):
+ """Equal counts are the normal case and must NOT be refused —
+ pins the comparison to ``>`` rather than ``>=``."""
+ mock_apprise = self._mock_apprise(mock_apprise_class, 2)
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(self.TWO_VALID_URLS)
+
+ assert result["success"] is True
+ mock_apprise.notify.assert_called_once()
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint",
+ return_value=(True, None, False),
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_fewer_registered_than_validated_still_sends(
+ self, mock_apprise_class, mock_validate
+ ):
+ """Apprise dropping an entry is harmless: only the smuggling
+ direction is refused."""
+ mock_apprise = self._mock_apprise(mock_apprise_class, 1)
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ result = service.test_service(self.TWO_VALID_URLS)
+
+ assert result["success"] is True
+ mock_apprise.notify.assert_called_once()
+
+ def test_bare_magicmock_len_is_zero(self):
+ """Documents WHY every test above sets ``__len__``: an
+ unconfigured MagicMock reports zero registered targets, which
+ would let the guard pass without ever being evaluated against a
+ real count."""
+ assert len(MagicMock()) == 0
+
+
+class TestSendMultiUrlSsrf:
+ """The configured-dispatch path (``send()``) must also validate every
+ entry Apprise parses out of a multi-URL string, so a comma/space
+ smuggled cloud-metadata target cannot reach dispatch behind a
+ valid-looking leading entry. Exercises the REAL validator and the
+ REAL parser; only ``notify`` is mocked."""
+
+ ATTACK_URL = (
+ "discord://123456789012345678/abcdefghijklmnop"
+ ",json://169.254.169.254/metadata"
+ )
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise.notify")
+ def test_send_rejects_comma_smuggled_metadata_url(self, mock_notify):
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ with pytest.raises(ServiceError):
+ service.send("Title", "Body", service_urls=self.ATTACK_URL)
+
+ mock_notify.assert_not_called()
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise.notify")
+ def test_send_rejects_space_smuggled_metadata_url(self, mock_notify):
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=False
+ )
+
+ with pytest.raises(ServiceError):
+ service.send(
+ "Title", "Body", service_urls=self.ATTACK_URL.replace(",", " ")
+ )
+
+ mock_notify.assert_not_called()
+
+
class TestGetServiceType:
"""Tests for get_service_type method."""