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