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 [`JmapReads::get_changes`] and
105/// [`JmapReads::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 [`JmapReads::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/// [`JmapReads::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/// [`JmapReads::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 /// `language` (draft-atwood-jmap-updates-00 §4.2.2): sort and filter
529 /// on a localizable property ([`JmapObject::LOCALIZABLE`]) compare the
530 /// value `/get` with these ranges returns
531 /// ([`jmap_types::i18n::localized_value`]), not the base value. `None`
532 /// compares stored values. Set only for an account whose
533 /// [`JmapAccounts::i18n_info`] is `Some`; such a backend MUST honour it.
534 pub language: Option<&'a [jmap_types::i18n::LanguageRange]>,
535}
536
537impl<'a, O: QueryObject> QueryParams<'a, O> {
538 /// The RFC 8620 §5.5 defaults: no filter, sort, limit or anchor, and
539 /// `position` and `anchorOffset` 0.
540 pub fn new() -> Self {
541 Self {
542 filter: None,
543 sort: None,
544 limit: None,
545 position: 0,
546 anchor: None,
547 anchor_offset: 0,
548 language: None,
549 }
550 }
551
552 /// Set [`filter`](Self::filter).
553 #[must_use]
554 pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
555 self.filter = filter;
556 self
557 }
558
559 /// Set [`sort`](Self::sort).
560 #[must_use]
561 pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
562 self.sort = sort;
563 self
564 }
565
566 /// Set [`limit`](Self::limit).
567 #[must_use]
568 pub fn limit(mut self, limit: Option<u64>) -> Self {
569 self.limit = limit;
570 self
571 }
572
573 /// Set [`position`](Self::position).
574 #[must_use]
575 pub fn position(mut self, position: i64) -> Self {
576 self.position = position;
577 self
578 }
579
580 /// Set [`anchor`](Self::anchor).
581 #[must_use]
582 pub fn anchor(mut self, anchor: Option<&'a jmap_types::Id>) -> Self {
583 self.anchor = anchor;
584 self
585 }
586
587 /// Set [`anchor_offset`](Self::anchor_offset).
588 #[must_use]
589 pub fn anchor_offset(mut self, anchor_offset: i64) -> Self {
590 self.anchor_offset = anchor_offset;
591 self
592 }
593
594 /// Set [`language`](Self::language).
595 #[must_use]
596 pub fn language(mut self, language: Option<&'a [jmap_types::i18n::LanguageRange]>) -> Self {
597 self.language = language;
598 self
599 }
600}
601
602impl<O: QueryObject> Default for QueryParams<'_, O> {
603 fn default() -> Self {
604 Self::new()
605 }
606}
607
608// Manual impls: derives would wrongly require `O: Clone` / `O: Debug`.
609impl<O: QueryObject> Clone for QueryParams<'_, O> {
610 fn clone(&self) -> Self {
611 *self
612 }
613}
614
615impl<O: QueryObject> Copy for QueryParams<'_, O> {}
616
617impl<O: QueryObject> std::fmt::Debug for QueryParams<'_, O>
618where
619 O::Filter: std::fmt::Debug,
620 O::Comparator: std::fmt::Debug,
621{
622 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623 f.debug_struct("QueryParams")
624 .field("filter", &self.filter)
625 .field("sort", &self.sort)
626 .field("limit", &self.limit)
627 .field("position", &self.position)
628 .field("anchor", &self.anchor)
629 .field("anchor_offset", &self.anchor_offset)
630 .field("language", &self.language)
631 .finish()
632 }
633}
634
635/// The `/queryChanges` arguments (RFC 8620 §5.6) passed to
636/// [`JmapReads::query_changes`], after `accountId`.
637///
638/// `#[non_exhaustive]` for the same reason as [`QueryParams`]. Build one
639/// with [`QueryChangesParams::new`], which takes the one required
640/// argument, `sinceQueryState`, and the setters.
641#[non_exhaustive]
642pub struct QueryChangesParams<'a, O: QueryObject> {
643 /// `sinceQueryState`, the `queryState` the client already has.
644 pub since_query_state: &'a jmap_types::State,
645 /// `filter`, as passed to the original `/query`.
646 pub filter: Option<&'a O::Filter>,
647 /// `sort`, as passed to the original `/query`.
648 pub sort: Option<&'a [O::Comparator]>,
649 /// `maxChanges`; `None` means no client limit.
650 pub max_changes: Option<u64>,
651 /// `upToId`: the last id in the client's cached results.
652 pub up_to_id: Option<&'a jmap_types::Id>,
653 /// `collapseThreads`, meaningful only for `Email/queryChanges`
654 /// (RFC 8621 §4.5); `false` for every other type.
655 pub collapse_threads: bool,
656 /// `language`, as passed to the original `/query`
657 /// (draft-atwood-jmap-updates-00 §4.2.3): sort and filter
658 /// on a localizable property ([`JmapObject::LOCALIZABLE`]) compare the
659 /// value `/get` with these ranges returns
660 /// ([`jmap_types::i18n::localized_value`]), not the base value. `None`
661 /// compares stored values. Set only for an account whose
662 /// [`JmapAccounts::i18n_info`] is `Some`; such a backend MUST honour it.
663 pub language: Option<&'a [jmap_types::i18n::LanguageRange]>,
664}
665
666impl<'a, O: QueryObject> QueryChangesParams<'a, O> {
667 /// Changes since `since_query_state`, with no filter, sort,
668 /// `maxChanges` or `upToId`, and `collapseThreads` false.
669 pub fn new(since_query_state: &'a jmap_types::State) -> Self {
670 Self {
671 since_query_state,
672 filter: None,
673 sort: None,
674 max_changes: None,
675 up_to_id: None,
676 collapse_threads: false,
677 language: None,
678 }
679 }
680
681 /// Set [`filter`](Self::filter).
682 #[must_use]
683 pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
684 self.filter = filter;
685 self
686 }
687
688 /// Set [`sort`](Self::sort).
689 #[must_use]
690 pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
691 self.sort = sort;
692 self
693 }
694
695 /// Set [`max_changes`](Self::max_changes).
696 #[must_use]
697 pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
698 self.max_changes = max_changes;
699 self
700 }
701
702 /// Set [`up_to_id`](Self::up_to_id).
703 #[must_use]
704 pub fn up_to_id(mut self, up_to_id: Option<&'a jmap_types::Id>) -> Self {
705 self.up_to_id = up_to_id;
706 self
707 }
708
709 /// Set [`collapse_threads`](Self::collapse_threads).
710 #[must_use]
711 pub fn collapse_threads(mut self, collapse_threads: bool) -> Self {
712 self.collapse_threads = collapse_threads;
713 self
714 }
715
716 /// Set [`language`](Self::language).
717 #[must_use]
718 pub fn language(mut self, language: Option<&'a [jmap_types::i18n::LanguageRange]>) -> Self {
719 self.language = language;
720 self
721 }
722}
723
724impl<O: QueryObject> Clone for QueryChangesParams<'_, O> {
725 fn clone(&self) -> Self {
726 *self
727 }
728}
729
730impl<O: QueryObject> Copy for QueryChangesParams<'_, O> {}
731
732impl<O: QueryObject> std::fmt::Debug for QueryChangesParams<'_, O>
733where
734 O::Filter: std::fmt::Debug,
735 O::Comparator: std::fmt::Debug,
736{
737 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
738 f.debug_struct("QueryChangesParams")
739 .field("since_query_state", &self.since_query_state)
740 .field("filter", &self.filter)
741 .field("sort", &self.sort)
742 .field("max_changes", &self.max_changes)
743 .field("up_to_id", &self.up_to_id)
744 .field("collapse_threads", &self.collapse_threads)
745 .field("language", &self.language)
746 .finish()
747 }
748}
749
750// ---------------------------------------------------------------------------
751// JmapBackend — the read-side supertrait
752// ---------------------------------------------------------------------------
753
754/// Backend supertrait shared by all JMAP server crates: [`JmapAccounts`]
755/// plus [`JmapReads`].
756///
757/// Domain-specific backend traits (`MailBackend`, `ChatBackend`, etc.) require
758/// this trait as a supertrait and add write-side methods on top.
759///
760/// Implement [`JmapAccounts`] and [`JmapReads`]; the blanket impl provides
761/// this trait, so it has no methods of its own and is never implemented
762/// directly. A wrapper that forwards the reads to another backend
763/// implements [`DelegateJmapReads`] instead of [`JmapReads`].
764///
765/// Only the read operations that have an identical signature across all JMAP
766/// object types belong here. Write operations (`create_object`, `update_object`,
767/// `destroy_object`) and domain-specific operations remain in the domain crate.
768///
769/// This trait is not object-safe by design (generic methods). Use
770/// `Arc<impl JmapBackend>` when sharing across tasks.
771pub trait JmapBackend: JmapAccounts + JmapReads {}
772
773impl<T: JmapAccounts + JmapReads> JmapBackend for T {}
774
775/// Per-account information every JMAP backend supplies: the error and caller
776/// context types, the account check, the caller's principal and
777/// Accept-Language, the request limits, and the metadata and i18n hooks.
778///
779/// One of the two halves of [`JmapBackend`]; the other is [`JmapReads`].
780/// A backend implements both, and gets [`JmapBackend`] from the blanket
781/// impl. The split lets a wrapper override [`Self::account_exists`] (or
782/// any method here) while forwarding the reads to the backend it wraps
783/// through [`DelegateJmapReads`], and the rest of this trait through
784/// [`DelegateJmapAccounts`].
785///
786/// # `CallerCtx`
787///
788/// Every backend method takes a `caller: &Self::CallerCtx` parameter as the
789/// first argument after `&self`. This is the per-request authentication /
790/// authorisation context produced by the caller's auth layer and forwarded
791/// unchanged through [`crate::Dispatcher::dispatch`] → [`crate::JmapHandler`]
792/// → the registered closure → the backend.
793///
794/// Implementations that do not need an auth identity can use the unit type:
795///
796/// ```rust,ignore
797/// impl JmapAccounts for MyBackend {
798/// type Error = MyError;
799/// type CallerCtx = ();
800/// // ...
801/// }
802/// ```
803///
804/// Implementations that do need to differentiate behaviour per caller (e.g.
805/// applying per-user visibility rules, or rejecting reads with
806/// `forbidden` when the caller is not the owner of the account) read the
807/// `caller` parameter to decide.
808///
809/// The trait bound `Clone + Send + 'static` is what [`crate::Dispatcher`]
810/// requires; the bound is repeated here so the supertrait can stand on its
811/// own without depending on the dispatcher.
812pub trait JmapAccounts: Send + Sync + 'static {
813 /// The error type returned by storage operations.
814 ///
815 /// # Security
816 ///
817 /// The `Display` impl of this type is surfaced through
818 /// [`BackendSetError::Other`]'s and [`BackendChangesError::Other`]'s
819 /// own `Display` impls, which in turn flow into
820 /// [`crate::request_error`]'s `RequestError::Display` output. When a
821 /// downstream consumer wires tracing-style logging on top, the
822 /// formatted error text lands in operator logs verbatim.
823 ///
824 /// Implementations MUST NOT include any of the following in this
825 /// type's `Display` output:
826 ///
827 /// - **Credential material** — auth tokens, passwords, push
828 /// verification codes, invite codes, session cookies, or anything
829 /// derived byte-for-byte from an `Authorization`-header value.
830 /// - **Blob content** — email bodies, sieve scripts, file contents,
831 /// or any user-supplied opaque payload. An error like
832 /// `"sieve parse error at line 42: <script excerpt>"` violates
833 /// this — emit the line number and a short type-only summary
834 /// ("sieve parse error at line 42: unexpected token") and let the
835 /// server log the full script body separately under a redacted
836 /// path.
837 /// - **PII shaped like an email address** in any code path that an
838 /// unauthenticated caller can trigger. Wrapping a downstream
839 /// service error that interpolates the caller's email is the
840 /// common foot-gun.
841 ///
842 /// Errors that wrap a downstream-service failure should sanitize
843 /// the downstream error text — or strip it entirely and replace it
844 /// with a static summary — before constructing the `Display`
845 /// string. The same rule applies to every extension `*Backend`
846 /// trait that inherits this associated type by transitivity:
847 /// `MailBackend::Error`, `ChatBackend::Error`,
848 /// `CalendarsBackend::Error`, `TasksBackend::Error`,
849 /// `ContactsBackend::Error`, `FileNodeBackend::Error`, and
850 /// `SharingBackend::Error` are all the same `JmapAccounts::Error`
851 /// associated type — the contract here governs all of them.
852 ///
853 /// Precedent: bd:JMAP-sc1b.79 redacted `BearerAuth` and `BasicAuth`
854 /// at the type-derive level; bd:JMAP-sc1b.100 documents the
855 /// equivalent contract at the trait-associated-type level.
856 type Error: std::error::Error + Send + Sync + 'static;
857
858 /// The per-request caller context type produced by the auth layer and
859 /// forwarded by [`crate::Dispatcher::dispatch`] into every method call.
860 ///
861 /// Use `()` when no auth context is needed.
862 ///
863 /// The bound is `Clone + Send + Sync + 'static`:
864 /// - `Clone` because [`crate::Dispatcher`] clones the value once per
865 /// method call in the batch.
866 /// - `Send + 'static` because each method call is spawned on a
867 /// [`tokio::task`].
868 /// - `Sync` because handler method bodies take `&Self::CallerCtx`
869 /// and hold that reference across `.await` boundaries inside a
870 /// `Send` future (a `&T` is `Send` iff `T: Sync`).
871 type CallerCtx: Clone + Send + Sync + 'static;
872
873 /// Return `true` if the given account exists in this backend.
874 ///
875 /// Handlers call this at the start of each method to return
876 /// `accountNotFound` (RFC 8620 §3.6.2) rather than surfacing
877 /// the wrong error when `accountId` is unknown.
878 ///
879 /// # Performance contract (bd:JMAP-jfia.27)
880 ///
881 /// Implementations SHOULD return in sub-millisecond time. The
882 /// JMAP standard handlers (`handle_get`, `handle_changes`,
883 /// `handle_query`, `handle_query_changes`) each call
884 /// `account_exists` at the START of the method, BEFORE delegating
885 /// to the per-domain backend. A typical JMAP request batch is
886 /// 4–16 method calls; a naive remote round-trip per call would
887 /// add 4–16× the network latency to every batch.
888 ///
889 /// Acceptable backing strategies: in-memory cache (the
890 /// reference `MemoryBackend` impls all use this); an indexed
891 /// primary-key lookup against a local database; a bloom filter
892 /// for negative lookups paired with a cache for positives. A
893 /// naive `SELECT 1 FROM accounts WHERE id = ?` against a remote
894 /// database is INCORRECT for this method even though it would
895 /// return the right value — the round-trip cost is the bug.
896 ///
897 /// The dispatcher does not cache this call across the method
898 /// calls in a single batch (workspace-architectural decision —
899 /// the dispatcher is intentionally stateless across the batch
900 /// loop). Caching is the backend implementor's responsibility.
901 fn account_exists(
902 &self,
903 caller: &Self::CallerCtx,
904 account_id: &jmap_types::Id,
905 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;
906
907 /// The caller's stable identity within this account namespace.
908 ///
909 /// Returns `None` for deployments that have not wired identity
910 /// (test fixtures, single-user dev servers). A `None`-returning
911 /// backend CANNOT honor JMAP semantics that depend on caller
912 /// identity — chat role-hierarchy, calendar ACLs, sharing/myRights,
913 /// per-user $seen on shared mailboxes, per-user metadata
914 /// `privateMetadata` filtering, etc. Authentication is still the HTTP
915 /// layer's job; this method exposes the result of that
916 /// authentication to the JMAP layer for in-method semantics.
917 ///
918 /// Implementations MUST NOT mint identity — they MUST read it
919 /// from the `CallerCtx` populated by the HTTP/auth middleware
920 /// before `dispatch()` was called.
921 ///
922 /// Backends that honor identity-dependent semantics MUST override
923 /// this method. Handlers and downstream backend traits MAY rely on
924 /// it being correct when it returns `Some`.
925 ///
926 /// # Why an associated function and not a method (bd:JMAP-wlip.6 / bd:JMAP-jfia.13)
927 ///
928 /// The signature deliberately takes `caller: &Self::CallerCtx`
929 /// without a `&self` receiver. Backends therefore have no access
930 /// to their own storage state from inside `principal_id`. The
931 /// auth-layer middleware MUST pre-resolve the principal (e.g. map
932 /// a JWT `sub` claim to a local `Id` via an internal lookup) and
933 /// stash the result inside `CallerCtx` *before* it calls
934 /// `dispatch`. The JMAP layer reads the pre-resolved value here;
935 /// no JIT lookup is possible.
936 ///
937 /// This is a structural enforcement of the "identity is not the
938 /// JMAP layer's job to mint" rule. A consumer that wants
939 /// JIT-resolved identity (e.g. database-backed JWT → principal
940 /// mapping) wires that mapping into the HTTP layer's `CallerCtx`
941 /// construction step instead of trying to fit it inside the
942 /// backend's `principal_id` impl.
943 ///
944 /// **Decision record (bd:JMAP-jfia.13)**: a future reviewer or AI
945 /// tool will reasonably suggest "this is an oversight, surely the
946 /// backend wants `&self` access to its identity store" and propose
947 /// `fn principal_id(&self, caller: ...) -> ...`. That suggestion
948 /// is **WRONG** and must be rejected: the function-vs-method
949 /// distinction is the structural enforcement of the no-JIT-lookup
950 /// policy. Comments alone could be ignored; the type system makes
951 /// the wrong thing impossible. Defending this shape protects the
952 /// workspace identity-seam policy from drift.
953 fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
954 let _ = caller;
955 None
956 }
957
958 /// The request's `Accept-Language` header field value (RFC 9110
959 /// §12.5.4), as the HTTP or WebSocket layer recorded it in the caller
960 /// context, or [`None`].
961 ///
962 /// It is the entry point for language in the JMAP layer, with the same
963 /// shape as [`Self::principal_id`] (decision 31): an associated function
964 /// over the caller context, so it is read without a backend lookup.
965 /// Over a WebSocket, the transport fills it from the opening
966 /// handshake for every Request on the connection
967 /// (draft-atwood-jmap-updates-00 §4.3).
968 ///
969 /// Use it only for custom strings that are not data: the `title` and
970 /// `detail` of a problem details response
971 /// ([`problem_response`](crate::problem_response), with
972 /// Content-Language), and the RFC 9425 Quota `description` when
973 /// `urn:ietf:params:jmap:i18n` is not in `using`. With that capability in
974 /// `using`, Accept-Language MUST NOT change `/get` or `/query` results
975 /// (§4.2.1); the `language` argument does that.
976 ///
977 /// Default: [`None`].
978 fn accept_language(caller: &Self::CallerCtx) -> Option<&str> {
979 let _ = caller;
980 None
981 }
982
983 /// Maximum number of objects this account permits in a single
984 /// `/set` call (RFC 8620 §5.3 `maxObjectsInSet`) (bd:JMAP-ayoz.41.1).
985 ///
986 /// Counts the sum of `create` + `update` + `destroy` entries in the
987 /// wire arguments. Handlers MUST enforce this at the top of every
988 /// `handle_*_set` via [`crate::helpers::enforce_max_objects_in_set`]
989 /// so a single batched request cannot drive O(M·N) work against
990 /// the storage layer.
991 ///
992 /// The default value `500` mirrors the workspace's testjig Session
993 /// JSON advertised cap and matches common Fastmail / Cyrus IMAP
994 /// server defaults. The cap is a *floor* on permissiveness, not a
995 /// floor on capability — backends MAY override per account (Free vs
996 /// Pro tier, multi-tenant software-as-a-service, etc.). The `caller` and `account_id`
997 /// arguments are passed even though the default impl ignores them
998 /// so production backends can vary without an API break.
999 ///
1000 /// Returning `0` makes every non-empty `/set` call fail with
1001 /// `requestTooLarge` (defensive read-only mode). Returning
1002 /// `u64::MAX` effectively disables the cap (NOT recommended — the
1003 /// cap is a denial-of-service defence and disabling it forfeits that defence).
1004 ///
1005 /// # Why on `JmapBackend` and not a per-extension `XxxLimits` struct
1006 ///
1007 /// `maxObjectsInSet` is RFC 8620 §5.3 base-protocol scope, not an
1008 /// extension concept. Putting it on the foundation supertrait
1009 /// covers all 8 extension server crates with one default impl;
1010 /// per-extension `XxxLimits` structs are the right shape for
1011 /// extension-specific caps (per-Space content limits, per-Mailbox
1012 /// message size, etc. per workspace AGENTS.md "Backend caps and
1013 /// limits") but are out of scope here.
1014 fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1015 let _ = (caller, account_id);
1016 500
1017 }
1018
1019 /// Maximum number of ids this account permits in a single `/get`
1020 /// call (RFC 8620 §5.1 `maxObjectsInGet`) (bd:JMAP-yt1w.31).
1021 ///
1022 /// Handlers MUST enforce this at the top of every `/get` handler via
1023 /// [`crate::helpers::enforce_max_objects_in_get`]; the generic
1024 /// [`handle_get`](crate::handle_get) already does. A null `ids` (fetch
1025 /// all) is not counted.
1026 ///
1027 /// The default value `500` is the RFC 8620 §2 suggested minimum and
1028 /// mirrors [`JmapAccounts::max_objects_in_set`]. Backends MAY override
1029 /// per account; the `caller` and `account_id` arguments exist for
1030 /// that. Keep the value in step with the `maxObjectsInGet` advertised
1031 /// in the Session object.
1032 fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1033 let _ = (caller, account_id);
1034 500
1035 }
1036
1037 /// The draft-ietf-jmap-metadata-05 §1.2.1 `DataTypeMetadataInfo` of `O`
1038 /// in `account_id`, as seen by `caller`, or [`None`] when the account's
1039 /// `urn:ietf:params:jmap:metadata` capability does not list `O`.
1040 ///
1041 /// Handlers use it where the wire shape depends on it: `Foo/get`
1042 /// returns `metadata` as an object (`{}` when nothing is stored),
1043 /// applies the `metadata/` subselectors and never returns
1044 /// `privateMetadata` when `supportsPrivate` is false (-05 §2, §3.1,
1045 /// through [`MetadataProjection`](crate::MetadataProjection));
1046 /// `Foo/copy` copies neither property into an account that does not
1047 /// list `O` (-05 §3.4). Keep it in step with the `dataTypes`
1048 /// advertised in the Session object.
1049 ///
1050 /// Default: [`None`], a backend without metadata.
1051 fn metadata_info<O: JmapObject>(
1052 &self,
1053 caller: &Self::CallerCtx,
1054 account_id: &jmap_types::Id,
1055 ) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
1056 let _ = (caller, account_id);
1057 None
1058 }
1059
1060 /// What `account_id` supports of `urn:ietf:params:jmap:i18n`
1061 /// (draft-atwood-jmap-updates-00), as seen by `caller`, or [`None`]
1062 /// when the account does not support localizations.
1063 ///
1064 /// # Session
1065 ///
1066 /// The deployment builds the Session object. It advertises
1067 /// `urn:ietf:params:jmap:i18n` with the value `{}`
1068 /// ([`I18nCapability`](jmap_types::i18n::I18nCapability)) in
1069 /// `capabilities` only when it supports localizations at all, and with
1070 /// the value `{}` ([`I18nAccountCapability`](jmap_types::i18n::I18nAccountCapability))
1071 /// in the `accountCapabilities` of exactly the accounts for which this
1072 /// method returns `Some` for the requesting caller (§3).
1073 ///
1074 /// `Some` puts the capability in the account's `accountCapabilities`;
1075 /// the deployment then stores `locale` and `localizations` on every
1076 /// type with [`JmapObject::LOCALIZABLE`] properties in this account
1077 /// and honours the `language` argument of
1078 /// [`QueryParams`]. `None` makes the handlers
1079 /// reject `language` with `invalidArguments` and never return the two
1080 /// properties (§3). Keep it in step with the Session object.
1081 ///
1082 /// Default: [`None`], a backend without localizations.
1083 fn i18n_info(
1084 &self,
1085 caller: &Self::CallerCtx,
1086 account_id: &jmap_types::Id,
1087 ) -> Option<crate::I18nInfo> {
1088 let _ = (caller, account_id);
1089 None
1090 }
1091}
1092
1093/// The five standard reads (RFC 8620 §5.1, §5.2, §5.5, §5.6), the half of
1094/// [`JmapBackend`] that a wrapper can forward with [`DelegateJmapReads`].
1095///
1096/// [`QueryChangesParams::collapse_threads`] is included for
1097/// `Email/queryChanges` (RFC 8621 §4.5). Non-mail backends may ignore it.
1098pub trait JmapReads: JmapAccounts {
1099 /// Fetch objects by id (or all objects when `ids` is `None`).
1100 ///
1101 /// `properties` is the list of property names requested by the client
1102 /// (RFC 8620 §5.1). `None` means the client did not send a `properties`
1103 /// field; the backend should return all properties. When `Some`, the backend
1104 /// MAY filter the response to only the named properties, but is not required
1105 /// to — implementations that always return all properties are correct.
1106 ///
1107 /// Returns `(found, not_found)` — objects that exist and ids that do not.
1108 ///
1109 /// # Unknown `account_id`
1110 ///
1111 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
1112 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
1113 /// [`JmapAccounts::account_exists`] before calling this method and return
1114 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
1115 /// need not repeat that check. A caller that bypasses those handlers can
1116 /// still reach this method with an unknown account; backends SHOULD then
1117 /// return `Ok` with an empty `found` list and every requested id in `not_found`. Returning `Err` is permitted but surfaces as
1118 /// `serverFail`, not `accountNotFound`.
1119 ///
1120 /// # Localized properties
1121 ///
1122 /// For a type with [`JmapObject::LOCALIZABLE`] properties, return the
1123 /// stored base values with their `locale` and `localizations`. The
1124 /// handlers build the single-language view of the `language` argument
1125 /// themselves. Do not let the request's Accept-Language change what
1126 /// this method or `query_objects` returns for a localizable property:
1127 /// draft-atwood-jmap-updates-00 §4.2.1 says the server MUST NOT, since
1128 /// a client that caches objects by id and state could not tell the
1129 /// languages apart.
1130 fn get_objects<O: GetObject + Send + Sync>(
1131 &self,
1132 caller: &Self::CallerCtx,
1133 account_id: &jmap_types::Id,
1134 ids: Option<&[jmap_types::Id]>,
1135 properties: Option<&[String]>,
1136 ) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send;
1137
1138 /// Return the current state token for an object type in the given account.
1139 ///
1140 /// # Unknown `account_id`
1141 ///
1142 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
1143 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
1144 /// [`JmapAccounts::account_exists`] before calling this method and return
1145 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
1146 /// need not repeat that check. A caller that bypasses those handlers can
1147 /// still reach this method with an unknown account; backends SHOULD then
1148 /// return `Ok` with the state token an empty account would report. Returning `Err` is permitted but surfaces as
1149 /// `serverFail`, not `accountNotFound`.
1150 fn get_state<O: JmapObject + Send + Sync>(
1151 &self,
1152 caller: &Self::CallerCtx,
1153 account_id: &jmap_types::Id,
1154 ) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send;
1155
1156 /// Return changes since `params.since_state`, up to
1157 /// `params.max_changes` entries, honouring
1158 /// `params.ignore_metadata_only_changes` (see [`ChangesParams`]).
1159 ///
1160 /// # Unknown `account_id`
1161 ///
1162 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
1163 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
1164 /// [`JmapAccounts::account_exists`] before calling this method and return
1165 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
1166 /// need not repeat that check. A caller that bypasses those handlers can
1167 /// still reach this method with an unknown account; backends SHOULD then
1168 /// return `Ok` with a [`ChangesResult`] whose change lists are empty. Returning `Err` is permitted but surfaces as
1169 /// `serverFail`, not `accountNotFound`.
1170 fn get_changes<O: JmapObject + Send + Sync>(
1171 &self,
1172 caller: &Self::CallerCtx,
1173 account_id: &jmap_types::Id,
1174 params: ChangesParams<'_>,
1175 ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;
1176
1177 /// Execute a `/query` and return a page of matching ids.
1178 ///
1179 /// `params.position` may be negative — negative values are relative to
1180 /// the end of the result set per RFC 8620 §5.5 (e.g. -1 means the last
1181 /// result).
1182 ///
1183 /// `params.anchor` and `params.anchor_offset` are the RFC 8620 §5.5
1184 /// `anchor` and `anchorOffset` arguments. With an `anchor`, `position` MUST be
1185 /// ignored and the page starts at the anchor's index in the filtered,
1186 /// sorted results plus `anchor_offset`, clamped to 0; an anchor not in
1187 /// the results is [`JmapError::anchor_not_found`] via
1188 /// [`BackendQueryError::Method`]. Without one, `anchor_offset` MUST be
1189 /// ignored. [`QueryResult::position`] is the page's actual start index.
1190 /// [`crate::resolve_query_start`] implements this over an in-memory id
1191 /// list.
1192 ///
1193 /// [`JmapError::anchor_not_found`]: jmap_types::JmapError::anchor_not_found
1194 ///
1195 /// # Filter and sort handling
1196 ///
1197 /// Implementations MUST honour the supplied `filter` and `sort` arguments
1198 /// efficiently — typically by pushing both into the indexed storage layer
1199 /// (database WHERE / ORDER BY, search index, etc.). Returning every
1200 /// matching id and relying on the caller to paginate after the fact
1201 /// degenerates to O(n) per page for IMAP-migration accounts.
1202 ///
1203 /// Handler implementations in `jmap-*-server` crates SHOULD NOT
1204 /// post-filter or post-sort the backend's result; doing so re-introduces
1205 /// the O(n) cost this method exists to avoid. The Mailbox handler in
1206 /// `jmap-mail-server` is the canonical example of pushing filter/sort
1207 /// fully into the backend.
1208 ///
1209 /// # Errors
1210 ///
1211 /// Return [`BackendQueryError::Method`] for an RFC 8620 §5.5 method
1212 /// error (`unsupportedFilter`, `unsupportedSort`, `anchorNotFound`,
1213 /// ...); handlers pass it to the client unchanged. Return
1214 /// [`BackendQueryError::Other`] (or use `?` on `Self::Error`) for an
1215 /// internal failure; handlers surface it as a redacted `serverFail`.
1216 ///
1217 /// # Unknown `account_id`
1218 ///
1219 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
1220 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
1221 /// [`JmapAccounts::account_exists`] before calling this method and return
1222 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
1223 /// need not repeat that check. A caller that bypasses those handlers can
1224 /// still reach this method with an unknown account; backends SHOULD then
1225 /// return `Ok` with an empty [`QueryResult`] page. Returning `Err` is permitted but surfaces as
1226 /// `serverFail`, not `accountNotFound`.
1227 fn query_objects<O: QueryObject + Send + Sync>(
1228 &self,
1229 caller: &Self::CallerCtx,
1230 account_id: &jmap_types::Id,
1231 params: QueryParams<'_, O>,
1232 ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;
1233
1234 /// Execute a `/queryChanges` and return deltas since `since_query_state`.
1235 ///
1236 /// `params.collapse_threads` is only meaningful for `Email/queryChanges`
1237 /// (RFC 8621 §4.5); it is `false` for all other object types.
1238 ///
1239 /// # Unknown `account_id`
1240 ///
1241 /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
1242 /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
1243 /// [`JmapAccounts::account_exists`] before calling this method and return
1244 /// `accountNotFound` (RFC 8620 §3.6.2) themselves, so implementations
1245 /// need not repeat that check. A caller that bypasses those handlers can
1246 /// still reach this method with an unknown account; backends SHOULD then
1247 /// return `Ok` with a [`QueryChangesResult`] whose `removed` and `added` lists are empty. Returning `Err` is permitted but surfaces as
1248 /// `serverFail`, not `accountNotFound`.
1249 fn query_changes<O: QueryObject + Send + Sync>(
1250 &self,
1251 caller: &Self::CallerCtx,
1252 account_id: &jmap_types::Id,
1253 params: QueryChangesParams<'_, O>,
1254 ) -> impl std::future::Future<
1255 Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
1256 > + Send;
1257}
1258
1259/// Forward [`JmapReads`] to another backend: implement this instead of
1260/// [`JmapReads`], and the blanket impl sends every read to
1261/// [`Self::jmap_reads`].
1262///
1263/// For a wrapper that overrides [`JmapAccounts`] methods (an
1264/// `account_exists` that consults a directory, say) but serves the reads
1265/// from the backend it wraps. The target has the same `Error` and
1266/// `CallerCtx` as the wrapper.
1267///
1268/// ```rust,ignore
1269/// impl JmapAccounts for Wrapper {
1270/// type Error = <Inner as JmapAccounts>::Error;
1271/// type CallerCtx = <Inner as JmapAccounts>::CallerCtx;
1272/// async fn account_exists(&self, caller: &Self::CallerCtx, id: &Id) -> Result<bool, Self::Error> {
1273/// // ...
1274/// }
1275/// }
1276///
1277/// impl DelegateJmapReads for Wrapper {
1278/// type Target = Inner;
1279/// fn jmap_reads(&self) -> &Inner {
1280/// &self.inner
1281/// }
1282/// }
1283/// ```
1284pub trait DelegateJmapReads: JmapAccounts {
1285 /// The backend the reads go to.
1286 type Target: JmapReads<Error = Self::Error, CallerCtx = Self::CallerCtx>;
1287
1288 /// The backend the reads go to.
1289 fn jmap_reads(&self) -> &Self::Target;
1290}
1291
1292impl<T: DelegateJmapReads> JmapReads for T {
1293 fn get_objects<O: GetObject + Send + Sync>(
1294 &self,
1295 caller: &Self::CallerCtx,
1296 account_id: &jmap_types::Id,
1297 ids: Option<&[jmap_types::Id]>,
1298 properties: Option<&[String]>,
1299 ) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send
1300 {
1301 self.jmap_reads()
1302 .get_objects(caller, account_id, ids, properties)
1303 }
1304 fn get_state<O: JmapObject + Send + Sync>(
1305 &self,
1306 caller: &Self::CallerCtx,
1307 account_id: &jmap_types::Id,
1308 ) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send {
1309 self.jmap_reads().get_state::<O>(caller, account_id)
1310 }
1311
1312 fn get_changes<O: JmapObject + Send + Sync>(
1313 &self,
1314 caller: &Self::CallerCtx,
1315 account_id: &jmap_types::Id,
1316 params: ChangesParams<'_>,
1317 ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send
1318 {
1319 self.jmap_reads()
1320 .get_changes::<O>(caller, account_id, params)
1321 }
1322
1323 fn query_objects<O: QueryObject + Send + Sync>(
1324 &self,
1325 caller: &Self::CallerCtx,
1326 account_id: &jmap_types::Id,
1327 params: QueryParams<'_, O>,
1328 ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send
1329 {
1330 self.jmap_reads().query_objects(caller, account_id, params)
1331 }
1332
1333 fn query_changes<O: QueryObject + Send + Sync>(
1334 &self,
1335 caller: &Self::CallerCtx,
1336 account_id: &jmap_types::Id,
1337 params: QueryChangesParams<'_, O>,
1338 ) -> impl std::future::Future<
1339 Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
1340 > + Send {
1341 self.jmap_reads().query_changes(caller, account_id, params)
1342 }
1343}
1344
1345/// Forward [`JmapAccounts`] to another backend, overriding only what the
1346/// wrapper changes: implement this instead of [`JmapAccounts`], and the
1347/// blanket impl answers every [`JmapAccounts`] method with this trait's
1348/// method of the same name, each of which defaults to the one of
1349/// [`Self::jmap_accounts`].
1350///
1351/// For a wrapper that changes one answer (an `account_exists` that
1352/// consults a directory, say) and keeps the wrapped backend's others,
1353/// whichever of them that backend overrides (a `metadata_info` or
1354/// `i18n_info`, the `max_objects_*` limits): a method the wrapper does not
1355/// override cannot silently fall back to the [`JmapAccounts`] default.
1356/// The wrapper's `Error` and `CallerCtx` are the target's. Pair it with
1357/// [`DelegateJmapReads`] to forward the reads too.
1358///
1359/// `principal_id` and `accept_language` are associated functions with no
1360/// `self` (see [`JmapAccounts::principal_id`] for why), so their defaults
1361/// call the target *type*'s functions, `<Self::Target as
1362/// JmapAccounts>::principal_id(caller)`; that is the same answer, since the
1363/// caller context is the target's. A wrapper may still override them.
1364///
1365/// A type implements either this trait or [`JmapAccounts`], never both:
1366/// the blanket impl is the [`JmapAccounts`] impl of every type that
1367/// implements this one.
1368///
1369/// ```rust
1370/// use jmap_server::{DelegateJmapAccounts, Id, JmapAccounts};
1371/// # #[derive(Debug)]
1372/// # struct MyError;
1373/// # impl std::fmt::Display for MyError {
1374/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("e") }
1375/// # }
1376/// # impl std::error::Error for MyError {}
1377///
1378/// /// Some backend whose `max_objects_in_set` is not the default.
1379/// struct Inner;
1380///
1381/// impl JmapAccounts for Inner {
1382/// type Error = MyError;
1383/// type CallerCtx = ();
1384/// async fn account_exists(&self, _: &(), _: &Id) -> Result<bool, MyError> {
1385/// Ok(true)
1386/// }
1387/// fn max_objects_in_set(&self, _: &(), _: &Id) -> u64 {
1388/// 50
1389/// }
1390/// }
1391///
1392/// /// Knows only the accounts of its directory; every other answer is
1393/// /// `Inner`'s.
1394/// struct Wrapper {
1395/// inner: Inner,
1396/// directory: Vec<Id>,
1397/// }
1398///
1399/// impl DelegateJmapAccounts for Wrapper {
1400/// type Target = Inner;
1401///
1402/// fn jmap_accounts(&self) -> &Inner {
1403/// &self.inner
1404/// }
1405///
1406/// async fn account_exists(&self, _: &(), account_id: &Id) -> Result<bool, MyError> {
1407/// Ok(self.directory.contains(account_id))
1408/// }
1409/// }
1410///
1411/// let wrapper = Wrapper { inner: Inner, directory: vec![Id::from("a1")] };
1412/// // Through `JmapAccounts`, as a handler sees it: the limit is `Inner`'s.
1413/// assert_eq!(JmapAccounts::max_objects_in_set(&wrapper, &(), &Id::from("a1")), 50);
1414/// ```
1415///
1416/// # Method-call syntax
1417///
1418/// The wrapper has each method twice, once from each trait. With both
1419/// traits in scope, `wrapper.account_exists(..)` is ambiguous (E0034);
1420/// call it as `JmapAccounts::account_exists(&wrapper, ..)`. Generic code
1421/// bounded by `JmapAccounts` (every handler) is unaffected.
1422pub trait DelegateJmapAccounts: Send + Sync + 'static {
1423 /// The backend the answers come from.
1424 type Target: JmapAccounts;
1425
1426 /// The backend the answers come from.
1427 fn jmap_accounts(&self) -> &Self::Target;
1428
1429 /// [`JmapAccounts::account_exists`]; defaults to the target's.
1430 fn account_exists(
1431 &self,
1432 caller: &<Self::Target as JmapAccounts>::CallerCtx,
1433 account_id: &jmap_types::Id,
1434 ) -> impl std::future::Future<Output = Result<bool, <Self::Target as JmapAccounts>::Error>> + Send
1435 {
1436 self.jmap_accounts().account_exists(caller, account_id)
1437 }
1438
1439 /// [`JmapAccounts::principal_id`]; defaults to the target type's.
1440 fn principal_id(caller: &<Self::Target as JmapAccounts>::CallerCtx) -> Option<&jmap_types::Id> {
1441 <Self::Target as JmapAccounts>::principal_id(caller)
1442 }
1443
1444 /// [`JmapAccounts::accept_language`]; defaults to the target type's.
1445 fn accept_language(caller: &<Self::Target as JmapAccounts>::CallerCtx) -> Option<&str> {
1446 <Self::Target as JmapAccounts>::accept_language(caller)
1447 }
1448
1449 /// [`JmapAccounts::max_objects_in_set`]; defaults to the target's.
1450 fn max_objects_in_set(
1451 &self,
1452 caller: &<Self::Target as JmapAccounts>::CallerCtx,
1453 account_id: &jmap_types::Id,
1454 ) -> u64 {
1455 self.jmap_accounts().max_objects_in_set(caller, account_id)
1456 }
1457
1458 /// [`JmapAccounts::max_objects_in_get`]; defaults to the target's.
1459 fn max_objects_in_get(
1460 &self,
1461 caller: &<Self::Target as JmapAccounts>::CallerCtx,
1462 account_id: &jmap_types::Id,
1463 ) -> u64 {
1464 self.jmap_accounts().max_objects_in_get(caller, account_id)
1465 }
1466
1467 /// [`JmapAccounts::metadata_info`]; defaults to the target's.
1468 fn metadata_info<O: JmapObject>(
1469 &self,
1470 caller: &<Self::Target as JmapAccounts>::CallerCtx,
1471 account_id: &jmap_types::Id,
1472 ) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
1473 self.jmap_accounts().metadata_info::<O>(caller, account_id)
1474 }
1475
1476 /// [`JmapAccounts::i18n_info`]; defaults to the target's.
1477 fn i18n_info(
1478 &self,
1479 caller: &<Self::Target as JmapAccounts>::CallerCtx,
1480 account_id: &jmap_types::Id,
1481 ) -> Option<crate::I18nInfo> {
1482 self.jmap_accounts().i18n_info(caller, account_id)
1483 }
1484}
1485
1486impl<T: DelegateJmapAccounts> JmapAccounts for T {
1487 type Error = <T::Target as JmapAccounts>::Error;
1488 type CallerCtx = <T::Target as JmapAccounts>::CallerCtx;
1489
1490 fn account_exists(
1491 &self,
1492 caller: &Self::CallerCtx,
1493 account_id: &jmap_types::Id,
1494 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1495 DelegateJmapAccounts::account_exists(self, caller, account_id)
1496 }
1497
1498 fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
1499 <T as DelegateJmapAccounts>::principal_id(caller)
1500 }
1501
1502 fn accept_language(caller: &Self::CallerCtx) -> Option<&str> {
1503 <T as DelegateJmapAccounts>::accept_language(caller)
1504 }
1505
1506 fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1507 DelegateJmapAccounts::max_objects_in_set(self, caller, account_id)
1508 }
1509
1510 fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1511 DelegateJmapAccounts::max_objects_in_get(self, caller, account_id)
1512 }
1513
1514 fn metadata_info<O: JmapObject>(
1515 &self,
1516 caller: &Self::CallerCtx,
1517 account_id: &jmap_types::Id,
1518 ) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
1519 DelegateJmapAccounts::metadata_info::<O>(self, caller, account_id)
1520 }
1521
1522 fn i18n_info(
1523 &self,
1524 caller: &Self::CallerCtx,
1525 account_id: &jmap_types::Id,
1526 ) -> Option<crate::I18nInfo> {
1527 DelegateJmapAccounts::i18n_info(self, caller, account_id)
1528 }
1529}
1530
1531// ---------------------------------------------------------------------------
1532// Tests
1533// ---------------------------------------------------------------------------
1534
1535#[cfg(test)]
1536mod tests {
1537 use super::*;
1538
1539 /// Oracle (RFC 8620 §5.6): `CannotCalculate` maps to the
1540 /// `cannotCalculateChanges` wire error.
1541 #[test]
1542 fn backend_changes_error_cannot_calculate_maps_to_cannot_calculate_changes() {
1543 let err = jmap_types::JmapError::from(
1544 BackendChangesError::<std::convert::Infallible>::CannotCalculate,
1545 );
1546 assert_eq!(
1547 err.error_type.to_string(),
1548 "cannotCalculateChanges",
1549 "CannotCalculate must produce cannotCalculateChanges; got: {:?}",
1550 err.error_type
1551 );
1552 }
1553
1554 /// Oracle: BackendChangesError::TooManyChanges { limit: N } (N > 0) maps to
1555 /// tooManyChanges with the suggested limit.
1556 #[test]
1557 fn backend_changes_error_nonzero_limit_maps_to_too_many_changes() {
1558 let err = jmap_types::JmapError::from(
1559 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 50 },
1560 );
1561 assert_eq!(
1562 err.error_type.to_string(),
1563 "tooManyChanges",
1564 "limit=50 must produce tooManyChanges; got: {:?}",
1565 err.error_type
1566 );
1567 }
1568
1569 /// Oracle (CHANGELOG, fc81085f): "A zero limit now maps to
1570 /// tooManyChanges like any other value", so `limit: 0` is not an alias
1571 /// for `cannotCalculateChanges`. Expected wire object is hand-written.
1572 #[test]
1573 fn backend_changes_error_zero_limit_maps_to_too_many_changes() {
1574 let err = jmap_types::JmapError::from(
1575 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
1576 );
1577 assert_eq!(
1578 serde_json::to_value(&err).unwrap(),
1579 serde_json::json!({"type": "tooManyChanges", "limit": 0})
1580 );
1581 }
1582
1583 /// Oracle (bd:JMAP-jfia.1 / bd:JMAP-wlip.2): the
1584 /// `From<BackendChangesError<E>> for JmapError` impl MUST NOT echo
1585 /// the wrapped backend error's `Display` text into the resulting
1586 /// `JmapError`'s description. The defence-in-depth contract is that
1587 /// even if a backend implementor accidentally violates the
1588 /// [`JmapAccounts::Error`] Display MUST-NOT (credential / blob /
1589 /// PII), the leaked text never reaches the wire — and the
1590 /// ergonomic `.map_err(JmapError::from)?` path that
1591 /// `handle_changes` / `handle_query_changes` take on
1592 /// `BackendChangesError` must redact identically to the explicit
1593 /// `server_fail_from_backend(&e)` helper used elsewhere.
1594 ///
1595 /// Test vector: an `Other` variant whose Display contains a canary
1596 /// string resembling a credential leak. The canary literal is
1597 /// hand-built and not derived from any production type's
1598 /// behaviour. Mirrors
1599 /// `server_fail_from_backend_drops_display_text` in
1600 /// `handlers.rs`.
1601 #[test]
1602 fn backend_changes_error_other_drops_display_text() {
1603 #[derive(Debug)]
1604 struct LeakyError(&'static str);
1605 impl std::fmt::Display for LeakyError {
1606 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1607 f.write_str(self.0)
1608 }
1609 }
1610 impl std::error::Error for LeakyError {}
1611
1612 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1613 let err: BackendChangesError<LeakyError> = BackendChangesError::Other(LeakyError(CANARY));
1614
1615 let jmap_err = jmap_types::JmapError::from(err);
1616
1617 // Serialize to wire shape and assert the canary is absent from
1618 // the resulting JSON. The error_invocation wraps a JmapError as
1619 // { "type": "serverFail", "description": "..." } — both fields
1620 // are wire-visible.
1621 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1622 let wire_str = wire.to_string();
1623 assert!(
1624 !wire_str.contains(CANARY),
1625 "From<BackendChangesError<E>> for JmapError must not echo \
1626 backend error Display onto the wire; got {wire_str}"
1627 );
1628 // The description MUST be exactly SERVER_FAIL_INTERNAL_DESC.
1629 assert_eq!(
1630 wire["description"],
1631 crate::handlers::SERVER_FAIL_INTERNAL_DESC,
1632 "description must be the static 'internal error' string"
1633 );
1634 assert_eq!(wire["type"], "serverFail");
1635 }
1636
1637 /// Oracle (bd:JMAP-jfia.36): `into_set_error_or_method_error` on
1638 /// `Other` MUST NOT echo the wrapped error's `Display` text; the
1639 /// wire form is exactly `{"type":"serverFail","description":"internal
1640 /// error"}` (hand-written expected JSON). The canary literal is
1641 /// hand-built. Mirrors `backend_changes_error_other_drops_display_text`.
1642 #[test]
1643 fn backend_set_error_other_drops_display_text() {
1644 struct LeakyError(&'static str);
1645 impl std::fmt::Display for LeakyError {
1646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1647 f.write_str(self.0)
1648 }
1649 }
1650
1651 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1652 let err: BackendSetError<LeakyError> = BackendSetError::Other(LeakyError(CANARY));
1653
1654 let Err(jmap_err) = err.into_set_error_or_method_error() else {
1655 panic!("Other must map to a method-level JmapError");
1656 };
1657 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1658 assert!(
1659 !wire.to_string().contains(CANARY),
1660 "into_set_error_or_method_error must not echo backend Display; got {wire}"
1661 );
1662 assert_eq!(
1663 wire,
1664 serde_json::json!({"type": "serverFail", "description": "internal error"})
1665 );
1666 }
1667
1668 /// Oracle (RFC 8620 §5.3): a per-object `SetError` belongs in the
1669 /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
1670 /// arm must come back as `Ok` with its wire form intact
1671 /// (hand-written expected JSON).
1672 #[test]
1673 fn backend_set_error_set_error_passes_through() {
1674 let err: BackendSetError<std::fmt::Error> =
1675 BackendSetError::SetError(Box::new(SetError::new(SetErrorType::Forbidden)));
1676 let se = err
1677 .into_set_error_or_method_error()
1678 .expect("SetError arm must be Ok");
1679 assert_eq!(
1680 serde_json::to_value(&se).expect("SetError must serialize"),
1681 serde_json::json!({"type": "forbidden"})
1682 );
1683 }
1684
1685 /// Oracle (RFC 8620 §5.3): a per-object `SetError` is the
1686 /// `notCreated`/`notUpdated`/`notDestroyed` map value verbatim
1687 /// (hand-written expected JSON).
1688 #[test]
1689 fn backend_set_error_value_set_error_is_verbatim() {
1690 let err: BackendSetError<std::fmt::Error> = BackendSetError::SetError(Box::new(
1691 SetError::new(SetErrorType::NotFound).with_description("gone"),
1692 ));
1693 assert_eq!(
1694 backend_set_error_value(err),
1695 serde_json::json!({"type": "notFound", "description": "gone"})
1696 );
1697 }
1698
1699 /// Oracle (bd:JMAP-jfia.36): `Other` becomes exactly
1700 /// `{"type":"serverFail","description":"internal error"}` and never
1701 /// carries the wrapped error's `Display` text (hand-written expected
1702 /// JSON, hand-built canary).
1703 #[test]
1704 fn backend_set_error_value_other_is_redacted_server_fail() {
1705 const CANARY: &str = "TOKEN-DO-NOT-LEAK-5e7e44";
1706 let err: BackendSetError<&str> = BackendSetError::Other(CANARY);
1707 let wire = backend_set_error_value(err);
1708 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
1709 assert_eq!(
1710 wire,
1711 serde_json::json!({"type": "serverFail", "description": "internal error"})
1712 );
1713 }
1714
1715 /// Hand-built storage error for the stub backend and the error-envelope
1716 /// tests; its `Display` text is a fixed literal.
1717 #[derive(Debug)]
1718 struct StubError;
1719
1720 impl std::fmt::Display for StubError {
1721 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1722 f.write_str("stub")
1723 }
1724 }
1725 impl std::error::Error for StubError {}
1726
1727 /// Minimal backend that implements only the required trait methods, so
1728 /// tests observe the provided (default) methods. The required methods
1729 /// are never invoked.
1730 struct StubBackend;
1731
1732 impl JmapAccounts for StubBackend {
1733 type Error = StubError;
1734 type CallerCtx = ();
1735
1736 async fn account_exists(
1737 &self,
1738 _caller: &(),
1739 _account_id: &jmap_types::Id,
1740 ) -> Result<bool, Self::Error> {
1741 unreachable!("stub backend: only default methods are exercised")
1742 }
1743 }
1744
1745 impl JmapReads for StubBackend {
1746 async fn get_objects<O: GetObject + Send + Sync>(
1747 &self,
1748 _caller: &(),
1749 _account_id: &jmap_types::Id,
1750 _ids: Option<&[jmap_types::Id]>,
1751 _properties: Option<&[String]>,
1752 ) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
1753 unreachable!("stub backend: only default methods are exercised")
1754 }
1755
1756 async fn get_state<O: JmapObject + Send + Sync>(
1757 &self,
1758 _caller: &(),
1759 _account_id: &jmap_types::Id,
1760 ) -> Result<jmap_types::State, Self::Error> {
1761 unreachable!("stub backend: only default methods are exercised")
1762 }
1763
1764 async fn get_changes<O: JmapObject + Send + Sync>(
1765 &self,
1766 _caller: &(),
1767 _account_id: &jmap_types::Id,
1768 _params: ChangesParams<'_>,
1769 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1770 unreachable!("stub backend: only default methods are exercised")
1771 }
1772
1773 async fn query_objects<O: QueryObject + Send + Sync>(
1774 &self,
1775 _caller: &(),
1776 _account_id: &jmap_types::Id,
1777 _params: QueryParams<'_, O>,
1778 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1779 unreachable!("stub backend: only default methods are exercised")
1780 }
1781
1782 async fn query_changes<O: QueryObject + Send + Sync>(
1783 &self,
1784 _caller: &(),
1785 _account_id: &jmap_types::Id,
1786 _params: QueryChangesParams<'_, O>,
1787 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1788 unreachable!("stub backend: only default methods are exercised")
1789 }
1790 }
1791
1792 /// Oracle (bd:JMAP-ga0q.1): `JmapAccounts::principal_id` has a default impl
1793 /// that returns `None`. A backend whose `CallerCtx = ()` and that does NOT
1794 /// override `principal_id` inherits that default and signals "identity not
1795 /// wired" to callers. JMAP semantics that depend on caller identity must
1796 /// treat `None` as a hard "cannot honor".
1797 #[test]
1798 fn principal_id_default_impl_returns_none_for_unit_caller_ctx() {
1799 let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
1800 let id = <StubBackend as JmapAccounts>::principal_id(&caller);
1801 assert!(
1802 id.is_none(),
1803 "default principal_id impl must return None; got Some({:?})",
1804 id
1805 );
1806 }
1807
1808 /// Oracle (bd:JMAP-ayoz.41.1): `JmapAccounts::max_objects_in_set`
1809 /// has a default impl that returns `500`. The constant is the
1810 /// workspace's testjig Session JSON advertised cap; a backend that
1811 /// does not override the method inherits a sane DoS-defence
1812 /// default rather than silently disabling the cap.
1813 #[test]
1814 fn max_objects_in_set_default_impl_returns_500() {
1815 let backend = StubBackend;
1816 let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
1817 let id = jmap_types::Id::from("any-account");
1818 assert_eq!(
1819 backend.max_objects_in_set(&caller, &id),
1820 500,
1821 "default max_objects_in_set must return 500"
1822 );
1823 }
1824
1825 /// Oracle (trait docs, same rationale as `max_objects_in_set`): the
1826 /// default `JmapAccounts::max_objects_in_get` cap is `500`, so a backend
1827 /// that does not override it keeps the RFC 8620 §5.1 `requestTooLarge`
1828 /// guard enabled.
1829 #[test]
1830 fn max_objects_in_get_default_impl_returns_500() {
1831 let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
1832 let id = jmap_types::Id::from("any-account");
1833 assert_eq!(StubBackend.max_objects_in_get(&caller, &id), 500);
1834 }
1835
1836 /// Oracle: hand-written expected strings. The `SetError` arm prefixes
1837 /// the `SetError` Display (`<type>: <description>`), and `Other` is
1838 /// transparent over the wrapped error.
1839 #[test]
1840 fn backend_set_error_display() {
1841 let se: BackendSetError<StubError> = BackendSetError::SetError(Box::new(
1842 SetError::new(SetErrorType::NotFound).with_description("gone"),
1843 ));
1844 assert_eq!(se.to_string(), "set error: notFound: gone");
1845 assert_eq!(BackendSetError::Other(StubError).to_string(), "stub");
1846 }
1847
1848 /// Oracle: hand-written expected strings for every variant.
1849 #[test]
1850 fn backend_changes_error_display() {
1851 assert_eq!(
1852 BackendChangesError::<StubError>::CannotCalculate.to_string(),
1853 "cannot calculate changes"
1854 );
1855 assert_eq!(
1856 BackendChangesError::<StubError>::TooManyChanges { limit: 7 }.to_string(),
1857 "too many changes (limit: 7)"
1858 );
1859 assert_eq!(BackendChangesError::Other(StubError).to_string(), "stub");
1860 }
1861
1862 /// Oracle: `Method` displays the wrapped `JmapError` unchanged and
1863 /// `Other` is transparent over the wrapped error (hand-written strings).
1864 #[test]
1865 fn backend_query_error_display() {
1866 let method = jmap_types::JmapError::server_fail("x");
1867 let expected = method.to_string();
1868 assert_eq!(
1869 BackendQueryError::<StubError>::Method(method).to_string(),
1870 expected
1871 );
1872 assert_eq!(BackendQueryError::Other(StubError).to_string(), "stub");
1873 }
1874
1875 /// Oracle (`std::error::Error::source` contract): only the `Other`
1876 /// variant wraps an underlying error, so only it reports a source, and
1877 /// that source is the wrapped value.
1878 #[test]
1879 fn backend_errors_source_is_wrapped_other_only() {
1880 use std::error::Error as _;
1881
1882 let is_stub = |e: Option<&(dyn std::error::Error + 'static)>| {
1883 e.is_some_and(|s| s.downcast_ref::<StubError>().is_some())
1884 };
1885
1886 assert!(is_stub(BackendSetError::Other(StubError).source()));
1887 assert!(
1888 BackendSetError::<StubError>::from(SetError::new(SetErrorType::Forbidden))
1889 .source()
1890 .is_none()
1891 );
1892
1893 assert!(is_stub(BackendChangesError::from(StubError).source()));
1894 assert!(
1895 BackendChangesError::<StubError>::CannotCalculate
1896 .source()
1897 .is_none()
1898 );
1899 assert!(
1900 BackendChangesError::<StubError>::TooManyChanges { limit: 1 }
1901 .source()
1902 .is_none()
1903 );
1904
1905 assert!(is_stub(BackendQueryError::from(StubError).source()));
1906 assert!(
1907 BackendQueryError::<StubError>::Method(jmap_types::JmapError::server_fail("x"))
1908 .source()
1909 .is_none()
1910 );
1911 }
1912}