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_registration: Rework using `Device` model.

Prakhar Pratyush4a6d26e9119e
diff --git a/api_docs/unmerged.d/ZF-42fbcd.md b/api_docs/unmerged.d/ZF-42fbcd.md
index 8fc1992fe82..97c29b1eb22 100644
--- a/api_docs/unmerged.d/ZF-42fbcd.md
+++ b/api_docs/unmerged.d/ZF-42fbcd.md
@@ -4,3 +4,8 @@
field to response.
* [`GET /events`](/api/get-events): A `device` event is sent
to clients to live-update the `devices` dictionary.
+* [`POST /mobile_push/register`](register-push-device): Redesigned
+ the endpoint to support rotation of `push_key` and FCM/APNs provided token.
+* [`POST /remotes/push/e2ee/register`](/api/register-remote-push-device):
+ Replaced `push_account_id` with `token_id` to support rotation
+ of `push_key` and FCM/APNs provided token.
diff --git a/zerver/actions/push_notifications.py b/zerver/actions/push_notifications.py
index 3d185b60c91..50a5128a351 100644
--- a/zerver/actions/push_notifications.py
+++ b/zerver/actions/push_notifications.py
@@ -1,20 +1,94 @@
+from django.utils.timezone import now as timezone_now
+
+from zerver.lib.timestamp import datetime_to_timestamp
from zerver.models import UserProfile
-from zerver.models.push_notifications import PushDevice
+from zerver.models.devices import Device
from zerver.tornado.django_api import send_event_on_commit
def do_register_push_device(
- user_profile: UserProfile, push_account_id: int, token_kind: str, push_key_bytes: bytes
+ user_profile: UserProfile,
+ device: Device,
+ *,
+ token_kind: str,
+ push_key_bytes: bytes,
+ push_key_id: int,
+ token_id_int: int,
+ token_id_base64: str,
+) -> None:
+ registered_at = timezone_now()
+ device.push_key = push_key_bytes
+ device.push_key_id = push_key_id
+ device.pending_push_token_id = token_id_int
+ device.push_token_kind = token_kind
+ device.push_token_last_updated_timestamp = registered_at
+ device.push_registration_error_code = None
+ device.save(
+ update_fields=[
+ "push_key",
+ "push_key_id",
+ "pending_push_token_id",
+ "push_token_kind",
+ "push_token_last_updated_timestamp",
+ "push_registration_error_code",
+ ]
+ )
+
+ event = dict(
+ type="device",
+ op="update",
+ device_id=device.id,
+ push_key_id=device.push_key_id,
+ pending_push_token_id=token_id_base64,
+ push_token_last_updated_timestamp=datetime_to_timestamp(registered_at),
+ push_registration_error_code=None,
+ )
+ send_event_on_commit(user_profile.realm, event, [user_profile.id])
+
+
+def do_rotate_push_key(
+ user_profile: UserProfile, device: Device, push_key_bytes: bytes, push_key_id: int
) -> None:
- PushDevice.objects.update_or_create(
- user=user_profile,
- push_account_id=push_account_id,
- defaults={"token_kind": token_kind, "push_key": push_key_bytes, "error_code": None},
+ if (
+ device.push_key_id == push_key_id
+ and device.push_key is not None
+ and bytes(device.push_key) == push_key_bytes
+ ):
+ return
+
+ device.push_key = push_key_bytes
+ device.push_key_id = push_key_id
+ device.save(update_fields=["push_key", "push_key_id"])
+
+ event = dict(
+ type="device",
+ op="update",
+ device_id=device.id,
+ push_key_id=device.push_key_id,
)
+ send_event_on_commit(user_profile.realm, event, [user_profile.id])
+
+def do_rotate_token(
+ user_profile: UserProfile, device: Device, token_id_int: int, token_id_base64: str
+) -> None:
+ token_updated_at = timezone_now()
+ device.pending_push_token_id = token_id_int
+ device.push_token_last_updated_timestamp = token_updated_at
+ device.push_registration_error_code = None
+ device.save(
+ update_fields=[
+ "pending_push_token_id",
+ "push_token_last_updated_timestamp",
+ "push_registration_error_code",
+ ]
+ )
event = dict(
- type="push_device",
- push_account_id=push_account_id,
- status="pending",
+ type="device",
+ op="update",
+ device_id=device.id,
+ pending_push_token_id=token_id_base64,
+ push_token_last_updated_timestamp=datetime_to_timestamp(token_updated_at),
+ push_registration_error_code=None,
)
send_event_on_commit(user_profile.realm, event, [user_profile.id])
diff --git a/zerver/lib/devices.py b/zerver/lib/devices.py
index 8c54ca8860c..13018b21186 100644
--- a/zerver/lib/devices.py
+++ b/zerver/lib/devices.py
@@ -1,7 +1,10 @@
import base64
+import binascii
+from django.utils.translation import gettext as _
from typing_extensions import TypedDict
+from zerver.lib.exceptions import JsonableError
from zerver.lib.timestamp import datetime_to_timestamp
from zerver.models.devices import Device
from zerver.models.users import UserProfile
@@ -20,6 +23,15 @@ def b64encode_token_id_int(token_id_int: int) -> str:
return base64.b64encode(token_id_bytes).decode()
+def b64decode_token_id_base64(token_id_base64: str) -> int:
+ try:
+ token_id_bytes = base64.b64decode(token_id_base64, validate=True)
+ except binascii.Error:
+ raise JsonableError(_("{var_name} is not Base64 encoded").format(var_name="`token_id`"))
+
+ return int.from_bytes(token_id_bytes, byteorder="big", signed=True)
+
+
def get_devices(user_profile: UserProfile) -> dict[str, DeviceInfoDict]:
devices = Device.objects.filter(user=user_profile)
@@ -47,3 +59,12 @@ def get_devices(user_profile: UserProfile) -> dict[str, DeviceInfoDict]:
)
return devices_dict
+
+
+def check_device_id(device_id: int, user_id: int) -> Device:
+ try:
+ device = Device.objects.get(id=device_id, user_id=user_id)
+ except Device.DoesNotExist:
+ raise JsonableError(_("Invalid `device_id`"))
+
+ return device
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index 9c25dfc3b1d..c122e65c146 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -31,6 +31,7 @@ from zerver.lib.event_types import (
EventDefaultStreams,
EventDeleteMessage,
EventDeviceAdd,
+ EventDeviceUpdate,
EventDirectMessage,
EventDraftsAdd,
EventDraftsRemove,
@@ -177,6 +178,7 @@ check_custom_profile_fields = make_checker(EventCustomProfileFields)
check_default_stream_groups = make_checker(EventDefaultStreamGroups)
check_default_streams = make_checker(EventDefaultStreams)
check_device_add = make_checker(EventDeviceAdd)
+check_device_update = make_checker(EventDeviceUpdate)
check_direct_message = make_checker(EventDirectMessage)
check_draft_add = make_checker(EventDraftsAdd)
check_draft_remove = make_checker(EventDraftsRemove)
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index b106d2093fc..988b6f162d6 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -303,6 +303,17 @@ class EventDeviceAdd(BaseEvent):
device_id: int
+class EventDeviceUpdate(BaseEvent):
+ type: Literal["device"]
+ op: Literal["update"]
+ device_id: int
+ push_key_id: int | None = None
+ push_token_id: str | None = None
+ pending_push_token_id: str | None = None
+ push_token_last_updated_timestamp: int | None = None
+ push_registration_error_code: str | None = None
+
+
class NavigationViewFields(BaseModel):
fragment: str
is_pinned: bool
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index e870e01c3a2..1a0df57b90a 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -2029,6 +2029,23 @@ def apply_event(
"push_token_last_updated_timestamp": None,
"push_registration_error_code": None,
}
+ elif event["op"] == "update":
+ if "push_key_id" in event:
+ state["devices"][str(event["device_id"])]["push_key_id"] = event["push_key_id"]
+ if "push_token_id" in event:
+ state["devices"][str(event["device_id"])]["push_token_id"] = event["push_token_id"]
+ if "pending_push_token_id" in event:
+ state["devices"][str(event["device_id"])]["pending_push_token_id"] = event[
+ "pending_push_token_id"
+ ]
+ if "push_token_last_updated_timestamp" in event:
+ state["devices"][str(event["device_id"])]["push_token_last_updated_timestamp"] = (
+ event["push_token_last_updated_timestamp"]
+ )
+ if "push_registration_error_code" in event:
+ state["devices"][str(event["device_id"])]["push_registration_error_code"] = event[
+ "push_registration_error_code"
+ ]
else:
raise AssertionError("Unexpected event type {type}/{op}".format(**event))
else:
diff --git a/zerver/lib/push_registration.py b/zerver/lib/push_registration.py
index c6f6112ff86..fd51456e907 100644
--- a/zerver/lib/push_registration.py
+++ b/zerver/lib/push_registration.py
@@ -6,6 +6,7 @@ from typing import TypedDict
from django.conf import settings
from django.utils.translation import gettext as _
+from zerver.lib.devices import b64decode_token_id_base64
from zerver.lib.exceptions import (
InvalidBouncerPublicKeyError,
InvalidEncryptedPushRegistrationError,
@@ -20,7 +21,7 @@ from zerver.lib.remote_server import (
PushNotificationBouncerServerError,
send_to_push_bouncer,
)
-from zerver.models import PushDevice
+from zerver.models.devices import Device
from zerver.models.users import UserProfile, get_user_profile_by_id
from zerver.tornado.django_api import send_event_on_commit
@@ -32,44 +33,39 @@ logger = logging.getLogger(__name__)
class RegisterPushDeviceToBouncerQueueItem(TypedDict):
user_profile_id: int
+ device_id: int
bouncer_public_key: str
encrypted_push_registration: str
- push_account_id: int
+ token_id_base64: str
def handle_registration_to_bouncer_failure(
- user_profile: UserProfile, push_account_id: int, error_code: str
+ user_profile: UserProfile, device_id: int, error_code: str
) -> None:
"""Handles a failed registration request to the bouncer by
notifying or preparing to notify clients.
- * Sends a `push_device` event to notify online clients immediately.
+ * Sends a `device` event to notify online clients immediately.
- * Stores the `error_code` in the `PushDevice` table. This is later
+ * Stores the `error_code` in the `Device` table. This is later
used, along with other metadata, to notify offline clients the
- next time they call `/register`. See the `push_devices` field in
+ next time they call `/register`. See the `devices` field in
the `/register` response.
"""
- PushDevice.objects.filter(user=user_profile, push_account_id=push_account_id).update(
- error_code=error_code
- )
+ Device.objects.filter(id=device_id).update(push_registration_error_code=error_code)
event = dict(
- type="push_device",
- push_account_id=push_account_id,
- status="failed",
- error_code=error_code,
+ type="device",
+ op="update",
+ device_id=device_id,
+ push_registration_error_code=error_code,
)
send_event_on_commit(user_profile.realm, event, [user_profile.id])
# Report the `REQUEST_EXPIRED_ERROR` to the server admins as it indicates
# a long-lasting outage somewhere between the server and the bouncer,
# most likely in either the server or its local network configuration.
- if error_code == PushDevice.ErrorCode.REQUEST_EXPIRED:
- logging.error(
- "Push device registration request for user_id=%s, push_account_id=%s expired.",
- user_profile.id,
- push_account_id,
- )
+ if error_code == Device.PushRegistrationErrorCode.REQUEST_EXPIRED:
+ logging.error("Push registration request for device_id=%s expired.", device_id)
def handle_register_push_device_to_bouncer(
@@ -77,28 +73,27 @@ def handle_register_push_device_to_bouncer(
) -> None:
user_profile_id = queue_item["user_profile_id"]
user_profile = get_user_profile_by_id(user_profile_id)
+ device_id = queue_item["device_id"]
bouncer_public_key = queue_item["bouncer_public_key"]
encrypted_push_registration = queue_item["encrypted_push_registration"]
- push_account_id = queue_item["push_account_id"]
+ token_id_base64 = queue_item["token_id_base64"]
try:
if settings.ZILENCER_ENABLED:
- device_id = do_register_remote_push_device(
+ do_register_remote_push_device(
bouncer_public_key,
encrypted_push_registration,
- push_account_id,
+ token_id_base64,
realm=user_profile.realm,
)
else:
post_data: dict[str, str | int] = {
"realm_uuid": str(user_profile.realm.uuid),
- "push_account_id": push_account_id,
+ "token_id": token_id_base64,
"encrypted_push_registration": encrypted_push_registration,
"bouncer_public_key": bouncer_public_key,
}
- result = send_to_push_bouncer("POST", "push/e2ee/register", post_data)
- assert isinstance(result["device_id"], int) # for mypy
- device_id = result["device_id"]
+ send_to_push_bouncer("POST", "push/e2ee/register", post_data)
except (
PushNotificationBouncerRetryLaterError,
PushNotificationBouncerServerError,
@@ -116,7 +111,7 @@ def handle_register_push_device_to_bouncer(
):
# Server admins need to fix these set of errors, report them.
# Server should keep retrying to register until `RequestExpiredError` is raised.
- error_msg = f"Push device registration request for user_id={user_profile.id}, push_account_id={push_account_id} failed."
+ error_msg = f"Push device registration request for device_id={device_id} failed."
logging.error(error_msg)
raise PushNotificationBouncerRetryLaterError(error_msg)
except (
@@ -127,18 +122,20 @@ def handle_register_push_device_to_bouncer(
JsonableError,
) as e:
handle_registration_to_bouncer_failure(
- user_profile, push_account_id, error_code=e.__class__.code.name
+ user_profile, device_id, error_code=e.__class__.code.name
)
return
# Registration successful.
- PushDevice.objects.filter(user=user_profile, push_account_id=push_account_id).update(
- bouncer_device_id=device_id
+ Device.objects.filter(id=device_id).update(
+ push_token_id=b64decode_token_id_base64(token_id_base64), pending_push_token_id=None
)
event = dict(
- type="push_device",
- push_account_id=push_account_id,
- status="active",
+ type="device",
+ op="update",
+ device_id=device_id,
+ push_token_id=token_id_base64,
+ pending_push_token_id=None,
)
send_event_on_commit(user_profile.realm, event, [user_profile.id])
diff --git a/zerver/lib/typed_endpoint_validators.py b/zerver/lib/typed_endpoint_validators.py
index 6616b2fc856..697746f8261 100644
--- a/zerver/lib/typed_endpoint_validators.py
+++ b/zerver/lib/typed_endpoint_validators.py
@@ -122,3 +122,13 @@ def parse_enum_from_string_value(
return enum[val]
except KeyError:
raise JsonableError(_("Invalid {setting_name}").format(setting_name=setting_name))
+
+
+def check_uint32(val: int) -> int:
+ if not (0 <= val <= 4294967295):
+ raise ValueError(_("Not a valid unsigned 32-bit integer"))
+ return val
+
+
+def uint32_validator() -> AfterValidator:
+ return AfterValidator(check_uint32)
diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.py
index dcaf40b8578..1e7586af089 100644
--- a/zerver/openapi/python_examples.py
+++ b/zerver/openapi/python_examples.py
@@ -1708,14 +1708,18 @@ def remove_fcm_token(client: Client) -> None:
@openapi_test_function("/mobile_push/register:post")
def register_push_device(client: Client) -> None:
+ result = client.call_endpoint(url="/register_client_device", method="POST")
+ device_id = result["device_id"]
# {code_example|start}
- # Register a push device.
+ # Register a device for push notifications.
request = {
+ "device_id": device_id,
"token_kind": "fcm",
- "push_account_id": 2408,
"push_key": "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt",
+ "push_key_id": 2408,
"bouncer_public_key": "bouncer-public-key",
"encrypted_push_registration": "encrypted-push-registration-data",
+ "token_id": "hGsEWGmyyfI=",
}
result = client.call_endpoint(url="/mobile_push/register", method="POST", request=request)
# {code_example|end}
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index f2144ea5f56..f9c5682c5b5 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -1912,6 +1912,81 @@ paths:
"op": "remove",
"device_id": 1144,
}
+ - type: object
+ additionalProperties: false
+ description: |
+ Event sent to a user's clients when the metadata in the
+ `devices` dictionary for the user changes.
+
+ Helps clients to live-update the `devices` dictionary
+ returned in [`POST /register`](/api/register-queue) response.
+
+ Besides `id`, `type`, `op`, and `device_id`, all other fields
+ are optional. Only fields whose values needs to be updated are
+ included in the event.
+
+ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd).
+ properties:
+ id:
+ $ref: "#/components/schemas/EventIdSchema"
+ type:
+ allOf:
+ - $ref: "#/components/schemas/EventTypeSchema"
+ - enum:
+ - device
+ op:
+ type: string
+ enum:
+ - update
+ device_id:
+ type: integer
+ description: |
+ The ID of the registered device whose metadata changed.
+ push_key_id:
+ type: integer
+ description: |
+ ID to reference the encryption key used to encrypt
+ push notifications sent to the device.
+ push_token_id:
+ type: string
+ nullable: true
+ description: |
+ ID to reference the token provided by FCM/APNs to the device,
+ which is registered to the push bouncer service.
+
+ A `null` value means the referenced token expired.
+ pending_push_token_id:
+ type: string
+ nullable: true
+ description: |
+ ID to reference the token provided by FCM/APNs to the device,
+ whose registration is in progress to the push bouncer service.
+
+ A `null` value means the pending registration succeeded.
+ push_token_last_updated_timestamp:
+ type: integer
+ description: |
+ The UNIX timestamp for the last time when `pending_push_token_id`
+ was set to a new non-null value, in UTC seconds.
+ push_registration_error_code:
+ type: string
+ nullable: true
+ description: |
+ If the push registration failed, a [Zulip API error code](/api/rest-error-handling)
+ indicating the type of failure that occurred.
+
+ The following error codes have recommended client behavior:
+
+ - `"INVALID_BOUNCER_PUBLIC_KEY"` - Inform the user to update app.
+ - `"REQUEST_EXPIRED` - Retry with a fresh payload.
+ example:
+ {
+ "id": 2,
+ "type": "device",
+ "op": "update",
+ "device_id": 12,
+ "push_key_id": 57,
+ }
- type: object
additionalProperties: false
description: |
@@ -12871,9 +12946,24 @@ paths:
summary: Register E2EE push device
tags: ["mobile"]
description: |
- Register a device to receive end-to-end encrypted mobile push notifications.
+ Register a device to receive end-to-end encrypted mobile push notifications,
+ or update such a registration.
- **Changes**: New in Zulip 11.0 (feature level 406).
+ To perform an initial registration, clients must provide both the
+ push key fields (`push_key` and `push_key_id`) and the token fields
+ (`token_kind`, `token_id`, `bouncer_public_key`, and `encrypted_push_registration`).
+
+ Once registered, clients should use this endpoint to rotate `push_key` or
+ FCM/APNs provided token:
+
+ - **Rotate push key**: Provide only the push key fields.
+ - **Rotate token**: Provide only the token fields.
+
+ **Changes**: In Zulip 12.0 (feature level ZF-42fbcd), 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:
required: true
content:
@@ -12881,20 +12971,19 @@ paths:
schema:
type: object
properties:
- token_kind:
+ device_id:
description: |
- Whether the token was generated by FCM or APNs.
- type: string
- enum:
- - fcm
- - apns
- example: "fcm"
- push_account_id:
+ The ID of the device to configure for push notifications.
+
+ See [`POST /register_client_device`](/api/register-client-device)
+ for how to obtain a device ID.
+ type: integer
+ example: 1
+ push_key_id:
description: |
- A random integer generated by the client that will be included
- in mobile push notifications along with encrypted payloads to
- identify pushes as being related to this registration.
- Must be unique in the client's table of accounts.
+ A random unsigned 32-bit integer generated by the client as an identifier
+ for `push_key`. It will be included in mobile push notifications
+ along with encrypted payloads to identify the `push_key` to decrypt.
type: integer
example: 2408
push_key:
@@ -12926,6 +13015,22 @@ paths:
did not have a natural way to support multiple cryptosystems.
type: string
example: "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt"
+ token_kind:
+ description: |
+ Whether the token was generated by FCM or APNs.
+ type: string
+ enum:
+ - fcm
+ - apns
+ example: "fcm"
+ token_id:
+ description: |
+ Identifier for the FCM/APNs provided token to the device,
+ produced by taking the first 8 bytes of the SHA-256 hash of
+ the token, then encoding those bytes using standard Base64 encoding
+ as defined in RFC 4648.
+ type: string
+ example: "hGsEWGmyyfI="
bouncer_public_key:
description: |
Which of the bouncer's public keys the client used to encrypt the
@@ -12935,6 +13040,9 @@ paths:
and the new public key is baked into a new client release. Because
the bouncer routinely rotates key, this field clarifies which
public key the client is using.
+
+ The public key is encoded using standard Base64 encoding as defined
+ in RFC 4648.
type: string
example: "bouncer-public-key"
encrypted_push_registration:
@@ -12949,11 +13057,7 @@ paths:
type: string
example: "encrypted-push-registration-data"
required:
- - token_kind
- - push_account_id
- - push_key
- - bouncer_public_key
- - encrypted_push_registration
+ - device_id
responses:
"200":
$ref: "#/components/responses/SimpleSuccess"
@@ -13001,12 +13105,15 @@ paths:
being registered belongs.
type: string
example: "9aa61d0b-8ce5-488d-8e9e-fedc346e6836"
- push_account_id:
+ token_id:
description: |
- The `push_account_id` value provided by the mobile client
+ The `token_id` value provided by the mobile client
to [register E2EE push device](/api/register-push-device).
- type: integer
- example: 2408
+
+ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd),
+ replacing `push_account_id`.
+ type: string
+ example: "+wKIhyAx/Eg="
encrypted_push_registration:
description: |
The `encrypted_push_registration` value provided by the mobile client
@@ -13021,30 +13128,12 @@ paths:
example: "bouncer-public-key"
required:
- realm_uuid
- - push_account_id
+ - token_id
- encrypted_push_registration
- bouncer_public_key
responses:
"200":
- description: Success
- content:
- application/json:
- schema:
- allOf:
- - $ref: "#/components/schemas/JsonSuccessBase"
- - required:
- - device_id
- additionalProperties: false
- properties:
- result: {}
- msg: {}
- ignored_parameters_unsupported: {}
- device_id:
- type: integer
- description: |
- Unique identifier assigned by the bouncer for the registration.
- example: 2408
- example: {"device_id": 2408, "msg": "", "result": "success"}
+ $ref: "#/components/responses/SimpleSuccess"
"400":
description: Bad request.
content:
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 3389bcb4648..e5135524a66 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -178,6 +178,7 @@ from zerver.lib.event_schema import (
check_default_streams,
check_delete_message,
check_device_add,
+ check_device_update,
check_direct_message,
check_draft_add,
check_draft_remove,
@@ -283,6 +284,7 @@ from zerver.lib.user_groups import (
from zerver.models import (
Attachment,
CustomProfileField,
+ Device,
ImageAttachment,
Message,
MultiuseInvite,
@@ -4322,6 +4324,48 @@ class NormalActionsTest(BaseAction):
do_register_device(self.user_profile)
check_device_add("events[0]", events[0])
+ def test_register_push_device(self) -> None:
+ self.login_user(self.user_profile)
+ device = Device.objects.create(user=self.user_profile)
+
+ with (
+ mock.patch("zerver.lib.push_registration.do_register_remote_push_device"),
+ self.verify_action(num_events=2) as events,
+ ):
+ payload = {
+ "device_id": device.id,
+ "token_kind": Device.PushTokenKind.FCM,
+ "push_key": "MY+paNlyduYJRQFNZva8w7Gv3PkBua9kIj581F9Vr301",
+ "push_key_id": 2408,
+ "bouncer_public_key": "bouncer-public-key",
+ "encrypted_push_registration": "encrypted-push-registration",
+ "token_id": "hGsEWGmyyfI=",
+ }
+ self.client_post("/json/mobile_push/register", payload)
+ check_device_update("events[0]", events[0])
+ check_device_update("events[1]", events[1])
+
+ # For coverage of `device.pending_push_token_id is not None` branch
+ # in `zerver.lib.devices.get_devices`.
+ device = Device.objects.create(user=self.user_profile)
+ with (
+ mock.patch(
+ "zerver.worker.missedmessage_mobile_notifications.handle_register_push_device_to_bouncer"
+ ),
+ self.verify_action(num_events=1) as events,
+ ):
+ payload = {
+ "device_id": device.id,
+ "token_kind": Device.PushTokenKind.FCM,
+ "push_key": "MTaUDJDMWypQ1WufZ1NRTHSSvgYtXh1qVNSjN3aBiEFt",
+ "push_key_id": 1144,
+ "bouncer_public_key": "bouncer-public-key-2",
+ "encrypted_push_registration": "encrypted-push-registration-2",
+ "token_id": "iGFeKNj3ngQ=",
+ }
+ self.client_post("/json/mobile_push/register", payload)
+ check_device_update("events[0]", events[0])
+
def test_notify_realm_export_on_failure(self) -> None:
self.set_user_role(self.user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR)
self.login_user(self.user_profile)
diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.py
index 6579af5b527..b666e909f0a 100644
--- a/zerver/tests/test_queue_worker.py
+++ b/zerver/tests/test_queue_worker.py
@@ -509,9 +509,10 @@ class WorkerTest(ZulipTestCase):
"type": "register_push_device_to_bouncer",
"payload": {
"user_profile_id": 2,
- "push_account_id": 3,
+ "device_id": 3,
"bouncer_public_key": "test-key",
"encrypted_push_registration": "test-encrypted",
+ "token_id_base64": "hGsEWGmyyfI=",
},
}
@@ -592,7 +593,7 @@ class WorkerTest(ZulipTestCase):
)
self.assertEqual(
warn_logs.output[2],
- "WARNING:zerver.worker.missedmessage_mobile_notifications:Maximum retries exceeded for trigger:(user_id=2, push_account_id=3) event:register_push_device_to_bouncer",
+ "WARNING:zerver.worker.missedmessage_mobile_notifications:Maximum retries exceeded for device_id:3 event:register_push_device_to_bouncer",
)
@patch("zerver.worker.email_mirror.mirror_email")
diff --git a/zerver/views/push_notifications.py b/zerver/views/push_notifications.py
index 35338599e2a..79f9eec90f7 100644
--- a/zerver/views/push_notifications.py
+++ b/zerver/views/push_notifications.py
@@ -2,15 +2,21 @@ from typing import Annotated
import orjson
from django.conf import settings
+from django.db import transaction
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import gettext as _
from pydantic import Json
-from zerver.actions.push_notifications import do_register_push_device
+from zerver.actions.push_notifications import (
+ do_register_push_device,
+ do_rotate_push_key,
+ do_rotate_token,
+)
from zerver.decorator import human_users_only, zulip_login_required
from zerver.lib import redis_utils
+from zerver.lib.devices import b64decode_token_id_base64, check_device_id
from zerver.lib.exceptions import (
ErrorCode,
JsonableError,
@@ -40,9 +46,14 @@ from zerver.lib.remote_server import (
send_to_push_bouncer,
)
from zerver.lib.response import json_success
-from zerver.lib.typed_endpoint import ApnsAppId, typed_endpoint, typed_endpoint_without_parameters
-from zerver.lib.typed_endpoint_validators import check_string_in_validator
-from zerver.models import PushDevice, PushDeviceToken, UserProfile
+from zerver.lib.typed_endpoint import (
+ ApiParamConfig,
+ ApnsAppId,
+ typed_endpoint,
+ 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.views.errors import config_error
redis_client = redis_utils.get_redis_client()
@@ -296,49 +307,120 @@ def register_push_device(
request: HttpRequest,
user_profile: UserProfile,
*,
- token_kind: Annotated[str, check_string_in_validator(PushDevice.TokenKind.values)],
- push_account_id: Json[int],
+ # `device_id` to configure for push notifications.
+ device_id: Json[int],
+ token_kind: Annotated[
+ str | None, check_string_in_validator(Device.PushTokenKind.values)
+ ] = None,
# 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,
+ push_key: str | None = None,
+ # ID which client uses to reference `push_key`.
+ push_key_id: Annotated[Json[int] | None, uint32_validator()] = None,
# Key that the client claims was used to encrypt
# `encrypted_push_registration`.
- bouncer_public_key: str,
+ bouncer_public_key: str | None = None,
# Registration data encrypted by mobile client for bouncer.
- encrypted_push_registration: str,
+ encrypted_push_registration: str | None = None,
+ # ID which client uses to reference token provided by FCM/APNs.
+ token_id_base64: Annotated[str | None, ApiParamConfig("token_id")] = None,
) -> HttpResponse:
if not (settings.ZILENCER_ENABLED or uses_notification_bouncer()):
raise PushServiceNotConfiguredError
- push_key_bytes = check_push_key(push_key)
+ device = check_device_id(device_id, user_profile.id)
+
+ push_key_fields_present = push_key is not None and push_key_id is not None
+ token_fields_present = (
+ bouncer_public_key is not None
+ and encrypted_push_registration is not None
+ and token_id_base64 is not None
+ and token_kind is not None
+ )
+
+ if not (push_key_fields_present or token_fields_present):
+ raise JsonableError(
+ _(
+ "Missing parameters: must provide either all push key fields, all token fields, or both."
+ )
+ )
+
+ if push_key_fields_present and not token_fields_present:
+ if device.push_key_id is None:
+ raise JsonableError(_("No push registration exists to rotate key for."))
- # Idempotency
- already_registered = PushDevice.objects.filter(
- user=user_profile, push_account_id=push_account_id, error_code__isnull=True
- ).exists()
- if already_registered:
+ assert push_key is not None and push_key_id is not None
+ push_key_bytes = check_push_key(push_key)
+ do_rotate_push_key(user_profile, device, push_key_bytes, push_key_id)
return json_success(request)
- do_register_push_device(user_profile, push_account_id, token_kind, push_key_bytes)
-
- # We use a queue worker to make the request to the bouncer
- # to complete the registration, so that any transient failures
- # can be managed between the two servers, without the mobile
- # device and its often-irregular network access in the picture.
- queue_item: RegisterPushDeviceToBouncerQueueItem = {
- "user_profile_id": user_profile.id,
- "bouncer_public_key": bouncer_public_key,
- "encrypted_push_registration": encrypted_push_registration,
- "push_account_id": push_account_id,
- }
- queue_event_on_commit(
- "missedmessage_mobile_notifications",
- {
- "type": "register_push_device_to_bouncer",
- "payload": queue_item,
- },
- )
+ # A registration request already in progress, don't enqueue another one
+ # to bouncer to avoid bugs due to race.
+ if device.push_registration_error_code is None and device.pending_push_token_id is not None:
+ raise JsonableError(_("A registration for the device already in progress."))
+
+ with transaction.atomic(durable=True):
+ assert token_id_base64 is not None
+ assert token_kind is not None
+ assert bouncer_public_key is not None
+ assert encrypted_push_registration is not None
+
+ token_id_int = b64decode_token_id_base64(token_id_base64)
+ if token_fields_present and not push_key_fields_present:
+ if device.push_key_id is None:
+ raise JsonableError(_("No push registration exists to rotate token for."))
+
+ if device.push_registration_error_code is None and device.push_token_id == token_id_int:
+ return json_success(request)
+
+ do_rotate_token(user_profile, device, token_id_int, token_id_base64)
+
+ # All fields present
+ if push_key_fields_present and token_fields_present:
+ assert push_key is not None
+ assert push_key_id is not None
+ push_key_bytes = check_push_key(push_key)
+
+ # Idempotent
+ if (
+ device.push_registration_error_code is None
+ and device.push_key_id == push_key_id
+ and device.push_key is not None
+ and bytes(device.push_key) == push_key_bytes
+ and device.push_token_id == token_id_int
+ and device.push_token_kind == token_kind
+ ):
+ return json_success(request)
+
+ do_register_push_device(
+ user_profile,
+ device,
+ token_kind=token_kind,
+ push_key_bytes=push_key_bytes,
+ push_key_id=push_key_id,
+ token_id_int=token_id_int,
+ token_id_base64=token_id_base64,
+ )
+
+ # We use a queue worker to make the request to the bouncer
+ # to complete the registration, so that any transient failures
+ # can be managed between the two servers, without the mobile
+ # device and its often-irregular network access in the picture.
+ queue_item: RegisterPushDeviceToBouncerQueueItem = {
+ "user_profile_id": user_profile.id,
+ "device_id": device_id,
+ "bouncer_public_key": bouncer_public_key,
+ "encrypted_push_registration": encrypted_push_registration,
+ "token_id_base64": token_id_base64,
+ }
+ queue_event_on_commit(
+ "missedmessage_mobile_notifications",
+ {
+ "type": "register_push_device_to_bouncer",
+ "payload": queue_item,
+ },
+ )
return json_success(request)
diff --git a/zerver/worker/missedmessage_mobile_notifications.py b/zerver/worker/missedmessage_mobile_notifications.py
index a8950f6c138..4d24ca8294c 100644
--- a/zerver/worker/missedmessage_mobile_notifications.py
+++ b/zerver/worker/missedmessage_mobile_notifications.py
@@ -60,9 +60,8 @@ class PushNotificationsWorker(QueueProcessingWorker):
def failure_processor(event: dict[str, Any]) -> None:
if event_type == "register_push_device_to_bouncer":
logger.warning(
- "Maximum retries exceeded for trigger:(user_id=%s, push_account_id=%s) event:register_push_device_to_bouncer",
- event["payload"]["user_profile_id"],
- event["payload"]["push_account_id"],
+ "Maximum retries exceeded for device_id:%s event:register_push_device_to_bouncer",
+ event["payload"]["device_id"],
)
else:
logger.warning(
diff --git a/zilencer/migrations/0068_add_remotepushdevice_token_id_and_more.py b/zilencer/migrations/0068_add_remotepushdevice_token_id_and_more.py
new file mode 100644
index 00000000000..13c27dfdafa
--- /dev/null
+++ b/zilencer/migrations/0068_add_remotepushdevice_token_id_and_more.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.10 on 2026-02-02 17:15
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("zerver", "0779_device"),
+ ("zilencer", "0067_remotepushdevicetoken_apns_case_insensitive"),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="remotepushdevice",
+ name="unique_remote_push_device_push_account_id_token",
+ ),
+ migrations.AddField(
+ model_name="remotepushdevice",
+ name="token_id",
+ field=models.BigIntegerField(default=None),
+ preserve_default=False,
+ ),
+ migrations.AddConstraint(
+ model_name="remotepushdevice",
+ constraint=models.UniqueConstraint(
+ fields=("token_id", "realm", "remote_realm"),
+ name="unique_remote_push_device_token_id_realm_remote_realm",
+ ),
+ ),
+ ]
diff --git a/zilencer/models.py b/zilencer/models.py
index d1946a69f20..3010cfb3433 100644
--- a/zilencer/models.py
+++ b/zilencer/models.py
@@ -634,8 +634,8 @@ class RemotePushDevice(AbstractPushDevice):
"""Core bouncer server table storing registrations to receive
mobile push notifications via the bouncer server.
- Each row corresponds to an account on an install of the app
- registered to receive mobile push notifications.
+ Each row corresponds to an install of the app registered
+ to receive mobile push notifications for a specific realm.
"""
# Unique identifier assigned by the bouncer for this registration.
@@ -653,6 +653,8 @@ class RemotePushDevice(AbstractPushDevice):
# FCM and APNs don't specify a maximum token length, so we only enforce
# that they're at most the maximum FCM / APNs payload size of 4096 bytes.
token = models.CharField(max_length=4096)
+ # ID to reference the `token`.
+ token_id = models.BigIntegerField()
# If the token is expired, the date when the bouncer learned it
# was expired via an error from the FCM/APNs server. Used to
@@ -666,13 +668,9 @@ class RemotePushDevice(AbstractPushDevice):
class Meta:
constraints = [
UniqueConstraint(
- # Each app install (token) can have multiple accounts (push_account_id).
- # The (push_account_id, token) pair needs to be unique to avoid sending
- # redundant notifications to the same account on a device.
- #
- # Also, the unique index created is used by a query in
+ # The unique index created is used by a query in
# 'do_register_remote_push_device'.
- fields=["push_account_id", "token"],
- name="unique_remote_push_device_push_account_id_token",
+ fields=["token_id", "realm", "remote_realm"],
+ name="unique_remote_push_device_token_id_realm_remote_realm",
),
]
diff --git a/zilencer/views.py b/zilencer/views.py
index 4962aac94b0..cfa3d45c34e 100644
--- a/zilencer/views.py
+++ b/zilencer/views.py
@@ -1,3 +1,5 @@
+import base64
+import hashlib
import logging
from collections import Counter
from datetime import datetime, timedelta, timezone
@@ -42,6 +44,7 @@ from analytics.lib.counts import (
from corporate.models.customers import get_customer_by_remote_realm
from corporate.models.plans import CustomerPlan, get_current_plan_by_customer
from zerver.decorator import require_post
+from zerver.lib.devices import b64decode_token_id_base64
from zerver.lib.email_validation import validate_is_not_disposable
from zerver.lib.exceptions import (
ErrorCode,
@@ -81,6 +84,7 @@ from zerver.lib.response import json_success
from zerver.lib.send_email import FromAddress
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
from zerver.lib.typed_endpoint import (
+ ApiParamConfig,
ApnsAppId,
JsonBodyPayload,
RequiredStringConstraint,
@@ -583,11 +587,11 @@ class PushRegistration(BaseModel):
def do_register_remote_push_device(
bouncer_public_key: str,
encrypted_push_registration: str,
- push_account_id: int,
+ token_id_base64: str,
*,
realm: Realm | None = None,
remote_realm: RemoteRealm | None = None,
-) -> int:
+) -> None:
assert (realm is None) ^ (remote_realm is None)
if bouncer_public_key not in settings.PUSH_REGISTRATION_ENCRYPTION_KEYS:
@@ -610,30 +614,37 @@ def do_register_remote_push_device(
except PydanticValidationError:
raise InvalidEncryptedPushRegistrationError
+ hash_bytes = hashlib.sha256(push_registration.token.encode()).digest()
+ expected_token_id_base64 = base64.b64encode(hash_bytes[0:8]).decode()
+ if token_id_base64 != expected_token_id_base64:
+ raise InvalidEncryptedPushRegistrationError
+
if (
datetime_to_timestamp(timezone_now()) - push_registration.timestamp
> PUSH_REGISTRATION_LIVENESS_TIMEOUT
):
raise RequestExpiredError
- # If already registered, return the device_id.
+ # If already registered, return.
# The query uses the unique index created by the
- # 'unique_remote_push_device_push_account_id_token' constraint.
- remote_push_device = RemotePushDevice.objects.filter(
- token=push_registration.token, push_account_id=push_account_id
- ).first()
- if remote_push_device:
- return remote_push_device.device_id
-
- remote_push_device = RemotePushDevice.objects.create(
+ # 'unique_remote_push_device_token_id_realm_remote_realm' constraint.
+ token_id_int = b64decode_token_id_base64(token_id_base64)
+ remote_push_device_exists = RemotePushDevice.objects.filter(
+ token_id=token_id_int,
+ realm=realm,
+ remote_realm=remote_realm,
+ ).exists()
+ if remote_push_device_exists:
+ return
+
+ RemotePushDevice.objects.create(
realm=realm,
remote_realm=remote_realm,
token=push_registration.token,
token_kind=push_registration.token_kind,
- push_account_id=push_account_id,
+ token_id=token_id_int,
ios_app_id=push_registration.ios_app_id,
)
- return remote_push_device.device_id
@typed_endpoint
@@ -642,7 +653,7 @@ def register_remote_push_device_for_e2ee_push_notification(
server: RemoteZulipServer,
*,
realm_uuid: str,
- push_account_id: Json[int],
+ token_id_base64: Annotated[str, ApiParamConfig("token_id")],
encrypted_push_registration: str,
bouncer_public_key: str,
) -> HttpResponse:
@@ -653,14 +664,13 @@ def register_remote_push_device_for_e2ee_push_notification(
remote_realm.last_request_datetime = timezone_now()
remote_realm.save(update_fields=["last_request_datetime"])
- device_id = do_register_remote_push_device(
+ do_register_remote_push_device(
bouncer_public_key,
encrypted_push_registration,
- push_account_id,
+ token_id_base64,
remote_realm=remote_realm,
)
-
- return json_success(request, {"device_id": device_id})
+ return json_success(request)
@typed_endpoint