~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): harden Apprise notification destination validation (#5085)
LearningCircuitb67ddb681649
diff --git a/SECURITY.md b/SECURITY.mdindex 793abc95ed..2cb811a693 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -121,6 +121,8 @@ This window is closed at the socket layer for the delivery path. The deliverable- **Block-private send window.** For the duration of the send a thread-local **block-private** mode also refuses any *unpinned* lookup (a plugin scheme's endpoint) that resolves to a private/loopback/link-local/cloud-metadata address, at the `getaddrinfo` layer before any socket is opened. The check runs on the very resolution the client is about to connect to, so there is no residual race. That send-time resolution is bounded by a timeout so a slow / hostile DNS authority cannot hang the sending thread — a timeout fails closed (refuses the send). The bounded lookup runs on a short-lived daemon thread that is abandoned (not force-killed) on timeout, so a sustained hostile-DNS attack against an outbound-enabled instance can accumulate a small number of parked daemon threads (each blocked in libc `getaddrinfo`) before the send gives up; this is a bounded resource cost, not a bypass — the send is still refused.- **Per-scheme policy, matching the validator.** `http`/`https` block private + metadata unless the operator set `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true`; plugin and raw-webhook schemes (`json://`, `xml://`, `form://`, `discord://`, `ntfy://`, `gotify://`, …) allow private/LAN targets (self-hosted notifiers keep working) but **always** block cloud-metadata **and the entire link-local range** (IPv4 `169.254.0.0/16`, IPv6 `fe80::/10`) regardless of any operator flag. The link-local block matters because cloud-provider metadata lives across the whole link-local range, not just the always-blocked literals (e.g. Scaleway serves instance metadata at `169.254.42.42`), and no legitimate self-hosted notifier lives on link-local. It is scoped to the plugin/raw-webhook partition: RFC1918, CGNAT, loopback, and non-link-local IPv6 ULA self-hosted notifiers are unaffected, and `http`/`https` still treats link-local as operator-recoverable via `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS`. It is threaded end-to-end (a `block_link_local` flag on `is_ip_blocked` / `pinned_notification_send` and the validator's plugin-scheme IMDS guard) rather than changing `is_ip_blocked`'s default, so the general fetch/LLM paths keep their existing link-local-under-`allow_private_ips` behaviour. TLS is unaffected: only name resolution is redirected, so SNI and certificate verification still use the original hostname.- **Fail-closed invariants.** The send is refused (never sent unguarded) if the `getaddrinfo` shim is not the active resolver, or if the Apprise instance is not synchronous, or if a `tag` is supplied — any of which would let delivery fan out to worker threads the thread-local guards do not cover. A confirmed security block is **not retried**: the pin's connect-time rebind catch raises a non-retryable error directly, and a block-private window refusal (which Apprise swallows into a generic delivery failure) is recognised after the failed send via a thread-local marker and re-raised non-retryably — so a hostile / misconfigured destination fails fast in one attempt instead of being retried three times against a slow DNS authority. Invariant violations likewise fail fast.+- **Unsafe query options rejected before DNS or `Apprise.add()`.** Apprise query parameters can select a *second* destination or resource that the authority check above never sees. The validator rejects `template` (consumed by Discord/Slack/Workflows as an unrestricted `AppriseAttachment`, which reads local files — `?template=/etc/passwd` — or fetches remote URLs) and `redirect` (which would override the hardened asset setting), plus the mail-specific `smtp` (replaces the actual SMTP host), `pgppub`/`pgpkey`/`pgpprv` (unrestricted key-file attachments), and `wkd` (derives HTTPS fetches from a recipient-controlled domain). Key parsing mirrors Apprise's own `parse_qsd` semantics — `&` and `;` separators, `+`-as-space, one round of percent-decoding, lowercasing, and duplicate keys — so an encoded or semicolon-smuggled key cannot slip past the policy; a malformed percent escape in a key is rejected outright. `apprise>=1.12.0,<2` is declared with 1.12.0 as the reviewed floor, and a test diffs LDR's canonical keys against the *installed* Apprise parser so a future release that changes those semantics fails CI rather than silently opening a bypass.+- **Validation-time DNS is still fail-open.** A DNS error or five-second timeout at validation time is allowed (matching historical behavior), so Apprise may perform the first successful resolution at send time. That path is covered by the send-time pin and block-private window above, which are fail-closed.- **Thread-scoped.** The pin and the block are thread-local, so they only affect the sending thread and can never wrongly block a legitimate private request running concurrently elsewhere.#### How to enable notifications@@ -131,7 +133,10 @@ LDR_NOTIFICATIONS_ALLOW_OUTBOUND=trueBy 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://`, `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.+- **Prefer a fixed-destination mode when it fits the target.** Against Apprise 1.12.0 (the reviewed dependency floor), `discord://` and `slack://` send to fixed service endpoints after LDR rejects their secondary `template` resource. ntfy cloud mode (`ntfy://<topic>`) sends to `https://ntfy.sh`, and Matrix t2bot mode (`matrix://<64-character-token>`) sends to `https://webhooks.t2bot.io`. Their authority fields are tokens/topics, not send hosts, so authority DNS manipulation cannot redirect the notification.+ - **Destination behaviour is URL-mode-dependent.** `signal://`, `gotify://`, ntfy private mode (`ntfy://` or `ntfys://` with `<host>/<topic>?mode=private`), Matrix server/webhook mode, `json://`, `xml://`, and `form://` send to a user-supplied authority host. `mailto://` sends either to an authority subject to the same best-effort screening or to Apprise's fixed built-in SMTP mapping for a recognized provider; the user-controlled `smtp` override is rejected. These modes retain the DNS resolution window described above. Apprise may also translate recognized native `http(s)://` service URLs into plugins; the same query restrictions and redirect policy apply before conversion.+ - **Direct scheme-prefix gap.** LDR's allowlist names `tgram`, so direct Telegram URLs work. Apprise 1.12.0 registers `pover`, `workflow`/`workflows`, `mmost`/`mmosts`, and `rocket`/`rockets`, while LDR's direct-scheme allowlist still names `pushover`, `teams`, `mattermost`, and `rocketchat`. LDR performs no alias translation, so those four direct plugin prefixes do not overlap. Native service `http(s)://` URLs are a separate Apprise conversion path; see `docs/NOTIFICATIONS.md` and use the Test button rather than assuming a direct alias works.+ - **Validation-time screening is attempted for every allowed plugin scheme.** A non-literal authority gets exactly one lookup via `_resolve_hostname_ips` inside the Phase 1 plugin IMDS guard; successful answers are screened and any cloud-metadata result is blocked. A DNS failure or timeout is allowed. IP literals are checked directly with no resolver call. Token/topic modes receive the same attempted screening even though Apprise does not send to that authority. This does not close the host-bearing modes' DNS resolution window because Apprise resolves their host when sending.- **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/5085.security.md b/changelog.d/5085.security.mdnew file mode 100644index 0000000000..86db7da33b--- /dev/null+++ b/changelog.d/5085.security.md@@ -0,0 +1 @@+Notification URL validation now rejects Apprise query options that can select an unvalidated secondary destination or resource (`template`, `redirect`, and mail-specific SMTP/PGP/WKD options) before any hostname parsing or DNS lookup. A `template` option is an unrestricted Apprise attachment, so `discord://id/token?template=/etc/passwd` previously made the server read a local file and ship it to the user's webhook. Query-key parsing mirrors Apprise's own `parse_qsd` rules (`&` and `;` separators, `+`-as-space, percent-decoding, duplicate keys) so encoded or semicolon-separated names cannot bypass the policy, and a malformed percent escape in a key is rejected outright. The published dependency now declares `apprise>=1.12.0,<2` — 1.12.0 is the reviewed parser floor — and a test diffs LDR's canonical keys against the installed Apprise parser so the contract cannot drift silently. Notification security documentation and compatibility tests now cover mode-dependent destinations and the current direct scheme-prefix gaps.diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex 9792d37d9f..c45ff2adc9 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -18,9 +18,9 @@ The notification system uses [Apprise](https://github.com/caronc/apprise) to sup### Why?-Notification webhooks have a known **DNS-rebinding TOCTOU window** that cannot be closed in code: LDR validates the URL once when it is configured, but the underlying Apprise library resolves the hostname *again* at send time, and Apprise exposes no DNS/Session hook to pin the resolved IP. A logged-in user with a controllable domain can serve a public IP at validation and a private IP at send time, causing the LDR server to make outbound HTTP requests to its own internal services (e.g. `127.0.0.1:<internal-port>`) or the local network.+Notification webhooks have a known **DNS resolution TOCTOU window** that cannot be closed in code: immediately before a test or dispatch, LDR attempts one DNS lookup and screens successful answers, but allows a lookup failure or five-second timeout. The underlying Apprise library resolves the hostname at send time and exposes no DNS/Session hook to pin a validated IP. A logged-in user with a controllable domain can serve a public IP—or make the validation lookup fail—and then serve a private IP at send time, causing the LDR server to make outbound HTTP requests to its own internal services (e.g. `127.0.0.1:<internal-port>`) or the local network.-Because LDR is multi-user (per-user encrypted SQLCipher databases behind `@login_required`), the right default is to keep this feature off until the operator explicitly opts in — flipping the env var is the operator's acknowledgement of the residual risk. See [SECURITY.md](../SECURITY.md#notification-webhook-ssrf) for the full rationale and operator-side mitigations (prefer plugin schemes over raw `http(s)://`, restrict egress).+Because LDR is multi-user (per-user encrypted SQLCipher databases behind `@login_required`), the right default is to keep this feature off until the operator explicitly opts in — flipping the env var is the operator's acknowledgement of the residual risk. See [SECURITY.md](../SECURITY.md#notification-webhook-ssrf) for the full rationale and operator-side mitigations (prefer a fixed-destination notification mode when one fits, and restrict egress).### Symptoms when the gate is closed@@ -37,17 +37,19 @@ The "Send Test Notification" UI button returns the same message inline.## Supported Services-The system supports all services that Apprise supports, including but not limited to:+LDR accepts selected Apprise URL forms. Direct prefixes verified against Apprise 1.12.0 (the reviewed dependency floor) include:- Discord (via webhooks)- Slack (via webhooks)- Telegram (via Apprise's `tgram://` scheme)- Email (SMTP)-- Pushover- Gotify-- Many more...+- ntfy+- Signal+- Matrix+- Generic JSON, XML, and form webhooks-For a complete list, refer to the [Apprise documentation](https://github.com/caronc/apprise/wiki).+LDR does not currently accept every direct prefix registered by Apprise. Some native `http(s)://` service URLs may be converted by Apprise, but always use the Test button before relying on one. See the [direct scheme-prefix compatibility table](#webhook-url-was-rejected) below and the [Apprise documentation](https://github.com/caronc/apprise/wiki) for URL formats.## Configuration@@ -300,13 +302,32 @@ The "Test" button in the notifications settings page returns the validator's rea- **Note (cloud-metadata IPs)**: If `\<host\>` is a cloud-metadata IP (see the next bullet), the env-var hint above is intentionally **not** surfaced by the "Test" button — neither flag re-opens metadata, so the hint would mislead. The user-visible error is just the bare `"Blocked private/internal IP address: 169.254.169.254"`.**"Blocked cloud-metadata IP address: \<host\>"**-- **Cause**: The URL uses an Apprise plugin scheme (`discord://`, `signal://`, `ntfy://`, etc.) whose host resolves to a cloud-metadata endpoint. Plugin schemes bypass the http/https private-IP check (their endpoints are typically LAN-local) but still hit the absolute cloud-metadata block.+- **Cause**: An allowed Apprise plugin URL has an authority that is, or successfully resolves to, a cloud-metadata endpoint. A non-literal authority gets exactly one resolution attempt during the Phase 1 plugin IMDS guard; successful answers are screened, while a DNS failure or five-second timeout is allowed. An IP literal is checked directly without a DNS call. The guard runs for user-host modes (`signal://`, `gotify://`, ntfy private, Matrix server/webhook, `json://`, `xml://`, and `form://`), `mailto://`, and fixed-destination token/topic modes (`discord://`, `slack://`, ntfy cloud, and Matrix t2bot). Mail sends either to an authority subject to this best-effort screening or to Apprise's fixed built-in SMTP mapping for a recognized provider. In another fixed-destination mode the authority is only an opaque token/topic, but LDR still attempts the same screening consistently.- **Always blocked**: AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud, Tencent — both as plain IPv4 and wrapped through any NAT64 prefix. No env var re-opens these. See [SECURITY.md](../SECURITY.md#cloud-metadata-endpoint-block-list).- **Fix**: Choose a different webhook destination. Metadata endpoints expose IAM/instance credentials and are never legitimate webhook targets.**"Blocked unsafe protocol: \<scheme\>"** / **"Unsupported protocol: \<scheme\>"**-- **Cause**: The URL uses a scheme that is either denylisted (`file`, `ftp`, `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`, `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.+- **Cause**: The URL uses a scheme that is either denylisted (`file`, `ftp`, `ftps`, `data`, `javascript`, `vbscript`, `about`, `blob`) or not in LDR's URL-scheme allowlist.+- **Fix**: Use one of the schemes in LDR's URL-scheme allowlist — `http`, `https`, `mailto`, `discord`, `slack`, `tgram`, `gotify`, `pushover`, `ntfy`, `ntfys`, `signal`, `matrix`, `mattermost`, `rocketchat`, `teams`, `json`, `xml`, `form` — and verify it with the Test button. Against Apprise 1.12.0 (the reviewed dependency floor), direct `discord://` and `slack://` URLs use fixed service endpoints; LDR blocks their `template` option so it cannot fetch a second resource. ntfy cloud (`ntfy://<topic>`) and Matrix t2bot (`matrix://<64-character-token>`) are fixed-destination modes too. `signal://`, `gotify://`, ntfy private, Matrix server/webhook, `json://`, `xml://`, and `form://` use a user-supplied authority host. `mailto://` uses its authority or Apprise's fixed SMTP mapping for a recognized provider. The user-host cases retain the DNS-rebinding risk described in [SECURITY.md](../SECURITY.md#notification-webhook-ssrf).++ **Direct scheme-prefix gap (Apprise 1.12.0 floor vs LDR's URL-scheme allowlist).** Telegram is accepted under Apprise's own `tgram` prefix. Four other names in LDR's allowlist do not overlap the direct prefixes Apprise 1.12.0 registers, and LDR has no alias translation:++ | Service | LDR allowlist name | Apprise 1.12.0 direct prefix(es) | Direct prefix overlap? |+ | --- | --- | --- | --- |+ | Pushover | `pushover` | `pover` | no |+ | Microsoft Teams Workflows | `teams` | `workflow`, `workflows` | no |+ | Mattermost | `mattermost` | `mmost`, `mmosts` | no |+ | Rocket.Chat | `rocketchat` | `rocket`, `rockets` | no |++ For those four, a name LDR accepts (for example `pushover://`) is not the prefix Apprise registers, while the Apprise prefix (for example `pover://`) is outside LDR's allowlist. Apprise can separately recognize some native service `http(s)://` URLs and convert them to plugins, so this table does not claim that every integration is unavailable. The validator applies its blocked-query and no-redirect policy before that conversion. Always use the Test button before relying on a candidate URL.++**"Blocked unsafe notification parameter: \<name\>"**+- **Cause**: The URL contains an Apprise option that can bypass validation of the visible authority. LDR rejects `template` because Discord, Slack, and Workflows can use it to read a local file or fetch another URL; `redirect` because it would re-enable redirect-based SSRF; and, for `mailto://`, `smtp`, `pgppub`/`pgpkey`, `pgpprv`, and `wkd` because they can select another SMTP destination, key resource, or recipient-derived HTTPS request.+- **Fix**: Remove the option. Put a custom SMTP server in the `mailto://` authority instead of `?smtp=...`. Notification redirects and plugin-supplied template/PGP/WKD resources are intentionally unavailable; LDR's own notification body templates are unaffected.++**"Malformed percent-encoding in notification parameter name"**+- **Cause**: A query parameter name contains `%` without two hexadecimal digits. LDR rejects this before DNS resolution to avoid parser-version differences with Apprise.+- **Fix**: Correct or remove the malformed parameter name.**"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/pdm.lock b/pdm.lockindex d19cf45f94..2cefafabc6 100644--- a/pdm.lock+++ b/pdm.lock@@ -5,7 +5,7 @@groups = ["default", "dev", "mcp"]strategy = ["inherit_metadata"]lock_version = "4.5.1"-content_hash = "sha256:dac2f36404922fa05e7c1204161ad4b7a9f1968b8f25a07fa2783789dd99b413"+content_hash = "sha256:048e6e6ddb8c9cb186b21dd21ebe4a8788be840632e33361535cef042d3c9227"[[metadata.targets]]requires_python = ">=3.12,<3.15"diff --git a/pyproject.toml b/pyproject.tomlindex 9dd7c18ce0..6845afde19 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -102,7 +102,11 @@ dependencies = ["weasyprint~=68.1","Pillow>=12.1.1", # CVE-2026-25990: out-of-bounds write in PSD"cryptography>=50.0.0,<51", # GHSA-g6cj-pr64-35w5 (CVE-2026-69247): PKCS#7 EnvelopedData Bleichenbacher oracle; only fix is 50.0.0 (no 48.x/49.x backport). 50.0.0 also subsumes CVE-2026-26007, CVE-2026-39892, GHSA-537c-gmf6-5ccf. Absorbs 49.0.0/50.0.0 breaking changes (removed *_KEY_TYPES aliases, stricter X.509/DER) safely: codebase audit found zero first-party cryptography usage — only pyjwt[crypto] touches it transitively- "apprise~=1.9",+ # notification_validator mirrors Apprise's query parser as a security+ # boundary (see BLOCKED_APPRISE_QUERY_KEYS). 1.12.0 is the reviewed+ # floor: never resolve below it, and re-check the parser contract and+ # its tests before raising the ceiling.+ "apprise>=1.12.0,<2","markdown~=3.10","pypandoc-binary~=1.16","datasets~=4.5",diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex a775ec3f23..397563c66d 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -311,11 +311,10 @@ class NotificationManager:detail="notifications.service_url is not configured",)- # Egress policy: gate each parsed webhook URL against the- # user's scope. Apprise URLs can be Slack/Discord/SMTP/HTTP —- # we treat anything with a host as an HTTP egress and ask- # evaluate_url. Schemes without a hostname (e.g. mailto)- # pass through; SSRF + provider-side checks still apply.+ # Egress policy: classify raw HTTP(S) URLs with evaluate_url.+ # PRIVATE_ONLY refuses non-HTTP Apprise schemes because their+ # effective destinations cannot be classified reliably; other+ # scopes pass plugin schemes to the service's URL validator.allowed_urls = self._filter_urls_by_egress_policy(service_urls)if not allowed_urls:logger.bind(policy_audit=True).warning(@@ -456,18 +455,18 @@ class NotificationManager:)return ""- # Apprise accepts space- or comma- separated URLs. Apprise has- # its own non-http schemes (discord://, slack://, tgram://,- # mailto://, msteams://, ntfy://, ...) that dispatch to EXTERNAL- # vendor APIs. evaluate_url only understands http/https.+ # Apprise accepts space- or comma-separated URLs and has non-HTTP+ # schemes (discord://, slack://, tgram://, mailto://, msteams://,+ # ntfy://, ...) whose effective destination may be a fixed provider,+ # a user-supplied authority, or a provider mapping. evaluate_url only+ # understands HTTP(S), so it cannot classify those modes reliably.#- # Under PRIVATE_ONLY ("nothing leaves the box") we cannot verify a- # vendor token resolves to a local endpoint, so a non-http scheme is- # refused — fail closed. A self-hosted notifier (local ntfy, SMTP)- # should be addressed by its http(s):// URL, which evaluate_url then- # allows as a private host. Under the other scopes the prior- # pass-through stands (the modeled threat there is internal-http- # SSRF via a raw webhook, not vendor APIs).+ # Under PRIVATE_ONLY ("nothing leaves the box"), a non-HTTP scheme is+ # therefore refused — fail closed. Services that expose a raw HTTP(S) webhook+ # can use that URL and be classified by evaluate_url; Apprise SMTP and+ # other plugin URLs remain unavailable under PRIVATE_ONLY. Under the+ # other scopes the prior pass-through stands (the modeled threat there+ # is internal-http SSRF via a raw webhook, not vendor APIs).parts = []for url_entry in url_entries:scheme = (diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex f9e894979f..a3c6481981 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -10,7 +10,7 @@ import reimport socketfrom concurrent.futures import ThreadPoolExecutor, TimeoutErrorfrom typing import ClassVar, List, Optional, Tuple, Union-from urllib.parse import urlparse+from urllib.parse import unquote, urlparsefrom loguru import loggerfrom urllib3.exceptions import LocationParseError@@ -119,6 +119,23 @@ class NotificationURLValidator:"form", # Form-encoded webhooks)+ # Apprise query parameters that can select a second outbound destination+ # or resource independently of the URL authority screened below.+ #+ # ``template`` is consumed by Discord/Slack/Workflows (including native+ # HTTPS webhook URLs that Apprise converts to those plugins) as an+ # unrestricted AppriseAttachment, which can read local files or fetch+ # remote URLs. ``redirect`` overrides the hardened AppriseAsset setting+ # used by the notification service and would re-enable redirect-based SSRF.+ BLOCKED_APPRISE_QUERY_KEYS = frozenset(("redirect", "template"))++ # mailto-specific secondary egress/resource selectors. ``smtp`` replaces+ # the actual SMTP host; PGP key paths are unrestricted attachments; and+ # WKD derives HTTPS fetches from recipient-controlled domains.+ BLOCKED_MAILTO_QUERY_KEYS = frozenset(+ ("smtp", "pgppub", "pgpkey", "pgpprv", "wkd")+ )+# Schemes whose authority identifies a network destination. Token-style# schemes such as discord and slack deliberately do not belong here.HOST_BEARING_PLUGIN_SCHEMES: ClassVar[frozenset[str]] = frozenset(@@ -239,6 +256,11 @@ class NotificationURLValidator:# plugin schemes (discord://, slack://, ntfy://, ntfys://, gotify://,# tgram://, mattermost://, etc.) that hardcode their endpoints.#+ # Plugin schemes are not categorically exempt from authority+ # validation: some have hardcoded destinations (Discord, Slack,+ # Teams Workflows), some send against the URL authority (Signal,+ # Gotify, generic webhooks), and ntfy/Matrix are mode-dependent.+ ## concurrent.futures for thread-safe timeout instead of# socket.setdefaulttimeout() which is process-global.try:@@ -355,6 +377,85 @@ class NotificationURLValidator:hostname = hostname.rstrip(".")return hostname or ""+ @staticmethod+ def _apprise_query_keys(url: str) -> Tuple[List[str], bool]:+ """Return canonical query keys using Apprise 1.12 semantics.++ Apprise splits pairs on both ``&`` and ``;``, preserves a leading+ ``+`` key namespace marker, converts later ``+`` characters to spaces,+ percent-decodes once, then lowercases and strips the key. Its URL+ parser also treats everything after the first ``?`` as query data,+ including text that ``urllib.parse`` would classify as a fragment.++ The boolean reports malformed percent escapes in a key. Values are+ intentionally neither decoded nor returned: they can contain secrets,+ file paths, and alternate destinations and are irrelevant to policy.+ """+ query_at = url.find("?")+ if query_at < 0:+ return [], False++ raw_query = url[query_at + 1 :]+ keys = []+ hex_digits = "0123456789abcdefABCDEF"++ for amp_pair in raw_query.split("&"):+ for pair in amp_pair.split(";"):+ raw_key = pair.split("=", 1)[0]++ index = 0+ while index < len(raw_key):+ if raw_key[index] != "%":+ index += 1+ continue+ if (+ index + 2 >= len(raw_key)+ or raw_key[index + 1] not in hex_digits+ or raw_key[index + 2] not in hex_digits+ ):+ return keys, True+ index += 3++ apprise_key = (+ raw_key[:1] + raw_key[1:].replace("+", " ")+ if raw_key+ else ""+ )+ keys.append(unquote(apprise_key).lower().strip())++ return keys, False++ @staticmethod+ def _validate_apprise_query_policy(url: str, scheme: str) -> Optional[str]:+ """Reject Apprise query options that bypass destination validation."""+ keys, malformed = NotificationURLValidator._apprise_query_keys(url)+ if malformed:+ logger.warning(+ "Blocked notification URL with malformed percent-encoding "+ "in a query parameter name"+ )+ return "Malformed percent-encoding in notification parameter name"++ blocked_keys = NotificationURLValidator.BLOCKED_APPRISE_QUERY_KEYS+ if scheme == "mailto":+ blocked_keys = (+ blocked_keys+ | NotificationURLValidator.BLOCKED_MAILTO_QUERY_KEYS+ )++ for key in keys:+ if key in blocked_keys:+ # Never log the value: it may contain a token, local path, or+ # alternate destination selected by an attacker.+ logger.warning(+ "Blocked unsafe notification parameter {} for {} URL",+ key,+ scheme,+ )+ return f"Blocked unsafe notification parameter: {key}"++ return None+@staticmethoddef _is_private_ip(hostname: str,@@ -542,6 +643,16 @@ class NotificationURLValidator:f"Allowed: {', '.join(NotificationURLValidator.ALLOWED_SCHEMES[:5])}...",)+ # Apprise supports query parameters that can select resources or+ # outbound destinations independently of the authority we validate+ # below. Enforce this deterministic policy before parsing the host or+ # performing any attacker-controlled DNS lookup.+ query_error = NotificationURLValidator._validate_apprise_query_policy(+ url, scheme+ )+ if query_error:+ return False, query_error+# Reject authorities with more than one "@" (fail closed). urllib3's# parse_url (which the SSRF host-check + the DNS pin validate against)# and Apprise's own parse_url disagree on which host a multi-"@"@@ -628,16 +739,16 @@ class NotificationURLValidator:# operator ``allow_private_ips`` opt-in. RFC1918 / loopback# are allowed through with the flag, but cloud-metadata and# NAT64-wrapped metadata always block.- # - Apprise plugin schemes (discord, slack, signal, gotify,- # ntfy/ntfys, mattermost, rocketchat, matrix, teams, mailto,- # json, xml, form): private-IP reachability is intentionally- # allowed (these are typically self-hosted on a LAN), but the- # absolute cloud-metadata block still applies. Apprise- # translates these to HTTP requests against the URL host- # (e.g. ``signal://169.254.169.254/...`` → ``POST- # http://169.254.169.254/v2/send``), so without this guard- # the plugin schemes would bypass the IMDS protection that- # http/https has.+ # - Apprise plugin schemes: private-IP authority values are+ # intentionally allowed for self-hosted modes, but the absolute+ # cloud-metadata block still applies. Some modes send against the+ # authority (for example Signal and ntfy private); fixed-destination+ # modes such as Discord, Slack, ntfy cloud, and Matrix t2bot treat it+ # as a token/topic instead. Mail can use its authority or a fixed+ # provider mapping. Screening every authority uniformly prevents+ # host-bearing modes from bypassing the IMDS protection without+ # incorrectly claiming every authority is the network destination.+ # Secondary resource/destination parameters were rejected above.try:u3 = parse_url(url)except LocationParseError:diff --git a/tests/notifications/test_notification_webhook_dns_pin.py b/tests/notifications/test_notification_webhook_dns_pin.pyindex cdcbdb7bc0..6fe092f97f 100644--- a/tests/notifications/test_notification_webhook_dns_pin.py+++ b/tests/notifications/test_notification_webhook_dns_pin.py@@ -40,6 +40,9 @@ from cryptography.x509.oid import NameOIDfrom local_deep_research.notifications.exceptions import SendError, ServiceErrorfrom local_deep_research.notifications.service import NotificationServicefrom local_deep_research.security import dns_pinning+from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+)# --------------------------------------------------------------------------@@ -454,15 +457,49 @@ def test_redirect_following_disabled_by_default():target_server.shutdown()+def test_redirect_param_is_rejected_by_url_validation():+ """OUTER layer: a user-supplied ``?redirect=yes`` never reaches Apprise.++ ``NotificationURLValidator`` rejects the ``redirect`` query key outright+ (it is one of ``BLOCKED_APPRISE_QUERY_KEYS``), so ``send()`` raises before+ ``Apprise.add()`` and no request is made at all. The INNER backstop — the+ per-plugin redirect re-force that would neutralize the option had it got+ through — is exercised separately below.+ """+ hook_server, hook_port, hook_hits = _start_server(+ redirect_to="http://redir-target.example:1/pwn"+ )+ try:+ with pytest.raises(ServiceError, match="redirect"):+ _service().send(+ title="t",+ body="b",+ service_urls=(+ f"json://public.example:{hook_port}/hook?redirect=yes"+ ),+ )+ assert not hook_hits, (+ "the rejected URL still reached the webhook host; validation "+ "must fail before Apprise.add()"+ )+ finally:+ hook_server.shutdown()++def test_redirect_param_yes_cannot_reenable_redirects():- """Airtight redirect-disable: a user-supplied ``?redirect=yes`` on the- webhook URL would, via Apprise's per-URL override, normally re-enable- redirect-following even when the asset default is off. The per-plugin- re-force (``NotificationService._disable_redirects``) neutralizes it, so- the redirect is STILL not followed. The redirect target is again a- loopback stand-in that the block-private window does not itself block, so- this isolates the re-force (deleting it makes the redirect follow through- to the target server and this test fail)."""+ """INNER backstop: even if a ``?redirect=yes`` URL somehow reached+ Apprise, the per-plugin re-force (``NotificationService._disable_redirects``)+ keeps redirect-following off.++ Via Apprise's per-URL override, ``?redirect=yes`` would normally re-enable+ redirect-following even when the asset default is off. URL validation now+ rejects that key up-front (see the test above), so this test deliberately+ stubs out the outer validation layer to isolate the inner one — deleting+ the re-force makes the redirect follow through to the target server and+ this test fail. Both layers are kept: the validator is the primary+ defence, and the re-force still covers any future path that constructs an+ Apprise client from an unvalidated URL.+ """target_server, target_port, target_hits = _start_server()hook_server, hook_port, hook_hits = _start_server(redirect_to=f"http://redir-target.example:{target_port}/pwn"@@ -474,17 +511,22 @@ def test_redirect_param_yes_cannot_reenable_redirects():})try:- with patch.object(dns_pinning, "_real_getaddrinfo", resolver):- with _connect_spy() as targets:- with pytest.raises(SendError):- _service().send(- title="t",- body="b",- service_urls=(- f"json://public.example:{hook_port}"- "/hook?redirect=yes"- ),- )+ with patch.object(+ NotificationURLValidator,+ "validate_multiple_urls",+ staticmethod(lambda *args, **kwargs: (True, None)),+ ):+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):+ with _connect_spy() as targets:+ with pytest.raises(SendError):+ _service().send(+ title="t",+ body="b",+ service_urls=(+ f"json://public.example:{hook_port}"+ "/hook?redirect=yes"+ ),+ )assert hook_hits, "initial request to the webhook host never happened"assert not target_hits, ("?redirect=yes re-enabled redirect-following "diff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.pyindex c3b93b2951..b24ad27119 100644--- a/tests/notifications/test_service.py+++ b/tests/notifications/test_service.py@@ -17,15 +17,23 @@ from local_deep_research.notifications.exceptions import (SendError,ServiceError,)+from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+)class TestNotificationServiceInit:"""Tests for NotificationService initialization."""- def test_init_creates_apprise_instance(self):+ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_init_creates_hardened_apprise_instance(self, mock_apprise_class):"""Test initialization creates Apprise instance."""service = NotificationService(outbound_allowed=True)assert service.apprise is not None+ mock_apprise_class.assert_called_once()+ assert (+ mock_apprise_class.call_args.kwargs["asset"].http_redirects is False+ )class TestSendOutboundGate:@@ -41,7 +49,7 @@ class TestSendOutboundGate:def test_send_returns_false_when_outbound_disallowed(self, mock_apprise_class):- """send() must bail out before constructing/calling Apprise."""+ """send() must bail out before adding a service or notifying."""mock_apprise_instance = MagicMock()mock_apprise_class.return_value = mock_apprise_instance@@ -75,6 +83,74 @@ class TestSendOutboundGate:assert result is Trueassert mock_apprise_instance.notify.call_count == 1+ assert mock_apprise_class.call_count == 2+ assert all(+ call.kwargs["asset"].http_redirects is False+ for call in mock_apprise_class.call_args_list+ )++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_rejects_template_before_apprise_add(self, mock_apprise_class):+ mock_apprise_instance = MagicMock()+ mock_apprise_class.return_value = mock_apprise_instance+ service = NotificationService(outbound_allowed=True)++ with pytest.raises(+ ServiceError,+ match="Blocked unsafe notification parameter: template",+ ):+ service.send(+ title="t",+ body="b",+ service_urls=(+ "discord://123456789012345678/token"+ "?template=file%3A%2F%2F%2Fetc%2Fpasswd"+ ),+ )++ assert mock_apprise_class.call_count == 1+ mock_apprise_instance.add.assert_not_called()++ @pytest.mark.parametrize(+ ("url", "blocked_key"),+ [+ pytest.param(+ "https://discord.com/api/webhooks/123456789012345678/token"+ "?template=file%3A%2F%2F%2Fetc%2Fpasswd",+ "template",+ id="native-discord-template",+ ),+ pytest.param(+ "https://hooks.example.com/path?redirect=yes",+ "redirect",+ id="native-https-redirect",+ ),+ ],+ )+ def test_send_rejects_unsafe_native_https_option_before_dns_and_add(+ self, url, blocked_key+ ):+ with patch(+ "local_deep_research.notifications.service.apprise.Apprise"+ ) as mock_apprise_class:+ mock_apprise_instance = MagicMock()+ mock_apprise_class.return_value = mock_apprise_instance+ service = NotificationService(outbound_allowed=True)++ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as resolver:+ with pytest.raises(+ ServiceError,+ match=(+ "Blocked unsafe notification parameter: " + blocked_key+ ),+ ):+ service.send(title="t", body="b", service_urls=url)++ resolver.assert_not_called()+ assert mock_apprise_class.call_count == 1+ mock_apprise_instance.add.assert_not_called()class TestSendWithTenacity:@@ -279,6 +355,31 @@ class TestTestService:assert "message" in result# Verify test notification was sentmock_apprise_instance.notify.assert_called_once()+ assert mock_apprise_class.call_count == 2+ assert all(+ call.kwargs["asset"].http_redirects is False+ for call in mock_apprise_class.call_args_list+ )++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_test_service_rejects_template_before_apprise_add(+ self, mock_apprise_class+ ):+ mock_apprise_instance = MagicMock()+ mock_apprise_class.return_value = mock_apprise_instance+ service = NotificationService(outbound_allowed=True)++ result = service.test_service(+ "slack://T00000000/B00000000/token"+ "?template=http%3A%2F%2F169.254.169.254%2Fmetadata"+ )++ assert result == {+ "success": False,+ "error": "Blocked unsafe notification parameter: template",+ }+ assert mock_apprise_class.call_count == 1+ mock_apprise_instance.add.assert_not_called()def test_test_service_exception(self):"""Test service test handles exceptions."""diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.pyindex 7c5fa89b96..eff927e9ff 100644--- a/tests/security/test_notification_validator.py+++ b/tests/security/test_notification_validator.py@@ -494,12 +494,10 @@ class TestCloudMetadataBlockedForPluginSchemes:"100.100.100.200", # AlibabaCloud)- # Plugin schemes that resolve a user-supplied host into an outbound- # HTTP request under Apprise. (Schemes whose "host" slot holds an- # opaque token — discord, slack, telegram, pushover, teams — are- # covered by the existing positive tests; an IP-shaped token would- # still trip this guard, which is fine.)- HOST_BEARING_SCHEMES = (+ # Allowed plugin-shaped authorities used to exercise the validator's+ # uniform IMDS policy. This is a validator allowlist fixture, not a claim+ # that locked Apprise registers every listed name as a direct prefix.+ PLUGIN_AUTHORITY_FIXTURES = ("signal","gotify","ntfy",@@ -513,7 +511,7 @@ class TestCloudMetadataBlockedForPluginSchemes:)@pytest.mark.parametrize("ip", METADATA_IPS)- @pytest.mark.parametrize("scheme", HOST_BEARING_SCHEMES)+ @pytest.mark.parametrize("scheme", PLUGIN_AUTHORITY_FIXTURES)def test_metadata_ip_blocked_by_default(self, scheme, ip):url = f"{scheme}://{ip}/path"is_valid, error = NotificationURLValidator.validate_service_url(url)@@ -521,7 +519,7 @@ class TestCloudMetadataBlockedForPluginSchemes:assert "cloud-metadata" in error.lower()@pytest.mark.parametrize("ip", METADATA_IPS)- @pytest.mark.parametrize("scheme", HOST_BEARING_SCHEMES)+ @pytest.mark.parametrize("scheme", PLUGIN_AUTHORITY_FIXTURES)def test_metadata_ip_blocked_even_with_allow_private_ips(self, scheme, ip):"""allow_private_ips=True unlocks LAN reach, NOT IMDS."""url = f"{scheme}://{ip}/path"@@ -564,10 +562,13 @@ class TestCloudMetadataBlockedForPluginSchemes:assert is_valid is Trueassert error is None- def test_plugin_scheme_token_host_unaffected(self):- """Schemes whose 'host' slot is an opaque token (discord, slack,- telegram, pushover, teams) keep working — the IMDS check is a- no-op against non-IP strings."""+ def test_allowlisted_token_shaped_urls_pass_validator(self):+ """Non-IP authority values pass the validator's IMDS check.++ This tests validation policy only. Direct-prefix compatibility with+ locked Apprise is asserted separately; several legacy LDR names do+ not overlap Apprise's registered prefixes.+ """for url in ("discord://webhook_id/token","slack://TestApp@TokenA/TokenB/TokenC",@@ -601,6 +602,181 @@ class TestCloudMetadataBlockedForPluginSchemes:assert "cloud-metadata" in error.lower()+class TestAppriseSecondaryDestinationPolicy:+ """Apprise options must not bypass validation of the URL authority."""++ @pytest.mark.parametrize(+ ("url", "blocked_key"),+ [+ pytest.param(+ "discord://123456789012345678/token"+ "?template=file%3A%2F%2F%2Fetc%2Fpasswd",+ "template",+ id="discord-local-template",+ ),+ pytest.param(+ "slack://T00000000/B00000000/token"+ "?template=http%3A%2F%2F169.254.169.254%2Fmetadata",+ "template",+ id="slack-remote-template",+ ),+ pytest.param(+ "https://discord.com/api/webhooks/123456789012345678/token"+ "?template=file%3A%2F%2F%2Fetc%2Fpasswd",+ "template",+ id="native-https-template",+ ),+ pytest.param(+ "https://example.com/hook?redirect=yes",+ "redirect",+ id="https-redirect-override",+ ),+ pytest.param(+ "signal://signal.example.com/source/destination?redirect=yes",+ "redirect",+ id="plugin-redirect-override",+ ),+ pytest.param(+ "mailto://sender:[email protected]/[email protected]"+ "?smtp=smtp-alt.example.com",+ "smtp",+ id="mailto-smtp-override",+ ),+ pytest.param(+ "mailto://sender:[email protected]/[email protected]"+ "?pgppub=http%3A%2F%2Fkeys.example.com%2Fpublic.asc",+ "pgppub",+ id="mailto-public-key-resource",+ ),+ pytest.param(+ "mailto://sender:[email protected]/[email protected]"+ "?pgpkey=file%3A%2F%2F%2Ftmp%2Fpublic.asc",+ "pgpkey",+ id="mailto-legacy-key-resource",+ ),+ pytest.param(+ "mailto://sender:[email protected]/[email protected]"+ "?pgpprv=file%3A%2F%2F%2Ftmp%2Fprivate.asc",+ "pgpprv",+ id="mailto-private-key-resource",+ ),+ pytest.param(+ "mailto://sender:[email protected]/[email protected]"+ "?wkd=yes",+ "wkd",+ id="mailto-recipient-wkd-fetch",+ ),+ ],+ )+ def test_secondary_destination_or_resource_is_rejected_before_dns(+ self, url, blocked_key+ ):+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as resolver:+ result = NotificationURLValidator.validate_service_url_with_hint(+ url+ )++ assert result == (+ False,+ f"Blocked unsafe notification parameter: {blocked_key}",+ False,+ )+ resolver.assert_not_called()++ @pytest.mark.parametrize(+ ("url", "blocked_key"),+ [+ pytest.param(+ "discord://id/token?TemPlate=file%3A%2F%2F%2Ftmp%2Fx",+ "template",+ id="mixed-case",+ ),+ pytest.param(+ "discord://id/token?%74emplate=file%3A%2F%2F%2Ftmp%2Fx",+ "template",+ id="encoded-key",+ ),+ pytest.param(+ "discord://id/token?footer=yes;%74emplate=file%3A%2F%2F%2Fx",+ "template",+ id="semicolon-separator",+ ),+ pytest.param(+ "discord://id/token?footer=yes#fragment&template=file%3A%2F%2Fx",+ "template",+ id="query-text-after-fragment-marker",+ ),+ pytest.param(+ "discord://id/token?template=&template=file%3A%2F%2F%2Fx",+ "template",+ id="duplicate-blocked-key",+ ),+ pytest.param(+ "discord://id/token?%20template%20=file%3A%2F%2F%2Fx",+ "template",+ id="encoded-surrounding-space",+ ),+ pytest.param(+ "mailto://user:[email protected]?mode=starttls;%73mtp=host",+ "smtp",+ id="encoded-mailto-key-after-semicolon",+ ),+ ],+ )+ def test_query_key_parser_matches_apprise(self, url, blocked_key):+ from apprise.utils.parse import parse_qsd++ raw_query = url.split("?", 1)[1]+ ldr_keys, malformed = NotificationURLValidator._apprise_query_keys(url)+ apprise_keys = set(parse_qsd(raw_query)["qsd"])++ assert malformed is False+ assert set(ldr_keys) == apprise_keys+ assert blocked_key in apprise_keys++ is_valid, error = NotificationURLValidator.validate_service_url(url)++ assert is_valid is False+ assert error == f"Blocked unsafe notification parameter: {blocked_key}"++ def test_malformed_percent_escape_in_query_key_is_rejected_before_dns(self):+ with patch.object(+ NotificationURLValidator, "_resolve_hostname_ips"+ ) as resolver:+ result = NotificationURLValidator.validate_service_url_with_hint(+ "discord://id/token?bad%=value"+ )++ assert result == (+ False,+ "Malformed percent-encoding in notification parameter name",+ False,+ )+ resolver.assert_not_called()++ @pytest.mark.parametrize(+ "url",+ [+ "https://93.184.216.34/hook?event=complete&redirect_uri=/done",+ "discord://93.184.216.34/token?footer=yes&tts=no",+ "discord://93.184.216.34/token?template_id=standard",+ "discord://93.184.216.34/token?+template=custom-token",+ "discord://93.184.216.34/token?-template=forwarded-value",+ "discord://93.184.216.34/token?:template=header-value",+ "mailto://user:[email protected]?mode=starttls",+ "ntfy://93.184.216.34/topic?mode=private&priority=high",+ "matrix://user:[email protected]/%23room?mode=matrix",+ ],+ )+ def test_benign_query_parameters_remain_allowed(self, url):+ is_valid, error = NotificationURLValidator.validate_service_url(url)++ assert is_valid is True+ assert error is None++class TestLinkLocalBlockedForPluginSchemes:"""Plugin-scheme link-local guard (metadata beyond the always-blockedliterals).diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.pyindex c56a695973..d05f273407 100644--- a/tests/web/services/test_notification_coverage.py+++ b/tests/web/services/test_notification_coverage.py@@ -13,11 +13,14 @@ Covers:- Exception hierarchy"""+import importlib.metadataimport ipaddressimport threading+import tomllibfrom collections import dequefrom datetime import datetime, timedelta, timezone-from unittest.mock import patch+from pathlib import Path+from unittest.mock import Mock, patchimport pytest@@ -271,6 +274,324 @@ class TestNotificationURLValidator:)+# ===================================================================+# Apprise plugin compatibility, destination, and DNS contract+# ===================================================================+++class TestPluginSchemeDNSContract:+ """Pin Apprise 1.12 compatibility, destinations, and DNS screening.++ Destination behaviour is URL-mode-dependent. Discord and Slack use fixed+ service endpoints after LDR rejects their secondary ``template`` resource.+ ntfy cloud and Matrix t2bot modes are also fixed-endpoint modes, while ntfy+ private, Matrix server/webhook, Signal, Gotify, and generic plugins send to+ the authority host. LDR attempts one metadata-screening DNS lookup for+ every non-literal plugin authority, including opaque tokens; successful+ answers are screened, while DNS failure or timeout is allowed.+ """++ # Reviewed floor, not an exact pin: pyproject declares+ # ``apprise>=1.12.0,<2`` and the lock resolves at or above it. The+ # BEHAVIOURAL contract is enforced separately (and more strongly) by+ # ``test_query_key_parser_matches_apprise``, which diffs LDR's canonical+ # query keys against the INSTALLED ``apprise.utils.parse.parse_qsd`` —+ # so a future Apprise that changes those semantics fails CI regardless+ # of what the version string says.+ MIN_APPRISE_VERSION = "1.12.0"+ MATRIX_TOKEN = "a" * 64+ DNS_FIXTURES = (+ (+ "signal://signal-api.example.com:8739/+15551234567/+15557654321",+ "signal-api.example.com",+ ),+ ("ntfy://topic", "topic"),+ (+ "ntfy://ntfy.example.com/topic?mode=private",+ "ntfy.example.com",+ ),+ ("matrix://" + MATRIX_TOKEN, MATRIX_TOKEN),+ (+ "matrix://user:[email protected]/%23room?mode=matrix",+ "matrix.example.com",+ ),+ )++ def test_apprise_security_contract_matches_metadata_lock_and_runtime(self):+ lock_path = Path(__file__).resolve().parents[3] / "pdm.lock"+ project_path = lock_path.with_name("pyproject.toml")+ with lock_path.open("rb") as lock_file:+ lock_data = tomllib.load(lock_file)+ with project_path.open("rb") as project_file:+ project_data = tomllib.load(project_file)++ locked_versions = [+ package["version"]+ for package in lock_data["package"]+ if package["name"] == "apprise"+ ]+ declared_requirements = [+ dependency+ for dependency in project_data["project"]["dependencies"]+ if dependency.lower().startswith("apprise")+ ]++ assert declared_requirements == [+ f"apprise>={self.MIN_APPRISE_VERSION},<2"+ ], (+ "pyproject.toml must declare the reviewed Apprise floor so the "+ "mirrored query-key parser cannot be resolved against an older, "+ "unreviewed Apprise"+ )++ # The floor is the contract, enforced on all three legs: the+ # published dependency (pyproject.toml), the resolved lockfile+ # (pdm.lock), and the installed runtime. It is a floor rather than an+ # exact pin because the dependency-update bot legitimately moves the+ # lock forward and CI installs into a container whose resolver/base+ # layer may surface a forward-compatible build; a hard equality would+ # fail the suite for drift that is not a contract regression. A+ # downgrade below the reviewed floor still fails loudly.+ def _release(version_string):+ parts = []+ for token in version_string.split("."):+ digits = ""+ for char in token:+ if char.isdigit():+ digits += char+ else:+ break+ parts.append(int(digits) if digits else 0)+ return tuple(parts)++ assert locked_versions and all(+ _release(version) >= _release(self.MIN_APPRISE_VERSION)+ for version in locked_versions+ ), (+ f"Locked apprise {locked_versions} is older than the reviewed "+ f"floor {self.MIN_APPRISE_VERSION}"+ )++ runtime_version = importlib.metadata.version("apprise")+ assert _release(runtime_version) >= _release(+ self.MIN_APPRISE_VERSION+ ), (+ "Installed apprise "+ f"{runtime_version} is older than the reviewed floor "+ f"{self.MIN_APPRISE_VERSION}"+ )++ @pytest.mark.parametrize(+ ("url", "attachment_type"),+ [+ pytest.param(+ "discord://123456789012345678/token"+ "?template=file%3A%2F%2F%2Fetc%2Fpasswd",+ "AttachFile",+ id="discord-file-template",+ ),+ pytest.param(+ "slack://T00000000/B00000000/token"+ "?template=http%3A%2F%2F169.254.169.254%2Fmetadata",+ "AttachHTTP",+ id="slack-http-template",+ ),+ ],+ )+ @pytest.mark.filterwarnings(+ "ignore:'imghdr' is deprecated.*:DeprecationWarning"+ )+ def test_unsafe_template_is_a_real_apprise_secondary_resource(+ self, url, attachment_type+ ):+ """Keep the denylist tied to the locked dependency's behavior."""+ from apprise import Apprise++ apprise_instance = Apprise()+ assert apprise_instance.add(url) is True+ assert type(apprise_instance[0].template[0]).__name__ == attachment_type++ is_valid, error = NotificationURLValidator.validate_service_url(url)+ assert is_valid is False+ assert error == "Blocked unsafe notification parameter: template"++ @pytest.mark.filterwarnings(+ "ignore:'imghdr' is deprecated.*:DeprecationWarning"+ )+ def test_apprise_protocol_prefix_compatibility(self):+ """Dependency bumps must trigger an explicit allowlist/doc review."""+ from apprise import Apprise++ details = Apprise().details()+ protocols = {+ protocol+ for schema in details["schemas"]+ for field in ("protocols", "secure_protocols")+ for protocol in (schema[field] or ())+ }++ functional_overlap = {+ "discord",+ "slack",+ "gotify",+ "ntfy",+ "ntfys",+ "signal",+ "matrix",+ "json",+ "xml",+ "form",+ "mailto",+ }+ ldr_only_names = {+ "telegram",+ "pushover",+ "teams",+ "mattermost",+ "rocketchat",+ }+ apprise_names = {+ "tgram",+ "pover",+ "workflow",+ "workflows",+ "mmost",+ "mmosts",+ "rocket",+ "rockets",+ }++ assert functional_overlap <= protocols+ assert ldr_only_names.isdisjoint(protocols)+ assert apprise_names <= protocols+ assert "msteams" not in protocols++ @pytest.mark.parametrize(+ ("url", "mode", "hostname", "post_target", "destination"),+ [+ pytest.param(+ "ntfy://topic",+ "cloud",+ "topic",+ "apprise.plugins.ntfy.requests.post",+ "https://ntfy.sh",+ id="ntfy-cloud-fixed-endpoint",+ ),+ pytest.param(+ "ntfy://ntfy.example.com/topic?mode=private",+ "private",+ "ntfy.example.com",+ "apprise.plugins.ntfy.requests.post",+ "http://ntfy.example.com",+ id="ntfy-private-authority-host",+ ),+ pytest.param(+ "matrix://" + MATRIX_TOKEN,+ "t2bot",+ MATRIX_TOKEN,+ "apprise.plugins.matrix.base.requests.post",+ "https://webhooks.t2bot.io/api/v1/matrix/hook/" + MATRIX_TOKEN,+ id="matrix-t2bot-fixed-endpoint",+ ),+ pytest.param(+ "matrix://user:[email protected]/%23room?mode=matrix",+ "matrix",+ "matrix.example.com",+ "apprise.plugins.matrix.base.requests.post",+ "http://matrix.example.com/api/v1/matrix/hook/token",+ id="matrix-webhook-authority-host",+ ),+ ],+ )+ def test_mode_selects_actual_destination_and_redirects_stay_disabled(+ self, url, mode, hostname, post_target, destination+ ):+ apprise_instance = NotificationService._new_apprise()+ assert apprise_instance.asset.http_redirects is False+ assert apprise_instance.add(url) is True++ plugin = apprise_instance[0]+ assert plugin.mode == mode+ assert plugin.host == hostname+ plugin.throttle = lambda *args, **kwargs: None++ response = Mock(status_code=200, content=b"{}")+ with patch(post_target, return_value=response) as post:+ assert plugin.notify(body="body", title="title") is True++ assert post.call_args.args[0] == destination+ assert post.call_args.kwargs["allow_redirects"] is False++ @pytest.mark.parametrize(("fixture", "hostname"), DNS_FIXTURES)+ @pytest.mark.parametrize(+ ("resolved_ip", "expect_valid"),+ [+ pytest.param(+ "93.184.216.34",+ True,+ id="public-resolves-valid",+ ),+ pytest.param(+ "169.254.169.254",+ False,+ id="metadata-resolves-blocked",+ ),+ ],+ )+ def test_plugin_dns_single_validation_time_resolution(+ self, fixture, hostname, resolved_ip, expect_valid+ ):+ """A successful plugin-authority lookup is performed exactly once."""+ from apprise import Apprise++ assert Apprise().add(fixture) is True+ resolver_calls = []++ def fake_resolve(name):+ resolver_calls.append(name)+ return [ipaddress.ip_address(resolved_ip)]++ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ staticmethod(fake_resolve),+ ):+ is_valid, error_msg, hint = (+ NotificationURLValidator.validate_service_url_with_hint(+ fixture, allow_private_ips=False+ )+ )++ assert resolver_calls == [hostname]+ assert is_valid is expect_valid+ assert hint is False+ assert error_msg == (+ None+ if expect_valid+ # Message wording comes from the link-local guard added on main+ # (the plugin-scheme partition blocks the whole link-local range,+ # not just the metadata literals).+ else f"Blocked cloud-metadata / link-local IP address: {hostname}"+ )++ @pytest.mark.parametrize(("fixture", "hostname"), DNS_FIXTURES)+ def test_plugin_dns_failure_is_attempted_once_and_fails_open(+ self, fixture, hostname+ ):+ """Pin the documented residual risk for plugin authorities."""+ with patch.object(+ NotificationURLValidator,+ "_resolve_hostname_ips",+ return_value=None,+ ) as resolver:+ result = NotificationURLValidator.validate_service_url_with_hint(+ fixture, allow_private_ips=False+ )++ assert result == (True, None, False)+ resolver.assert_called_once_with(hostname)++# ===================================================================# NotificationService# ===================================================================@@ -651,8 +972,8 @@ class TestNotificationService:## The matrix above exercises this end-to-end via test_service for# http(s) URLs. Plugin-scheme URLs reach test_service via a- # different validator prefix ("Blocked cloud-metadata IP- # address:") and the prefix guard inside+ # different validator prefix ("Blocked cloud-metadata /+ # link-local IP address:") and the prefix guard inside# validate_service_url_with_hint short-circuits before the hint# decision is reached — meaning the plugin-scheme rows in the# matrix pass via the prefix-guard fall-through, not via the hint