diff --git a/docs/users-and-requests.md b/docs/users-and-requests.md index 0ddb921e..5c715a8e 100644 --- a/docs/users-and-requests.md +++ b/docs/users-and-requests.md @@ -61,6 +61,8 @@ Override how a user searches, on top of the global search defaults: Users can configure personal notification routes, separate from the global notification settings. Each route targets a URL (e.g. an Apprise-compatible endpoint) and can be scoped to specific event types or all events. +Route URLs can use `{User}` and `{Email}` in their path or query, filled in from each user's account when a notification is sent. A route is skipped for users without the value it needs, or whose value contains spaces or any of `, ; / \ "` (or is only dots, such as `..`), since those would split it into several targets or change the URL path. The admin-set default routes apply to every user who hasn't set routes of their own and can use any service, so one default such as `mailtos://user:pass@smtp.example.com?to={Email}` reaches each user at their own address. The service a default points to then receives each user's email address, so only use one you trust with it. Routes a user sets themselves stay limited to the personal-route services, e.g. `ntfys://ntfy.sh/shelfmark-{User}`. + ### Request Policy (admin-only) Admins can override the default ebook/audiobook modes and request rules for individual users. See [Per-User Overrides](#per-user-overrides) below. diff --git a/shelfmark/config/notifications_settings.py b/shelfmark/config/notifications_settings.py index 4fff97d2..dbd4e51e 100644 --- a/shelfmark/config/notifications_settings.py +++ b/shelfmark/config/notifications_settings.py @@ -9,6 +9,7 @@ from urllib.parse import urlsplit from shelfmark.core.config import config as app_config from shelfmark.core.notifications import ( NotificationEvent, + expand_user_route_placeholders, send_test_notification, user_route_url_problem, ) @@ -147,12 +148,17 @@ def _extract_unique_route_urls(routes: list[dict[str, Any]]) -> list[str]: def build_notification_test_result( - routes_input: Any, *, scope_label: str, user_scope: bool = False + routes_input: Any, + *, + scope_label: str, + user_scope: bool = False, + user_id: int | None = None, ) -> dict[str, Any]: """Validate routes and return a test-notification result payload. ``user_scope`` is for a user's own routes, which may only use the services and public hosts - that ``user_route_url_problem`` allows. + that ``user_route_url_problem`` allows. ``user_id`` fills in ``{User}``/``{Email}`` first, so + the check sees the URL that would actually be sent. """ invalid_event_count = _count_invalid_route_events(routes_input) if invalid_event_count: @@ -182,6 +188,17 @@ def build_notification_test_result( "message": f"Add at least one {scope_label} notification URL route first.", } + if user_id is not None: + urls = expand_user_route_placeholders(urls, user_id) + if not urls: + return { + "success": False, + "message": ( + "Every route was skipped while filling in {User}/{Email}: the account has " + "no value for it, or a placeholder is in the host part of the URL." + ), + } + if user_scope: for url in urls: problem = user_route_url_problem(url) @@ -332,7 +349,9 @@ def notifications_settings() -> list[SettingsField]: label="", description=( "Create one route per URL. Start with All, then add event-specific routes " - "for targeted delivery. Need format examples? " + "for targeted delivery. Use {User} or {Email} in the path or query to fill in " + "each user's account details, e.g. ntfys://ntfy.sh/shelfmark-{User}, or " + "mailtos://...?to={Email} in the admin default. Need format examples? " "[View Apprise URL formats](https://appriseit.com/services/)." ), columns=[ diff --git a/shelfmark/core/admin_settings_routes.py b/shelfmark/core/admin_settings_routes.py index f02c92fb..60b0d287 100644 --- a/shelfmark/core/admin_settings_routes.py +++ b/shelfmark/core/admin_settings_routes.py @@ -226,14 +226,26 @@ def build_user_notification_test_response( """Build a notification test response using effective per-user routes.""" from shelfmark.core.config import config as app_config - routes_input = app_config.get("USER_NOTIFICATION_ROUTES", [], user_id=user_id) + effective_routes, is_own = app_config.get_for_user( + "USER_NOTIFICATION_ROUTES", [], user_id=user_id + ) + routes_input = effective_routes if isinstance(payload, dict): if "USER_NOTIFICATION_ROUTES" in payload: routes_input = payload.get("USER_NOTIFICATION_ROUTES") elif "routes" in payload: routes_input = payload.get("routes") - result = build_notification_test_result(routes_input, scope_label="personal", user_scope=True) + # The settings screens always post the routes they show, which for a user without their own + # is the inherited admin default. Trust it like at send time only when it is exactly that; + # anything else would become the user's own routes once saved, so it is checked. + user_scope = is_own or normalize_notification_routes( + routes_input + ) != normalize_notification_routes(effective_routes) + + result = build_notification_test_result( + routes_input, scope_label="personal", user_scope=user_scope, user_id=user_id + ) status_code = 200 if result.get("success", False) else 400 return result, status_code diff --git a/shelfmark/core/config.py b/shelfmark/core/config.py index d42d2de4..7b4c4104 100644 --- a/shelfmark/core/config.py +++ b/shelfmark/core/config.py @@ -212,6 +212,16 @@ class Config: Returns: The setting value, or default if not found + """ + return self.get_for_user(key, default, user_id=user_id)[0] + + def get_for_user( + self, key: str, default: object = None, user_id: int | None = None + ) -> tuple[object, bool]: + """Like ``get``, plus whether the value is the user's own override. + + Both come from a single read, so a settings save in between cannot make them + disagree. False means the deployment-wide value set by an admin or ENV. """ self._ensure_loaded() @@ -221,15 +231,15 @@ class Config: # Deployment-level ENV values always win. if field.env_supported and registry.is_value_from_env(field): - return self._cache.get(key, default) + return self._cache.get(key, default), False # User overrides are only available for explicitly overridable fields. if user_id is not None and getattr(field, "user_overridable", False): user_value = self._get_user_override(user_id, key) if user_value is not None: - return user_value + return user_value, True - return self._cache.get(key, default) + return self._cache.get(key, default), False def __getattr__(self, name: str) -> object: """Allow attribute-style access to settings. diff --git a/shelfmark/core/notifications.py b/shelfmark/core/notifications.py index 88d6e525..b2f2a417 100644 --- a/shelfmark/core/notifications.py +++ b/shelfmark/core/notifications.py @@ -4,14 +4,16 @@ from __future__ import annotations import ipaddress import logging +import re import socket +import sqlite3 from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager, suppress from contextvars import ContextVar from dataclasses import dataclass from enum import StrEnum from typing import TYPE_CHECKING, Any, Protocol, TypeGuard -from urllib.parse import urlsplit +from urllib.parse import quote, urlsplit try: import apprise @@ -20,7 +22,7 @@ except ImportError: # pragma: no cover - exercised in tests via monkeypatch from shelfmark.core.config import config as app_config from shelfmark.core.logger import setup_logger -from shelfmark.core.request_helpers import normalize_positive_int +from shelfmark.core.request_helpers import is_plain_email_address, normalize_positive_int if TYPE_CHECKING: from collections.abc import Iterable, Iterator @@ -37,6 +39,12 @@ _APPRISE_LOGO_URL = ( ) _APPRISE_LOGGER_NAME = "apprise" _APPRISE_DISPATCH_ERRORS = (RuntimeError, TypeError, ValueError) +_USER_ROUTE_PLACEHOLDER_PATTERN = re.compile(r"\{(user|email)\}", re.IGNORECASE) +# Apprise splits a decoded value on these, so "John Smith" or '"a,b@x.com"@y.com' would reach +# extra topics or recipients (e.g. add recipients to an admin-set mailto route). +_UNSAFE_PLACEHOLDER_VALUE = re.compile(r'[\s,;/\\"]') +# Percent-encoding leaves dots alone, so a username of ".." would walk up a webhook URL's path. +_DOTS_ONLY_PLACEHOLDER_VALUE = re.compile(r"\.+") class _ApprisePluginWithUrl(Protocol): @@ -363,14 +371,89 @@ def _allowed_user_urls(urls: list[str]) -> list[str]: return allowed -def _resolve_user_routes(user_id: int | None) -> list[dict[str, str]]: +def _resolve_user_routes(user_id: int | None) -> tuple[list[dict[str, str]], bool]: + """The user's routes, and whether they are the inherited admin default. + + Admin-set routes are trusted like the global ones, so they skip the personal-route checks. + Both come from one config read, so a settings save in between cannot pair the user's own + routes with the admin default's trust. + """ normalized_user_id = _normalize_user_id(user_id) if normalized_user_id is None: - return [] + return [], False - return _normalize_routes( - app_config.get("USER_NOTIFICATION_ROUTES", [], user_id=normalized_user_id) + value, is_own = app_config.get_for_user( + "USER_NOTIFICATION_ROUTES", [], user_id=normalized_user_id ) + return _normalize_routes(value), not is_own + + +def _get_route_user(user_id: int) -> dict[str, Any] | None: + try: + from shelfmark.core.user_db import UserDB, get_users_db_path + + return UserDB(get_users_db_path()).get_user(user_id=user_id) + except (ImportError, OSError, sqlite3.Error) as exc: + logger.warning("Failed to look up user_id=%s for notification routes: %s", user_id, exc) + return None + + +def expand_user_route_placeholders(urls: list[str], user_id: int) -> list[str]: + """Expand `{User}` and `{Email}` in per-user route URLs from the user's account. + + Placeholders are only filled in the path, query or fragment: a URL with one in its host part + is dropped, because Apprise decodes percent-escapes there (so an email such as + ``x%40127.0.0.1`` would still reach 127.0.0.1). Values are fully percent-encoded, and a + value containing whitespace or any of ``, ; / \\ "`` is ignored, since Apprise would split it + into several targets, and so is a value made only of dots, which would change the URL path. + URLs that need a value the user does not have are dropped. + Callers should still validate the returned URLs, not the templates. + """ + if not any(_USER_ROUTE_PLACEHOLDER_PATTERN.search(url) for url in urls): + return urls + + user = _get_route_user(user_id) or {} + values: dict[str, str] = {} + for name, field in (("user", "username"), ("email", "email")): + value = str(user.get(field) or "").strip() + if value and ( + _UNSAFE_PLACEHOLDER_VALUE.search(value) + or _DOTS_ONLY_PLACEHOLDER_VALUE.fullmatch(value) + or (name == "email" and not is_plain_email_address(value)) + ): + logger.info( + "Ignoring the %s on file for user_id=%s in notification routes: it could " + "split into several targets or change the URL path", + field, + user_id, + ) + value = "" + values[name] = value + + expanded: list[str] = [] + for url in urls: + if _USER_ROUTE_PLACEHOLDER_PATTERN.search(urlsplit(url).netloc): + logger.warning( + "Skipping notification route for user_id=%s: {User}/{Email} is not allowed " + "in the host part of a URL", + user_id, + ) + continue + needed = {match.lower() for match in _USER_ROUTE_PLACEHOLDER_PATTERN.findall(url)} + missing = sorted(name for name in needed if not values[name]) + if missing: + logger.info( + "Skipping notification route for user_id=%s: no %s on file", + user_id, + ", ".join(missing), + ) + continue + expanded.append( + _USER_ROUTE_PLACEHOLDER_PATTERN.sub( + lambda match: quote(values[match.group(1).lower()], safe=""), url + ) + ) + return expanded def _resolve_route_urls_for_event( @@ -715,13 +798,24 @@ def notify_user( if normalized_user_id is None: return - routes = _resolve_user_routes(normalized_user_id) - urls = _allowed_user_urls(_resolve_route_urls_for_event(routes, event)) + routes, admin_default = _resolve_user_routes(normalized_user_id) + urls = expand_user_route_placeholders( + _resolve_route_urls_for_event(routes, event), normalized_user_id + ) + if not admin_default: + urls = _allowed_user_urls(urls) if not urls: return try: - _executor.submit(_dispatch_user_async, normalized_user_id, event, context, urls) + _executor.submit( + _dispatch_user_async, + normalized_user_id, + event, + context, + urls, + admin_default=admin_default, + ) except RuntimeError as exc: logger.warning( "Failed to queue user notification '%s' for user_id=%s: %s", @@ -748,9 +842,12 @@ def _dispatch_user_async( event: NotificationEvent, context: NotificationContext, urls: list[str], + *, + admin_default: bool = False, ) -> None: # Checked again at send time: the host may resolve differently than when it was queued. - urls = _allowed_user_urls(urls) + if not admin_default: + urls = _allowed_user_urls(urls) if not urls: return result = _send_admin_event(event, context, urls) diff --git a/tests/core/test_config_user_overrides.py b/tests/core/test_config_user_overrides.py index fbba5e85..ebdb738e 100644 --- a/tests/core/test_config_user_overrides.py +++ b/tests/core/test_config_user_overrides.py @@ -5,6 +5,8 @@ from __future__ import annotations from types import SimpleNamespace from unittest.mock import patch +import pytest + from shelfmark.core.config import config @@ -83,6 +85,34 @@ def test_get_keeps_empty_string_override(monkeypatch): assert config.get("DESTINATION_AUDIOBOOK", "/default", user_id=10) == "" +@pytest.mark.parametrize( + ("override", "from_env", "expected"), + [ + ("/user/books", False, ("/user/books", True)), + ("", False, ("", True)), + (None, False, ("/global/books", False)), + ("/user/books", True, ("/global/books", False)), + ], +) +def test_get_for_user_returns_get_value_and_whether_it_is_the_users_own( + monkeypatch, override, from_env, expected +): + field = _download_field("DESTINATION") + + monkeypatch.setattr(config, "_ensure_loaded", lambda: None) + monkeypatch.setattr(config, "_cache", {"DESTINATION": "/global/books"}) + monkeypatch.setattr(config, "_field_map", {"DESTINATION": (field, "downloads")}) + monkeypatch.setattr(config, "_get_user_override", lambda user_id, key: override) + monkeypatch.setattr( + "shelfmark.core.config._get_registry", + lambda: SimpleNamespace(is_value_from_env=lambda field: from_env), + ) + + assert config.get_for_user("DESTINATION", "/default", user_id=10) == expected + assert config.get("DESTINATION", "/default", user_id=10) == expected[0] + assert config.get_for_user("DESTINATION", "/default", user_id=None) == ("/global/books", False) + + def test_build_user_preferences_payload_reports_effective_sources(monkeypatch): import shelfmark.config.settings # noqa: F401 from shelfmark.core import settings_registry diff --git a/tests/core/test_notifications.py b/tests/core/test_notifications.py index d07ea655..455537a8 100644 --- a/tests/core/test_notifications.py +++ b/tests/core/test_notifications.py @@ -6,6 +6,7 @@ import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import apprise +import pytest from shelfmark.core import notifications as notifications_module @@ -529,9 +530,9 @@ def test_resolve_admin_routes_returns_empty_when_no_routes(monkeypatch): def test_resolve_user_routes_uses_user_overrides(monkeypatch): - def _fake_get(key, default=None, user_id=None): + def _fake_get_for_user(key, default=None, user_id=None): if user_id != 42: - return default + return default, False values = { "USER_NOTIFICATION_ROUTES": [ {"event": "all", "url": " ntfys://ntfy.sh/alice "}, @@ -539,16 +540,17 @@ def test_resolve_user_routes_uses_user_overrides(monkeypatch): {"event": "download_failed", "url": "ntfys://ntfy.sh/errors"}, ], } - return values.get(key, default) + return values.get(key, default), True - monkeypatch.setattr(notifications_module.app_config, "get", _fake_get) + monkeypatch.setattr(notifications_module.app_config, "get_for_user", _fake_get_for_user) - routes = notifications_module._resolve_user_routes(42) + routes, admin_default = notifications_module._resolve_user_routes(42) assert routes == [ {"event": "all", "url": "ntfys://ntfy.sh/alice"}, {"event": "download_failed", "url": "ntfys://ntfy.sh/errors"}, ] + assert admin_default is False def test_notify_user_submits_non_blocking_when_route_matches_event(monkeypatch): @@ -557,7 +559,7 @@ def test_notify_user_submits_non_blocking_when_route_matches_event(monkeypatch): monkeypatch.setattr( notifications_module, "_resolve_user_routes", - lambda _user_id: [{"event": "download_failed", "url": "discord://Webhook/Token"}], + lambda _user_id: ([{"event": "download_failed", "url": "discord://Webhook/Token"}], False), ) context = notifications_module.NotificationContext( @@ -652,20 +654,20 @@ def test_resolve_admin_routes_expands_multiselect_event_rows(monkeypatch): def test_resolve_user_routes_expands_multiselect_event_rows(monkeypatch): - def _fake_get(key, default=None, user_id=None): + def _fake_get_for_user(key, default=None, user_id=None): if key != "USER_NOTIFICATION_ROUTES" or user_id != 7: - return default + return default, False return [ { "event": ["download_complete", "request_fulfilled"], "url": "ntfys://ntfy.sh/user-main", }, {"event": ["all", "download_failed"], "url": "ntfys://ntfy.sh/user-all"}, - ] + ], True - monkeypatch.setattr(notifications_module.app_config, "get", _fake_get) + monkeypatch.setattr(notifications_module.app_config, "get_for_user", _fake_get_for_user) - routes = notifications_module._resolve_user_routes(7) + routes, _ = notifications_module._resolve_user_routes(7) assert routes == [ {"event": "download_complete", "url": "ntfys://ntfy.sh/user-main"}, @@ -674,6 +676,156 @@ def test_resolve_user_routes_expands_multiselect_event_rows(monkeypatch): ] +def test_expand_user_route_placeholders_fills_account_details(monkeypatch): + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": "alice", "email": "alice+books@example.com"}, + ) + + urls = notifications_module.expand_user_route_placeholders( + [ + "mailtos://smtp.example.com?to={Email}", + "ntfys://ntfy.sh/shelfmark-{user}", + "ntfys://ntfy.sh/static", + ], + 7, + ) + + assert urls == [ + "mailtos://smtp.example.com?to=alice%2Bbooks%40example.com", + "ntfys://ntfy.sh/shelfmark-alice", + "ntfys://ntfy.sh/static", + ] + + +def test_expand_user_route_placeholders_refuses_placeholder_in_host(monkeypatch): + # Apprise decodes %40 in the host, so x%40127.0.0.1 would still reach loopback. + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": "mallory", "email": "x@127.0.0.1"}, + ) + + urls = notifications_module.expand_user_route_placeholders( + ["ntfys://{Email}/alerts", "ntfys://{User}.example.com/alerts", "ntfys://ntfy.sh/{User}"], + 7, + ) + + assert urls == ["ntfys://ntfy.sh/mallory"] + + +def test_notify_user_does_not_queue_placeholder_host_pointing_at_loopback(monkeypatch): + fake_executor = _FakeExecutor() + monkeypatch.setattr(notifications_module, "_executor", fake_executor) + monkeypatch.setattr( + notifications_module, + "_resolve_user_routes", + lambda _user_id: ([{"event": "all", "url": "ntfys://{Email}/alerts"}], False), + ) + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": "mallory", "email": "x@127.0.0.1"}, + ) + + context = notifications_module.NotificationContext( + event=notifications_module.NotificationEvent.DOWNLOAD_FAILED, + title="Example Book", + author="Example Author", + username="mallory", + ) + notifications_module.notify_user( + 7, notifications_module.NotificationEvent.DOWNLOAD_FAILED, context + ) + + assert fake_executor.calls == [] + + +@pytest.mark.parametrize( + ("username", "email", "expected"), + [ + # A list would let a user add recipients to an admin-set mailto route. + ("mallory", "a@example.com,b@example.com", ["ntfys://ntfy.sh/mallory"]), + # Valid syntax, but Apprise decodes %2C and sends to a@evil.com and b@evil.com. + ("mallory", '"x,a@evil.com,b@evil.com"@example.com', ["ntfys://ntfy.sh/mallory"]), + # Apprise would publish to two topics, "...-John" and "Smith". + ("John Smith", "john@example.com", ["mailtos://smtp.example.com?to=john%40example.com"]), + ("a/b", "x\\y@example.com", []), + # A slash walks the topic path: this would publish to a topic called "admin". + ("bob/../admin", "bob@example.com", ["mailtos://smtp.example.com?to=bob%40example.com"]), + # A newline splits like any other whitespace. + ("eve\nadmin", "eve@example.com\nb@example.com", []), + ], +) +def test_expand_user_route_placeholders_ignores_values_apprise_would_split( + monkeypatch, username, email, expected +): + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": username, "email": email}, + ) + + urls = notifications_module.expand_user_route_placeholders( + ["mailtos://smtp.example.com?to={Email}", "ntfys://ntfy.sh/{User}"], + 7, + ) + + assert urls == expected + + +@pytest.mark.parametrize( + ("username", "expected"), + [ + # Left unencoded, ".." would turn /notify/.. into /, another path on the same host. + (".", []), + ("..", []), + ("...", []), + ("john.doe", ["json://hook.example/notify/john.doe"]), + ("..john", ["json://hook.example/notify/..john"]), + ], +) +def test_expand_user_route_placeholders_ignores_dots_only_values(monkeypatch, username, expected): + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": username, "email": "user@example.com"}, + ) + + urls = notifications_module.expand_user_route_placeholders( + ["json://hook.example/notify/{User}"], + 7, + ) + + assert urls == expected + + +def test_expand_user_route_placeholders_drops_routes_missing_a_value(monkeypatch): + monkeypatch.setattr( + notifications_module, + "_get_route_user", + lambda user_id: {"username": "carol", "email": None}, + ) + + urls = notifications_module.expand_user_route_placeholders( + ["mailtos://smtp.example.com?to={Email}", "ntfys://ntfy.sh/{User}"], + 7, + ) + + assert urls == ["ntfys://ntfy.sh/carol"] + + +def test_expand_user_route_placeholders_skips_lookup_without_placeholders(monkeypatch): + def _fail_lookup(user_id): + raise AssertionError("user lookup should not run") + + monkeypatch.setattr(notifications_module, "_get_route_user", _fail_lookup) + + urls = ["ntfys://ntfy.sh/static"] + assert notifications_module.expand_user_route_placeholders(urls, 7) == urls + + class TestAppriseProxyEnv: """Regression tests for issue #956 — proxy settings ignored for notifications.""" diff --git a/tests/core/test_notifications_user_routes.py b/tests/core/test_notifications_user_routes.py index c41d2204..89d0353e 100644 --- a/tests/core/test_notifications_user_routes.py +++ b/tests/core/test_notifications_user_routes.py @@ -106,7 +106,7 @@ class TestSending: {"event": "all", "url": "discord://1234567890/abcdefghijk"}, ] with ( - patch.object(notifications, "_resolve_user_routes", return_value=routes), + patch.object(notifications, "_resolve_user_routes", return_value=(routes, False)), patch.object(notifications._executor, "submit") as submit, ): notifications.notify_user(5, NotificationEvent.REQUEST_CREATED, self._context()) @@ -117,13 +117,36 @@ class TestSending: def test_nothing_is_queued_when_every_route_is_refused(self): routes = [{"event": "all", "url": "json://127.0.0.1:9/x"}] with ( - patch.object(notifications, "_resolve_user_routes", return_value=routes), + patch.object(notifications, "_resolve_user_routes", return_value=(routes, False)), patch.object(notifications._executor, "submit") as submit, ): notifications.notify_user(5, NotificationEvent.REQUEST_CREATED, self._context()) submit.assert_not_called() + def test_the_admin_default_is_not_restricted(self): + routes = [{"event": "all", "url": "mailtos://user:pass@10.0.0.5?to=a@example.com"}] + with ( + patch.object(notifications, "_resolve_user_routes", return_value=(routes, True)), + patch.object(notifications._executor, "submit") as submit, + ): + notifications.notify_user(5, NotificationEvent.REQUEST_CREATED, self._context()) + + assert submit.call_args.args[-1] == ["mailtos://user:pass@10.0.0.5?to=a@example.com"] + assert submit.call_args.kwargs == {"admin_default": True} + + def test_the_send_trusts_the_admin_default(self): + with patch.object(notifications, "_send_admin_event") as send: + notifications._dispatch_user_async( + 5, + NotificationEvent.REQUEST_CREATED, + self._context(), + ["json://10.0.0.5:8080/hook"], + admin_default=True, + ) + + assert send.call_args.args[2] == ["json://10.0.0.5:8080/hook"] + def test_the_send_checks_again(self): with patch.object(notifications, "_send_admin_event") as send: notifications._dispatch_user_async( @@ -201,3 +224,44 @@ class TestTestEndpoint: assert resp.status_code == 200 send.assert_called_once() + + DEFAULT_ROUTE = "mailtos://user:pass@10.0.0.5?to=a@example.com" + + def _inherit_admin_default(self): + from shelfmark.core.config import config as app_config + + real_get_for_user = app_config.get_for_user + + def _get_for_user(key, default=None, user_id=None): + if key == "USER_NOTIFICATION_ROUTES": + return [{"event": "all", "url": self.DEFAULT_ROUTE}], False + return real_get_for_user(key, default, user_id=user_id) + + return patch.object(app_config, "get_for_user", side_effect=_get_for_user) + + # The settings screens always post the routes they show: the inherited default. + @pytest.mark.parametrize("body", [{"routes": [{"event": ["all"], "url": DEFAULT_ROUTE}]}, {}]) + def test_the_inherited_admin_default_is_tested_without_the_personal_checks(self, client, body): + with ( + self._inherit_admin_default(), + patch( + "shelfmark.config.notifications_settings.send_test_notification", + return_value={"success": True, "message": "ok"}, + ) as send, + ): + resp = client.post(self.URL, json=body) + + assert resp.status_code == 200 + send.assert_called_once_with([self.DEFAULT_ROUTE]) + + def test_edited_routes_are_checked_even_while_inheriting_the_default(self, client): + edited = "mailtos://user:pass@10.0.0.5?to=b@example.com" + with ( + self._inherit_admin_default(), + patch("shelfmark.config.notifications_settings.send_test_notification") as send, + ): + resp = client.post(self.URL, json={"routes": [{"event": "all", "url": edited}]}) + + assert resp.status_code == 400 + assert "refused" in resp.json["message"] + send.assert_not_called()