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(security): harden notification IPv6 fragment parsing (#5630)

LearningCircuita68aac20f824
diff --git a/changelog.d/+notification-ipv6-fragment-fail-closed.security.md b/changelog.d/+notification-ipv6-fragment-fail-closed.security.md
new file mode 100644
index 0000000000..b28f31f2f4
--- /dev/null
+++ b/changelog.d/+notification-ipv6-fragment-fail-closed.security.md
@@ -0,0 +1,32 @@
+Notification URL parsing now recognizes scheme-less IPv6 literal fragments and
+refuses the entire configuration instead of dispatching only the valid subset.
+
+IPv6 candidates are confirmed with the standard-library address parser, so
+colon-rich credentials and timestamps remain valid URL data. A MAC-48 address
+(``aa:bb:cc:dd:ee:ff``) is likewise kept as data, while an eight-group token
+such as an EUI-64 is refused: it is a syntactically valid IPv6 literal, and the
+ambiguity is resolved fail-closed.
+
+The guard now reaches one verdict across the alternate spellings of a host
+rather than only the lowercase bare one: ``localhost`` matches
+case-insensitively, a scheme-relative ``//host`` prefix is recognized on the
+hostname and IPv4 alternatives as it already was on the IPv6 one, a trailing
+root dot is stripped the way ``_normalize_host`` strips it -- in its ``%2e``
+spelling too, and off a bracketed literal carrying a port, so ``[::1].:8080/x``
+is refused the way ``[::1]:8080/x`` is -- a ``userinfo@`` prefix no longer
+hides a loopback or IPv6 authority, percent-encoded IPv6 brackets
+(``%5b``/``%5d``) are decoded, and the historical inet_aton spellings
+(``0177.0.0.1``, ``127.1``, ``//2130706433``) are routed through the same
+``legacy_ipv4`` grammar whole URLs already use, their percent-encoded forms
+included.
+
+A whole URL carries a scheme, so its host position is unambiguous; a
+comma-separated fragment's is not. The one-component inet_aton form accepts
+every integer below 2**32, which is also the shape of the Telegram chat ids,
+phone numbers and timestamps an Apprise comma-separated target list leaves in
+front of a ``/`` or a ``?``. A one-component numeric token is therefore only
+read as a host when the fragment carries an authority marker of its own: a
+second dot-separated component (a trailing root dot, ``.`` or ``%2e``, does
+not count), a ``//`` prefix, or a ``userinfo@`` prefix.
+Outside that one-component case the alias handling only adds refusals; no
+fragment that previously failed closed is readmitted.
diff --git a/changelog.d/+notification-separator-egress-alignment.security.md b/changelog.d/+notification-separator-egress-alignment.security.md
new file mode 100644
index 0000000000..d69117bdbd
--- /dev/null
+++ b/changelog.d/+notification-separator-egress-alignment.security.md
@@ -0,0 +1,12 @@
+Notification validation, egress filtering, and dispatch now share one URL
+partition, so an embedded comma in an Apprise URL survives the round trip
+instead of splitting the URL. The custom `separator` parameter is now plumbed
+consistently through that shared path; no production call site passes a
+non-default separator today, so this is groundwork rather than a behaviour fix.
+That shared parser also no longer relies on consuming/trimming regexes that
+backtracked quadratically over long runs of separators or whitespace in
+`notifications.service_url` — a crafted value could stall a send for minutes
+(about 234s at the test input, versus 19ms with the fixed parser). The
+custom-separator path now enforces the scheme check it previously skipped, so a
+custom-separated entry must carry a top-level scheme and pass normal URL
+security validation before dispatch, matching the default comma separator.
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index 05086489b9..534fcf9e7f 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -383,6 +383,13 @@ class NotificationManager:
# PRIVATE_ONLY refuses non-HTTP Apprise schemes because their
# effective destinations cannot be classified reliably; other
# scopes pass plugin schemes to the service's URL validator.
+ # No separator is passed here, so this parses/rejoins with the
+ # default ",". If a non-default separator is ever exposed to
+ # callers, it must be passed here too and to service.send_event
+ # below — otherwise the two calls disagree on where one URL
+ # ends and the next begins, and the joined output the service
+ # re-parses merges two entries into one (losing a destination,
+ # not gaining one).
allowed_urls = self._filter_urls_by_egress_policy(service_urls)
if not allowed_urls:
# Distinguish "the policy was evaluated and refused every
@@ -405,7 +412,10 @@ class NotificationManager:
detail=detail,
)
- # Send notification with the allowed subset.
+ # Send notification with the allowed subset. No separator is
+ # passed here either, so this must keep agreeing with the
+ # default "," used above to build allowed_urls — see the
+ # comment on the _filter_urls_by_egress_policy call.
logger.debug(f"Calling service.send_event for {event_type.value}")
sent = self.service.send_event(
event_type, context, service_urls=allowed_urls
@@ -629,23 +639,28 @@ class NotificationManager:
}
return self.service.test_service(allowed)
- def _filter_urls_by_egress_policy(self, service_urls: str) -> Optional[str]:
+ def _filter_urls_by_egress_policy(
+ self, service_urls: str, separator: str = ","
+ ) -> Optional[str]:
"""Filter an Apprise URL string by the user's egress policy.
- Commas inside one service URL are preserved; commas or whitespace
- followed by another scheme delimit URLs. Returns the joined string
- of allowed URLs (may be empty — every URL was refused), or ``None``
- when the policy itself could not be evaluated and we failed closed.
- Both are falsy; callers that care why nothing was allowed check for
- ``None``. When no snapshot / context is available, returns the
- input unchanged for backwards compatibility.
+ Default comma input preserves commas inside one service URL and is
+ canonicalized to whitespace-separated output. Custom-separated input
+ retains its caller-provided separator for the service to consume.
+ Returns the joined allowed URLs (possibly empty if every URL was
+ refused), or ``None`` when the policy could not be evaluated and we
+ failed closed. Both are falsy; callers that care why nothing was
+ allowed check for ``None``. When no snapshot / context is available,
+ return the input unchanged for backwards compatibility.
"""
+ if not isinstance(separator, str) or not separator:
+ raise ValueError("separator must be a non-empty string")
snapshot = getattr(self, "_settings_snapshot", None)
if not snapshot:
return service_urls
url_entries, invalid_fragment = parse_notification_url_list(
- service_urls
+ service_urls, separator
)
if invalid_fragment is not None:
# As in ``send_notification``: never log anything derived
@@ -743,7 +758,15 @@ class NotificationManager:
scope=ctx.scope.value,
reason=decision.reason,
)
- return " ".join(parts)
+ # Rejoin with the caller's separator so the filtered output stays
+ # parseable by the same rule it was parsed with. If a non-default
+ # separator is ever exposed to callers, it must be threaded through
+ # every call site that reaches this method (see send_notification's
+ # _filter_urls_by_egress_policy call and its service.send_event call
+ # above) — a desync here does not add a destination, it MERGES two
+ # entries into one unparseable one and silently loses a destination.
+ joiner = " " if separator == "," else separator
+ return joiner.join(parts)
def _should_notify(self, event_type: EventType) -> bool:
"""
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 6c5a52b683..ed55aabc84 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -201,20 +201,23 @@ class NotificationService:
self._disable_redirects(apprise_instance)
@staticmethod
- def _partition_urls(service_urls: str) -> Tuple[List[str], List[str]]:
+ def _partition_urls(
+ service_urls: str, separator: str = ","
+ ) -> Tuple[List[str], List[str]]:
"""Split an Apprise URL string into (http(s), everything-else).
- Partitioning uses the notification validator's scheme-boundary
- split (``parse_notification_url_list``): a comma/whitespace
- sequence only separates entries when a URL scheme follows it, so
- commas INSIDE one Apprise URL (e.g. a multi-target Telegram
- ``?to=id1,id2``) are preserved and dispatched as a single entry —
- the same partition the validator applies before the send. The two
- groups get different send-time SSRF policies (see
- :meth:`_dispatch`), mirroring the notification validator's
- per-scheme rules: ``http``/``https`` block private IPs
- unless the operator opted in, while plugin / raw-webhook schemes
- allow private (self-hosted LAN) but always block cloud-metadata.
+ Uses the same separator-aware parser as validation and egress filtering
+ (``parse_notification_url_list``). The default comma parser recognizes
+ scheme-aware boundaries — a comma/whitespace sequence only separates
+ entries when a URL scheme follows it, so commas INSIDE one Apprise URL
+ (e.g. a multi-target Telegram ``?to=id1,id2``) are preserved and
+ dispatched as a single entry; an explicit custom separator preserves
+ commas and whitespace inside each URL outright. The two groups get
+ different send-time SSRF policies (see :meth:`_dispatch`), mirroring
+ the notification validator's per-scheme rules: ``http``/``https``
+ block private IPs 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 only
PARTLY deliverable. Apprise has no generic http(s) notifier, so an
@@ -232,7 +235,7 @@ class NotificationService:
strict: List[str] = []
lenient: List[str] = []
entries, invalid_fragment = parse_notification_url_list(
- service_urls, ","
+ service_urls, separator
)
if invalid_fragment is not None:
# The only correct response to a non-``None`` fragment is to
@@ -241,11 +244,11 @@ class NotificationService:
# 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 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.
+ # separator-aware parse) before reaching here, so a malformed
+ # fragment is already rejected there; this branch only fires
+ # for direct callers of this helper. Fail closed rather than
+ # dispatching only the valid subset — the caller must validate
+ # the list themselves before dispatching it.
logger.warning(
"Notification service_url list contains a malformed "
"fragment; refusing the whole list",
@@ -254,9 +257,6 @@ class NotificationService:
)
return [], []
for entry in entries:
- entry = entry.strip()
- if not entry:
- continue
scheme = entry.split(":", 1)[0].lower() if ":" in entry else ""
if scheme in ("http", "https"):
strict.append(entry)
@@ -438,16 +438,18 @@ class NotificationService:
service_urls: Optional[str] = None,
tag: Optional[str] = None,
attach: Optional[List[str]] = None,
+ separator: str = ",",
) -> bool:
"""
- Send a notification to service URLs with automatic retry.
+ Send a notification to separator-delimited service URLs with retry.
Args:
title: Notification title
body: Notification body text
- service_urls: Comma-separated list of service URLs to override configured ones
+ service_urls: Service URLs delimited by ``separator``
tag: Optional tag to target specific services
attach: Optional list of file paths to attach
+ separator: Delimiter between service URLs
Returns:
True if notification was sent successfully to at least one service
@@ -491,7 +493,9 @@ class NotificationService:
# Validate service URLs for security (SSRF prevention)
is_valid, error_msg = (
NotificationURLValidator.validate_multiple_urls(
- service_urls, allow_private_ips=self.allow_private_ips
+ service_urls,
+ allow_private_ips=self.allow_private_ips,
+ separator=separator,
)
)
@@ -503,7 +507,9 @@ class NotificationService:
# If service_urls are provided, partition them by scheme and
# dispatch each group with its own SSRF send-time guard.
if service_urls:
- strict_urls, lenient_urls = self._partition_urls(service_urls)
+ strict_urls, lenient_urls = self._partition_urls(
+ service_urls, separator
+ )
if not strict_urls and not lenient_urls:
logger.error("No service URLs after parsing")
return False
@@ -701,6 +707,7 @@ class NotificationService:
service_urls: Optional[str] = None,
tag: Optional[str] = None,
custom_template: Optional[Dict[str, str]] = None,
+ separator: str = ",",
) -> bool:
"""
Send a notification for a specific event type.
@@ -708,9 +715,10 @@ class NotificationService:
Args:
event_type: Type of event
context: Context data for template formatting
- service_urls: Comma-separated list of service URLs
+ service_urls: Service URLs delimited by ``separator``
tag: Optional tag to target specific services
custom_template: Optional custom template override
+ separator: Delimiter between service URLs
Returns:
True if notification was sent successfully
@@ -732,6 +740,7 @@ class NotificationService:
body=message["body"],
service_urls=service_urls,
tag=tag,
+ separator=separator,
)
def test_service(self, url: str) -> Dict[str, Any]:
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index 4303573a1e..c5c30bea51 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -29,37 +29,263 @@ from .ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE, redact_url_for_log
# ipaddress._BaseAddress API).
ResolvedIP = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
+# ``localhost`` carries an inline case-insensitive group rather than a
+# pattern-wide re.IGNORECASE: hostnames are case-insensitive, but the other two
+# alternatives are already case-agnostic (``\d`` and explicit ``A-Za-z``
+# classes), and a blanket flag would additionally fold Unicode look-alikes
+# (U+017F, U+212A) into those ``A-Za-z`` classes. Scoping the flag keeps the
+# widening to the one alternative that needed it.
+# ``(?://)?`` mirrors the IPv6 arm below: a scheme-relative fragment names the
+# same host as its bare spelling, so ``//localhost/x`` has to fail closed
+# exactly like ``localhost/x``.
_SCHEMELESS_URL_FRAGMENT_RE = re.compile(
- r"^(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|"
+ r"^(?://)?(?:(?i:localhost)|(?:\d{1,3}\.){3}\d{1,3}|"
r"(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,})"
r"(?::\d+)?(?:[/?#]|$)"
)
+# A userinfo prefix hides the host from the anchored pattern above, so
+# ``[email protected]/x`` would otherwise read as opaque data. Two deliberate
+# narrowings keep this from swallowing ordinary URL data:
+# * only the loopback-name and IPv4-literal alternatives are carried over.
+# This alternation, not the trailer below, is what keeps
+# ``[email protected]`` in a ``?to=`` list an e-mail address:
+# ``more:secret:[email protected]/webhook`` is credentials in front of an
+# ordinary domain — exactly the shape an Apprise service URL uses — and a
+# public domain is not a blocked shortcut in the first place.
+# * a ``[/?#]`` trailer is required rather than also accepting
+# end-of-string. That is what keeps a bare ``admin@localhost`` or
+# ``[email protected]`` — a recipient whose domain part happens to be
+# spelled like a loopback host — an address rather than an authority.
+_USERINFO_URL_FRAGMENT_RE = re.compile(
+ r"^(?://)?[^/?#@\s]*@(?:(?i:localhost)|(?:\d{1,3}\.){3}\d{1,3})"
+ r"(?::\d+)?[/?#]"
+)
+# Legacy inet_aton spellings (decimal, hexadecimal, octal, shortened) name the
+# same host as their dotted-quad form; ``legacy_ipv4`` already owns that
+# grammar for whole URLs. The ``[/?#]`` trailer is NOT the safeguard here —
+# it is the common case. Apprise's comma-separated target lists put a ``/``
+# or a ``?`` directly after the last id (``tgram://…/111111111,222222222?
+# format=markdown``, ``twilio://…/2125551234,4085551234?batch=yes``), and the
+# one-component inet_aton form accepts every decimal below 2**32, so a bare
+# id would read as a host. ``_names_legacy_numeric_host`` therefore demands
+# an authority marker as well: two or more dot-separated components, a
+# ``//`` prefix, or a ``userinfo@`` prefix. ``%`` is in the host class so the
+# percent-encoded spellings reach the same decision.
+_NUMERIC_HOST_FRAGMENT_RE = re.compile(
+ r"^(?P<prefix>(?://)?(?:[^/?#@\s]*@)?)"
+ r"(?P<host>[0-9A-Fa-fXx.%]+)(?::\d+)?[/?#]"
+)
+# Keep candidate detection deliberately broad. IPv6Address below is the sole
+# authority for validity, including dotted-quad and scoped IPv6 forms.
+_IPV6_FRAGMENT_CANDIDATE_RE = re.compile(
+ r"^(?://)?(?:\[(?P<bracketed>[^\s,\]/?#]+)\]"
+ r"(?::[^\s,/?#]*)?|"
+ r"(?P<bare>(?=[^\s,/?#]*:[^\s,/?#]*:)[^\s,/?#]+))"
+ r"(?:[/?#]|$)"
+)
+_PERCENT_ENCODED_BRACKETS = {"%5b": "[", "%5d": "]"}
+_PERCENT_ENCODED_BRACKET_RE = re.compile(
+ "|".join(_PERCENT_ENCODED_BRACKETS), re.IGNORECASE
+)
+# ``%2e`` spells the label separator, so it decides both where a host's
+# trailing root dot ends and how many components the host has.
+_PERCENT_ENCODED_DOTS = ("%2e", "%2E")
+# One scan finds the end of a fragment's authority for every helper below.
+_AUTHORITY_END_RE = re.compile(r"[/?#]")
_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)
-
-
+# Keep this boundary zero-width to avoid quadratic backtracking on
+# separator runs.
+_URL_BOUNDARY_RE = re.compile(r"(?<=[,\s])(?=[A-Za-z][A-Za-z0-9+.-]{0,31}://)")
_APPRISE_TELEGRAM_URL_RE = re.compile(
r"^tgram://(?:bot)?[0-9]+(?::|%3A)[a-z0-9_-]+(?:/|\?|$)",
re.IGNORECASE,
)
+def _strip_notification_url_delimiters(entry: str) -> str:
+ start = 0
+ end = len(entry)
+ while start < end and (entry[start] == "," or entry[start].isspace()):
+ start += 1
+ while end > start and (entry[end - 1] == "," or entry[end - 1].isspace()):
+ end -= 1
+ return entry[start:end]
+
+
+def _is_ipv6_literal(host: str) -> bool:
+ try:
+ ipaddress.IPv6Address(host)
+ except ipaddress.AddressValueError:
+ return False
+ return True
+
+
+def _decode_bracket_escapes(fragment: str) -> str:
+ """Decode ``%5b``/``%5d`` so an encoded IPv6 literal stays recognizable."""
+ return _PERCENT_ENCODED_BRACKET_RE.sub(
+ lambda match: _PERCENT_ENCODED_BRACKETS[match.group(0).lower()],
+ fragment,
+ )
+
+
+def _has_label_separator(host: str) -> bool:
+ """Return whether a host carries a dot in either spelling."""
+ return "." in host or any(dot in host for dot in _PERCENT_ENCODED_DOTS)
+
+
+def _strip_trailing_host_dots(host: str) -> str:
+ r"""Drop a host's trailing root dots, ``%2e`` included.
+
+ A fragment's authority is attacker-supplied and unbounded, so the
+ literal dots come off with one C-level ``rstrip`` and the encoded ones
+ walk back by index. Repeated slicing and a ``(?:\.|%2e)+$`` regex are
+ both quadratic on a long run of dots.
+ """
+ stripped = host.rstrip(".")
+ if not stripped.endswith(_PERCENT_ENCODED_DOTS):
+ return stripped
+ end = len(stripped)
+ while True:
+ if end >= 3 and stripped[end - 3 : end].lower() == "%2e":
+ end -= 3
+ elif end > 0 and stripped[end - 1] == ".":
+ end -= 1
+ else:
+ return stripped[:end]
+
+
+def _authority_end(rest: str) -> int:
+ """Return the offset of a fragment's first ``/``, ``?`` or ``#``."""
+ boundary = _AUTHORITY_END_RE.search(rest)
+ return len(rest) if boundary is None else boundary.start()
+
+
+def _strip_fragment_host_dots(fragment: str) -> str:
+ """Drop a host's trailing dots the way ``_normalize_host`` does.
+
+ ``localhost.`` and ``localhost`` are one host to every resolver, so the
+ fully-qualified spelling must not read as opaque data here when the bare
+ one fails closed. ``%2e`` spells the same dot, so ``localhost%2e``
+ normalizes onto the same host as ``localhost.`` does.
+ """
+ prefix, rest = "", fragment
+ if rest.startswith("//"):
+ prefix, rest = "//", rest[2:]
+ boundary = _authority_end(rest)
+ host, tail = rest[:boundary], rest[boundary:]
+ port = ""
+ colon = host.rfind(":")
+ # Split a port off a colon-free host, or off a bracketed one: a BARE
+ # IPv6 literal's own colons are part of the address rather than a port
+ # delimiter, but a bracketed literal has already closed, so ``[::1].:80``
+ # has to split the way ``[::1]:80`` does.
+ if (
+ colon > 0
+ and (":" not in host[:colon] or "]" in host[:colon])
+ and host[colon + 1 :].isdigit()
+ ):
+ host, port = host[:colon], host[colon:]
+ stripped = _strip_trailing_host_dots(host)
+ if stripped == host:
+ return fragment
+ return prefix + stripped + port + tail
+
+
+def _strip_fragment_userinfo(fragment: str) -> str:
+ """Drop a ``userinfo@`` prefix from a fragment's authority component."""
+ prefix, rest = "", fragment
+ if rest.startswith("//"):
+ prefix, rest = "//", rest[2:]
+ authority_end = _authority_end(rest)
+ # The LAST ``@`` inside the authority delimits userinfo; any ``@`` in the
+ # path or query belongs to the data, not to the host.
+ at_sign = rest.rfind("@", 0, authority_end)
+ return fragment if at_sign < 0 else prefix + rest[at_sign + 1 :]
+
+
+def _is_ipv6_url_fragment(fragment: str) -> bool:
+ candidate = _IPV6_FRAGMENT_CANDIDATE_RE.match(fragment)
+ if candidate is None:
+ return False
+
+ bracketed = candidate.group("bracketed")
+ host = bracketed or candidate.group("bare")
+ if _is_ipv6_literal(host):
+ return True
+ if bracketed is not None:
+ return False
+ # The bare alternative has no port group, so its greedy run swallows a
+ # trailing ``:<port>``. Without this retry ``::1:99999`` -- a valid host
+ # with an out-of-range port -- fails ``IPv6Address`` as one literal and is
+ # silently accepted as URL data, while the bracketed ``[::1]:99999`` is
+ # refused. Retry once with the final colon-segment removed so both forms
+ # fail closed on the same input.
+ head, sep, _tail = host.rpartition(":")
+ return bool(sep) and _is_ipv6_literal(head)
+
+
+def _names_legacy_numeric_host(prefix: str, host: str) -> bool:
+ """Return whether a fragment's leading token is an inet_aton authority.
+
+ A one-component inet_aton host is any integer below 2**32, which is also
+ the shape of every Telegram chat id, Twilio number and Unix timestamp
+ that an Apprise comma-separated target list leaves in front of a ``/``
+ or ``?``. Such a token only names a host once the fragment carries an
+ authority marker of its own: a second dot-separated component (a
+ trailing root dot does not count), a ``//`` prefix, or a ``userinfo@``
+ prefix.
+ """
+ # A trailing root dot (``.`` or ``%2e``) is not a second component:
+ # ``222222222%2e`` is still a one-component numeric token.
+ bare_host = re.sub(r"(?:\.|%2[eE])+$", "", host)
+ if not prefix and not _has_label_separator(bare_host):
+ return False
+ return is_ambiguous_numeric_ipv4_host(
+ host
+ ) or is_percent_encoded_numeric_ipv4_host(host)
+
+
+def _matches_scheme_less_url_shape(fragment: str) -> bool:
+ if _SCHEMELESS_URL_FRAGMENT_RE.match(fragment):
+ return True
+ if _USERINFO_URL_FRAGMENT_RE.match(fragment):
+ return True
+
+ numeric = _NUMERIC_HOST_FRAGMENT_RE.match(fragment)
+ if numeric is not None and _names_legacy_numeric_host(
+ numeric.group("prefix"), numeric.group("host")
+ ):
+ return True
+
+ return _is_ipv6_url_fragment(fragment)
+
+
+def _is_scheme_less_url_fragment(fragment: str) -> bool:
+ """Recognize a comma-separated fragment that names a host without a scheme.
+
+ Every check is additive: an alternate spelling is only ever consulted
+ after the literal fragment has been cleared, so normalization can widen
+ the refusal set but can never readmit a fragment that already fails
+ closed.
+ """
+ if _matches_scheme_less_url_shape(fragment):
+ return True
+ # Spellings that normalize onto a host the checks above already refuse:
+ # percent-encoded brackets and a trailing root dot, encoded or literal.
+ normalized = _strip_fragment_host_dots(_decode_bracket_escapes(fragment))
+ if normalized != fragment and _matches_scheme_less_url_shape(normalized):
+ return True
+ # A userinfo prefix hides an IPv6 authority from the anchored patterns
+ # above. Only the IPv6 arm is retried on the stripped form: stripping
+ # userinfo from ``[email protected]`` would read an e-mail address as
+ # a hostname, which is why the hostname arm demands the ``[/?#]`` trailer
+ # that proves an authority instead.
+ without_userinfo = _strip_fragment_userinfo(normalized)
+ return without_userinfo != normalized and _is_ipv6_url_fragment(
+ without_userinfo
+ )
+
+
def parse_notification_url_list(
urls: str, separator: str = ","
) -> tuple[list[str], Optional[str]]:
@@ -88,8 +314,8 @@ def parse_notification_url_list(
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
+ backslash and the non-``\s`` control bytes, which the
+ scheme-boundary regex 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
@@ -104,22 +330,32 @@ def parse_notification_url_list(
The only correct response to a non-``None`` fragment is to refuse the
whole input.
+ Custom separators are explicit boundaries: commas and whitespace inside
+ each resulting URL remain data, subject to service URL validation. Every
+ parsed entry still requires a top-level URL scheme. The scheme-less
+ fragment check below is the one guard a custom separator does NOT get:
+ its entries take ``validate_service_url`` but are never scanned for
+ comma-separated scheme-less fragments, because with an explicit separator
+ a comma is ordinary data inside one URL.
+
Returns ``(parsed_urls, invalid_fragment)``. Custom separators retain the
- historical split behavior.
+ historical explicit-split behavior.
"""
if separator != ",":
- return (
- [entry.strip() for entry in urls.split(separator) if entry.strip()],
- None,
- )
-
- trimmed = (
- _trim_entry_edges(entry) for entry in _URL_BOUNDARY_RE.split(urls)
- )
- parsed_urls = [entry for entry in trimmed if entry]
+ parsed_urls = [
+ entry.strip() for entry in urls.split(separator) if entry.strip()
+ ]
+ else:
+ parsed_urls = []
+ for entry in _URL_BOUNDARY_RE.split(urls):
+ normalized_entry = _strip_notification_url_delimiters(entry)
+ if normalized_entry:
+ parsed_urls.append(normalized_entry)
for entry in parsed_urls:
if not _URL_SCHEME_RE.match(entry):
return parsed_urls, entry
+ if separator != ",":
+ continue
# 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
@@ -141,7 +377,7 @@ def parse_notification_url_list(
# 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):
+ if _is_scheme_less_url_fragment(fragment):
return parsed_urls, fragment
return parsed_urls, None
@@ -1167,10 +1403,10 @@ class NotificationURLValidator:
urls: str, allow_private_ips: bool = False, separator: str = ","
) -> Tuple[bool, Optional[str]]:
"""
- Validate multiple comma-separated service URLs.
+ Validate multiple separator-delimited service URLs.
Args:
- urls: Comma-separated service URLs
+ urls: Service URLs delimited by ``separator``
allow_private_ips: Whether to allow private IPs (default: False)
separator: URL separator (default: ",")
diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.py
index 66ac5dab1b..949901447c 100644
--- a/tests/notifications/test_manager.py
+++ b/tests/notifications/test_manager.py
@@ -1592,3 +1592,22 @@ class TestEgressPolicyURLFilter:
assert mgr._filter_urls_by_egress_policy("slack://t") == "slack://t"
malformed = "typo.example.com/x slack://t/x/y"
assert mgr._filter_urls_by_egress_policy(malformed) == malformed
+
+ def test_empty_separator_raises_instead_of_merging_entries(self):
+ """An empty (or non-string) ``separator`` must be refused before it
+ reaches the ``joiner.join(parts)`` rejoin.
+
+ ``joiner = " " if separator == "," else separator`` means a falsy
+ non-comma separator becomes ``""``, and ``"".join(parts)`` fuses two
+ allowed URLs into one unparseable string — silently losing a
+ destination rather than gaining one.
+
+ Teeth: remove the ``if not isinstance(separator, str) or not
+ separator: raise ValueError(...)`` guard at the top of
+ ``_filter_urls_by_egress_policy`` and this test fails because no
+ exception is raised.
+ """
+ mgr = NotificationManager.__new__(NotificationManager)
+ mgr._settings_snapshot = None
+ with pytest.raises(ValueError, match="non-empty string"):
+ mgr._filter_urls_by_egress_policy("slack://t discord://x", "")
diff --git a/tests/notifications/test_notification_ipv6_policy.py b/tests/notifications/test_notification_ipv6_policy.py
new file mode 100644
index 0000000000..808b3f090a
--- /dev/null
+++ b/tests/notifications/test_notification_ipv6_policy.py
@@ -0,0 +1,59 @@
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.notifications.exceptions import ServiceError
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.notifications.manager import NotificationManager
+
+
+def _unprotected_manager() -> NotificationManager:
+ return NotificationManager(
+ settings_snapshot={
+ "policy.egress_scope": {"value": "unprotected"},
+ "search.tool": {"value": "searxng"},
+ },
+ user_id="u",
+ )
+
+
+ "service_urls",
+ [
+ "slack://t/x/y,::1/x",
+ "discord://id/token, [::1]:8080/hook",
+ "slack://t/x/y,::ffff:192.0.2.128/hook",
+ "slack://t/x/y,[fe80::1%25eth0]:8080/hook",
+ "slack://t/x/y,fe80::1%eth0/hook",
+ "slack://t/x/y,::1:99999/hook",
+ "slack://t/x/y,[::1]/x",
+ "slack://t/x/y,[2001:db8::1]:8080/x",
+ "slack://t/x/y [::1]/x",
+ "slack://t/x/y [2001:db8::1]/x",
+ "slack://t/x/y,//[::1]/x",
+ "slack://t/x/y //[::1]/x",
+ "slack://t/x/y,[::1]:/x",
+ "slack://t/x/y [::1]:/x",
+ "slack://t/x/y,[::1]:name/x",
+ "slack://t/x/y [::1]:name/x",
+ ],
+)
+def test_manager_refuses_ipv6_fragment_configuration(
+ service_urls: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ manager = _unprotected_manager()
+ service = NotificationService(outbound_allowed=True)
+ dispatch = Mock()
+ monkeypatch.setattr(service, "_dispatch", dispatch)
+
+ # When
+ filtered = manager._filter_urls_by_egress_policy(service_urls)
+
+ # Then
+ assert filtered == ""
+ assert service._partition_urls(service_urls) == ([], [])
+ with pytest.raises(ServiceError):
+ service.send("title", "body", service_urls=service_urls)
+ dispatch.assert_not_called()
diff --git a/tests/notifications/test_notification_url_pipeline_custom_separator.py b/tests/notifications/test_notification_url_pipeline_custom_separator.py
new file mode 100644
index 0000000000..bb3f119df6
--- /dev/null
+++ b/tests/notifications/test_notification_url_pipeline_custom_separator.py
@@ -0,0 +1,243 @@
+"""Custom separator pipeline and ``send``/``send_event`` forwarding.
+
+Covers a non-default separator staying consistent across parsing, the
+manager, and dispatch: embedded-comma data preserved inside custom-separated
+entries, ``send``/``send_event`` threading the separator through to
+partitioning, scheme-less and IPv6-fragment refusal, and policy-evaluation
+failure. Default comma parsing and its performance regressions live in
+``test_notification_url_pipeline_default_parser``.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.notifications.manager import NotificationManager
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.notifications.templates import EventType
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ parse_notification_url_list,
+)
+
+
+def _unprotected_manager() -> NotificationManager:
+ return NotificationManager(
+ settings_snapshot={
+ "policy.egress_scope": {"value": "unprotected"},
+ "search.tool": {"value": "searxng"},
+ },
+ user_id="u",
+ )
+
+
+def test_custom_separator_is_shared_across_pipeline() -> None:
+ # Given
+ urls = "slack://token/path|discord://id/token"
+ expected = ["slack://token/path", "discord://id/token"]
+ manager = _unprotected_manager()
+
+ # When
+ parsed, invalid_fragment = parse_notification_url_list(urls, separator="|")
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ urls, separator="|"
+ )
+ filtered = manager._filter_urls_by_egress_policy(urls, separator="|")
+ strict, lenient = NotificationService._partition_urls(urls, separator="|")
+
+ # Then
+ assert invalid_fragment is None
+ assert parsed == expected
+ assert is_valid is True
+ assert error is None
+ assert filtered == "|".join(expected)
+ assert strict == []
+ assert lenient == expected
+
+
+def test_custom_separator_preserves_embedded_comma_data(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ monkeypatch.setattr(
+ NotificationURLValidator,
+ "_resolve_hostname_ips",
+ Mock(return_value=[]),
+ )
+ comma_bearing_url = (
+ "json://example.com/webhook?+X-Hosts=api.example.com,backup.example.com"
+ )
+ urls = f"{comma_bearing_url}|discord://id/token"
+ expected = [comma_bearing_url, "discord://id/token"]
+
+ # When
+ parsed, invalid_fragment = parse_notification_url_list(urls, separator="|")
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ urls, separator="|"
+ )
+ strict, lenient = NotificationService._partition_urls(urls, separator="|")
+
+ # Then
+ assert invalid_fragment is None
+ assert parsed == expected
+ assert is_valid is True
+ assert error is None
+ assert strict == []
+ assert lenient == expected
+
+
+def test_manager_output_reuses_custom_separator(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
+ urls = "slack://token/path|discord://id/token"
+ expected = ["slack://token/path", "discord://id/token"]
+ manager = _unprotected_manager()
+
+ # When
+ filtered = manager._filter_urls_by_egress_policy(urls, separator="|")
+ strict, lenient = NotificationService._partition_urls(
+ filtered, separator="|"
+ )
+
+ # Then
+ assert filtered == "|".join(expected)
+ assert strict == []
+ assert lenient == expected
+
+
+def test_send_threads_custom_separator_to_dispatch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ service_urls = "json://example.com/hook?field=a,b|discord://id/token"
+ lenient_urls = [
+ "json://example.com/hook?field=a,b",
+ "discord://id/token",
+ ]
+ service = NotificationService(outbound_allowed=True)
+ validate = Mock(return_value=(True, None))
+ partition = Mock(return_value=([], lenient_urls))
+ dispatch = Mock(return_value=True)
+ monkeypatch.setattr(
+ NotificationURLValidator, "validate_multiple_urls", validate
+ )
+ monkeypatch.setattr(service, "_partition_urls", partition)
+ monkeypatch.setattr(service, "_dispatch", dispatch)
+
+ # When
+ sent = service.send(
+ title="title",
+ body="body",
+ service_urls=service_urls,
+ separator="|",
+ )
+
+ # Then
+ assert sent is True
+ validate.assert_called_once_with(
+ service_urls,
+ allow_private_ips=False,
+ separator="|",
+ )
+ partition.assert_called_once_with(service_urls, "|")
+ dispatch.assert_called_once_with(
+ "title", "body", [], lenient_urls, None, None
+ )
+
+
+def test_send_event_threads_custom_separator_to_send(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ service_urls = "slack://token/path|discord://id/token"
+ context = {
+ "query": "query",
+ "research_id": "research-id",
+ "summary": "summary",
+ "url": "https://example.com/research/research-id",
+ }
+ service = NotificationService(outbound_allowed=True)
+ send = Mock(return_value=True)
+ monkeypatch.setattr(service, "send", send)
+
+ # When
+ sent = service.send_event(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context=context,
+ service_urls=service_urls,
+ separator="|",
+ )
+
+ # Then
+ assert sent is True
+ send.assert_called_once()
+ assert send.call_args.kwargs["service_urls"] == service_urls
+ assert send.call_args.kwargs["separator"] == "|"
+
+
+def test_custom_separator_ipv6_fragment_fails_closed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
+ urls = "discord://id/token|[2001:db8::1]:8080/webhook"
+ manager = _unprotected_manager()
+
+ # When
+ parsed, invalid_fragment = parse_notification_url_list(urls, separator="|")
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ urls, separator="|"
+ )
+ filtered = manager._filter_urls_by_egress_policy(urls, separator="|")
+ strict, lenient = NotificationService._partition_urls(urls, separator="|")
+
+ # Then
+ assert invalid_fragment == "[2001:db8::1]:8080/webhook"
+ assert parsed == ["discord://id/token", "[2001:db8::1]:8080/webhook"]
+ assert is_valid is False
+ assert error is not None
+ assert "must have a protocol" in error
+ assert filtered == ""
+ assert strict == []
+ assert lenient == []
+
+
+def test_custom_separator_preserves_policy_evaluation_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
+ manager = _unprotected_manager()
+ with monkeypatch.context() as patcher:
+ from local_deep_research.security.egress import policy
+
+ patcher.setattr(
+ policy,
+ "context_from_snapshot",
+ Mock(side_effect=ValueError("bad policy")),
+ )
+ filtered = manager._filter_urls_by_egress_policy(
+ "slack://token/path|discord://id/token", separator="|"
+ )
+ assert filtered is None
+
+
+def test_send_refuses_custom_separator_fragment_before_dispatch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from local_deep_research.notifications.exceptions import ServiceError
+
+ service = NotificationService(outbound_allowed=True)
+ dispatch = Mock()
+ monkeypatch.setattr(service, "_dispatch", dispatch)
+ with pytest.raises(ServiceError):
+ service.send(
+ "title",
+ "body",
+ service_urls="slack://token/path|::1/x",
+ separator="|",
+ )
+ dispatch.assert_not_called()
diff --git a/tests/notifications/test_notification_url_pipeline_default_parser.py b/tests/notifications/test_notification_url_pipeline_default_parser.py
new file mode 100644
index 0000000000..1362be23a7
--- /dev/null
+++ b/tests/notifications/test_notification_url_pipeline_default_parser.py
@@ -0,0 +1,233 @@
+"""Default comma-boundary parsing, performance, and validation alignment.
+
+Covers embedded-comma preservation, whitespace-boundary normalization,
+strict/lenient scheme partitioning, malformed-fragment refusal, and the
+linear-time scan across the parser, validator, manager and service for the
+default "," separator. The custom-separator pipeline and ``send``/
+``send_event`` forwarding are exercised in
+``test_notification_url_pipeline_custom_separator``.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+
+import pytest
+
+from local_deep_research.notifications.manager import NotificationManager
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ parse_notification_url_list,
+)
+
+
+def _unprotected_manager() -> NotificationManager:
+ return NotificationManager(
+ settings_snapshot={
+ "policy.egress_scope": {"value": "unprotected"},
+ "search.tool": {"value": "searxng"},
+ },
+ user_id="u",
+ )
+
+
+def test_parser_preserves_embedded_comma_boundary() -> None:
+ # Given
+ urls = "json://example.com/webhook?field=a,b, discord://webhook/token"
+ expected = [
+ "json://example.com/webhook?field=a,b",
+ "discord://webhook/token",
+ ]
+
+ # When
+ parsed, invalid_fragment = parse_notification_url_list(urls)
+
+ # Then
+ assert invalid_fragment is None
+ assert parsed == expected
+
+
+def test_validator_accepts_embedded_comma_boundary() -> None:
+ # Given
+ urls = "json://example.com/webhook?field=a,b, discord://webhook/token"
+
+ # When
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(urls)
+
+ # Then
+ assert is_valid is True
+ assert error is None
+
+
+def test_manager_preserves_embedded_comma_boundary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Given
+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
+ urls = "json://example.com/webhook?field=a,b, discord://webhook/token"
+ expected = [
+ "json://example.com/webhook?field=a,b",
+ "discord://webhook/token",
+ ]
+ manager = _unprotected_manager()
+
+ # When
+ filtered = manager._filter_urls_by_egress_policy(urls)
+
+ # Then
+ assert filtered == " ".join(expected)
+ filtered_entries, invalid_fragment = parse_notification_url_list(filtered)
+ assert invalid_fragment is None
+ assert filtered_entries == expected
+
+
+def test_service_preserves_embedded_comma_boundary() -> None:
+ # Given
+ urls = "json://example.com/webhook?field=a,b, discord://webhook/token"
+ expected = [
+ "json://example.com/webhook?field=a,b",
+ "discord://webhook/token",
+ ]
+
+ # When
+ strict, lenient = NotificationService._partition_urls(urls)
+
+ # Then
+ assert strict == []
+ assert lenient == expected
+
+
+def test_partition_preserves_strict_and_lenient_urls() -> None:
+ # Given
+ embedded_comma_url = "json://example.com/webhook?field=a,b"
+ service_urls = (
+ f"https://public.example.com/hook,{embedded_comma_url},"
+ "discord://id/token"
+ )
+
+ # When
+ strict_urls, lenient_urls = NotificationService._partition_urls(
+ service_urls
+ )
+
+ # Then
+ assert strict_urls == ["https://public.example.com/hook"]
+ assert lenient_urls == [embedded_comma_url, "discord://id/token"]
+
+
+def test_invalid_fragment_refuses_entire_partition() -> None:
+ # Given
+ service_urls = "discord://id/token,example.com/webhook"
+
+ # When
+ partitions = NotificationService._partition_urls(service_urls)
+
+ # Then
+ assert partitions == ([], [])
+
+
+ "delimiter",
+ ["\v", "\f", "\u00a0", "\u2003", ",\v \f\u00a0\u2003"],
+ ids=["vertical-tab", "form-feed", "nbsp", "em-space", "mixed"],
+)
+def test_default_parser_normalizes_all_whitespace_boundaries(
+ delimiter: str,
+) -> None:
+ # Given
+ urls = f"slack://token/path{delimiter}discord://id/token"
+ expected = ["slack://token/path", "discord://id/token"]
+
+ # When
+ parsed, invalid_fragment = parse_notification_url_list(urls)
+
+ # Then
+ assert invalid_fragment is None
+ assert parsed == expected
+
+
+ "delimiter",
+ ["\v", "\f", "\u00a0", "\u2003", ",\v \f\u00a0\u2003"],
+ ids=["vertical-tab", "form-feed", "nbsp", "em-space", "mixed"],
+)
+def test_partition_normalizes_all_whitespace_boundaries(delimiter: str) -> None:
+ # Given
+ urls = f"slack://token/path{delimiter}discord://id/token"
+ expected = ["slack://token/path", "discord://id/token"]
+
+ # When
+ strict, lenient = NotificationService._partition_urls(urls)
+
+ # Then
+ assert strict == []
+ assert lenient == expected
+
+
+def test_default_separator_scan_is_linear_for_long_non_boundary_run() -> None:
+ # Given
+ probe = (
+ "from local_deep_research.security.notification_validator "
+ "import parse_notification_url_list\n"
+ 'separator_run = ", \\t" * 49_152\n'
+ 'urls = f"discord://id/token?payload=start{separator_run}opaque"\n'
+ "parsed, invalid_fragment = parse_notification_url_list(urls)\n"
+ "assert invalid_fragment is not None\n"
+ "assert parsed == [urls]\n"
+ )
+
+ # When
+ completed = subprocess.run(
+ [sys.executable, "-c", probe],
+ check=True,
+ # Generous: the probe is ~3s of interpreter start-up plus a
+ # sub-millisecond scan. A quadratic scan over the 49k-separator
+ # run would take minutes, so a loose bound still fails closed
+ # while leaving headroom for a loaded CI runner.
+ timeout=60,
+ )
+
+ # Then
+ assert completed.returncode == 0
+
+
+def test_manager_to_service_scan_is_linear_for_long_non_boundary_run() -> None:
+ # Given
+ probe = (
+ "import os\n"
+ 'os.environ["LDR_POLICY_ALLOW_UNPROTECTED_EGRESS"] = "true"\n'
+ "from local_deep_research.notifications.manager import "
+ "NotificationManager\n"
+ "from local_deep_research.notifications.service import "
+ "NotificationService\n"
+ 'separator_run = ", \\t" * 49_152\n'
+ 'urls = f"discord://id/token?payload=start{separator_run}opaque"\n'
+ "manager = NotificationManager(\n"
+ " settings_snapshot={\n"
+ ' "policy.egress_scope": {"value": "unprotected"},\n'
+ ' "search.tool": {"value": "searxng"},\n'
+ " },\n"
+ ' user_id="subprocess-probe",\n'
+ ")\n"
+ "filtered = manager._filter_urls_by_egress_policy(urls)\n"
+ "strict, lenient = NotificationService._partition_urls(urls)\n"
+ 'assert filtered == ""\n'
+ "assert strict == []\n"
+ "assert lenient == []\n"
+ )
+
+ # When
+ completed = subprocess.run(
+ [sys.executable, "-c", probe],
+ check=True,
+ # Generous: the probe is ~3s of interpreter start-up plus a
+ # sub-millisecond scan. A quadratic scan over the 49k-separator
+ # run would take minutes, so a loose bound still fails closed
+ # while leaving headroom for a loaded CI runner.
+ timeout=60,
+ )
+
+ # Then
+ assert completed.returncode == 0
diff --git a/tests/security/test_notification_host_alias_fragments.py b/tests/security/test_notification_host_alias_fragments.py
new file mode 100644
index 0000000000..7c566cd792
--- /dev/null
+++ b/tests/security/test_notification_host_alias_fragments.py
@@ -0,0 +1,348 @@
+"""Alias spellings of a host in the scheme-less notification fragment guard.
+
+``_is_scheme_less_url_fragment`` refuses a comma-separated fragment that names
+a host without carrying a scheme. A host has several spellings that all resolve
+to the same machine -- scheme-relative (``//host``), userinfo-prefixed
+(``user@host``), fully qualified with a root dot (``host.``), percent-encoded
+IPv6 brackets, and the historical inet_aton numeric forms -- and the guard has
+to reach one verdict across all of them, exactly as it already does for
+``localhost`` versus ``LOCALHOST``.
+
+Like the rest of this guard the property is fail-closed integrity rather than a
+reachable SSRF: a fragment the guard misses stays inert URL data instead of
+being dialed. Every check here only ever ADDS a refusal -- no spelling that was
+already refused is readmitted.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ _is_scheme_less_url_fragment,
+ parse_notification_url_list,
+)
+
+
+ "fragment",
+ [
+ "//localhost/x",
+ "//127.0.0.1/x",
+ "//169.254.169.254/latest/meta",
+ "//evil.example.com/hook",
+ ],
+)
+def test_scheme_relative_hostname_fragment_fails_closed(
+ fragment: str,
+) -> None:
+ """``//host`` names the same host as ``host``.
+
+ The IPv6 alternative already accepted the scheme-relative prefix, so
+ ``//[::1]/x`` was refused while ``//127.0.0.1/x`` was kept as data.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ "localhost.",
+ "LOCALHOST.",
+ "127.0.0.1.",
+ "localhost./webhook",
+ "localhost.:8080/x",
+ "//localhost./x",
+ "evil.example.com.",
+ # ``%2e`` spells the same dot.
+ "localhost%2e/x",
+ "LOCALHOST%2E/x",
+ "localhost%2e.%2e/x",
+ "127.0.0.1%2e/x",
+ # A bracketed literal has already closed, so its port splits off the
+ # way it does without the root dot -- ``[::1]:8080/x`` is refused.
+ "[::1].:8080/x",
+ "%5b::1%5d.:8080/hook",
+ "//[::1].:8080/x",
+ "user@[::1].:8080/x",
+ ],
+)
+def test_root_dotted_host_fragment_fails_closed(fragment: str) -> None:
+ """A trailing root dot is the same host to every resolver.
+
+ ``_normalize_host`` already strips it for whole URLs, so ``localhost.``
+ reaching a different verdict from ``localhost`` was the same
+ two-spellings-disagree defect the case fix closed.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ "user@[::1]/hook",
+ "user:pw@[::1]/hook",
+ "@[::1]/hook",
+ "user@::1/hook",
+ "user@localhost/x",
+ "//user@[::1]/x",
+ "a@b@[::1]/x",
+ ],
+)
+def test_userinfo_prefixed_host_fragment_fails_closed(fragment: str) -> None:
+ """Userinfo hides the host from an anchored pattern.
+
+ Both alternatives are ``^``-anchored, so ``user@[::1]`` was read as one
+ opaque token that ``IPv6Address`` rejected, and the fragment was kept as
+ URL data while its unprefixed spelling was refused.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ "%5b::1%5d/hook",
+ "%5B::1%5D/hook",
+ "%5b::1%5d:8080/hook",
+ "%5b::ffff:127.0.0.1%5d/hook",
+ "%5B::1%5D",
+ "user@%5b::1%5d/x",
+ ],
+)
+def test_percent_encoded_bracket_fragment_fails_closed(fragment: str) -> None:
+ """``%5b``/``%5d`` in either hex case spell the IPv6 brackets."""
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ # Two or more dot-separated components are an authority on their own.
+ "0177.0.0.1/x",
+ "127.1/x",
+ "0x7f.0x0.0x0.0x1/x",
+ "0177.0.0.1:8080/x",
+ # A one-component spelling needs a ``//`` or ``userinfo@`` prefix,
+ # because bare it is indistinguishable from an Apprise target id.
+ "//2130706433/x",
+ "user@2130706433/x",
+ "//0x7f000001/x",
+ "user@017700000001/x",
+ ],
+)
+def test_legacy_numeric_ipv4_fragment_fails_closed(fragment: str) -> None:
+ """Decimal, hexadecimal, octal and shortened forms name one address.
+
+ ``validate_service_url`` already refuses these spellings for a whole URL
+ through ``legacy_ipv4``; the fragment guard routes the same grammar
+ through the same helper rather than growing a second one.
+
+ A whole URL carries a scheme, so its host position is unambiguous. A
+ fragment's is not, which is why only the multi-component spellings and
+ the prefixed one-component ones reach the helper here.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ "%327%2e0%2e0%2e1/x",
+ "%31%32%37%2e%30%2e%30%2e%31/x",
+ "//%32130706433/x",
+ "user@%30x7f000001/x",
+ "%310%2e0%2e0%2e1:8080/x",
+ ],
+)
+def test_percent_encoded_numeric_ipv4_fragment_fails_closed(
+ fragment: str,
+) -> None:
+ """One decoding pass exposes the same numeric host.
+
+ ``validate_service_url`` runs ``is_percent_encoded_numeric_ipv4_host``
+ beside ``is_ambiguous_numeric_ipv4_host`` for a whole URL; the fragment
+ guard consults both under the same authority-marker rule rather than
+ only the unencoded one.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ # Members of an Apprise ``?to=`` recipient list. The userinfo
+ # alternative carries only the loopback name and IPv4 literals, which
+ # is what keeps an ordinary recipient domain an e-mail address; its
+ # ``[/?#]`` trailer is what keeps a recipient whose domain part IS
+ # spelled like a loopback host one too.
+ "admin@localhost",
+ # A one-component inet_aton host is any integer below 2**32, so every
+ # Apprise target id matches it. Bare or trailed, such a token only
+ # names a host once the fragment carries an authority marker of its
+ # own -- a second component, ``//``, or ``userinfo@``.
+ "1712345678",
+ "12345",
+ "2",
+ "2130706433/x",
+ # A trailing root dot in either spelling is not a second component.
+ "2130706433%2e/x",
+ "12345%2e/x",
+ "222222222%2e?format=markdown",
+ "0x7f000001/x",
+ "017700000001/x",
+ "222222222?format=markdown",
+ "1700000001/x",
+ "4085551234?batch=yes",
+ "%32130706433/x",
+ # Colon-rich data the changelog promises stays data.
+ "aa:bb:cc:dd:ee:ff",
+ "00:11:22:33:44:55",
+ "12:34:56",
+ "sha256:abcdef",
+ "user:pass",
+ # Credentials in front of an ordinary domain are what an Apprise
+ # service URL looks like, so the userinfo alternative covers only the
+ # loopback name and IPv4 literals.
+ "more:secret:[email protected]/webhook",
+ ],
+)
+def test_non_authority_tokens_remain_url_data(fragment: str) -> None:
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is False
+
+
+ ("urls", "expected_fragment"),
+ [
+ ("slack://t/x/y,//127.0.0.1/x", "//127.0.0.1/x"),
+ ("slack://t/x/y,localhost.", "localhost."),
+ ("slack://t/x/y,user@[::1]/hook", "user@[::1]/hook"),
+ ("slack://t/x/y,%5b::1%5d/hook", "%5b::1%5d/hook"),
+ ("slack://t/x/y,//2130706433/x", "//2130706433/x"),
+ ("slack://t/x/y,localhost%2e/x", "localhost%2e/x"),
+ ],
+)
+def test_host_alias_fragment_refuses_entire_partition(
+ urls: str, expected_fragment: str
+) -> None:
+ """A missed alias must not leave the rest of the list dispatchable.
+
+ Asserted on the mechanism -- the partition surfaces the alias as its
+ invalid fragment -- rather than on the wording of the refusal, so a
+ reworded message cannot make this pass while the guard is reverted.
+ """
+ # Given
+ service_urls = urls
+
+ # When
+ _parsed_urls, invalid_fragment = parse_notification_url_list(service_urls)
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_urls
+ )
+
+ # Then
+ assert invalid_fragment == expected_fragment
+ assert is_valid is False
+ assert error is not None
+
+
+ "urls",
+ [
+ # Each comment records the targets apprise resolves the URL to.
+ # 2 Telegram chat ids
+ "tgram://123456789:ABCdefGHIjklMNOpqrsTUVwxyz/111111111,222222222/",
+ # 2 Telegram chat ids
+ "tgram://123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
+ "/111111111,222222222?format=markdown",
+ # 3 Telegram chat ids
+ "tgram://123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
+ "/111111111,222222222/333333333",
+ # 1 JSON endpoint, the timestamps are query data
+ "json://example.com/hook?ts=1700000000,1700000001/x",
+ # 1 form endpoint, the attachments are query data
+ "form://example.com/?attach=/a/b.txt,2024/report.pdf",
+ # 2 Twilio numbers
+ "twilio://ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ ":bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@+15551234567"
+ "/2125551234,4085551234?batch=yes",
+ # 2 PushSafer device ids
+ "psafer://privatekey/123,456?priority=1",
+ # 2 Slack targets
+ "slack://TokA/TokB/TokC/#general,12345?footer=no",
+ ],
+)
+def test_comma_separated_target_lists_stay_one_url(urls: str) -> None:
+ """Apprise's comma-separated target lists are one URL, not a partition.
+
+ A comma-delimited target list is a first-class Apprise form, and it puts
+ a ``/`` or a ``?`` directly after the last id. Reading that id as an
+ inet_aton host -- every integer below 2**32 is one -- refused the whole
+ notification configuration, every other destination in it included, for
+ a Telegram chat id, a phone number or a timestamp.
+ """
+ # Given
+ service_urls = urls
+
+ # When
+ parsed_urls, invalid_fragment = parse_notification_url_list(service_urls)
+
+ # Then
+ assert invalid_fragment is None
+ assert parsed_urls == [service_urls]
diff --git a/tests/security/test_notification_ipv6_fragments.py b/tests/security/test_notification_ipv6_fragments.py
new file mode 100644
index 0000000000..dbcbd194d4
--- /dev/null
+++ b/tests/security/test_notification_ipv6_fragments.py
@@ -0,0 +1,175 @@
+import socket
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ _is_scheme_less_url_fragment,
+)
+
+
+ "urls",
+ [
+ "slack://t/x/y,::1/x",
+ "slack://t/x/y,[::1]/x",
+ "slack://t/x/y,[2001:db8::1]:8080/x",
+ "slack://t/x/y [::1]/x",
+ "slack://t/x/y [2001:db8::1]/x",
+ "slack://t/x/y,//[::1]/x",
+ "slack://t/x/y //[::1]/x",
+ "slack://t/x/y,[::1]:/x",
+ "slack://t/x/y [::1]:/x",
+ "slack://t/x/y,[::1]:name/x",
+ "slack://t/x/y [::1]:name/x",
+ ],
+)
+def test_scheme_less_ipv6_fragment_fails_closed(urls: str) -> None:
+ # Given
+ service_urls = urls
+
+ # When
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_urls
+ )
+
+ # Then
+ assert is_valid is False
+ assert error is not None
+ assert "protocol" in error.lower()
+
+
+ "urls",
+ [
+ "json://user:pass@host/path",
+ "json://host/path?times=12:30,13:45",
+ "json://host/path?stamp=a,12:30:45",
+ "json://host/path?macs=a,aa:bb:cc:dd:ee:ff/path",
+ "json://host/path discord://webhook/token",
+ "json://user:pa:ss,more:secret:[email protected]/webhook",
+ "json://example.com/webhook?times=12:30:45,13:45:00",
+ "json://example.com/webhook?macs=00:11:22:33:44:55,aa:bb:cc:dd:ee:ff",
+ ],
+)
+def test_colon_rich_non_fragments_remain_valid(urls: str) -> None:
+ # Given
+ service_urls = urls
+ fake_result = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0)),
+ ]
+
+ # When
+ with patch("socket.getaddrinfo", return_value=fake_result):
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_urls
+ )
+
+ # Then
+ assert is_valid is True
+ assert error is None
+
+
+def test_ipv6_like_query_fragment_fails_closed_by_policy() -> None:
+ # Given
+ service_urls = "json://example.com/path?ips=a,[::1]/x"
+
+ # When
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_urls
+ )
+
+ # Then
+ assert is_valid is False
+ assert error is not None
+ assert "protocol" in error.lower()
+
+
+ "fragment",
+ [
+ "::1/x",
+ "[::1]/x",
+ "[2001:db8::1]:8080/x",
+ "2001:db8::1/path",
+ "::ffff:192.0.2.128/webhook",
+ ],
+)
+def test_scheme_less_ipv6_fragment_helper_accepts_literals(
+ fragment: str,
+) -> None:
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "fragment",
+ [
+ "user:pass@host/path",
+ "12:30",
+ "12:30:45",
+ "aa:bb:cc:dd:ee:ff/path",
+ ],
+)
+def test_scheme_less_ipv6_fragment_helper_rejects_colon_rich_tokens(
+ fragment: str,
+) -> None:
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is False
+
+
+ "fragment",
+ [
+ "::1:99999",
+ "::1:99999/x",
+ "2001:db8::1:99999",
+ "::1:name",
+ ],
+)
+def test_bare_ipv6_fragment_with_unusable_port_still_fails_closed(
+ fragment: str,
+) -> None:
+ """A bare host is refused even when its trailing port is unusable.
+
+ The bare alternative carries no port group, so its greedy run swallows
+ the ``:<port>``. Validating that whole run as one literal made
+ ``::1:99999`` fail ``IPv6Address`` and be accepted as ordinary URL data,
+ while the bracketed ``[::1]:99999`` was refused -- the two forms
+ disagreed on the same address.
+ """
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+def test_bare_and_bracketed_forms_agree_on_an_unusable_port() -> None:
+ """The two spellings of one address must reach the same verdict."""
+ # Given
+ bare = "::1:99999"
+ bracketed = "[::1]:99999"
+
+ # When
+ bare_is_fragment = _is_scheme_less_url_fragment(bare)
+ bracketed_is_fragment = _is_scheme_less_url_fragment(bracketed)
+
+ # Then
+ assert bare_is_fragment == bracketed_is_fragment is True
diff --git a/tests/security/test_notification_schemeless_host_case.py b/tests/security/test_notification_schemeless_host_case.py
new file mode 100644
index 0000000000..82d151485c
--- /dev/null
+++ b/tests/security/test_notification_schemeless_host_case.py
@@ -0,0 +1,93 @@
+"""Case-insensitivity of the scheme-less notification URL fragment guard.
+
+Hostnames are case-insensitive (RFC 4343), so the ``localhost`` alternative in
+``_SCHEMELESS_URL_FRAGMENT_RE`` must reach the same verdict regardless of how
+the fragment is capitalized. The guard is fail-closed integrity rather than a
+reachable SSRF -- a fragment it misses is kept as inert URL data, not dialed --
+but the two spellings disagreeing was plainly unintended.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+ _is_scheme_less_url_fragment,
+)
+
+
+ "fragment",
+ [
+ "localhost",
+ "LOCALHOST",
+ "Localhost",
+ "LocalHost",
+ "localhost:8080/x",
+ "LOCALHOST:8080/x",
+ "LocalHost:8080/x",
+ "lOcAlHoSt/webhook",
+ ],
+)
+def test_schemeless_localhost_fragment_detected_in_any_case(
+ fragment: str,
+) -> None:
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is True
+
+
+ "urls",
+ [
+ "slack://t/x/y,LOCALHOST:8080/x",
+ "slack://t/x/y Localhost/webhook",
+ "slack://t/x/y,LocalHost",
+ ],
+)
+def test_mixed_case_localhost_fragment_refuses_entire_partition(
+ urls: str,
+) -> None:
+ # Given
+ service_urls = urls
+
+ # When
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_urls
+ )
+
+ # Then
+ assert is_valid is False
+ assert error is not None
+ assert "protocol" in error.lower()
+
+
+ "fragment",
+ [
+ # A pattern-wide ``re.IGNORECASE`` folds U+017F and U+212A into the
+ # ``A-Za-z`` classes of the domain alternative, admitting these as
+ # hostname characters. Scoping the flag to ``localhost`` keeps that
+ # alternative exactly as strict as it was.
+ "\u017fervice.example/x",
+ "example.com\u212a/x",
+ "\u212aelvin.example/x",
+ ],
+)
+def test_unicode_case_folds_are_not_admitted_as_host_characters(
+ fragment: str,
+) -> None:
+ # Given
+ candidate = fragment
+
+ # When
+ is_fragment = _is_scheme_less_url_fragment(candidate)
+
+ # Then
+ assert is_fragment is False