jmap_server/backend.rs
1//! Shared backend infrastructure for all JMAP server crates.
2//!
3//! Re-exports the marker traits and the `SetError` types from `jmap-types` and adds the result types,
4//! `BackendChangesError`, `BackendQueryError`, and [`JmapBackend`] supertrait. Domain crates add
5//! their write-side methods and domain-specific error variants on top.
6
7pub use jmap_types::{
8 GetObject, JmapObject, QueryObject, ReservedExtrasKey, SetError, SetErrorType, SetObject,
9};
10
11/// Error type returned by create/update/destroy backend methods.
12#[non_exhaustive]
13#[derive(Debug)]
14pub enum BackendSetError<E> {
15 /// A well-typed JMAP [`SetError`] to place verbatim in the
16 /// `notCreated`/`notUpdated`/`notDestroyed` map.
17 ///
18 /// Boxed so the `Err` arm of a backend `Result` stays pointer-sized
19 /// (`SetError` is over 200 bytes; clippy `result_large_err`).
20 SetError(Box<SetError>),
21 /// An unexpected storage-layer error.
22 Other(E),
23}
24
25impl<E: std::fmt::Display> std::fmt::Display for BackendSetError<E> {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 match self {
28 Self::SetError(se) => write!(f, "set error: {se}"),
29 Self::Other(e) => write!(f, "{e}"),
30 }
31 }
32}
33
34impl<E: std::error::Error + 'static> std::error::Error for BackendSetError<E> {
35 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
36 match self {
37 Self::Other(e) => Some(e),
38 _ => None,
39 }
40 }
41}
42
43impl<E> From<SetError> for BackendSetError<E> {
44 fn from(e: SetError) -> Self {
45 Self::SetError(Box::new(e))
46 }
47}
48
49impl<E> From<Box<SetError>> for BackendSetError<E> {
50 fn from(e: Box<SetError>) -> Self {
51 Self::SetError(e)
52 }
53}
54
55impl<E: std::fmt::Display> BackendSetError<E> {
56 /// Split into the per-object [`SetError`] (`Ok`) or a redacted
57 /// method-level `serverFail` (`Err`).
58 ///
59 /// RFC 8620 §5.3 places a per-object `SetError` in the
60 /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
61 /// variant is returned unchanged for the caller to insert there.
62 /// [`Other`](Self::Other) becomes
63 /// `JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)`: the inner
64 /// error's `Display` text never reaches the wire (bd:JMAP-jfia.36).
65 ///
66 /// There is deliberately no `From<BackendSetError<E>> for JmapError`:
67 /// a `?` on that impl would turn per-object set errors into
68 /// method-level errors.
69 ///
70 /// [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
71 ///
72 /// # Errors
73 ///
74 /// Returns the redacted `serverFail` [`JmapError`](jmap_types::JmapError) for
75 /// [`Other`](Self::Other).
76 pub fn into_set_error_or_method_error(self) -> Result<SetError, jmap_types::JmapError> {
77 match self {
78 Self::SetError(se) => Ok(*se),
79 Self::Other(e) => Err(crate::handlers::server_fail_from_backend(&e)),
80 }
81 }
82}
83
84/// The `notCreated` / `notUpdated` / `notDestroyed` map value for a
85/// backend `/set` failure (RFC 8620 §5.3).
86///
87/// [`BackendSetError::SetError`] serializes verbatim;
88/// [`BackendSetError::Other`] becomes a `serverFail` with the fixed
89/// [`SERVER_FAIL_INTERNAL_DESC`](crate::SERVER_FAIL_INTERNAL_DESC)
90/// description, so the inner error's `Display` text never reaches the
91/// wire (bd:JMAP-jfia.36). Every `*-server` crate maps per-object backend
92/// errors through this one function.
93pub fn backend_set_error_value<E: std::fmt::Display>(err: BackendSetError<E>) -> serde_json::Value {
94 match err {
95 BackendSetError::SetError(se) => serde_json::Value::from(*se),
96 BackendSetError::Other(e) => crate::handlers::server_fail_value_from_backend(&e),
97 }
98}
99
100// ---------------------------------------------------------------------------
101// Backend error envelopes
102// ---------------------------------------------------------------------------
103
104/// Error type returned by [`JmapBackend::get_changes`] and
105/// [`JmapBackend::query_changes`].
106///
107/// The two non-`Other` variants map to the RFC 8620 §5.6 wire errors
108/// `cannotCalculateChanges` and `tooManyChanges`; `/changes` (§5.2) has
109/// only the former (see [`changes_error_from_backend`](crate::changes_error_from_backend)).
110#[non_exhaustive]
111#[derive(Debug)]
112pub enum BackendChangesError<E> {
113 /// The server has no usable change log for the given `sinceState`
114 /// and cannot supply incremental changes — the client MUST
115 /// discard ALL locally cached objects for the affected type,
116 /// reset its local state token to the empty string, and perform a
117 /// full resync (`/get` with `ids: null`). Partial recovery is not
118 /// permitted. Maps to `cannotCalculateChanges` (RFC 8620 §5.6;
119 /// authoritative behavior documented in jmapio/jmap-js
120 /// `mail-model.js`).
121 CannotCalculate,
122 /// The change window exceeds what the server can supply in a
123 /// single response. Maps to `tooManyChanges` with the `limit` as the
124 /// suggested maximum for `/queryChanges` (RFC 8620 §5.6). `/changes`
125 /// has no such error (§5.2), so
126 /// [`changes_error_from_backend`](crate::changes_error_from_backend)
127 /// maps it to `cannotCalculateChanges` there; a `get_changes` backend
128 /// over `maxChanges` SHOULD instead return an intermediate state with
129 /// `has_more_changes` set.
130 TooManyChanges {
131 /// Maximum window size the server can supply in a single
132 /// `/changes` response, the suggested maximum the client may
133 /// retry with.
134 limit: u64,
135 },
136 /// An unexpected storage-layer error.
137 Other(E),
138}
139
140impl<E: std::fmt::Display> std::fmt::Display for BackendChangesError<E> {
141 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 match self {
143 Self::CannotCalculate => write!(f, "cannot calculate changes"),
144 Self::TooManyChanges { limit } => write!(f, "too many changes (limit: {limit})"),
145 Self::Other(e) => write!(f, "{e}"),
146 }
147 }
148}
149
150impl<E: std::error::Error + 'static> std::error::Error for BackendChangesError<E> {
151 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
152 match self {
153 Self::Other(e) => Some(e),
154 _ => None,
155 }
156 }
157}
158
159impl<E> From<E> for BackendChangesError<E> {
160 fn from(e: E) -> Self {
161 Self::Other(e)
162 }
163}
164
165impl<E: std::error::Error> From<BackendChangesError<E>> for jmap_types::JmapError {
166 fn from(e: BackendChangesError<E>) -> Self {
167 match e {
168 BackendChangesError::CannotCalculate => {
169 jmap_types::JmapError::cannot_calculate_changes()
170 }
171 BackendChangesError::TooManyChanges { limit } => {
172 jmap_types::JmapError::too_many_changes_with_limit(limit)
173 }
174 // bd:JMAP-jfia.1 / bd:JMAP-wlip.2 — the `Other` arm wraps a
175 // backend `Error` whose `Display` impl is contractually
176 // forbidden from carrying credential/blob/PII text but which
177 // we still treat as untrusted at the wire boundary. Use the
178 // same static [`SERVER_FAIL_INTERNAL_DESC`] string that the
179 // [`server_fail_from_backend`] handler-layer helper uses so
180 // the defence-in-depth chain (backend Display contract →
181 // handler helper → this From impl) cannot be bypassed by
182 // handlers that take the ergonomic `.map_err(JmapError::from)?`
183 // path on `BackendChangesError`.
184 //
185 // [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
186 // [`server_fail_from_backend`]: crate::handlers::server_fail_from_backend
187 BackendChangesError::Other(_inner) => {
188 jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
189 }
190 }
191 }
192}
193
194/// Error type returned by [`JmapBackend::query_objects`].
195///
196/// RFC 8620 §5.5 lets a `/query` fail with method errors that only the
197/// backend can detect (`unsupportedFilter`, `unsupportedSort`,
198/// `anchorNotFound`, ...). [`Self::Method`] carries such an error to the
199/// client unchanged; [`Self::Other`] is an internal storage-layer failure
200/// that handlers surface as the redacted `serverFail`.
201#[non_exhaustive]
202#[derive(Debug)]
203pub enum BackendQueryError<E> {
204 /// An RFC 8620 §5.5 method error, returned to the client as-is
205 /// (type and description). Backends MUST NOT put internal error
206 /// text in it.
207 Method(jmap_types::JmapError),
208 /// An unexpected storage-layer error.
209 Other(E),
210}
211
212impl<E: std::fmt::Display> std::fmt::Display for BackendQueryError<E> {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 match self {
215 Self::Method(e) => write!(f, "{e}"),
216 Self::Other(e) => write!(f, "{e}"),
217 }
218 }
219}
220
221impl<E: std::error::Error + 'static> std::error::Error for BackendQueryError<E> {
222 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
223 match self {
224 Self::Method(_) => None,
225 Self::Other(e) => Some(e),
226 }
227 }
228}
229
230impl<E> From<E> for BackendQueryError<E> {
231 fn from(e: E) -> Self {
232 Self::Other(e)
233 }
234}
235
236impl<E> From<BackendQueryError<E>> for jmap_types::JmapError {
237 fn from(e: BackendQueryError<E>) -> Self {
238 match e {
239 BackendQueryError::Method(err) => err,
240 // Same redaction as `BackendChangesError::Other`: the backend
241 // error's text never reaches the wire.
242 BackendQueryError::Other(_inner) => {
243 jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
244 }
245 }
246 }
247}
248
249// ---------------------------------------------------------------------------
250// Result types
251// ---------------------------------------------------------------------------
252
253/// Result of a `/changes` call (RFC 8620 §5.2).
254#[derive(Debug)]
255#[non_exhaustive]
256pub struct ChangesResult {
257 /// Ids of objects that were created since `sinceState`.
258 pub created: Vec<jmap_types::Id>,
259 /// Ids of objects that were updated since `sinceState`.
260 pub updated: Vec<jmap_types::Id>,
261 /// Ids of objects that were destroyed since `sinceState`.
262 pub destroyed: Vec<jmap_types::Id>,
263 /// `true` if there are more changes beyond this batch.
264 pub has_more_changes: bool,
265 /// The current state token after applying all reported changes.
266 pub new_state: jmap_types::State,
267 /// The `updatedProperties` response argument (RFC 8621 §2.2,
268 /// draft-ietf-jmap-metadata-05 §3.3): the only properties that may
269 /// have changed on every id in [`updated`](Self::updated), or `None`
270 /// when any other property may have changed or the backend cannot
271 /// tell. [`crate::handle_changes`] sends `null` when `updated` is
272 /// empty, whatever this holds.
273 pub updated_properties: Option<Vec<String>>,
274}
275
276impl ChangesResult {
277 /// Construct a [`ChangesResult`].
278 pub fn new(
279 created: Vec<jmap_types::Id>,
280 updated: Vec<jmap_types::Id>,
281 destroyed: Vec<jmap_types::Id>,
282 has_more_changes: bool,
283 new_state: jmap_types::State,
284 ) -> Self {
285 Self {
286 created,
287 updated,
288 destroyed,
289 has_more_changes,
290 new_state,
291 updated_properties: None,
292 }
293 }
294
295 /// Set [`updated_properties`](Self::updated_properties); [`Self::new`]
296 /// leaves it `None`.
297 #[must_use]
298 pub fn with_updated_properties(mut self, updated_properties: Option<Vec<String>>) -> Self {
299 self.updated_properties = updated_properties;
300 self
301 }
302}
303
304/// Result of a `/query` call (RFC 8620 §5.5).
305#[derive(Debug)]
306#[non_exhaustive]
307pub struct QueryResult {
308 /// The ordered list of matching object ids.
309 pub ids: Vec<jmap_types::Id>,
310 /// The 0-based index of the first returned id in the complete result list.
311 ///
312 /// RFC 8620 §5.5 specifies this as `UnsignedInt` in the response —
313 /// a non-negative integer (bd:JMAP-wlip.25). The request-side
314 /// position parameter accepts negative values as end-relative
315 /// offsets, but the response position cannot validly be negative.
316 /// Backends that derive `position` from a request-side `i64`
317 /// offset MUST clamp / normalize to `u64` before constructing this
318 /// struct.
319 pub position: u64,
320 /// Total number of results, if the backend can calculate it.
321 pub total: Option<u64>,
322 /// Opaque query state token for subsequent `/queryChanges` calls.
323 pub query_state: jmap_types::State,
324 /// Whether the backend supports `/queryChanges` for this query.
325 pub can_calculate_changes: bool,
326}
327
328impl QueryResult {
329 /// Construct a [`QueryResult`].
330 pub fn new(
331 ids: Vec<jmap_types::Id>,
332 position: u64,
333 total: Option<u64>,
334 query_state: jmap_types::State,
335 can_calculate_changes: bool,
336 ) -> Self {
337 Self {
338 ids,
339 position,
340 total,
341 query_state,
342 can_calculate_changes,
343 }
344 }
345
346 /// Construct a [`QueryResult`] from a signed request-side position,
347 /// clamping negatives to `0` and normalizing to `u64`
348 /// (bd:JMAP-jfia.25).
349 ///
350 /// RFC 8620 §5.5 specifies the response `position` as `UnsignedInt`,
351 /// but the request-side `position` parameter accepts negative
352 /// values as end-relative offsets. Backends typically receive the
353 /// signed value, walk the offset into the result list, and need
354 /// to surface the resulting 0-based index. This constructor takes
355 /// the resolved-offset value and clamps to `u64`, matching the
356 /// spec contract.
357 ///
358 /// Negative inputs clamp to `0` (representing "the start of the
359 /// result list"). Backends that have already done the
360 /// offset-to-index resolution and have a `u64` already SHOULD use
361 /// the plain [`Self::new`] constructor instead.
362 pub fn new_clamped(
363 ids: Vec<jmap_types::Id>,
364 position_signed: i64,
365 total: Option<u64>,
366 query_state: jmap_types::State,
367 can_calculate_changes: bool,
368 ) -> Self {
369 // i64::max(_, 0) then cast to u64 — both fit in u64 because
370 // i64 >= 0 has range [0, i64::MAX], which is a strict subset
371 // of u64's range.
372 let position = u64::try_from(position_signed.max(0)).unwrap_or(0);
373 Self::new(ids, position, total, query_state, can_calculate_changes)
374 }
375}
376
377/// One entry in the `added` list of a `/queryChanges` response (RFC 8620 §5.6).
378#[derive(Debug)]
379#[non_exhaustive]
380pub struct AddedItem {
381 /// The id of the newly-added object.
382 pub id: jmap_types::Id,
383 /// Its 0-based position in the result list after applying all changes.
384 pub index: u64,
385}
386
387impl AddedItem {
388 /// Construct an [`AddedItem`].
389 pub fn new(id: jmap_types::Id, index: u64) -> Self {
390 Self { id, index }
391 }
392}
393
394/// Result of a `/queryChanges` call (RFC 8620 §5.6).
395#[derive(Debug)]
396#[non_exhaustive]
397pub struct QueryChangesResult {
398 /// The query state token supplied by the client in `sinceQueryState`.
399 pub old_query_state: jmap_types::State,
400 /// The current query state token.
401 pub new_query_state: jmap_types::State,
402 /// Total number of results in the new query, if the backend can calculate it.
403 pub total: Option<u64>,
404 /// Ids removed from the result set since `oldQueryState`.
405 pub removed: Vec<jmap_types::Id>,
406 /// Ids added to the result set since `oldQueryState`, with their positions.
407 pub added: Vec<AddedItem>,
408}
409
410impl QueryChangesResult {
411 /// Construct a [`QueryChangesResult`].
412 pub fn new(
413 old_query_state: jmap_types::State,
414 new_query_state: jmap_types::State,
415 total: Option<u64>,
416 removed: Vec<jmap_types::Id>,
417 added: Vec<AddedItem>,
418 ) -> Self {
419 Self {
420 old_query_state,
421 new_query_state,
422 total,
423 removed,
424 added,
425 }
426 }
427}
428
429// ---------------------------------------------------------------------------
430// Changes parameters
431// ---------------------------------------------------------------------------
432
433/// The `/changes` arguments (RFC 8620 §5.2) passed to
434/// [`JmapBackend::get_changes`], after `accountId`.
435///
436/// `#[non_exhaustive]` for the same reason as [`QueryParams`]. Build one
437/// with [`ChangesParams::new`], which takes the one required argument,
438/// `sinceState`, and the setters:
439///
440/// ```
441/// # use jmap_server::ChangesParams;
442/// let since = jmap_server::State::from("s1");
443/// let params = ChangesParams::new(&since).max_changes(Some(50));
444/// assert_eq!(params.max_changes, Some(50));
445/// assert!(!params.ignore_metadata_only_changes);
446/// ```
447#[derive(Debug, Clone, Copy)]
448#[non_exhaustive]
449pub struct ChangesParams<'a> {
450 /// `sinceState`, the state the client already has.
451 pub since_state: &'a jmap_types::State,
452 /// `maxChanges`; `None` means no client limit.
453 pub max_changes: Option<u64>,
454 /// `ignoreMetadataOnlyChanges` (draft-ietf-jmap-metadata-05 §3.3):
455 /// when `true`, a backend that tracks per-update changed properties
456 /// MUST leave out of `updated` every id whose only changes are to
457 /// `metadata` and/or `privateMetadata`, and those ids do not count
458 /// toward `max_changes`. [`crate::handle_changes`] sets it `true`
459 /// for a request whose `using` lacks `urn:ietf:params:jmap:metadata`
460 /// (-05 §3). A backend that does not support metadata ignores it.
461 pub ignore_metadata_only_changes: bool,
462}
463
464impl<'a> ChangesParams<'a> {
465 /// Changes since `since_state`, with no `maxChanges` and
466 /// `ignoreMetadataOnlyChanges` false (its -05 §3.3 default).
467 pub fn new(since_state: &'a jmap_types::State) -> Self {
468 Self {
469 since_state,
470 max_changes: None,
471 ignore_metadata_only_changes: false,
472 }
473 }
474
475 /// Set [`max_changes`](Self::max_changes).
476 #[must_use]
477 pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
478 self.max_changes = max_changes;
479 self
480 }
481
482 /// Set [`ignore_metadata_only_changes`](Self::ignore_metadata_only_changes).
483 #[must_use]
484 pub fn ignore_metadata_only_changes(mut self, ignore: bool) -> Self {
485 self.ignore_metadata_only_changes = ignore;
486 self
487 }
488}
489
490// ---------------------------------------------------------------------------
491// Query parameters
492// ---------------------------------------------------------------------------
493
494/// The `/query` arguments (RFC 8620 §5.5) passed to
495/// [`JmapBackend::query_objects`], after `accountId`.
496///
497/// `#[non_exhaustive]` so a new RFC or extension argument is a new field,
498/// not a breaking change to every backend (bd:JMAP-wf92.7). Backends read
499/// the public fields; callers build one with [`QueryParams::new`] and the
500/// setters:
501///
502/// ```
503/// # use jmap_server::{JmapObject, QueryObject, QueryParams};
504/// # #[derive(serde::Serialize, serde::Deserialize)]
505/// # struct Foo;
506/// # impl JmapObject for Foo { const TYPE_NAME: &'static str = "Foo"; type Property = (); }
507/// # impl QueryObject for Foo { type Filter = serde_json::Value; type Comparator = serde_json::Value; }
508/// let filter = serde_json::json!({"text": "hello"});
509/// let params = QueryParams::<Foo>::new().filter(Some(&filter)).limit(Some(50));
510/// assert_eq!(params.position, 0);
511/// ```
512#[non_exhaustive]
513pub struct QueryParams<'a, O: QueryObject> {
514 /// `filter`; `None` matches every object.
515 pub filter: Option<&'a O::Filter>,
516 /// `sort`; `None` leaves the order to the server.
517 pub sort: Option<&'a [O::Comparator]>,
518 /// `limit`; `None` means no client limit.
519 pub limit: Option<u64>,
520 /// `position`. Negative values count from the end of the results
521 /// (RFC 8620 §5.5); ignored when `anchor` is set.
522 pub position: i64,
523 /// `anchor`: start the page at this id's index instead of `position`.
524 pub anchor: Option<&'a jmap_types::Id>,
525 /// `anchorOffset`, added to the anchor's index; ignored without an
526 /// `anchor`.
527 pub anchor_offset: i64,
528}
529
530impl<'a, O: QueryObject> QueryParams<'a, O> {
531 /// The RFC 8620 §5.5 defaults: no filter, sort, limit or anchor, and
532 /// `position` and `anchorOffset` 0.
533 pub fn new() -> Self {
534 Self {
535 filter: None,
536 sort: None,
537 limit: None,
538 position: 0,
539 anchor: None,
540 anchor_offset: 0,
541 }
542 }
543
544 /// Set [`filter`](Self::filter).
545 #[must_use]
546 pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
547 self.filter = filter;
548 self
549 }
550
551 /// Set [`sort`](Self::sort).
552 #[must_use]
553 pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
554 self.sort = sort;
555 self
556 }
557
558 /// Set [`limit`](Self::limit).
559 #[must_use]
560 pub fn limit(mut self, limit: Option<u64>) -> Self {
561 self.limit = limit;
562 self
563 }
564
565 /// Set [`position`](Self::position).
566 #[must_use]
567 pub fn position(mut self, position: i64) -> Self {
568 self.position = position;
569 self
570 }
571
572 /// Set [`anchor`](Self::anchor).
573 #[must_use]
574 pub fn anchor(mut self, anchor: Option<&'a jmap_types::Id>) -> Self {
575 self.anchor = anchor;
576 self
577 }
578
579 /// Set [`anchor_offset`](Self::anchor_offset).
580 #[must_use]
581 pub fn anchor_offset(mut self, anchor_offset: i64) -> Self {
582 self.anchor_offset = anchor_offset;
583 self
584 }
585}
586
587impl<O: QueryObject> Default for QueryParams<'_, O> {
588 fn default() -> Self {
589 Self::new()
590 }
591}
592
593// Manual impls: derives would wrongly require `O: Clone` / `O: Debug`.
594impl<O: QueryObject> Clone for QueryParams<'_, O> {
595 fn clone(&self) -> Self {
596 *self
597 }
598}
599
600impl<O: QueryObject> Copy for QueryParams<'_, O> {}
601
602impl<O: QueryObject> std::fmt::Debug for QueryParams<'_, O>
603where
604 O::Filter: std::fmt::Debug,
605 O::Comparator: std::fmt::Debug,
606{
607 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
608 f.debug_struct("QueryParams")
609 .field("filter", &self.filter)
610 .field("sort", &self.sort)
611 .field("limit", &self.limit)
612 .field("position", &self.position)
613 .field("anchor", &self.anchor)
614 .field("anchor_offset", &self.anchor_offset)
615 .finish()
616 }
617}
618
619/// The `/queryChanges` arguments (RFC 8620 §5.6) passed to
620/// [`JmapBackend::query_changes`], after `accountId`.
621///
622/// `#[non_exhaustive]` for the same reason as [`QueryParams`]. Build one
623/// with [`QueryChangesParams::new`], which takes the one required
624/// argument, `sinceQueryState`, and the setters.
625#[non_exhaustive]
626pub struct QueryChangesParams<'a, O: QueryObject> {
627 /// `sinceQueryState`, the `queryState` the client already has.
628 pub since_query_state: &'a jmap_types::State,
629 /// `filter`, as passed to the original `/query`.
630 pub filter: Option<&'a O::Filter>,
631 /// `sort`, as passed to the original `/query`.
632 pub sort: Option<&'a [O::Comparator]>,
633 /// `maxChanges`; `None` means no client limit.
634 pub max_changes: Option<u64>,
635 /// `upToId`: the last id in the client's cached results.
636 pub up_to_id: Option<&'a jmap_types::Id>,
637 /// `collapseThreads`, meaningful only for `Email/queryChanges`
638 /// (RFC 8621 §4.5); `false` for every other type.
639 pub collapse_threads: bool,
640}
641
642impl<'a, O: QueryObject> QueryChangesParams<'a, O> {
643 /// Changes since `since_query_state`, with no filter, sort,
644 /// `maxChanges` or `upToId`, and `collapseThreads` false.
645 pub fn new(since_query_state: &'a jmap_types::State) -> Self {
646 Self {
647 since_query_state,
648 filter: None,
649 sort: None,
650 max_changes: None,
651 up_to_id: None,
652 collapse_threads: false,
653 }
654 }
655
656 /// Set [`filter`](Self::filter).
657 #[must_use]
658 pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
659 self.filter = filter;
660 self
661 }
662
663 /// Set [`sort`](Self::sort).
664 #[must_use]
665 pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
666 self.sort = sort;
667 self
668 }
669
670 /// Set [`max_changes`](Self::max_changes).
671 #[must_use]
672 pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
673 self.max_changes = max_changes;
674 self
675 }
676
677 /// Set [`up_to_id`](Self::up_to_id).
678 #[must_use]
679 pub fn up_to_id(mut self, up_to_id: Option<&'a jmap_types::Id>) -> Self {
680 self.up_to_id = up_to_id;
681 self
682 }
683
684 /// Set [`collapse_threads`](Self::collapse_threads).
685 #[must_use]
686 pub fn collapse_threads(mut self, collapse_threads: bool) -> Self {
687 self.collapse_threads = collapse_threads;
688 self
689 }
690}
691
692impl<O: QueryObject> Clone for QueryChangesParams<'_, O> {
693 fn clone(&self) -> Self {
694 *self
695 }
696}
697
698impl<O: QueryObject> Copy for QueryChangesParams<'_, O> {}
699
700impl<O: QueryObject> std::fmt::Debug for QueryChangesParams<'_, O>
701where
702 O::Filter: std::fmt::Debug,
703 O::Comparator: std::fmt::Debug,
704{
705 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
706 f.debug_struct("QueryChangesParams")
707 .field("since_query_state", &self.since_query_state)
708 .field("filter", &self.filter)
709 .field("sort", &self.sort)
710 .field("max_changes", &self.max_changes)
711 .field("up_to_id", &self.up_to_id)
712 .field("collapse_threads", &self.collapse_threads)
713 .finish()
714 }
715}
716
717// ---------------------------------------------------------------------------
718// JmapBackend — the read-side supertrait
719// ---------------------------------------------------------------------------
720
721/// Read-side backend supertrait shared by all JMAP server crates.
722///
723/// Domain-specific backend traits (`MailBackend`, `ChatBackend`, etc.) require
724/// this trait as a supertrait and add write-side methods on top.
725///
726/// Only the read operations that have an identical signature across all JMAP
727/// object types belong here. Write operations (`create_object`, `update_object`,
728/// `destroy_object`) and domain-specific operations remain in the domain crate.
729///
730/// [`QueryChangesParams::collapse_threads`] is included for
731/// `Email/queryChanges` (RFC 8621 §4.5). Non-mail backends may ignore it.
732///
733/// This trait is not object-safe by design (generic methods). Use
734/// `Arc<impl JmapBackend>` when sharing across tasks.
735///
736/// # CallerCtx
737///
738/// Every backend method takes a `caller: &Self::CallerCtx` parameter as the
739/// first argument after `&self`. This is the per-request authentication /
740/// authorisation context produced by the caller's auth layer and forwarded
741/// unchanged through [`crate::Dispatcher::dispatch`] → [`crate::JmapHandler`]
742/// → the registered closure → the backend.
743///
744/// Implementations that do not need an auth identity can use the unit type:
745///
746/// ```rust,ignore
747/// impl JmapBackend for MyBackend {
748/// type Error = MyError;
749/// type CallerCtx = ();
750/// // ...
751/// }
752/// ```
753///
754/// Implementations that do need to differentiate behaviour per caller (e.g.
755/// applying per-user visibility rules, or rejecting reads with
756/// `forbidden` when the caller is not the owner of the account) read the
757/// `caller` parameter to decide.
758///
759/// The trait bound `Clone + Send + 'static` is what [`crate::Dispatcher`]
760/// requires; the bound is repeated here so the supertrait can stand on its
761/// own without depending on the dispatcher.
762pub trait JmapBackend: Send + Sync + 'static {
763 /// The error type returned by storage operations.
764 ///
765 /// # Security
766 ///
767 /// The `Display` impl of this type is surfaced through
768 /// [`BackendSetError::Other`]'s and [`BackendChangesError::Other`]'s
769 /// own `Display` impls, which in turn flow into
770 /// [`crate::request_error`]'s `RequestError::Display` output. When a
771 /// downstream consumer wires tracing-style logging on top, the
772 /// formatted error text lands in operator logs verbatim.
773 ///
774 /// Implementations MUST NOT include any of the following in this
775 /// type's `Display` output:
776 ///
777 /// - **Credential material** — auth tokens, passwords, push
778 /// verification codes, invite codes, session cookies, or anything
779 /// derived byte-for-byte from an `Authorization`-header value.
780 /// - **Blob content** — email bodies, sieve scripts, file contents,
781 /// or any user-supplied opaque payload. An error like
782 /// `"sieve parse error at line 42: <script excerpt>"` violates
783 /// this — emit the line number and a short type-only summary
784 /// ("sieve parse error at line 42: unexpected token") and let the
785 /// server log the full script body separately under a redacted
786 /// path.
787 /// - **PII shaped like an email address** in any code path that an
788 /// unauthenticated caller can trigger. Wrapping a downstream
789 /// service error that interpolates the caller's email is the
790 /// common foot-gun.
791 ///
792 /// Errors that wrap a downstream-service failure should sanitize
793 /// the downstream error text — or strip it entirely and replace it
794 /// with a static summary — before constructing the `Display`
795 /// string. The same rule applies to every extension `*Backend`
796 /// trait that inherits this associated type by transitivity:
797 /// `MailBackend::Error`, `ChatBackend::Error`,
798 /// `CalendarsBackend::Error`, `TasksBackend::Error`,
799 /// `ContactsBackend::Error`, `FileNodeBackend::Error`, and
800 /// `SharingBackend::Error` are all the same `JmapBackend::Error`
801 /// associated type — the contract here governs all of them.
802 ///
803 /// Precedent: bd:JMAP-sc1b.79 redacted `BearerAuth` and `BasicAuth`
804 /// at the type-derive level; bd:JMAP-sc1b.100 documents the
805 /// equivalent contract at the trait-associated-type level.
806 type Error: std::error::Error + Send + Sync + 'static;
807
808 /// The per-request caller context type produced by the auth layer and
809 /// forwarded by [`crate::Dispatcher::dispatch`] into every method call.
810 ///
811 /// Use `()` when no auth context is needed.
812 ///
813 /// The bound is `Clone + Send + Sync + 'static`:
814 /// - `Clone` because [`crate::Dispatcher`] clones the value once per
815 /// method call in the batch.
816 /// - `Send + 'static` because each method call is spawned on a
817 /// [`tokio::task`].
818 /// - `Sync` because handler method bodies take `&Self::CallerCtx`
819 /// and hold that reference across `.await` boundaries inside a
820 /// `Send` future (a `&T` is `Send` iff `T: Sync`).
821 type CallerCtx: Clone + Send + Sync + 'static;
822
823 /// Return `true` if the given account exists in this backend.
824 ///
825 /// Handlers call this at the start of each method to return
826 /// `accountNotFound` (RFC 8620 §3.6.2) rather than surfacing
827 /// the wrong error when `accountId` is unknown.
828 ///
829 /// # Performance contract (bd:JMAP-jfia.27)
830 ///
831 /// Implementations SHOULD return in sub-millisecond time. The
832 /// JMAP standard handlers (`handle_get`, `handle_changes`,
833 /// `handle_query`, `handle_query_changes`) each call
834 /// `account_exists` at the START of the method, BEFORE delegating
835 /// to the per-domain backend. A typical JMAP request batch is
836 /// 4–16 method calls; a naive remote round-trip per call would
837 /// add 4–16× the network latency to every batch.
838 ///
839 /// Acceptable backing strategies: in-memory cache (the
840 /// reference `MemoryBackend` impls all use this); an indexed
841 /// primary-key lookup against a local database; a bloom filter
842 /// for negative lookups paired with a cache for positives. A
843 /// naive `SELECT 1 FROM accounts WHERE id = ?` against a remote
844 /// database is INCORRECT for this method even though it would
845 /// return the right value — the round-trip cost is the bug.
846 ///
847 /// The dispatcher does not cache this call across the method
848 /// calls in a single batch (workspace-architectural decision —
849 /// the dispatcher is intentionally stateless across the batch
850 /// loop). Caching is the backend implementor's responsibility.
851 fn account_exists(
852 &self,
853 caller: &Self::CallerCtx,
854 account_id: &jmap_types::Id,
855 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;
856
857 /// Fetch objects by id (or all objects when `ids` is `None`).
858 ///
859 /// `properties` is the list of property names requested by the client
860 /// (RFC 8620 §5.1). `None` means the client did not send a `properties`
861 /// field; the backend should return all properties. When `Some`, the backend
862 /// MAY filter the response to only the named properties, but is not required
863 /// to — implementations that always return all properties are correct.
864 ///
865 /// Returns `(found, not_found)` — objects that exist and ids that do not.
866 ///
867 /// # Unknown `account_id`
868 ///
869 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
870 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
871 /// [`Self::account_exists`] before calling this method and return
872 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
873 /// need not repeat that check. A caller that bypasses those handlers can
874 /// still reach this method with an unknown account; backends SHOULD then
875 /// return `Ok` with an empty `found` list and every requested id in `not_found`. Returning `Err` is permitted but surfaces as
876 /// `serverFail`, not `accountNotFound`.
877 fn get_objects<O: GetObject + Send + Sync>(
878 &self,
879 caller: &Self::CallerCtx,
880 account_id: &jmap_types::Id,
881 ids: Option<&[jmap_types::Id]>,
882 properties: Option<&[String]>,
883 ) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send;
884
885 /// Return the current state token for an object type in the given account.
886 ///
887 /// # Unknown `account_id`
888 ///
889 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
890 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
891 /// [`Self::account_exists`] before calling this method and return
892 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
893 /// need not repeat that check. A caller that bypasses those handlers can
894 /// still reach this method with an unknown account; backends SHOULD then
895 /// return `Ok` with the state token an empty account would report. Returning `Err` is permitted but surfaces as
896 /// `serverFail`, not `accountNotFound`.
897 fn get_state<O: JmapObject + Send + Sync>(
898 &self,
899 caller: &Self::CallerCtx,
900 account_id: &jmap_types::Id,
901 ) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send;
902
903 /// Return changes since `params.since_state`, up to
904 /// `params.max_changes` entries, honouring
905 /// `params.ignore_metadata_only_changes` (see [`ChangesParams`]).
906 ///
907 /// # Unknown `account_id`
908 ///
909 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
910 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
911 /// [`Self::account_exists`] before calling this method and return
912 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
913 /// need not repeat that check. A caller that bypasses those handlers can
914 /// still reach this method with an unknown account; backends SHOULD then
915 /// return `Ok` with a [`ChangesResult`] whose change lists are empty. Returning `Err` is permitted but surfaces as
916 /// `serverFail`, not `accountNotFound`.
917 fn get_changes<O: JmapObject + Send + Sync>(
918 &self,
919 caller: &Self::CallerCtx,
920 account_id: &jmap_types::Id,
921 params: ChangesParams<'_>,
922 ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;
923
924 /// Execute a `/query` and return a page of matching ids.
925 ///
926 /// `params.position` may be negative — negative values are relative to
927 /// the end of the result set per RFC 8620 §5.5 (e.g. -1 means the last
928 /// result).
929 ///
930 /// `params.anchor` and `params.anchor_offset` are the RFC 8620 §5.5
931 /// `anchor` and `anchorOffset` arguments. With an `anchor`, `position` MUST be
932 /// ignored and the page starts at the anchor's index in the filtered,
933 /// sorted results plus `anchor_offset`, clamped to 0; an anchor not in
934 /// the results is [`JmapError::anchor_not_found`] via
935 /// [`BackendQueryError::Method`]. Without one, `anchor_offset` MUST be
936 /// ignored. [`QueryResult::position`] is the page's actual start index.
937 /// [`crate::resolve_query_start`] implements this over an in-memory id
938 /// list.
939 ///
940 /// [`JmapError::anchor_not_found`]: jmap_types::JmapError::anchor_not_found
941 ///
942 /// # Filter and sort handling
943 ///
944 /// Implementations MUST honour the supplied `filter` and `sort` arguments
945 /// efficiently — typically by pushing both into the indexed storage layer
946 /// (database WHERE / ORDER BY, search index, etc.). Returning every
947 /// matching id and relying on the caller to paginate after the fact
948 /// degenerates to O(n) per page for IMAP-migration accounts.
949 ///
950 /// Handler implementations in `jmap-*-server` crates SHOULD NOT
951 /// post-filter or post-sort the backend's result; doing so re-introduces
952 /// the O(n) cost this method exists to avoid. The Mailbox handler in
953 /// `jmap-mail-server` is the canonical example of pushing filter/sort
954 /// fully into the backend.
955 ///
956 /// # Errors
957 ///
958 /// Return [`BackendQueryError::Method`] for an RFC 8620 §5.5 method
959 /// error (`unsupportedFilter`, `unsupportedSort`, `anchorNotFound`,
960 /// ...); handlers pass it to the client unchanged. Return
961 /// [`BackendQueryError::Other`] (or use `?` on `Self::Error`) for an
962 /// internal failure; handlers surface it as a redacted `serverFail`.
963 ///
964 /// # Unknown `account_id`
965 ///
966 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
967 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
968 /// [`Self::account_exists`] before calling this method and return
969 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
970 /// need not repeat that check. A caller that bypasses those handlers can
971 /// still reach this method with an unknown account; backends SHOULD then
972 /// return `Ok` with an empty [`QueryResult`] page. Returning `Err` is permitted but surfaces as
973 /// `serverFail`, not `accountNotFound`.
974 fn query_objects<O: QueryObject + Send + Sync>(
975 &self,
976 caller: &Self::CallerCtx,
977 account_id: &jmap_types::Id,
978 params: QueryParams<'_, O>,
979 ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;
980
981 /// Execute a `/queryChanges` and return deltas since `since_query_state`.
982 ///
983 /// `params.collapse_threads` is only meaningful for `Email/queryChanges`
984 /// (RFC 8621 §4.5); it is `false` for all other object types.
985 ///
986 /// # Unknown `account_id`
987 ///
988 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
989 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
990 /// [`Self::account_exists`] before calling this method and return
991 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
992 /// need not repeat that check. A caller that bypasses those handlers can
993 /// still reach this method with an unknown account; backends SHOULD then
994 /// return `Ok` with a [`QueryChangesResult`] whose `removed` and `added` lists are empty. Returning `Err` is permitted but surfaces as
995 /// `serverFail`, not `accountNotFound`.
996 fn query_changes<O: QueryObject + Send + Sync>(
997 &self,
998 caller: &Self::CallerCtx,
999 account_id: &jmap_types::Id,
1000 params: QueryChangesParams<'_, O>,
1001 ) -> impl std::future::Future<
1002 Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
1003 > + Send;
1004
1005 /// The caller's stable identity within this account namespace.
1006 ///
1007 /// Returns `None` for deployments that have not wired identity
1008 /// (test fixtures, single-user dev servers). A `None`-returning
1009 /// backend CANNOT honor JMAP semantics that depend on caller
1010 /// identity — chat role-hierarchy, calendar ACLs, sharing/myRights,
1011 /// per-user $seen on shared mailboxes, per-user metadata
1012 /// `privateMetadata` filtering, etc. Authentication is still the HTTP
1013 /// layer's job; this method exposes the result of that
1014 /// authentication to the JMAP layer for in-method semantics.
1015 ///
1016 /// Implementations MUST NOT mint identity — they MUST read it
1017 /// from the `CallerCtx` populated by the HTTP/auth middleware
1018 /// before `dispatch()` was called.
1019 ///
1020 /// Backends that honor identity-dependent semantics MUST override
1021 /// this method. Handlers and downstream backend traits MAY rely on
1022 /// it being correct when it returns `Some`.
1023 ///
1024 /// # Why an associated function and not a method (bd:JMAP-wlip.6 / bd:JMAP-jfia.13)
1025 ///
1026 /// The signature deliberately takes `caller: &Self::CallerCtx`
1027 /// without a `&self` receiver. Backends therefore have no access
1028 /// to their own storage state from inside `principal_id`. The
1029 /// auth-layer middleware MUST pre-resolve the principal (e.g. map
1030 /// a JWT `sub` claim to a local `Id` via an internal lookup) and
1031 /// stash the result inside `CallerCtx` *before* it calls
1032 /// `dispatch`. The JMAP layer reads the pre-resolved value here;
1033 /// no JIT lookup is possible.
1034 ///
1035 /// This is a structural enforcement of the "identity is not the
1036 /// JMAP layer's job to mint" rule. A consumer that wants
1037 /// JIT-resolved identity (e.g. database-backed JWT → principal
1038 /// mapping) wires that mapping into the HTTP layer's `CallerCtx`
1039 /// construction step instead of trying to fit it inside the
1040 /// backend's `principal_id` impl.
1041 ///
1042 /// **Decision record (bd:JMAP-jfia.13)**: a future reviewer or AI
1043 /// tool will reasonably suggest "this is an oversight, surely the
1044 /// backend wants `&self` access to its identity store" and propose
1045 /// `fn principal_id(&self, caller: ...) -> ...`. That suggestion
1046 /// is **WRONG** and must be rejected: the function-vs-method
1047 /// distinction is the structural enforcement of the no-JIT-lookup
1048 /// policy. Comments alone could be ignored; the type system makes
1049 /// the wrong thing impossible. Defending this shape protects the
1050 /// workspace identity-seam policy from drift.
1051 fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
1052 let _ = caller;
1053 None
1054 }
1055
1056 /// Maximum number of objects this account permits in a single
1057 /// `/set` call (RFC 8620 §5.3 `maxObjectsInSet`) (bd:JMAP-ayoz.41.1).
1058 ///
1059 /// Counts the sum of `create` + `update` + `destroy` entries in the
1060 /// wire arguments. Handlers MUST enforce this at the top of every
1061 /// `handle_*_set` via [`crate::helpers::enforce_max_objects_in_set`]
1062 /// so a single batched request cannot drive O(M·N) work against
1063 /// the storage layer.
1064 ///
1065 /// The default value `500` mirrors the workspace's testjig Session
1066 /// JSON advertised cap and matches common Fastmail / Cyrus IMAP
1067 /// server defaults. The cap is a *floor* on permissiveness, not a
1068 /// floor on capability — backends MAY override per account (Free vs
1069 /// Pro tier, multi-tenant SaaS, etc.). The `caller` and `account_id`
1070 /// arguments are passed even though the default impl ignores them
1071 /// so production backends can vary without an API break.
1072 ///
1073 /// Returning `0` makes every non-empty `/set` call fail with
1074 /// `requestTooLarge` (defensive read-only mode). Returning
1075 /// `u64::MAX` effectively disables the cap (NOT recommended — the
1076 /// cap is a DoS defence and disabling it forfeits that defence).
1077 ///
1078 /// # Why on `JmapBackend` and not a per-extension `XxxLimits` struct
1079 ///
1080 /// `maxObjectsInSet` is RFC 8620 §5.3 base-protocol scope, not an
1081 /// extension concept. Putting it on the foundation supertrait
1082 /// covers all 8 extension server crates with one default impl;
1083 /// per-extension `XxxLimits` structs are the right shape for
1084 /// extension-specific caps (per-Space content limits, per-Mailbox
1085 /// message size, etc. per workspace AGENTS.md "Backend caps and
1086 /// limits") but are out of scope here.
1087 fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1088 let _ = (caller, account_id);
1089 500
1090 }
1091
1092 /// Maximum number of ids this account permits in a single `/get`
1093 /// call (RFC 8620 §5.1 `maxObjectsInGet`) (bd:JMAP-yt1w.31).
1094 ///
1095 /// Handlers MUST enforce this at the top of every `/get` handler via
1096 /// [`crate::helpers::enforce_max_objects_in_get`]; the generic
1097 /// [`handle_get`](crate::handle_get) already does. A null `ids` (fetch
1098 /// all) is not counted.
1099 ///
1100 /// The default value `500` is the RFC 8620 §2 suggested minimum and
1101 /// mirrors [`JmapBackend::max_objects_in_set`]. Backends MAY override
1102 /// per account; the `caller` and `account_id` arguments exist for
1103 /// that. Keep the value in step with the `maxObjectsInGet` advertised
1104 /// in the Session object.
1105 fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1106 let _ = (caller, account_id);
1107 500
1108 }
1109
1110 /// The draft-ietf-jmap-metadata-05 §1.2.1 DataTypeMetadataInfo of `O`
1111 /// in `account_id`, as seen by `caller`, or [`None`] when the account's
1112 /// `urn:ietf:params:jmap:metadata` capability does not list `O`.
1113 ///
1114 /// Handlers use it where the wire shape depends on it: `Foo/get`
1115 /// returns `metadata` as an object (`{}` when nothing is stored),
1116 /// applies the `metadata/` subselectors and never returns
1117 /// `privateMetadata` when `supportsPrivate` is false (-05 §2, §3.1,
1118 /// through [`MetadataProjection`](crate::MetadataProjection));
1119 /// `Foo/copy` copies neither property into an account that does not
1120 /// list `O` (-05 §3.4). Keep it in step with the `dataTypes`
1121 /// advertised in the Session object.
1122 ///
1123 /// Default: [`None`], a backend without metadata.
1124 fn metadata_info<O: JmapObject>(
1125 &self,
1126 caller: &Self::CallerCtx,
1127 account_id: &jmap_types::Id,
1128 ) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
1129 let _ = (caller, account_id);
1130 None
1131 }
1132}
1133
1134// ---------------------------------------------------------------------------
1135// Tests
1136// ---------------------------------------------------------------------------
1137
1138#[cfg(test)]
1139mod tests {
1140 use super::*;
1141
1142 /// Oracle (RFC 8620 §5.6): `CannotCalculate` maps to the
1143 /// `cannotCalculateChanges` wire error.
1144 #[test]
1145 fn backend_changes_error_cannot_calculate_maps_to_cannot_calculate_changes() {
1146 let err = jmap_types::JmapError::from(
1147 BackendChangesError::<std::convert::Infallible>::CannotCalculate,
1148 );
1149 assert_eq!(
1150 err.error_type.to_string(),
1151 "cannotCalculateChanges",
1152 "CannotCalculate must produce cannotCalculateChanges; got: {:?}",
1153 err.error_type
1154 );
1155 }
1156
1157 /// Oracle: BackendChangesError::TooManyChanges { limit: N } (N > 0) maps to
1158 /// tooManyChanges with the suggested limit.
1159 #[test]
1160 fn backend_changes_error_nonzero_limit_maps_to_too_many_changes() {
1161 let err = jmap_types::JmapError::from(
1162 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 50 },
1163 );
1164 assert_eq!(
1165 err.error_type.to_string(),
1166 "tooManyChanges",
1167 "limit=50 must produce tooManyChanges; got: {:?}",
1168 err.error_type
1169 );
1170 }
1171
1172 /// Oracle (CHANGELOG, fc81085f): "A zero limit now maps to
1173 /// tooManyChanges like any other value", so `limit: 0` is not an alias
1174 /// for `cannotCalculateChanges`. Expected wire object is hand-written.
1175 #[test]
1176 fn backend_changes_error_zero_limit_maps_to_too_many_changes() {
1177 let err = jmap_types::JmapError::from(
1178 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
1179 );
1180 assert_eq!(
1181 serde_json::to_value(&err).unwrap(),
1182 serde_json::json!({"type": "tooManyChanges", "limit": 0})
1183 );
1184 }
1185
1186 /// Oracle (bd:JMAP-jfia.1 / bd:JMAP-wlip.2): the
1187 /// `From<BackendChangesError<E>> for JmapError` impl MUST NOT echo
1188 /// the wrapped backend error's `Display` text into the resulting
1189 /// `JmapError`'s description. The defence-in-depth contract is that
1190 /// even if a backend implementor accidentally violates the
1191 /// [`JmapBackend::Error`] Display MUST-NOT (credential / blob /
1192 /// PII), the leaked text never reaches the wire — and the
1193 /// ergonomic `.map_err(JmapError::from)?` path that
1194 /// `handle_changes` / `handle_query_changes` take on
1195 /// `BackendChangesError` must redact identically to the explicit
1196 /// `server_fail_from_backend(&e)` helper used elsewhere.
1197 ///
1198 /// Test vector: an `Other` variant whose Display contains a canary
1199 /// string resembling a credential leak. The canary literal is
1200 /// hand-built and not derived from any production type's
1201 /// behaviour. Mirrors
1202 /// `server_fail_from_backend_drops_display_text` in
1203 /// `handlers.rs`.
1204 #[test]
1205 fn backend_changes_error_other_drops_display_text() {
1206 #[derive(Debug)]
1207 struct LeakyError(&'static str);
1208 impl std::fmt::Display for LeakyError {
1209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1210 f.write_str(self.0)
1211 }
1212 }
1213 impl std::error::Error for LeakyError {}
1214
1215 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1216 let err: BackendChangesError<LeakyError> = BackendChangesError::Other(LeakyError(CANARY));
1217
1218 let jmap_err = jmap_types::JmapError::from(err);
1219
1220 // Serialize to wire shape and assert the canary is absent from
1221 // the resulting JSON. The error_invocation wraps a JmapError as
1222 // { "type": "serverFail", "description": "..." } — both fields
1223 // are wire-visible.
1224 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1225 let wire_str = wire.to_string();
1226 assert!(
1227 !wire_str.contains(CANARY),
1228 "From<BackendChangesError<E>> for JmapError must not echo \
1229 backend error Display onto the wire; got {wire_str}"
1230 );
1231 // The description MUST be exactly SERVER_FAIL_INTERNAL_DESC.
1232 assert_eq!(
1233 wire["description"],
1234 crate::handlers::SERVER_FAIL_INTERNAL_DESC,
1235 "description must be the static 'internal error' string"
1236 );
1237 assert_eq!(wire["type"], "serverFail");
1238 }
1239
1240 /// Oracle (bd:JMAP-jfia.36): `into_set_error_or_method_error` on
1241 /// `Other` MUST NOT echo the wrapped error's `Display` text; the
1242 /// wire form is exactly `{"type":"serverFail","description":"internal
1243 /// error"}` (hand-written expected JSON). The canary literal is
1244 /// hand-built. Mirrors `backend_changes_error_other_drops_display_text`.
1245 #[test]
1246 fn backend_set_error_other_drops_display_text() {
1247 struct LeakyError(&'static str);
1248 impl std::fmt::Display for LeakyError {
1249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1250 f.write_str(self.0)
1251 }
1252 }
1253
1254 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1255 let err: BackendSetError<LeakyError> = BackendSetError::Other(LeakyError(CANARY));
1256
1257 let Err(jmap_err) = err.into_set_error_or_method_error() else {
1258 panic!("Other must map to a method-level JmapError");
1259 };
1260 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1261 assert!(
1262 !wire.to_string().contains(CANARY),
1263 "into_set_error_or_method_error must not echo backend Display; got {wire}"
1264 );
1265 assert_eq!(
1266 wire,
1267 serde_json::json!({"type": "serverFail", "description": "internal error"})
1268 );
1269 }
1270
1271 /// Oracle (RFC 8620 §5.3): a per-object `SetError` belongs in the
1272 /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
1273 /// arm must come back as `Ok` with its wire form intact
1274 /// (hand-written expected JSON).
1275 #[test]
1276 fn backend_set_error_set_error_passes_through() {
1277 let err: BackendSetError<std::fmt::Error> =
1278 BackendSetError::SetError(Box::new(SetError::new(SetErrorType::Forbidden)));
1279 let se = err
1280 .into_set_error_or_method_error()
1281 .expect("SetError arm must be Ok");
1282 assert_eq!(
1283 serde_json::to_value(&se).expect("SetError must serialize"),
1284 serde_json::json!({"type": "forbidden"})
1285 );
1286 }
1287
1288 /// Oracle (RFC 8620 §5.3): a per-object `SetError` is the
1289 /// `notCreated`/`notUpdated`/`notDestroyed` map value verbatim
1290 /// (hand-written expected JSON).
1291 #[test]
1292 fn backend_set_error_value_set_error_is_verbatim() {
1293 let err: BackendSetError<std::fmt::Error> = BackendSetError::SetError(Box::new(
1294 SetError::new(SetErrorType::NotFound).with_description("gone"),
1295 ));
1296 assert_eq!(
1297 backend_set_error_value(err),
1298 serde_json::json!({"type": "notFound", "description": "gone"})
1299 );
1300 }
1301
1302 /// Oracle (bd:JMAP-jfia.36): `Other` becomes exactly
1303 /// `{"type":"serverFail","description":"internal error"}` and never
1304 /// carries the wrapped error's `Display` text (hand-written expected
1305 /// JSON, hand-built canary).
1306 #[test]
1307 fn backend_set_error_value_other_is_redacted_server_fail() {
1308 const CANARY: &str = "TOKEN-DO-NOT-LEAK-5e7e44";
1309 let err: BackendSetError<&str> = BackendSetError::Other(CANARY);
1310 let wire = backend_set_error_value(err);
1311 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
1312 assert_eq!(
1313 wire,
1314 serde_json::json!({"type": "serverFail", "description": "internal error"})
1315 );
1316 }
1317
1318 /// Hand-built storage error for the stub backend and the error-envelope
1319 /// tests; its `Display` text is a fixed literal.
1320 #[derive(Debug)]
1321 struct StubError;
1322
1323 impl std::fmt::Display for StubError {
1324 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1325 f.write_str("stub")
1326 }
1327 }
1328 impl std::error::Error for StubError {}
1329
1330 /// Minimal backend that implements only the required trait methods, so
1331 /// tests observe the provided (default) methods. The required methods
1332 /// are never invoked.
1333 struct StubBackend;
1334
1335 impl JmapBackend for StubBackend {
1336 type Error = StubError;
1337 type CallerCtx = ();
1338
1339 async fn account_exists(
1340 &self,
1341 _caller: &(),
1342 _account_id: &jmap_types::Id,
1343 ) -> Result<bool, Self::Error> {
1344 unreachable!("stub backend: only default methods are exercised")
1345 }
1346
1347 async fn get_objects<O: GetObject + Send + Sync>(
1348 &self,
1349 _caller: &(),
1350 _account_id: &jmap_types::Id,
1351 _ids: Option<&[jmap_types::Id]>,
1352 _properties: Option<&[String]>,
1353 ) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
1354 unreachable!("stub backend: only default methods are exercised")
1355 }
1356
1357 async fn get_state<O: JmapObject + Send + Sync>(
1358 &self,
1359 _caller: &(),
1360 _account_id: &jmap_types::Id,
1361 ) -> Result<jmap_types::State, Self::Error> {
1362 unreachable!("stub backend: only default methods are exercised")
1363 }
1364
1365 async fn get_changes<O: JmapObject + Send + Sync>(
1366 &self,
1367 _caller: &(),
1368 _account_id: &jmap_types::Id,
1369 _params: ChangesParams<'_>,
1370 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1371 unreachable!("stub backend: only default methods are exercised")
1372 }
1373
1374 async fn query_objects<O: QueryObject + Send + Sync>(
1375 &self,
1376 _caller: &(),
1377 _account_id: &jmap_types::Id,
1378 _params: QueryParams<'_, O>,
1379 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1380 unreachable!("stub backend: only default methods are exercised")
1381 }
1382
1383 async fn query_changes<O: QueryObject + Send + Sync>(
1384 &self,
1385 _caller: &(),
1386 _account_id: &jmap_types::Id,
1387 _params: QueryChangesParams<'_, O>,
1388 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1389 unreachable!("stub backend: only default methods are exercised")
1390 }
1391 }
1392
1393 /// Oracle (bd:JMAP-ga0q.1): `JmapBackend::principal_id` has a default impl
1394 /// that returns `None`. A backend whose `CallerCtx = ()` and that does NOT
1395 /// override `principal_id` inherits that default and signals "identity not
1396 /// wired" to callers. JMAP semantics that depend on caller identity must
1397 /// treat `None` as a hard "cannot honor".
1398 #[test]
1399 fn principal_id_default_impl_returns_none_for_unit_caller_ctx() {
1400 let caller: <StubBackend as JmapBackend>::CallerCtx = ();
1401 let id = <StubBackend as JmapBackend>::principal_id(&caller);
1402 assert!(
1403 id.is_none(),
1404 "default principal_id impl must return None; got Some({:?})",
1405 id
1406 );
1407 }
1408
1409 /// Oracle (bd:JMAP-ayoz.41.1): `JmapBackend::max_objects_in_set`
1410 /// has a default impl that returns `500`. The constant is the
1411 /// workspace's testjig Session JSON advertised cap; a backend that
1412 /// does not override the method inherits a sane DoS-defence
1413 /// default rather than silently disabling the cap.
1414 #[test]
1415 fn max_objects_in_set_default_impl_returns_500() {
1416 let backend = StubBackend;
1417 let caller: <StubBackend as JmapBackend>::CallerCtx = ();
1418 let id = jmap_types::Id::from("any-account");
1419 assert_eq!(
1420 backend.max_objects_in_set(&caller, &id),
1421 500,
1422 "default max_objects_in_set must return 500"
1423 );
1424 }
1425
1426 /// Oracle (trait docs, same rationale as `max_objects_in_set`): the
1427 /// default `JmapBackend::max_objects_in_get` cap is `500`, so a backend
1428 /// that does not override it keeps the RFC 8620 §5.1 `requestTooLarge`
1429 /// guard enabled.
1430 #[test]
1431 fn max_objects_in_get_default_impl_returns_500() {
1432 let caller: <StubBackend as JmapBackend>::CallerCtx = ();
1433 let id = jmap_types::Id::from("any-account");
1434 assert_eq!(StubBackend.max_objects_in_get(&caller, &id), 500);
1435 }
1436
1437 /// Oracle: hand-written expected strings. The `SetError` arm prefixes
1438 /// the `SetError` Display (`<type>: <description>`), and `Other` is
1439 /// transparent over the wrapped error.
1440 #[test]
1441 fn backend_set_error_display() {
1442 let se: BackendSetError<StubError> = BackendSetError::SetError(Box::new(
1443 SetError::new(SetErrorType::NotFound).with_description("gone"),
1444 ));
1445 assert_eq!(se.to_string(), "set error: notFound: gone");
1446 assert_eq!(BackendSetError::Other(StubError).to_string(), "stub");
1447 }
1448
1449 /// Oracle: hand-written expected strings for every variant.
1450 #[test]
1451 fn backend_changes_error_display() {
1452 assert_eq!(
1453 BackendChangesError::<StubError>::CannotCalculate.to_string(),
1454 "cannot calculate changes"
1455 );
1456 assert_eq!(
1457 BackendChangesError::<StubError>::TooManyChanges { limit: 7 }.to_string(),
1458 "too many changes (limit: 7)"
1459 );
1460 assert_eq!(BackendChangesError::Other(StubError).to_string(), "stub");
1461 }
1462
1463 /// Oracle: `Method` displays the wrapped `JmapError` unchanged and
1464 /// `Other` is transparent over the wrapped error (hand-written strings).
1465 #[test]
1466 fn backend_query_error_display() {
1467 let method = jmap_types::JmapError::server_fail("x");
1468 let expected = method.to_string();
1469 assert_eq!(
1470 BackendQueryError::<StubError>::Method(method).to_string(),
1471 expected
1472 );
1473 assert_eq!(BackendQueryError::Other(StubError).to_string(), "stub");
1474 }
1475
1476 /// Oracle (`std::error::Error::source` contract): only the `Other`
1477 /// variant wraps an underlying error, so only it reports a source, and
1478 /// that source is the wrapped value.
1479 #[test]
1480 fn backend_errors_source_is_wrapped_other_only() {
1481 use std::error::Error as _;
1482
1483 let is_stub = |e: Option<&(dyn std::error::Error + 'static)>| {
1484 e.is_some_and(|s| s.downcast_ref::<StubError>().is_some())
1485 };
1486
1487 assert!(is_stub(BackendSetError::Other(StubError).source()));
1488 assert!(
1489 BackendSetError::<StubError>::from(SetError::new(SetErrorType::Forbidden))
1490 .source()
1491 .is_none()
1492 );
1493
1494 assert!(is_stub(BackendChangesError::from(StubError).source()));
1495 assert!(
1496 BackendChangesError::<StubError>::CannotCalculate
1497 .source()
1498 .is_none()
1499 );
1500 assert!(
1501 BackendChangesError::<StubError>::TooManyChanges { limit: 1 }
1502 .source()
1503 .is_none()
1504 );
1505
1506 assert!(is_stub(BackendQueryError::from(StubError).source()));
1507 assert!(
1508 BackendQueryError::<StubError>::Method(jmap_types::JmapError::server_fail("x"))
1509 .source()
1510 .is_none()
1511 );
1512 }
1513}