Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
actions: Rework do_delete_user functions.
Mateusz Mandera31801672d11c
diff --git a/corporate/tests/test_support_views.py b/corporate/tests/test_support_views.pyindex 5bc38a28de5..97dc6c9d7c6 100644--- a/corporate/tests/test_support_views.py+++ b/corporate/tests/test_support_views.py@@ -2031,5 +2031,5 @@ class TestSupportEndpoint(ZulipTestCase):"/activity/support",{"realm_id": f"{realm.id}", "delete_user_by_id": hamlet.id},)- m.assert_called_once_with(hamlet)+ m.assert_called_once_with(hamlet, acting_user=self.example_user("iago"))self.assert_in_success_response([f"{hamlet_email} in zulip deleted"], result)diff --git a/corporate/views/support.py b/corporate/views/support.pyindex 26936877aeb..9e25834368e 100644--- a/corporate/views/support.py+++ b/corporate/views/support.py@@ -574,7 +574,7 @@ def support(user_profile_for_deletion = get_user_profile_by_id(delete_user_by_id)user_email = user_profile_for_deletion.delivery_emailassert user_profile_for_deletion.realm == realm- do_delete_user_preserving_messages(user_profile_for_deletion)+ do_delete_user_preserving_messages(user_profile_for_deletion, acting_user=acting_user)context["success_message"] = f"{user_email} in {realm.subdomain} deleted."if support_view_request is not None:diff --git a/zerver/actions/users.py b/zerver/actions/users.pyindex b85971a694d..1427edb8a6f 100644--- a/zerver/actions/users.py+++ b/zerver/actions/users.py@@ -1,4 +1,3 @@-import secretsfrom collections import defaultdictfrom email.headerregistry import Addressfrom typing import Any@@ -7,21 +6,23 @@ from django.conf import settingsfrom django.contrib.auth.tokens import PasswordResetTokenGenerator, default_token_generatorfrom django.db import transactionfrom django.db.models import Q+from django.forms.models import model_to_dictfrom django.http import HttpRequestfrom django.urls import reversefrom django.utils.http import urlsafe_base64_encodefrom django.utils.timezone import now as timezone_nowfrom django.utils.translation import get_language-from zerver.actions.streams import send_peer_remove_events+from zerver.actions.message_delete import do_delete_messages_by_sender+from 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.lib.avatar import get_avatar_fieldfrom zerver.lib.bot_config import ConfigError, get_bot_config, get_bot_configs, set_bot_config-from zerver.lib.cache import bot_dict_fields-from zerver.lib.create_user import create_user+from zerver.lib.cache import bot_dict_fields, flush_user_profile+from zerver.lib.create_user import create_user_profilefrom zerver.lib.event_types import BotServicesOutgoingfrom zerver.lib.invites import revoke_invites_generated_by_userfrom zerver.lib.remote_server import maybe_enqueue_audit_log_upload@@ -33,7 +34,10 @@ from zerver.lib.send_email import ()from zerver.lib.sessions import delete_user_sessionsfrom zerver.lib.soft_deactivation import queue_soft_reactivation-from zerver.lib.stream_subscription import update_all_subscriber_counts_for_user+from zerver.lib.stream_subscription import (+ get_user_subscribed_streams,+ update_all_subscriber_counts_for_user,+)from zerver.lib.stream_traffic import get_streams_trafficfrom zerver.lib.streams import (get_anonymous_group_membership_dict_for_streams,@@ -55,8 +59,8 @@ from zerver.lib.users import (user_access_restricted_in_realm,)from zerver.models import (+ Draft,GroupGroupMembership,- Message,NamedUserGroup,Realm,RealmAuditLog,@@ -69,9 +73,14 @@ from zerver.models import (UserProfile,)from zerver.models.bots import get_bot_services+from zerver.models.messages import UserMessagefrom zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.realms import get_fake_email_domain+from zerver.models.saved_snippets import SavedSnippet+from zerver.models.scheduled_jobs import ScheduledMessagefrom zerver.models.users import (+ ExternalAuthID,+ UserBaseSettings,active_non_guest_user_ids,active_user_ids,bot_owner_user_ids,@@ -82,187 +91,148 @@ from zerver.tornado.django_api import send_event_on_commitdef do_delete_user(user_profile: UserProfile, *, acting_user: UserProfile | None) -> None:- do_deactivate_user(user_profile, acting_user=acting_user)+ do_delete_user_core(user_profile, delete_messages=True, acting_user=acting_user)- to_resubscribe_recipient_ids = set(- Subscription.objects.filter(- user_profile=user_profile, recipient__type=Recipient.DIRECT_MESSAGE_GROUP- ).values_list("recipient_id", flat=True)- )- user_id = user_profile.id- realm = user_profile.realm- date_joined = user_profile.date_joined- personal_recipient = user_profile.recipient- with transaction.atomic(durable=True):- user_profile.delete()- # Recipient objects don't get deleted through CASCADE, so we need to handle- # the user's personal recipient manually. This will also delete all Messages pointing- # to this recipient (all direct messages sent to the user).- if personal_recipient is not None:- personal_recipient.delete()- replacement_user = create_user(- force_id=user_id,- email=Address(- username=f"deleteduser{user_id}", domain=get_fake_email_domain(realm.host)- ).addr_spec,- password=None,- realm=realm,- full_name=f"Deleted User {user_id}",- active=False,- is_mirror_dummy=True,- force_date_joined=date_joined,- )- subs_to_recreate = [- Subscription(- user_profile=replacement_user,- recipient=recipient,- is_user_active=replacement_user.is_active,- )- for recipient in Recipient.objects.filter(id__in=to_resubscribe_recipient_ids)- ]- Subscription.objects.bulk_create(subs_to_recreate)-- RealmAuditLog.objects.create(- realm=replacement_user.realm,- modified_user=replacement_user,- acting_user=acting_user,- event_type=AuditLogEventType.USER_DELETED,- event_time=timezone_now(),- )---def do_delete_user_preserving_messages(user_profile: UserProfile) -> None:- """This is a version of do_delete_user which does not delete messages- that the user was a participant in, and thus is less potentially- disruptive to other users.+def do_delete_user_preserving_messages(+ user_profile: UserProfile, *, acting_user: UserProfile | None+) -> None:+ do_delete_user_core(user_profile, delete_messages=False, acting_user=acting_user)- The code is a bit tricky, because we want to, at some point, call- user_profile.delete() to trigger cascading deletions of related- models - but we need to avoid the cascades deleting all messages- sent by the user to avoid messing up history of public stream- conversations that they may have participated in.- Not recommended for general use due to the following quirks:+def do_delete_user_core(+ user_profile: UserProfile, *, delete_messages: bool, acting_user: UserProfile | None+) -> None:+ """* Does not live-update other clients via `send_event_on_commit`about the user's new name, email, or other attributes.- * Not guaranteed to clear caches containing the deleted users. The- temporary user may be visible briefly in caches due to the- UserProfile model's post_save hook.- * Deletes `acting_user`/`modified_user` entries in RealmAuditLog,- potentially leading to corruption in audit tables if the user had,- for example, changed organization-level settings previously.- * May violate invariants like deleting the only subscriber to a- stream/group or the last owner in a realm.- * Will remove MutedUser records for other users who might have- muted this user.- * Will destroy Attachment/ArchivedAttachment records for files- uploaded by the user, making them inaccessible.- * Will destroy ArchivedMessage records associated with the user,- making them impossible to restore from backups.- * Will destroy Reaction/Submessage objects for reactions/poll- votes done by the user.-- Most of these issues are not relevant for the common case that the- user being deleted hasn't used Zulip extensively.-- It is possible a different algorithm that worked via overwriting- the UserProfile's values with RealmUserDefault values, as well as- a targeted set of deletions of cascading models (`Subscription`,- `UserMessage`, `CustomProfileFieldValue`, etc.) would be a cleaner- path to a high quality system.Other lesser quirks to be aware of:* The deleted user will disappear from all "Read receipts"displays, as all UserMessage rows will have been deleted.+ * Messages mentioning the deleted user will no longer be found+ by searching mentions:{user_id}, also from UserMessage deletion.* Raw Markdown syntax mentioning the user still contain theiroriginal name (though modern clients will look up the user via`data-user-id` and display the current name). This is hard tochange, and not important, since nothing prevents other users fromjust typing the user's name in their own messages.- * Consumes a user ID sequence number, resulting in gaps in the- space of user IDs that contain actual users.-"""do_deactivate_user(user_profile, acting_user=None)user_id = user_profile.id- personal_recipient = user_profile.recipientrealm = user_profile.realm- date_joined = user_profile.date_joined+ # We create a temporary dummy UserProfile just to have a valid object with defaults+ # set for all the various user settings. We can then copy them over onto the original+ # user_profile object that we're overwriting.+ # This is important as the combination of all the settings of a user could make them+ # theoretically possible to de-anonymize even after deletion, if the original values+ # were preserved.+ # This temporary dummy is never saved to the database, so this operation doesn't do any+ # writes and doesn't consume an id number.with transaction.atomic(durable=True):- # The strategy is that before calling user_profile.delete(), we need to- # reassign Messages sent by the user to a dummy user, so that they don't- # get affected by CASCADE. We cannot yet create a dummy user with .id- # matching that of the user_profile, so the general scheme is:- # 1. We create a *temporary* dummy for the initial re-assignment of messages.- # 2. We delete the UserProfile.- # 3. We create a replacement dummy user with its id matching what the UserProfile had.- # 4. This is the intended, final replacement UserProfile, so we re-assign- # the messages from step (1) to it and delete the temporary dummy.- #- # We also do the same for Subscriptions - while they could be handled like- # in do_delete_user by re-creating the objects after CASCADE deletion, the code- # is cleaner by using the same re-assignment approach for them together with Messages.- random_token = secrets.token_hex(16)- temp_replacement_user = create_user(- email=Address(- username=f"temp_deleteduser{random_token}", domain=get_fake_email_domain(realm.host)- ).addr_spec,- password=None,+ temp_replacement_user = create_user_profile(realm=realm,- full_name=f"Deleted User {user_id} (temp)",- active=False,- is_mirror_dummy=True,- force_date_joined=date_joined,- create_personal_recipient=False,- )- # Uses index: zerver_message_realm_sender_recipient (prefix)- Message.objects.filter(realm_id=realm.id, sender=user_profile).update(- sender=temp_replacement_user- )- Subscription.objects.filter(- user_profile=user_profile, recipient__type=Recipient.DIRECT_MESSAGE_GROUP- ).update(user_profile=temp_replacement_user)- user_profile.delete()-- replacement_user = create_user(- force_id=user_id,email=Address(username=f"deleteduser{user_id}", domain=get_fake_email_domain(realm.host)).addr_spec,password=None,- realm=realm,- full_name=f"Deleted User {user_id}",active=False,+ bot_type=user_profile.bot_type,+ full_name=f"Deleted User {user_id}",+ bot_owner=user_profile.bot_owner,is_mirror_dummy=True,- force_date_joined=date_joined,- create_personal_recipient=False,+ tos_version=user_profile.tos_version,+ # These required arguments should get default values configured on the UserProfile model,+ # to overwrite the values of user_profile.+ timezone=UserProfile._meta.get_field("timezone").get_default(),+ default_language=UserProfile._meta.get_field("default_language").get_default(),+ email_address_visibility=UserBaseSettings.EMAIL_ADDRESS_VISIBILITY_EVERYONE,+ )++ overwrite_data = model_to_dict(+ temp_replacement_user,+ exclude=[+ "id",+ "date_joined",+ "realm",+ "recipient",+ "uuid",+ "last_login",+ # These come from Django and aren't used by Zulip. We+ # need to exclude them as they are ManyToManyFields+ # and as such, would break the code below.+ "groups",+ "user_permissions",+ ],)- # We don't delete the personal recipient to preserve personal messages!- # Now, the personal recipient belong to replacement_user, because- # personal_recipient.type_id is equal to replacement_user.id.- replacement_user.recipient = personal_recipient- replacement_user.save(update_fields=["recipient"])-- # Uses index: zerver_message_realm_sender_recipient (prefix)- Message.objects.filter(realm_id=realm.id, sender=temp_replacement_user).update(- sender=replacement_user++ UserProfile.objects.filter(id=user_profile.id).update(**overwrite_data)+ user_profile.refresh_from_db()++ # First, we run bulk_remove_subscriptions to execute our+ # complete, end-to-end unsubscribing procedure, which handles+ # events, updating subscriber_count, etc.+ #+ # Then we hard-delete all the Subscription objects to avoid+ # preserving the user's previous personal metadata about+ # channel subscriptions (colors, notification preferences, etc.).+ bulk_remove_subscriptions(+ realm, [user_profile], get_user_subscribed_streams(user_profile), acting_user=None)Subscription.objects.filter(- user_profile=temp_replacement_user, recipient__type=Recipient.DIRECT_MESSAGE_GROUP- ).update(user_profile=replacement_user, is_user_active=replacement_user.is_active)- temp_replacement_user.delete()+ user_profile=user_profile, recipient__type=Recipient.STREAM+ ).delete()++ fks_to_delete: list[tuple[Any, str]] = [+ (UserMessage, "user_profile"),+ (ExternalAuthID, "user"),+ (SavedSnippet, "user_profile"),+ (ScheduledMessage, "sender"),+ (Draft, "user_profile"),+ ]+ for table, field_name in fks_to_delete:+ table.objects.filter(**{field_name: user_profile}).delete()+ # There's also a many-to-many relationship between UserProfile and ScheduledEmail,+ # which would require separate handling from foreign keys. But the clearing out+ # of this data is handled by do_deactivate_user already, so we don't need to do+ # anything.++ # These audit logs can carry personal information in extra_data.+ # We need to scrub that data in the process of user deletion.+ audit_log_event_types_for_scrubbing = [+ AuditLogEventType.USER_EMAIL_CHANGED,+ AuditLogEventType.USER_FULL_NAME_CHANGED,+ AuditLogEventType.USER_SETTING_CHANGED,+ ]+ RealmAuditLog.objects.filter(+ modified_user=user_profile, event_type__in=audit_log_event_types_for_scrubbing+ ).update(extra_data={}, scrubbed=True)++ if delete_messages:+ do_delete_messages_by_sender(user_profile)++ if delete_messages:+ event_type = AuditLogEventType.USER_DELETED+ else:+ event_type = AuditLogEventType.USER_DELETED_PRESERVING_MESSAGESRealmAuditLog.objects.create(- realm=replacement_user.realm,- modified_user=replacement_user,- acting_user=None,- event_type=AuditLogEventType.USER_DELETED_PRESERVING_MESSAGES,+ realm=realm,+ modified_user=user_profile,+ acting_user=acting_user,+ event_type=event_type,event_time=timezone_now(),)+ flush_user_profile(+ instance=user_profile,+ # update_fields=None is treated as "update_fields=<all fields>" and invalidates+ # all the caches related to this user.+ update_fields=None,+ )+def change_user_is_active(user_profile: UserProfile, value: bool) -> None:"""diff --git a/zerver/lib/create_user.py b/zerver/lib/create_user.pyindex c7409fb82b4..6585ac97091 100644--- a/zerver/lib/create_user.py+++ b/zerver/lib/create_user.py@@ -114,22 +114,17 @@ def create_user_profile(tos_version: str | None,timezone: str,default_language: str,- force_id: int | None = None,force_date_joined: datetime | None = None,*,email_address_visibility: int,) -> UserProfile:if force_date_joined is None:date_joined = timezone_now()- else:+ else: # nocoveragedate_joined = force_date_joinedemail = UserManager.normalize_email(email)- extra_kwargs = {}- if force_id is not None:- extra_kwargs["id"] = force_id-user_profile = UserProfile(is_staff=False,is_active=active,@@ -146,7 +141,6 @@ def create_user_profile(default_language=default_language,delivery_email=email,email_address_visibility=email_address_visibility,- **extra_kwargs,)if bot_type or not active:password = None@@ -175,9 +169,7 @@ def create_user(default_events_register_stream: Stream | None = None,default_all_public_streams: bool | None = None,source_profile: UserProfile | None = None,- force_id: int | None = None,force_date_joined: datetime | None = None,- create_personal_recipient: bool = True,enable_marketing_emails: bool | None = None,email_address_visibility: int | None = None,) -> UserProfile:@@ -210,7 +202,6 @@ def create_user(tos_version,timezone,default_language,- force_id=force_id,force_date_joined=force_date_joined,email_address_visibility=user_email_address_visibility,)@@ -250,9 +241,6 @@ def create_user(user_profile.email = get_display_email_address(user_profile)user_profile.save(update_fields=["email"])- if not create_personal_recipient:- return user_profile-recipient = Recipient.objects.create(type_id=user_profile.id, type=Recipient.PERSONAL)user_profile.recipient = recipientuser_profile.save(update_fields=["recipient"])diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex d1ba2ff02be..d7a98315f4d 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -22,7 +22,11 @@ from zerver.actions.realm_settings import (do_change_realm_permission_group_setting,do_set_realm_property,)-from zerver.actions.user_settings import bulk_regenerate_api_keys, do_change_user_setting+from zerver.actions.user_settings import (+ bulk_regenerate_api_keys,+ do_change_full_name,+ do_change_user_setting,+)from zerver.actions.user_topics import do_set_user_topic_visibility_policyfrom zerver.actions.users import (change_user_is_active,@@ -3308,13 +3312,18 @@ class DeleteUserTest(ZulipTestCase):hamlet_user_id = hamlet.idhamlet_date_joined = hamlet.date_joined+ denmark = get_stream("Denmark", hamlet.realm)+ self.subscribe(hamlet, denmark.name)+ denmark_original_sub_count = denmark.subscriber_count+self.send_personal_message(cordelia, hamlet)self.send_personal_message(hamlet, cordelia)personal_message_ids_to_hamlet = Message.objects.filter(realm_id=realm.id, recipient=hamlet_personal_recipient).values_list("id", flat=True)- self.assertGreater(len(personal_message_ids_to_hamlet), 0)+ personal_message_ids_to_hamlet_original_count = len(personal_message_ids_to_hamlet)+ self.assertGreater(personal_message_ids_to_hamlet_original_count, 0)self.assertTrue(Message.objects.filter(realm_id=realm.id, sender=hamlet).exists())group_direct_message_ids_from_cordelia = [@@ -3331,18 +3340,36 @@ class DeleteUserTest(ZulipTestCase):)self.assertGreater(len(direct_message_group_with_hamlet_recipient_ids), 0)+ do_change_full_name(hamlet, "some new name", acting_user=hamlet)+ name_change_log = RealmAuditLog.objects.last()+ assert name_change_log is not None+ self.assertEqual(name_change_log.event_type, AuditLogEventType.USER_FULL_NAME_CHANGED)+ self.assertEqual(name_change_log.modified_user, hamlet)++ send_future_email(+ "zerver/emails/onboarding_zulip_topics",+ realm,+ to_user_ids=[hamlet.id],+ delay=timedelta(hours=1),+ )+ self.assertEqual(ScheduledEmail.objects.count(), 1)+do_delete_user(hamlet, acting_user=None)- replacement_dummy_user = UserProfile.objects.get(id=hamlet_user_id, realm=realm)+ hamlet.refresh_from_db()++ self.assertEqual(hamlet.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver")+ self.assertEqual(hamlet.is_mirror_dummy, True)+ self.assertEqual(hamlet.is_active, False)+ self.assertEqual(hamlet.date_joined, hamlet_date_joined)+ # Messages that were sent TO the user are preserved. They'll just appear+ # to the senders as sent to a deleted dummy user.self.assertEqual(- replacement_dummy_user.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver"+ Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(),+ personal_message_ids_to_hamlet_original_count,)- self.assertEqual(replacement_dummy_user.is_mirror_dummy, True)- self.assertEqual(replacement_dummy_user.is_active, False)- self.assertEqual(replacement_dummy_user.date_joined, hamlet_date_joined)- self.assertEqual(Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(), 0)# Group direct messages from hamlet should have been deleted, but messages of other# participants should be kept.self.assertEqual(@@ -3357,18 +3384,34 @@ class DeleteUserTest(ZulipTestCase):)# Verify that the dummy user is subscribed to the deleted user's direct message groups,- # to keep direct message group's data in a correct state.+ # to keep direct message group's data in a correct state.for recipient_id in direct_message_group_with_hamlet_recipient_ids:self.assertTrue(- Subscription.objects.filter(- user_profile=replacement_dummy_user, recipient_id=recipient_id- ).exists()+ Subscription.objects.filter(user_profile=hamlet, recipient_id=recipient_id).exists())+ # Make sure the subscriber count was decremented correctly.+ denmark.refresh_from_db()+ self.assertEqual(denmark.subscriber_count, denmark_original_sub_count - 1)++ # Ensure we don't lose audit logs tied to the user.+ self.assertTrue(RealmAuditLog.objects.filter(id=name_change_log.id).exists())+ name_change_log.refresh_from_db()+ self.assertEqual(name_change_log.modified_user, hamlet)+ self.assertEqual(name_change_log.acting_user, hamlet)+ # We do scrub private information out of extra_data however.+ self.assertEqual(name_change_log.extra_data, {})+ self.assertEqual(name_change_log.scrubbed, True)++ self.assertEqual(ScheduledEmail.objects.count(), 0)+def test_do_delete_user_preserving_messages(self) -> None:"""- This test is extremely similar to the one for do_delete_user, with the only difference being- that Messages are supposed to be preserved. All other effects should be identical.+ Since do_delete_user and do_delete_user_preserving_messages share the same+ code, besides the latter skipping message deletion, we don't repeat the various+ assertions from test_do_delete_user here. Instead, we just want to make sure+ the user gets replaced with a deleted dummy as expected and that messages are+ preserved."""realm = get_realm("zulip")@@ -3377,7 +3420,6 @@ class DeleteUserTest(ZulipTestCase):hamlet = self.example_user("hamlet")hamlet_personal_recipient = hamlet.recipienthamlet_user_id = hamlet.id- hamlet_date_joined = hamlet.date_joinedself.send_personal_message(cordelia, hamlet)self.send_personal_message(hamlet, cordelia)@@ -3395,28 +3437,16 @@ class DeleteUserTest(ZulipTestCase):self.send_group_direct_message(hamlet, [cordelia, othello]) for i in range(3)]- direct_message_group_with_hamlet_recipient_ids = list(- Subscription.objects.filter(- user_profile=hamlet, recipient__type=Recipient.DIRECT_MESSAGE_GROUP- ).values_list("recipient_id", flat=True)- )- self.assertGreater(len(direct_message_group_with_hamlet_recipient_ids), 0)-original_messages_from_hamlet_count = Message.objects.filter(realm_id=realm.id, sender_id=hamlet_user_id).count()self.assertGreater(original_messages_from_hamlet_count, 0)- do_delete_user_preserving_messages(hamlet)+ do_delete_user_preserving_messages(hamlet, acting_user=None)- replacement_dummy_user = UserProfile.objects.get(id=hamlet_user_id, realm=realm)+ hamlet.refresh_from_db()- self.assertEqual(- replacement_dummy_user.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver"- )- self.assertEqual(replacement_dummy_user.is_mirror_dummy, True)- self.assertEqual(replacement_dummy_user.is_active, False)- self.assertEqual(replacement_dummy_user.date_joined, hamlet_date_joined)+ self.assertEqual(hamlet.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver")# All messages should have been preserved:self.assertEqual(@@ -3437,15 +3467,6 @@ class DeleteUserTest(ZulipTestCase):original_messages_from_hamlet_count,)- # Verify that the dummy user is subscribed to the deleted user's direct message groups,- # to keep direct message group's data in a correct state.- for recipient_id in direct_message_group_with_hamlet_recipient_ids:- self.assertTrue(- Subscription.objects.filter(- user_profile=replacement_dummy_user, recipient_id=recipient_id- ).exists()- )-class FakeEmailDomainTest(ZulipTestCase):def test_get_fake_email_domain(self) -> None: