diff --git a/zerver/lib/message.py b/zerver/lib/message.py index e0d54dfd47..8de57e4dab 100644 --- a/zerver/lib/message.py +++ b/zerver/lib/message.py @@ -77,8 +77,10 @@ from zerver.models import ( UserTopic, ) from zerver.models.constants import MAX_TOPIC_NAME_LENGTH +from zerver.models.groups import SystemGroups from zerver.models.messages import get_usermessage_by_message_id from zerver.models.realms import get_fake_email_domain +from zerver.models.users import is_cross_realm_bot_email class MessageDetailsDict(TypedDict, total=False): @@ -1756,9 +1758,20 @@ def check_user_group_mention_allowed(sender: UserProfile, user_group_ids: List[i user_groups = UserGroup.objects.filter(id__in=user_group_ids).select_related( "can_mention_group" ) + sender_is_system_bot = is_cross_realm_bot_email(sender.delivery_email) for group in user_groups: can_mention_group = group.can_mention_group + + if sender_is_system_bot: + if can_mention_group.name == SystemGroups.EVERYONE: + continue + raise JsonableError( + _( + "You are not allowed to mention user group '{user_group_name}'. You must be a member of '{can_mention_group_name}' to mention this group." + ).format(user_group_name=group.name, can_mention_group_name=can_mention_group.name) + ) + if not is_user_in_group(can_mention_group, sender, direct_member_only=False): raise JsonableError( _( diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py index bfd4ac5e82..7df5eb5ff9 100644 --- a/zerver/tests/test_message_send.py +++ b/zerver/tests/test_message_send.py @@ -2174,6 +2174,34 @@ class StreamMessagesTest(ZulipTestCase): result = self.api_get(shiva, "/api/v1/messages/" + str(msg_id)) self.assert_json_success(result) + # Test system bots. + content = "Test mentioning user group @*support*" + members_group = UserGroup.objects.get( + name=SystemGroups.MEMBERS, realm=iago.realm, is_system_group=True + ) + support.can_mention_group = members_group + support.save() + + internal_realm = get_realm(settings.SYSTEM_BOT_REALM) + system_bot = get_system_bot(settings.EMAIL_GATEWAY_BOT, internal_realm.id) + with self.assertRaisesRegex( + JsonableError, + f"You are not allowed to mention user group '{support.name}'. You must be a member of '{members_group.name}' to mention this group.", + ): + self.send_stream_message(system_bot, "test_stream", content, recipient_realm=iago.realm) + + everyone_group = UserGroup.objects.get( + name=SystemGroups.EVERYONE, realm=iago.realm, is_system_group=True + ) + support.can_mention_group = everyone_group + support.save() + + msg_id = self.send_stream_message( + system_bot, "test_stream", content, recipient_realm=iago.realm + ) + result = self.api_get(shiva, "/api/v1/messages/" + str(msg_id)) + self.assert_json_success(result) + def test_stream_message_mirroring(self) -> None: user = self.mit_user("starnine") self.subscribe(user, "Verona")