Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
users: Add backend for deactivating a user as spammer.
whilstsomebody4c4eabb73d7e
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 6e48d032f7c..6b77773e2fc 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,13 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 459**++* [`DELETE /users/{user_id}`](/api/deactivate-user): Added new+ parameter `actions` that asks the server to perform additional+ actions, such as deleting messages the user sent, while deactivating+ the user.+**Feature level 458*** [`GET users/{user_id}/channels`](/api/get-user-channels): Fixeddiff --git a/version.py b/version.pyindex b2eae803782..0e68fa470d8 100644--- a/version.py+++ b/version.py@@ -35,7 +35,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# new level means in api_docs/changelog.md, as well as "**Changes**"# entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 458+API_FEATURE_LEVEL = 459# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/actions/message_delete.py b/zerver/actions/message_delete.pyindex ad073159035..ae2339cab0b 100644--- a/zerver/actions/message_delete.py+++ b/zerver/actions/message_delete.py@@ -1,9 +1,15 @@+from collections import defaultdictfrom collections.abc import Iterablefrom typing import TypedDict+from django.db.models import Q+from pydantic import BaseModel+from zerver.lib import retentionfrom zerver.lib.retention import move_messages_to_archive+from zerver.lib.streams import get_public_streams_querysetfrom zerver.models import Message, Realm, Stream, UserProfile+from zerver.models.recipients import Recipientfrom zerver.tornado.django_api import send_event_on_commit@@ -15,6 +21,13 @@ class DeleteMessagesEvent(TypedDict, total=False):stream_id: int+class DeactivateUserActions(BaseModel):+ delete_profile: bool = False+ delete_public_channel_messages: bool = False+ delete_private_channel_messages: bool = False+ delete_direct_messages: bool = False++def check_update_first_message_id(realm: Realm, stream: Stream, message_ids: list[int], users_to_notify: Iterable[int]) -> None:@@ -76,3 +89,66 @@ def do_delete_messages_by_sender(user: UserProfile, skip_notify: bool = False) -chunk_size=retention.STREAM_MESSAGE_BATCH_SIZE,skip_notify=skip_notify,)+++def delete_deactivated_user_messages(+ realm: Realm,+ user_profile: UserProfile,+ deactivate_user_actions: DeactivateUserActions,+ acting_user: UserProfile | None,+) -> None:+ delete_public_channel_messages = deactivate_user_actions.delete_public_channel_messages+ delete_private_channel_messages = deactivate_user_actions.delete_private_channel_messages+ delete_direct_messages = deactivate_user_actions.delete_direct_messages++ if not (+ delete_public_channel_messages or delete_private_channel_messages or delete_direct_messages+ ):+ return++ message_filter_query = Q()+ message_exclude_query = Q()++ if delete_direct_messages:+ message_filter_query |= Q(recipient__type=Recipient.DIRECT_MESSAGE_GROUP)++ public_channel_ids = get_public_streams_queryset(realm).values_list("id", flat=True)+ if delete_public_channel_messages and delete_private_channel_messages:+ message_filter_query |= Q(recipient__type=Recipient.STREAM)+ elif delete_public_channel_messages:+ message_filter_query |= Q(+ recipient__type=Recipient.STREAM,+ recipient__type_id__in=list(public_channel_ids),+ )+ elif delete_private_channel_messages:+ message_filter_query |= Q(recipient__type=Recipient.STREAM)+ message_exclude_query |= Q(+ recipient__type=Recipient.STREAM,+ recipient__type_id__in=list(public_channel_ids),+ )++ messages = list(+ Message.objects.filter(sender=user_profile, realm_id=user_profile.realm_id)+ .filter(message_filter_query)+ .exclude(message_exclude_query)+ .select_related("recipient")+ )+ do_delete_messages(user_profile.realm, messages, acting_user=acting_user)++ # 1:1 DMs need to be handled separately as we need to group them by conversation+ if delete_direct_messages:+ direct_messages = list(+ Message.objects.filter(+ sender=user_profile,+ realm_id=user_profile.realm_id,+ recipient__type=Recipient.PERSONAL,+ ).select_related("recipient")+ )++ personal_messages_by_recipient_dict: defaultdict[int, list[Message]] = defaultdict(list)+ for message in direct_messages:+ recipient_user_id = message.recipient.type_id+ personal_messages_by_recipient_dict[recipient_user_id].append(message)++ for conversation_messages in personal_messages_by_recipient_dict.values():+ do_delete_messages(user_profile.realm, conversation_messages, acting_user=acting_user)diff --git a/zerver/actions/users.py b/zerver/actions/users.pyindex 2b3288de89b..76b10e6b363 100644--- a/zerver/actions/users.py+++ b/zerver/actions/users.py@@ -13,13 +13,18 @@ from django.utils.http import urlsafe_base64_encodefrom django.utils.timezone import now as timezone_nowfrom django.utils.translation import get_language-from zerver.actions.message_delete import do_delete_messages_by_sender+from zerver.actions.message_delete import (+ DeactivateUserActions,+ delete_deactivated_user_messages,+ do_delete_messages_by_sender,+)from zerver.actions.message_send import send_user_profile_update_notificationfrom zerver.actions.streams import bulk_remove_subscriptions, send_peer_remove_eventsfrom zerver.actions.user_groups import (do_send_user_group_members_update_event,update_users_in_full_members_system_group,)+from zerver.actions.user_settings import do_change_avatar_fields, do_change_full_namefrom zerver.lib.avatar import get_avatar_fieldfrom zerver.lib.bot_config import ConfigError, get_bot_config, get_bot_configs, set_bot_configfrom zerver.lib.cache import bot_dict_fields, flush_user_profile@@ -468,7 +473,11 @@ def send_events_for_user_deactivation(user_profile: UserProfile) -> None:def do_deactivate_user(- user_profile: UserProfile, _cascade: bool = True, *, acting_user: UserProfile | None+ user_profile: UserProfile,+ _cascade: bool = True,+ *,+ acting_user: UserProfile | None,+ deactivate_user_actions: DeactivateUserActions | None = None,) -> None:if not user_profile.is_active:return@@ -481,13 +490,42 @@ def do_deactivate_user(# that a failure partway through this function cannot result# in only the user being deactivated.bot_profiles = get_active_bots_owned_by_user(user_profile)+ # Same policies should be applied to the bots as to the user who created+ # them. If the user is marked as spammer or their content is being+ # deleted, the same should happen with the bots created by that user.for profile in bot_profiles:- do_deactivate_user(profile, _cascade=False, acting_user=acting_user)-+ do_deactivate_user(+ profile,+ _cascade=False,+ acting_user=acting_user,+ deactivate_user_actions=deactivate_user_actions,+ )with transaction.atomic(savepoint=False):change_user_is_active(user_profile, False)clear_scheduled_emails([user_profile.id])+ if deactivate_user_actions is not None:+ if deactivate_user_actions.delete_profile:+ # The full name of spam user is changed to Deleted user.+ if user_profile.full_name != "Deleted user" and not user_profile.is_bot:+ do_change_full_name(+ user_profile, "Deleted user", acting_user=acting_user, notify=False+ )+ elif user_profile.full_name != "Deactivated bot" and user_profile.is_bot:+ do_change_full_name(+ user_profile, "Deactivated bot", acting_user=acting_user, notify=False+ )++ # TODO: Change avatar image to that of an inaccessible user.+ if user_profile.avatar_source != UserProfile.AVATAR_FROM_GRAVATAR:+ do_change_avatar_fields(+ user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=acting_user+ )++ delete_deactivated_user_messages(+ user_profile.realm, user_profile, deactivate_user_actions, acting_user+ )+revoke_invites_generated_by_user(user_profile)event_time = timezone_now()diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.pyindex e601029e5be..8254a4825c6 100644--- a/zerver/lib/test_helpers.py+++ b/zerver/lib/test_helpers.py@@ -347,6 +347,14 @@ def get_user_messages(user_profile: UserProfile) -> list[Message]:return [um.message for um in query]+def get_user_sent_message_ids(user_profile: UserProfile) -> list[int]:+ return list(+ Message.objects.filter(realm_id=user_profile.realm_id, sender=user_profile).values_list(+ "id", flat=True+ )+ )++class DummyHandler(AsyncDjangoHandler):def __init__(self) -> None:self.handler_id = allocate_handler_id(self)diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 215ff60460e..659a27ca455 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -15163,8 +15163,48 @@ paths:[Deactivates auser](https://zulip.com/help/deactivate-or-reactivate-a-user)given their user ID.++ Note that any bots controlled by the user will be deactivated+ before the user; clients that don't want this behavior are+ expected to prompt the user to adjust the bot's owners before+ making this API request.parameters:- $ref: "#/components/parameters/UserId"+ - name: actions+ in: query+ description: |+ Additional actions for the server to perform while deactivating the user.++ As with the actual deactivation, actions are first applied+ to any bots controlled by the target user, and then to the+ target user.++ **Changes**: New in Zulip 12.0 (feature level 459).+ content:+ application/json:+ schema:+ type: object+ properties:+ delete_profile:+ type: boolean+ description: |+ Whether to delete the user's profile by updating their name+ to "Deleted user" and removing their profile picture.+ delete_public_channel_messages:+ type: boolean+ description: Whether to delete messages in public channels.+ delete_private_channel_messages:+ type: boolean+ description: Whether to delete messages in private channels.+ delete_direct_messages:+ type: boolean+ description: Whether to delete direct messages.+ example:+ delete_profile: false+ delete_public_channel_messages: false+ delete_private_channel_messages: false+ delete_direct_messages: false+ required: falserequestBody:required: falsecontent:diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 4a52843a6a8..8b62fc38123 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -50,6 +50,7 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import (get_subscription,get_test_image_file,+ get_user_sent_message_ids,most_recent_message,reset_email_visibility_to_everyone_in_zulip_realm,simulated_empty_cache,@@ -2478,6 +2479,352 @@ class ActivateTest(ZulipTestCase):)+class DeactivateActionsTest(ZulipTestCase):+ # Helper for setting up various types of messages.+ def setup_user_with_messages(+ self, user: UserProfile, admin: UserProfile+ ) -> tuple[list[int], list[int], list[int]]:+ msg_id_1 = self.send_personal_message(user, admin, content="private message 1")+ # Sending dm to a different user.+ msg_id_2 = self.send_personal_message(+ user, self.example_user("aaron"), content="private message 2"+ )+ # Me message+ msg_id_3 = self.send_personal_message(user, user, content="private message 3")+ personal_msg_ids = [msg_id_1, msg_id_2, msg_id_3]++ msg_id_1 = self.send_stream_message(+ user, "Verona", topic_name="topic1", content="channel message 1"+ )+ msg_id_2 = self.send_stream_message(+ user, "Verona", topic_name="topic1", content="channel message 2"+ )+ msg_id_3 = self.send_stream_message(user, "Verona", topic_name="topic2")+ msg_id_4 = self.send_stream_message(user, "Verona")+ public_channel_msg_ids = [msg_id_1, msg_id_2, msg_id_3, msg_id_4]++ private_channel = self.make_stream("private_channel", invite_only=True)+ self.subscribe(user, private_channel.name)+ msg_id_1 = self.send_stream_message(+ user, private_channel.name, topic_name="topic1", content="private channel message 1"+ )+ msg_id_2 = self.send_stream_message(+ user, private_channel.name, topic_name="topic2", content="private channel message 2"+ )+ private_channel_msg_ids = [msg_id_1, msg_id_2]++ return (personal_msg_ids, public_channel_msg_ids, private_channel_msg_ids)++ def test_permission_to_delete_messages_when_deactivating_user(self) -> None:+ admin = self.example_user("iago")+ owner = self.example_user("desdemona")+ cordelia = self.example_user("cordelia")+ aaron = self.example_user("aaron")++ owner_group = NamedUserGroup.objects.get(+ name=SystemGroups.OWNERS, realm=admin.realm, is_system_group=True+ )++ do_change_realm_permission_group_setting(+ admin.realm, "can_delete_any_message_group", owner_group, acting_user=None+ )++ # Non-owner users do not have permission to delete anyone's messages.+ result = self.api_delete(+ admin,+ f"/api/v1/users/{cordelia.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_error(result, "User is not allowed to delete other user's messages.")++ # Admin can still delete the deactivated user's profile.+ result = self.api_delete(+ admin,+ f"/api/v1/users/{cordelia.id}",+ {+ "actions": orjson.dumps({"delete_profile": True}).decode(),+ },+ )+ self.assert_json_success(result)+ cordelia.refresh_from_db()+ self.assertFalse(cordelia.is_active)++ # Owner have permission to delete anyone's messages.+ result = self.api_delete(+ owner,+ f"/api/v1/users/{aaron.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ aaron.refresh_from_db()+ self.assertFalse(aaron.is_active)++ def test_deactivation_without_deleting_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ self.setup_user_with_messages(user, admin)++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ # Test with all actions explicitly set to False+ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": False,+ "delete_private_channel_messages": False,+ "delete_direct_messages": False,+ }+ ).decode(),+ },+ )++ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ do_reactivate_user(user, acting_user=admin)++ result = self.api_delete(admin, f"/api/v1/users/{user.id}")++ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ def test_deactivation_with_deleting_public_channel_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ (dm_msg_ids, _, private_channel_msg_ids) = self.setup_user_with_messages(user, admin)++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ # 4 public channel messages were deleted; 2 private channel messages the 3 DMs remain.+ self.assert_length(user_message_ids, 5)+ self.assertCountEqual(user_message_ids, [*dm_msg_ids, *private_channel_msg_ids])++ def test_deactivation_with_deleting_private_channel_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ (dm_msg_ids, public_channel_msg_ids, _) = self.setup_user_with_messages(user, admin)++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_private_channel_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ # 2 private channel messages deleted out of 9 messages.+ self.assert_length(user_message_ids, 7)+ self.assertCountEqual(user_message_ids, [*public_channel_msg_ids, *dm_msg_ids])++ def test_deactivation_with_deleting_direct_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ hamlet = self.example_user("hamlet")++ (_, public_channel_msg_ids, private_channel_msg_ids) = self.setup_user_with_messages(+ user, admin+ )++ self.send_group_direct_message(user, [admin, hamlet], content="group dm message 1")+ self.send_group_direct_message(user, [admin, hamlet], content="group dm message 2")++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 11)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_direct_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 6)+ self.assertCountEqual(user_message_ids, [*public_channel_msg_ids, *private_channel_msg_ids])++ def test_deactivation_with_deleting_all_channel_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ (dm_msg_ids, _, _) = self.setup_user_with_messages(user, admin)++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": True,+ "delete_private_channel_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ # Only 3 direct messages remain out of 9 messages.+ self.assert_length(user_message_ids, 3)+ self.assertCountEqual(user_message_ids, dm_msg_ids)++ def test_deactivation_with_deleting_all_messages(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ self.setup_user_with_messages(user, admin)++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 9)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_public_channel_messages": True,+ "delete_private_channel_messages": True,+ "delete_direct_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 0)++ def test_deactivation_with_no_messages_to_delete(self) -> None:+ """Test that deactivation works when there are no messages matching the deletion criteria."""+ admin = self.example_user("iago")+ user = self.example_user("cordelia")++ self.send_stream_message(user, "Verona", content="channel message only")++ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 1)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps(+ {+ "delete_direct_messages": True,+ }+ ).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ self.assertFalse(user.is_active)+ user_message_ids = get_user_sent_message_ids(user)+ self.assert_length(user_message_ids, 1)++ def test_name_and_avatar_change_on_deactiation(self) -> None:+ admin = self.example_user("iago")+ user = self.example_user("cordelia")+ self.assertNotEqual(user.full_name, "Deleted user")++ user.avatar_source = UserProfile.AVATAR_FROM_USER+ user.save(update_fields=["avatar_source"])+ self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_USER)++ bot = do_create_user(+ email="[email protected]",+ password="",+ realm=user.realm,+ full_name="Bot 1",+ bot_type=UserProfile.DEFAULT_BOT,+ bot_owner=user,+ acting_user=user,+ )+ self.assertNotEqual(bot.full_name, "Deactivated bot")++ bot.avatar_source = UserProfile.AVATAR_FROM_USER+ bot.save(update_fields=["avatar_source"])+ self.assertEqual(bot.avatar_source, UserProfile.AVATAR_FROM_USER)++ result = self.api_delete(+ admin,+ f"/api/v1/users/{user.id}",+ {+ "actions": orjson.dumps({"delete_profile": True}).decode(),+ },+ )+ self.assert_json_success(result)+ user.refresh_from_db()+ bot.refresh_from_db()+ self.assertFalse(user.is_active)+ self.assertFalse(bot.is_active)++ self.assertEqual(user.full_name, "Deleted user")+ self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)+ self.assertGreater(user.avatar_version, 0)++ self.assertEqual(bot.full_name, "Deactivated bot")+ self.assertEqual(bot.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)+ self.assertGreater(bot.avatar_version, 0)++class RecipientInfoTest(ZulipTestCase):def test_stream_recipient_info(self) -> None:hamlet = self.example_user("hamlet")diff --git a/zerver/views/users.py b/zerver/views/users.pyindex 85ea9fbae6f..b2a3b09b231 100644--- a/zerver/views/users.py+++ b/zerver/views/users.py@@ -23,6 +23,7 @@ from zerver.actions.custom_profile_fields import (check_remove_custom_profile_field_value,do_update_user_custom_profile_data_if_changed,)+from zerver.actions.message_delete import DeactivateUserActionsfrom zerver.actions.user_settings import (check_change_bot_full_name,check_change_full_name,@@ -128,6 +129,7 @@ def deactivate_user_backend(request: HttpRequest,user_profile: UserProfile,*,+ actions: Json[DeactivateUserActions] | None = None,deactivation_notification_comment: Annotated[str, StringConstraints(max_length=2000)]| None = None,user_id: PathOnly[int],@@ -139,10 +141,21 @@ def deactivate_user_backend(raise JsonableError(_("Cannot deactivate the only organization owner"))if deactivation_notification_comment is not None:deactivation_notification_comment = deactivation_notification_comment.strip()+ if (+ actions is not None+ and (+ actions.delete_public_channel_messages+ or actions.delete_private_channel_messages+ or actions.delete_direct_messages+ )+ and not user_profile.has_permission("can_delete_any_message_group")+ ):+ raise JsonableError(_("User is not allowed to delete other user's messages."))return _deactivate_user_profile_backend(request,user_profile,target,+ deactivate_user_actions=actions,deactivation_notification_comment=deactivation_notification_comment,)@@ -171,9 +184,14 @@ def _deactivate_user_profile_backend(user_profile: UserProfile,target: UserProfile,*,+ deactivate_user_actions: Json[DeactivateUserActions] | None = None,deactivation_notification_comment: str | None,) -> HttpResponse:- do_deactivate_user(target, acting_user=user_profile)+ do_deactivate_user(+ target,+ acting_user=user_profile,+ deactivate_user_actions=deactivate_user_actions,+ )# It's important that we check for None explicitly here, since ""# encodes sending an email without a custom administrator comment.