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): correct #5113 follow-up defects (invalid_url, dead test coverage) (#6205)

LearningCircuitadec5703ec5a
diff --git a/changelog.d/+notification-invalid-url-followup.bugfix.md b/changelog.d/+notification-invalid-url-followup.bugfix.md
new file mode 100644
index 0000000000..94c771dabd
--- /dev/null
+++ b/changelog.d/+notification-invalid-url-followup.bugfix.md
@@ -0,0 +1,42 @@
+Follow-up to the #5113 notification drop-reason fix: an unparseable
+notification service URL is now reported as `invalid_url` instead of
+the misleading `egress_denied` (the egress policy was never actually
+consulted for it). A `notifications.service_url` that parses to zero
+URLs (separator characters only, e.g. `","`) is likewise `invalid_url`,
+not `egress_denied`. The `invalid_url` reason is also now honest when a
+mixed URL list has one rejected entry — it no longer claims Apprise
+"accepted none" of the configured URLs. Seven DNS-pin regression tests
+that had been widened to accept either a pre-dispatch or a send-time
+security block now assert the send-time `SecurityBlockError`
+specifically, and `NotificationGuardUnavailableError` (the DNS-pin
+shim's fail-closed refusal) is now covered by a test asserting its
+specific type end-to-end through `NotificationService.send()`.
+
+**Behavior change:** a `notifications.service_url` entry that contains a
+character which is illegal unencoded in a URI — a space, a backslash, or
+a control byte — is now reported as `invalid_url` for the WHOLE setting.
+Such entries were already refused before dispatch (URL validation has
+rejected them on both the send and test-notification paths for some
+time); what changes is the reason the operator sees, which previously
+could be `egress_denied` for a policy that was never consulted. Values
+such as `discord://x garbage` and `slack://t/x/y\` are affected.
+Percent-encode the character, or split the value into separate
+comma-separated URLs. Surrounding whitespace is still trimmed and stays
+harmless, including non-ASCII whitespace such as a pasted `U+00A0`
+no-break space.
+
+The "Send Test Notification" endpoint now REFUSES any service URL that
+does not partition into unambiguous entries, instead of validating the
+trailing fragment in place of the entry it was carved out of, and it
+hands Apprise the already-parsed entry list rather than the raw string,
+so Apprise's own URL splitter is out of the path. The `invalid_url`
+audit log no longer records any form of the offending fragment (only its
+length), since for token-in-authority Apprise schemes even a
+`scheme://host` redaction preserves the secret, and the egress-policy
+audit log now records a refused webhook's `scheme://host` instead of its
+full URL. `NotificationManager.test_service` classifies an unusable URL
+the same way the send path does, so an unparseable or empty value no
+longer tells the operator to widen an egress scope that was never
+consulted. A host that cannot be IDNA-encoded is now refused as an
+ordinary resolution failure inside the DNS block-private window too,
+rather than being mislabelled a confirmed security block.
diff --git a/changelog.d/5110.bugfix.md b/changelog.d/5110.bugfix.md
index ddc2562a01..57453c620c 100644
--- a/changelog.d/5110.bugfix.md
+++ b/changelog.d/5110.bugfix.md
@@ -4,8 +4,9 @@ is reported as `webhook_failed` instead of the generic `exception`,
and a service URL rejected before dispatch (unparseable, or blocked
by URL security validation) is reported as the new `invalid_url`
reason. `egress_denied` details now distinguish "policy refused every
-URL" from "policy could not be evaluated" (including in the
-test-notification endpoint), and the `server_disabled` detail no
-longer claims the env var "is not set" when it is explicitly
-disabled. `NotificationResult`/`NotificationReason` are exported from
-the `notifications` package.
+URL" from "policy could not be evaluated" for scheduled/queued
+notifications and in `NotificationManager.test_service`, and the
+`server_disabled` detail no longer claims the
+env var "is not set" when it is explicitly disabled.
+`NotificationResult`/`NotificationReason` are exported from the
+`notifications` package.
diff --git a/docs/NOTIFICATION_FLOW.md b/docs/NOTIFICATION_FLOW.md
index 22a3fab69f..bdf24e7652 100644
--- a/docs/NOTIFICATION_FLOW.md
+++ b/docs/NOTIFICATION_FLOW.md
@@ -164,6 +164,30 @@ def send_notification(
dispatch — unparseable, or blocked by URL security validation),
`webhook_failed` (delivery failed after retries), or `exception`.
+"Unparseable" includes any entry containing a character that is illegal
+unencoded in a URI (a space, a backslash, or a control byte): the whole
+setting now fails closed as a whole, because such an entry does not
+partition into unambiguous URLs — deliberately, even when the setting
+has other, well-formed entries. That is more than a change of reported
+reason: a multi-entry setting that previously delivered to its clean
+entries no longer does. For example, `notifications.service_url =
+"http://10.0.0.1/x garbage, https://public.example/hook"` under
+`egress_scope = public_only` used to have the malformed private entry
+dropped by the egress filter and the clean entry delivered to the
+public hook; the whole setting is now refused as `invalid_url` and
+nothing is delivered. Calling the drop `invalid_url` "rather than
+`egress_denied` for a policy that was never consulted" only holds for a
+scheme-less fragment (no scheme at all), where parsing fails before any
+per-URL policy check runs. For an entry with a space, backslash, or
+control byte, the previous parser did not detect it as malformed at
+all, so the entry reached the per-URL egress loop and could be — and,
+for a non-`http(s)` scheme under a `PRIVATE_ONLY` policy, genuinely
+was — evaluated and refused by a policy that DID run. Percent-encode
+the character, or split the value into separate comma-separated URLs.
+Whitespace *around* an entry is trimmed before this check and remains
+harmless, including non-ASCII whitespace such as a pasted `U+00A0`
+no-break space.
+
**Settings Checked (from `settings_snapshot`):**
1. **`notifications.on_research_completed`** - Is this event type enabled? (default: False for most events)
2. **Per-User Rate Limits** - Check shared rate limiter with user-specific limits:
@@ -514,7 +538,8 @@ result = notification_manager.send_notification(
event_type=EventType.RESEARCH_COMPLETED,
context=context
)
-# Returns: False (respects user preference)
+# Returns: falsy NotificationResult (reason=event_disabled, respects
+# user preference; no error raised)
# Log: "Notifications disabled for event type: research_completed"
```
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index bc2363967b..05086489b9 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -320,6 +320,65 @@ class NotificationManager:
detail="notifications.service_url is not configured",
)
+ # Reject an unparseable service URL (missing scheme, or a
+ # scheme-less fragment trailing a valid one) before consulting
+ # the egress policy at all. `_filter_urls_by_egress_policy`
+ # also refuses this case (returns ""), which — if reported
+ # here as EGRESS_DENIED — would falsely claim the policy was
+ # consulted and refused it, when it was never evaluated. This
+ # is a genuinely invalid configuration, not a policy denial —
+ # see issue #5110.
+ url_entries, invalid_fragment = parse_notification_url_list(
+ service_urls
+ )
+ if invalid_fragment is not None:
+ # Log NOTHING derived from the fragment's content — not
+ # even a redacted form. ``redact_url_for_log`` keeps
+ # ``scheme://host``, but for the token-in-authority
+ # Apprise schemes the first authority segment IS the
+ # secret (``slack://xoxb-SECRET/T00/B00`` redacts to
+ # ``slack://xoxb-SECRET``), and a fragment can be the
+ # whole entry when the illegal character only trails it.
+ # The fragment's length and position are enough to
+ # diagnose the misconfiguration.
+ logger.bind(policy_audit=True).warning(
+ "notification dropped: unparseable service URL fragment",
+ fragment_length=len(invalid_fragment),
+ entries_parsed=len(url_entries),
+ user=self._user_id,
+ event=event_type.value,
+ )
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.INVALID_URL,
+ detail=(
+ "a configured service URL could not be parsed "
+ "(missing scheme, or an unencoded space, "
+ "backslash or control character)"
+ ),
+ )
+
+ if not url_entries:
+ # A nonempty setting that parses to zero URLs —
+ # separator characters only, e.g. "," — never reaches
+ # the policy's per-URL loop, so the egress branch below
+ # would report "all configured URLs refused" for a
+ # refusal that never happened. Invalid configuration,
+ # same class as a scheme-less fragment — issue #5110.
+ logger.bind(policy_audit=True).warning(
+ "notification dropped: service URL setting contains "
+ "no parseable URLs",
+ user=self._user_id,
+ event=event_type.value,
+ )
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.INVALID_URL,
+ detail=(
+ "notifications.service_url contains no parseable URLs"
+ ),
+ )
+
# Egress policy: classify raw HTTP(S) URLs with evaluate_url.
# PRIVATE_ONLY refuses non-HTTP Apprise schemes because their
# effective destinations cannot be classified reliably; other
@@ -364,19 +423,28 @@ class NotificationManager:
reason=NotificationReason.SENT,
detail="",
)
- # A falsy return from send_event means Apprise accepted none
- # of the URLs (temp_apprise.add() failed — unparseable or
- # unsupported scheme). Actual delivery failures raise
+ # A falsy return from send_event means Apprise rejected a
+ # service URL (temp_apprise.add() failed — unparseable or
+ # unsupported scheme) in one of the scheme partitions
+ # NotificationService._dispatch builds. NOT "none of the
+ # URLs": _dispatch returns False on the FIRST partition whose
+ # add() fails, before attempting any later partition — so a
+ # mixed configuration (e.g. one malformed http(s) URL plus a
+ # valid json:// URL) is reported here even though the valid
+ # partition was never tried. Actual delivery failures raise
# SendError and are handled below — see issue #5110.
logger.warning(
f"Notification failed: {event_type.value} to user "
- f"{self._user_id} — Apprise accepted none of the "
- f"configured service URLs"
+ f"{self._user_id} — Apprise rejected a configured "
+ f"service URL before dispatch completed"
)
return NotificationResult(
sent=False,
reason=NotificationReason.INVALID_URL,
- detail="Apprise accepted none of the configured service URLs",
+ detail=(
+ "Apprise rejected a configured service URL before "
+ "dispatch completed"
+ ),
)
except SendError:
@@ -394,8 +462,13 @@ class NotificationManager:
# routes that non-retryable case through ServiceError instead
# (see the except clause below) precisely so it is never
# mislabeled as a retryable webhook failure here. Keep the
- # detail static — SendError's message wraps the underlying
- # error, which may contain webhook URLs with embedded tokens.
+ # detail static regardless: SendError's own raise site
+ # (NotificationService._send_with_retry) uses a fixed message
+ # with no interpolated URL/token today, but this except clause
+ # also logs the exception via logger.exception above — a
+ # static, non-interpolated detail here keeps that guarantee
+ # independent of what any future SendError raise site puts in
+ # its message.
logger.exception(
f"Webhook delivery failed for {event_type.value} to user "
f"{self._user_id}"
@@ -484,13 +557,59 @@ class NotificationManager:
Returns:
Dict with test results
+
+ Note:
+ Nothing in ``src/`` currently calls this method — the live
+ ``POST /api/notifications/test-url`` route constructs a
+ ``NotificationService`` directly and never goes through
+ ``NotificationManager``, so the egress-policy precheck below
+ is not applied to that endpoint (see issue #5110 follow-up
+ discussion). Only test suites exercise this method today.
"""
- # Egress policy precheck before forwarding to Apprise.
- # /api/notifications/test-url is a user-supplied URL endpoint.
+ # Classify an unusable URL the same way ``send_notification``
+ # now does, BEFORE consulting the egress policy.
+ # ``_filter_urls_by_egress_policy`` returns ``""`` for three
+ # different things — an unparseable fragment, zero parseable
+ # entries, and a genuine per-URL policy refusal — so mapping
+ # every ``""`` onto the "Set Egress Scope to 'Unprotected'"
+ # remediation tells the operator to widen a policy that was
+ # never consulted (issue #5110 / #5113 follow-up). Parse here so
+ # the first two are reported as invalid configuration and the
+ # egress message is reserved for a real refusal.
+ url_entries, invalid_fragment = parse_notification_url_list(url)
+ if invalid_fragment is not None:
+ # Log NOTHING derived from the fragment's content, not even
+ # a redacted form — see the identical branch in
+ # ``send_notification`` for why ``scheme://host`` is still
+ # the secret for token-in-authority Apprise schemes.
+ logger.bind(policy_audit=True).warning(
+ "test notification refused: unparseable service URL fragment",
+ fragment_length=len(invalid_fragment),
+ entries_parsed=len(url_entries),
+ )
+ return {
+ "status": "error",
+ "message": (
+ "Service URL could not be parsed (missing scheme, or "
+ "an unencoded space, backslash or control character)."
+ ),
+ }
+ if not url_entries:
+ return {
+ "status": "error",
+ "message": "Service URL contains no parseable URLs.",
+ }
+
+ # Egress policy precheck before forwarding to Apprise. NOT
+ # currently reached by any live route — see the Note above.
allowed = self._filter_urls_by_egress_policy(url)
if allowed is None:
# Fail-closed: the policy could not be evaluated at all, so
- # don't tell the user their scope refused the URL.
+ # don't tell the user their scope refused the URL — the
+ # "Set Egress Scope to 'Unprotected'" remediation below
+ # fixes the wrong thing. Same distinction send_notification
+ # draws between "refused every URL" and "could not be
+ # evaluated".
return {
"status": "error",
"message": (
@@ -499,6 +618,8 @@ class NotificationManager:
),
}
if not allowed:
+ # Reached only for a real per-URL refusal now: the fragment
+ # and zero-entry cases returned above.
return {
"status": "error",
"message": (
@@ -527,9 +648,15 @@ class NotificationManager:
service_urls
)
if invalid_fragment is not None:
+ # As in ``send_notification``: never log anything derived
+ # from the fragment's content. Even the redacted
+ # ``scheme://host`` form leaks the secret for token-in-
+ # authority Apprise schemes, and the fragment may be the
+ # entire entry.
logger.bind(policy_audit=True).warning(
- "all notification URLs refused: scheme-less URL fragment",
- fragment=redact_url_for_log(invalid_fragment),
+ "all notification URLs refused: unparseable URL fragment",
+ fragment_length=len(invalid_fragment),
+ entries_parsed=len(url_entries),
)
return ""
@@ -603,9 +730,16 @@ class NotificationManager:
if decision.allowed:
parts.append(url_entry)
else:
+ # Log the redacted ``scheme://host[:port]`` form, never
+ # the entry: this branch only sees http(s) URLs, whose
+ # userinfo may carry the operator's credentials
+ # (RFC 3986 §3.2.1) and whose path may itself be the
+ # webhook secret. The host is what an operator needs to
+ # act on a policy refusal, and it is the part the policy
+ # decided on.
logger.bind(policy_audit=True).warning(
"notification URL refused by egress policy",
- url=url_entry,
+ url=redact_url_for_log(url_entry),
scope=ctx.scope.value,
reason=decision.reason,
)
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 4a9aa14986..6c5a52b683 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -216,14 +216,18 @@ class NotificationService:
unless the operator opted in, while plugin / raw-webhook schemes
allow private (self-hosted LAN) but always block cloud-metadata.
- NOTE: the ``strict`` (``http``/``https``) partition is UNREACHABLE
- for delivery today — Apprise rejects bare ``http(s)://`` notification
- URLs at ``add()`` (verified: ``apprise.Apprise().add("http://x/")``
- is False), so a strict-partition ``add()`` in :meth:`_dispatch`
- returns False and nothing is sent. The stricter policy is retained
- as defense-in-depth for a hypothetical future where a raw ``http(s)``
- scheme becomes deliverable; deliverable webhooks use the raw-webhook
- schemes ``json``/``xml``/``form`` (in the ``lenient`` partition).
+ NOTE: the ``strict`` (``http``/``https``) partition is only
+ PARTLY deliverable. Apprise has no generic http(s) notifier, so an
+ arbitrary webhook is rejected at ``add()``
+ (``apprise.Apprise().add("https://example.com/hook")`` is False on
+ apprise 1.13.0) and a strict-only ``add()`` in :meth:`_dispatch`
+ returns False without sending. But Apprise DOES claim the native
+ ``https://`` forms of several vendors, so those deliver from this
+ partition:
+ ``apprise.Apprise().add("https://discord.com/api/webhooks/<id>/<token>")``
+ and the ``https://hooks.slack.com/services/...`` form both return
+ True. Generic webhooks should still use the raw-webhook schemes
+ ``json``/``xml``/``form`` (in the ``lenient`` partition).
"""
strict: List[str] = []
lenient: List[str] = []
@@ -231,16 +235,24 @@ class NotificationService:
service_urls, ","
)
if invalid_fragment is not None:
- # Never log the fragment itself — it may contain credentials.
+ # The only correct response to a non-``None`` fragment is to
+ # refuse the whole input (see ``parse_notification_url_list``'s
+ # docstring) — never dispatch the malformed entry verbatim.
+ # Never log the fragment itself — it may contain credentials;
+ # length/count only, as the other fragment-log sites do.
# ``send()`` runs ``validate_multiple_urls`` (same
- # scheme-boundary parse) before reaching here, so a malformed
- # fragment is already rejected there; this branch only fires
- # for direct callers of this helper, which must validate the
- # list themselves before dispatching it.
+ # scheme-boundary parse) before reaching here, so this branch
+ # is unreachable through the only production caller today;
+ # it is defense-in-depth for any future direct caller of this
+ # helper, which must otherwise validate the list before
+ # dispatching it.
logger.warning(
"Notification service_url list contains a malformed "
- "fragment; callers must validate the list before dispatch"
+ "fragment; refusing the whole list",
+ fragment_length=len(invalid_fragment),
+ entries_parsed=len(entries),
)
+ return [], []
for entry in entries:
entry = entry.strip()
if not entry:
@@ -768,12 +780,56 @@ class NotificationService:
# ``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]
+ # The input does not partition unambiguously: either a
+ # URL-like fragment carries no scheme (Apprise may repair
+ # it or absorb it into a neighbouring entry) or an entry
+ # contains a character that is illegal unencoded in a URI
+ # (backslash, whitespace, a control byte) and the token
+ # after it is a second, unvalidated destination. REFUSE
+ # the whole input — mirrors ``validate_multiple_urls``,
+ # which returns False for every fragment shape.
+ #
+ # Substituting ``url_entries = [invalid_fragment]`` here
+ # (as this code did before) was exploitable: the
+ # fragment is NOT necessarily scheme-less, because
+ # ``_URL_BOUNDARY_RE`` splits only on ``[,\s]+`` while
+ # the fragment is cut on ``RFC_FORBIDDEN_URL_CHARS_RE``,
+ # which also covers backslash and non-``\s`` control
+ # bytes. So ``json://<metadata-host>/x\https://vendor/ok``
+ # stays ONE entry whose fragment is the *vendor* URL:
+ # the loop below would validate only that decoy, the
+ # smuggle check would compare ``1 > 1``, and the
+ # then-current ``temp_apprise.add(url)`` would dispatch
+ # the RAW original string to the metadata host — with the
+ # pin/block-private policy derived from the decoy's
+ # scheme. (``add()`` now takes the parsed entry list, so
+ # the raw string is no longer in the dispatch path at
+ # all; this refusal is still the primary defence, since
+ # the decoy would otherwise be the only entry vetted.)
+ # Never validate a fragment in place of the input it was
+ # carved out of.
+ #
+ # The message is deliberately generic: the fragment's
+ # own content is attacker-shaped AND may carry the
+ # operator's real credentials, so nothing derived from
+ # it is echoed to the user or the log.
+ logger.warning(
+ "Test notification refused: the service URL does not "
+ "partition into unambiguous entries "
+ "({} entries parsed, {}-character trailing fragment).",
+ len(url_entries),
+ len(invalid_fragment),
+ )
+ return {
+ "success": False,
+ "error": (
+ "Notification service URL could not be parsed "
+ "unambiguously; refusing to send. Every entry must "
+ "begin with a protocol such as discord:// — remove "
+ "any spaces, backslashes or control characters and "
+ "configure one complete service URL per test."
+ ),
+ }
if not url_entries:
return {
"success": False,
@@ -848,7 +904,25 @@ class NotificationService:
# Create temporary Apprise instance (synchronous so the pin +
# block-private window below applies in this thread).
temp_apprise = self._new_apprise()
- add_result = temp_apprise.add(url)
+ # Hand Apprise the ALREADY-PARTITIONED entries, not the raw
+ # string — the same thing :meth:`_dispatch` does. ``add()``
+ # runs its own ``parse_urls`` splitter ONLY on a ``str``
+ # argument; given a list it instantiates exactly one plugin
+ # per element. Passing ``url`` here let LDR's boundary regex
+ # and Apprise's ``URL_DETECTION_RE`` each get a vote on where
+ # the entries start, and the two do not agree: Apprise's
+ # scheme class is ``[a-z0-9]`` (a LEADING DIGIT starts a new
+ # entry, ``+ . -`` do not) while LDR's requires a leading
+ # letter and accepts ``+ . -``. So ``discord://a/b,7z://x``
+ # is ONE entry to LDR (validated as a discord URL) and TWO to
+ # Apprise — the second never seen by the SSRF validator. Only
+ # the count guard below caught that, and only because every
+ # scheme in ``ALLOWED_SCHEMES`` happens to be pure lowercase
+ # alpha, which is a property of a constant rather than of
+ # this code. With a list there is ONE parser in the path and
+ # the set Apprise dispatches is exactly the set validated
+ # above.
+ add_result = temp_apprise.add(list(url_entries))
if not add_result:
return {
@@ -861,6 +935,20 @@ class NotificationService:
# would be notified without ever passing the SSRF validator.
# Fewer is harmless (Apprise dropped an entry), so only the
# smuggling direction is refused.
+ #
+ # With the list-form ``add()`` above this guard is STRUCTURAL,
+ # not a live check: ``Apprise.__len__`` counts one per
+ # instantiated plugin and the list form appends AT MOST ONE
+ # plugin per element, so ``len(temp_apprise) > len(url_entries)``
+ # cannot be true for any input on the current Apprise. It is
+ # kept as a cheap invariant assertion — it still catches a
+ # future Apprise release that expands one URL into several
+ # servers, and it is the last thing standing if the ``add()``
+ # argument is ever changed back to a string. The argument
+ # shape itself is pinned by
+ # ``test_test_service_success`` in ``tests/notifications/
+ # test_service.py``, which asserts ``add`` receives the parsed
+ # LIST.
if len(temp_apprise) > len(url_entries):
logger.warning(
f"Test notification refused: Apprise registered "
diff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.py
index 015ef2af01..630a2e6336 100644
--- a/src/local_deep_research/security/dns_pinning.py
+++ b/src/local_deep_research/security/dns_pinning.py
@@ -376,6 +376,18 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
targets a host that was never pinned. The check runs on the SAME address
list the caller will connect to (this IS the ``getaddrinfo`` the client
uses), so there is no second resolution to race against.
+
+ No failure mode inside an active window escapes as a bare
+ ``ValueError``: an IDNA-unencodable host raises a native
+ ``UnicodeError`` (a ``ValueError`` subclass), which is caught below and
+ re-raised as ``socket.gaierror`` instead, since a ``ValueError``
+ reaching the sender would otherwise be mislabelled a confirmed
+ security block. A resolution error raised by the resolver itself
+ (``socket.gaierror`` / ``OSError``) propagates unchanged. The
+ IDNA case reaches this function through an allowed-but-not-pinnable scheme
+ (``ntfy``/``ntfys``, whose Apprise plugin parses with
+ ``verify_host=False``); see the inline comment below.
+ ``_resolve_and_validate`` enforces the same invariant at pin time.
"""
block = getattr(_thread_state, "block_private", None)
if block is None:
@@ -383,7 +395,35 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
return _real_getaddrinfo(host, port, family, type, proto, flags)
# Window active — bound the resolution (send path) and fail closed on a
# timeout by letting the gaierror propagate to the client.
- results = _getaddrinfo_bounded(host, port, family, type, proto, flags)
+ #
+ # ``socket.getaddrinfo`` raises ``UnicodeError`` (a ``ValueError``
+ # subclass) for a host that cannot be IDNA-encoded — a label over 63
+ # bytes, or an empty label. Letting that escape from inside an active
+ # window would break the same invariant ``_resolve_and_validate``
+ # protects one function away: at this layer a ``ValueError`` reaching
+ # the sender means a CONFIRMED SSRF block, so an unencodable name would
+ # be mislabelled as a security block (``SecurityBlockError``) instead
+ # of an ordinary resolution failure.
+ #
+ # This path IS reachable in practice, but not via a pin-time failure:
+ # ``pin_hosts`` only considers :data:`_PINNABLE_SCHEMES`, and for those
+ # Apprise's ``add()`` (``verify_host=True``) rejects an
+ # IDNA-unencodable host before a pin is ever attempted. The live route
+ # is a scheme that is ALLOWED but NOT pinnable — ``ntfy://`` /
+ # ``ntfys://``, whose Apprise plugin calls
+ # ``NotifyBase.parse_url(url, verify_host=False)`` and therefore
+ # accepts such a host. ``pin_hosts`` skips it on the scheme check, so
+ # it stays unpinned and its send-time lookup lands here, inside the
+ # active block-private window. Refuse it the way every other failed
+ # lookup in this shim is refused: ``socket.gaierror``, fail closed.
+ try:
+ results = _getaddrinfo_bounded(host, port, family, type, proto, flags)
+ except UnicodeError as exc:
+ raise socket.gaierror(
+ getattr(socket, "EAI_NONAME", getattr(socket, "EAI_FAIL", -1)),
+ f"DNS resolution for {_host_for_log(host)!r} failed: host is "
+ f"not encodable to IDNA (refused during a pinned send window)",
+ ) from exc
# A ``None`` host is an AF_PASSIVE bind
# (``getaddrinfo(None, port, ..., AI_PASSIVE)`` — a local listening-socket
# setup, not an outbound name to rebind), so it carries no attacker-
@@ -540,18 +580,35 @@ def _resolve_and_validate(
Raises:
ValueError: if any resolved address is blocked. SSRF-style message
- so existing callers/tests catch it uniformly.
+ so existing callers/tests catch it uniformly. NOTE: this is
+ raised ONLY for a confirmed SSRF block (below) — a resolver
+ failure is always routed through ``requests.ConnectionError``
+ instead, specifically so ``send()``'s ``except ValueError``
+ handler (which reports a confirmed security block) is never
+ reached by an ordinary resolution failure.
requests.ConnectionError: if the host no longer resolves at pin
- time, OR if resolution times out (a slow / hostile DNS authority
- cannot hang the send) — fail closed as an ordinary transport
- error so the existing retry / ``RequestException`` handling stays
- intact.
+ time, if resolution times out (a slow / hostile DNS authority
+ cannot hang the send), OR if the host is unencodable to IDNA
+ (``socket.getaddrinfo`` raises ``UnicodeError`` — a
+ ``UnicodeEncodeError`` is a ``ValueError`` subclass — for a
+ label over 63 bytes or an empty label). This particular catch
+ is currently unreachable in practice: it runs only for a
+ scheme in :data:`_PINNABLE_SCHEMES`, and those Apprise plugins
+ parse with ``verify_host=True``, so ``Apprise.add()`` rejects
+ an IDNA-unencodable host before ``_dispatch`` ever calls
+ ``pin_hosts``. The catch keeps the
+ ValueError-means-SSRF-block invariant true at THIS layer
+ rather than relying on that upstream reject. (The SEND-time
+ sibling in :func:`_resolve_maybe_block` is genuinely
+ reachable — see its comment — via a non-pinnable scheme.)
+ Fail closed as an ordinary transport error so the existing
+ retry / ``RequestException`` handling stays intact.
"""
try:
addr_info = _getaddrinfo_bounded(
host, None, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 0
)
- except socket.gaierror as exc:
+ except (socket.gaierror, UnicodeError) as exc:
raise requests.ConnectionError(
f"DNS resolution failed while pinning host {host}"
) from exc
@@ -718,6 +775,16 @@ def pin_hosts(
block_link_local=block_link_local,
)
except requests.ConnectionError:
+ # Skipping leaves the host unpinned, so its send-time
+ # lookup goes through ``_resolve_maybe_block``, which
+ # applies the same policy inside the block window. This
+ # nominally includes the IDNA-unencodable host
+ # (``UnicodeError`` routed to ``ConnectionError`` by
+ # ``_resolve_and_validate``), though that shape does not
+ # reach here today: for a pinnable scheme Apprise's
+ # ``add()`` rejects such a host first. The reachable
+ # IDNA route into ``_resolve_maybe_block`` is a scheme
+ # skipped by the ``_PINNABLE_SCHEMES`` check above.
logger.debug(
"Skipping pin for currently-unresolvable host {}", host
)
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index a3c6481981..4303573a1e 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -36,6 +36,24 @@ _SCHEMELESS_URL_FRAGMENT_RE = re.compile(
)
_URL_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]{0,31}://")
_URL_BOUNDARY_RE = re.compile(r"[,\s]+(?=[A-Za-z][A-Za-z0-9+.-]{0,31}://)")
+# Separator characters that may surround an entry after the boundary split:
+# commas and ANY Unicode whitespace. ``str.strip(" ,\t\r\n")`` is ASCII-only
+# and would leave U+00A0 / U+3000 / \x0b / \x0c attached to the entry, where
+# ``RFC_FORBIDDEN_URL_CHARS_RE`` (whose ``\s`` IS Unicode-aware) then reads it
+# as an illegal character inside the URL. Every other consumer of an entry
+# trims with bare ``str.strip()`` before its own RFC check
+# (``validate_service_url``, ``notifications.service._partition_urls``), so
+# trimming the same class here keeps this parser from refusing an entry the
+# rest of the module would have accepted. Anchored to the ends only: it can
+# never remove a smuggled token from the middle of an entry.
+_URL_ENTRY_EDGE_RE = re.compile(r"^[,\s]+|[,\s]+$")
+
+
+def _trim_entry_edges(entry: str) -> str:
+ """Strip surrounding commas / Unicode whitespace from a split entry."""
+ return _URL_ENTRY_EDGE_RE.sub("", entry)
+
+
_APPRISE_TELEGRAM_URL_RE = re.compile(
r"^tgram://(?:bot)?[0-9]+(?::|%3A)[a-z0-9_-]+(?:/|\?|$)",
re.IGNORECASE,
@@ -45,13 +63,46 @@ _APPRISE_TELEGRAM_URL_RE = re.compile(
def parse_notification_url_list(
urls: str, separator: str = ","
) -> tuple[list[str], Optional[str]]:
- """Partition notification URLs without dropping malformed fragments.
+ r"""Partition notification URLs without dropping malformed fragments.
A boundary is a comma or whitespace sequence followed by a URL scheme.
This preserves commas inside one Apprise service URL while keeping
- whitespace a hard separator. URL-like fragments without a scheme are
- returned separately so callers can fail closed instead of dispatching only
- the valid subset.
+ whitespace a hard separator. Commas and surrounding whitespace — any
+ Unicode whitespace, matching the bare ``str.strip()`` every other
+ consumer of an entry applies — are trimmed from each entry's ENDS
+ before it is inspected, so a value pasted with a trailing NBSP is not
+ mistaken for a URL with an illegal character in it. An entry whose
+ head carries a scheme but which contains characters that are illegal
+ unencoded in a URI (whitespace, control bytes, backslash —
+ ``RFC_FORBIDDEN_URL_CHARS_RE``, the same class ``validate_service_url``
+ rejects) is malformed no matter what trails it: the token after the first illegal character is returned
+ as the invalid fragment, so ``discord://x garbage`` fails closed exactly
+ like ``discord://x example.com/hook`` instead of being dispatched as a
+ single entry. When the illegal character only TRAILS the entry
+ (``slack://t/x/y\``) there is no token after it, so the whole entry is
+ returned as the fragment. URL-like fragments without a scheme are
+ returned separately so callers can fail closed instead of dispatching
+ only the valid subset.
+
+ ``invalid_fragment`` is a REFUSAL SIGNAL, not a substitute URL, and it
+ carries three warnings for callers:
+
+ * It may CARRY A SCHEME. ``RFC_FORBIDDEN_URL_CHARS_RE`` covers
+ backslash and the non-``\s`` control bytes, which the boundary
+ regex ``[,\s]+`` does not split on, so
+ ``a://h1/p\https://h2/q`` stays ONE entry whose fragment is
+ ``https://h2/q``. A caller that validates the fragment *in place of*
+ the entry validates a decoy while the raw original string — pointing
+ at ``h1`` — is what gets dispatched.
+ * It may be VALID on its own. Never assume validating it yields an
+ error message.
+ * It may CONTAIN CREDENTIALS. When the illegal character trails the
+ entry the fragment IS the entry, and for token-in-authority Apprise
+ schemes even a ``scheme://host`` redaction of it is the secret. Log
+ its length, never its content.
+
+ The only correct response to a non-``None`` fragment is to refuse the
+ whole input.
Returns ``(parsed_urls, invalid_fragment)``. Custom separators retain the
historical split behavior.
@@ -62,15 +113,34 @@ def parse_notification_url_list(
None,
)
- parsed_urls = [
- entry.strip(" ,\t\r\n")
- for entry in _URL_BOUNDARY_RE.split(urls)
- if entry.strip(" ,\t\r\n")
- ]
+ trimmed = (
+ _trim_entry_edges(entry) for entry in _URL_BOUNDARY_RE.split(urls)
+ )
+ parsed_urls = [entry for entry in trimmed if entry]
for entry in parsed_urls:
if not _URL_SCHEME_RE.match(entry):
return parsed_urls, entry
- for fragment in re.split(r"[,\s]+", entry)[1:]:
+ # A URL entry containing characters illegal unencoded in a URI is
+ # malformed regardless of what trails it: ``discord://x garbage``
+ # is not one URL with "garbage" in it, it is a URL followed by
+ # junk. Any token after the first illegal character surfaces as
+ # the invalid fragment so every caller fails closed on the shape.
+ if RFC_FORBIDDEN_URL_CHARS_RE.search(entry):
+ fragments = [
+ fragment
+ for fragment in RFC_FORBIDDEN_URL_CHARS_RE.split(entry)
+ if fragment
+ ]
+ # fragments[0] is the prefix before the illegal character; the
+ # next non-empty token is the smuggled fragment. When the
+ # illegal character only trails the entry, the entry itself
+ # is the malformed fragment.
+ return parsed_urls, fragments[1] if len(fragments) > 1 else entry
+ # Commas are legal inside one Apprise URL (e.g. a multi-target
+ # ``?to=id1,id2``), so a comma-separated fragment only fails closed
+ # when it is itself a scheme-less URL that Apprise could repair
+ # away or absorb into a neighbouring entry.
+ for fragment in re.split(r",+", entry)[1:]:
if _SCHEMELESS_URL_FRAGMENT_RE.match(fragment):
return parsed_urls, fragment
return parsed_urls, None
@@ -1119,9 +1189,35 @@ class NotificationURLValidator:
urls, separator
)
if invalid_fragment is not None:
+ # The fragment is refused because the INPUT does not partition
+ # unambiguously, not because the fragment itself is a bad URL.
+ # A fragment can be a perfectly valid URL on its own — the
+ # illegal character that carved it out may only trail the
+ # entry, or the token after it may be a well-formed vendor URL
+ # smuggled behind a hostile one — in which case
+ # ``validate_service_url`` returns ``(True, None)`` and the
+ # unconditional interpolation below produced the nonsense
+ # "Invalid notification service URL: None". Fall back to the
+ # parse-level reason, whose static text echoes nothing at all.
+ # The fragment's raw text is never echoed WHOLE, but the
+ # ``validate_service_url`` message used by the other branch is
+ # not credential-free by construction: a few of its returns
+ # interpolate a piece the caller supplied (the scheme in
+ # "Unsupported protocol: …", the hostname in the private-IP /
+ # metadata rejections). That is the same exposure the
+ # single-URL path already has, and no Apprise credential lives
+ # in a scheme or a resolvable hostname — but do not read this
+ # as a guarantee that nothing derived from the fragment can
+ # reach the user.
_, error_message = NotificationURLValidator.validate_service_url(
invalid_fragment, allow_private_ips
)
+ if not error_message:
+ error_message = (
+ "the URL list could not be parsed unambiguously "
+ "(unencoded space, backslash or control character, "
+ "or a fragment with no scheme)"
+ )
return (
False,
f"Invalid notification service URL: {error_message}",
diff --git a/tests/notifications/conftest.py b/tests/notifications/conftest.py
index 50fa3a65b3..d24db55510 100644
--- a/tests/notifications/conftest.py
+++ b/tests/notifications/conftest.py
@@ -10,9 +10,39 @@ verify the gate behavior itself can override by calling
the test body.
"""
+from io import StringIO
+
import pytest
+from loguru import logger as loguru_logger
@pytest.fixture(autouse=True)
def enable_notifications_by_default(monkeypatch):
monkeypatch.setenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", "true")
+
+
+def capture_loguru():
+ """Capture loguru output INCLUDING the bound ``extra`` mapping.
+
+ Credential-leak assertions must see the structured fields too: a
+ ``logger.bind(...).warning("msg", field=value)`` call puts ``field``
+ in ``record["extra"]``, not in ``{message}``, so a ``{message}``-only
+ sink would make a leak-through-``extra`` test pass vacuously.
+ """
+ output = StringIO()
+ sink_id = loguru_logger.add(
+ output,
+ format="{message} | {extra}",
+ level="DEBUG",
+ diagnose=False,
+ )
+ loguru_logger.enable("local_deep_research")
+ try:
+ yield output
+ finally:
+ loguru_logger.remove(sink_id)
+ # Restore the package's default-disabled state (see
+ # ``src/local_deep_research/__init__.py`` and the ``loguru_caplog``
+ # fixtures in the root conftest, which do the same).
+ loguru_logger.disable("local_deep_research")
diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.py
index b090958e07..66ac5dab1b 100644
--- a/tests/notifications/test_manager.py
+++ b/tests/notifications/test_manager.py
@@ -594,6 +594,184 @@ class TestNotificationResultSemantics:
assert "could not be evaluated" in result.detail
assert "refused" not in result.detail
+ def test_unparseable_service_url_is_invalid_url_not_egress_denied(
+ self, mocker
+ ):
+ """A scheme-less service URL is rejected before the egress policy
+ is even consulted, so it must be reported as ``invalid_url`` — not
+ ``egress_denied``, which would falsely imply the policy was
+ evaluated and refused it (issue #5110)."""
+ snapshot = {
+ "notifications.service_url": "example.com/hook",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.sent is False
+ assert result.reason is NotificationReason.INVALID_URL
+ assert "egress" not in result.detail
+
+ def test_unparseable_fragment_in_multi_url_list_is_invalid_url(
+ self, mocker
+ ):
+ """Same as above, but the unparseable fragment trails a
+ well-formed URL in a multi-URL configuration."""
+ snapshot = {
+ "notifications.service_url": "discord://x example.com/hook",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.sent is False
+ assert result.reason is NotificationReason.INVALID_URL
+ assert "egress" not in result.detail
+
+ def test_separator_only_service_url_is_invalid_url_not_egress_denied(
+ self, mocker
+ ):
+ """A nonempty setting that parses to zero URLs (separator
+ characters only, e.g. ",") must be reported as ``invalid_url``
+ — not ``egress_denied``. No URL was ever evaluated, so
+ "all configured URLs refused by egress policy" would claim a
+ refusal that never happened — the same dishonest-classification
+ defect this PR fixes elsewhere (issue #5110).
+
+ Teeth: drop the empty-``url_entries`` guard in
+ ``send_notification`` and the flow falls through to the egress
+ branch, which returns ``egress_denied`` with "refused" in the
+ detail — both assertions fail."""
+ snapshot = {
+ "notifications.service_url": ",",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.sent is False
+ assert result.reason is NotificationReason.INVALID_URL
+ assert "refused" not in result.detail
+
+ def test_whitespace_mixed_malformed_url_is_invalid_url_not_egress_denied(
+ self, mocker
+ ):
+ """A scheme-bearing entry trailed by a bare word —
+ ``discord://x garbage`` — is malformed configuration, not a policy
+ refusal. The parser must flag ANY token after unencoded whitespace,
+ not only scheme-less dotted names like ``example.com/hook``;
+ otherwise this shape sails through to the egress filter, which
+ under PRIVATE_ONLY refuses the discord scheme and mislabels the
+ drop as ``egress_denied`` / "all configured URLs refused by egress
+ policy" (issue #5113 follow-up).
+
+ Teeth: weaken ``parse_notification_url_list`` back to dotted-
+ name-only trailing-fragment detection and ``garbage`` goes
+ undetected — the flow falls through to the egress branch, which
+ returns ``egress_denied`` with "refused" in the detail, failing
+ both assertions."""
+ snapshot = {
+ "notifications.service_url": "discord://x garbage",
+ "notifications.on_research_completed": True,
+ "policy.egress_scope": "private_only",
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.sent is False
+ assert result.reason is NotificationReason.INVALID_URL
+ assert "refused" not in result.detail
+
+ def test_fragment_drop_log_never_carries_the_fragment(
+ self, mocker, capture_loguru
+ ):
+ r"""The ``invalid_url`` drop log must record NOTHING derived from
+ the fragment's content — not even a redacted form.
+
+ ``redact_url_for_log`` keeps ``scheme://host[:port]``, but for the
+ token-in-authority Apprise schemes the first authority segment IS
+ the secret: ``slack://xoxb-SECRET-TOKEN/T00/B00`` redacts to
+ ``slack://xoxb-SECRET-TOKEN``. And when the illegal character only
+ TRAILS the entry the parser returns the WHOLE entry as the
+ fragment, so the redaction runs on the operator's real,
+ credential-bearing service URL. The sibling comment in this same
+ code already says "Never log the fragment itself — it may contain
+ credentials"; a redaction that preserves the credential does not
+ satisfy that.
+
+ Teeth: restore ``fragment=redact_url_for_log(invalid_fragment)``
+ in ``NotificationManager.send_notification`` and the bound extra
+ carries ``slack://xoxb-SECRET-TOKEN`` — the token assertion fails
+ while the positive control still passes.
+ """
+ token = "xoxb-SECRET-TOKEN"
+ snapshot = {
+ "notifications.service_url": f"slack://{token}/T00000/B00000\\",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+
+ assert result.sent is False
+ assert result.reason is NotificationReason.INVALID_URL
+
+ logged = capture_loguru.getvalue()
+ # Positive control: without this the token assertions below would
+ # pass vacuously on an empty log.
+ assert "unparseable service URL fragment" in logged
+ assert token not in logged
+ assert "slack://" not in logged
+ # The diagnostic that replaced it is content-free.
+ assert "fragment_length" in logged
+
+ # ...and the user-facing detail is content-free too.
+ assert token not in result.detail
+
+ def test_egress_filter_fragment_log_never_carries_the_fragment(
+ self, capture_loguru
+ ):
+ r"""Same defect, second call site:
+ ``_filter_urls_by_egress_policy`` logged
+ ``redact_url_for_log(invalid_fragment)`` too.
+
+ Teeth: restore that call and the bound extra carries
+ ``slack://xoxb-SECRET-TOKEN`` while the positive control keeps
+ passing.
+ """
+ token = "xoxb-SECRET-TOKEN"
+ snapshot = {
+ "notifications.service_url": "unused",
+ "policy.egress_scope": "both",
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+
+ allowed = manager._filter_urls_by_egress_policy(
+ f"slack://{token}/T00000/B00000\\"
+ )
+
+ assert allowed == ""
+ logged = capture_loguru.getvalue()
+ assert "unparseable URL fragment" in logged
+ assert token not in logged
+ assert "slack://" not in logged
+
def test_invalid_url_when_apprise_accepts_no_urls(self, mocker):
"""A falsy return from ``send_event`` means Apprise rejected the
URL string at parse time (dispatch never attempted) →
@@ -610,13 +788,29 @@ class TestNotificationResultSemantics:
context={"query": "q"},
)
assert result.reason is NotificationReason.INVALID_URL
+ # The detail must carry the corrected claim — Apprise rejected
+ # a URL before dispatch completed — not the old "accepted
+ # none" wording that was false for a mixed URL list (the valid
+ # partition was never tried). Revert the detail correction in
+ # send_notification and both assertions fail.
+ assert "rejected a configured service URL" in result.detail
+ assert "accepted none" not in result.detail
def test_invalid_url_real_service_contract(self, mocker):
- """Same as above but through the REAL NotificationService, so the
- test breaks if the service's invalid-URL contract ever changes.
- An unrecognized scheme fails the SSRF URL validator, which raises
+ """Same as above but through the REAL NotificationService. An
+ unrecognized scheme fails the SSRF URL validator, which raises
ServiceError before any network I/O — that too must map to
- ``invalid_url``, not ``exception``."""
+ ``invalid_url``, not ``exception``.
+
+ Note: this only guards the manager's ``except ServiceError``
+ clause, not "the service's invalid-URL contract" broadly. If the
+ scheme allowlist regressed instead (e.g. the validator started
+ accepting ``not-a-real-scheme://``), the URL would instead fail at
+ Apprise's own ``add()`` inside ``_dispatch``, which returns
+ ``False`` — and the manager's falsy-``send_event`` branch (see
+ ``test_invalid_url_when_apprise_accepts_no_urls``) still yields
+ ``invalid_url`` too, so this test would keep passing (for the
+ wrong reason) even with that regression."""
snapshot = {
"notifications.service_url": "not-a-real-scheme://nope",
"notifications.on_research_completed": True,
@@ -766,7 +960,15 @@ class TestNotificationResultSemantics:
def test_test_service_distinguishes_unevaluable_policy(self, mocker):
"""test_service must not blame the egress scope when the policy
- could not be evaluated at all (filter returned None)."""
+ could not be evaluated at all (filter returned None) — an
+ unevaluable policy is a configuration problem, not a refusal,
+ and the "Set Egress Scope to 'Unprotected'" remediation fixes
+ the wrong thing.
+
+ Teeth: drop the ``allowed is None`` branch in ``test_service``
+ and the None return falls into the refusal branch below it —
+ the message becomes "URL refused by egress policy...", failing
+ both assertions."""
snapshot = {"notifications.service_url": "discord://x"}
manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
with patch.object(
@@ -777,6 +979,43 @@ class TestNotificationResultSemantics:
assert "could not be evaluated" in result["message"]
assert "refused" not in result["message"]
+ @pytest.mark.parametrize(
+ ("label", "url"),
+ [
+ ("scheme-less fragment", "secret.example.com/x discord://a/b"),
+ ("no parseable URLs", ","),
+ ],
+ )
+ def test_test_service_reports_unusable_url_as_invalid_not_egress_denied(
+ self, mocker, label, url
+ ):
+ """``test_service`` must draw the same distinction
+ ``send_notification`` draws: ``_filter_urls_by_egress_policy``
+ returns ``""`` for an unparseable fragment and for a setting with
+ no parseable URLs as well as for a real per-URL refusal, so
+ mapping every ``""`` onto "Set Egress Scope to 'Unprotected'"
+ tells the operator to widen a policy that was never consulted.
+
+ Teeth: drop the ``parse_notification_url_list`` precheck at the
+ top of ``test_service`` and both inputs fall through to the
+ ``if not allowed`` branch — the message becomes "URL refused by
+ egress policy. Set Egress Scope to 'Unprotected'…", failing the
+ two assertions below.
+ """
+ snapshot = {
+ "policy.egress_scope": {"value": "unprotected"},
+ "search.tool": {"value": "searxng"},
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager.service.test_service = mocker.MagicMock()
+
+ result = manager.test_service(url)
+
+ assert result["status"] == "error", label
+ assert "Egress Scope" not in result["message"], label
+ assert "refused by egress policy" not in result["message"], label
+ manager.service.test_service.assert_not_called()
+
def test_rate_limit_still_raises(self, mocker):
"""Backward compat: rate-limit refusal still raises, not returned."""
snapshot = {
@@ -1262,9 +1501,23 @@ class TestEgressPolicyURLFilter:
assert mgr._filter_urls_by_egress_policy(service_urls) == ""
- def test_scheme_less_refusal_logs_only_redacted_fragment(self):
+ def test_scheme_less_refusal_logs_no_fragment_content(self):
+ """The scheme-less refusal log records the fragment's LENGTH and
+ the entry count, and nothing derived from its content — not even
+ a ``redact_url_for_log`` form.
+
+ ``redact_url_for_log`` keeps ``scheme://host``, but for the
+ token-in-authority Apprise schemes the first authority segment IS
+ the secret, and when the illegal character only trails an entry
+ the fragment is the whole entry. Teeth: restore
+ ``fragment=redact_url_for_log(invalid_fragment)`` in
+ ``_filter_urls_by_egress_policy`` and the ``"fragment" not in
+ kwargs`` assertion fails; drop the diagnostics and the
+ ``fragment_length`` / ``entries_parsed`` assertions fail.
+ """
mgr = self._mgr("unprotected")
- service_urls = "secret.example.com/private/token slack://t/x/y"
+ fragment = "secret.example.com/private/token"
+ service_urls = f"{fragment} slack://t/x/y"
with patch(
"local_deep_research.notifications.manager.logger"
@@ -1274,8 +1527,57 @@ class TestEgressPolicyURLFilter:
mock_logger.bind.assert_called_once_with(policy_audit=True)
warning = mock_logger.bind.return_value.warning
warning.assert_called_once()
- assert warning.call_args.kwargs["fragment"] == "?://secret.example.com"
- assert "/private/token" not in warning.call_args.kwargs["fragment"]
+ # No content-bearing field at all.
+ assert "fragment" not in warning.call_args.kwargs
+ # Only the content-free diagnostics, and they are the real values.
+ assert warning.call_args.kwargs["fragment_length"] == len(fragment)
+ assert warning.call_args.kwargs["entries_parsed"] == 2
+ # Nothing derived from the input reaches the message or any kwarg.
+ emitted = [str(warning.call_args.args[0])] + [
+ str(value) for value in warning.call_args.kwargs.values()
+ ]
+ for text in emitted:
+ assert "secret.example.com" not in text
+ assert "/private/token" not in text
+
+ def test_egress_refusal_log_never_carries_the_refused_url(
+ self, capture_loguru
+ ):
+ """The ``policy_audit`` line for a refused http(s) URL must carry
+ only the redacted ``scheme://host[:port]``.
+
+ This branch sees http(s) URLs straight from
+ ``notifications.service_url``. RFC 3986 §3.2.1 allows credentials
+ in the userinfo, and for a Slack/Discord-style webhook the PATH is
+ the secret — ``https://hooks.example/services/T0/B0/TOKEN`` is a
+ bearer credential in its entirety. Logging the entry verbatim put
+ both into the audit log (and, via ``database_sink``, into
+ ``app_logs``).
+
+ Teeth: revert ``url=redact_url_for_log(url_entry)`` to
+ ``url=url_entry`` in ``_filter_urls_by_egress_policy`` and the
+ bound ``extra`` carries the password, the userinfo and the whole
+ secret path — four of the assertions below fail while the
+ positive controls keep passing.
+ """
+ mgr = self._mgr("public_only")
+ # A private host is refused under PUBLIC_ONLY, so this reaches the
+ # ``decision.allowed is False`` branch. An IP literal keeps the
+ # classification deterministic (no DNS).
+ url = "https://ops:[email protected]/services/T0/B0/SECRETTOKEN"
+
+ assert mgr._filter_urls_by_egress_policy(url) == ""
+
+ logged = capture_loguru.getvalue()
+ # Positive controls: without these the absence assertions could
+ # pass vacuously on an empty log.
+ assert "notification URL refused by egress policy" in logged
+ assert "127.0.0.1" in logged
+ # ...and nothing else from the entry survives.
+ assert "PASSWORDSECRET" not in logged
+ assert "ops:" not in logged
+ assert "SECRETTOKEN" not in logged
+ assert "/services/" not in logged
def test_public_only_blocks_private_http_keeps_public(self):
mgr = self._mgr("public_only", tool="searxng")
diff --git a/tests/notifications/test_notification_webhook_dns_pin.py b/tests/notifications/test_notification_webhook_dns_pin.py
index f0dd05e696..53796396b3 100644
--- a/tests/notifications/test_notification_webhook_dns_pin.py
+++ b/tests/notifications/test_notification_webhook_dns_pin.py
@@ -347,15 +347,18 @@ def test_rebind_to_metadata_blocked_through_apprise():
"""Validation sees a public IP; the pin's connect-time re-validation
catches the rebind to cloud-metadata and refuses the send before any
connection is made. The pin's rebind catch raises a non-retryable
- ValueError, which ``send()`` surfaces as ServiceError (a confirmed
- security block, not a retryable SendError — see
- ``NotificationService.send``'s docstring)."""
+ ValueError, which ``send()`` surfaces as ``SecurityBlockError`` — a
+ ``ServiceError`` subclass reserved for a CONFIRMED send-time block (as
+ opposed to plain ``ServiceError``, raised for pre-dispatch validation
+ rejects) — see ``NotificationService.send``'s docstring. Asserting the
+ subclass here (not the broader ``ServiceError``) is what pins this test
+ to the send-time rebind path rather than any pre-dispatch reject."""
resolver = _Resolver(
{"rebind.example": [["93.184.216.34"], ["169.254.169.254"]]}
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
@@ -371,7 +374,9 @@ def test_multi_url_batch_guards_every_host():
the batch is pinned/checked: one host that rebinds to metadata refuses
the whole batch (fail closed) and no connection to the metadata IP is
made — proving the guard is not applied to just the first URL. The
- confirmed rebind raises ServiceError (non-retryable), not SendError."""
+ confirmed rebind raises ``SecurityBlockError`` (non-retryable, a
+ ``ServiceError`` subclass) — asserting the subclass pins this to the
+ send-time block path, not any pre-dispatch reject."""
server, port, _hits = _start_server()
resolver = _Resolver(
{
@@ -382,7 +387,7 @@ def test_multi_url_batch_guards_every_host():
urls = f"json://a.example:{port}/x,json://b.example/y"
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(title="t", body="b", service_urls=urls)
try:
assert not any(addr[0] == "169.254.169.254" for addr in targets)
@@ -590,8 +595,17 @@ def test_pinned_notification_send_fails_closed_when_shim_missing():
"""If ``socket.getaddrinfo`` is no longer our shim (e.g. a late
gevent/eventlet monkeypatch), the thread-local pin/block would silently
not apply. pinned_notification_send must REFUSE the send (fail closed)
- rather than proceed unguarded. Teeth: drop the ``_shim_installed`` guard
- and this raises nothing."""
+ rather than proceed unguarded.
+
+ Asserts the SPECIFIC ``NotificationGuardUnavailableError`` type (not a
+ bare ``RuntimeError``, which it subclasses) — see
+ ``test_send_fails_closed_through_send_when_shim_missing`` below for why
+ that distinction matters: a bare ``RuntimeError`` here would still pass
+ if ``dns_pinning`` reverted to ``raise RuntimeError(...)``, silently
+ losing the dedicated type ``notifications.service`` relies on to route
+ this into ``SecurityBlockError`` instead of the generic
+ ``except Exception`` catch-all. Teeth: drop the ``_shim_installed``
+ guard and this raises nothing."""
saved = socket.getaddrinfo
resolver = _Resolver({}) # empty: any real lookup would gaierror
try:
@@ -599,7 +613,9 @@ def test_pinned_notification_send_fails_closed_when_shim_missing():
# Displace our shim with a plain non-shim resolver.
socket.getaddrinfo = resolver
assert not dns_pinning._shim_installed()
- with pytest.raises(RuntimeError, match="shim"):
+ with pytest.raises(
+ dns_pinning.NotificationGuardUnavailableError, match="shim"
+ ):
with dns_pinning.pinned_notification_send(
["json://x.example/y"], allow_private_ips=True
):
@@ -610,6 +626,179 @@ def test_pinned_notification_send_fails_closed_when_shim_missing():
assert dns_pinning._shim_installed()
+def test_send_fails_closed_through_send_when_shim_missing():
+ """End-to-end: when the DNS-pin shim is not installed,
+ ``NotificationService.send()`` must surface this as
+ ``SecurityBlockError`` (a ``ServiceError`` subclass, mapped by
+ ``NotificationManager`` to the non-retryable ``invalid_url`` reason) —
+ NOT let it fall through to the generic ``except Exception`` branch
+ (which ``NotificationManager`` maps to the ``exception`` reason,
+ silently losing the fact that this was a deliberate fail-closed
+ security refusal, not an incidental bug).
+
+ Teeth: if ``dns_pinning.pinned_notification_send`` reverted to raising
+ a bare ``RuntimeError`` instead of the dedicated
+ ``NotificationGuardUnavailableError`` subclass, ``send()``'s
+ ``except dns_pinning.NotificationGuardUnavailableError`` clause would
+ no longer match, this test's ``pytest.raises(SecurityBlockError)``
+ would fail, and the bare ``RuntimeError`` would propagate through the
+ generic ``except Exception`` branch instead.
+
+ ``guard-missing.example`` resolves to a public IP so PRE-DISPATCH URL
+ validation (which itself calls ``socket.getaddrinfo``, and would
+ otherwise fail with an unrelated "could not resolve host" ServiceError
+ before the guard is even reached) succeeds; the guard-unavailable
+ refusal then happens purely because the shim is displaced, not because
+ the host is unresolvable."""
+ saved = socket.getaddrinfo
+ resolver = _Resolver({"guard-missing.example": [["93.184.216.34"]]})
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ # Displace our shim with a plain non-shim resolver, exactly as
+ # test_pinned_notification_send_fails_closed_when_shim_missing
+ # does above.
+ socket.getaddrinfo = resolver
+ assert not dns_pinning._shim_installed()
+ with pytest.raises(SecurityBlockError):
+ _service().send(
+ title="t",
+ body="b",
+ service_urls="json://guard-missing.example/y",
+ )
+ finally:
+ socket.getaddrinfo = saved
+ assert dns_pinning._shim_installed()
+
+
+def test_resolver_unicode_error_is_connection_error_not_security_block():
+ """A resolver failure that is a ``UnicodeError`` — what
+ ``socket.getaddrinfo`` raises for a host whose IDNA encoding fails
+ (a label over 63 bytes or an empty label; ``UnicodeEncodeError`` is
+ a ``ValueError`` subclass) — must leave ``_resolve_and_validate``
+ as a ``requests.ConnectionError``, an ordinary transport failure,
+ and never as a bare ``ValueError``:
+ ``NotificationService.send()``'s ``except ValueError`` clause
+ treats that as a CONFIRMED send-time SSRF block and re-raises it as
+ ``SecurityBlockError``, which would mislabel a resolution failure
+ as a security block (and map it to the non-retryable ``invalid_url``
+ instead of a retryable transport failure).
+
+ Teeth: revert ``except (socket.gaierror, UnicodeError)`` to
+ ``except socket.gaierror`` in ``dns_pinning._resolve_and_validate``
+ and the ``UnicodeEncodeError`` escapes this call uncaught, so
+ ``pytest.raises(requests.ConnectionError)`` fails.
+ """
+
+ def _idna_broken_resolver(host, port, family=0, type=0, proto=0, flags=0):
+ raise UnicodeEncodeError(
+ "idna", host, 0, len(host), "label too long or empty"
+ )
+
+ with patch.object(dns_pinning, "_real_getaddrinfo", _idna_broken_resolver):
+ with pytest.raises(requests.ConnectionError):
+ dns_pinning._resolve_and_validate(
+ "unicode-fail.example",
+ allow_localhost=False,
+ allow_private_ips=False,
+ )
+
+
+def test_send_time_unicode_error_is_gaierror_not_security_block():
+ """The SAME invariant, one function away: an IDNA-unencodable host
+ that reaches ``_resolve_maybe_block`` (i.e. resolution INSIDE an
+ active block-private window) must be refused as ``socket.gaierror``,
+ never as a bare ``ValueError``.
+
+ ``socket.getaddrinfo`` raises ``UnicodeError`` — a ``ValueError``
+ subclass — for a label over 63 bytes or an empty label. At this layer
+ a ``ValueError`` reaching the sender means a CONFIRMED SSRF block, so
+ letting it escape mislabels an ordinary resolution failure as
+ ``SecurityBlockError`` — exactly the defect
+ ``_resolve_and_validate``'s ``except (socket.gaierror, UnicodeError)``
+ fixed at pin time.
+
+ This path is genuinely reachable, not hypothetical: ``pin_hosts``
+ SKIPS a host whose pin-time resolution raised
+ ``requests.ConnectionError`` — which, since that fix, INCLUDES this
+ UnicodeError case — and leaves it unpinned, so its send-time lookup
+ lands here.
+
+ Teeth: remove the ``except UnicodeError`` clause around
+ ``_getaddrinfo_bounded`` in ``dns_pinning._resolve_maybe_block`` and
+ the ``UnicodeEncodeError`` escapes uncaught, so
+ ``pytest.raises(socket.gaierror)`` fails (it is a ``ValueError``, not
+ an ``OSError``).
+ """
+
+ def _idna_broken_resolver(host, port, family=0, type=0, proto=0, flags=0):
+ raise UnicodeEncodeError(
+ "idna", str(host), 0, len(str(host)), "label too long or empty"
+ )
+
+ # Clear any marker a sibling test left on this thread so the
+ # "not reported as a confirmed block" assertion below is meaningful.
+ dns_pinning.reset_ssrf_block()
+
+ with patch.object(dns_pinning, "_real_getaddrinfo", _idna_broken_resolver):
+ with dns_pinning.block_private_resolution(
+ allow_localhost=False,
+ allow_private_ips=False,
+ block_link_local=True,
+ ):
+ with pytest.raises(socket.gaierror) as excinfo:
+ dns_pinning._resolve_maybe_block(
+ "unicode-fail.example",
+ None,
+ socket.AF_UNSPEC,
+ socket.SOCK_STREAM,
+ 0,
+ 0,
+ )
+
+ # A gaierror is an OSError, so it can never be caught by the
+ # ``except ValueError`` clause that reports a confirmed SSRF block.
+ assert not isinstance(excinfo.value, ValueError)
+ # And this is NOT reported as a confirmed block, so the send is not
+ # forced onto the fail-fast security path.
+ assert dns_pinning.consume_ssrf_block() is False
+
+
+def test_pin_hosts_skips_idna_unencodable_host_without_aborting():
+ """``pin_hosts`` must not abort the batch for an IDNA-unencodable
+ host: ``_resolve_and_validate`` routes it to
+ ``requests.ConnectionError``, which the loop skips. Pins the handoff
+ the test above depends on — the host is left UNPINNED, so the
+ block-private window governs its send-time lookup.
+
+ Teeth: revert this PR's delta — ``_resolve_and_validate``'s
+ ``except (socket.gaierror, UnicodeError)`` back to ``except
+ socket.gaierror`` — and the resolver's ``UnicodeEncodeError`` is never
+ converted to ``requests.ConnectionError``, so ``pin_hosts``' handler
+ does not catch it: the context manager raises instead of yielding and
+ the body below never runs.
+ """
+
+ calls = []
+
+ def _idna_broken_resolver(host, port, family=0, type=0, proto=0, flags=0):
+ calls.append(host)
+ raise UnicodeEncodeError(
+ "idna", str(host), 0, len(str(host)), "label too long or empty"
+ )
+
+ with patch.object(dns_pinning, "_real_getaddrinfo", _idna_broken_resolver):
+ # ``json`` is a PINNABLE scheme, so the loop really does try to
+ # resolve this host — a non-pinnable scheme (``ntfy``) would be
+ # skipped before resolution and make this test vacuous.
+ with dns_pinning.pin_hosts(
+ ["json://unicode-fail.example/x"],
+ allow_localhost=False,
+ allow_private_ips=False,
+ ):
+ assert calls, "pin_hosts never attempted to resolve the host"
+ assert dns_pinning._get_pins().get("unicode-fail.example") is None
+
+
def _fixed_resolver(ip):
"""A resolver that answers EVERY host (str or bytes) with ``ip``."""
@@ -756,15 +945,19 @@ def test_ssrf_block_is_not_retried():
fail fast, not be retried 3x by Tenacity. The rebind host resolves
public at validation (call #1) and metadata at the guarded pin (call
#2), which raises the SSRF ValueError; with that excluded from retries
- the guarded pin runs exactly ONCE. ``send()`` surfaces this confirmed,
- non-retryable block as ServiceError, not SendError. Teeth: restore
+ the guarded pin runs exactly ONCE. ``send()``'s ``except ValueError``
+ maps that confirmed, non-retryable block to ``SecurityBlockError`` —
+ asserted specifically here rather than as its ``ServiceError`` base,
+ so a regression that reports the block as a plain ``ServiceError``
+ (or lets ``SendError``'s retryable ``WEBHOOK_FAILED`` reason claim it)
+ fails the test. Teeth: restore
``retry_if_exception_type((Exception,))`` and the pin is retried, so
rebind.example is resolved 4 times (1 validation + 3 pin attempts)."""
resolver = _Resolver(
{"rebind.example": [["93.184.216.34"], ["169.254.169.254"]]}
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
@@ -853,8 +1046,11 @@ def test_block_window_block_is_not_retried():
re-raises it non-retryably. The rebind host resolves public at validation
(call #1) and metadata at the send-time window resolution (call #2), so
with the block excluded from retries the host is resolved exactly TWICE.
- ``send()`` surfaces the confirmed, non-retryable block as ServiceError,
- not SendError. Teeth: drop the ``consume_ssrf_block`` short-circuit in
+ ``send()``'s ``except ValueError`` maps the confirmed, non-retryable
+ block to ``SecurityBlockError`` — asserted specifically, not as its
+ ``ServiceError`` base, so a regression that reports it as a plain
+ ``ServiceError`` (or as a retryable ``SendError``) fails the test.
+ Teeth: drop the ``consume_ssrf_block`` short-circuit in
``_send_with_retry`` and the send is retried, resolving the host 4 times
(1 validation + 3 send attempts)."""
resolver = _Resolver(
@@ -862,7 +1058,7 @@ def test_block_window_block_is_not_retried():
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
@@ -1075,7 +1271,10 @@ def test_ipv6_imds_rebind_refused_through_send():
re-validation catches the rebind (the cloud-metadata block is absolute even
under allow_private_ips=True, which permits the fc00::/7 ULA the address
sits in) and raises the SSRF ValueError, which ``send()`` surfaces as
- ServiceError (confirmed, non-retryable security block — not SendError).
+ ``SecurityBlockError`` (confirmed, non-retryable send-time security
+ block — a ``ServiceError`` subclass, not SendError). Asserting the
+ subclass pins this to the send-time rebind path, not a pre-dispatch
+ reject.
Teeth: drop the ``is_ip_blocked`` check in
``dns_pinning._resolve_and_validate`` (or remove ``fd00:ec2::254`` from
@@ -1091,7 +1290,7 @@ def test_ipv6_imds_rebind_refused_through_send():
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
@@ -1262,15 +1461,17 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition():
fails — the rebind pins successfully and the connect spy sees
169.254.42.42.
- The confirmed rebind raises ServiceError (non-retryable), not
- SendError.
+ The confirmed rebind raises ``SecurityBlockError`` (non-retryable, a
+ ``ServiceError`` subclass), not SendError. Asserting the subclass (not
+ the broader ``ServiceError``) pins this to the send-time rebind path
+ exercised by ``_dispatch``, not any pre-dispatch reject.
"""
resolver = _Resolver(
{"ll-rebind.example": [["93.184.216.34"], ["169.254.42.42"]]}
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
@@ -1287,7 +1488,9 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition_ipv6():
address ``fe80::1`` (fe80::/10, not an always-blocked literal) at
``_dispatch``'s pin resolution (call #2). Same wiring lock —
refused only by ``_dispatch``'s ``block_link_local=True``. The
- confirmed rebind raises ServiceError (non-retryable), not SendError."""
+ confirmed rebind raises ``SecurityBlockError`` (non-retryable, a
+ ``ServiceError`` subclass), not SendError. Asserting the subclass pins
+ this to the send-time rebind path, not a pre-dispatch reject."""
resolver = _Resolver(
{
"ll-rebind6.example": [
@@ -1298,7 +1501,7 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition_ipv6():
)
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
with _connect_spy() as targets:
- with pytest.raises(ServiceError):
+ with pytest.raises(SecurityBlockError):
_service().send(
title="t",
body="b",
diff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.py
index b24ad27119..40fc52913e 100644
--- a/tests/notifications/test_service.py
+++ b/tests/notifications/test_service.py
@@ -341,7 +341,20 @@ class TestTestService:
@patch("local_deep_research.notifications.service.apprise.Apprise")
def test_test_service_success(self, mock_apprise_class):
- """Test successful service test."""
+ """Test successful service test.
+
+ Also pins the SHAPE of the ``temp_apprise.add`` argument: the
+ parsed entry LIST, never the raw setting string. Teeth: revert
+ ``temp_apprise.add(list(url_entries))`` to ``temp_apprise.add(url)``
+ in ``NotificationService.test_service`` and the argument is a
+ ``str``, so the list assertion below fails. That revert matters
+ because ``add()`` runs Apprise's own ``parse_urls`` splitter ONLY
+ on a ``str``: with a string in the path, LDR's boundary regex and
+ Apprise's ``URL_DETECTION_RE`` each get a vote on where entries
+ start and they disagree (a LEADING DIGIT starts a new entry for
+ Apprise but not for LDR), so ``discord://a/b,7z://x`` is one
+ validated entry to LDR and two dispatched targets to Apprise.
+ """
mock_apprise_instance = MagicMock()
mock_apprise_instance.add.return_value = True
mock_apprise_instance.notify.return_value = True
@@ -360,6 +373,10 @@ class TestTestService:
call.kwargs["asset"].http_redirects is False
for call in mock_apprise_class.call_args_list
)
+ # Apprise is handed the already-parsed entries, as a list.
+ add_arg = mock_apprise_instance.add.call_args[0][0]
+ assert add_arg == ["discord://webhook/token"]
+ assert isinstance(add_arg, list)
@patch("local_deep_research.notifications.service.apprise.Apprise")
def test_test_service_rejects_template_before_apprise_add(
@@ -664,6 +681,163 @@ class TestTestServiceParserDifferential:
assert len(MagicMock()) == 0
+class TestTestServiceInvalidFragmentRefusal:
+ r"""``test_service()`` must REFUSE outright when
+ ``parse_notification_url_list`` reports an ``invalid_fragment`` —
+ it must never validate the fragment IN PLACE OF the input it was
+ carved out of.
+
+ The fragment is cut on ``RFC_FORBIDDEN_URL_CHARS_RE``
+ (``[\\\s\x00-\x1f\x7f]`` — backslash and every control byte), but the
+ entry boundary regex is ``[,\s]+``. Backslash and the non-``\s``
+ control bytes are therefore in the fragment class but NOT in the
+ boundary class, so ``a://h1/p\https://h2/q`` stays ONE parsed entry
+ whose fragment is ``https://h2/q``. The old code substituted
+ ``url_entries = [invalid_fragment]``, which made that fragment a
+ dispatchable DECOY:
+
+ * only the decoy was validated by the per-entry loop;
+ * ``temp_apprise.add(url)`` then added the RAW ORIGINAL string, so
+ the real destination was ``h1``;
+ * the smuggle guard compared ``len(temp_apprise) > len(url_entries)``
+ — ``1 > 1`` — and stayed silent;
+ * the pin / block-private policy (``has_http``, ``block_link_local``)
+ was derived from the DECOY's scheme, so a link-local target rode
+ out under ``block_link_local=False``.
+
+ Under the old (pre-#5113-follow-up) parser this shape was hard-
+ rejected because the backslash tripped ``validate_service_url``'s own
+ RFC check, so the substitution is a regression introduced by widening
+ the parser — closed here at the consumer, not by weakening the parser.
+ """
+
+ # A hostile link-local (Scaleway-style metadata) target hidden behind
+ # a perfectly valid Discord webhook decoy, joined by a backslash.
+ BACKSLASH_DECOY_URL = (
+ "json://169.254.42.42/x"
+ "\\https://discord.com/api/webhooks/123456789/abcdefghijklmnop"
+ )
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_backslash_smuggled_decoy_fragment_is_refused(
+ self, mock_apprise_class
+ ):
+ r"""Teeth: restore ``url_entries = [invalid_fragment]`` in
+ ``NotificationService.test_service`` and the per-entry loop
+ validates only the ``https://discord.com/...`` decoy, which
+ passes — so ``temp_apprise.add`` IS reached and
+ ``result["success"]`` is True, failing every assertion below.
+
+ With ONLY that revert, ``add(list(url_entries))`` hands Apprise
+ the decoy, so the send goes to ``discord.com`` rather than to the
+ link-local target. Reaching the raw
+ ``json://169.254.42.42/x\https://...`` string — the original
+ defect, where the link-local host is what actually gets notified
+ — takes the SECOND revert as well: ``add(list(url_entries))``
+ back to ``add(url)``. That is the pairing the class docstring
+ above describes; either half alone is enough to fail this test.
+ """
+ mock_apprise_instance = MagicMock()
+ mock_apprise_instance.add.return_value = True
+ mock_apprise_instance.notify.return_value = True
+ mock_apprise_instance.__len__.return_value = 1
+ mock_apprise_class.return_value = mock_apprise_instance
+
+ service = NotificationService(
+ outbound_allowed=True, allow_private_ips=True
+ )
+
+ result = service.test_service(self.BACKSLASH_DECOY_URL)
+
+ assert result["success"] is False
+ assert "could not be parsed unambiguously" in result["error"]
+ # The dispatch side must never be reached: Apprise would have
+ # been handed the RAW original string, not the validated decoy.
+ mock_apprise_instance.add.assert_not_called()
+ mock_apprise_instance.notify.assert_not_called()
+ # And nothing derived from the input is echoed back to the user.
+ assert "169.254.42.42" not in result["error"]
+ assert "discord.com" not in result["error"]
+
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_trailing_forbidden_byte_is_refused(self, mock_apprise_class):
+ r"""The ``else entry`` branch of the parser: when the illegal
+ character only TRAILS the entry there is no token after it, so the
+ WHOLE entry comes back as the fragment.
+
+ Teeth (narrow, and NOT the ``add``/``notify`` assertions): restore
+ ``url_entries = [invalid_fragment]`` and the fragment IS the entry,
+ so the loop validates ``"slack://tokenA/tokenB/tokenC/\\"`` — and
+ the REAL ``validate_service_url_with_hint`` rejects it on the
+ trailing backslash (``RFC_FORBIDDEN_URL_CHARS_RE``) before Apprise
+ is touched. So ``add``/``notify`` stay uncalled on the revert too;
+ what actually breaks is the MESSAGE assertion: the user would get
+ the validator's "URL contains characters that are not allowed"
+ instead of this path's "could not be parsed unambiguously", i.e.
+ a per-entry complaint about a decoy rather than a refusal of the
+ whole input. The ``add``/``notify`` assertions are kept as
+ belt-and-braces for a revert that ALSO loosens the validator.
+ ``test_fragment_that_would_pass_validation_is_still_refused``
+ below is the sibling that keeps teeth on the dispatch itself, by
+ stubbing the validator open.
+ """
+ mock_apprise_instance = MagicMock()
+ mock_apprise_instance.add.return_value = True
+ mock_apprise_instance.notify.return_value = True
+ mock_apprise_instance.__len__.return_value = 1
+ mock_apprise_class.return_value = mock_apprise_instance
+
+ service = NotificationService(outbound_allowed=True)
+
+ result = service.test_service("slack://tokenA/tokenB/tokenC/\\")
+
+ assert result["success"] is False
+ assert "could not be parsed unambiguously" in result["error"]
+ mock_apprise_instance.add.assert_not_called()
+ mock_apprise_instance.notify.assert_not_called()
+
+ @patch(
+ "local_deep_research.notifications.service"
+ ".NotificationURLValidator.validate_service_url_with_hint"
+ )
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_fragment_that_would_pass_validation_is_still_refused(
+ self, mock_apprise_class, mock_validate
+ ):
+ """The refusal must NOT depend on the fragment failing
+ validation. A scheme-carrying fragment can be a perfectly valid
+ URL on its own — that is exactly what makes it a usable decoy.
+
+ The validator is stubbed to accept EVERYTHING here, so the only
+ thing that can refuse this input is the fragment check itself.
+
+ Teeth: restore ``url_entries = [invalid_fragment]``; with the
+ validator accepting every entry the flow reaches
+ ``temp_apprise.add`` and returns success, failing every assertion
+ below. (This also pins the weaker fix of merely making the
+ validation loop reject fragments: with validation stubbed open,
+ that fix would not refuse this input either.)
+ """
+ mock_validate.return_value = (True, None, False)
+ mock_apprise_instance = MagicMock()
+ mock_apprise_instance.add.return_value = True
+ mock_apprise_instance.notify.return_value = True
+ mock_apprise_instance.__len__.return_value = 1
+ mock_apprise_class.return_value = mock_apprise_instance
+
+ service = NotificationService(outbound_allowed=True)
+
+ result = service.test_service(
+ "bark://internal.invalid/key\\https://public.example/hook"
+ )
+
+ assert result["success"] is False
+ assert "could not be parsed unambiguously" in result["error"]
+ mock_validate.assert_not_called()
+ mock_apprise_instance.add.assert_not_called()
+ mock_apprise_instance.notify.assert_not_called()
+
+
class TestSendMultiUrlSsrf:
"""The configured-dispatch path (``send()``) must also validate every
entry Apprise parses out of a multi-URL string, so a comma/space
diff --git a/tests/security/test_egress_notifications_callsite.py b/tests/security/test_egress_notifications_callsite.py
index b6c83aa7da..881079b58f 100644
--- a/tests/security/test_egress_notifications_callsite.py
+++ b/tests/security/test_egress_notifications_callsite.py
@@ -225,7 +225,12 @@ def test_outbound_master_switch_blocks_even_policy_allowed_url():
# ---------------------------------------------------------------------------
-# H. test_service (the /api/notifications/test-url PEP) honors the policy.
+# H. NotificationManager.test_service honors the policy.
+#
+# NOTE: nothing in src/ currently calls NotificationManager.test_service —
+# the live POST /api/notifications/test-url route constructs a
+# NotificationService directly and is NOT gated by this precheck. These
+# tests cover the manager method's own contract, not that live route.
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.py
index eff927e9ff..5401a7d0aa 100644
--- a/tests/security/test_notification_validator.py
+++ b/tests/security/test_notification_validator.py
@@ -8,6 +8,7 @@ import pytest
from local_deep_research.security.notification_validator import (
NotificationURLValidationError,
NotificationURLValidator,
+ parse_notification_url_list,
)
@@ -1046,6 +1047,135 @@ class TestValidateMultipleUrls:
assert "example.com" not in error
assert "typo.example.com" not in error
+ @pytest.mark.parametrize(
+ ("urls", "expected_fragment"),
+ [
+ ("discord://x garbage", "garbage"),
+ ("discord://x ???", "???"),
+ ("discord://x\tgarbage", "garbage"),
+ ("discord://x\x00garbage", "garbage"),
+ ],
+ )
+ def test_unencoded_whitespace_fragment_fails_closed(
+ self, urls, expected_fragment
+ ):
+ """An entry containing characters that are illegal unencoded in a
+ URI (whitespace, control bytes) is not one URL: the token after
+ the first illegal character must surface as ``invalid_fragment``
+ however it is shaped — a bare word like ``garbage`` is exactly as
+ undeliverable as the dotted ``example.com/hook`` shape pinned
+ above. Weakening the parser back to dotted-name-only fragment
+ detection returns ``None`` for these inputs and the manager
+ mislabels the resulting drop as an egress refusal instead of
+ ``invalid_url``."""
+ parsed_urls, invalid_fragment = parse_notification_url_list(urls)
+
+ assert invalid_fragment == expected_fragment
+ assert parsed_urls == [urls]
+
+ @pytest.mark.parametrize(
+ ("label", "whitespace"),
+ [
+ ("NBSP U+00A0", "\u00a0"),
+ ("IDEOGRAPHIC SPACE U+3000", "\u3000"),
+ ("LINE SEPARATOR U+2028", "\u2028"),
+ ("THIN SPACE U+2009", "\u2009"),
+ ("VERTICAL TAB", "\x0b"),
+ ("FORM FEED", "\x0c"),
+ ],
+ )
+ def test_surrounding_unicode_whitespace_is_trimmed_not_refused(
+ self, label, whitespace
+ ):
+ """A URL pasted with invisible whitespace around it is still a
+ valid single URL, not a malformed entry.
+
+ ``RFC_FORBIDDEN_URL_CHARS_RE``'s ``\\s`` is Unicode-aware, but
+ ``str.strip(" ,\\t\\r\\n")`` is ASCII-only. Trimming with the
+ narrow set and then applying the wide check made an entry ending
+ in U+00A0 / U+3000 / \\x0b / \\x0c (a webhook URL copied out of a
+ rendered docs page, say) come back as an ``invalid_fragment`` —
+ so the whole ``notifications.service_url`` failed closed as
+ ``invalid_url``, with a message telling the operator to "remove
+ any spaces, backslashes or control characters" that describes
+ nothing they can see. Every other consumer trims with bare
+ ``str.strip()`` before its own RFC check
+ (``validate_service_url``, ``_partition_urls``), so these values
+ were, and must stay, deliverable.
+
+ Teeth: revert the trim to ``entry.strip(" ,\\t\\r\\n")`` and every
+ TRAILING case here returns a fragment instead of ``None``. The
+ LEADING-only candidate is a CONTROL, not a tooth: ``\\s`` in
+ ``_URL_BOUNDARY_RE`` is Unicode-aware too, so leading whitespace is
+ consumed as an entry boundary and never reaches the RFC check on
+ the entry. It is kept to pin that the boundary split and the trim
+ agree on the same whitespace class.
+ """
+ base = "discord://123456789012345678/abcdefghijklmnop"
+
+ for candidate in (
+ base + whitespace,
+ # Control: handled by the boundary split — see the docstring.
+ whitespace + base,
+ whitespace + base + whitespace,
+ base + " " + whitespace,
+ base + whitespace + ",",
+ ):
+ parsed_urls, invalid_fragment = parse_notification_url_list(
+ candidate
+ )
+ assert invalid_fragment is None, (label, repr(candidate))
+ assert parsed_urls == [base], (label, repr(candidate))
+
+ def test_unicode_whitespace_trim_applies_to_every_entry(self):
+ """The trim runs per entry, so a trailing NBSP on the LAST URL of
+ a multi-URL setting does not condemn the whole list either."""
+ parsed_urls, invalid_fragment = parse_notification_url_list(
+ "discord://111111111111111111/aaaaaaaaaaaaaaaa\u00a0"
+ ", json://hook.example/x\u3000"
+ )
+
+ assert invalid_fragment is None
+ assert parsed_urls == [
+ "discord://111111111111111111/aaaaaaaaaaaaaaaa",
+ "json://hook.example/x",
+ ]
+
+ @pytest.mark.parametrize(
+ ("urls", "expected_fragment"),
+ [
+ # Positive controls for the trim above: it is anchored to the
+ # ENDS of an entry, so nothing with a smuggled token after an
+ # illegal character may be loosened by it.
+ ("discord://x garbage", "garbage"),
+ ("discord://x\u00a0garbage", "garbage"),
+ ("discord://x\u3000garbage", "garbage"),
+ ("discord://x example.com/hook", "example.com/hook"),
+ (
+ "json://ok.example/x, slack://tokenA/tokenB/tokenC\\",
+ "slack://tokenA/tokenB/tokenC\\",
+ ),
+ (
+ "json://metadata.example/x\\https://vendor.example/ok",
+ "https://vendor.example/ok",
+ ),
+ ],
+ )
+ def test_edge_trim_does_not_loosen_smuggled_tokens(
+ self, urls, expected_fragment
+ ):
+ """The Unicode-whitespace trim must not weaken the fail-closed
+ parse. An illegal character with a token after it, and an illegal
+ character that is not whitespace at all (backslash), still yield a
+ fragment.
+
+ Teeth: widen the trim from the entry's ends to a global
+ substitution and the first four cases stop fragmenting, silently
+ dispatching the smuggled destination."""
+ parsed_urls, invalid_fragment = parse_notification_url_list(urls)
+
+ assert invalid_fragment == expected_fragment
+
def test_one_invalid_url_fails_all(self):
"""Should fail if any URL is invalid."""
urls = "https://example.com/webhook,file:///etc/passwd"
@@ -1060,6 +1190,17 @@ class TestValidateMultipleUrls:
assert is_valid is True
assert error is None
+ def test_unicode_whitespace_around_urls_stripped(self):
+ """The user-visible half of the trim: a setting whose entries carry
+ invisible surrounding whitespace still validates, so the send path
+ does not report ``invalid_url`` for a URL the operator cannot see
+ anything wrong with. ``discord://`` is a token scheme, so this
+ exercises no DNS."""
+ urls = "\u00a0discord://id/token\u00a0,\u3000discord://id2/token2\u3000"
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(urls)
+ assert is_valid is True
+ assert error is None
+
def test_custom_separator(self):
"""Should support custom separator."""
urls = "https://example.com/webhook|discord://id/token"
@@ -1086,6 +1227,84 @@ class TestValidateMultipleUrls:
assert error is None
+class TestValidateMultipleUrlsFragmentMessage:
+ r"""``validate_multiple_urls`` refuses ANY non-``None``
+ ``invalid_fragment``, and says something true while doing it.
+
+ The refusal is about the INPUT not partitioning unambiguously, not
+ about the fragment being a bad URL — and a fragment can be a
+ perfectly good URL on its own: when the illegal character only trails
+ the entry the fragment IS the entry, and when it separates two
+ entries the trailing token can be a well-formed vendor URL. So
+ interpolating ``validate_service_url``'s error unconditionally can
+ interpolate ``None``.
+ """
+
+ @patch(
+ "local_deep_research.security.notification_validator"
+ ".NotificationURLValidator.validate_service_url",
+ return_value=(True, None),
+ )
+ def test_valid_fragment_still_refused_with_a_real_message(
+ self, mock_validate
+ ):
+ r"""Teeth: drop the ``if not error_message:`` fallback in
+ ``validate_multiple_urls`` and the user-facing message becomes
+ the nonsense ``"Invalid notification service URL: None"`` — the
+ ``"None"`` assertion below fails.
+
+ ``validate_service_url`` is stubbed to accept everything (no DNS,
+ and it pins the branch that only exists when the fragment passes
+ on its own).
+ """
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ "https://example.com/a\\https://example.org/b"
+ )
+
+ assert is_valid is False
+ assert "None" not in error
+ assert "could not be parsed unambiguously" in error
+ # The fragment's own text is never echoed back — it is
+ # attacker-shaped and may carry real credentials.
+ assert "example.org" not in error
+
+ @patch(
+ "local_deep_research.security.notification_validator"
+ ".NotificationURLValidator.validate_service_url",
+ return_value=(True, None),
+ )
+ def test_trailing_forbidden_byte_refused_without_echoing_the_entry(
+ self, mock_validate
+ ):
+ r"""Companion to the above on the ``else entry`` branch, where the
+ illegal character only TRAILS the entry so the fragment IS the
+ whole credential-bearing service URL.
+
+ ``validate_service_url`` is stubbed to accept everything for the
+ same reason as the test above: with the real validator this input
+ takes the OTHER branch (the RFC check returns a non-empty message,
+ so the ``if not error_message:`` fallback never runs) and the
+ assertions below would hold no matter what the fallback said. The
+ stub forces the fallback, which is the branch that has to invent
+ its own text and is therefore the one that could echo the entry.
+
+ Teeth: interpolate ``invalid_fragment`` into that fallback message
+ and ``"tokenA"``/``"slack://"`` appear in the user-facing error —
+ an Apprise bot token in a validation message. Drop the fallback
+ entirely and the message becomes ``"... : None"``.
+ """
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ "slack://tokenA/tokenB/tokenC/\\"
+ )
+
+ assert is_valid is False
+ assert error
+ assert "None" not in error
+ assert "could not be parsed unambiguously" in error
+ assert "tokenA" not in error
+ assert "slack://" not in error
+
+
class TestClassConstants:
"""Tests for class constants."""
diff --git a/tests/web/routers/test_settings_news_hostile_input.py b/tests/web/routers/test_settings_news_hostile_input.py
index 6206deb47e..05ad1a8a4d 100644
--- a/tests/web/routers/test_settings_news_hostile_input.py
+++ b/tests/web/routers/test_settings_news_hostile_input.py
@@ -309,10 +309,12 @@ def test_test_url_empty_string_service_url_value_rejected_cleanly(
def test_test_url_non_url_string_rejected_cleanly(
authenticated_client, outbound_enabled
):
- """No whitespace in this string on purpose: a space would instead hit
- the earlier RFC-illegal-character check (GHSA-g23j-2vwm-5c25 hardening)
- with a different message. This string is specifically schemeless, to
- exercise the "must have a protocol" branch."""
+ """A schemeless string never reaches the per-URL validator: the
+ scheme-boundary parse yields no entries and the whole input as a
+ scheme-less fragment, so ``NotificationService.test_service`` refuses
+ the input as a whole. That refusal must be a clean ``success: False``
+ (not a 500) and its message must tell the operator that every entry
+ needs a protocol such as ``discord://``."""
resp = authenticated_client.post(
TEST_URL_ROUTE, json={"service_url": "not-a-url-at-all"}
)