Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
push_notifications: Rework using `Device` model.
Prakhar Pratyushc9dd1a413627
diff --git a/api_docs/unmerged.d/ZF-42fbcd.md b/api_docs/unmerged.d/ZF-42fbcd.mdindex 97c29b1eb22..369033e8d88 100644--- a/api_docs/unmerged.d/ZF-42fbcd.md+++ b/api_docs/unmerged.d/ZF-42fbcd.md@@ -9,3 +9,5 @@* [`POST /remotes/push/e2ee/register`](/api/register-remote-push-device):Replaced `push_account_id` with `token_id` to support rotationof `push_key` and FCM/APNs provided token.+* [`POST /mobile_push/e2ee/test_notification`](/api/e2ee-test-notify):+ Replaced `push_account_id` parameter with `device_id`.diff --git a/zerver/actions/message_flags.py b/zerver/actions/message_flags.pyindex 1515c96cc1b..89706cf99ea 100644--- a/zerver/actions/message_flags.py+++ b/zerver/actions/message_flags.py@@ -19,7 +19,7 @@ from zerver.lib.queue import queue_event_on_commitfrom zerver.lib.stream_subscription import get_subscribed_stream_recipient_ids_for_userfrom zerver.lib.topic import filter_by_topic_name_via_messagefrom zerver.lib.user_message import DEFAULT_HISTORICAL_FLAGS, create_historical_user_messages-from zerver.models import Message, PushDevice, PushDeviceToken, Recipient, UserMessage, UserProfile+from zerver.models import Device, Message, PushDeviceToken, Recipient, UserMessage, UserProfilefrom zerver.tornado.django_api import send_event_on_commit, send_event_rollback_unsafe@@ -268,9 +268,9 @@ def do_clear_mobile_push_notifications_for_ids(PushDeviceToken.objects.filter(user_id__in=clear_notifications_user_ids).values_list("user_id", flat=True).union(- # Uses index "zerver_pushdevice_user_bouncer_device_id_idx".- PushDevice.objects.filter(- user_id__in=clear_notifications_user_ids, bouncer_device_id__isnull=False+ # Uses index "zerver_device_user_push_token_id_idx".+ Device.objects.filter(+ user_id__in=clear_notifications_user_ids, push_token_id__isnull=False).values_list("user_id", flat=True)))diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.pyindex fde82ac1c02..78159a90602 100644--- a/zerver/actions/message_send.py+++ b/zerver/actions/message_send.py@@ -103,8 +103,8 @@ from zerver.lib.validator import check_widget_contentfrom zerver.lib.widget import do_widget_post_save_actionsfrom zerver.models import (Client,+ Device,Message,- PushDevice,PushDeviceToken,Realm,Recipient,@@ -427,12 +427,10 @@ def get_recipient_info("QuerySet[WithAnnotations[UserProfile, UserProfileAnnotations], ActiveUserDict]",UserProfile.objects.filter(is_active=True).annotate(- # Uses index "zerver_pushdevice_user_bouncer_device_id_idx"+ # Uses index "zerver_device_user_push_token_id_idx"# and "zerver_pushdevicetoken_user_id_015e5dc1".has_push_device_registered=Exists(- PushDevice.objects.filter(- user_id=OuterRef("id"), bouncer_device_id__isnull=False- )+ Device.objects.filter(user_id=OuterRef("id"), push_token_id__isnull=False))| Exists(PushDeviceToken.objects.filter(user_id=OuterRef("id"))))diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.pyindex 4f9f0de5aec..7022f8e5789 100644--- a/zerver/lib/push_notifications.py+++ b/zerver/lib/push_notifications.py@@ -38,6 +38,7 @@ from zerver.actions.realm_settings import (do_set_realm_property,)from zerver.lib.avatar import absolute_avatar_url, get_avatar_for_inaccessible_user+from zerver.lib.devices import b64decode_token_id_base64, b64encode_token_id_intfrom zerver.lib.display_recipient import get_display_recipientfrom zerver.lib.emoji_utils import hex_codepoint_to_emojifrom zerver.lib.exceptions import ErrorCode, JsonableError, MissingRemoteRealmError@@ -65,6 +66,7 @@ from zerver.lib.users import check_can_access_userfrom zerver.models import (AbstractPushDeviceToken,ArchivedMessage,+ Device,Message,PushDevice,PushDeviceToken,@@ -77,6 +79,7 @@ from zerver.models import (from zerver.models.realms import get_fake_email_domainfrom zerver.models.scheduled_jobs import NotificationTriggersfrom zerver.models.users import get_user_profile_by_id+from zerver.tornado.django_api import send_event_on_commitif TYPE_CHECKING:import aioapns@@ -241,7 +244,7 @@ def dedupe_device_tokens(@dataclassclass APNsResultInfo:successfully_sent: bool- delete_device_id: int | None = None+ delete_token_id_base64: str | None = Nonedelete_device_token: str | None = None@@ -266,7 +269,7 @@ def get_info_from_apns_result("APNs: Removing invalid/expired token %s (%s)", device.token, result.description)if settings.ZILENCER_ENABLED and isinstance(device, RemotePushDevice):- result_info.delete_device_id = device.device_id+ result_info.delete_token_id_base64 = b64encode_token_id_int(device.token_id)else:result_info.delete_device_token = device.tokenelse:@@ -1415,7 +1418,7 @@ class RealmPushStatusDict(TypedDict):class SendNotificationResponseData(TypedDict):android_successfully_sent_count: intapple_successfully_sent_count: int- delete_device_ids: list[int]+ delete_token_ids: list[str]class SendNotificationRemoteResponseData(SendNotificationResponseData):@@ -1434,13 +1437,13 @@ class PushRequestBasePayload:# FCM expects in this type must always be strings. Non-string# fields must be converted into strings in the FCM code path# within send_e2ee_push_notifications.- push_account_id: int+ push_key_id: intencrypted_data: str@dataclassclass FCMPushRequest:- device_id: int+ token_id: strfcm_priority: FCMPrioritypayload: PushRequestBasePayload@@ -1460,7 +1463,7 @@ class APNsPayload(PushRequestBasePayload):@dataclassclass APNsPushRequest:- device_id: int+ token_id: strhttp_headers: APNsHTTPHeaderspayload: APNsPayload@@ -1496,7 +1499,7 @@ def get_encrypted_data(payload_data_to_encrypt: dict[str, Any], push_key_bytes:def send_push_notifications(user_profile: UserProfile,payload_data_to_encrypt: dict[str, Any],- push_devices: QuerySet[PushDevice],+ push_devices: QuerySet[Device],) -> None:assert len(push_devices) != 0@@ -1512,30 +1515,32 @@ def send_push_notifications(# Prepare payload to send.push_requests: list[FCMPushRequest | APNsPushRequest] = []for push_device in push_devices:- assert push_device.bouncer_device_id is not None # for mypy+ assert push_device.push_key is not None # for mypy+ assert push_device.push_key_id is not None # for mypy+ assert push_device.push_token_id is not None # for mypyencrypted_data = get_encrypted_data(payload_data_to_encrypt, bytes(push_device.push_key))- if push_device.token_kind == PushDevice.TokenKind.APNS:+ if push_device.push_token_kind == Device.PushTokenKind.APNS:apns_http_headers = APNsHTTPHeaders(apns_priority=apns_priority,apns_push_type=apns_push_type,)apns_payload = APNsPayload(- push_account_id=push_device.push_account_id,+ push_key_id=push_device.push_key_id,encrypted_data=encrypted_data,)apns_push_request = APNsPushRequest(- device_id=push_device.bouncer_device_id,+ token_id=b64encode_token_id_int(push_device.push_token_id),http_headers=apns_http_headers,payload=apns_payload,)push_requests.append(apns_push_request)else:fcm_payload = PushRequestBasePayload(- push_account_id=push_device.push_account_id,+ push_key_id=push_device.push_key_id,encrypted_data=encrypted_data,)fcm_push_request = FCMPushRequest(- device_id=push_device.bouncer_device_id,+ token_id=b64encode_token_id_int(push_device.push_token_id),fcm_priority=fcm_priority,payload=fcm_payload,)@@ -1579,20 +1584,32 @@ def send_push_notifications(return# Handle success response data- delete_device_ids = response_data["delete_device_ids"]+ delete_token_ids_base64 = response_data["delete_token_ids"]+ delete_token_ids_int = [+ b64decode_token_id_base64(token_id_base64) for token_id_base64 in delete_token_ids_base64+ ]apple_successfully_sent_count = response_data["apple_successfully_sent_count"]android_successfully_sent_count = response_data["android_successfully_sent_count"]- if len(delete_device_ids) > 0:+ if len(delete_token_ids_base64) > 0:logger.info(- "Deleting PushDevice rows with the following device IDs based on response from bouncer: %s",- sorted(delete_device_ids),+ "Clearing `push_token_id` for Device rows with the following token IDs based on response from bouncer: %s",+ sorted(delete_token_ids_base64),)- # Filtering on `user_profile` is not necessary here, we do it to take- # advantage of 'zerver_pushdevice_user_bouncer_device_id_idx' index.- PushDevice.objects.filter(- user=user_profile, bouncer_device_id__in=delete_device_ids- ).delete()+ # Uses 'zerver_device_user_push_token_id_idx' index.+ with transaction.atomic(durable=True):+ push_devices = Device.objects.select_for_update().filter(+ user=user_profile, push_token_id__in=delete_token_ids_int+ )+ for push_device in push_devices:+ event = dict(+ type="device",+ op="update",+ device_id=push_device.id,+ push_token_id=None,+ )+ send_event_on_commit(user_profile.realm, event, [user_profile.id])+ push_devices.update(push_token_id=None)do_increment_logging_stat(user_profile.realm,@@ -1628,7 +1645,7 @@ def send_push_notifications(if can_push:record_push_notifications_recently_working()- if is_test_notification and len(push_requests) == len(delete_device_ids):+ if is_test_notification and len(push_requests) == len(delete_token_ids_base64):# While sending test push notification, the bouncer reported# that there's no active registered push device. Inform the# same to the client.@@ -1667,8 +1684,8 @@ def prepare_payload_and_send_push_notifications()# Send E2EE push notifications.- # Uses 'zerver_pushdevice_user_bouncer_device_id_idx' index.- push_devices = PushDevice.objects.filter(user=user_profile, bouncer_device_id__isnull=False)+ # Uses 'zerver_device_user_push_token_id_idx' index.+ push_devices = Device.objects.filter(user=user_profile, push_token_id__isnull=False)if push_devices:payload_to_encrypt = get_payload_to_encrypt()send_push_notifications(user_profile, payload_to_encrypt, push_devices)@@ -1941,7 +1958,7 @@ def send_test_push_notification(user_profile: UserProfile, devices: list[PushDevdef send_e2ee_test_push_notification(- user_profile: UserProfile, push_devices: QuerySet[PushDevice]+ user_profile: UserProfile, push_devices: QuerySet[Device]) -> None:payload_data_to_encrypt = get_base_payload(user_profile, for_legacy_clients=False)payload_data_to_encrypt["type"] = "test"diff --git a/zerver/models/devices.py b/zerver/models/devices.pyindex af141859de0..d43d93aec45 100644--- a/zerver/models/devices.py+++ b/zerver/models/devices.py@@ -60,6 +60,9 @@ class Device(models.Model):]indexes = [models.Index(+ # Used in 'get_recipient_info', `do_clear_mobile_push_notifications_for_ids`,+ # `prepare_payload_and_send_push_notifications`, `send_push_notifications`,+ # and `send_e2ee_test_push_notification_api`.fields=["user", "push_token_id"],condition=Q(push_token_id__isnull=False),name="zerver_device_user_push_token_id_idx",diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex f9c5682c5b5..76a46e61fde 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -12894,9 +12894,9 @@ paths:schema:type: objectproperties:- push_account_id:+ device_id:description: |- The push account ID for the device to which to send the test notification.+ The ID for the device to which to send the test notification.If this parameter is not submitted, the E2EE test notification willbe sent to all of the user's devices registered on the server.@@ -12904,10 +12904,14 @@ paths:A mobile client should pass this parameter, to avoid triggering a testnotification for other clients.- See [`POST /mobile_push/register`](/api/register-push-device)- for details on push account IDs.+ See [`POST /register_client_device`](/api/register-client-device)+ for details on device ID.++ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd).++ Previously, `push_account_id` was used.type: integer- example: 111222+ example: 1144responses:"200":description: Success.diff --git a/zerver/tests/test_handle_push_notification.py b/zerver/tests/test_handle_push_notification.pyindex 17fd3d58073..518b1d7f0e2 100644--- a/zerver/tests/test_handle_push_notification.py+++ b/zerver/tests/test_handle_push_notification.py@@ -612,7 +612,7 @@ class HandlePushNotificationTest(PushNotificationTestCase):# * 1 : `get_user_profile_by_id`# * 2 : `access_message_and_usermessage` (Fetch Message + UserMessage)# * 1 : update fetched user_message flag- # * 3 : fetch PushDeviceToken, update RealmCount, fetch PushDevice+ # * 3 : fetch PushDeviceToken, update RealmCount, fetch Devicemessage = self.get_message(Recipient.PERSONAL,type_id=self.personal_recipient_user.id,diff --git a/zerver/views/push_notifications.py b/zerver/views/push_notifications.pyindex 79f9eec90f7..e2976dd0017 100644--- a/zerver/views/push_notifications.py+++ b/zerver/views/push_notifications.py@@ -53,7 +53,7 @@ from zerver.lib.typed_endpoint import (typed_endpoint_without_parameters,)from zerver.lib.typed_endpoint_validators import check_string_in_validator, uint32_validator-from zerver.models import Device, PushDevice, PushDeviceToken, UserProfile+from zerver.models import Device, PushDeviceToken, UserProfilefrom zerver.views.errors import config_errorredis_client = redis_utils.get_redis_client()@@ -127,18 +127,17 @@ def send_test_push_notification_api(@human_users_only@typed_endpointdef send_e2ee_test_push_notification_api(- request: HttpRequest, user_profile: UserProfile, *, push_account_id: Json[int] | None = None+ request: HttpRequest, user_profile: UserProfile, *, device_id: Json[int] | None = None) -> HttpResponse:- # We skip push devices with `bouncer_device_id` set to `null` as they are+ # We skip devices with `push_token_id` set to `null` as they are# not yet registered with the bouncer to send mobile push notifications.- if push_account_id is not None:- # Uses unique index created for 'unique_push_device_user_push_account_id' constraint.- push_devices = PushDevice.objects.filter(- user=user_profile, push_account_id=push_account_id, bouncer_device_id__isnull=False+ if device_id is not None:+ push_devices = Device.objects.filter(+ id=device_id, user=user_profile, push_token_id__isnull=False)else:- # Uses 'zerver_pushdevice_user_bouncer_device_id_idx' index.- push_devices = PushDevice.objects.filter(user=user_profile, bouncer_device_id__isnull=False)+ # Uses 'zerver_device_user_push_token_id_idx' index.+ push_devices = Device.objects.filter(user=user_profile, push_token_id__isnull=False)if len(push_devices) == 0:raise NoActivePushDeviceErrordiff --git a/zilencer/lib/push_notifications.py b/zilencer/lib/push_notifications.pyindex 891225c4ce6..f00ae700628 100644--- a/zilencer/lib/push_notifications.py+++ b/zilencer/lib/push_notifications.py@@ -9,6 +9,7 @@ from firebase_admin import exceptions as firebase_exceptionsfrom firebase_admin import messaging as firebase_messagingfrom firebase_admin.messaging import UnregisteredError as FCMUnregisteredError+from zerver.lib.devices import b64decode_token_id_base64, b64encode_token_id_intfrom zerver.lib.push_notifications import (APNsPushRequest,FCMPushRequest,@@ -26,17 +27,18 @@ logger = logging.getLogger(__name__)@dataclassclass SentPushNotificationResult:successfully_sent_count: int- delete_device_ids: list[int]+ delete_token_ids_base64: list[str]def send_e2ee_push_notification_apple(apns_requests: list[NotificationRequest],apns_remote_push_devices: list[RemotePushDevice],+ log_context: str,) -> SentPushNotificationResult:import aioapnssuccessfully_sent_count = 0- delete_device_ids: list[int] = []+ delete_token_ids_base64: list[str] = []apns_context = get_apns_context()if apns_context is None:@@ -46,7 +48,7 @@ def send_e2ee_push_notification_apple()return SentPushNotificationResult(successfully_sent_count=successfully_sent_count,- delete_device_ids=delete_device_ids,+ delete_token_ids_base64=delete_token_ids_base64,)async def send_all_notifications() -> Iterable[@@ -61,7 +63,7 @@ def send_e2ee_push_notification_apple(results = apns_context.loop.run_until_complete(send_all_notifications())for remote_push_device, result in results:- log_context = f"to (push_account_id={remote_push_device.push_account_id}, device={remote_push_device.token})"+ log_context = log_context % remote_push_device.tokenresult_info = get_info_from_apns_result(result,remote_push_device,@@ -70,29 +72,30 @@ def send_e2ee_push_notification_apple(if result_info.successfully_sent:successfully_sent_count += 1- elif result_info.delete_device_id is not None:+ elif result_info.delete_token_id_base64 is not None:remote_push_device.expired_time = timezone_now()remote_push_device.save(update_fields=["expired_time"])- delete_device_ids.append(result_info.delete_device_id)+ delete_token_ids_base64.append(result_info.delete_token_id_base64)return SentPushNotificationResult(successfully_sent_count=successfully_sent_count,- delete_device_ids=delete_device_ids,+ delete_token_ids_base64=delete_token_ids_base64,)def send_e2ee_push_notification_android(fcm_requests: list[firebase_messaging.Message],fcm_remote_push_devices: list[RemotePushDevice],+ log_context: str,) -> SentPushNotificationResult:successfully_sent_count = 0- delete_device_ids: list[int] = []+ delete_token_ids_base64: list[str] = []if fcm_app is None:logger.error("FCM: Dropping push notifications since ANDROID_FCM_CREDENTIALS_PATH is unset")return SentPushNotificationResult(successfully_sent_count=successfully_sent_count,- delete_device_ids=delete_device_ids,+ delete_token_ids_base64=delete_token_ids_base64,)try:@@ -101,7 +104,7 @@ def send_e2ee_push_notification_android(logger.warning("Error while pushing to FCM", exc_info=True)return SentPushNotificationResult(successfully_sent_count=successfully_sent_count,- delete_device_ids=delete_device_ids,+ delete_token_ids_base64=delete_token_ids_base64,)for idx, response in enumerate(batch_response.responses):@@ -111,35 +114,30 @@ def send_e2ee_push_notification_android(remote_push_device = fcm_remote_push_devices[idx]token = remote_push_device.token- push_account_id = remote_push_device.push_account_id+ log_context = log_context % token+if response.success:successfully_sent_count += 1- logger.info(- "FCM: Sent message with ID: %s to (push_account_id=%s, device=%s)",- response.message_id,- push_account_id,- token,- )+ logger.info("FCM: Sent message with ID: %s %s", response.message_id, log_context)else:error = response.exceptionif isinstance(error, FCMUnregisteredError):remote_push_device.expired_time = timezone_now()remote_push_device.save(update_fields=["expired_time"])- delete_device_ids.append(remote_push_device.device_id)+ delete_token_ids_base64.append(b64encode_token_id_int(remote_push_device.token_id))logger.info("FCM: Removing %s due to %s", token, error.code)else:logger.warning(- "FCM: Delivery failed for (push_account_id=%s, device=%s): %s:%s",- push_account_id,- token,+ "FCM: Delivery failed %s: %s:%s",+ log_context,error.__class__,error,)return SentPushNotificationResult(successfully_sent_count=successfully_sent_count,- delete_device_ids=delete_device_ids,+ delete_token_ids_base64=delete_token_ids_base64,)@@ -153,21 +151,32 @@ def send_e2ee_push_notifications(import aioapns- device_ids = {push_request.device_id for push_request in push_requests}+ token_ids_base64 = set()+ token_ids_int = set()+ for push_request in push_requests:+ token_ids_base64.add(push_request.token_id)+ token_ids_int.add(b64decode_token_id_base64(push_request.token_id))+remote_push_devices = RemotePushDevice.objects.filter(- device_id__in=device_ids, expired_time__isnull=True, realm=realm, remote_realm=remote_realm+ token_id__in=token_ids_int,+ realm=realm,+ remote_realm=remote_realm,+ expired_time__isnull=True,)- device_id_to_remote_push_device = {- remote_push_device.device_id: remote_push_device+ token_id_base64_to_remote_push_device = {+ b64encode_token_id_int(remote_push_device.token_id): remote_push_devicefor remote_push_device in remote_push_devices}- unexpired_remote_push_device_ids = set(device_id_to_remote_push_device.keys())+ unexpired_token_ids_base64 = set(token_id_base64_to_remote_push_device.keys())- # Device IDs which should be deleted on server.- # Either the device ID is invalid or the token+ # Token IDs which should be deleted on server.+ # Either the token ID is invalid or the token# associated has been marked invalid/expired by APNs/FCM.- delete_device_ids = list(- filter(lambda device_id: device_id not in unexpired_remote_push_device_ids, device_ids)+ delete_token_ids_base64 = list(+ filter(+ lambda token_id_base64: token_id_base64 not in unexpired_token_ids_base64,+ token_ids_base64,+ ))apns_requests = []@@ -177,11 +186,11 @@ def send_e2ee_push_notifications(fcm_remote_push_devices: list[RemotePushDevice] = []for push_request in push_requests:- device_id = push_request.device_id- if device_id not in unexpired_remote_push_device_ids:+ token_id_base64 = push_request.token_id+ if token_id_base64 not in unexpired_token_ids_base64:continue- remote_push_device = device_id_to_remote_push_device[device_id]+ remote_push_device = token_id_base64_to_remote_push_device[token_id_base64]if remote_push_device.token_kind == RemotePushDevice.TokenKind.APNS:assert isinstance(push_request, APNsPushRequest)apns_requests.append(@@ -197,8 +206,8 @@ def send_e2ee_push_notifications(else:assert isinstance(push_request, FCMPushRequest)fcm_payload = dict(- # FCM only allows string values, so we stringify push_account_id.- push_account_id=str(push_request.payload.push_account_id),+ # FCM only allows string values, so we stringify push_key_id.+ push_key_id=str(push_request.payload.push_key_id),encrypted_data=push_request.payload.encrypted_data,)fcm_requests.append(@@ -210,26 +219,34 @@ def send_e2ee_push_notifications()fcm_remote_push_devices.append(remote_push_device)+ if realm is not None:+ log_context = f"to (realm={realm.uuid}, device=%s)"+ else:+ assert remote_realm is not None+ log_context = f"to (remote_realm={remote_realm.uuid}, device=%s)"+apple_successfully_sent_count = 0if len(apns_requests) > 0:sent_push_notification_result = send_e2ee_push_notification_apple(apns_requests,apns_remote_push_devices,+ log_context,)apple_successfully_sent_count = sent_push_notification_result.successfully_sent_count- delete_device_ids.extend(sent_push_notification_result.delete_device_ids)+ delete_token_ids_base64.extend(sent_push_notification_result.delete_token_ids_base64)android_successfully_sent_count = 0if len(fcm_requests) > 0:sent_push_notification_result = send_e2ee_push_notification_android(fcm_requests,fcm_remote_push_devices,+ log_context,)android_successfully_sent_count = sent_push_notification_result.successfully_sent_count- delete_device_ids.extend(sent_push_notification_result.delete_device_ids)+ delete_token_ids_base64.extend(sent_push_notification_result.delete_token_ids_base64)return {"apple_successfully_sent_count": apple_successfully_sent_count,"android_successfully_sent_count": android_successfully_sent_count,- "delete_device_ids": delete_device_ids,+ "delete_token_ids": delete_token_ids_base64,}