Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
push_registration: Clean up legacy token on E2EE registration.
Prakhar Pratyusheddaedacb9c3
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 505c8ac16c3..1499eb90b24 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,13 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 483**++* [`POST /mobile_push/register`](/api/register-push-device): On a+ successful E2EE push device registration, the server now+ automatically removes any legacy push device registration with+ a matching token for the user.+**Feature level 482*** [`GET /messages`](/api/get-messages), [`GETdiff --git a/version.py b/version.pyindex 4248f4759c1..f2fd13898ee 100644--- a/version.py+++ b/version.py@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide# Also available at docs/documentation/api.md.-API_FEATURE_LEVEL = 482+API_FEATURE_LEVEL = 483# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/lib/push_registration.py b/zerver/lib/push_registration.pyindex bab840af636..9576390dae6 100644--- a/zerver/lib/push_registration.py+++ b/zerver/lib/push_registration.py@@ -1,5 +1,6 @@import base64import binascii+import hashlibimport loggingfrom typing import TypedDict@@ -14,6 +15,7 @@ from zerver.lib.exceptions import (MissingRemoteRealmError,RequestExpiredError,)+from zerver.lib.push_notifications import remove_push_device_tokenfrom zerver.lib.remote_server import (PushNotificationBouncerError,PushNotificationBouncerRetryLaterError,@@ -21,6 +23,7 @@ from zerver.lib.remote_server import (send_to_push_bouncer,)from zerver.models.devices import Device+from zerver.models.push_notifications import PushDeviceTokenfrom zerver.models.users import UserProfile, get_user_profile_by_idfrom zerver.tornado.django_api import send_event_on_commit@@ -67,6 +70,49 @@ def handle_registration_to_bouncer_failure(logging.error("Push registration request for device_id=%s expired.", device_id)+def cleanup_legacy_push_device_token(user_profile: UserProfile, token_id_int: int) -> None:+ MAX_REQUEST_RETRIES = 3+ legacy_tokens = PushDeviceToken.objects.filter(user=user_profile)++ for legacy_token in legacy_tokens:+ hash_bytes = hashlib.sha256(legacy_token.token.encode()).digest()+ computed_token_id_base64 = base64.b64encode(hash_bytes[0:8]).decode()+ computed_token_id_int = b64decode_token_id_base64(computed_token_id_base64)++ if computed_token_id_int != token_id_int:+ continue++ for attempt in range(MAX_REQUEST_RETRIES):+ try:+ remove_push_device_token(user_profile, legacy_token.token, legacy_token.kind)+ return+ except (+ PushNotificationBouncerRetryLaterError,+ PushNotificationBouncerServerError,+ ) as e:+ # Network error or 5xx error response from bouncer server.+ # TODO: Retry with backoff. Implement it while working on #35853.+ if attempt == MAX_REQUEST_RETRIES - 1:+ logger.warning(+ "Failed to remove legacy push token from bouncer "+ "for user %s after retries: %s",+ user_profile.id,+ e,+ )+ return+ except PushNotificationBouncerError as e:+ # Invalid credentials or unexpected status code+ logger.error(+ "Bouncer error cleaning up legacy push token for user %s: %s",+ user_profile.id,+ e,+ )+ return+ except JsonableError:+ # Token doesn't exist i.e. already cleaned up.+ return++def handle_register_push_device_to_bouncer(queue_item: RegisterPushDeviceToBouncerQueueItem,) -> None:@@ -124,8 +170,9 @@ def handle_register_push_device_to_bouncer(return# Registration successful.+ token_id_int = b64decode_token_id_base64(token_id_base64)Device.objects.filter(id=device_id).update(- push_token_id=b64decode_token_id_base64(token_id_base64), pending_push_token_id=None+ push_token_id=token_id_int, pending_push_token_id=None)event = dict(type="device",@@ -136,6 +183,10 @@ def handle_register_push_device_to_bouncer()send_event_on_commit(user_profile.realm, event, [user_profile.id])+ # When a client successfully registers a token for E2EE notifications,+ # clear out any existing legacy registration on that account for the same token.+ cleanup_legacy_push_device_token(user_profile, token_id_int)+def check_push_key(push_key_str: str) -> bytes:error_message = _("Invalid `push_key`")diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 343deed0856..1c9d3d999ec 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -13415,9 +13415,22 @@ paths:- **Rotate push key**: Provide only the push key fields.- **Rotate token**: Provide only the token fields.- **Changes**: In Zulip 12.0 (feature level 468), the endpoint- was significantly redesigned to support rotation of `push_key` and- token provided by FCM/APNs.+ On a successful registration, the server automatically removes+ any legacy push device registration with a matching token for+ the user. For self-hosted servers, if removing the legacy+ registration from the push notification bouncer fails (e.g.,+ due to a network error), legacy notifications to that token+ will continue until all of the user's legacy registrations+ have been removed from the local server, at which point the+ server will stop sending legacy notification requests to the+ bouncer entirely.++ **Changes**: In Zulip 12.0 (feature level 483),+ the server began automatically removing legacy registrations+ with a matching token on successful E2EE registration.++ In Zulip 12.0 (feature level 468), the endpoint was significantly+ redesigned to support rotation of `push_key` and token provided by FCM/APNs.New in Zulip 11.0 (feature level 406).requestBody:diff --git a/zerver/tests/test_push_registration.py b/zerver/tests/test_push_registration.pyindex d3196c6b67b..14499deb57a 100644--- a/zerver/tests/test_push_registration.py+++ b/zerver/tests/test_push_registration.py@@ -2,6 +2,7 @@ import base64import hashlibimport uuidfrom datetime import timedelta+from unittest import mockimport orjsonimport responses@@ -16,15 +17,20 @@ from zerver.lib.devices import b64decode_token_id_base64from zerver.lib.exceptions import (InvalidBouncerPublicKeyError,InvalidEncryptedPushRegistrationError,+ JsonableError,RequestExpiredError,)from zerver.lib.push_registration import check_push_keyfrom zerver.lib.queue import queue_event_on_commit+from zerver.lib.remote_server import (+ PushNotificationBouncerError,+ PushNotificationBouncerRetryLaterError,+)from 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 Device, UserProfile-from zilencer.models import RemotePushDevice, RemoteRealm+from zerver.models import Device, PushDeviceToken, UserProfile+from zilencer.models import RemotePushDevice, RemotePushDeviceToken, RemoteRealmclass RegisterPushDeviceToBouncer(BouncerTestCase):@@ -962,3 +968,117 @@ class RegisterPushDeviceToServer(BouncerTestCase):pending_push_token_id=None,),)++ @activate_push_notification_service()+ @override_settings(ZILENCER_ENABLED=False)+ @responses.activate+ def test_legacy_token_cleanup_on_e2ee_registration(self) -> None:+ self.add_mock_response()+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ token = "c0ffee"++ # Create a legacy token with a different value+ # to verify it is NOT removed.+ PushDeviceToken.objects.create(+ user=hamlet,+ token="different_token",+ kind=PushDeviceToken.APNS,+ ios_app_id="example.app",+ )++ # Create legacy PushDeviceToken and RemotePushDeviceToken+ # with the same token used for E2EE registration.+ PushDeviceToken.objects.create(+ user=hamlet,+ token=token,+ kind=PushDeviceToken.APNS,+ ios_app_id="example.app",+ )+ RemotePushDeviceToken.objects.create(+ server=self.server,+ user_uuid=str(hamlet.uuid),+ token=token,+ kind=RemotePushDeviceToken.APNS,+ ios_app_id="example.app",+ )++ self.assertEqual(PushDeviceToken.objects.count(), 2)+ self.assertEqual(RemotePushDeviceToken.objects.count(), 1)++ payload = self.get_register_push_device_payload(token=token)+ with self.capture_send_event_calls(expected_num_events=2):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_success(result)++ # The matching legacy tokens should be removed+ # on both server and bouncer.+ remaining_tokens = PushDeviceToken.objects.filter(user=hamlet)+ self.assert_length(remaining_tokens, 1)+ self.assertEqual(remaining_tokens[0].token, "different_token")++ self.assertEqual(RemotePushDeviceToken.objects.count(), 0)++ @activate_push_notification_service()+ @override_settings(ZILENCER_ENABLED=False)+ @responses.activate+ def test_legacy_token_cleanup_error_handling(self) -> None:+ self.add_mock_response()+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ token = "c0ffee"++ def do_e2ee_registration_with_legacy_token(+ error: Exception,+ ) -> None:+ # Reset+ PushDeviceToken.objects.all().delete()++ PushDeviceToken.objects.create(+ user=hamlet,+ token=token,+ kind=PushDeviceToken.APNS,+ ios_app_id="example.app",+ )+ payload = self.get_register_push_device_payload(token=token)+ with (+ mock.patch(+ "zerver.lib.push_notifications.send_to_push_bouncer",+ side_effect=error,+ ),+ self.capture_send_event_calls(expected_num_events=2),+ ):+ result = self.client_post("/json/mobile_push/register", payload)+ self.assert_json_success(result)++ # "Token does not exist" on bouncer, verify it gets deleted on server.+ do_e2ee_registration_with_legacy_token(+ error=JsonableError("Token does not exist"),+ )+ self.assertEqual(PushDeviceToken.objects.count(), 0)++ # PushNotificationBouncerRetryLaterError: retries then logs warning.+ with self.assertLogs("zerver.lib.push_registration", level="WARNING") as logs:+ do_e2ee_registration_with_legacy_token(+ error=PushNotificationBouncerRetryLaterError("5xx or Network error"),+ )+ self.assertEqual(+ "WARNING:zerver.lib.push_registration:"+ f"Failed to remove legacy push token from bouncer for user {hamlet.id} after retries: 5xx or Network error",+ logs.output[0],+ )+ self.assertEqual(PushDeviceToken.objects.count(), 0)++ # PushNotificationBouncerError: logged to notify server admin.+ with self.assertLogs("zerver.lib.push_registration", level="ERROR") as logs:+ do_e2ee_registration_with_legacy_token(+ error=PushNotificationBouncerError("unexpected status code"),+ )+ self.assertEqual(+ "ERROR:zerver.lib.push_registration:"+ f"Bouncer error cleaning up legacy push token for user {hamlet.id}: unexpected status code",+ logs.output[0],+ )+ self.assertEqual(PushDeviceToken.objects.count(), 0)