Skip to main content

jmap_server/
push.rs

1//! RFC 8620 §7.2 push subscriptions: the caller-scoped storage trait, the
2//! `PushSubscription/get` and `PushSubscription/set` handlers
3//! (bd:JMAP-nbk3.2, bd:JMAP-nbk3.3), and the delivery gates
4//! [`is_deliverable`] and [`state_change_for`].
5//!
6//! Push subscriptions are not tied to an account (RFC 8620 §7.2.1), so the
7//! handlers here do not use `accountId`, [`JmapBackend::account_exists`],
8//! or [`JmapBackend::get_state`]. Instead they scope every lookup to the
9//! caller's credentials through [`PushSubscriptionBackend`].
10//!
11//! Sending the `PushVerification` and `StateChange` requests is the
12//! consumer's job; this module only decides what may be sent.
13
14use std::{
15    collections::{BTreeMap, HashSet},
16    fmt,
17    future::Future,
18    sync::Arc,
19    time::SystemTime,
20};
21
22use jmap_types::{Id, JmapError, PushSubscription, SetObject, State, StateChange, UTCDate};
23use serde_json::{Map, Value, json};
24use subtle::ConstantTimeEq;
25
26use crate::backend::{
27    BackendSetError, JmapBackend, SetError, SetErrorType, backend_set_error_value,
28};
29use crate::handlers::{server_fail_from_backend, server_fail_value_from_backend};
30use crate::helpers::{
31    apply_patch_object, enforce_max_objects_in_get, enforce_max_objects_in_set, not_found_json,
32    optional_arg, reject_server_set, serialize_value, signed_seconds_since_epoch,
33    utc_date_from_epoch_seconds,
34};
35use crate::{CallContext, ClosureHandler, Dispatcher, HandlerFuture, HandlerOutput, JmapHandler};
36
37/// The properties that `PushSubscription/get` never returns and rejects
38/// with `forbidden` when requested (RFC 8620 §7.2.1).
39const PRIVATE_PROPERTIES: [&str; 2] = ["url", "keys"];
40
41/// The RFC 8620 §7.2 properties that `PushSubscription/get` may return.
42const RFC_PROPERTIES: [&str; 5] = [
43    "id",
44    "deviceClientId",
45    "verificationCode",
46    "expires",
47    "types",
48];
49
50/// The `ids` cap for `PushSubscription/get`.
51///
52/// ponytail: a fixed RFC 8620 §2 suggested minimum.
53/// [`JmapBackend::max_objects_in_get`] is per account and this method has
54/// no account, so a backend override of that method does not apply here.
55/// The upgrade path is a caller-scoped limit method on
56/// [`PushSubscriptionBackend`].
57const MAX_OBJECTS_IN_GET: u64 = 500;
58
59/// The `create` + `update` + `destroy` cap for `PushSubscription/set`.
60///
61/// ponytail: fixed, for the same reason as [`MAX_OBJECTS_IN_GET`], with the
62/// same upgrade path.
63const MAX_OBJECTS_IN_SET: u64 = 500;
64
65/// The furthest in the future, in seconds from now, that
66/// `PushSubscription/set` lets `expires` be: 7 days.
67///
68/// RFC 8620 §7.2.1 (rfc8620.txt:3711-3715): the server "SHOULD set an
69/// expiry time for the push subscription if none is given and limit the
70/// expiry time if set too far in the future. This maximum expiry time MUST
71/// be at least 48 hours in the future and SHOULD be at least 7 days in the
72/// future."
73///
74/// ponytail: one fixed limit for every caller. RFC 8620 (rfc8620.txt:
75/// 3706-3709) says the server SHOULD NOT bound the expiry for session-bound
76/// credentials, but MUST expire the subscription with the session; a backend
77/// can only shorten `expires` further. The upgrade path is a caller-scoped
78/// limit method on [`PushSubscriptionBackend`].
79pub const MAX_PUSH_EXPIRY_SECS: i64 = 7 * 86_400;
80
81/// A push subscription as the backend stores it.
82///
83/// `subscription` is the object as the client sees it, including the
84/// private `url` and `keys`, which `PushSubscription/get` strips.
85/// `subscription.verification_code` is the code the client echoed back, if
86/// any. `expected_code` is the code the server sent in the
87/// `PushVerification` object.
88///
89/// The `Debug` impl redacts `expected_code`.
90#[derive(Clone, PartialEq, Eq)]
91pub struct StoredPushSubscription {
92    /// The subscription, including the private `url` and `keys`.
93    pub subscription: PushSubscription,
94    /// The verification code the server sent to the push endpoint.
95    pub expected_code: String,
96}
97
98impl fmt::Debug for StoredPushSubscription {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.debug_struct("StoredPushSubscription")
101            .field("subscription", &self.subscription)
102            .field("expected_code", &"[REDACTED]")
103            .finish()
104    }
105}
106
107/// Storage for RFC 8620 §7.2 push subscriptions, scoped to the caller's
108/// credentials rather than to an account.
109///
110/// The `PushSubscription/set` handler validates the request before it calls
111/// the create and update methods: `url` begins with `"https://"`, a create
112/// carries no `id` or `verificationCode`, an update changes no immutable
113/// property, a new `verificationCode` matches
114/// [`StoredPushSubscription::expected_code`], and `expires` is at most
115/// [`MAX_PUSH_EXPIRY_SECS`] in the future. A backend may reject a request
116/// for its own policy reasons by returning [`BackendSetError::SetError`],
117/// which the handler places in the response verbatim.
118///
119/// # Consumer MUSTs
120///
121/// These RFC 8620 requirements need I/O, clocks or credential state that
122/// this crate does not have. The consumer that implements this trait and
123/// sends the pushes MUST meet them:
124///
125/// - "The server MUST ensure the URL is externally resolvable to avoid
126///   server-side request forgery" (rfc8620.txt:4151-4153).
127/// - "The rate of creation MUST also be limited" (rfc8620.txt:4175-4177).
128/// - "Should these credentials expire or be revoked, the push subscription
129///   MUST be destroyed by the JMAP server" (rfc8620.txt:3691-3693).
130/// - "When a push subscription is destroyed, the server MUST securely erase
131///   the URL and encryption keys from memory and storage as soon as
132///   possible" (rfc8620.txt:3725-3727).
133/// - Send nothing but the `PushVerification` to a subscription until
134///   [`is_deliverable`] is true, and filter each `StateChange` with
135///   [`state_change_for`].
136pub trait PushSubscriptionBackend: JmapBackend {
137    /// The extension property names, beyond those of RFC 8620 §7.2, that
138    /// `PushSubscription/get` accepts in its `properties` argument (e.g.
139    /// `chatPush`, draft-atwood-jmap-chat-push-00).
140    ///
141    /// RFC 8620 §5.1 (rfc8620.txt:1609-1611): "If an invalid property is
142    /// requested, the call MUST be rejected with an "invalidArguments"
143    /// error." The handler rejects any name that is neither an RFC 8620
144    /// §7.2 property nor listed here.
145    const PUSH_SUBSCRIPTION_EXTENSION_PROPERTIES: &'static [&'static str] = &[];
146
147    /// Return every push subscription created with the credentials that
148    /// `caller` identifies, and no others.
149    ///
150    /// RFC 8620 §7.2.1: "The server MUST only return push subscriptions
151    /// that were created using the same authentication credentials as for
152    /// this "PushSubscription/get" request." The handler cannot tell
153    /// credentials apart, so it relies on this method for that MUST.
154    fn list_push_subscriptions(
155        &self,
156        caller: &Self::CallerCtx,
157    ) -> impl Future<Output = Result<Vec<StoredPushSubscription>, Self::Error>> + Send;
158
159    /// Store `new` as a subscription owned by the credentials that `caller`
160    /// identifies, and return what was stored.
161    ///
162    /// `new` has no `id` and no `verificationCode`, and its `expires` is
163    /// already limited to [`MAX_PUSH_EXPIRY_SECS`] from now. The backend
164    /// MUST:
165    ///
166    /// - assign `id`;
167    /// - generate [`StoredPushSubscription::expected_code`] as a fixed-length
168    ///   code carrying at least 128 bits from a CSPRNG. The code "MUST
169    ///   contain sufficient entropy to avoid the client being able to guess
170    ///   the code via brute force" (rfc8620.txt:3784-3786);
171    /// - check its per-user subscription cap atomically with the insert and
172    ///   return `overQuota` when it is reached. "The server MUST limit the
173    ///   number of push subscriptions any one user may have"
174    ///   (rfc8620.txt:4172-4175);
175    /// - hand a `PushVerification` with the new id and code to the
176    ///   consumer's delivery path.
177    ///
178    /// The backend may shorten `expires`. In `created` the handler echoes
179    /// the returned `id` and `expires`, plus every property the client did
180    /// not send.
181    fn create_push_subscription(
182        &self,
183        caller: &Self::CallerCtx,
184        new: PushSubscription,
185    ) -> impl Future<Output = Result<StoredPushSubscription, BackendSetError<Self::Error>>> + Send;
186
187    /// Replace the caller's subscription whose id is `sub.id` with `sub`,
188    /// and return what was stored.
189    ///
190    /// `sub` is the stored subscription with the client's patch applied and
191    /// validated. Return `notFound` if no subscription of the caller has
192    /// that id. The backend may shorten `expires`. The handler reports a
193    /// returned `expires` that differs from the one the client asked for in
194    /// `updated`.
195    fn update_push_subscription(
196        &self,
197        caller: &Self::CallerCtx,
198        sub: PushSubscription,
199    ) -> impl Future<Output = Result<PushSubscription, BackendSetError<Self::Error>>> + Send;
200
201    /// Delete the caller's subscription with this `id`, or return
202    /// `notFound` if the caller has none.
203    ///
204    /// See the secure-erase MUST in the trait docs.
205    fn destroy_push_subscription(
206        &self,
207        caller: &Self::CallerCtx,
208        id: &Id,
209    ) -> impl Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
210}
211
212/// Register the `PushSubscription/get` (RFC 8620 §7.2.1) and
213/// `PushSubscription/set` (RFC 8620 §7.2.2) handlers on `dispatcher`.
214///
215/// Like the `register_*_handlers` functions of the extension server crates,
216/// this calls [`Dispatcher::register`], which silently replaces any handler
217/// already registered under the same method name.
218pub fn register_push_subscription_handlers<B>(
219    dispatcher: &mut Dispatcher<B::CallerCtx>,
220    backend: Arc<B>,
221) where
222    B: PushSubscriptionBackend + 'static,
223{
224    let handler: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
225        Arc::clone(&backend),
226        |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
227            Box::pin(async move { handle_push_subscription_get(&*b, &cx.caller, cx.args).await })
228                as HandlerFuture
229        },
230    ));
231    dispatcher.register("PushSubscription/get", handler);
232
233    let handler: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
234        backend,
235        |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
236            Box::pin(async move { handle_push_subscription_set(&*b, &cx.caller, cx.args).await })
237                as HandlerFuture
238        },
239    ));
240    dispatcher.register("PushSubscription/set", handler);
241}
242
243/// `PushSubscription/get` (RFC 8620 §7.2.1).
244///
245/// A standard `/get` without `accountId` in the arguments or the response,
246/// and without `state` in the response. A null `ids` returns all of the
247/// caller's subscriptions. `url` and `keys` are never returned, and
248/// requesting either in `properties` fails the call with `forbidden`.
249async fn handle_push_subscription_get<B: PushSubscriptionBackend>(
250    backend: &B,
251    caller: &B::CallerCtx,
252    args: Value,
253) -> Result<HandlerOutput, JmapError> {
254    let Value::Object(mut args) = args else {
255        return Err(JmapError::invalid_arguments("arguments must be an object"));
256    };
257    enforce_max_objects_in_get(&args, MAX_OBJECTS_IN_GET)?;
258
259    let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
260        JmapError::invalid_arguments("ids must be an Id array")
261    })?;
262    let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
263        JmapError::invalid_arguments("properties must be a string array")
264    })?;
265    if properties
266        .iter()
267        .flatten()
268        .any(|p| PRIVATE_PROPERTIES.contains(&p.as_str()))
269    {
270        return Err(JmapError::forbidden());
271    }
272    // RFC 8620 §5.1 (rfc8620.txt:1609-1611): "If an invalid property is
273    // requested, the call MUST be rejected with an "invalidArguments" error."
274    if let Some(bad) = properties.iter().flatten().find(|p| {
275        !RFC_PROPERTIES.contains(&p.as_str())
276            && !B::PUSH_SUBSCRIPTION_EXTENSION_PROPERTIES.contains(&p.as_str())
277    }) {
278        return Err(JmapError::invalid_arguments(format!(
279            "unknown PushSubscription property: {bad}"
280        )));
281    }
282
283    let stored = backend
284        .list_push_subscriptions(caller)
285        .await
286        .map_err(|e| server_fail_from_backend(&e))?;
287    let mut subs: Vec<PushSubscription> = stored.into_iter().map(|s| s.subscription).collect();
288
289    let mut not_found = Vec::new();
290    if let Some(ids) = ids {
291        let mut found = Vec::with_capacity(ids.len());
292        let mut seen = HashSet::with_capacity(ids.len());
293        for id in ids {
294            // RFC 8620 §5.1 (rfc8620.txt:1648-1651): an id given more than
295            // once appears only once in "list" or "notFound".
296            if !seen.insert(id.clone()) {
297                continue;
298            }
299            match subs.iter().find(|s| s.id.as_ref() == Some(&id)) {
300                Some(s) => found.push(s.clone()),
301                None => not_found.push(id),
302            }
303        }
304        subs = found;
305    }
306
307    let list = subs
308        .into_iter()
309        .map(|mut sub| {
310            sub.url = None;
311            sub.keys = None;
312            let mut value = serialize_value(&sub)?;
313            if let (Some(props), Value::Object(obj)) = (&properties, &mut value) {
314                // RFC 8620 §5.1 (rfc8620.txt:1608-1609): "The id property of
315                // the object is *always* returned, even if not explicitly
316                // requested."
317                obj.retain(|key, _| key == "id" || props.contains(key));
318            }
319            Ok(value)
320        })
321        .collect::<Result<Vec<Value>, JmapError>>()?;
322
323    Ok(HandlerOutput::new(json!({
324        "list": list,
325        "notFound": not_found_json(&not_found),
326    })))
327}
328
329/// `PushSubscription/set` (RFC 8620 §7.2.2).
330///
331/// RFC 8620 §7.2.2 (rfc8620.txt:3761-3764): "Standard /set method as
332/// described in Section 5.3, except it does *not* take or return an
333/// "accountId" argument, as push subscriptions are not tied to specific
334/// accounts. It also does *not* take an "ifInState" argument or return
335/// "oldState" or "newState" arguments." Those arguments are ignored if
336/// sent.
337///
338/// Creates, then updates, then destroys, as RFC 8620 §5.3 orders them.
339async fn handle_push_subscription_set<B: PushSubscriptionBackend>(
340    backend: &B,
341    caller: &B::CallerCtx,
342    args: Value,
343) -> Result<HandlerOutput, JmapError> {
344    let Value::Object(mut args) = args else {
345        return Err(JmapError::invalid_arguments("arguments must be an object"));
346    };
347    enforce_max_objects_in_set(&args, MAX_OBJECTS_IN_SET)?;
348
349    let create: Option<Map<String, Value>> = optional_arg(&mut args, "create", || {
350        JmapError::invalid_arguments("create must be an object")
351    })?;
352    let update: Option<Map<String, Value>> = optional_arg(&mut args, "update", || {
353        JmapError::invalid_arguments("update must be an object")
354    })?;
355    let destroy: Option<Vec<Id>> = optional_arg(&mut args, "destroy", || {
356        JmapError::invalid_arguments("destroy must be an Id array")
357    })?;
358
359    // Read the stored subscriptions before any create is committed, so a
360    // list failure returns a method-level serverFail with no state changed
361    // (RFC 8620 §3.6.2, rfc8620.txt:1158-1160). An update cannot name a
362    // same-call create: its server-assigned id is unknown to the client.
363    // ponytail: one O(n) list per call instead of a lookup by id. The
364    // upgrade path is a get_push_subscription method on the trait.
365    let update_with_stored = match update.filter(|u| !u.is_empty()) {
366        Some(update) => {
367            let stored = backend
368                .list_push_subscriptions(caller)
369                .await
370                .map_err(|e| server_fail_from_backend(&e))?;
371            Some((update, stored))
372        }
373        None => None,
374    };
375
376    let mut created = Map::new();
377    let mut not_created = Map::new();
378    for (creation_id, obj) in create.unwrap_or_default() {
379        let sent: HashSet<String> = obj
380            .as_object()
381            .map(|fields| fields.keys().cloned().collect())
382            .unwrap_or_default();
383        let new = match validate_create(obj) {
384            Ok(new) => new,
385            Err(err) => {
386                not_created.insert(creation_id, err);
387                continue;
388            }
389        };
390        match backend.create_push_subscription(caller, new).await {
391            Ok(stored) => {
392                created.insert(creation_id, created_value(&stored.subscription, &sent));
393            }
394            Err(e) => {
395                not_created.insert(creation_id, backend_set_error_value(e));
396            }
397        }
398    }
399
400    let mut updated = Map::new();
401    let mut not_updated = Map::new();
402    if let Some((update, stored)) = update_with_stored {
403        for (id, patch) in update {
404            let current = stored
405                .iter()
406                .find(|s| s.subscription.id.as_ref().map(AsRef::as_ref) == Some(id.as_str()));
407            match update_one(backend, caller, current, patch).await {
408                Ok(changed) => {
409                    updated.insert(id, changed);
410                }
411                Err(err) => {
412                    not_updated.insert(id, err);
413                }
414            }
415        }
416    }
417
418    let mut destroyed = Vec::new();
419    let mut not_destroyed = Map::new();
420    for id in destroy.unwrap_or_default() {
421        match backend.destroy_push_subscription(caller, &id).await {
422            Ok(()) => destroyed.push(Value::String(id.as_ref().to_owned())),
423            Err(e) => {
424                not_destroyed.insert(id.as_ref().to_owned(), backend_set_error_value(e));
425            }
426        }
427    }
428
429    let or_null = |m: Map<String, Value>| {
430        if m.is_empty() {
431            Value::Null
432        } else {
433            Value::Object(m)
434        }
435    };
436    Ok(HandlerOutput::new(json!({
437        "created": or_null(created),
438        "updated": or_null(updated),
439        "destroyed": if destroyed.is_empty() { Value::Null } else { Value::Array(destroyed) },
440        "notCreated": or_null(not_created),
441        "notUpdated": or_null(not_updated),
442        "notDestroyed": or_null(not_destroyed),
443    })))
444}
445
446/// The `created` entry for `sub`: every property the client did not send,
447/// plus `id` and `expires`, which the server always sets.
448///
449/// RFC 8620 §5.3 (rfc8620.txt:2034-2039): "created" holds "any properties
450/// of the created Foo object that were not sent by the client. This
451/// includes all server-set properties (such as the "id" in most object
452/// types) and any properties that were omitted by the client and thus set
453/// to a default by the server." `url` is always sent, so the url is never
454/// echoed, and `keys` is echoed only when it was omitted (and so is null).
455fn created_value(sub: &PushSubscription, sent: &HashSet<String>) -> Value {
456    let mut props = Map::new();
457    props.insert("id".to_owned(), json!(sub.id));
458    props.insert("deviceClientId".to_owned(), json!(sub.device_client_id));
459    props.insert("url".to_owned(), json!(sub.url));
460    props.insert("keys".to_owned(), json!(sub.keys));
461    props.insert("verificationCode".to_owned(), json!(sub.verification_code));
462    props.insert("expires".to_owned(), json!(sub.expires));
463    props.insert("types".to_owned(), json!(sub.types));
464    props.extend(sub.extra.clone());
465    props.retain(|k, _| k == "id" || k == "expires" || !sent.contains(k));
466    Value::Object(props)
467}
468
469/// Check one `create` entry and turn it into the subscription to store,
470/// with `expires` limited to [`MAX_PUSH_EXPIRY_SECS`] from now.
471///
472/// Returns the `notCreated` SetError on failure.
473fn validate_create(obj: Value) -> Result<PushSubscription, Value> {
474    let Value::Object(fields) = &obj else {
475        return Err(Value::from(
476            &SetError::new(SetErrorType::InvalidProperties)
477                .with_description("a create entry must be an object"),
478        ));
479    };
480    // RFC 8620 §1.1 (rfc8620.txt:261-262): the client MUST NOT send a
481    // server-set property when creating.
482    if let Some(err) = reject_server_set::<PushSubscription>(fields) {
483        return Err(Value::from(&err));
484    }
485    // RFC 8620 §7.2 (rfc8620.txt:3620-3621): "This MUST begin with
486    // "https://"."
487    if !fields
488        .get("url")
489        .and_then(Value::as_str)
490        .is_some_and(|url| url.starts_with("https://"))
491    {
492        return Err(invalid_property("url"));
493    }
494    // RFC 8620 §7.2 (rfc8620.txt:3649): "This MUST be null (or omitted) when
495    // the subscription is created."
496    if fields.get("verificationCode").is_some_and(|v| !v.is_null()) {
497        return Err(invalid_property("verificationCode"));
498    }
499    let mut new: PushSubscription = serde_json::from_value(obj).map_err(|e| {
500        Value::from(&SetError::new(SetErrorType::InvalidProperties).with_description(e.to_string()))
501    })?;
502    new.expires = Some(limit_expires(new.expires.as_ref())?);
503    Ok(new)
504}
505
506/// Apply one `update` entry to `current` and store the result.
507///
508/// Returns the `updated` value on success (`{"expires": ...}` when the
509/// stored expiry differs from the one the client asked for, else null) and
510/// the `notUpdated` SetError on failure.
511async fn update_one<B: PushSubscriptionBackend>(
512    backend: &B,
513    caller: &B::CallerCtx,
514    current: Option<&StoredPushSubscription>,
515    patch: Value,
516) -> Result<Value, Value> {
517    let Some(current) = current else {
518        return Err(Value::from(&SetError::new(SetErrorType::NotFound)));
519    };
520    let Value::Object(patch) = patch else {
521        return Err(Value::from(
522            &SetError::new(SetErrorType::InvalidPatch)
523                .with_description("a PatchObject must be an object"),
524        ));
525    };
526    let Value::Object(mut target) =
527        serialize_value(&current.subscription).map_err(|e| server_fail_value_from_backend(&e))?
528    else {
529        return Err(server_fail_value_from_backend(
530            "PushSubscription did not serialize to an object",
531        ));
532    };
533    let before = target.clone();
534    apply_patch_object(&mut target, &patch).map_err(|e| {
535        Value::from(&SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()))
536    })?;
537    // RFC 8620 §5.3 (rfc8620.txt:2141-2145): sending an immutable or
538    // server-set property is an error only if the value differs.
539    let changed_read_only = PushSubscription::SERVER_SET
540        .iter()
541        .chain(PushSubscription::IMMUTABLE)
542        .find(|p| before.get(**p) != target.get(**p));
543    let mut patched: PushSubscription =
544        serde_json::from_value(Value::Object(target)).map_err(|e| {
545            Value::from(
546                &SetError::new(SetErrorType::InvalidProperties).with_description(e.to_string()),
547            )
548        })?;
549
550    if let Some(property) = changed_read_only {
551        return Err(invalid_property(property));
552    }
553    let old = &current.subscription;
554
555    // RFC 8620 §7.2.2 (rfc8620.txt:3790-3792): "Attempts to update the
556    // subscription with an invalid verification code MUST be rejected by
557    // the server with an "invalidProperties" SetError."
558    if patched.verification_code != old.verification_code
559        && let Some(code) = &patched.verification_code
560        && !codes_match(code, &current.expected_code)
561    {
562        return Err(invalid_property("verificationCode"));
563    }
564
565    // RFC 8620 §7.2.2 (rfc8620.txt:3794-3798): "The server MAY modify the
566    // proposed new expiry time to enforce server-defined limits. Extending
567    // the lifetime does not require the subscription to be verified again."
568    let requested_expires = patched.expires.clone();
569    if requested_expires != old.expires {
570        patched.expires = Some(limit_expires(requested_expires.as_ref())?);
571    }
572
573    let stored = backend
574        .update_push_subscription(caller, patched)
575        .await
576        .map_err(backend_set_error_value)?;
577    // RFC 8620 §5.3 (rfc8620.txt:2048-2051): "updated" holds "any property
578    // that changed in a way *not* explicitly requested by the PatchObject".
579    Ok(if stored.expires == requested_expires {
580        Value::Null
581    } else {
582        json!({ "expires": stored.expires })
583    })
584}
585
586/// `requested`, or `None`'s default, limited to [`MAX_PUSH_EXPIRY_SECS`]
587/// from now.
588///
589/// Returns `invalidProperties` naming `expires` if `requested` is not a
590/// valid UTCDate, and `serverFail` if the system clock cannot be read.
591fn limit_expires(requested: Option<&UTCDate>) -> Result<UTCDate, Value> {
592    let clock_fail = || server_fail_value_from_backend("system clock out of range");
593    let (now, _) = signed_seconds_since_epoch(SystemTime::now()).ok_or_else(clock_fail)?;
594    let max = now
595        .checked_add(MAX_PUSH_EXPIRY_SECS)
596        .ok_or_else(clock_fail)?;
597    if let Some(requested) = requested {
598        let secs = requested
599            .to_epoch_seconds()
600            .map_err(|_| invalid_property("expires"))?;
601        if secs <= max {
602            return Ok(requested.clone());
603        }
604    }
605    utc_date_from_epoch_seconds(max).ok_or_else(clock_fail)
606}
607
608/// Whether a push may be sent to `stored` at `now_secs` seconds since the
609/// Unix epoch: the subscription is verified and has not expired.
610///
611/// RFC 8620 §7.2 (rfc8620.txt:3578-3581): "The JMAP server MUST NOT make
612/// any further requests to the URL until the client receives the push and
613/// updates the subscription with the correct verification code."
614///
615/// RFC 8620 §7.2 (rfc8620.txt:3656-3658): "If specified, the JMAP server
616/// MUST NOT make further requests to this resource after this time." A push
617/// at exactly `expires` is allowed. An `expires` that is not a valid
618/// UTCDate counts as expired.
619///
620/// This does not cover the `PushVerification` itself, which is sent before
621/// the subscription is verified.
622pub fn is_deliverable(stored: &StoredPushSubscription, now_secs: i64) -> bool {
623    let sub = &stored.subscription;
624    let verified = sub
625        .verification_code
626        .as_deref()
627        .is_some_and(|code| codes_match(code, &stored.expected_code));
628    let unexpired = match &sub.expires {
629        None => true,
630        Some(expires) => expires
631            .to_epoch_seconds()
632            .is_ok_and(|expires| now_secs <= expires),
633    };
634    verified && unexpired
635}
636
637/// The `StateChange` to push to `sub` for the `changed` map, or `None` if
638/// none of its types changed.
639///
640/// RFC 8620 §7.2 (rfc8620.txt:3669-3672): "A StateChange notification will
641/// only be sent if the data for one of these types changes. Other types are
642/// omitted from the TypeState object. If null, changes will be pushed for
643/// all types." Accounts left with no types are dropped.
644///
645/// This does not check which accounts the subscription's credentials may
646/// see; the caller passes only those.
647pub fn state_change_for(
648    sub: &PushSubscription,
649    changed: &BTreeMap<Id, BTreeMap<String, State>>,
650) -> Option<StateChange> {
651    let filtered: BTreeMap<Id, BTreeMap<String, State>> = changed
652        .iter()
653        .map(|(account, types)| {
654            let kept: BTreeMap<String, State> = types
655                .iter()
656                .filter(|(t, _)| sub.types.as_ref().is_none_or(|wanted| wanted.contains(t)))
657                .map(|(t, s)| (t.clone(), s.clone()))
658                .collect();
659            (account.clone(), kept)
660        })
661        .filter(|(_, kept)| !kept.is_empty())
662        .collect();
663    (!filtered.is_empty()).then(|| StateChange::new(filtered))
664}
665
666/// Compare a client-sent verification code with the expected one in
667/// constant time for equal lengths. Codes are fixed-length (see
668/// [`PushSubscriptionBackend::create_push_subscription`]), so a length
669/// mismatch reveals nothing secret.
670fn codes_match(sent: &str, expected: &str) -> bool {
671    sent.as_bytes().ct_eq(expected.as_bytes()).into()
672}
673
674/// An `invalidProperties` SetError naming `property`.
675fn invalid_property(property: &str) -> Value {
676    Value::from(&SetError::new(SetErrorType::InvalidProperties).with_properties([property]))
677}