Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
test_push_notification: Rework using `Device` model.
Prakhar Pratyushf03b52ffedba
diff --git a/zerver/lib/export.py b/zerver/lib/export.pyindex 89318211952..798b9bfddc5 100644--- a/zerver/lib/export.py+++ b/zerver/lib/export.py@@ -181,7 +181,6 @@ ALL_ZULIP_TABLES = {"zerver_preregistrationuser_streams","zerver_preregistrationuser_groups","zerver_presencesequence",- "zerver_pushdevice","zerver_pushdevicetoken","zerver_reaction","zerver_realm",@@ -246,7 +245,6 @@ NON_EXPORTED_TABLES = {# When switching servers, clients will need to re-log in and# reregister for push notifications anyway."zerver_device",- "zerver_pushdevice","zerver_pushdevicetoken",# We don't use these generated Django tables"zerver_userprofile_groups",diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 0fe33389c08..8b83d403c7d 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -97,9 +97,9 @@ from zerver.lib.webhooks.common import ()from zerver.models import (Client,+ Device,Message,NamedUserGroup,- PushDevice,PushDeviceToken,Reaction,Realm,@@ -1950,11 +1950,11 @@ Output:)def register_push_device(self, user_profile_id: int) -> None:- PushDevice.objects.create(+ Device.objects.create(user_id=user_profile_id,- push_account_id=10,- bouncer_device_id=1,- token_kind=PushDevice.TokenKind.FCM,+ push_key_id=10,+ push_token_id=1,+ push_token_kind=Device.PushTokenKind.FCM,push_key=base64.b64decode("MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt"),)@@ -2953,18 +2953,18 @@ class E2EEPushNotificationTestCase(BouncerTestCase):realm = hamlet.realm# Hamlet registers both an Android and an Apple device for push notification.- PushDevice.objects.create(+ Device.objects.create(user=hamlet,- push_account_id=10,- bouncer_device_id=1,- token_kind=PushDevice.TokenKind.APNS,+ push_key_id=10,+ push_token_id=1,+ push_token_kind=Device.PushTokenKind.APNS,push_key=base64.b64decode("MXPC4WK2YfyfCBdK6ElnzSpKJtcpFSZrYiJto4YCETzx"),)- PushDevice.objects.create(+ Device.objects.create(user=hamlet,- push_account_id=20,- bouncer_device_id=2,- token_kind=PushDevice.TokenKind.FCM,+ push_key_id=20,+ push_token_id=2,+ push_token_kind=Device.PushTokenKind.FCM,push_key=base64.b64decode("Mc3u6xraEI79aGk6Nd+boqi/ODfT+JcsEIATzG7C/m+V"),)@@ -2977,16 +2977,14 @@ class E2EEPushNotificationTestCase(BouncerTestCase):realm_and_remote_realm_fields = {"realm": None, "remote_realm": remote_realm}registered_device_apple = RemotePushDevice.objects.create(- push_account_id=10,- device_id=1,+ token_id=1,token_kind=RemotePushDevice.TokenKind.APNS,token="push-device-token-1",ios_app_id="abc",**realm_and_remote_realm_fields,)registered_device_android = RemotePushDevice.objects.create(- push_account_id=20,- device_id=2,+ token_id=2,token_kind=RemotePushDevice.TokenKind.FCM,token="push-device-token-3",**realm_and_remote_realm_fields,diff --git a/zerver/migrations/0780_delete_pushdevice.py b/zerver/migrations/0780_delete_pushdevice.pynew file mode 100644index 00000000000..ead1f8f3b16--- /dev/null+++ b/zerver/migrations/0780_delete_pushdevice.py@@ -0,0 +1,15 @@+# Generated by Django 5.2.10 on 2026-02-03 16:35++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("zerver", "0779_device"),+ ]++ operations = [+ migrations.DeleteModel(+ name="PushDevice",+ ),+ ]diff --git a/zerver/models/__init__.py b/zerver/models/__init__.pyindex 9045bdf44ae..56ec8a7f253 100644--- a/zerver/models/__init__.py+++ b/zerver/models/__init__.py@@ -43,9 +43,7 @@ from zerver.models.prereg_users import PreregistrationUser as PreregistrationUsefrom zerver.models.prereg_users import RealmReactivationStatus as RealmReactivationStatusfrom zerver.models.presence import UserPresence as UserPresencefrom zerver.models.presence import UserStatus as UserStatus-from zerver.models.push_notifications import AbstractPushDevice as AbstractPushDevicefrom zerver.models.push_notifications import AbstractPushDeviceToken as AbstractPushDeviceToken-from zerver.models.push_notifications import PushDevice as PushDevicefrom zerver.models.push_notifications import PushDeviceToken as PushDeviceTokenfrom zerver.models.realm_audit_logs import AbstractRealmAuditLog as AbstractRealmAuditLogfrom zerver.models.realm_audit_logs import RealmAuditLog as RealmAuditLogdiff --git a/zerver/models/push_notifications.py b/zerver/models/push_notifications.pyindex 50486f4a3bf..c1800ca7703 100644--- a/zerver/models/push_notifications.py+++ b/zerver/models/push_notifications.py@@ -1,14 +1,7 @@-from typing import Literal-from django.db import models-from django.db.models import CASCADE, F, Q, UniqueConstraint+from django.db.models import CASCADE, F, Qfrom django.db.models.functions import Lower-from zerver.lib.exceptions import (- InvalidBouncerPublicKeyError,- InvalidEncryptedPushRegistrationError,- RequestExpiredError,-)from zerver.models.users import UserProfile@@ -63,86 +56,3 @@ class PushDeviceToken(AbstractPushDeviceToken):condition=Q(kind=AbstractPushDeviceToken.FCM),),]---class AbstractPushDevice(models.Model):- class TokenKind(models.TextChoices):- APNS = "apns", "APNs"- FCM = "fcm", "FCM"-- token_kind = models.CharField(max_length=4, choices=TokenKind.choices)-- # 64-bit random integer ID generated by the client; will only be- # guaranteed to be unique within the client's own table of accounts.- push_account_id = models.BigIntegerField()-- class Meta:- abstract = True---class PushDevice(AbstractPushDevice):- """Core zulip server table storing registrations that are potentially- registered with the mobile push notifications bouncer service.-- Each row corresponds to an account on an install of the app- that has attempted to register with the bouncer to receive- mobile push notifications.- """-- # The user on this server to whom this PushDevice belongs.- user = models.ForeignKey(UserProfile, on_delete=CASCADE)-- # Key to use to encrypt notifications for delivery to this device.- # Consists of a 1-byte prefix identifying the symmetric cryptosystem- # in use, followed by the secret key.- # Prefix Cryptosystem- # 0x31 libsodium's `crypto_secretbox_easy`- push_key = models.BinaryField()-- # `device_id` of the corresponding `RemotePushDevice`- # row created after successful registration to bouncer.- # Set to NULL while registration to bouncer is in progress or failed.- bouncer_device_id = models.BigIntegerField(null=True)-- class ErrorCode(models.TextChoices):- INVALID_BOUNCER_PUBLIC_KEY = InvalidBouncerPublicKeyError.code.name- INVALID_ENCRYPTED_PUSH_REGISTRATION = InvalidEncryptedPushRegistrationError.code.name- REQUEST_EXPIRED = RequestExpiredError.code.name-- # The error code returned when registration to bouncer fails.- # Set to NULL if the registration is in progress or successful.- error_code = models.CharField(max_length=100, choices=ErrorCode.choices, null=True)-- class Meta:- constraints = [- UniqueConstraint(- # In theory, there's possibility that a user with- # two different devices having the same 'push_account_id'- # generated by the client to register. But the API treats- # that as idempotent request.- # We treat (user, push_account_id) as a unique registration.- #- # Also, the unique index created is used by queries in `get_push_accounts`,- # `register_push_device`, `handle_register_push_device_to_bouncer`, and- # `send_e2ee_test_push_notification_api`.- fields=["user", "push_account_id"],- name="unique_push_device_user_push_account_id",- ),- ]- indexes = [- models.Index(- # Used in 'send_push_notifications', `send_e2ee_test_push_notification_api`,- # 'get_recipient_info', and 'do_clear_mobile_push_notifications_for_ids'.- fields=["user", "bouncer_device_id"],- condition=Q(bouncer_device_id__isnull=False),- name="zerver_pushdevice_user_bouncer_device_id_idx",- ),- ]-- @property- def status(self) -> Literal["active", "pending", "failed"]:- if self.error_code is not None:- return "failed"- elif self.bouncer_device_id is None:- return "pending"- return "active"diff --git a/zerver/tests/test_e2ee_push_notifications.py b/zerver/tests/test_e2ee_push_notifications.pyindex 7e32c41c239..8d4dc9240d3 100644--- a/zerver/tests/test_e2ee_push_notifications.py+++ b/zerver/tests/test_e2ee_push_notifications.py@@ -13,6 +13,7 @@ from typing_extensions import overridefrom analytics.models import RealmCountfrom zerver.actions.user_groups import check_add_user_groupfrom zerver.lib.avatar import absolute_avatar_url+from zerver.lib.devices import b64encode_token_id_intfrom zerver.lib.exceptions import MissingRemoteRealmErrorfrom zerver.lib.push_notifications import (PushNotificationsDisallowedByBouncerError,@@ -27,7 +28,7 @@ from zerver.lib.remote_server import (from zerver.lib.test_classes import E2EEPushNotificationTestCasefrom zerver.lib.test_helpers import activate_push_notification_servicefrom zerver.lib.timestamp import datetime_to_timestamp-from zerver.models import PushDevice, UserMessage+from zerver.models import Device, UserMessagefrom zerver.models.realms import get_realmfrom zerver.models.scheduled_jobs import NotificationTriggersfrom zerver.models.streams import get_stream@@ -77,12 +78,12 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertEqual("INFO:zerver.lib.push_notifications:"- f"APNs: Success sending to (push_account_id={registered_device_apple.push_account_id}, device={registered_device_apple.token})",+ f"APNs: Success sending to (realm={hamlet.realm.uuid}, device={registered_device_apple.token})",zerver_logger.output[2],)self.assertEqual("INFO:zilencer.lib.push_notifications:"- f"FCM: Sent message with ID: 0 to (push_account_id={registered_device_android.push_account_id}, device={registered_device_android.token})",+ f"FCM: Sent message with ID: 0 to (realm={hamlet.realm.uuid}, device={registered_device_android.token})",zilencer_logger.output[0],)self.assertEqual(@@ -105,7 +106,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):# * 1 : `get_user_profile_by_id`# * 2 : `access_message_and_usermessage` (Fetch Message + UserMessage)# * 1 : update fetched user_message flag- # * 2 : fetch PushDeviceToken + PushDevice+ # * 2 : fetch PushDeviceToken + Device# * 1 : `get_display_recipient` in `get_message_payload`# * 2 : fetch RemotePushDevice + update RealmCountmessage_id = self.send_personal_message(@@ -197,7 +198,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertIsNone(registered_device_apple.expired_time)self.assertIsNone(registered_device_android.expired_time)- self.assertEqual(PushDevice.objects.count(), 2)+ self.assertEqual(Device.objects.filter(push_token_id__isnull=False).count(), 2)message_id = self.send_personal_message(from_user=aaron, to_user=hamlet, skip_capture_on_commit_callbacks=True@@ -242,7 +243,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertEqual("INFO:zerver.lib.push_notifications:"- f"Deleting PushDevice rows with the following device IDs based on response from bouncer: [{registered_device_apple.device_id}, {registered_device_android.device_id}]",+ f"Clearing `push_token_id` for Device rows with the following token IDs based on response from bouncer: ['{b64encode_token_id_int(registered_device_apple.token_id)}', '{b64encode_token_id_int(registered_device_android.token_id)}']",zerver_logger.output[3],)self.assertEqual(@@ -257,7 +258,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):registered_device_android.refresh_from_db()self.assertIsNotNone(registered_device_apple.expired_time)self.assertIsNotNone(registered_device_android.expired_time)- self.assertEqual(PushDevice.objects.count(), 0)+ self.assertEqual(Device.objects.filter(push_token_id__isnull=False).count(), 0)def test_fcm_apns_error(self) -> None:hamlet = self.example_user("hamlet")@@ -302,7 +303,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertIn("WARNING:zilencer.lib.push_notifications:"- f"FCM: Delivery failed for (push_account_id={registered_device_android.push_account_id}, device={registered_device_android.token})",+ f"FCM: Delivery failed to (realm={hamlet.realm.uuid}, device={registered_device_android.token})",zilencer_logger.output[1],)self.assertEqual(@@ -326,7 +327,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):"zilencer.lib.push_notifications.send_e2ee_push_notification_apple",return_value=SentPushNotificationResult(successfully_sent_count=1,- delete_device_ids=[],+ delete_token_ids_base64=[],),),self.assertLogs("zerver.lib.push_notifications", level="INFO") as zerver_logger,@@ -366,7 +367,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):"zilencer.lib.push_notifications.send_e2ee_push_notification_apple",return_value=SentPushNotificationResult(successfully_sent_count=1,- delete_device_ids=[],+ delete_token_ids_base64=[],),),self.assertLogs("zerver.lib.push_notifications", level="INFO") as zerver_logger,@@ -403,7 +404,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):registered_device_apple.save(update_fields=["expired_time"])registered_device_android.save(update_fields=["expired_time"])- self.assertEqual(PushDevice.objects.count(), 2)+ self.assertEqual(Device.objects.filter(push_token_id__isnull=False).count(), 2)message_id = self.send_personal_message(from_user=aaron, to_user=hamlet, skip_capture_on_commit_callbacks=True@@ -415,7 +416,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):# Since 'expired_time' is set for concerned 'RemotePushDevice' rows,# the bouncer will not attempt to send notification and instead returns- # a list of device IDs which server should erase on their own end.+ # a list of token IDs which server should erase on their own end.with (mock.patch("zilencer.lib.push_notifications.send_e2ee_push_notification_apple"@@ -428,7 +429,7 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):send_apple.assert_not_called()send_android.assert_not_called()- self.assertEqual(PushDevice.objects.count(), 0)+ self.assertEqual(Device.objects.filter(push_token_id__isnull=False).count(), 0)@responses.activate@override_settings(ZILENCER_ENABLED=False)@@ -491,12 +492,12 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertEqual("INFO:zerver.lib.push_notifications:"- f"APNs: Success sending to (push_account_id={registered_device_apple.push_account_id}, device={registered_device_apple.token})",+ f"APNs: Success sending to (remote_realm={hamlet.realm.uuid}, device={registered_device_apple.token})",zerver_logger.output[2],)self.assertEqual("INFO:zilencer.lib.push_notifications:"- f"FCM: Sent message with ID: 0 to (push_account_id={registered_device_android.push_account_id}, device={registered_device_android.token})",+ f"FCM: Sent message with ID: 0 to (remote_realm={hamlet.realm.uuid}, device={registered_device_android.token})",zilencer_logger.output[0],)self.assertEqual(@@ -703,12 +704,12 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):# Logs in E2EE codepathself.assertEqual("INFO:zerver.lib.push_notifications:"- f"APNs: Success sending to (push_account_id={registered_device_apple.push_account_id}, device={registered_device_apple.token})",+ f"APNs: Success sending to (realm={hamlet.realm.uuid}, device={registered_device_apple.token})",zerver_logger.output[6],)self.assertEqual("INFO:zilencer.lib.push_notifications:"- f"FCM: Sent message with ID: 0 to (push_account_id={registered_device_android.push_account_id}, device={registered_device_android.token})",+ f"FCM: Sent message with ID: 0 to (realm={hamlet.realm.uuid}, device={registered_device_android.token})",zilencer_logger.output[0],)self.assertEqual(@@ -1104,10 +1105,11 @@ class SendTestPushNotificationTest(E2EEPushNotificationTestCase):)# Send test notification to a selected mobile device.+ push_device = Device.objects.get(push_token_id=registered_device_android.token_id)result = self.api_post(hamlet,"/api/v1/mobile_push/e2ee/test_notification",- {"push_account_id": registered_device_android.push_account_id},+ {"device_id": push_device.id},subdomain="zulip",)self.assert_json_success(result)diff --git a/zerver/tests/test_event_queue.py b/zerver/tests/test_event_queue.pyindex deb708c21da..e42a2850862 100644--- a/zerver/tests/test_event_queue.py+++ b/zerver/tests/test_event_queue.py@@ -16,7 +16,7 @@ from zerver.actions.user_topics import do_set_user_topic_visibility_policyfrom zerver.lib.cache import cache_delete, get_muting_users_cache_keyfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import HostRequestMock, dummy_handler, mock_queue_publish-from zerver.models import PushDevice, Recipient, Subscription, UserProfile, UserTopic+from zerver.models import Device, Recipient, Subscription, UserProfile, UserTopicfrom zerver.models.streams import get_streamfrom zerver.tornado.event_queue import (ClientDescriptor,@@ -313,7 +313,7 @@ class MissedMessageHookTest(ZulipTestCase):do_change_user_setting(self.user_profile, "enable_offline_push_notifications", True, acting_user=None)- PushDevice.objects.all().delete()+ Device.objects.filter(push_token_id__isnull=False).delete()msg_id = self.send_personal_message(self.iago, self.user_profile)with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:missedmessage_hook(self.user_profile.id, self.client_descriptor, True)diff --git a/zerver/tests/test_message_edit_notifications.py b/zerver/tests/test_message_edit_notifications.pyindex a65bb132379..b325bc9542e 100644--- a/zerver/tests/test_message_edit_notifications.py+++ b/zerver/tests/test_message_edit_notifications.py@@ -10,7 +10,7 @@ from zerver.actions.user_topics import do_set_user_topic_visibility_policyfrom zerver.lib.push_notifications import get_apns_badge_count, get_apns_badge_count_futurefrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import mock_queue_publish-from zerver.models import PushDevice, Subscription, UserPresence, UserTopic+from zerver.models import Device, Subscription, UserPresence, UserTopicfrom zerver.models.scheduled_jobs import NotificationTriggersfrom zerver.models.streams import get_streamfrom zerver.tornado.event_queue import maybe_enqueue_notifications@@ -240,7 +240,7 @@ class EditMessageSideEffectsTest(ZulipTestCase):cordelia, "enable_offline_email_notifications", False, acting_user=None)self.assertTrue(cordelia.enable_offline_push_notifications)- PushDevice.objects.all().delete()+ Device.objects.filter(push_token_id__isnull=False).delete()original_content = "no mention"updated_content = "now we mention @**Cordelia, Lear's daughter**"diff --git a/zerver/tests/test_message_flags.py b/zerver/tests/test_message_flags.pyindex 3413fea6ab3..191ac15fe53 100644--- a/zerver/tests/test_message_flags.py+++ b/zerver/tests/test_message_flags.py@@ -30,8 +30,8 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import get_subscriptionfrom zerver.lib.user_message import DEFAULT_HISTORICAL_FLAGS, create_historical_user_messagesfrom zerver.models import (+ Device,Message,- PushDevice,Recipient,Stream,Subscription,@@ -982,7 +982,7 @@ class PushNotificationMarkReadFlowsTest(ZulipTestCase):# Device unregistered. Verify that no event to revoke notifications gets# enqueued to `missedmessage_mobile_notifications` and `active_mobile_push_notification`# flag is unset.- PushDevice.objects.all().delete()+ Device.objects.filter(push_token_id__isnull=False).delete()with (mock.patch("zerver.actions.message_flags.queue_event_on_commit"diff --git a/zerver/tests/test_push_registration.py b/zerver/tests/test_push_registration.pyindex 0bb1b5dcacd..418156f5407 100644--- a/zerver/tests/test_push_registration.py+++ b/zerver/tests/test_push_registration.py@@ -1,25 +1,29 @@import base64+import hashlibimport uuidfrom datetime import timedeltaimport orjsonimport responses+import time_machinefrom django.conf import settingsfrom django.test import override_settingsfrom django.utils.timezone import nowfrom nacl.encoding import Base64Encoderfrom nacl.public import PublicKey, SealedBox+from zerver.lib.devices import b64decode_token_id_base64from zerver.lib.exceptions import (InvalidBouncerPublicKeyError,InvalidEncryptedPushRegistrationError,RequestExpiredError,)+from zerver.lib.push_registration import check_push_keyfrom zerver.lib.queue import queue_event_on_commitfrom zerver.lib.test_classes import BouncerTestCasefrom zerver.lib.test_helpers import activate_push_notification_service, mock_queue_publishfrom zerver.lib.timestamp import datetime_to_timestamp-from zerver.models import PushDevice+from zerver.models import Device, UserProfilefrom zilencer.models import RemotePushDevice, RemoteRealm@@ -46,6 +50,9 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):"timestamp": timestamp,}+ hash_bytes = hashlib.sha256(token.encode()).digest()+ token_id_base64 = base64.b64encode(hash_bytes[0:8]).decode()+assert settings.PUSH_REGISTRATION_ENCRYPTION_KEYSpublic_key_str: str = next(iter(settings.PUSH_REGISTRATION_ENCRYPTION_KEYS.keys()))public_key = PublicKey(public_key_str.encode("utf-8"), Base64Encoder)@@ -57,7 +64,7 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):payload: dict[str, str | int] = {"realm_uuid": str(remote_realm.uuid),- "push_account_id": 2408,+ "token_id": token_id_base64,"encrypted_push_registration": encrypted_push_registration,"bouncer_public_key": public_key_str,}@@ -74,12 +81,14 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):"/api/v1/remotes/push/e2ee/register",payload,)- response_dict = self.assert_json_success(result)- device_id = response_dict["device_id"]+ self.assert_json_success(result)remote_push_devices = RemotePushDevice.objects.all()self.assert_length(remote_push_devices, 1)- self.assertEqual(device_id, remote_push_devices[0].device_id)+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(+ remote_push_devices[0].token_id, b64decode_token_id_base64(payload["token_id"])+ )# Idempotentresult = self.uuid_post(@@ -87,8 +96,7 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):"/api/v1/remotes/push/e2ee/register",payload,)- response_dict = self.assert_json_success(result)- self.assertEqual(response_dict["device_id"], device_id)+ self.assert_json_success(result)remote_push_devices_count = RemotePushDevice.objects.count()self.assertEqual(remote_push_devices_count, 1)@@ -101,12 +109,14 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):"/api/v1/remotes/push/e2ee/register",payload,)- response_dict = self.assert_json_success(result)- device_id = response_dict["device_id"]+ self.assert_json_success(result)remote_push_devices = RemotePushDevice.objects.order_by("pk")self.assert_length(remote_push_devices, 2)- self.assertEqual(device_id, remote_push_devices[1].device_id)+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(+ remote_push_devices[1].token_id, b64decode_token_id_base64(payload["token_id"])+ )def test_register_push_device_error(self) -> None:payload = self.get_register_push_device_payload()@@ -202,10 +212,21 @@ class RegisterPushDeviceToBouncer(BouncerTestCase):)self.assert_json_error(result, "Invalid encrypted_push_registration")+ # Invalid `token_id`+ payload = self.get_register_push_device_payload()+ payload["token_id"] = "192057"+ result = self.uuid_post(+ self.server_uuid,+ "/api/v1/remotes/push/e2ee/register",+ payload,+ )+ self.assert_json_error(result, "Invalid encrypted_push_registration")+class RegisterPushDeviceToServer(BouncerTestCase):def get_register_push_device_payload(self,+ device_user: UserProfile | None = None,token: str = "c0ffee",token_kind: str = RemotePushDevice.TokenKind.APNS,ios_app_id: str | None = "example.app",@@ -221,6 +242,9 @@ class RegisterPushDeviceToServer(BouncerTestCase):"timestamp": timestamp,}+ hash_bytes = hashlib.sha256(token.encode()).digest()+ token_id_base64 = base64.b64encode(hash_bytes[0:8]).decode()+assert settings.PUSH_REGISTRATION_ENCRYPTION_KEYSpublic_key_str: str = next(iter(settings.PUSH_REGISTRATION_ENCRYPTION_KEYS.keys()))public_key = PublicKey(public_key_str.encode("utf-8"), Base64Encoder)@@ -230,43 +254,74 @@ class RegisterPushDeviceToServer(BouncerTestCase):)encrypted_push_registration = encrypted_push_registration_bytes.decode("utf-8")+ if device_user is None:+ device_user = self.example_user("hamlet")+ device = Device.objects.create(user=device_user)+payload: dict[str, str | int] = {+ "device_id": device.id,"token_kind": token_kind,- "push_account_id": 2408,"push_key": "MY+paNlyduYJRQFNZva8w7Gv3PkBua9kIj581F9Vr301",+ "push_key_id": 2408,"bouncer_public_key": public_key_str,"encrypted_push_registration": encrypted_push_registration,+ "token_id": token_id_base64,}return payload- @activate_push_notification_service()- @responses.activate+ def assert_push_fields_null(self, device: Device) -> None:+ self.assertIsNone(device.push_key)+ self.assertIsNone(device.push_key_id)+ self.assertIsNone(device.push_token_id)+ self.assertIsNone(device.pending_push_token_id)+ self.assertIsNone(device.push_token_kind)+ self.assertIsNone(device.push_token_last_updated_timestamp)+ self.assertIsNone(device.push_registration_error_code)+def test_register_push_device_success(self) -> None:- self.add_mock_response()self.login("hamlet")- push_devices_count = PushDevice.objects.count()- self.assertEqual(push_devices_count, 0)-payload = self.get_register_push_device_payload()- # Verify the created `PushDevice` row and `push_device` event+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])++ # Verify the updated `Device` row and `device` event# while the `register_push_device_to_bouncer` event is still# not consumed by the `PushNotificationsWorker` worker.+ time_now = now()with (+ time_machine.travel(time_now, tick=False),self.capture_send_event_calls(expected_num_events=1) as events,mock_queue_publish("zerver.views.push_notifications.queue_event_on_commit") as m,):result = self.client_post("/json/mobile_push/register", payload)self.assert_json_success(result)m.assert_called_once()- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertIsNone(push_devices[0].bouncer_device_id)- self.assertEqual(push_devices[0].status, "pending")+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]+ self.assertEqual(device.push_key_id, payload["push_key_id"])+ self.assertIsNone(device.push_token_id)+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(+ device.pending_push_token_id, b64decode_token_id_base64(payload["token_id"])+ )+ self.assertEqual(device.push_token_kind, payload["token_kind"])+ self.assertEqual(device.push_token_last_updated_timestamp, time_now)+ self.assertIsNone(device.push_registration_error_code)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)queue_name = m.call_args[0][0]@@ -275,42 +330,85 @@ class RegisterPushDeviceToServer(BouncerTestCase):# Now, the `PushNotificationsWorker` worker consumes.with self.capture_send_event_calls(expected_num_events=1) as events:queue_event_on_commit(queue_name, queue_message)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertIsNotNone(push_devices[0].bouncer_device_id)- self.assertEqual(push_devices[0].status, "active")+ device.refresh_from_db()+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(device.push_token_id, b64decode_token_id_base64(payload["token_id"]))+ self.assertIsNone(device.pending_push_token_id)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="active"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_token_id=payload["token_id"],+ pending_push_token_id=None,+ ),)# Idempotentwith self.capture_send_event_calls(expected_num_events=0):result = self.client_post("/json/mobile_push/register", payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)+ pending_push_devices_count = Device.objects.filter(+ pending_push_token_id__isnull=False+ ).count()+ self.assertEqual(pending_push_devices_count, 0)++ @activate_push_notification_service()+ @responses.activate+ @override_settings(ZILENCER_ENABLED=False)+ def test_register_push_device_self_hosted_server_success(self) -> None:+ """+ Self-hosted servers make a network call to bouncer instead of+ a `do_register_remote_push_device` function call.+ """+ self.add_mock_response()+ self.login("hamlet")++ payload = self.get_register_push_device_payload()++ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])- # For self-hosted servers. They make a network call to bouncer- # instead of a `do_register_remote_push_device` function call.+ time_now = now()with (- self.settings(ZILENCER_ENABLED=False),+ time_machine.travel(time_now, tick=False),self.capture_send_event_calls(expected_num_events=2) as events,):- payload["push_account_id"] = 5555result = self.client_post("/json/mobile_push/register", payload)self.assert_json_success(result)- push_devices = PushDevice.objects.order_by("pk")- self.assert_length(push_devices, 2)- self.assertIsNotNone(push_devices[1].bouncer_device_id)- self.assertEqual(push_devices[1].status, "active")+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]+ self.assertEqual(device.push_key_id, payload["push_key_id"])+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(device.push_token_id, b64decode_token_id_base64(payload["token_id"]))+ self.assertIsNone(device.pending_push_token_id)+ self.assertEqual(device.push_token_kind, payload["token_kind"])+ self.assertEqual(device.push_token_last_updated_timestamp, time_now)+ self.assertIsNone(device.push_registration_error_code)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=5555, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(events[1]["event"],- dict(type="push_device", push_account_id=5555, status="active"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_token_id=payload["token_id"],+ pending_push_token_id=None,+ ),)@override_settings(ZILENCER_ENABLED=False)@@ -321,6 +419,30 @@ class RegisterPushDeviceToServer(BouncerTestCase):result = self.client_post("/json/mobile_push/register", payload)self.assert_json_error(result, "Server is not configured to use push notification service.")+ @activate_push_notification_service()+ def test_invalid_device_error(self) -> None:+ self.login("hamlet")+ iago = self.example_user("iago")+ payload = self.get_register_push_device_payload(device_user=iago)++ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_error(result, "Invalid `device_id`")++ @activate_push_notification_service()+ def test_missing_parameters_error(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()++ # Payload not good for push key rotation, token rotation, or fresh registration.+ del payload["push_key_id"]+ del payload["token_id"]++ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_error(+ result,+ "Missing parameters: must provide either all push key fields, all token fields, or both.",+ )+@activate_push_notification_service()def test_invalid_push_key_error(self) -> None:self.login("hamlet")@@ -349,6 +471,35 @@ class RegisterPushDeviceToServer(BouncerTestCase):result = self.client_post("/json/mobile_push/register", invalid_push_key_payload)self.assert_json_error(result, "Invalid `push_key`")+ @activate_push_notification_service()+ def test_invalid_push_key_id_error(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()++ # Test negative push_key_id+ invalid_push_key_id_payload = {**payload, "push_key_id": -1}+ result = self.client_post("/json/mobile_push/register", invalid_push_key_id_payload)+ self.assert_json_error(+ result, "Invalid push_key_id: Value error, Not a valid unsigned 32-bit integer"+ )++ # Test push_key_id > 2^32 - 1+ invalid_push_key_id_payload = {**payload, "push_key_id": 4294967296}+ result = self.client_post("/json/mobile_push/register", invalid_push_key_id_payload)+ self.assert_json_error(+ result, "Invalid push_key_id: Value error, Not a valid unsigned 32-bit integer"+ )++ @activate_push_notification_service()+ def test_invalid_token_id_error(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()++ # Invalid Base64 alphabet in `token_id`+ invalid_token_id_payload = {**payload, "token_id": "@abcdefg"}+ result = self.client_post("/json/mobile_push/register", invalid_token_id_payload)+ self.assert_json_error(result, "`token_id` is not Base64 encoded")+@activate_push_notification_service()@override_settings(ZILENCER_ENABLED=False)@responses.activate@@ -357,52 +508,85 @@ class RegisterPushDeviceToServer(BouncerTestCase):hamlet = self.example_user("hamlet")self.login_user(hamlet)- push_devices_count = PushDevice.objects.count()- self.assertEqual(push_devices_count, 0)-payload = self.get_register_push_device_payload()+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])+# Verify InvalidBouncerPublicKeyError+ time_now = now()invalid_bouncer_public_key_payload = {**payload, "bouncer_public_key": "invalid public key"}- with self.capture_send_event_calls(expected_num_events=2) as events:+ with (+ time_machine.travel(time_now, tick=False),+ self.capture_send_event_calls(expected_num_events=2) as events,+ ):result = self.client_post("/json/mobile_push/register", invalid_bouncer_public_key_payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertEqual(push_devices[0].error_code, InvalidBouncerPublicKeyError.code.name)- self.assertEqual(push_devices[0].status, "failed")+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]+ self.assertEqual(+ device.push_registration_error_code, InvalidBouncerPublicKeyError.code.name+ )self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(events[1]["event"],dict(- type="push_device",- push_account_id=2408,- status="failed",- error_code="INVALID_BOUNCER_PUBLIC_KEY",+ type="device",+ op="update",+ device_id=device.id,+ push_registration_error_code="INVALID_BOUNCER_PUBLIC_KEY",),)# Retrying with correct payload results in success.- # `error_code` of the same PushDevice row updated to None.- with self.capture_send_event_calls(expected_num_events=2) as events:+ # `push_registration_error_code` of the same Device row updated to None.+ with (+ time_machine.travel(time_now, tick=False),+ self.capture_send_event_calls(expected_num_events=2) as events,+ ):result = self.client_post("/json/mobile_push/register", payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertIsNone(push_devices[0].error_code)- self.assertEqual(push_devices[0].status, "active")+ device.refresh_from_db()+ self.assertIsNone(device.push_registration_error_code)+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(device.push_token_id, b64decode_token_id_base64(payload["token_id"]))+ self.assertIsNone(device.pending_push_token_id)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(events[1]["event"],- dict(type="push_device", push_account_id=2408, status="active"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_token_id=payload["token_id"],+ pending_push_token_id=None,+ ),)@activate_push_notification_service()@@ -413,31 +597,45 @@ class RegisterPushDeviceToServer(BouncerTestCase):hamlet = self.example_user("hamlet")self.login_user(hamlet)- push_devices_count = PushDevice.objects.count()- self.assertEqual(push_devices_count, 0)+ invalid_token_payload = self.get_register_push_device_payload(token="")++ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])# Verify InvalidEncryptedPushRegistrationError- invalid_token_payload = self.get_register_push_device_payload(token="")- with self.capture_send_event_calls(expected_num_events=2) as events:+ time_now = now()+ with (+ time_machine.travel(time_now, tick=False),+ self.capture_send_event_calls(expected_num_events=2) as events,+ ):result = self.client_post("/json/mobile_push/register", invalid_token_payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertEqual(push_devices[0].status, "failed")+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]self.assertEqual(- push_devices[0].error_code, InvalidEncryptedPushRegistrationError.code.name+ device.push_registration_error_code, InvalidEncryptedPushRegistrationError.code.name)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=invalid_token_payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(events[1]["event"],dict(- type="push_device",- push_account_id=2408,- status="failed",- error_code="BAD_REQUEST",+ type="device",+ op="update",+ device_id=device.id,+ push_registration_error_code="BAD_REQUEST",),)@@ -449,41 +647,51 @@ class RegisterPushDeviceToServer(BouncerTestCase):hamlet = self.example_user("hamlet")self.login_user(hamlet)- push_devices_count = PushDevice.objects.count()- self.assertEqual(push_devices_count, 0)-- # Verify RequestExpiredErrorliveness_timed_out_payload = self.get_register_push_device_payload(timestamp=datetime_to_timestamp(now() - timedelta(days=2)))++ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])++ # Verify RequestExpiredError+ time_now = now()with (+ time_machine.travel(time_now, tick=False),self.assertLogs(level="ERROR") as m,self.capture_send_event_calls(expected_num_events=2) as events,):result = self.client_post("/json/mobile_push/register", liveness_timed_out_payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)- self.assertEqual(push_devices[0].status, "failed")- self.assertEqual(push_devices[0].error_code, RequestExpiredError.code.name)+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]+ self.assertEqual(device.push_registration_error_code, RequestExpiredError.code.name)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=liveness_timed_out_payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(events[1]["event"],dict(- type="push_device",- push_account_id=2408,- status="failed",- error_code="REQUEST_EXPIRED",+ type="device",+ op="update",+ device_id=device.id,+ push_registration_error_code="REQUEST_EXPIRED",),)self.assertEqual(m.output,- [- f"ERROR:root:Push device registration request for user_id={hamlet.id}, push_account_id=2408 expired."- ],+ [f"ERROR:root:Push registration request for device_id={device.id} expired."],)@activate_push_notification_service()@@ -494,35 +702,202 @@ class RegisterPushDeviceToServer(BouncerTestCase):hamlet = self.example_user("hamlet")self.login_user(hamlet)- push_devices_count = PushDevice.objects.count()- self.assertEqual(push_devices_count, 0)-payload = self.get_register_push_device_payload()+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ self.assert_push_fields_null(devices[0])+# Verify MissingRemoteRealm# Update realm's UUID to a random UUID.hamlet.realm.uuid = uuid.uuid4()hamlet.realm.save()+ time_now = now()with (+ time_machine.travel(time_now, tick=False),self.assertLogs(level="ERROR") as m,self.capture_send_event_calls(expected_num_events=1) as events,):result = self.client_post("/json/mobile_push/register", payload)self.assert_json_success(result)- push_devices = PushDevice.objects.all()- self.assert_length(push_devices, 1)+ devices = Device.objects.all()+ self.assert_length(devices, 1)+ device = devices[0]# We keep retrying until `RequestExpiredError` is raised.- self.assertEqual(push_devices[0].status, "pending")+ self.assertIsNotNone(device.pending_push_token_id)+ self.assertIsNone(device.push_registration_error_code)self.assertEqual(events[0]["event"],- dict(type="push_device", push_account_id=2408, status="pending"),+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_key_id=device.push_key_id,+ pending_push_token_id=payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),)self.assertEqual(m.output[0],- f"ERROR:root:Push device registration request for user_id={hamlet.id}, push_account_id=2408 failed.",+ f"ERROR:root:Push device registration request for device_id={device.id} failed.",)# TODO: Verify that we retry for a day, then raise `RequestExpiredError`.# This implementation would be a follow-up. Currently `retry_event`# leads to 3 retries at max.++ @activate_push_notification_service()+ def test_push_key_rotation(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()+ device = Device.objects.get(id=payload["device_id"])+ self.assert_push_fields_null(device)++ # Attempt to set only `push_key` and `push_key_id` fields.+ rotate_push_key_payload = {+ "device_id": device.id,+ "push_key": "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt",+ "push_key_id": 1144,+ }+ result = self.client_post("/json/mobile_push/register", rotate_push_key_payload)+ self.assert_json_error(result, "No push registration exists to rotate key for.")++ # Fresh push registration.+ with self.capture_send_event_calls(expected_num_events=2):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_success(result)+ device.refresh_from_db()+ assert device.push_key is not None+ assert type(payload["push_key"]) is str # for mypy+ self.assertEqual(bytes(device.push_key), check_push_key(payload["push_key"]))+ self.assertEqual(device.push_key_id, payload["push_key_id"])++ # Rotate push key for the registration.+ with self.capture_send_event_calls(expected_num_events=1) as events:+ result = self.client_post("/json/mobile_push/register", rotate_push_key_payload)+ self.assert_json_success(result)+ device.refresh_from_db()+ assert device.push_key is not None+ assert type(rotate_push_key_payload["push_key"]) is str # for mypy+ self.assertEqual(+ bytes(device.push_key), check_push_key(rotate_push_key_payload["push_key"])+ )+ self.assertEqual(device.push_key_id, rotate_push_key_payload["push_key_id"])+ self.assertEqual(+ events[0]["event"],+ dict(type="device", op="update", device_id=device.id, push_key_id=device.push_key_id),+ )++ # Idempotent+ with self.capture_send_event_calls(expected_num_events=0):+ result = self.client_post("/json/mobile_push/register", rotate_push_key_payload)+ self.assert_json_success(result)++ @activate_push_notification_service()+ def test_token_rotation(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()+ device = Device.objects.get(id=payload["device_id"])+ self.assert_push_fields_null(device)++ # Attempt to set only token fields.+ push_registration: dict[str, str | int] = {+ "token": "abcdef",+ "token_kind": Device.PushTokenKind.APNS,+ "ios_app_id": "example.app",+ "timestamp": datetime_to_timestamp(now()),+ }+ assert settings.PUSH_REGISTRATION_ENCRYPTION_KEYS+ public_key_str: str = next(iter(settings.PUSH_REGISTRATION_ENCRYPTION_KEYS.keys()))+ public_key = PublicKey(public_key_str.encode("utf-8"), Base64Encoder)+ sealed_box = SealedBox(public_key)+ encrypted_push_registration_bytes = sealed_box.encrypt(+ orjson.dumps(push_registration), Base64Encoder+ )+ encrypted_push_registration = encrypted_push_registration_bytes.decode("utf-8")+ assert type(push_registration["token"]) is str # for mypy+ hash_bytes = hashlib.sha256(push_registration["token"].encode()).digest()+ token_id_base64 = base64.b64encode(hash_bytes[0:8]).decode()+ rotate_token_payload = {+ "device_id": device.id,+ "token_kind": Device.PushTokenKind.APNS,+ "bouncer_public_key": public_key_str,+ "encrypted_push_registration": encrypted_push_registration,+ "token_id": token_id_base64,+ }+ result = self.client_post("/json/mobile_push/register", rotate_token_payload)+ self.assert_json_error(result, "No push registration exists to rotate token for.")++ # Fresh push registration.+ with self.capture_send_event_calls(expected_num_events=2):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_success(result)+ device.refresh_from_db()+ assert type(payload["token_id"]) is str # for mypy+ self.assertEqual(device.push_token_id, b64decode_token_id_base64(payload["token_id"]))++ # Rotate token for the registration.+ time_now = now()+ with (+ time_machine.travel(time_now, tick=False),+ self.capture_send_event_calls(expected_num_events=2) as events,+ ):+ result = self.client_post("/json/mobile_push/register", rotate_token_payload)+ self.assert_json_success(result)+ device.refresh_from_db()+ assert type(rotate_token_payload["token_id"]) is str # for mypy+ self.assertEqual(+ device.push_token_id, b64decode_token_id_base64(rotate_token_payload["token_id"])+ )+ self.assertEqual(+ events[0]["event"],+ dict(+ type="device",+ op="update",+ device_id=device.id,+ pending_push_token_id=rotate_token_payload["token_id"],+ push_token_last_updated_timestamp=datetime_to_timestamp(time_now),+ push_registration_error_code=None,+ ),+ )+ self.assertEqual(+ events[1]["event"],+ dict(+ type="device",+ op="update",+ device_id=device.id,+ push_token_id=rotate_token_payload["token_id"],+ pending_push_token_id=None,+ ),+ )++ # Idempotent+ with self.capture_send_event_calls(expected_num_events=0):+ result = self.client_post("/json/mobile_push/register", rotate_token_payload)+ self.assert_json_success(result)++ @activate_push_notification_service()+ def test_avoid_parallel_registration_request_to_bouncer(self) -> None:+ self.login("hamlet")+ payload = self.get_register_push_device_payload()++ # Fresh registration request, `register_push_device_to_bouncer` event+ # not consumed by the `PushNotificationsWorker` worker yet.+ with (+ self.capture_send_event_calls(expected_num_events=1),+ mock_queue_publish("zerver.views.push_notifications.queue_event_on_commit") as m,+ ):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_success(result)+ m.assert_called_once()++ # Another registration request is not processed.+ with (+ self.capture_send_event_calls(expected_num_events=0),+ mock_queue_publish("zerver.views.push_notifications.queue_event_on_commit") as m,+ ):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_error(result, "A registration for the device already in progress.")+ m.assert_not_called()diff --git a/zilencer/migrations/0069_remove_remotepushdevice_push_account_id.py b/zilencer/migrations/0069_remove_remotepushdevice_push_account_id.pynew file mode 100644index 00000000000..30dadf2f6b4--- /dev/null+++ b/zilencer/migrations/0069_remove_remotepushdevice_push_account_id.py@@ -0,0 +1,16 @@+# Generated by Django 5.2.10 on 2026-02-03 16:35++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("zilencer", "0068_add_remotepushdevice_token_id_and_more"),+ ]++ operations = [+ migrations.RemoveField(+ model_name="remotepushdevice",+ name="push_account_id",+ ),+ ]diff --git a/zilencer/models.py b/zilencer/models.pyindex 3010cfb3433..541a0294686 100644--- a/zilencer/models.py+++ b/zilencer/models.py@@ -11,13 +11,7 @@ from typing_extensions import overridefrom analytics.models import BaseCountfrom zerver.lib.rate_limiter import RateLimitedObject-from zerver.models import (- AbstractPushDevice,- AbstractPushDeviceToken,- AbstractRealmAuditLog,- Realm,- UserProfile,-)+from zerver.models import AbstractPushDeviceToken, AbstractRealmAuditLog, Realm, UserProfilefrom zerver.models.realm_audit_logs import AuditLogEventType@@ -630,7 +624,7 @@ def has_stale_audit_log(server: RemoteZulipServer) -> bool:return False-class RemotePushDevice(AbstractPushDevice):+class RemotePushDevice(models.Model):"""Core bouncer server table storing registrations to receivemobile push notifications via the bouncer server.@@ -656,6 +650,12 @@ class RemotePushDevice(AbstractPushDevice):# ID to reference the `token`.token_id = models.BigIntegerField()+ class TokenKind(models.TextChoices):+ APNS = "apns", "APNs"+ FCM = "fcm", "FCM"++ token_kind = models.CharField(max_length=4, choices=TokenKind.choices)+# If the token is expired, the date when the bouncer learned it# was expired via an error from the FCM/APNs server. Used to# support delayed deletion. Null if the bouncer believes this