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): accept tgram Telegram URLs (#5576)

LearningCircuit8a729fb1257b
diff --git a/SECURITY.md b/SECURITY.md
index a6322c5899..793abc95ed 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -131,7 +131,7 @@ LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true
By setting this, the operator acknowledges the residual risk above. To minimise it:
-- **Prefer plugin schemes over raw `http(s)://`.** Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, `ntfys://`, `gotify://`, `telegram://`, `mattermost://`, `rocketchat://`, `teams://`, `matrix://`, `mailto://`, etc.) hardcode their endpoints internally and have no user-controllable hostname — no SSRF surface. Use them whenever the target service supports them.
+- **Prefer plugin schemes over raw `http(s)://`.** Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, `ntfys://`, `gotify://`, `tgram://`, `mattermost://`, `rocketchat://`, `teams://`, `matrix://`, `mailto://`, etc.) hardcode their endpoints internally and have no user-controllable hostname — no SSRF surface. Use them whenever the target service supports them.
- **Restrict egress** if private-network exposure is a concern: deploy LDR behind an egress-restricted network so that even a successful rebinding cannot reach internal services.
The general HTTP fetch path (`safe_requests`, used for RAG sources and web scraping) resolves the hostname and connects to that **same** validated address: `security.dns_pinning` pins the resolved IP for the outbound connection (re-resolving and re-validating at connect time, and re-pinning at every redirect hop) so `requests`/`urllib3` cannot connect to a different address than the one the guard checked. The request keeps the original hostname, so TLS SNI and certificate verification are unchanged — only name resolution is pinned. The notification path above reuses this same shim (via `pinned_notification_send`, plus the block-private window for unpinned plugin-endpoint hosts) — but with redirect-following disabled outright rather than validated hop-by-hop, since a notification webhook has no legitimate need to follow redirects. It still does not apply to callers that hand a URL to an external client that re-resolves on its own with no in-thread `getaddrinfo` interception (LLM SDKs — see "LLM Provider URL Validation"); for those, egress restriction remains the primary defense. It also does not apply when `requests` is configured to use a forward proxy (`HTTP(S)_PROXY` / `trust_env`): `urllib3` then resolves the *proxy* host rather than the target, so target-IP selection is delegated to the proxy and the pin is a safe no-op (the pre-connection `validate_url` check still runs).
diff --git a/changelog.d/5576.bugfix.md b/changelog.d/5576.bugfix.md
new file mode 100644
index 0000000000..7a2f603abe
--- /dev/null
+++ b/changelog.d/5576.bugfix.md
@@ -0,0 +1 @@
+Telegram notifications now use Apprise's canonical `tgram://` scheme; the unregistered `telegram://` alias is rejected. Apprise diagnostic log output that could contain notification credentials is suppressed. Multi-target URLs such as `tgram://...?to=id1,id2` are no longer split into partial notifications, and `telegram://` URLs now get a dedicated migration error pointing at the `tgram://` form.
diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md
index 194cba4c1f..9792d37d9f 100644
--- a/docs/NOTIFICATIONS.md
+++ b/docs/NOTIFICATIONS.md
@@ -41,7 +41,7 @@ The system supports all services that Apprise supports, including but not limite
- Discord (via webhooks)
- Slack (via webhooks)
-- Telegram
+- Telegram (via Apprise's `tgram://` scheme)
- Email (SMTP)
- Pushover
- Gotify
@@ -306,7 +306,7 @@ The "Test" button in the notifications settings page returns the validator's rea
**"Blocked unsafe protocol: \<scheme\>"** / **"Unsupported protocol: \<scheme\>"**
- **Cause**: The URL uses a scheme that is either denylisted (`file`, `ftp`, `ftps`, `data`, `javascript`, `vbscript`, `about`, `blob`) or not in the Apprise-supported allowlist.
-- **Fix**: Use one of the allowed schemes — `http`, `https`, `mailto`, `discord`, `slack`, `telegram`, `gotify`, `pushover`, `ntfy`, `ntfys`, `signal`, `matrix`, `mattermost`, `rocketchat`, `teams`, `json`, `xml`, `form`. Prefer Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, etc.) over raw `http(s)://` webhooks — they hardcode their endpoints and have no SSRF surface.
+- **Fix**: Use one of the allowed schemes — `http`, `https`, `mailto`, `discord`, `slack`, `tgram`, `gotify`, `pushover`, `ntfy`, `ntfys`, `signal`, `matrix`, `mattermost`, `rocketchat`, `teams`, `json`, `xml`, `form`. Prefer Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, etc.) over raw `http(s)://` webhooks — they hardcode their endpoints and have no SSRF surface.
**"URL contains characters that are not allowed (whitespace, backslash, or control bytes)"**
- **Cause**: Layer-1 defense against parser-differential SSRF bypasses (GHSA-g23j-2vwm-5c25) — RFC 3986 forbids these characters in URLs.
diff --git a/src/local_deep_research/notifications/apprise_log_utils.py b/src/local_deep_research/notifications/apprise_log_utils.py
new file mode 100644
index 0000000000..7398212bb0
--- /dev/null
+++ b/src/local_deep_research/notifications/apprise_log_utils.py
@@ -0,0 +1,33 @@
+import logging
+from collections.abc import Callable
+from typing import Final
+
+
+APPRISE_DIAGNOSTIC: Final = (
+ "Apprise emitted a diagnostic; details suppressed to protect "
+ "notification credentials."
+)
+
+
+class _AppriseSanitizingRecordFactory[**P]:
+ def __init__(self, delegate: Callable[P, logging.LogRecord]) -> None:
+ self._delegate = delegate
+
+ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> logging.LogRecord:
+ record = self._delegate(*args, **kwargs)
+ if record.name == "apprise" or record.name.startswith("apprise."):
+ record.msg = APPRISE_DIAGNOSTIC
+ record.args = ()
+ record.exc_info = None
+ record.exc_text = None
+ record.stack_info = None
+ return record
+
+
+def install_apprise_log_record_factory() -> None:
+ current_factory = logging.getLogRecordFactory()
+ if isinstance(current_factory, _AppriseSanitizingRecordFactory):
+ return
+ logging.setLogRecordFactory(
+ _AppriseSanitizingRecordFactory(current_factory)
+ )
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index a0a72482c7..a775ec3f23 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -457,7 +457,7 @@ class NotificationManager:
return ""
# Apprise accepts space- or comma- separated URLs. Apprise has
- # its own non-http schemes (discord://, slack://, telegram://,
+ # its own non-http schemes (discord://, slack://, tgram://,
# mailto://, msteams://, ntfy://, ...) that dispatch to EXTERNAL
# vendor APIs. evaluate_url only understands http/https.
#
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 9e2d3d8312..e045deb479 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -18,11 +18,12 @@ from tenacity import (
)
from .exceptions import ServiceError, SendError
+from .apprise_log_utils import install_apprise_log_record_factory
from .templates import EventType, NotificationTemplate
from ..security import dns_pinning
-from ..security.url_builder import mask_sensitive_url
from ..security.notification_validator import (
NotificationURLValidator,
+ parse_notification_url_list,
)
PRIVATE_IP_REJECTION_PREFIX = (
@@ -68,6 +69,7 @@ class NotificationService:
the operator opts in. See SECURITY.md "Notification
Webhook SSRF" for the rationale.
"""
+ install_apprise_log_record_factory()
self.apprise = self._new_apprise()
self.allow_private_ips = allow_private_ips
self.outbound_allowed = outbound_allowed
@@ -191,11 +193,15 @@ class NotificationService:
def _partition_urls(service_urls: str) -> Tuple[List[str], List[str]]:
"""Split an Apprise URL string into (http(s), everything-else).
- Splits on commas and whitespace — the separators Apprise's own
- ``add()`` accepts — so the partition matches what Apprise will
- actually dispatch. 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
+ 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.
@@ -210,7 +216,21 @@ class NotificationService:
"""
strict: List[str] = []
lenient: List[str] = []
- for entry in service_urls.replace(",", " ").split():
+ entries, invalid_fragment = parse_notification_url_list(
+ service_urls, ","
+ )
+ if invalid_fragment is not None:
+ # Never log the fragment itself — it may contain credentials.
+ # ``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.
+ logger.warning(
+ "Notification service_url list contains a malformed "
+ "fragment; callers must validate the list before dispatch"
+ )
+ for entry in entries:
entry = entry.strip()
if not entry:
continue
@@ -431,10 +451,7 @@ class NotificationService:
)
if not is_valid:
- logger.error(
- f"Service URL validation failed: {error_msg}. "
- f"URL: {mask_sensitive_url(service_urls)}"
- )
+ logger.error("Service URL validation failed")
raise ServiceError(f"Invalid service URL: {error_msg}")
try:
@@ -443,10 +460,7 @@ class NotificationService:
if service_urls:
strict_urls, lenient_urls = self._partition_urls(service_urls)
if not strict_urls and not lenient_urls:
- logger.error(
- f"No service URLs after parsing: "
- f"{mask_sensitive_url(service_urls)}"
- )
+ logger.error("No service URLs after parsing")
return False
return self._dispatch(
title, body, strict_urls, lenient_urls, tag, attach
@@ -548,10 +562,7 @@ class NotificationService:
# runtime but mypy rejects it on list invariance (upstream should
# use ``Sequence``).
if not temp_apprise.add(urls, tag=tag): # type: ignore[arg-type]
- logger.error(
- f"Failed to add service URLs to Apprise: "
- f"{mask_sensitive_url(' '.join(urls))}"
- )
+ logger.error("Failed to add service URLs to Apprise")
return False
# _send_with_retry returns True or raises SendError after
# Tenacity exhausts its retries; a raise propagates to send().
@@ -648,8 +659,7 @@ class NotificationService:
if not is_valid:
logger.warning(
- f"Test service URL validation failed: {error_msg}. "
- f"URL: {mask_sensitive_url(url)}"
+ f"Test service URL validation failed: {error_msg}"
)
# Surface the validator's reason so users know what to fix.
# The hostname/scheme echoed here was supplied by the user
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index ce593fbcbd..8b82e3ebe7 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -315,4 +315,4 @@ be retriever-backed or dynamically injected engines the factory evaluates
via its own path) — the pre-filter is never stricter than the factory PEP
it fronts.
-> **Notification footnote.** The notification PEP (`notifications/manager.py` `_filter_urls_by_egress_policy`) gates **http/https** webhook URLs through `evaluate_url`. Apprise vendor schemes (`slack://`, `discord://`, `telegram://`, `mailto://`, …) dispatch to external vendor APIs: under **PRIVATE_ONLY** (incl. Adaptive-private) they are **refused outright** (we can't verify a vendor token is local — fail closed; address a self-hosted notifier by its `http(s)://` URL, which `evaluate_url` allows as a private host). Under the other scopes they pass the URL gate (the modeled threat there is internal-http SSRF, not vendor APIs); the audit-hook net is an additional backstop for the actual connection when armed.
+> **Notification footnote.** The notification PEP (`notifications/manager.py` `_filter_urls_by_egress_policy`) gates **http/https** webhook URLs through `evaluate_url`. Apprise vendor schemes (`slack://`, `discord://`, `tgram://`, `mailto://`, …) dispatch to external vendor APIs: under **PRIVATE_ONLY** (incl. Adaptive-private) they are **refused outright** (we can't verify a vendor token is local — fail closed; address a self-hosted notifier by its `http(s)://` URL, which `evaluate_url` allows as a private host). Under the other scopes they pass the URL gate (the modeled threat there is internal-http SSRF, not vendor APIs); the audit-hook net is an additional backstop for the actual connection when armed.
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index 780b4ed584..2954fff77d 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -30,6 +30,10 @@ _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}://)")
+_APPRISE_TELEGRAM_URL_RE = re.compile(
+ r"^tgram://(?:bot)?[0-9]+(?::|%3A)[a-z0-9_-]+(?:/|\?|$)",
+ re.IGNORECASE,
+)
def parse_notification_url_list(
@@ -94,7 +98,7 @@ class NotificationURLValidator:
"mailto", # Email notifications
"discord", # Discord webhooks
"slack", # Slack webhooks
- "telegram", # Telegram bot API
+ "tgram", # Apprise Telegram scheme
"gotify", # Gotify notifications
"pushover", # Pushover notifications
"ntfy", # ntfy.sh notifications (http)
@@ -206,7 +210,7 @@ class NotificationURLValidator:
# operator's explicit decision. See SECURITY.md "Notification Webhook
# SSRF". Operators can further avoid raw webhooks by preferring
# plugin schemes (discord://, slack://, ntfy://, ntfys://, gotify://,
- # telegram://, mattermost://, etc.) that hardcode their endpoints.
+ # tgram://, mattermost://, etc.) that hardcode their endpoints.
#
# concurrent.futures for thread-safe timeout instead of
# socket.setdefaulttimeout() which is process-global.
@@ -491,6 +495,17 @@ class NotificationURLValidator:
# Check for allowed schemes
if scheme not in NotificationURLValidator.ALLOWED_SCHEMES:
+ if scheme == "telegram":
+ # Dedicated migration error: 'telegram://' was an Apprise
+ # scheme removed upstream; point users at the canonical
+ # 'tgram://' form instead of the generic allowed-list.
+ return (
+ False,
+ "The 'telegram://' scheme is no longer supported by "
+ "Apprise (removed upstream); replace it with Apprise's "
+ "canonical 'tgram://<bot_token>/<chat_id>' form "
+ "(e.g. tgram://123456789:AAexample_token/123456789)",
+ )
logger.warning(
f"Unknown notification protocol: {scheme} in URL: {redact_url_for_log(url)}"
)
@@ -550,6 +565,15 @@ class NotificationURLValidator:
"'scheme:///' is not allowed",
)
+ if scheme == "tgram":
+ if not _APPRISE_TELEGRAM_URL_RE.match(url):
+ return (
+ False,
+ "Invalid Telegram service URL; expected "
+ "tgram://<bot_id>:<token>/<chat_id>",
+ )
+ return True, None
+
# Extract the host for any allowed scheme. We use urllib3 (the
# parser ``requests`` uses internally) instead of urlparse —
# urlparse is vulnerable to parser-differential bypasses like
@@ -925,8 +949,7 @@ class NotificationURLValidator:
)
return (
False,
- f"Invalid URL '{redact_url_for_log(invalid_fragment)}': "
- f"{error_message}",
+ f"Invalid notification service URL: {error_message}",
)
if not url_list:
@@ -944,7 +967,7 @@ class NotificationURLValidator:
# Return first error found
return (
False,
- f"Invalid URL '{redact_url_for_log(url)}': {error_message}",
+ f"Invalid notification service URL: {error_message}",
)
# All URLs passed validation
diff --git a/tests/notifications/test_apprise_log_utils.py b/tests/notifications/test_apprise_log_utils.py
new file mode 100644
index 0000000000..89f1fbd8ce
--- /dev/null
+++ b/tests/notifications/test_apprise_log_utils.py
@@ -0,0 +1,290 @@
+import logging
+import sys
+from collections.abc import Callable, Generator
+from io import StringIO
+from unittest.mock import MagicMock, patch
+
+import apprise
+import pytest
+from apprise.logger import LogCapture
+from loguru import logger as loguru_logger
+
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.utilities.log_utils import InterceptHandler
+
+
+GENERIC_APPRISE_DIAGNOSTIC = (
+ "Apprise emitted a diagnostic; details suppressed to protect "
+ "notification credentials."
+)
+BOT_TOKEN = "123456789:Token_abc-123"
+CHAT_ID = 987654321
+LEAKING_URLS = (
+ f"tgram://{BOT_TOKEN}/{CHAT_ID}?content=)%29QuerySecret",
+ f"tgram://{BOT_TOKEN}/)%29TargetSecret?content=)",
+)
+DESCENDANT_LOGGER_NAME = "apprise.plugins.future"
+
+
[email protected](autouse=True)
+def restore_apprise_logging_state() -> Generator[logging.Logger, None, None]:
+ dependency_logger = logging.getLogger("apprise")
+ managed_loggers = (
+ dependency_logger,
+ logging.getLogger(DESCENDANT_LOGGER_NAME),
+ )
+ original_factory = logging.getLogRecordFactory()
+
+ def factory_with_exc_text(*args, **kwargs) -> logging.LogRecord:
+ record = original_factory(*args, **kwargs)
+ record.exc_text = "ExcTextSecret"
+ return record
+
+ logging.setLogRecordFactory(factory_with_exc_text)
+ logger_states = tuple(
+ (tuple(item.filters), tuple(item.handlers), item.level, item.propagate)
+ for item in managed_loggers
+ )
+ for item, (filters, _, _, _) in zip(
+ managed_loggers, logger_states, strict=True
+ ):
+ for logger_filter in filters:
+ item.removeFilter(logger_filter)
+
+ yield dependency_logger
+
+ logging.setLogRecordFactory(original_factory)
+ for item, (filters, handlers, level, propagate) in zip(
+ managed_loggers, logger_states, strict=True
+ ):
+ item.filters[:] = filters
+ item.handlers[:] = handlers
+ item.setLevel(level)
+ item.propagate = propagate
+
+
+def _make_sensitive_record(logger: logging.Logger) -> logging.LogRecord:
+ try:
+ raise OSError("ExcInfoSecret")
+ except OSError:
+ record = logger.makeRecord(
+ logger.name,
+ logging.ERROR,
+ __file__,
+ 1,
+ "MessageSecret %s",
+ ("ArgsSecret",),
+ sys.exc_info(),
+ sinfo="StackInfoSecret",
+ )
+ return record
+
+
+def _assert_record_is_sanitized(record: logging.LogRecord) -> None:
+ assert record.msg == GENERIC_APPRISE_DIAGNOSTIC
+ assert record.args == ()
+ assert record.exc_info is None
+ assert record.exc_text is None
+ assert record.stack_info is None
+
+
+ "service_url",
+ LEAKING_URLS,
+ ids=("query-secret", "target-secret"),
+)
+def test_notification_service_add_failure_does_not_log_supplied_url(
+ service_url: str,
+) -> None:
+ output = StringIO()
+ sink_id = loguru_logger.add(
+ output,
+ format="{message}",
+ level="DEBUG",
+ diagnose=False,
+ )
+ loguru_logger.enable("local_deep_research")
+
+ try:
+ service = NotificationService(outbound_allowed=True)
+ with patch(
+ "apprise.plugins.telegram.requests.post",
+ side_effect=AssertionError("Telegram POST must not occur"),
+ ) as post:
+ result = service.send(
+ title="Test",
+ body="Network-free message",
+ service_urls=service_url,
+ )
+ finally:
+ loguru_logger.remove(sink_id)
+ loguru_logger.disable("local_deep_research")
+
+ assert result is False
+ post.assert_not_called()
+ rendered = output.getvalue()
+ for secret in (BOT_TOKEN, "QuerySecret", "TargetSecret"):
+ assert secret not in rendered
+ assert "Failed to add service URLs to Apprise" in rendered
+
+
+def test_service_installs_one_factory_before_every_apprise_instance(
+ restore_apprise_logging_state: logging.Logger,
+) -> None:
+ original_factory = logging.getLogRecordFactory()
+ delegated_records: list[logging.LogRecord] = []
+
+ def existing_factory(*args, **kwargs) -> logging.LogRecord:
+ record = original_factory(*args, **kwargs)
+ delegated_records.append(record)
+ return record
+
+ logging.setLogRecordFactory(existing_factory)
+ factories_at_construction: list[Callable[..., logging.LogRecord]] = []
+
+ def construct_apprise(*_args, **_kwargs) -> MagicMock:
+ factories_at_construction.append(logging.getLogRecordFactory())
+ return MagicMock()
+
+ with patch(
+ "local_deep_research.notifications.service.apprise.Apprise",
+ side_effect=construct_apprise,
+ ):
+ _ = NotificationService(outbound_allowed=True)
+ _ = NotificationService(outbound_allowed=True)
+
+ assert factories_at_construction[0] is not existing_factory
+ assert factories_at_construction[0] is factories_at_construction[1]
+ control = logging.getLogger("apprise_extra").makeRecord(
+ "apprise_extra",
+ logging.INFO,
+ __file__,
+ 1,
+ "Control %s",
+ ("detail",),
+ None,
+ )
+ assert delegated_records[-1] is control
+ assert control.getMessage() == "Control detail"
+ assert control.exc_text == "ExcTextSecret"
+
+
+def test_apprise_factory_clears_deferred_record_details_only_for_apprise(
+ restore_apprise_logging_state: logging.Logger,
+) -> None:
+ _ = NotificationService(outbound_allowed=True)
+ record = _make_sensitive_record(restore_apprise_logging_state)
+ restore_apprise_logging_state.handle(record)
+ _assert_record_is_sanitized(record)
+
+ control_record = logging.LogRecord(
+ "apprise_extra",
+ logging.WARNING,
+ __file__,
+ 1,
+ "Control detail %s",
+ ("unchanged",),
+ None,
+ )
+ logging.getLogger("apprise_extra").handle(control_record)
+ assert control_record.getMessage() == "Control detail unchanged"
+ assert control_record.args == ("unchanged",)
+
+
+def test_descendant_child_handler_sanitizes_record_before_render() -> None:
+ _ = NotificationService(outbound_allowed=True)
+ child_logger = logging.getLogger(DESCENDANT_LOGGER_NAME)
+ output = StringIO()
+ handler = logging.StreamHandler(output)
+ handler.setFormatter(
+ logging.Formatter("%(message)s\n%(exc_text)s\n%(stack_info)s")
+ )
+ child_logger.addHandler(handler)
+ child_logger.propagate = False
+
+ record = _make_sensitive_record(child_logger)
+ child_logger.handle(record)
+
+ _assert_record_is_sanitized(record)
+ rendered = output.getvalue()
+ assert GENERIC_APPRISE_DIAGNOSTIC in rendered
+
+
+def test_descendant_record_is_sanitized_before_parent_intercept_handler(
+ restore_apprise_logging_state: logging.Logger,
+) -> None:
+ _ = NotificationService(outbound_allowed=True)
+ child_logger = logging.getLogger(DESCENDANT_LOGGER_NAME)
+ output = StringIO()
+ sink_id = loguru_logger.add(output, format="{message}\n{exception}")
+ restore_apprise_logging_state.addHandler(InterceptHandler())
+ restore_apprise_logging_state.propagate = False
+ child_logger.propagate = True
+ try:
+ record = _make_sensitive_record(child_logger)
+ child_logger.handle(record)
+ finally:
+ loguru_logger.remove(sink_id)
+
+ _assert_record_is_sanitized(record)
+ rendered = output.getvalue()
+ assert GENERIC_APPRISE_DIAGNOSTIC in rendered
+
+
+def test_real_apprise_records_are_safe_for_stdlib_logcapture() -> None:
+ _ = NotificationService(outbound_allowed=True)
+
+ with LogCapture(level=logging.DEBUG, fmt="%(message)s") as captured:
+ for url in LEAKING_URLS:
+ assert apprise.Apprise().add(url) is False
+
+ assert isinstance(captured, StringIO)
+ output = captured.getvalue()
+ for secret in (BOT_TOKEN, "QuerySecret", "TargetSecret"):
+ assert secret not in output
+ assert set(output.splitlines()) == {GENERIC_APPRISE_DIAGNOSTIC}
+
+
+def test_real_intercept_handler_drops_apprise_exception_details(
+ restore_apprise_logging_state: logging.Logger,
+) -> None:
+ _ = NotificationService(outbound_allowed=True)
+ output = StringIO()
+ handler = InterceptHandler()
+ sink_id = loguru_logger.add(
+ output,
+ format="{message}\n{exception}",
+ level="DEBUG",
+ backtrace=True,
+ diagnose=False,
+ )
+ loguru_logger.enable("local_deep_research")
+ restore_apprise_logging_state.setLevel(logging.DEBUG)
+ restore_apprise_logging_state.propagate = False
+ restore_apprise_logging_state.addHandler(handler)
+
+ try:
+ for url in LEAKING_URLS:
+ assert apprise.Apprise().add(url) is False
+ try:
+ raise OSError("ExcInfoSecret")
+ except OSError:
+ restore_apprise_logging_state.exception(
+ "Apprise detail %s", "ArgsSecret"
+ )
+ finally:
+ restore_apprise_logging_state.removeHandler(handler)
+ loguru_logger.remove(sink_id)
+ loguru_logger.disable("local_deep_research")
+
+ rendered = output.getvalue()
+ for secret in (
+ BOT_TOKEN,
+ "QuerySecret",
+ "TargetSecret",
+ "ArgsSecret",
+ "ExcInfoSecret",
+ ):
+ assert secret not in rendered
+ assert GENERIC_APPRISE_DIAGNOSTIC in rendered
+ assert "Traceback" not in rendered
diff --git a/tests/notifications/test_tgram_notify_log_utils.py b/tests/notifications/test_tgram_notify_log_utils.py
new file mode 100644
index 0000000000..99bc228f30
--- /dev/null
+++ b/tests/notifications/test_tgram_notify_log_utils.py
@@ -0,0 +1,122 @@
+"""Notify-time redaction of Apprise Telegram token-bearing diagnostics.
+
+Apprise 1.12.0's Telegram plugin logs token-bearing POST URLs while
+notifying (``telegram.py`` builds ``https://api.telegram.org/bot<token>/...``
+and logs it in ``detect_bot_owner`` / the attachment path). The repo
+installs a sanitizing log-record factory
+(``notifications.apprise_log_utils``) that scrubs every ``apprise`` /
+``apprise.*`` record before any handler renders it; these tests prove
+both halves against the REAL notify path with the network mocked out.
+"""
+
+import logging
+from collections.abc import Generator
+from typing import List
+from unittest.mock import patch
+
+import pytest
+import requests
+
+from local_deep_research.notifications.apprise_log_utils import (
+ APPRISE_DIAGNOSTIC,
+)
+from local_deep_research.notifications.service import NotificationService
+
+TG_FAKE_CREDENTIAL = "123456789:AAexample_token" # obviously fake constant
+# Trigger path (chosen after reading apprise 1.12.0 telegram.py): a
+# TARGET-LESS tgram:// URL parses zero chat ids, so notify() falls back to
+# detect_owner -> detect_bot_owner(), which logs the token-bearing
+# "Telegram User Detection POST URL" diagnostic (debug) BEFORE its HTTP
+# POST — the most deterministic token-bearing path (no attachment file or
+# phone-style target needed). requests.post is mocked to raise so Apprise
+# emits its full diagnostics with zero network activity.
+TGRAM_URL = f"tgram://{TG_FAKE_CREDENTIAL}/"
+
+
+class _CapturingHandler(logging.Handler):
+ def __init__(self) -> None:
+ super().__init__(level=logging.DEBUG)
+ self.records: List[logging.LogRecord] = []
+
+ def emit(self, record: logging.LogRecord) -> None:
+ self.records.append(record)
+
+
[email protected](autouse=True)
+def _restore_apprise_logging_state() -> Generator[None, None, None]:
+ apprise_logger = logging.getLogger("apprise")
+ original_factory = logging.getLogRecordFactory()
+ logger_state = (
+ tuple(apprise_logger.filters),
+ tuple(apprise_logger.handlers),
+ apprise_logger.level,
+ apprise_logger.propagate,
+ )
+ yield
+ logging.setLogRecordFactory(original_factory)
+ apprise_logger.filters[:] = logger_state[0]
+ apprise_logger.handlers[:] = logger_state[1]
+ apprise_logger.setLevel(logger_state[2])
+ apprise_logger.propagate = logger_state[3]
+
+
+def _apprise_records_with_token(
+ records: List[logging.LogRecord],
+) -> List[logging.LogRecord]:
+ return [
+ record
+ for record in records
+ if record.name == "apprise" or record.name.startswith("apprise.")
+ if TG_FAKE_CREDENTIAL in record.getMessage()
+ or TG_FAKE_CREDENTIAL in str(record.args or ())
+ ]
+
+
+def test_notify_time_telegram_token_diagnostics_are_redacted() -> None:
+ # Constructing the service installs the sanitizing record factory the
+ # production send path uses (see NotificationService.__init__).
+ NotificationService(outbound_allowed=True)
+ sanitizing_factory = logging.getLogRecordFactory()
+
+ handler = _CapturingHandler()
+ apprise_logger = logging.getLogger("apprise")
+ apprise_logger.addHandler(handler)
+ apprise_logger.setLevel(logging.DEBUG)
+ apprise_logger.propagate = False
+
+ def _notify_and_collect() -> List[logging.LogRecord]:
+ handler.records.clear()
+ apprise_obj = NotificationService._new_apprise()
+ assert apprise_obj.add(TGRAM_URL) is True
+ with patch(
+ "apprise.plugins.telegram.requests.post",
+ side_effect=requests.RequestException("mocked network failure"),
+ ):
+ apprise_obj.notify(title="Test", body="Network-free body")
+ return list(handler.records)
+
+ # (a) Prove the diagnostic really fires and really carries the raw
+ # token in this scenario: temporarily replace the sanitizing factory
+ # with the default (unsanitized) LogRecord construction.
+ logging.setLogRecordFactory(
+ lambda *args, **kwargs: logging.LogRecord(*args, **kwargs)
+ )
+ try:
+ raw_pass = _notify_and_collect()
+ finally:
+ logging.setLogRecordFactory(sanitizing_factory)
+ assert _apprise_records_with_token(raw_pass), (
+ "expected the Telegram detect-owner diagnostic to carry the raw "
+ "bot token when the sanitizing factory is absent"
+ )
+
+ # (b) Production state: with the sanitizing factory installed, every
+ # captured record is free of the raw token (and Apprise records carry
+ # only the generic diagnostic).
+ sanitized_pass = _notify_and_collect()
+ assert sanitized_pass, "expected Apprise diagnostics during notify()"
+ assert not _apprise_records_with_token(sanitized_pass)
+ assert all(
+ record.msg == APPRISE_DIAGNOSTIC and record.args == ()
+ for record in sanitized_pass
+ )
diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.py
index 48a04707d7..7c5fa89b96 100644
--- a/tests/security/test_notification_validator.py
+++ b/tests/security/test_notification_validator.py
@@ -245,11 +245,19 @@ class TestValidateServiceUrl:
assert is_valid is True
assert error is None
- def test_telegram_scheme_valid(self):
- """Should accept telegram:// URLs."""
+ def test_telegram_scheme_rejected_as_unsupported(self):
is_valid, error = NotificationURLValidator.validate_service_url(
"telegram://bot_token/chat_id"
)
+ assert is_valid is False
+ assert "no longer supported" in error
+ assert "tgram://" in error
+
+ def test_tgram_scheme_valid(self):
+ """Should accept tgram:// URLs (regression for #5399)."""
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "tgram://123456789:Token_abc-123/987654321"
+ )
assert is_valid is True
assert error is None
@@ -563,7 +571,7 @@ class TestCloudMetadataBlockedForPluginSchemes:
for url in (
"discord://webhook_id/token",
"slack://TestApp@TokenA/TokenB/TokenC",
- "telegram://bottoken/ChatID",
+ "tgram://123456789:Token_abc-123/987654321",
"pushover://user@token",
"teams://group@token1/token2/token3",
):
@@ -859,7 +867,8 @@ class TestValidateMultipleUrls:
assert is_valid is False
assert "must have a protocol" in error
- assert "example.com" in error
+ assert "example.com" not in error
+ assert "typo.example.com" not in error
def test_one_invalid_url_fails_all(self):
"""Should fail if any URL is invalid."""
@@ -919,7 +928,8 @@ class TestClassConstants:
assert "https" in allowed
assert "discord" in allowed
assert "slack" in allowed
- assert "telegram" in allowed
+ assert "tgram" in allowed
+ assert "telegram" not in allowed
assert "mailto" in allowed
assert "ntfys" in allowed
assert "signal" in allowed
diff --git a/tests/security/test_tgram_notification_security.py b/tests/security/test_tgram_notification_security.py
new file mode 100644
index 0000000000..630813920d
--- /dev/null
+++ b/tests/security/test_tgram_notification_security.py
@@ -0,0 +1,213 @@
+import json
+from collections.abc import Generator
+from io import StringIO
+from unittest.mock import patch
+
+import apprise
+import pytest
+from loguru import logger as loguru_logger
+
+from local_deep_research.notifications.exceptions import ServiceError
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidator,
+)
+
+
+BOT_ID = "123456789"
+TOKEN_SECRET = "Token_abc-123"
+BOT_TOKEN = f"{BOT_ID}:{TOKEN_SECRET}"
+CHAT_ID = 987654321
+TARGET_ID = str(CHAT_ID)
+MALFORMED_TELEGRAM_URLS = (
+ f"tgram://bot{BOT_ID}:{TOKEN_SECRET}.evil/{TARGET_ID}",
+ f"tgram://bot{BOT_ID}%3A{TOKEN_SECRET}.evil/{TARGET_ID}",
+)
+SECRET_PARTS = (BOT_ID, TOKEN_SECRET, TARGET_ID)
+
+
+def loguru_output() -> Generator[StringIO, None, None]:
+ output = StringIO()
+ sink_id = loguru_logger.add(
+ output,
+ format="{message}",
+ level="DEBUG",
+ diagnose=False,
+ )
+ loguru_logger.enable("local_deep_research")
+ try:
+ yield output
+ finally:
+ loguru_logger.remove(sink_id)
+ loguru_logger.disable("local_deep_research")
+
+
+ "url",
+ (
+ f"tgram://{BOT_TOKEN}/{CHAT_ID}",
+ "tgram://bot123456789%3AToken_abc-123?detect=no",
+ f"tgram://{BOT_TOKEN}",
+ ),
+ ids=("literal-colon", "encoded-colon", "authority-only"),
+)
+def test_canonical_apprise_telegram_urls_validate_without_dns(url: str) -> None:
+ with patch(
+ "local_deep_research.security.notification_validator.socket.getaddrinfo"
+ ) as dns_lookup:
+ validation_result = NotificationURLValidator.validate_service_url(url)
+
+ apprise_result = apprise.Apprise().add(url)
+ alias_result = apprise.Apprise().add(
+ url.replace("tgram://", "telegram://", 1)
+ )
+
+ assert apprise_result is True
+ assert alias_result is False
+ assert validation_result == (True, None)
+ dns_lookup.assert_not_called()
+
+
+ "url",
+ (
+ "tgram://bot_token/chat_id",
+ "tgram://123456789/Token_abc-123/987654321",
+ "tgram://123456789::Token_abc-123/987654321",
+ "tgram://123456789%3A/987654321",
+ "tgram://user@123456789:Token_abc-123/987654321",
+ "tgram://123456789:Token_abc-123.evil/987654321",
+ "tgram://123456789:Token_abc-123#fragment",
+ ),
+)
+def test_noncanonical_apprise_telegram_authorities_are_rejected(
+ url: str,
+) -> None:
+ with patch(
+ "local_deep_research.security.notification_validator.socket.getaddrinfo"
+ ) as dns_lookup:
+ result = NotificationURLValidator.validate_service_url(url)
+
+ assert result == (
+ False,
+ "Invalid Telegram service URL; expected "
+ "tgram://<bot_id>:<token>/<chat_id>",
+ )
+ dns_lookup.assert_not_called()
+
+
+ "notification_url",
+ (
+ f"tgram://bot{BOT_TOKEN}/{CHAT_ID}",
+ "tgram://bot123456789%3AToken_abc-123/987654321",
+ ),
+ ids=("literal-colon", "encoded-colon"),
+)
+def test_real_apprise_telegram_notify_uses_only_the_pinned_endpoint(
+ notification_url: str,
+) -> None:
+ instance = apprise.Apprise()
+ assert instance.add(notification_url) is True
+
+ with patch("apprise.plugins.telegram.requests.post") as post:
+ post.return_value.status_code = 200
+
+ result = instance.notify(title="Test", body="Network-free message")
+
+ assert result is True
+ post.assert_called_once()
+ request_url = post.call_args.args[0]
+ payload = json.loads(post.call_args.kwargs["data"])
+ assert request_url == (
+ "https://api.telegram.org/bot123456789:Token_abc-123/sendMessage"
+ )
+ assert payload["chat_id"] == CHAT_ID
+ assert str(CHAT_ID) not in request_url
+
+
+ "service_url",
+ MALFORMED_TELEGRAM_URLS,
+ ids=("literal-colon", "encoded-colon"),
+)
+def test_validate_multiple_urls_omits_malformed_telegram_url(
+ service_url: str,
+) -> None:
+ is_valid, error = NotificationURLValidator.validate_multiple_urls(
+ service_url
+ )
+
+ assert is_valid is False
+ assert error is not None
+ for secret in SECRET_PARTS:
+ assert secret not in error
+ assert error == (
+ "Invalid notification service URL: Invalid Telegram service URL; "
+ "expected tgram://<bot_id>:<token>/<chat_id>"
+ )
+
+
+ "service_url",
+ MALFORMED_TELEGRAM_URLS,
+ ids=("literal-colon", "encoded-colon"),
+)
+def test_send_validation_failure_omits_malformed_telegram_url(
+ service_url: str,
+ loguru_output: StringIO,
+) -> None:
+ service = NotificationService(outbound_allowed=True)
+ with (
+ patch(
+ "apprise.plugins.telegram.requests.post",
+ side_effect=AssertionError("Telegram POST must not occur"),
+ ) as post,
+ pytest.raises(ServiceError) as raised,
+ ):
+ service.send(
+ title="Test",
+ body="Network-free message",
+ service_urls=service_url,
+ )
+
+ post.assert_not_called()
+ exception_text = str(raised.value)
+ output = loguru_output.getvalue()
+ for secret in SECRET_PARTS:
+ assert secret not in output
+ assert secret not in exception_text
+ assert "Service URL validation failed" in output
+ assert "Invalid Telegram service URL" in exception_text
+
+
+ "service_url",
+ MALFORMED_TELEGRAM_URLS,
+ ids=("literal-colon", "encoded-colon"),
+)
+def test_test_service_warning_omits_malformed_telegram_url(
+ service_url: str,
+ loguru_output: StringIO,
+) -> None:
+ service = NotificationService(outbound_allowed=True)
+ with patch(
+ "apprise.plugins.telegram.requests.post",
+ side_effect=AssertionError("Telegram POST must not occur"),
+ ) as post:
+ result = service.test_service(service_url)
+
+ post.assert_not_called()
+ assert result["success"] is False
+ user_error = result["error"]
+ assert isinstance(user_error, str)
+ output = loguru_output.getvalue()
+ for secret in SECRET_PARTS:
+ assert secret not in output
+ assert secret not in user_error
+ assert (
+ "Test service URL validation failed: Invalid Telegram service URL"
+ in output
+ )
+ assert "Invalid Telegram service URL" in user_error
diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.py
index d12f469c57..56dc74b794 100644
--- a/tests/web/services/test_notification_coverage.py
+++ b/tests/web/services/test_notification_coverage.py
@@ -120,7 +120,7 @@ class TestNotificationURLValidator:
"mailto://user:[email protected]",
"https://hooks.example.com/webhook",
"http://hooks.example.com/webhook",
- "telegram://bot_token/chat_id",
+ "tgram://123456789:Token_abc-123/987654321",
"gotify://gotify.example.com/token",
"pushover://user_key/token",
"ntfy://ntfy.sh/topic",
@@ -305,6 +305,48 @@ class TestNotificationService:
# Should not raise
NotificationService._validate_url("discord://id/token")
+ # -- _partition_urls (static) -----------------------------------------
+
+ def test_partition_urls_preserves_comma_inside_one_url(self):
+ # A multi-target Telegram URL keeps its ?to=id1,id2 query intact:
+ # the boundary split only separates at comma/whitespace followed
+ # by a scheme, matching the validator's partition.
+ strict, lenient = NotificationService._partition_urls(
+ "tgram://123456789:AAexample_token?to=111,222"
+ )
+ assert strict == []
+ assert lenient == ["tgram://123456789:AAexample_token?to=111,222"]
+
+ def test_partition_urls_splits_comma_separated_urls(self):
+ strict, lenient = NotificationService._partition_urls(
+ "tgram://123456789:AAexample_token/1,tgram://123456789:AAexample_token/2"
+ )
+ assert strict == []
+ assert lenient == [
+ "tgram://123456789:AAexample_token/1",
+ "tgram://123456789:AAexample_token/2",
+ ]
+
+ def test_partition_urls_splits_whitespace_separated_urls(self):
+ strict, lenient = NotificationService._partition_urls(
+ "discord://id/token tgram://123456789:AAexample_token/987"
+ )
+ assert strict == []
+ assert lenient == [
+ "discord://id/token",
+ "tgram://123456789:AAexample_token/987",
+ ]
+
+ def test_partition_urls_classifies_http_as_strict(self):
+ strict, lenient = NotificationService._partition_urls(
+ "https://webhook.example.com/a,http://webhook.example.com/b"
+ )
+ assert strict == [
+ "https://webhook.example.com/a",
+ "http://webhook.example.com/b",
+ ]
+ assert lenient == []
+
# -- get_service_type --------------------------------------------------
def test_get_service_type_known(self):