Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
push_notifications: Skip legacy notifications when E2EE is required.
Prakhar Pratyush7013f22bbdc1
diff --git a/api_docs/unmerged.d/ZF-cd878d.md b/api_docs/unmerged.d/ZF-cd878d.mdnew file mode 100644index 00000000000..8837ba5f50a--- /dev/null+++ b/api_docs/unmerged.d/ZF-cd878d.md@@ -0,0 +1,4 @@+* [`POST /register`](/api/register-queue), [`GET /events`](/api/get-events):+ The `require_e2ee_push_notifications` realm setting, when enabled,+ now completely disables legacy push notifications rather than sending+ them with redacted content.diff --git a/docs/production/mobile-push-notifications.md b/docs/production/mobile-push-notifications.mdindex dde89dc40fc..ecad4f4ef49 100644--- a/docs/production/mobile-push-notifications.md+++ b/docs/production/mobile-push-notifications.md@@ -534,12 +534,12 @@ service, even in error cases.- A timestamp.- The message's content.- Zulip 11.0+ has an organization-level setting available to disable- message content being sent via the push notification bouncer (i.e.,- message content will be replaced with `New message`), for clients- that don't support the new end-to-end encrypted notifications- protocol. (Prior to Zulip 11.0, this functionality was available via the- `PUSH_NOTIFICATION_REDACT_CONTENT` server-level setting).+ Organization administrators can [require end-to-end encryption for+ push notifications][require-e2ee]. When this setting is enabled,+ legacy push notifications are not sent; only clients that support+ E2EE push notifications will receive push notifications.++ [require-e2ee]: https://zulip.com/help/mobile-notifications#require-end-to-end-encryption-for-mobile-push-notifications- All of the network requests (both from Zulip servers to the PushNotification Service and from the Push Notification Service to thediff --git a/starlight_help/src/content/docs/mobile-notifications.mdx b/starlight_help/src/content/docs/mobile-notifications.mdxindex 304ceb10fdf..ea50efccdd3 100644--- a/starlight_help/src/content/docs/mobile-notifications.mdx+++ b/starlight_help/src/content/docs/mobile-notifications.mdx@@ -31,17 +31,19 @@ topics](/help/follow-a-topic#configure-notifications-for-followed-topics).## End-to-end encryption (E2EE) for mobile push notificationsZulip Server 12.0+ and Zulip Cloud support end-to-end encrypted (E2EE) mobile-push notifications. E2EE ensures that message **content** and **metadata**+push notifications. All push notifications sent from an up-to-date version of+the server to an updated version of the app (30.0.271+ on Android, 30.0.272+ on iOS)+will be end-to-end encrypted. E2EE ensures that message **content** and **metadata**(including the sender's and recipient's names, or channel and topic where themessage was sent) are not visible to Apple, Google, or Zulip's[Mobile Push NotificationService](https://zulip.readthedocs.io/en/stable/production/mobile-push-notifications.html).Organization administrators can require end-to-end encryption for-message content in mobile push notifications. When this setting is-enabled, message content will be omitted when sending notifications to-an app that doesn't support end-to-end encryption. Users will see “New-message” in place of message text.+mobile push notifications. When this setting is enabled, push+notifications will only be sent to updated version of the apps that+support end-to-end encryption. Older apps that don't support E2EE+will not receive any push notifications.See [technicaldocumentation](https://zulip.readthedocs.io/en/stable/production/mobile-push-notifications.html#security-and-privacy)@@ -55,7 +57,7 @@ for encryption protocol details.<NavigationSteps target="settings/organization-settings" />1. Under **Notifications security**, toggle- **Require end-to-end encryption for push notification content**.+ **Require end-to-end encryption for push notifications**.</FlattenedSteps>## Mobile notifications while onlinediff --git a/web/src/admin.ts b/web/src/admin.tsindex 65a1e775316..07703032c4b 100644--- a/web/src/admin.ts+++ b/web/src/admin.ts@@ -48,7 +48,7 @@ const admin_settings_label = {realm_inline_url_embed_preview: $t({defaultMessage: "Show previews of linked websites"}),realm_send_welcome_emails: $t({defaultMessage: "Send emails introducing Zulip to new users"}),realm_require_e2ee_push_notifications: $t({- defaultMessage: "Require end-to-end encryption for push notification content",+ defaultMessage: "Require end-to-end encryption for push notifications",}),realm_message_content_allowed_in_email_notifications: $t({defaultMessage: "Allow message content in message notification emails",diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.pyindex 6e1b96e409e..51d39c93c82 100644--- a/zerver/lib/push_notifications.py+++ b/zerver/lib/push_notifications.py@@ -1363,18 +1363,6 @@ def send_push_notifications_legacy(android_devices: list[PushDeviceToken],) -> None:assert len(android_devices) + len(apple_devices) != 0- # While sending push notifications for new messages to older clients- # (which don't support E2EE), if `require_e2ee_push_notifications`- # realm setting is set to `true`, we redact the content.- if user_profile.realm.require_e2ee_push_notifications:- # Make deep copies so redaction doesn't affect the original dicts- placeholder_content = _("New message")- if gcm_payload and gcm_payload.get("event") != "remove":- gcm_payload = copy.deepcopy(gcm_payload)- gcm_payload["content"] = placeholder_content- if apns_payload and apns_payload["custom"]["zulip"].get("event") != "remove":- apns_payload = copy.deepcopy(apns_payload)- apns_payload["alert"]["body"] = placeholder_contentif uses_notification_bouncer():send_notifications_to_bouncer(@@ -1659,28 +1647,29 @@ def prepare_payload_and_send_push_notifications(],get_payload_to_encrypt: Callable[[], dict[str, Any]],) -> None:- # Send legacy/non-E2EE push notifications.- push_device_tokens = PushDeviceToken.objects.filter(user=user_profile).order_by("id")- if push_device_tokens:- apple_devices, android_devices = [], []-- for push_device_token in push_device_tokens:- if push_device_token.kind == PushDeviceToken.APNS:- apple_devices.append(push_device_token)- else:- android_devices.append(push_device_token)+ if not user_profile.realm.require_e2ee_push_notifications:+ # Send legacy/non-E2EE push notifications.+ push_device_tokens = PushDeviceToken.objects.filter(user=user_profile).order_by("id")+ if push_device_tokens:+ apple_devices, android_devices = [], []++ for push_device_token in push_device_tokens:+ if push_device_token.kind == PushDeviceToken.APNS:+ apple_devices.append(push_device_token)+ else:+ android_devices.append(push_device_token)- apns_payload, gcm_payload, gcm_options = get_payload_legacy(- bool(apple_devices), bool(android_devices)- )- send_push_notifications_legacy(- user_profile, apns_payload, gcm_payload, gcm_options, apple_devices, android_devices- )- else:- logger.info(- "Skipping legacy push notifications for user %s because there are no registered devices",- user_profile.id,- )+ apns_payload, gcm_payload, gcm_options = get_payload_legacy(+ bool(apple_devices), bool(android_devices)+ )+ send_push_notifications_legacy(+ user_profile, apns_payload, gcm_payload, gcm_options, apple_devices, android_devices+ )+ else:+ logger.info(+ "Skipping legacy push notifications for user %s because there are no registered devices",+ user_profile.id,+ )# Send E2EE push notifications.# Uses 'zerver_device_user_push_token_id_idx' index.diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex c66e052edf3..a0f5b8b6cdd 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -5910,26 +5910,22 @@ paths:type: booleandescription: |Whether this realm is configured to disallow sending mobile- push notifications with message content through the legacy- mobile push notifications APIs. The new API uses end-to-end- encryption to protect message content and metadata from- being accessible to the push bouncer service, APNs, and- FCM. Clients that support the new E2EE API will use it+ push notifications through the legacy mobile push+ notifications APIs. The new API uses end-to-end encryption+ to protect message content and metadata from being+ accessible to the push bouncer service, APNs, and FCM.+ Clients that support the new E2EE API will use itautomatically regardless of this setting.- If `true`, mobile push notifications sent to clients that- lack support for E2EE push notifications will always have- "New message" as their content. Note that these legacy- mobile notifications will still contain metadata, which may- include the message's ID, the sender's name, email address,- and avatar.+ If `true`, legacy mobile push notifications will not be+ sent. Only updated version of clients (which support E2EE+ push notifications) will receive push notifications.- In a future release, once the official mobile apps have- implemented fully validated their E2EE protocol support,- this setting will become strict, and disable the legacy- protocol entirely.+ **Changes**: In Zulip 12.0 (feature level ZF-cd878d), this+ setting now completely disables legacy push notifications+ rather than sending them with redacted content.- **Changes**: New in Zulip 11.0 (feature level 409). Previously,+ New in Zulip 11.0 (feature level 409). Previously,this behavior was available only via the`PUSH_NOTIFICATION_REDACT_CONTENT` global server setting.require_unique_names:@@ -20624,26 +20620,22 @@ paths:Present if `realm` is present in `fetch_event_types`.Whether this realm is configured to disallow sending mobile- push notifications with message content through the legacy- mobile push notifications APIs. The new API uses end-to-end- encryption to protect message content and metadata from- being accessible to the push bouncer service, APNs, and- FCM. Clients that support the new E2EE API will use it+ push notifications through the legacy mobile push+ notifications APIs. The new API uses end-to-end encryption+ to protect message content and metadata from being+ accessible to the push bouncer service, APNs, and FCM.+ Clients that support the new E2EE API will use itautomatically regardless of this setting.- If `true`, mobile push notifications sent to clients that- lack support for E2EE push notifications will always have- "New message" as their content. Note that these legacy- mobile notifications will still contain metadata, which may- include the message's ID, the sender's name, email address,- and avatar.+ If `true`, legacy mobile push notifications will not be+ sent. Only updated version of clients (which support E2EE+ push notifications) will receive push notifications.- In a future release, once the official mobile apps have- implemented fully validated their E2EE protocol support,- this setting will become strict, and disable the legacy- protocol entirely.+ **Changes**: In Zulip 12.0 (feature level ZF-cd878d), this+ setting now completely disables legacy push notifications+ rather than sending them with redacted content.- **Changes**: New in Zulip 11.0 (feature level 409). Previously,+ New in Zulip 11.0 (feature level 409). Previously,this behavior was available only via the`PUSH_NOTIFICATION_REDACT_CONTENT` global server setting.realm_require_unique_names:diff --git a/zerver/tests/test_e2ee_push_notifications.py b/zerver/tests/test_e2ee_push_notifications.pyindex d0fad5afd93..b57fe194c12 100644--- a/zerver/tests/test_e2ee_push_notifications.py+++ b/zerver/tests/test_e2ee_push_notifications.py@@ -8,10 +8,10 @@ from django.test import override_settingsfrom django.utils.timezone import nowfrom firebase_admin.exceptions import InternalErrorfrom firebase_admin.messaging import UnregisteredError-from typing_extensions import overridefrom analytics.models import RealmCountfrom corporate.lib.stripe import BillingUserCounts+from zerver.actions.realm_settings import do_set_realm_propertyfrom zerver.actions.user_groups import check_add_user_groupfrom zerver.lib.avatar import absolute_avatar_urlfrom zerver.lib.devices import b64encode_token_id_int@@ -653,6 +653,12 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):hamlet = self.example_user("hamlet")aaron = self.example_user("aaron")+ # With require_e2ee_push_notifications disabled,+ # both legacy and E2EE notifications are sent.+ do_set_realm_property(+ hamlet.realm, "require_e2ee_push_notifications", False, acting_user=None+ )+registered_device_apple, registered_device_android = (self.register_push_devices_for_notification())@@ -736,6 +742,76 @@ class SendPushNotificationTest(E2EEPushNotificationTestCase):)self.assertEqual(realm_count_dict, dict(subgroup=None, value=4))+ # Now test with require_e2ee_push_notifications=True.+ # Legacy notifications should be skipped entirely, and only+ # E2EE notifications should be sent.+ do_set_realm_property(+ hamlet.realm, "require_e2ee_push_notifications", True, acting_user=None+ )++ message_id_2 = self.send_personal_message(+ from_user=aaron, to_user=hamlet, skip_capture_on_commit_callbacks=True+ )+ missed_message_2 = {+ "message_id": message_id_2,+ "trigger": NotificationTriggers.DIRECT_MESSAGE,+ }++ with (+ self.mock_fcm(for_legacy=True) as mock_fcm_messaging_legacy,+ self.mock_apns(for_legacy=True) as send_notification_legacy,+ self.mock_fcm() as mock_fcm_messaging,+ self.mock_apns() as send_notification,+ mock.patch(+ "zerver.lib.push_notifications.uses_notification_bouncer", return_value=False+ ),+ self.assertLogs("zerver.lib.push_notifications", level="INFO") as zerver_logger,+ self.assertLogs("zilencer.lib.push_notifications", level="INFO") as zilencer_logger,+ mock.patch("time.perf_counter", side_effect=[10.0, 12.0]),+ ):+ mock_fcm_messaging.send_each.return_value = self.make_fcm_success_response()+ send_notification.return_value.is_successful = True++ handle_push_notification(hamlet.id, missed_message_2)++ # Legacy paths should not be called at all.+ mock_fcm_messaging_legacy.send_each.assert_not_called()+ send_notification_legacy.assert_not_called()+ # E2EE paths should be called.+ mock_fcm_messaging.send_each.assert_called_once()+ send_notification.assert_called_once()++ self.assertEqual(+ "INFO:zerver.lib.push_notifications:"+ f"Sending push notifications to mobile clients for user {hamlet.id}",+ zerver_logger.output[0],+ )+ # No legacy logs; E2EE logs directly follow.+ self.assertEqual(+ "INFO:zerver.lib.push_notifications:"+ f"APNs: Success sending to (realm={hamlet.realm.uuid}, device={registered_device_apple.token})",+ zerver_logger.output[1],+ )+ self.assertEqual(+ "INFO:zilencer.lib.push_notifications:"+ f"FCM: Sent message with ID: 0 to (realm={hamlet.realm.uuid}, device={registered_device_android.token})",+ zilencer_logger.output[0],+ )+ self.assertEqual(+ "INFO:zerver.lib.push_notifications:"+ f"Sent E2EE mobile push notifications for user {hamlet.id}: 1 via FCM, 1 via APNs in 2.000s",+ zerver_logger.output[2],+ )++ # 2 new E2EE notifications sent, on top of the previous 4.+ realm_count_dict = (+ RealmCount.objects.filter(property="mobile_pushes_sent::day")+ .values("subgroup", "value")+ .order_by("-id")+ .first()+ )+ self.assertEqual(realm_count_dict, dict(subgroup=None, value=6))+def test_payload_data_to_encrypt_channel_message(self) -> None:hamlet = self.example_user("hamlet")aaron = self.example_user("aaron")@@ -964,123 +1040,6 @@ class RemovePushNotificationTest(E2EEPushNotificationTestCase):self.assertEqual(m.call_args.args[1], expected_payload_data_to_encrypt)-class RequireE2EEPushNotificationsSettingTest(E2EEPushNotificationTestCase):- @override- def setUp(self) -> None:- super().setUp()-- self.hamlet = self.example_user("hamlet")- self.aaron = self.example_user("aaron")-- realm = self.hamlet.realm- realm.require_e2ee_push_notifications = True- realm.save(update_fields=["require_e2ee_push_notifications"])-- def get_example_missed_message(self, content: str = "test content") -> dict[str, int | str]:- message_id = self.send_personal_message(- from_user=self.aaron,- to_user=self.hamlet,- content=content,- skip_capture_on_commit_callbacks=True,- )- missed_message: dict[str, int | str] = {- "message_id": message_id,- "trigger": NotificationTriggers.DIRECT_MESSAGE,- }- return missed_message-- def test_content_redacted(self) -> None:- self.register_old_push_devices_for_notification()- self.register_push_devices_for_notification()-- missed_message = self.get_example_missed_message(content="not-redacted")-- # Verify that the content is redacted in payloads supplied to- # 'send_notifications_to_bouncer' - payloads supplied to bouncer (legacy codepath).- #- # Verify that the content is not redacted in payloads supplied to- # 'send_push_notifications' - payloads which get encrypted.- with (- activate_push_notification_service(),- mock.patch(- "zerver.lib.push_notifications.send_notifications_to_bouncer"- ) as mock_legacy,- mock.patch("zerver.lib.push_notifications.send_push_notifications") as mock_e2ee,- ):- handle_push_notification(self.hamlet.id, missed_message)-- mock_legacy.assert_called_once()- self.assertEqual(mock_legacy.call_args.args[1]["alert"]["body"], "New message")- self.assertEqual(mock_legacy.call_args.args[2]["content"], "New message")-- mock_e2ee.assert_called_once()- self.assertEqual(mock_e2ee.call_args.args[1]["content"], "not-redacted")-- missed_message = self.get_example_missed_message()-- # Verify that the content is redacted in payloads supplied to- # to functions for sending it through APNs and FCM directly.- with (- mock.patch("zerver.lib.push_notifications.has_apns_credentials", return_value=True),- mock.patch("zerver.lib.push_notifications.has_fcm_credentials", return_value=True),- mock.patch(- "zerver.lib.push_notifications.send_notifications_to_bouncer"- ) as send_bouncer,- mock.patch(- "zerver.lib.push_notifications.send_apple_push_notification", return_value=0- ) as send_apple,- mock.patch(- "zerver.lib.push_notifications.send_android_push_notification", return_value=0- ) as send_android,- # We have already asserted the payloads passed to E2EE codepath above.- mock.patch("zerver.lib.push_notifications.send_push_notifications"),- ):- handle_push_notification(self.hamlet.id, missed_message)-- send_bouncer.assert_not_called()- send_apple.assert_called_once()- send_android.assert_called_once()-- self.assertEqual(send_apple.call_args.args[2]["alert"]["body"], "New message")- self.assertEqual(send_android.call_args.args[2]["content"], "New message")-- def test_content_redacted_only_android_registered(self) -> None:- registered_device_apple, _ = self.register_old_push_devices_for_notification()- registered_device_apple.delete()-- missed_message = self.get_example_missed_message()-- with (- activate_push_notification_service(),- mock.patch(- "zerver.lib.push_notifications.send_notifications_to_bouncer"- ) as mock_legacy,- ):- handle_push_notification(self.hamlet.id, missed_message)-- mock_legacy.assert_called_once()- self.assertEqual(mock_legacy.call_args.args[1], {})- self.assertEqual(mock_legacy.call_args.args[2]["content"], "New message")-- def test_content_redacted_only_apple_registered(self) -> None:- _, registered_device_android = self.register_old_push_devices_for_notification()- registered_device_android.delete()-- missed_message = self.get_example_missed_message()-- with (- activate_push_notification_service(),- mock.patch(- "zerver.lib.push_notifications.send_notifications_to_bouncer"- ) as mock_legacy,- ):- handle_push_notification(self.hamlet.id, missed_message)-- mock_legacy.assert_called_once()- self.assertEqual(mock_legacy.call_args.args[1]["alert"]["body"], "New message")- self.assertEqual(mock_legacy.call_args.args[2], {})--class SendTestPushNotificationTest(E2EEPushNotificationTestCase):def test_success_cloud(self) -> None:hamlet = self.example_user("hamlet")