Files
galaxy/test/unit/app/managers/test_NotificationManager.py

877 lines
40 KiB
Python

from datetime import (
datetime,
timedelta,
)
from typing import (
Any,
cast,
)
from unittest.mock import (
MagicMock,
patch,
)
import pytest
from pydantic import ValidationError
from galaxy.exceptions import ObjectNotFound
from galaxy.managers.notification import (
DefaultStrategy,
EmailNotificationChannelPlugin,
NOTIFICATION_PREFERENCES_SECTION_NAME,
NotificationManager,
NotificationRecipientResolver,
TemplateFormats,
ToolInstallationRequestEmailNotificationTemplateBuilder,
)
from galaxy.model import (
DatasetStorageOperationRun,
Group,
Role,
User,
)
from galaxy.schema.fields import Security
from galaxy.schema.notifications import (
BroadcastNotificationContent,
BroadcastNotificationCreateRequest,
InternalNotificationCreateData,
NotificationBroadcastUpdateRequest,
NotificationCategorySettings,
NotificationChannelSettings,
NotificationCreateData,
NotificationCreatedResponse,
NotificationCreateRequest,
NotificationRecipients,
NotificationVariant,
PersonalNotificationCategory,
RequestedTool,
StoredToolInstallationRequestContent,
ToolInstallationRequestCreateContent,
UpdateUserNotificationPreferencesRequest,
UserNotificationPreferences,
UserNotificationResponse,
UserNotificationUpdateRequest,
)
from galaxy.schema.storage_operations import (
StorageOperationExecutionResult,
StorageOperationRunState,
)
from galaxy.util import now
from .base import BaseTestCase
class NotificationsBaseTestCase(BaseTestCase):
def _create_test_user(self, username="user1") -> User:
user_data = dict(email=f"{username}@user.email", username=username, password="password")
user = self.user_manager.create(**user_data)
return user
def _create_test_users(self, num_users: int = 1) -> list[User]:
users = [self._create_test_user(f"username{num:02}") for num in range(num_users)]
return users
class NotificationManagerBaseTestCase(NotificationsBaseTestCase):
def set_up_managers(self):
super().set_up_managers()
self.notification_manager = NotificationManager(self.trans.sa_session, self.app.config)
def _default_test_notification_data(self):
"""Dictionary with default values for a simple Message notification."""
return {
"source": "testing",
"variant": "info",
"category": "message",
"content": {
"category": "message",
"subject": "Testing Subject",
"message": "Testing Message",
},
}
def _send_message_notification_to_users(self, users: list[User], notification: dict[str, Any] | None = None):
data = self._default_test_notification_data()
if notification:
data.update(notification)
notification_data = InternalNotificationCreateData(**data)
request = NotificationCreateRequest(
recipients=NotificationRecipients.model_construct(
user_ids=[user.id for user in users],
),
notification=notification_data,
galaxy_url="https://test.galaxy.url",
)
created_notification, notifications_sent = self.notification_manager.send_notification_to_recipients(request)
return created_notification, notifications_sent
def _has_expired(self, expiration_time: datetime | None) -> bool:
return expiration_time < now() if expiration_time else False
def _assert_notification_expected(self, actual_notification: Any, expected_notification: dict[str, Any]):
assert actual_notification
assert actual_notification.id
assert actual_notification.source == expected_notification["source"]
assert actual_notification.variant == expected_notification["variant"]
assert actual_notification.category == expected_notification["category"]
if expected_publication_time := expected_notification.get("publication_time"):
assert actual_notification.publication_time == expected_publication_time
else:
assert actual_notification.publication_time is not None
if expected_expiration_time := expected_notification.get("expiration_time"):
assert actual_notification.expiration_time == expected_expiration_time
else:
assert actual_notification.expiration_time is not None
assert actual_notification.content
user_notification_content = actual_notification.content
assert user_notification_content["category"] == expected_notification["content"]["category"]
assert user_notification_content["subject"] == expected_notification["content"]["subject"]
assert user_notification_content["message"] == expected_notification["content"]["message"]
class NotificationManagerBaseTestCaseWithTasks(NotificationManagerBaseTestCase):
def set_up_managers(self):
super().set_up_managers()
self.app.config.enable_celery_tasks = True
self.notification_manager = NotificationManager(self.trans.sa_session, self.app.config)
class TestBroadcastNotifications(NotificationManagerBaseTestCase):
def test_create_notification_broadcast(self):
data = self._default_broadcast_notification_data()
actual_notification = self._send_broadcast_notification(data)
assert actual_notification.id
assert actual_notification.category == "broadcast"
notification_content = actual_notification.content
assert notification_content["category"] == "broadcast"
assert notification_content["subject"] == "Testing Broadcast Subject"
assert notification_content["message"] == "Testing Broadcast Message"
action_links = notification_content["action_links"]
assert len(action_links) == 1
assert action_links[0]["action_name"] == "Go to Survey"
assert action_links[0]["link"] == "https://link_to_anonymous.test/survey"
def test_get_broadcasted_notification(self):
notification_data = self._default_broadcast_notification_data()
created_notification = self._send_broadcast_notification(notification_data)
actual_notification = self.notification_manager.get_broadcasted_notification(created_notification.id)
assert actual_notification.id == created_notification.id
def test_get_all_broadcasted_notifications(self):
current_time = now()
next_week = current_time + timedelta(days=7)
next_month = current_time + timedelta(days=30)
notification_data = self._default_broadcast_notification_data()
notification_data["content"]["subject"] = "Recent Notification"
notification_data["publication_time"] = current_time
self._send_broadcast_notification(notification_data)
notification_data = self._default_broadcast_notification_data()
notification_data["content"]["subject"] = "Scheduled Next Week Notification"
notification_data["publication_time"] = next_week
self._send_broadcast_notification(notification_data)
notification_data = self._default_broadcast_notification_data()
notification_data["content"]["subject"] = "Scheduled Next Month Notification"
notification_data["publication_time"] = next_month
self._send_broadcast_notification(notification_data)
notifications = self.notification_manager.get_all_broadcasted_notifications()
assert len(notifications) == 1
assert notifications[0].content["subject"] == "Recent Notification"
notifications = self.notification_manager.get_all_broadcasted_notifications(since=next_week, active_only=False)
assert len(notifications) == 2
assert notifications[0].content["subject"] == "Scheduled Next Week Notification"
assert notifications[1].content["subject"] == "Scheduled Next Month Notification"
notifications = self.notification_manager.get_all_broadcasted_notifications(since=next_month, active_only=False)
assert len(notifications) == 1
assert notifications[0].content["subject"] == "Scheduled Next Month Notification"
def test_update_broadcasted_notification(self):
next_month = now() + timedelta(days=30)
notification_data = self._default_broadcast_notification_data()
notification_data["content"]["subject"] = "Old Scheduled Notification"
notification_data["publication_time"] = next_month
actual_notification = self._send_broadcast_notification(notification_data)
current_time = now()
expected_content = BroadcastNotificationContent(subject="Updated Notification", message="Updated Message")
update_request = NotificationBroadcastUpdateRequest(
source="updated_source",
variant=NotificationVariant.warning,
publication_time=current_time,
content=expected_content,
)
updated_count = self.notification_manager.update_broadcasted_notification(
actual_notification.id, update_request
)
assert updated_count == 1
updated_notification = self.notification_manager.get_broadcasted_notification(actual_notification.id)
assert updated_notification.source == update_request.source
assert updated_notification.variant == update_request.variant
assert updated_notification.publication_time == update_request.publication_time
content = updated_notification.content
assert content["subject"] == expected_content.subject
assert content["message"] == expected_content.message
def test_cleanup_expired_broadcast_notifications(self):
one_hour_ago = now() - timedelta(hours=1)
notification_data = self._default_broadcast_notification_data()
notification_data["expiration_time"] = one_hour_ago
actual_notification = self._send_broadcast_notification(notification_data)
assert self._has_expired(actual_notification.expiration_time) is True
result = self.notification_manager.cleanup_expired_notifications()
assert result.deleted_notifications_count == 1
assert result.deleted_associations_count == 0
with pytest.raises(ObjectNotFound):
self.notification_manager.get_broadcasted_notification(actual_notification.id, active_only=False)
def _default_broadcast_notification_data(self):
return {
"source": "testing",
"variant": "warning",
"content": {
"category": "broadcast",
"subject": "Testing Broadcast Subject",
"message": "Testing Broadcast Message",
"action_links": [
{
"action_name": "Go to Survey",
"link": "https://link_to_anonymous.test/survey",
},
],
},
}
def _send_broadcast_notification(self, broadcast_notification_data: dict[str, Any]):
request = BroadcastNotificationCreateRequest(**broadcast_notification_data)
created_notification = self.notification_manager.create_broadcast_notification(request)
return created_notification
class TestUserNotifications(NotificationManagerBaseTestCase):
def test_create_notification_for_users(self):
num_target_users = 2
users = self._create_test_users(num_users=num_target_users)
expected_notification = self._default_test_notification_data()
expected_notification["source"] = "test_create_notification_for_users"
actual_notification, actual_notifications_sent = self._send_message_notification_to_users(
users, notification=expected_notification
)
assert actual_notifications_sent == num_target_users
self._assert_notification_expected(actual_notification, expected_notification)
def test_send_storage_operation_notification(self):
user = self._create_test_user()
run = DatasetStorageOperationRun(
id=7,
history_id=11,
mode="move",
total_count=3,
succeeded_count=3,
failed_count=0,
skipped_count=0,
)
notification, sent_count = self.notification_manager.send_storage_operation_notification(
user_id=user.id,
run=run,
execution_result=StorageOperationExecutionResult(
state=StorageOperationRunState.completed,
message="Bulk move completed.",
),
encode_id=lambda value: f"encoded-{value}",
)
assert sent_count == 1
assert notification is not None
assert notification.category == PersonalNotificationCategory.storage_operation
content = cast(dict[str, Any], notification.content)
assert content["state"] == StorageOperationRunState.completed.value
assert content["history_id"] == "encoded-11"
assert content["run_id"] == "encoded-7"
def test_notifications_expire_six_months_after_they_are_created(self):
user = self._create_test_users(num_users=1)[0]
created = datetime(2030, 1, 1)
with patch("galaxy.model.now", return_value=created):
notification, _ = self._send_message_notification_to_users([user])
assert notification.expiration_time == created + timedelta(days=30 * 6)
def test_get_user_notifications(self):
user = self._create_test_user()
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 0
self._send_message_notification_to_users([user])
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 1
def test_get_user_notification(self):
user = self._create_test_user()
expected_user_notification = self._default_test_notification_data()
notification, _ = self._send_message_notification_to_users([user], notification=expected_user_notification)
actual_user_notification = self.notification_manager.get_user_notification(user, notification.id)
self._assert_notification_expected(actual_user_notification, expected_user_notification)
assert actual_user_notification._mapping["seen_time"] is None
assert actual_user_notification._mapping["deleted"] is False
def test_update_user_notifications(self):
user = self._create_test_user()
notification, _ = self._send_message_notification_to_users([user])
user_notification = self.notification_manager.get_user_notification(user, notification.id)
assert user_notification.seen_time is None
assert user_notification.deleted is False
request = UserNotificationUpdateRequest(seen=True)
self.notification_manager.update_user_notifications(user, {notification.id}, request)
user_notification = self.notification_manager.get_user_notification(user, notification.id)
assert user_notification.seen_time is not None
assert user_notification.deleted is False
def test_scheduled_notifications(self):
user = self._create_test_user()
tomorrow = now() + timedelta(hours=24)
expected_notification = self._default_test_notification_data()
expected_notification["source"] = "test_scheduled"
expected_notification["publication_time"] = tomorrow
actual_notification, actual_notifications_sent = self._send_message_notification_to_users(
[user], notification=expected_notification
)
assert actual_notifications_sent == 1
self._assert_notification_expected(actual_notification, expected_notification)
# The user cannot access the notification
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 0
with pytest.raises(ObjectNotFound):
self.notification_manager.get_user_notification(user, actual_notification.id)
# Because is not active yet
active_only = False
user_notification = self.notification_manager.get_user_notification(
user, actual_notification.id, active_only=active_only
)
self._assert_notification_expected(user_notification, expected_notification)
def test_get_user_notification_preferences_returns_default_preferences(self):
user = self._create_test_user()
default_preferences = UserNotificationPreferences.default()
actual_preferences = self.notification_manager.get_user_notification_preferences(user)
assert actual_preferences == default_preferences
def test_old_preferences_include_new_categories_without_changing_saved_settings(self):
user = self._create_test_user()
user.preferences[NOTIFICATION_PREFERENCES_SECTION_NAME] = UserNotificationPreferences(
preferences={PersonalNotificationCategory.message: NotificationCategorySettings(enabled=False)}
).model_dump_json()
expected = UserNotificationPreferences.default()
expected.preferences[PersonalNotificationCategory.message].enabled = False
assert self.notification_manager.get_user_notification_preferences(user) == expected
def test_update_user_notification_preferences(self):
user = self._create_test_user()
preferences = self.notification_manager.get_user_notification_preferences(user)
message_preferences = preferences.get(PersonalNotificationCategory.message)
assert message_preferences
assert message_preferences.enabled is True
assert message_preferences.channels.push is True
update_request = UpdateUserNotificationPreferencesRequest(
preferences={
PersonalNotificationCategory.message: NotificationCategorySettings(
enabled=False,
channels=NotificationChannelSettings(push=False),
),
}
)
updated_preferences = self.notification_manager.update_user_notification_preferences(user, update_request)
updated_preferences = self.notification_manager.get_user_notification_preferences(user)
message_preferences = updated_preferences.get(PersonalNotificationCategory.message)
assert message_preferences
assert message_preferences.enabled is False
assert message_preferences.channels.push is False
def test_cleanup_expired_notifications(self):
user = self._create_test_user()
current_time = now()
notification, _ = self._send_message_notification_to_users(
[user], notification={"expiration_time": current_time}
)
user_notification = self.notification_manager.get_user_notification(user, notification.id, active_only=False)
assert user_notification
assert self._has_expired(user_notification.expiration_time) is True
result = self.notification_manager.cleanup_expired_notifications()
assert result.deleted_notifications_count == 1
assert result.deleted_associations_count == 1
with pytest.raises(ObjectNotFound):
self.notification_manager.get_user_notification(user, notification.id, active_only=False)
def test_users_do_not_receive_opt_out_notifications(self):
users = self._create_test_users(num_users=2)
user_opt_out = users[0]
user_opt_in = users[1]
update_request = UpdateUserNotificationPreferencesRequest(
preferences={
PersonalNotificationCategory.message: NotificationCategorySettings(enabled=False),
}
)
self.notification_manager.update_user_notification_preferences(user_opt_out, update_request)
self._send_message_notification_to_users(users)
user_notifications = self.notification_manager.get_user_notifications(user_opt_out)
assert len(user_notifications) == 0
user_notifications = self.notification_manager.get_user_notifications(user_opt_in)
assert len(user_notifications) == 1
def test_urgent_notifications_ignore_preferences(self):
user = self._create_test_user()
update_request = UpdateUserNotificationPreferencesRequest(
preferences={
PersonalNotificationCategory.message: NotificationCategorySettings(enabled=False),
}
)
self.notification_manager.update_user_notification_preferences(user, update_request)
# Send normal message notification
notification_data = self._default_test_notification_data()
self._send_message_notification_to_users([user], notification=notification_data)
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 0
# Send urgent message notification
notification_data["variant"] = NotificationVariant.urgent
self._send_message_notification_to_users([user], notification=notification_data)
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 1
def test_send_via_channels_uses_all_channel_fields(self):
user = self._create_test_user()
notification_data = NotificationCreateData(**self._default_test_notification_data())
notification = self.notification_manager._create_notification_model(notification_data)
push_plugin = MagicMock()
email_plugin = MagicMock()
self.notification_manager.channel_plugins = {
"push": push_plugin,
"email": email_plugin,
}
# `email` remains at its default value (True) and should still be considered.
channel_settings = NotificationChannelSettings(push=False)
self.notification_manager._send_via_channels(notification, user, channel_settings)
push_plugin.send.assert_not_called()
email_plugin.send.assert_called_once_with(notification, user)
class TestUserNotificationsWithTasks(NotificationManagerBaseTestCaseWithTasks):
def test_urgent_notifications_via_email_channel(self):
user = self._create_test_user()
# Disable email channel only
update_request = UpdateUserNotificationPreferencesRequest(
preferences={
PersonalNotificationCategory.message: NotificationCategorySettings(
enabled=True,
channels=NotificationChannelSettings(email=False),
),
}
)
self.notification_manager.update_user_notification_preferences(user, update_request)
emails_sent = []
def validate_send_email(frm, to, subject, body, config, html=None):
emails_sent.append(
{
"frm": frm,
"to": to,
"subject": subject,
"body": body,
"config": config,
"html": html,
}
)
with patch("galaxy.util.send_mail", side_effect=validate_send_email) as mock_send_mail:
notification_data = self._default_test_notification_data()
# Send normal message notification
self._send_message_notification_to_users([user], notification=notification_data)
# The in-app notification should be sent but the email notification should not be sent after dispatching
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 1
self.notification_manager.dispatch_pending_notifications_via_channels()
mock_send_mail.assert_not_called()
# Send urgent message notification
notification_data["variant"] = NotificationVariant.urgent
self._send_message_notification_to_users([user], notification=notification_data)
# The in-app notification should be sent, now there are 2 notifications
user_notifications = self.notification_manager.get_user_notifications(user)
assert len(user_notifications) == 2
# The email notification should be sent after dispatching the pending notifications
self.notification_manager.dispatch_pending_notifications_via_channels()
mock_send_mail.assert_called_once()
assert len(emails_sent) == 1
def test_force_sync_creates_notification_without_dispatching_email_channel_when_async_is_enabled(self):
user = self._create_test_user()
# The response model encodes ids via the process-global Security.security;
# patch it for this test only so the helper does not leak into later tests.
with patch.object(Security, "security", self.trans.security, create=True):
self._assert_force_sync_creates_notification_without_dispatching_email(user)
def _assert_force_sync_creates_notification_without_dispatching_email(self, user: User):
request = NotificationCreateRequest(
recipients=NotificationRecipients.model_construct(user_ids=[user.id]),
notification=InternalNotificationCreateData(**self._default_test_notification_data()),
galaxy_url="https://test.galaxy.url",
)
with patch("galaxy.util.send_mail") as mock_send_mail:
response = self.notification_manager.send_notification_internal(request, force_sync=True)
assert isinstance(response, NotificationCreatedResponse)
assert response.total_notifications_sent == 1
mock_send_mail.assert_not_called()
assert "email" in self.notification_manager.get_supported_channels()
pending_notifications = self.notification_manager.get_pending_notifications()
assert len(pending_notifications) == 1
assert pending_notifications[0].category == response.notification.category
with patch("galaxy.util.send_mail") as mock_send_mail:
dispatched_count = self.notification_manager.dispatch_pending_notifications_via_channels()
assert dispatched_count == 1
mock_send_mail.assert_called_once()
assert self.notification_manager.get_pending_notifications() == []
def test_dispatch_now_queues_delivery_instead_of_waiting_for_the_dispatcher(self):
user = self._create_test_user()
with patch("galaxy.celery.tasks.dispatch_notification.delay") as queue_dispatch:
notification, _ = self._send_dispatch_now_notification(user)
queue_dispatch.assert_called_once_with(notification_id=notification.id)
assert self.notification_manager.get_pending_notifications() == []
with patch("galaxy.util.send_mail") as mock_send_mail:
self.notification_manager.dispatch_notification_via_channels(notification.id)
mock_send_mail.assert_called_once()
def test_dispatch_now_leaves_notification_to_the_dispatcher_when_queueing_fails(self):
user = self._create_test_user()
with patch("galaxy.celery.tasks.dispatch_notification.delay", side_effect=ConnectionError("broker down")):
notification, _ = self._send_dispatch_now_notification(user)
assert self.notification_manager.get_pending_notifications() == [notification]
def _send_dispatch_now_notification(self, user: User):
request = NotificationCreateRequest(
recipients=NotificationRecipients.model_construct(user_ids=[user.id]),
notification=InternalNotificationCreateData(**self._default_test_notification_data()),
galaxy_url="https://test.galaxy.url",
dispatch_now=True,
)
return self.notification_manager.send_notification_to_recipients(request)
class TestNotificationRecipientResolver(NotificationsBaseTestCase):
def test_default_resolution_strategy(self):
recipients, expected_user_ids = self._create_test_recipients_scenario()
resolver = NotificationRecipientResolver(strategy=DefaultStrategy(self.trans.sa_session))
resolved_users = resolver.resolve(recipients)
self._assert_resolved_match_expected_users(resolved_users, expected_user_ids)
def _create_test_recipients_scenario(self):
"""Creates a slightly 'complex' hierarchy combination of groups and roles
for testing recipient users resolution."""
users = self._create_test_users(num_users=10)
group1 = self._create_test_group(
"Group1",
users=[users[0], users[1]],
roles=[],
)
role1 = self._create_test_role(
"Role1",
users=[users[3], users[5]],
groups=[],
)
group2 = self._create_test_group(
"Group2",
users=[users[1], users[2]],
roles=[role1],
)
role2 = self._create_test_role(
"Role2",
users=[users[4]],
groups=[group2],
)
group3 = self._create_test_group(
"Group3",
users=[users[5]],
roles=[role2],
)
role3 = self._create_test_role(
"Role3",
users=[users[7]],
groups=[group1],
)
recipients = NotificationRecipients.model_construct(
user_ids=[users[9].id],
group_ids=[group3.id],
role_ids=[role3.id],
)
expected_user_ids: set[int] = {
users[9].id, # From direct recipients.user_ids
users[5].id, # From group3.user_ids
users[4].id, # -From role2.user_ids
users[1].id, # --From group2.user_ids
users[2].id, # --From group2.user_ids
users[3].id, # ---From role1.user_ids
users[5].id, # ---From role1.user_ids (duplicated)
users[7].id, # From role3.user_ids
users[0].id, # -From group1.user_ids
users[1].id, # -From group1.user_ids (duplicated)
}
return recipients, expected_user_ids
def _assert_resolved_match_expected_users(self, resolved_users: list[User], expected_user_ids: set[int]):
assert len(resolved_users) == len(expected_user_ids)
for user in resolved_users:
assert user.id in expected_user_ids
def _create_test_group(self, name: str, users: list[User], roles: list[Role]):
sa_session = self.trans.sa_session
group = Group(name=name)
sa_session.add(group)
user_ids = [user.id for user in users]
role_ids = [role.id for role in roles]
self.trans.app.security_agent.set_group_user_and_role_associations(group, user_ids=user_ids, role_ids=role_ids)
return group
def _create_test_role(self, name: str, users: list[User], groups: list[Group]):
sa_session = self.trans.sa_session
role = Role(name=name)
sa_session.add(role)
for user in users:
self.trans.app.security_agent.associate_user_role(user, role)
for group in groups:
self.trans.app.security_agent.associate_group_role(group, role)
sa_session.flush()
return role
class TestUserNotificationPreferencesFallback:
def test_get_falls_back_to_default_for_a_category_missing_from_the_stored_blob(self):
# Preferences saved before a category existed have no key for it; a
# KeyError here would drop the notification when associations are created.
stale_blob = {
PersonalNotificationCategory.message: {
"enabled": True,
"channels": {"push": True, "email": True, "webhook": False},
}
}
preferences = UserNotificationPreferences.model_validate({"preferences": stale_blob})
settings = preferences.get(PersonalNotificationCategory.tool_installation_request)
assert settings == NotificationCategorySettings()
assert settings.enabled is True
assert settings.channels.push is True
class TestToolInstallationRequestContentValidation:
def test_control_characters_are_collapsed_in_single_line_fields(self):
tool = RequestedTool(name="FastQC\nEvil", requested_version="1.0\r2")
assert tool.name == "FastQC Evil"
assert tool.requested_version == "1.0 2"
def test_whitespace_only_identifier_is_rejected(self):
with pytest.raises(ValidationError):
RequestedTool(name=" ")
def test_multiline_fields_keep_newlines_but_drop_other_control_characters(self):
content = ToolInstallationRequestCreateContent(
tools=[RequestedTool(name="bwa")],
additional_remarks="line1\r\nline2\x00x",
)
assert content.additional_remarks == "line1\nline2 x"
def test_non_http_tool_url_is_rejected(self):
with pytest.raises(ValidationError):
RequestedTool(tool_url="javascript:alert(1)")
def test_unicode_line_separators_are_sanitized(self):
# NEL in single-line fields collapses to a space; in multiline fields
# Unicode line/paragraph separators normalize to newlines.
tool = RequestedTool(name="FastQC\x85Evil", description="l1\u2028l2\u2029l3")
assert tool.name == "FastQC Evil"
assert tool.description == "l1\nl2\nl3"
def test_crlf_text_fitting_after_normalization_is_accepted(self):
# Raw length exceeds the bound, sanitized length does not.
remarks = ("y\r\n" * 2000).rstrip()
assert len(remarks) > 5000
content = ToolInstallationRequestCreateContent(tools=[RequestedTool(name="bwa")], additional_remarks=remarks)
assert content.additional_remarks == "\n".join(["y"] * 2000)
def test_uppercase_url_scheme_is_accepted(self):
assert RequestedTool(tool_url="HTTPS://example.com/tool").tool_url == "HTTPS://example.com/tool"
def test_mismatched_envelope_and_content_category_is_rejected(self):
with pytest.raises(ValidationError, match="does not match"):
NotificationCreateData.model_validate(
{
"source": "s",
"category": "tool_installation_request",
"variant": "info",
"content": {"category": "message", "subject": "x", "message": "y"},
}
)
def test_every_unicode_format_character_is_stripped(self):
# The filter is by general category (Cf), not an enumerated list: the
# RTL override (U+202E) must not survive into rendered labels, and bidi
# marks outside the classic ranges (U+061C ARABIC LETTER MARK) go too.
tool = RequestedTool(name="a\u202eevil\u202cb\u061c", description="l1\n\u061cl2")
assert tool.name == "aevilb"
assert tool.description == "l1\nl2"
# A name made only of format characters (zero-width space, tag characters) is not an identifier.
for name in ("\u200b", "\U000e0041\U000e0042", "\u061c"):
with pytest.raises(ValidationError):
RequestedTool(name=name)
def test_subject_tool_label_is_truncated_for_header_safety(self):
tool = RequestedTool(tool_url="https://example.org/" + "x" * 1500)
label = ToolInstallationRequestEmailNotificationTemplateBuilder._tool_label(tool)
assert len(label) <= ToolInstallationRequestEmailNotificationTemplateBuilder._SUBJECT_LABEL_MAX_LENGTH + 3
assert label.endswith("...")
# Short labels are untouched.
assert ToolInstallationRequestEmailNotificationTemplateBuilder._tool_label(RequestedTool(name="bwa")) == "bwa"
def test_bounds_are_enforced(self):
with pytest.raises(ValidationError):
RequestedTool(name="x" * 256)
with pytest.raises(ValidationError):
ToolInstallationRequestCreateContent(tools=[RequestedTool(name="bwa")], additional_remarks="x" * 5001)
with pytest.raises(ValidationError):
ToolInstallationRequestCreateContent(tools=[RequestedTool(name=f"tool-{i}") for i in range(51)])
class TestMessageEmailBuilder(NotificationManagerBaseTestCase):
@pytest.mark.parametrize(
"category",
[
PersonalNotificationCategory.message,
PersonalNotificationCategory.workflow_execution_completed,
PersonalNotificationCategory.tool_execution_completed,
],
)
def test_html_email_renders_the_message_markdown_and_escapes_the_subject(self, category):
user = self._create_test_user()
notification, _ = self._send_message_notification_to_users(
[user],
notification={
"category": category,
"content": {"category": category, "subject": "<i>Maintenance</i>", "message": "**Downtime** tonight"},
},
)
builder_class = EmailNotificationChannelPlugin.email_templates_by_category[category]
builder = builder_class(self.app.config, notification, user)
html = builder.get_body(TemplateFormats.HTML)
assert "<strong>Downtime</strong>" in html
assert "&lt;i&gt;Maintenance&lt;/i&gt;" in html
class TestToolInstallationRequestEmailBuilder(NotificationManagerBaseTestCase):
"""The email builder renders from the stored content alone, without a database lookup."""
def _send_stored_request(self, user: User, **content_overrides):
content = StoredToolInstallationRequestContent.model_validate(
{
"tools": [RequestedTool(name="bwa")],
"workflow_id": "deadbeef",
"workflow_name": "Mapping pipeline",
"requester_email": "requester@user.email",
**content_overrides,
}
)
request = NotificationCreateRequest(
recipients=NotificationRecipients.model_construct(user_ids=[user.id]),
notification=InternalNotificationCreateData(
source="tool_installation_request_form",
category=PersonalNotificationCategory.tool_installation_request,
variant=NotificationVariant.info,
content=content,
),
galaxy_url="https://test.galaxy.url",
)
notification, _ = self.notification_manager.send_notification_to_recipients(request)
assert notification
return notification
def test_admin_email_renders_the_stamped_workflow_name(self):
admin = self._create_test_user()
notification = self._send_stored_request(admin)
builder = ToolInstallationRequestEmailNotificationTemplateBuilder(self.app.config, notification, admin)
assert "Mapping pipeline" in builder.get_body(TemplateFormats.TXT)
assert "Mapping pipeline" in builder.get_body(TemplateFormats.HTML)
assert "confirmation" not in builder.get_template_path(TemplateFormats.TXT)
assert builder.get_subject() == "[Galaxy] Tool installation request: bwa"
def test_admin_html_email_escapes_request_fields(self):
admin = self._create_test_user()
notification = self._send_stored_request(
admin, tools=[RequestedTool(name="<script>alert(1)</script>")], workflow_name="<b>Mapping</b>"
)
builder = ToolInstallationRequestEmailNotificationTemplateBuilder(self.app.config, notification, admin)
html = builder.get_body(TemplateFormats.HTML)
assert "&lt;script&gt;alert(1)&lt;/script&gt;" in html
assert "&lt;b&gt;Mapping&lt;/b&gt;" in html
assert "<script>" not in html
assert "<b>Mapping</b>" not in html
def test_confirmation_copy_selects_the_confirmation_template(self):
requester = self._create_test_user()
notification = self._send_stored_request(requester, is_confirmation=True)
builder = ToolInstallationRequestEmailNotificationTemplateBuilder(self.app.config, notification, requester)
assert "confirmation" in builder.get_template_path(TemplateFormats.TXT)
assert builder.get_subject() == "[Galaxy] Tool installation request submitted: bwa"
def test_server_only_fields_do_not_reach_the_response_model(self):
admin = self._create_test_user()
self._send_stored_request(admin)
user_notification = self.notification_manager.get_user_notifications(admin)[0]
with patch.object(Security, "security", self.trans.security, create=True):
response = UserNotificationResponse.model_validate(user_notification)
content = response.content.model_dump()
assert content["requester_email"] == "requester@user.email"
assert "is_confirmation" not in content
assert "workflow_name" not in content