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