~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
feat(notifications): default-off + env-only master switch for SSRF rebinding risk (#3675)
LearningCircuit2f7056a52ca9
diff --git a/SECURITY.md b/SECURITY.mdindex f3c74a87f5..b52fb84dc9 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -105,6 +105,30 @@ docker run --cap-add IPC_LOCK -e LDR_DB_CONFIG_CIPHER_MEMORY_SECURITY=ON ...`IPC_LOCK` is a narrow Linux capability that only permits memory locking — it does not grant any other privileges.+### Notification Webhook SSRF++**Outbound notifications via Apprise are disabled by default.** To enable them, the operator must set `LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true` in the server environment. This is intentional: notifications carry a known residual SSRF risk that cannot be fully closed in code, and the env-only gate makes turning them on an explicit operator decision rather than something any logged-in user can flip via the settings API.++#### The residual risk++LDR validates user-configured notification service URLs (`NotificationURLValidator`) before handing them to Apprise. Hostnames are resolved once at validation time and the resulting IPs are checked against private/internal ranges. There is a known **DNS rebinding TOCTOU window** between this check and the actual outbound request:++- **The window.** Apprise (and its underlying `requests`/`urllib3` stack) resolves the hostname *again* when it sends the notification. A DNS-rebinding attacker controlling a domain can serve a public IP to LDR's validator and a private IP to Apprise's send-time resolver — bypassing the private-IP check and reaching internal services on the LDR server (e.g., `127.0.0.1:<internal-port>`) or the local network. This is exploitable by any logged-in user, not just by the deployment operator.+- **Why it isn't closed in code.** Apprise exposes no Session/adapter/DNS hook. Closing the window would require monkey-patching `requests` inside Apprise's plugin namespace — fragile across Apprise versions, HTTPS-only, and doesn't handle redirects correctly. The blast radius outweighs the benefit.++#### How to enable notifications++```bash+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://`, `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.+- **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 same DNS-rebinding caveat applies to `safe_requests` / `ssrf_validator.validate_url`, used for general HTTP fetches (RAG sources, web scraping). Egress restriction is the primary defense for that path as well.+## Supported VersionsSecurity fixes are only provided for the latest release. Please upgrade to receive patches.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex a008417cf3..1e9fd40e8c 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -49,6 +49,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_DB_CONFIG_SYNCHRONOUS` | Enum | `'NORMAL'` | No | EXTRA, FULL, NORMAL, OFF | SQLite synchronous mode | Db Config | LDR_DB_SYNCHRONOUS || `LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL` | Boolean | `False` | No | | Allow authenticated users to start/stop the global news scheduler via API. Disable in multi-user deployments to prevent users from affecting each other. | News Scheduler | || `LDR_NEWS_SCHEDULER_ENABLED` | Boolean | `True` | No | | Enable or disable the news subscription scheduler | News Scheduler | |+| `LDR_NOTIFICATIONS_ALLOW_OUTBOUND` | Boolean | `False` | No | | Master switch for outbound notification webhooks (Apprise). Disabled by default because Apprise re-resolves DNS at send time, leaving a DNS-rebinding TOCTOU window that cannot be closed in code (Apprise exposes no Session/DNS hook). See SECURITY.md 'Notification Webhook SSRF' for details. Set to true only after reviewing the residual risk. Distinct from the per-user notifications.enabled toggle in the settings UI: this is the server-level operator gate, env-only so it cannot be flipped via the user-writable settings API. | Security | || `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` | Boolean | `False` | No | | Allow notification webhooks to target private/local IP addresses. Environment-only to prevent SSRF bypass via the user-writable settings API. Only enable this if your notification endpoints are on a trusted local network. | Security | || `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | || `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Use '*' for all origins (default), empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex c49e41c897..4fa4b56b65 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -6,6 +6,35 @@ The Local Deep Research (LDR) notifications system provides a flexible way to seThe notification system uses [Apprise](https://github.com/caronc/apprise) to support multiple notification services with a unified API. It allows users to configure comma-separated service URLs to receive notifications for different events.+## Server-Side Opt-In Required++> **Outbound notifications are disabled by default.** The deployment operator must explicitly enable them by setting an environment variable on the server:+>+> ```bash+> LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true+> ```+>+> Without this, every `send_notification` call returns `False` and the "Send Test Notification" button returns an error. This applies to **all** users on the deployment.++### 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.++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).++### Symptoms when the gate is closed++If you've configured a notification URL and aren't receiving messages, check the server logs first. You should see lines like:++```+WARNING Notification refused: outbound notifications are disabled at the+ server level. Set LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true to enable.+ See SECURITY.md 'Notification Webhook SSRF' for the rationale and+ residual risk. (event=research_completed, user=...)+```++The "Send Test Notification" UI button returns the same message inline.+## Supported ServicesThe system supports all services that Apprise supports, including but not limited to:diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex 458a74eaf8..aff5855435 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -94,7 +94,20 @@ class NotificationManager:"notifications.allow_private_ips", False)- self.service = NotificationService(allow_private_ips=allow_private_ips)+ # Server-level master switch (env-only). Distinct from the per-user+ # notifications.enabled toggle in the UI: this gate is set by the+ # deployment operator and cannot be flipped via the user-writable+ # settings API. Disabled by default; enabling it accepts the+ # documented DNS-rebinding TOCTOU residual risk+ # (see SECURITY.md "Notification Webhook SSRF").+ self._outbound_allowed = bool(+ get_env_setting("notifications.allow_outbound", False)+ )++ self.service = NotificationService(+ allow_private_ips=allow_private_ips,+ outbound_allowed=self._outbound_allowed,+ )# Initialize shared rate limiter on first use# The shared rate limiter now supports per-user limits, so each user's@@ -181,6 +194,25 @@ class NotificationManager:)logger.debug(f"Context keys: {list(context.keys())}")+ # Server-level master switch (env-only). Disabled by default;+ # flipping it on is the operator's acknowledgement of the+ # documented SSRF rebinding residual risk. force=True does NOT+ # bypass this — it bypasses the per-user event-type and+ # rate-limit toggles only. WARNING level so an operator wondering+ # "why aren't notifications firing?" sees the actionable signal+ # at default log level.+ if not self._outbound_allowed:+ logger.warning(+ "Notification refused: outbound notifications are disabled "+ "at the server level. Set "+ "LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true to enable. See "+ "SECURITY.md 'Notification Webhook SSRF' for the rationale "+ "and residual risk. (event={}, user={})",+ event_type.value,+ self._user_id,+ )+ return False+# Check if notifications are enabled for this event typeshould_notify = self._should_notify(event_type)logger.debug(diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.pyindex 23b546b3b3..734bff25f1 100644--- a/src/local_deep_research/notifications/service.py+++ b/src/local_deep_research/notifications/service.py@@ -42,7 +42,11 @@ class NotificationService:"smtp": r"^(smtp|smtps)://",}- def __init__(self, allow_private_ips: bool = False):+ def __init__(+ self,+ allow_private_ips: bool = False,+ outbound_allowed: bool = False,+ ):"""Initialize the notification service.@@ -50,9 +54,15 @@ class NotificationService:allow_private_ips: Whether to allow notifications to private/local IPs(default: False for security). Set to True fordevelopment/testing environments only.+ outbound_allowed: Server-level master switch+ (env-only via LDR_NOTIFICATIONS_ALLOW_OUTBOUND).+ Default False — outbound notifications are off until+ the operator opts in. See SECURITY.md "Notification+ Webhook SSRF" for the rationale."""self.apprise = apprise.Apprise()self.allow_private_ips = allow_private_ips+ self.outbound_allowed = outbound_allowed@retry(stop=stop_after_attempt(3),@@ -136,6 +146,20 @@ class NotificationService:out of scope. This simple approach is ideal for small deployments(~5 users) and avoids memory management complexity."""+ # Defense-in-depth: enforce the operator-level master switch at+ # the service layer too, not just at NotificationManager.+ # Today the manager always wraps this method, but keeping the+ # gate here means a future direct caller cannot accidentally+ # bypass it. See SECURITY.md "Notification Webhook SSRF".+ if not self.outbound_allowed:+ logger.warning(+ "Notification not sent: outbound notifications are disabled "+ "at the server level. Set "+ "LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true to enable. See "+ "SECURITY.md 'Notification Webhook SSRF'."+ )+ return False+# If service_urls are provided, validate before trying to sendif service_urls:logger.debug("Creating Apprise instance for provided service URLs")@@ -236,6 +260,28 @@ class NotificationService:Returns:Dict with 'success' boolean and optional 'error' message"""+ # Server-level master switch (env-only). Mirrors+ # NotificationManager's gate so the "Send Test Notification"+ # button cannot bypass it. WARNING level so the operator sees+ # the actionable signal naming the env var.+ if not self.outbound_allowed:+ logger.warning(+ "Notification test refused: outbound notifications are "+ "disabled at the server level. Set "+ "LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true to enable. See "+ "SECURITY.md 'Notification Webhook SSRF'."+ )+ return {+ "success": False,+ "error": (+ "Outbound notifications are disabled. The server "+ "administrator must set "+ "LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true to enable "+ "notification webhooks. See SECURITY.md "+ "'Notification Webhook SSRF' for details."+ ),+ }+try:# Validate service URL for security (SSRF prevention)is_valid, error_msg = NotificationURLValidator.validate_service_url(diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex d4ec3d8838..6706f4ec82 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -88,7 +88,27 @@ class NotificationURLValidator:for network in NotificationURLValidator.PRIVATE_IP_RANGES)except ValueError:- # Hostname - resolve to IP and check+ # Hostname - resolve to IP and check.+ #+ # NOTE: This is a best-effort, validation-time check. Apprise+ # re-resolves the hostname when it actually sends the request+ # (via requests/urllib3), so an attacker controlling DNS can+ # serve a public IP here and a private IP at send time -- a+ # classic DNS rebinding TOCTOU window. Apprise exposes no+ # Session/adapter/DNS hook to close this in code without+ # fragile monkey-patching of its plugin internals.+ #+ # Because the window cannot be closed cleanly in code, the+ # whole outbound-notification path is gated behind an+ # env-only master switch (LDR_NOTIFICATIONS_ALLOW_OUTBOUND,+ # default off); turning it on is the operator's explicit+ # risk-acceptance. See SECURITY.md "Notification Webhook+ # SSRF" for details.+ # Operators wanting to avoid the window entirely should+ # prefer plugin schemes (discord://, slack://, ntfy://,+ # gotify://, telegram://, mattermost://, etc.) that hardcode+ # their endpoints instead of raw http(s):// webhooks.+ ## Use concurrent.futures for thread-safe timeout instead of# socket.setdefaulttimeout() which is process-global and not# thread-safe.diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex d02ca334f4..6d15123653 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -160,7 +160,17 @@ def validate_url(# Not an IP address, it's a hostname - need to resolve itpass- # Resolve hostname to IP and check+ # Resolve hostname to IP and check.+ #+ # NOTE: This is a best-effort, validation-time check. The caller+ # (typically safe_requests) hands the URL to requests/urllib3+ # afterwards, which resolves the hostname AGAIN at connect time --+ # a DNS rebinding TOCTOU window. Closing it would require pinning+ # the resolved IP into the outbound connection (HTTPAdapter shim+ # with server_hostname for SNI), which is HTTPS-only and doesn't+ # follow redirects cleanly. See SECURITY.md "Notification Webhook+ # SSRF" subsection for the accepted-risk rationale (the same+ # caveat applies here).try:# Get all IP addresses for hostname# nosec B104 - DNS resolution is intentional for SSRF prevention (checking if hostname resolves to private IP)diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex 701bff3bde..45ddde6be8 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -43,4 +43,19 @@ SECURITY_SETTINGS = [),default=False,),+ BooleanSetting(+ key="notifications.allow_outbound",+ description=(+ "Master switch for outbound notification webhooks (Apprise). "+ "Disabled by default because Apprise re-resolves DNS at send time, "+ "leaving a DNS-rebinding TOCTOU window that cannot be closed in code "+ "(Apprise exposes no Session/DNS hook). See SECURITY.md "+ "'Notification Webhook SSRF' for details. Set to true only after "+ "reviewing the residual risk. Distinct from the per-user "+ "notifications.enabled toggle in the settings UI: this is the "+ "server-level operator gate, env-only so it cannot be flipped via "+ "the user-writable settings API."+ ),+ default=False,+ ),]diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 6f8983684a..4ec6f11965 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -2415,6 +2415,7 @@ def api_test_notification_url():"""try:from ...notifications.service import NotificationService+ from ...settings.env_registry import get_env_settingdata = request.get_json()if not data or "service_url" not in data:@@ -2424,9 +2425,18 @@ def api_test_notification_url():service_url = data["service_url"]- # Create notification service instance and test the URL- # No password/session needed - URL provided directly, no DB access- notification_service = NotificationService()+ # Create notification service instance and test the URL.+ # Gate by the env-only master switch so the test endpoint cannot+ # bypass the operator's risk-acceptance decision (see SECURITY.md+ # "Notification Webhook SSRF").+ notification_service = NotificationService(+ allow_private_ips=bool(+ get_env_setting("notifications.allow_private_ips", False)+ ),+ outbound_allowed=bool(+ get_env_setting("notifications.allow_outbound", False)+ ),+ )result = notification_service.test_service(service_url)# Only return expected fields to prevent information leakagediff --git a/tests/notifications/conftest.py b/tests/notifications/conftest.pynew file mode 100644index 0000000000..50fa3a65b3--- /dev/null+++ b/tests/notifications/conftest.py@@ -0,0 +1,18 @@+"""+Shared fixtures for notification tests.++Notifications are gated behind LDR_NOTIFICATIONS_ALLOW_OUTBOUND at the server level+(see SECURITY.md "Notification Webhook SSRF"). Existing tests exercise the+underlying logic and assume the gate is open; this autouse fixture sets the+env var so they don't all need explicit monkeypatching. Tests that want to+verify the gate behavior itself can override by calling+``monkeypatch.delenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", raising=False)`` inside+the test body.+"""++import pytest++[email protected](autouse=True)+def enable_notifications_by_default(monkeypatch):+ monkeypatch.setenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", "true")diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.pyindex 061e7b6a0d..7b0a1a3877 100644--- a/tests/notifications/test_manager.py+++ b/tests/notifications/test_manager.py@@ -377,6 +377,73 @@ class TestTestService:assert "error" in result+class TestMasterSwitchEnvGate:+ """Tests for the LDR_NOTIFICATIONS_ALLOW_OUTBOUND env-only master switch.++ See SECURITY.md "Notification Webhook SSRF" — outbound notifications+ are off until the operator opts in, because Apprise's DNS-rebinding+ TOCTOU window cannot be closed in code.+ """++ def test_send_notification_returns_false_when_env_unset(+ self, monkeypatch, mocker+ ):+ """If LDR_NOTIFICATIONS_ALLOW_OUTBOUND is unset, send_notification bails early."""+ monkeypatch.delenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", raising=False)++ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )+ manager.service.send_event = mocker.MagicMock(return_value=True)+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context={"query": "Test"},+ )++ assert result is False+ manager.service.send_event.assert_not_called()++ def test_send_notification_with_force_does_not_bypass_env_gate(+ self, monkeypatch, mocker+ ):+ """force=True bypasses per-user toggles, never the operator switch."""+ monkeypatch.delenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", raising=False)++ snapshot = {"notifications.service_url": "discord://webhook/token"}+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )+ manager.service.send_event = mocker.MagicMock(return_value=True)++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context={"query": "Test"},+ force=True,+ )++ assert result is False+ manager.service.send_event.assert_not_called()++ def test_test_service_returns_disabled_error_when_env_unset(+ self, monkeypatch+ ):+ """test_service should refuse with a clear error when the gate is off."""+ monkeypatch.delenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", raising=False)++ manager = NotificationManager(settings_snapshot={}, user_id="test_user")++ result = manager.test_service("discord://webhook/token")++ assert result["success"] is False+ assert "LDR_NOTIFICATIONS_ALLOW_OUTBOUND" in result["error"]++class TestRateLimiter:"""Tests for RateLimiter class."""diff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.pyindex 0dae3d3dd1..3451222307 100644--- a/tests/notifications/test_service.py+++ b/tests/notifications/test_service.py@@ -20,10 +20,59 @@ class TestNotificationServiceInit:def test_init_creates_apprise_instance(self):"""Test initialization creates Apprise instance."""- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert service.apprise is not None+class TestSendOutboundGate:+ """Tests for the operator-level master switch enforced inside send().++ Defense-in-depth: the gate is also checked in NotificationManager and+ NotificationService.test_service. Re-checking inside send() means a+ direct caller (now or in the future) cannot bypass it. See SECURITY.md+ 'Notification Webhook SSRF'.+ """++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_returns_false_when_outbound_disallowed(+ self, mock_apprise_class+ ):+ """send() must bail out before constructing/calling Apprise."""+ mock_apprise_instance = MagicMock()+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService(outbound_allowed=False)++ result = service.send(+ title="t",+ body="b",+ service_urls="discord://webhook/token",+ )++ assert result is False+ # Apprise should never be touched once the gate refuses.+ mock_apprise_instance.notify.assert_not_called()+ mock_apprise_instance.add.assert_not_called()++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_proceeds_when_outbound_allowed(self, mock_apprise_class):+ """Sanity check: gate open => normal send path runs."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService(outbound_allowed=True)++ result = service.send(+ title="t",+ body="b",+ service_urls="discord://webhook/token",+ )++ assert result is True+ assert mock_apprise_instance.notify.call_count == 1++class TestSendWithTenacity:"""Tests for send method with Tenacity retry logic."""@@ -34,7 +83,7 @@ class TestSendWithTenacity:mock_apprise_instance.notify.return_value = Truemock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.send(title="Test Title",@@ -54,7 +103,7 @@ class TestSendWithTenacity:mock_apprise_instance.notify.side_effect = [False, False, True]mock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.send(title="Test",@@ -80,7 +129,7 @@ class TestSendWithTenacity:mock_apprise_instance.notify.return_value = Falsemock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)with pytest.raises(SendError, match="Failed to send notification"):service.send(@@ -107,7 +156,7 @@ class TestSendWithTenacity:]mock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.send(title="Test",@@ -122,7 +171,7 @@ class TestSendWithTenacity:@patch("local_deep_research.notifications.service.apprise.Apprise")def test_send_with_no_service_urls(self, mock_apprise_class):"""Test send returns False when configured instance empty."""- service = NotificationService()+ service = NotificationService(outbound_allowed=True)# Don't provide service_urls, use configured instanceresult = service.send(@@ -151,7 +200,7 @@ class TestTenacityConfiguration:mock_apprise_instance.notify.return_value = False # Always failmock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)# Verify the retry decorator is appliedassert hasattr(service._send_with_retry, "__wrapped__")@@ -180,7 +229,7 @@ class TestSendEvent:mock_apprise_instance.add.return_value = Truemock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)# Include all required template variablescontext = {@@ -218,7 +267,7 @@ class TestTestService:mock_apprise_instance.notify.return_value = Truemock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("discord://webhook/token")@@ -229,7 +278,7 @@ class TestTestService:def test_test_service_exception(self):"""Test service test handles exceptions."""- service = NotificationService()+ service = NotificationService(outbound_allowed=True)# Mock the internal apprise.Apprise to raise exceptionwith patch(@@ -252,13 +301,13 @@ class TestGetServiceType:def test_get_service_type_discord(self):"""Test detecting Discord service."""- service = NotificationService()+ service = NotificationService(outbound_allowed=True)service_type = service.get_service_type("discord://webhook/token")assert service_type == "discord"def test_get_service_type_unknown(self):"""Test unknown service type."""- service = NotificationService()+ service = NotificationService(outbound_allowed=True)service_type = service.get_service_type("unknown://service")assert service_type == "unknown"@@ -274,7 +323,7 @@ class TestIntegration:mock_apprise_instance.notify.return_value = Truemock_apprise_class.return_value = mock_apprise_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)context = {"query": "Test research query",diff --git a/tests/notifications/test_service_edge_cases.py b/tests/notifications/test_service_edge_cases.pyindex 4f30e4b3fc..e367687deb 100644--- a/tests/notifications/test_service_edge_cases.py+++ b/tests/notifications/test_service_edge_cases.py@@ -17,7 +17,7 @@ class TestTestServiceErrorPaths:return_value=(False, "blocked by SSRF check"),)def test_ssrf_validation_fails(self, mock_validator, mock_apprise_class):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("http://169.254.169.254/metadata")assert result["success"] is Falseassert "Invalid" in result["error"]@@ -32,7 +32,7 @@ class TestTestServiceErrorPaths:mock_instance.add.return_value = Falsemock_apprise_class.return_value = mock_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("discord://webhook/token")assert result["success"] is Falseassert "Failed to add" in result["error"]@@ -48,7 +48,7 @@ class TestTestServiceErrorPaths:mock_instance.notify.return_value = Falsemock_apprise_class.return_value = mock_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("discord://webhook/token")assert result["success"] is Falseassert "Failed to send" in result["error"]@@ -64,7 +64,7 @@ class TestTestServiceErrorPaths:mock_instance.notify.return_value = Truemock_apprise_class.return_value = mock_instance- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("discord://webhook/token")assert result["success"] is Trueassert "successfully" in result["message"]@@ -77,7 +77,7 @@ class TestTestServiceErrorPaths:def test_validation_error_message_not_leaked(self, mock_validator, mock_apprise_class):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)result = service.test_service("http://evil.com")assert result["success"] is False# Internal error detail should NOT appear in the user-facing message@@ -89,26 +89,26 @@ class TestGetServiceTypePatterns:"""Tests for get_service_type() across all SERVICE_PATTERNS."""def test_email_detection(self):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert service.get_service_type("mailto://[email protected]") == "email"def test_slack_detection(self):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert (service.get_service_type("slack://token_a/token_b/token_c")== "slack")def test_telegram_detection(self):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert (service.get_service_type("tgram://bottoken/chat_id") == "telegram")def test_smtp_detection(self):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert service.get_service_type("smtp://user:[email protected]") == "smtp"def test_smtps_detection(self):- service = NotificationService()+ service = NotificationService(outbound_allowed=True)assert service.get_service_type("smtps://user:[email protected]") == "smtp"diff --git a/tests/notifications/test_service_extra_coverage.py b/tests/notifications/test_service_extra_coverage.pyindex cc9808e2ee..6a1f58d6fd 100644--- a/tests/notifications/test_service_extra_coverage.py+++ b/tests/notifications/test_service_extra_coverage.py@@ -20,6 +20,9 @@ def _make_service():svc = NotificationService.__new__(NotificationService)svc.apprise = mock_apprise_module.Apprise.return_valuesvc.allow_private_ips = False+ # Tests in this file exercise inner logic; open the gate so+ # send() doesn't bail at the operator-level check.+ svc.outbound_allowed = Truesvc.SERVICE_PATTERNS = NotificationService.SERVICE_PATTERNSreturn svcdiff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.pyindex fca8767c21..84de6c1c72 100644--- a/tests/web/services/test_notification_coverage.py+++ b/tests/web/services/test_notification_coverage.py@@ -64,6 +64,17 @@ def _reset_shared_rate_limiter():NotificationManager._shared_rate_limiter = None[email protected](autouse=True)+def _enable_outbound_notifications(monkeypatch):+ """Module-level autouse: open the operator-level env gate so tests in+ this file that exercise the inner notification logic don't bail at+ NotificationManager.__init__ / NotificationService.send. Tests of the+ gate itself (none in this file) should override with+ monkeypatch.delenv. See SECURITY.md "Notification Webhook SSRF".+ """+ monkeypatch.setenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", "true")++@pytest.fixture()def default_settings():"""Settings snapshot that enables notifications with a valid URL."""@@ -267,11 +278,11 @@ class TestNotificationService:"""Tests for the low-level notification service wrapping Apprise."""def test_init_defaults(self):- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)assert svc.allow_private_ips is Falsedef test_init_allow_private_ips(self):- svc = NotificationService(allow_private_ips=True)+ svc = NotificationService(allow_private_ips=True, outbound_allowed=True)assert svc.allow_private_ips is True# -- _validate_url (static) -------------------------------------------@@ -295,7 +306,7 @@ class TestNotificationService:# -- get_service_type --------------------------------------------------def test_get_service_type_known(self):- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)assert svc.get_service_type("mailto://[email protected]") == "email"assert svc.get_service_type("discord://id/token") == "discord"assert svc.get_service_type("slack://a/b/c") == "slack"@@ -304,7 +315,7 @@ class TestNotificationService:assert svc.get_service_type("smtps://mail.example.com") == "smtp"def test_get_service_type_unknown(self):- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)assert svc.get_service_type("https://hooks.example.com") == "unknown"# -- send (mocked Apprise) ---------------------------------------------@@ -317,7 +328,7 @@ class TestNotificationService:mock_instance.add.return_value = Truemock_instance.notify.return_value = True- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.send(title="Test",body="Body",@@ -336,7 +347,7 @@ class TestNotificationService:"bad url",)- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)with pytest.raises(ServiceError):svc.send(title="Test",@@ -353,7 +364,7 @@ class TestNotificationService:mock_instance = MockApprise.return_valuemock_instance.add.return_value = False- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)# When add() returns False the original apprise instance is used,# but the temp one is used here so it returns False immediately.result = svc.send(@@ -362,7 +373,7 @@ class TestNotificationService:assert result is Falsedef test_send_no_urls_no_configured_services_returns_false(self):- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.send(title="Test", body="Body")assert result is False@@ -370,7 +381,7 @@ class TestNotificationService:@patch.object(NotificationService, "send", return_value=True)def test_send_event_uses_template(self, mock_send):- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.send_event(event_type=EventType.RESEARCH_COMPLETED,context={"query": "test query", "research_id": "abc123"},@@ -392,7 +403,7 @@ class TestNotificationService:mock_instance.add.return_value = Truemock_instance.notify.return_value = True- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.test_service("discord://id/token")assert result["success"] is True@@ -400,7 +411,7 @@ class TestNotificationService:def test_test_service_invalid_url(self, MockValidator):MockValidator.validate_service_url.return_value = (False, "blocked")- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.test_service("file:///etc/passwd")assert result["success"] is Falseassert "error" in result@@ -412,7 +423,7 @@ class TestNotificationService:mock_instance = MockApprise.return_valuemock_instance.add.return_value = False- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.test_service("discord://id/token")assert result["success"] is Falseassert "Failed to add" in result["error"]@@ -425,7 +436,7 @@ class TestNotificationService:mock_instance.add.return_value = Truemock_instance.notify.return_value = False- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.test_service("discord://id/token")assert result["success"] is Falseassert "Failed to send" in result["error"]@@ -434,7 +445,7 @@ class TestNotificationService:def test_test_service_exception(self, MockValidator):MockValidator.validate_service_url.side_effect = RuntimeError("boom")- svc = NotificationService()+ svc = NotificationService(outbound_allowed=True)result = svc.test_service("discord://id/token")assert result["success"] is False@@ -583,6 +594,9 @@ class TestRateLimiter:class TestNotificationManager:"""Tests for the high-level notification manager."""+ # Module-level autouse fixture _enable_outbound_notifications opens+ # the operator-level env gate for all tests in this file.+def _make_manager(self, settings, user_id="test_user"):return NotificationManager(settings_snapshot=settings, user_id=user_id)