Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

push_notification: Use symmetric cryptography to encrypt notifications.

Prakhar Pratyush7ebdca52e845
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index 421e2c93145..adf2b8cdf9a 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,11 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 432**
+
+* [`POST /mobile_push/register`](/api/register-push-device): Replaced
+ `push_public_key` parameter with `push_key`.
+
**Feature level 431**
* [`POST /register`](/api/register-queue), [`PATCH /settings`](/api/update-settings),
diff --git a/version.py b/version.py
index 24a5c778cc4..81ac36dee7d 100644
--- a/version.py
+++ b/version.py
@@ -35,7 +35,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# new level means in api_docs/changelog.md, as well as "**Changes**"
# entries in the endpoint's documentation in `zulip.yaml`.
-API_FEATURE_LEVEL = 431
+API_FEATURE_LEVEL = 432
# 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. Bump
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py
index ca05ce5e688..4fefc7066dd 100644
--- a/zerver/lib/push_notifications.py
+++ b/zerver/lib/push_notifications.py
@@ -28,7 +28,7 @@ from firebase_admin import initialize_app as firebase_initialize_app
from firebase_admin import messaging as firebase_messaging
from firebase_admin.messaging import UnregisteredError as FCMUnregisteredError
from nacl.encoding import Base64Encoder
-from nacl.public import PublicKey, SealedBox
+from nacl.secret import SecretBox
from pydantic import TypeAdapter
from typing_extensions import TypedDict, override
@@ -1481,10 +1481,30 @@ class APNsPushRequest:
payload: APNsPayload
-def get_encrypted_data(payload_data_to_encrypt: dict[str, Any], public_key_str: str) -> str:
- public_key = PublicKey(public_key_str.encode("utf-8"), Base64Encoder)
- sealed_box = SealedBox(public_key)
- encrypted_data_bytes = sealed_box.encrypt(orjson.dumps(payload_data_to_encrypt), Base64Encoder)
+@dataclass
+class PushKey:
+ algorithm_type_byte: bytes
+ secret_bytes: bytes
+
+
+def parse_push_key(push_key_bytes: bytes) -> PushKey:
+ push_key = PushKey(
+ algorithm_type_byte=push_key_bytes[:1],
+ secret_bytes=push_key_bytes[1:],
+ )
+ return push_key
+
+
+def get_encrypted_data(payload_data_to_encrypt: dict[str, Any], push_key_bytes: bytes) -> str:
+ push_key = parse_push_key(push_key_bytes)
+ # The `algorithm_type_byte` will play a role in future
+ # when we'll potentially revise the cryptosystem we use.
+ assert push_key.algorithm_type_byte == bytes([0x31])
+
+ secret_box = SecretBox(push_key.secret_bytes)
+ encrypted_data_bytes = secret_box.encrypt(
+ orjson.dumps(payload_data_to_encrypt), encoder=Base64Encoder
+ )
encrypted_data = encrypted_data_bytes.decode("utf-8")
return encrypted_data
@@ -1509,7 +1529,7 @@ def send_push_notifications(
push_requests: list[FCMPushRequest | APNsPushRequest] = []
for push_device in push_devices:
assert push_device.bouncer_device_id is not None # for mypy
- encrypted_data = get_encrypted_data(payload_data_to_encrypt, push_device.push_public_key)
+ encrypted_data = get_encrypted_data(payload_data_to_encrypt, bytes(push_device.push_key))
if push_device.token_kind == PushDevice.TokenKind.APNS:
apns_http_headers = APNsHTTPHeaders(
apns_priority=apns_priority,
diff --git a/zerver/lib/push_registration.py b/zerver/lib/push_registration.py
index 6f536b88ffe..bb077868507 100644
--- a/zerver/lib/push_registration.py
+++ b/zerver/lib/push_registration.py
@@ -1,7 +1,10 @@
+import base64
+import binascii
import logging
from typing import TypedDict
from django.conf import settings
+from django.utils.translation import gettext as _
from zerver.lib.exceptions import (
InvalidBouncerPublicKeyError,
@@ -138,3 +141,17 @@ def handle_register_push_device_to_bouncer(
status="active",
)
send_event_on_commit(user_profile.realm, event, [user_profile.id])
+
+
+def check_push_key(push_key_str: str) -> bytes:
+ error_message = _("Invalid `push_key`")
+
+ try:
+ push_key_bytes = base64.b64decode(push_key_str, validate=True)
+ except binascii.Error:
+ raise JsonableError(error_message)
+
+ if len(push_key_bytes) != 33 or push_key_bytes[0] != 0x31:
+ raise JsonableError(error_message)
+
+ return push_key_bytes
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index 50312f27c30..cc9399cbf3a 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -1927,7 +1927,7 @@ Output:
push_account_id=10,
bouncer_device_id=1,
token_kind=PushDevice.TokenKind.FCM,
- push_public_key="n4WTVqj8KH6u0vScRycR4TqRaHhFeJ0POvMb8LCu8iI=",
+ push_key=base64.b64decode("MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt"),
)
def register_push_device_token(self, user_profile_id: int) -> None:
@@ -2912,14 +2912,14 @@ class E2EEPushNotificationTestCase(BouncerTestCase):
push_account_id=10,
bouncer_device_id=1,
token_kind=PushDevice.TokenKind.APNS,
- push_public_key="9VvW7k59AET0v3+VFCkKTrNm5DJQ7JTKdvUjZInZZ0Y=",
+ push_key=base64.b64decode("MXPC4WK2YfyfCBdK6ElnzSpKJtcpFSZrYiJto4YCETzx"),
)
PushDevice.objects.create(
user=hamlet,
push_account_id=20,
bouncer_device_id=2,
token_kind=PushDevice.TokenKind.FCM,
- push_public_key="n4WTVqj8KH6u0vScRycR4TqRaHhFeJ0POvMb8LCu8iI=",
+ push_key=base64.b64decode("Mc3u6xraEI79aGk6Nd+boqi/ODfT+JcsEIATzG7C/m+V"),
)
realm_and_remote_realm_fields: dict[str, Realm | RemoteRealm | None] = {
diff --git a/zerver/migrations/0758_remove_pushdevice_push_public_key_and_more.py b/zerver/migrations/0758_remove_pushdevice_push_public_key_and_more.py
new file mode 100644
index 00000000000..c6bb2d4d4c1
--- /dev/null
+++ b/zerver/migrations/0758_remove_pushdevice_push_public_key_and_more.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.6 on 2025-10-15 14:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("zerver", "0757_realmuserdefault_web_inbox_show_channel_folders_and_more"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="pushdevice",
+ name="push_public_key",
+ ),
+ migrations.AddField(
+ model_name="pushdevice",
+ name="push_key",
+ field=models.BinaryField(default=None),
+ preserve_default=False,
+ ),
+ ]
diff --git a/zerver/models/push_notifications.py b/zerver/models/push_notifications.py
index 61f5beea790..cac17ea675e 100644
--- a/zerver/models/push_notifications.py
+++ b/zerver/models/push_notifications.py
@@ -93,7 +93,11 @@ class PushDevice(AbstractPushDevice):
user = models.ForeignKey(UserProfile, on_delete=CASCADE)
# Key to use to encrypt notifications for delivery to this device.
- push_public_key = models.TextField()
+ # 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.
diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.py
index 5c486b99f72..0cc26a9a821 100644
--- a/zerver/openapi/python_examples.py
+++ b/zerver/openapi/python_examples.py
@@ -1698,7 +1698,7 @@ def register_push_device(client: Client) -> None:
request = {
"token_kind": "fcm",
"push_account_id": 2408,
- "push_public_key": "push-public-key",
+ "push_key": "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt",
"bouncer_public_key": "bouncer-public-key",
"encrypted_push_registration": "encrypted-push-registration-data",
}
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index f5d2b3ef4c6..cfd2084b7a2 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -12764,15 +12764,28 @@ paths:
Must be unique in the client's table of accounts.
type: integer
example: 2408
- push_public_key:
- description: |
- Public part of the asymmetric key pair generated by the client
- using NaCl (the Networking and Cryptography Library), encoded
- using a RFC 4648 standard base64 encoder.
-
- It is used to encrypt notifications for delivery to the client.
+ push_key:
+ description: |
+ Key that the client would like the server to use to encrypt notifications. It
+ consists of a single byte encoding which cryptosystem to use, followed by the
+ byte sequence representing the key to use for that cryptosystem. This byte
+ sequence is encoded using standard Base64 encoding as defined in RFC
+ 4648. Supported cryptosystems are:
+
+ - `0x31`: LibSodium's [SecretBox][libsodium-secretbox] symmetric key encryption
+ system. Keys are 32 bytes, generated by the client using libsodium's
+ `crypto_secretbox_easy`. See the [NaCl documentation][nacl-secretbox], which
+ details how this system uses `XSalsa20` and `Poly1305` to provide authenticated
+ encryption.
+
+ [libsodium-secretbox]: https://libsodium.gitbook.io/doc/secret-key_cryptography/secretbox
+ [nacl-secretbox]: https://nacl.cr.yp.to/secretbox.html
+
+ **Changes**: New in Zulip 12.0 (feature level 432). This replaced the
+ `push_public_key` parameter which had a prototype asymmetric cryptosystem, and
+ did not have a natural way to support multiple cryptosystems.
type: string
- example: "push-public-key"
+ example: "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt"
bouncer_public_key:
description: |
Which of the bouncer's public keys the client used to encrypt the
@@ -12798,7 +12811,7 @@ paths:
required:
- token_kind
- push_account_id
- - push_public_key
+ - push_key
- bouncer_public_key
- encrypted_push_registration
responses:
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index ab4ea075944..9126df95c80 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -4,6 +4,7 @@
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to validate our documentation.
+import base64
import copy
import time
from collections.abc import Callable, Iterator
@@ -4266,7 +4267,7 @@ class NormalActionsTest(BaseAction):
user=hamlet,
token_kind=PushDevice.TokenKind.FCM,
push_account_id=2408,
- push_public_key="dummy-push-public-key",
+ push_key=base64.b64decode("MbZ1JWx6YMHw1cZEgCPRQAgolV3lBRefP5qp/GNisiP+"),
)
queue_item: RegisterPushDeviceToBouncerQueueItem = {
diff --git a/zerver/tests/test_push_registration.py b/zerver/tests/test_push_registration.py
index c209c7a6d31..e87337a51d5 100644
--- a/zerver/tests/test_push_registration.py
+++ b/zerver/tests/test_push_registration.py
@@ -1,3 +1,4 @@
+import base64
import uuid
from datetime import timedelta
@@ -232,7 +233,7 @@ class RegisterPushDeviceToServer(BouncerTestCase):
payload: dict[str, str | int] = {
"token_kind": token_kind,
"push_account_id": 2408,
- "push_public_key": "push-public-key",
+ "push_key": "MY+paNlyduYJRQFNZva8w7Gv3PkBua9kIj581F9Vr301",
"bouncer_public_key": public_key_str,
"encrypted_push_registration": encrypted_push_registration,
}
@@ -309,6 +310,34 @@ 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_push_key_error(self) -> None:
+ self.login("hamlet")
+ payload = self.get_register_push_device_payload()
+
+ # Invalid Base64 alphabet in `push_key`
+ invalid_push_key_payload = {**payload, "push_key": "@abcdefg"}
+ result = self.client_post("/json/mobile_push/register", invalid_push_key_payload)
+ self.assert_json_error(result, "Invalid `push_key`")
+
+ # Value (which is base64 encoded to get `push_key`) is not 33 bytes in size
+ invalid_push_key_payload = {**payload, "push_key": "abcd"}
+ result = self.client_post("/json/mobile_push/register", invalid_push_key_payload)
+ self.assert_json_error(result, "Invalid `push_key`")
+
+ # Verify error when prefix (1st byte) is not 0x31
+ push_key = payload["push_key"]
+ assert type(push_key) is str # for mypy
+ valid_push_key_bytes = base64.b64decode(push_key)
+ self.assertEqual(valid_push_key_bytes[0], 0x31)
+ self.assert_length(valid_push_key_bytes, 33)
+ # Note: Prefix changed to 0x32
+ invalid_push_key_bytes = bytes([0x32]) + valid_push_key_bytes[1:]
+ invalid_push_key = base64.b64encode(invalid_push_key_bytes).decode("utf-8")
+ invalid_push_key_payload = {**payload, "push_key": invalid_push_key}
+ result = self.client_post("/json/mobile_push/register", invalid_push_key_payload)
+ self.assert_json_error(result, "Invalid `push_key`")
+
@activate_push_notification_service()
@override_settings(ZILENCER_ENABLED=False)
@responses.activate
diff --git a/zerver/views/push_notifications.py b/zerver/views/push_notifications.py
index 532bc5d2956..350e11ea1cd 100644
--- a/zerver/views/push_notifications.py
+++ b/zerver/views/push_notifications.py
@@ -29,7 +29,7 @@ from zerver.lib.push_notifications import (
uses_notification_bouncer,
validate_token,
)
-from zerver.lib.push_registration import RegisterPushDeviceToBouncerQueueItem
+from zerver.lib.push_registration import RegisterPushDeviceToBouncerQueueItem, check_push_key
from zerver.lib.queue import queue_event_on_commit
from zerver.lib.remote_server import (
SELF_HOSTING_REGISTRATION_TAKEOVER_CHALLENGE_TOKEN_REDIS_KEY,
@@ -297,9 +297,11 @@ def register_push_device(
*,
token_kind: Annotated[str, check_string_in_validator(PushDevice.TokenKind.values)],
push_account_id: Json[int],
- # Key that the client is requesting be used for
- # encrypting push notifications for delivery to it.
- push_public_key: str,
+ # Key that the client is requesting be used for encrypting
+ # push notifications for delivery to it.
+ # Consists of a 1-byte prefix identifying the symmetric
+ # cryptosystem in use, followed by the secret key.
+ push_key: str,
# Key that the client claims was used to encrypt
# `encrypted_push_registration`.
bouncer_public_key: str,
@@ -309,6 +311,8 @@ def register_push_device(
if not (settings.ZILENCER_ENABLED or uses_notification_bouncer()):
raise PushServiceNotConfiguredError
+ push_key_bytes = check_push_key(push_key)
+
# Idempotency
already_registered = PushDevice.objects.filter(
user=user_profile, push_account_id=push_account_id, error_code__isnull=True
@@ -319,7 +323,7 @@ def register_push_device(
PushDevice.objects.update_or_create(
user=user_profile,
push_account_id=push_account_id,
- defaults={"token_kind": token_kind, "push_public_key": push_public_key, "error_code": None},
+ defaults={"token_kind": token_kind, "push_key": push_key_bytes, "error_code": None},
)
# We use a queue worker to make the request to the bouncer