jmap_server/backend.rs
1//! Shared backend infrastructure for all JMAP server crates.
2//!
3//! Re-exports the marker traits 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::{GetObject, JmapObject, QueryObject, SetObject};
8
9// ---------------------------------------------------------------------------
10// SetError — RFC 8620 §5.3 per-object set-method error
11// ---------------------------------------------------------------------------
12
13/// A per-item error in a `/set` response (`notCreated`, `notUpdated`,
14/// `notDestroyed` maps) (RFC 8620 §5.3).
15///
16/// Construct with [`SetError::new`] and chain the builder methods as needed.
17#[non_exhaustive]
18#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct SetError {
21 /// The machine-readable error type.
22 #[serde(rename = "type")]
23 pub error_type: SetErrorType,
24 /// Optional human-readable description of the error.
25 #[serde(skip_serializing_if = "Option::is_none")]
26 pub description: Option<String>,
27 /// Property names that caused the error (for `invalidProperties`).
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub properties: Option<Vec<String>>,
30 /// The existing object id (for `alreadyExists` — RFC 8621 §5.7).
31 #[serde(rename = "existingId", skip_serializing_if = "Option::is_none")]
32 pub existing_id: Option<jmap_types::Id>,
33 /// Maximum recipients allowed (for `tooManyRecipients` — RFC 8621 §7.5).
34 #[serde(rename = "maxRecipients", skip_serializing_if = "Option::is_none")]
35 pub max_recipients: Option<u64>,
36 /// Invalid recipient addresses (for `invalidRecipients` — RFC 8621 §7.5).
37 #[serde(rename = "invalidRecipients", skip_serializing_if = "Option::is_none")]
38 pub invalid_recipients: Option<Vec<String>>,
39 /// Missing blob IDs (for `blobNotFound` — RFC 8621 §5.5).
40 #[serde(rename = "notFound", skip_serializing_if = "Option::is_none")]
41 pub not_found: Option<Vec<jmap_types::Id>>,
42 /// Maximum message size in octets (for `tooLarge` on EmailSubmission — RFC 8621 §7.5).
43 #[serde(rename = "maxSize", skip_serializing_if = "Option::is_none")]
44 pub max_size: Option<u64>,
45 /// Catch-all for extension-defined SetError fields not covered by
46 /// the typed members above.
47 ///
48 /// JMAP extensions sometimes ship error variants whose wire shape
49 /// includes additional structured fields beyond the RFC 8620 §5.3
50 /// base set — e.g. JMAP Chat's `rateLimited` SetError carries a
51 /// `serverRetryAfter` UTCDate telling the client when it may
52 /// retry, and `mdnAlreadySent` (RFC 8621 §7.7) is a typed
53 /// extension error variant. This map preserves any such field
54 /// across serialize / deserialize round-trip, mirroring the
55 /// extras-preservation policy on the client-side
56 /// [`jmap_types::SetError`] type.
57 ///
58 /// Use [`SetError::with_extra`] to populate from handler code:
59 ///
60 /// ```ignore
61 /// SetError::new(SetErrorType::custom("rateLimited"))
62 /// .with_description("Slow mode is active for this chat")
63 /// .with_extra("serverRetryAfter", json!(retry_after_str))
64 /// ```
65 ///
66 /// Per workspace AGENTS.md "Extras-preservation policy" — wire
67 /// format is byte-identical to a pre-extras SetError when the
68 /// map is empty (the `skip_serializing_if` collapses it).
69 ///
70 /// # Reserved-name invariant (bd:JMAP-jfia.17)
71 ///
72 /// Keys in [`RESERVED_SET_ERROR_WIRE_NAMES`] MUST NOT appear in
73 /// this map. The typed fields above serialize to those names, so
74 /// a colliding extras key produces a JSON object with two keys at
75 /// the same level — RFC 8259 §4 permits duplicate keys but the
76 /// behaviour is implementation-defined and the resulting SetError
77 /// is malformed in practice.
78 ///
79 /// [`SetError::with_extra`] enforces this in debug builds via
80 /// `debug_assert!`; direct field mutation (this field is `pub` per
81 /// the workspace extras-preservation policy) bypasses that guard.
82 /// Test and audit code SHOULD call [`SetError::validate_extras`]
83 /// to detect collisions deterministically across build profiles.
84 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
85 pub extra: serde_json::Map<String, serde_json::Value>,
86}
87
88impl SetError {
89 /// Construct a [`SetError`] with the given type and all optional fields `None`.
90 pub fn new(error_type: SetErrorType) -> Self {
91 Self {
92 error_type,
93 description: None,
94 properties: None,
95 existing_id: None,
96 max_recipients: None,
97 invalid_recipients: None,
98 not_found: None,
99 max_size: None,
100 extra: serde_json::Map::new(),
101 }
102 }
103
104 /// Set the human-readable description.
105 ///
106 /// # Security
107 ///
108 /// `SetError.description` is serialized verbatim into the JMAP wire
109 /// response (RFC 8620 §5.3 `notCreated` / `notUpdated` /
110 /// `notDestroyed` maps) and is visible to any client that can
111 /// dispatch the failing `/set` call. The MUST-NOT rules that apply
112 /// to [`JmapBackend::Error`]'s [`Display`](std::fmt::Display) output
113 /// also apply to this string:
114 ///
115 /// - **Credential material** — auth tokens, passwords, push
116 /// verification codes, invite codes, session cookies, or anything
117 /// derived byte-for-byte from an `Authorization`-header value.
118 /// - **Blob content** — email bodies, sieve scripts, file
119 /// contents, or any user-supplied opaque payload.
120 /// - **PII shaped like an email address** in any code path that
121 /// an unauthenticated caller can trigger.
122 ///
123 /// Wrap downstream errors with [`crate::server_fail_from_backend`]
124 /// (which always emits the static "internal error" description)
125 /// rather than interpolating them into a SetError description.
126 ///
127 /// `SetError` paths are MORE leak-prone than `serverFail` because
128 /// adversarial clients can probe for descriptions by sending
129 /// crafted `/set` arguments — the typed-error contract guarantees
130 /// the response includes a `SetError` for every failing target.
131 /// Static, caller-meaningful descriptions ("rate limit exceeded —
132 /// retry in N seconds", "patch nesting exceeds server limit") are
133 /// fine; backend-error interpolations are not.
134 ///
135 /// Precedent: the parallel contract on
136 /// [`JmapBackend::Error`] (bd:JMAP-sc1b.100) and the matching
137 /// handler-side leak path closed in bd:JMAP-wlip.2. This warning
138 /// added in bd:JMAP-wlip.26.
139 pub fn with_description(mut self, desc: impl Into<String>) -> Self {
140 self.description = Some(desc.into());
141 self
142 }
143
144 /// Set the list of property names that caused the error.
145 pub fn with_properties<I, S>(mut self, props: I) -> Self
146 where
147 I: IntoIterator<Item = S>,
148 S: Into<String>,
149 {
150 self.properties = Some(props.into_iter().map(|s| s.into()).collect());
151 self
152 }
153
154 /// Set the existing object id (used with `alreadyExists`).
155 pub fn with_existing_id(mut self, id: jmap_types::Id) -> Self {
156 self.existing_id = Some(id);
157 self
158 }
159
160 /// Set the maximum recipients (used with `tooManyRecipients` — RFC 8621 §7.5).
161 pub fn with_max_recipients(mut self, n: u64) -> Self {
162 self.max_recipients = Some(n);
163 self
164 }
165
166 /// Set the invalid recipient addresses (used with `invalidRecipients` — RFC 8621 §7.5).
167 pub fn with_invalid_recipients<I, S>(mut self, addrs: I) -> Self
168 where
169 I: IntoIterator<Item = S>,
170 S: Into<String>,
171 {
172 self.invalid_recipients = Some(addrs.into_iter().map(|s| s.into()).collect());
173 self
174 }
175
176 /// Set the missing blob IDs (used with `blobNotFound` — RFC 8621 §5.5).
177 pub fn with_not_found(mut self, ids: Vec<jmap_types::Id>) -> Self {
178 self.not_found = Some(ids);
179 self
180 }
181
182 /// Set the maximum message size in octets (used with `tooLarge` on EmailSubmission — RFC 8621 §7.5).
183 pub fn with_max_size(mut self, n: u64) -> Self {
184 self.max_size = Some(n);
185 self
186 }
187
188 /// Insert an extension-defined field into [`Self::extra`].
189 ///
190 /// Used by handlers to attach typed wire fields that no `with_*`
191 /// builder covers — for example JMAP Chat's `rateLimited` SetError
192 /// must carry a `serverRetryAfter` UTCDate:
193 ///
194 /// ```ignore
195 /// SetError::new(SetErrorType::custom("rateLimited"))
196 /// .with_description("Slow mode is active for this chat")
197 /// .with_extra("serverRetryAfter", serde_json::json!(retry_after_str))
198 /// ```
199 ///
200 /// The serialized wire shape merges `key`/`value` at the same
201 /// level as the typed fields (via `#[serde(flatten)]` on
202 /// [`Self::extra`]). Calling `with_extra("type", ...)`,
203 /// `with_extra("properties", ...)`, or any other reserved
204 /// wire-name will produce a malformed SetError on the wire —
205 /// callers are responsible for choosing extension-namespace keys
206 /// that do not collide with the typed-field wire names.
207 ///
208 /// In debug builds, a `with_extra(key, ...)` call where `key` is in
209 /// the reserved set [`RESERVED_SET_ERROR_WIRE_NAMES`] panics via
210 /// `debug_assert!` to catch the bug at first test run
211 /// (bd:JMAP-wlip.3). Release builds preserve the current
212 /// no-validation behaviour to avoid silent runtime cost on a
213 /// correctly-written caller.
214 pub fn with_extra(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
215 // bd:JMAP-jfia.32 — accept impl Into<String> to match the
216 // sibling builders on the same type (with_description,
217 // with_properties, with_invalid_recipients). Existing
218 // &str-passing call sites compile unchanged via
219 // impl From<&str> for String.
220 let key: String = key.into();
221 debug_assert!(
222 !RESERVED_SET_ERROR_WIRE_NAMES.contains(&key.as_str()),
223 "SetError::with_extra called with reserved wire-name key {key:?} \
224 — would produce a malformed JSON SetError on the wire. \
225 Choose an extension-namespace key that does not collide \
226 with the typed-field wire names \
227 ({RESERVED_SET_ERROR_WIRE_NAMES:?})."
228 );
229 self.extra.insert(key, value);
230 self
231 }
232
233 /// Validate that [`Self::extra`] does not contain any key in
234 /// [`RESERVED_SET_ERROR_WIRE_NAMES`] (bd:JMAP-jfia.17).
235 ///
236 /// [`Self::with_extra`] enforces the same invariant in debug builds
237 /// via `debug_assert!`, but direct field mutation (e.g.
238 /// `err.extra.insert("type", json!("evil"))`) bypasses that guard.
239 /// This method is the deterministic, build-profile-independent
240 /// gate: callers and tests that construct SetError values
241 /// programmatically should run it before serializing, to catch
242 /// the collision case that would produce a malformed wire shape
243 /// with two keys at the same name.
244 ///
245 /// Returns the first colliding key on `Err`; check `validate_extras`
246 /// in a loop if you need to surface all collisions.
247 ///
248 /// # Errors
249 ///
250 /// Returns [`ReservedExtrasKey`] with the first reserved key
251 /// encountered in [`Self::extra`].
252 pub fn validate_extras(&self) -> Result<(), ReservedExtrasKey> {
253 for key in self.extra.keys() {
254 if RESERVED_SET_ERROR_WIRE_NAMES.contains(&key.as_str()) {
255 return Err(ReservedExtrasKey { key: key.clone() });
256 }
257 }
258 Ok(())
259 }
260}
261
262/// Returned by [`SetError::validate_extras`] when [`SetError::extra`]
263/// contains a key that collides with a typed-field wire-name in
264/// [`RESERVED_SET_ERROR_WIRE_NAMES`] (bd:JMAP-jfia.17).
265#[non_exhaustive]
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct ReservedExtrasKey {
268 /// The first reserved wire-name found in `SetError.extra`.
269 pub key: String,
270}
271
272impl std::fmt::Display for ReservedExtrasKey {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 write!(
275 f,
276 "SetError.extra contains reserved wire-name key {:?} — would \
277 produce a malformed JSON SetError on the wire",
278 self.key
279 )
280 }
281}
282
283impl std::error::Error for ReservedExtrasKey {}
284
285/// Reserved wire-name keys that [`SetError::with_extra`] MUST NOT receive.
286///
287/// These are the JSON keys emitted by the typed `#[serde(rename)]` /
288/// `#[serde(rename_all = "camelCase")]` fields on [`SetError`]. Passing
289/// any of these as the `key` argument to `with_extra` would produce a
290/// JSON object with two keys at the same name — technically RFC 8259
291/// §4 permits duplicate keys but the behaviour is implementation-defined
292/// and the resulting SetError on the wire is malformed in practice.
293///
294/// Kept here as a `pub const` rather than inline in the assert message
295/// so consumers can reference the same list — e.g. a future contract
296/// test, or a wire-format conformance check.
297pub const RESERVED_SET_ERROR_WIRE_NAMES: &[&str] = &[
298 "type",
299 "description",
300 "properties",
301 "existingId",
302 "maxRecipients",
303 "invalidRecipients",
304 "notFound",
305 "maxSize",
306];
307
308impl std::fmt::Display for SetError {
309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310 write!(f, "{}", self.error_type)?;
311 if let Some(ref desc) = self.description {
312 write!(f, ": {desc}")?;
313 }
314 Ok(())
315 }
316}
317
318/// The machine-readable type for a [`SetError`] (RFC 8620 §5.3 and RFC 8621).
319///
320/// # Variant policy
321///
322/// The variant set below carries:
323///
324/// - The 10 RFC 8620 §5.3 base error types
325/// (`Forbidden`, `OverQuota`, `TooLarge`, `RateLimit`, `NotFound`,
326/// `InvalidPatch`, `WillDestroy`, `InvalidProperties`, `Singleton`,
327/// `AlreadyExists`).
328/// - 13 RFC 8621 mail-specific error types
329/// (`MailboxHasChild`, `MailboxHasEmail`, `TooManyKeywords`,
330/// `TooManyMailboxes`, `BlobNotFound`, `ForbiddenFrom`,
331/// `InvalidEmail`, `TooManyRecipients`, `NoRecipients`,
332/// `InvalidRecipients`, `ForbiddenMailFrom`, `ForbiddenToSend`,
333/// `CannotUnsend`). These predate the canonical-template extraction
334/// and ship in the foundation for back-compat with existing
335/// `jmap-mail-server` callers (bd:JMAP-wlip.19).
336/// - [`Self::Custom`] for everything else.
337///
338/// **New extension errors MUST use [`Self::custom`].** Other JMAP
339/// extensions (chat, calendars, tasks, contacts, filenode, sharing,
340/// metadata) ship their error strings via `custom("rateLimited")`,
341/// `custom("addressBookHasContents")`, `custom("invalidSieve")`, etc.
342/// The known wire-name table inside the private `from_wire_str` helper
343/// is the authoritative list of typed variants — any wire-name outside
344/// that list round-trips as `Custom(s)`.
345///
346/// The mail-variants asymmetry is documented but not yet reshaped.
347/// Moving the 13 mail variants to `jmap-mail-types` is a breaking
348/// change that requires a workspace-wide major version bump and
349/// propagation across every `*-server` extension crate; it is tracked
350/// separately rather than performed silently. Until that bump, do not
351/// add further extension-specific variants here — even mail-style
352/// extensions like Calendars / Tasks / Contacts use [`Self::custom`].
353#[non_exhaustive]
354#[derive(Debug, Clone, PartialEq)]
355pub enum SetErrorType {
356 /// The action would violate an ACL or other access control policy.
357 Forbidden,
358 /// Creating or modifying the object would exceed a server quota.
359 OverQuota,
360 /// The object is too large to be stored by the server.
361 TooLarge,
362 /// The server is rate-limiting this client.
363 RateLimit,
364 /// The object to be updated or destroyed does not exist.
365 NotFound,
366 /// The patch object is not a valid JSON Merge Patch or cannot be applied.
367 InvalidPatch,
368 /// The client requested destruction of an object that will be destroyed
369 /// implicitly when another object is destroyed.
370 WillDestroy,
371 /// One or more properties have invalid values.
372 InvalidProperties,
373 /// The object type is a singleton and cannot be created or destroyed.
374 Singleton,
375 /// An object with the same unique key already exists.
376 AlreadyExists,
377 /// RFC 8621 §2.5 — Mailbox has child mailboxes and cannot be destroyed.
378 MailboxHasChild,
379 /// RFC 8621 §2.5 — Mailbox contains emails and `onDestroyRemoveEmails` is false.
380 MailboxHasEmail,
381 /// RFC 8621 §5.5 — Too many keywords on the Email.
382 TooManyKeywords,
383 /// RFC 8621 §5.5 — Email is in too many mailboxes.
384 TooManyMailboxes,
385 /// RFC 8621 §5.5 — A referenced blob was not found.
386 BlobNotFound,
387 /// RFC 8621 §6.3 — The `from` address is not permitted for this Identity.
388 ForbiddenFrom,
389 /// RFC 8621 §7.5 — The Email is invalid for submission.
390 InvalidEmail,
391 /// RFC 8621 §7.5 — Too many recipients.
392 TooManyRecipients,
393 /// RFC 8621 §7.5 — No recipients specified.
394 NoRecipients,
395 /// RFC 8621 §7.5 — One or more recipient addresses are invalid.
396 InvalidRecipients,
397 /// RFC 8621 §7.5 — The MAIL FROM address is not permitted.
398 ForbiddenMailFrom,
399 /// RFC 8621 §7.5 — The user does not have send permission.
400 ForbiddenToSend,
401 /// RFC 8621 §7.5 — The submission cannot be undone.
402 CannotUnsend,
403 /// An extension-defined error type not covered by the variants above.
404 /// Serializes as the inner string directly (e.g. `"mdnAlreadySent"`).
405 Custom(String),
406}
407
408impl SetErrorType {
409 /// Construct a [`SetErrorType`] from any string, canonicalising
410 /// known wire-names back to their typed variant.
411 ///
412 /// `custom("forbidden")` returns [`SetErrorType::Forbidden`], NOT
413 /// `Custom("forbidden")`. Only strings that do not match any known
414 /// JMAP wire-name produce [`SetErrorType::Custom`]. This makes
415 /// round-trip symmetric — `custom(s)` equals the result of
416 /// deserialising `"s"` for every `s`, eliminating the silent
417 /// contract drift filed as bd:JMAP-wlip.22.
418 ///
419 /// Use this in extension crates to emit domain-specific error
420 /// types without adding variants to this enum; if your extension's
421 /// chosen name later becomes a typed variant in this crate, the
422 /// call site keeps working — `custom("mdnAlreadySent")` returns
423 /// `Custom("mdnAlreadySent")` today and would return the typed
424 /// variant when that variant is added.
425 pub fn custom(s: impl Into<String>) -> Self {
426 let s: String = s.into();
427 Self::from_wire_str(&s).unwrap_or(Self::Custom(s))
428 }
429
430 /// Map a JMAP wire-name string to its typed variant, returning
431 /// `None` for any string not in the known-name set.
432 ///
433 /// Single source of truth used by both [`Self::custom`] and the
434 /// [`serde::Deserialize`] visitor (bd:JMAP-wlip.22). Adding a new
435 /// typed variant requires extending this match arm AND the
436 /// `Display` impl; the table-driven round-trip test
437 /// `set_error_type_all_known_variants_round_trip` (bd:JMAP-wlip.29)
438 /// catches any drift between them.
439 fn from_wire_str(s: &str) -> Option<Self> {
440 Some(match s {
441 "forbidden" => Self::Forbidden,
442 "overQuota" => Self::OverQuota,
443 "tooLarge" => Self::TooLarge,
444 "rateLimit" => Self::RateLimit,
445 "notFound" => Self::NotFound,
446 "invalidPatch" => Self::InvalidPatch,
447 "willDestroy" => Self::WillDestroy,
448 "invalidProperties" => Self::InvalidProperties,
449 "singleton" => Self::Singleton,
450 "alreadyExists" => Self::AlreadyExists,
451 "mailboxHasChild" => Self::MailboxHasChild,
452 "mailboxHasEmail" => Self::MailboxHasEmail,
453 "tooManyKeywords" => Self::TooManyKeywords,
454 "tooManyMailboxes" => Self::TooManyMailboxes,
455 "blobNotFound" => Self::BlobNotFound,
456 "forbiddenFrom" => Self::ForbiddenFrom,
457 "invalidEmail" => Self::InvalidEmail,
458 "tooManyRecipients" => Self::TooManyRecipients,
459 "noRecipients" => Self::NoRecipients,
460 "invalidRecipients" => Self::InvalidRecipients,
461 "forbiddenMailFrom" => Self::ForbiddenMailFrom,
462 "forbiddenToSend" => Self::ForbiddenToSend,
463 "cannotUnsend" => Self::CannotUnsend,
464 _ => return None,
465 })
466 }
467}
468
469impl std::fmt::Display for SetErrorType {
470 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471 let s: &str = match self {
472 Self::Forbidden => "forbidden",
473 Self::OverQuota => "overQuota",
474 Self::TooLarge => "tooLarge",
475 Self::RateLimit => "rateLimit",
476 Self::NotFound => "notFound",
477 Self::InvalidPatch => "invalidPatch",
478 Self::WillDestroy => "willDestroy",
479 Self::InvalidProperties => "invalidProperties",
480 Self::Singleton => "singleton",
481 Self::AlreadyExists => "alreadyExists",
482 Self::MailboxHasChild => "mailboxHasChild",
483 Self::MailboxHasEmail => "mailboxHasEmail",
484 Self::TooManyKeywords => "tooManyKeywords",
485 Self::TooManyMailboxes => "tooManyMailboxes",
486 Self::BlobNotFound => "blobNotFound",
487 Self::ForbiddenFrom => "forbiddenFrom",
488 Self::InvalidEmail => "invalidEmail",
489 Self::TooManyRecipients => "tooManyRecipients",
490 Self::NoRecipients => "noRecipients",
491 Self::InvalidRecipients => "invalidRecipients",
492 Self::ForbiddenMailFrom => "forbiddenMailFrom",
493 Self::ForbiddenToSend => "forbiddenToSend",
494 Self::CannotUnsend => "cannotUnsend",
495 Self::Custom(s) => s.as_str(),
496 };
497 f.write_str(s)
498 }
499}
500
501impl serde::Serialize for SetErrorType {
502 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
503 // bd:JMAP-jfia.33 — collect_str avoids the per-call String
504 // allocation that `s.serialize_str(&self.to_string())` does.
505 // serde_json's collect_str uses a stack buffer for short
506 // strings; every SetErrorType variant's Display is short
507 // enough to fit. The round-trip oracle
508 // set_error_type_all_known_variants_round_trip pins
509 // wire-format identity.
510 s.collect_str(self)
511 }
512}
513
514impl<'de> serde::Deserialize<'de> for SetErrorType {
515 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
516 struct Visitor;
517 impl serde::de::Visitor<'_> for Visitor {
518 type Value = SetErrorType;
519 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520 f.write_str("a JMAP SetError type string")
521 }
522 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
523 // Single source of truth shared with [`SetErrorType::custom`]
524 // (bd:JMAP-wlip.22). An unknown wire-name falls through to
525 // Custom; a known wire-name canonicalises to its typed
526 // variant so that round-trip is symmetric.
527 Ok(SetErrorType::from_wire_str(v)
528 .unwrap_or_else(|| SetErrorType::Custom(v.to_owned())))
529 }
530 }
531 d.deserialize_str(Visitor)
532 }
533}
534
535/// Error type returned by create/update/destroy backend methods.
536#[non_exhaustive]
537#[derive(Debug)]
538pub enum BackendSetError<E> {
539 /// A well-typed JMAP [`SetError`] to place verbatim in the
540 /// `notCreated`/`notUpdated`/`notDestroyed` map.
541 SetError(SetError),
542 /// An unexpected storage-layer error.
543 Other(E),
544}
545
546impl<E: std::fmt::Display> std::fmt::Display for BackendSetError<E> {
547 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548 match self {
549 Self::SetError(se) => write!(f, "set error: {se}"),
550 Self::Other(e) => write!(f, "{e}"),
551 }
552 }
553}
554
555impl<E: std::error::Error + 'static> std::error::Error for BackendSetError<E> {
556 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
557 match self {
558 Self::Other(e) => Some(e),
559 _ => None,
560 }
561 }
562}
563
564impl<E> From<SetError> for BackendSetError<E> {
565 fn from(e: SetError) -> Self {
566 Self::SetError(e)
567 }
568}
569
570impl<E: std::fmt::Display> BackendSetError<E> {
571 /// Split into the per-object [`SetError`] (`Ok`) or a redacted
572 /// method-level `serverFail` (`Err`).
573 ///
574 /// RFC 8620 §5.3 places a per-object `SetError` in the
575 /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
576 /// variant is returned unchanged for the caller to insert there.
577 /// [`Other`](Self::Other) becomes
578 /// `JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)`: the inner
579 /// error's `Display` text never reaches the wire (bd:JMAP-jfia.36).
580 ///
581 /// There is deliberately no `From<BackendSetError<E>> for JmapError`:
582 /// a `?` on that impl would turn per-object set errors into
583 /// method-level errors.
584 ///
585 /// [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
586 ///
587 /// # Errors
588 ///
589 /// Returns the redacted `serverFail` [`JmapError`](jmap_types::JmapError) for
590 /// [`Other`](Self::Other).
591 pub fn into_set_error_or_method_error(self) -> Result<SetError, jmap_types::JmapError> {
592 match self {
593 Self::SetError(se) => Ok(se),
594 Self::Other(e) => Err(crate::handlers::server_fail_from_backend(&e)),
595 }
596 }
597}
598
599// ---------------------------------------------------------------------------
600// Backend error envelopes
601// ---------------------------------------------------------------------------
602
603/// Error type returned by [`JmapBackend::get_changes`] and
604/// [`JmapBackend::query_changes`].
605///
606/// # `CannotCalculate` vs `TooManyChanges`
607///
608/// The two non-`Other` variants map to two distinct JMAP wire errors
609/// (RFC 8620 §5.6). Previously a single `TooManyChanges { limit: 0 }`
610/// variant overloaded both meanings via a magic-zero sentinel; the
611/// `CannotCalculate` variant was added in bd:JMAP-jfia.31 to surface
612/// the distinction at the type level. `TooManyChanges { limit: 0 }`
613/// is preserved as a **permanent** legacy alias — it still maps to
614/// `cannotCalculateChanges` via the `From` and `Display` impls — but
615/// new backends SHOULD construct `CannotCalculate` directly. See the
616/// `TooManyChanges` variant docs for why the alias cannot be
617/// `#[deprecated]` at the type level (bd:JMAP-jfia.37).
618#[non_exhaustive]
619#[derive(Debug)]
620pub enum BackendChangesError<E> {
621 /// The server has no usable change log for the given `sinceState`
622 /// and cannot supply incremental changes — the client MUST
623 /// discard ALL locally cached objects for the affected type,
624 /// reset its local state token to the empty string, and perform a
625 /// full resync (`/get` with `ids: null`). Partial recovery is not
626 /// permitted. Maps to `cannotCalculateChanges` (RFC 8620 §5.6;
627 /// authoritative behavior documented in jmapio/jmap-js
628 /// `mail-model.js`).
629 ///
630 /// Added in bd:JMAP-jfia.31 to replace the
631 /// `TooManyChanges { limit: 0 }` magic-zero overload. New backends
632 /// SHOULD construct `CannotCalculate` directly; legacy backends
633 /// that emit `TooManyChanges { limit: 0 }` still map to the same
634 /// wire error via the permanent legacy alias (bd:JMAP-jfia.37).
635 CannotCalculate,
636 /// The change window exceeds what the server can supply in a
637 /// single `/changes` response. Maps to `tooManyChanges` with the
638 /// `limit` as the suggested maximum — the client may retry with
639 /// a smaller window.
640 ///
641 /// **Legacy sub-case (bd:JMAP-jfia.31, bd:JMAP-jfia.37)**: a
642 /// `limit` of `0` historically meant "full state reset
643 /// required" and is preserved as an alias for the new
644 /// [`Self::CannotCalculate`] variant. New code SHOULD use
645 /// `CannotCalculate` directly. The alias is **permanent** at
646 /// the type level — Rust cannot `#[deprecated]` a single
647 /// discriminator value of an enum variant without deprecating
648 /// the variant itself, and removing the alias would silently
649 /// break any backend still emitting `TooManyChanges { limit: 0 }`
650 /// (their returns would stop mapping to `cannotCalculateChanges`
651 /// and start emitting a malformed RFC 8620 §5.6 `tooManyChanges`
652 /// with `limit: 0`). The `From` and `Display` impls below pin
653 /// the alias semantics permanently. Match arms in extension
654 /// servers SHOULD treat `TooManyChanges { limit: 0 }` and
655 /// `CannotCalculate` as a single "full-resync required" case
656 /// rather than branching them apart.
657 TooManyChanges {
658 /// Maximum window size the server can supply in a single
659 /// `/changes` response. A value of `0` is the permanent
660 /// legacy alias for [`Self::CannotCalculate`]; any non-zero
661 /// value is the suggested maximum the client may retry with.
662 limit: u64,
663 },
664 /// An unexpected storage-layer error.
665 Other(E),
666}
667
668impl<E: std::fmt::Display> std::fmt::Display for BackendChangesError<E> {
669 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
670 match self {
671 Self::CannotCalculate => write!(f, "cannot calculate changes"),
672 // Permanent legacy alias (bd:JMAP-jfia.31, bd:JMAP-jfia.37).
673 Self::TooManyChanges { limit: 0 } => write!(f, "cannot calculate changes"),
674 Self::TooManyChanges { limit } => write!(f, "too many changes (limit: {limit})"),
675 Self::Other(e) => write!(f, "{e}"),
676 }
677 }
678}
679
680impl<E: std::error::Error + 'static> std::error::Error for BackendChangesError<E> {
681 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
682 match self {
683 Self::Other(e) => Some(e),
684 _ => None,
685 }
686 }
687}
688
689impl<E> From<E> for BackendChangesError<E> {
690 fn from(e: E) -> Self {
691 Self::Other(e)
692 }
693}
694
695impl<E: std::error::Error> From<BackendChangesError<E>> for jmap_types::JmapError {
696 fn from(e: BackendChangesError<E>) -> Self {
697 match e {
698 BackendChangesError::CannotCalculate => {
699 jmap_types::JmapError::cannot_calculate_changes()
700 }
701 // Permanent legacy alias for CannotCalculate
702 // (bd:JMAP-jfia.31, bd:JMAP-jfia.37). Preserved so
703 // backends that emit TooManyChanges { limit: 0 } produce
704 // the correct wire error. The variant docs explain why
705 // this cannot be #[deprecated] at the type level.
706 BackendChangesError::TooManyChanges { limit: 0 } => {
707 jmap_types::JmapError::cannot_calculate_changes()
708 }
709 BackendChangesError::TooManyChanges { limit } => {
710 jmap_types::JmapError::too_many_changes_with_limit(limit)
711 }
712 // bd:JMAP-jfia.1 / bd:JMAP-wlip.2 — the `Other` arm wraps a
713 // backend `Error` whose `Display` impl is contractually
714 // forbidden from carrying credential/blob/PII text but which
715 // we still treat as untrusted at the wire boundary. Use the
716 // same static [`SERVER_FAIL_INTERNAL_DESC`] string that the
717 // [`server_fail_from_backend`] handler-layer helper uses so
718 // the defence-in-depth chain (backend Display contract →
719 // handler helper → this From impl) cannot be bypassed by
720 // handlers that take the ergonomic `.map_err(JmapError::from)?`
721 // path on `BackendChangesError`.
722 //
723 // [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
724 // [`server_fail_from_backend`]: crate::handlers::server_fail_from_backend
725 BackendChangesError::Other(_inner) => {
726 jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
727 }
728 }
729 }
730}
731
732/// Error type returned by [`JmapBackend::query_objects`].
733///
734/// RFC 8620 §5.5 lets a `/query` fail with method errors that only the
735/// backend can detect (`unsupportedFilter`, `unsupportedSort`,
736/// `anchorNotFound`, ...). [`Self::Method`] carries such an error to the
737/// client unchanged; [`Self::Other`] is an internal storage-layer failure
738/// that handlers surface as the redacted `serverFail`.
739#[derive(Debug)]
740pub enum BackendQueryError<E> {
741 /// An RFC 8620 §5.5 method error, returned to the client as-is
742 /// (type and description). Backends MUST NOT put internal error
743 /// text in it.
744 Method(jmap_types::JmapError),
745 /// An unexpected storage-layer error.
746 Other(E),
747}
748
749impl<E: std::fmt::Display> std::fmt::Display for BackendQueryError<E> {
750 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
751 match self {
752 Self::Method(e) => write!(f, "{e}"),
753 Self::Other(e) => write!(f, "{e}"),
754 }
755 }
756}
757
758impl<E: std::error::Error + 'static> std::error::Error for BackendQueryError<E> {
759 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
760 match self {
761 Self::Method(_) => None,
762 Self::Other(e) => Some(e),
763 }
764 }
765}
766
767impl<E> From<E> for BackendQueryError<E> {
768 fn from(e: E) -> Self {
769 Self::Other(e)
770 }
771}
772
773impl<E> From<BackendQueryError<E>> for jmap_types::JmapError {
774 fn from(e: BackendQueryError<E>) -> Self {
775 match e {
776 BackendQueryError::Method(err) => err,
777 // Same redaction as `BackendChangesError::Other`: the backend
778 // error's text never reaches the wire.
779 BackendQueryError::Other(_inner) => {
780 jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
781 }
782 }
783 }
784}
785
786// ---------------------------------------------------------------------------
787// Result types
788// ---------------------------------------------------------------------------
789
790/// Result of a `/changes` call (RFC 8620 §5.2).
791#[derive(Debug)]
792#[non_exhaustive]
793pub struct ChangesResult {
794 /// Ids of objects that were created since `sinceState`.
795 pub created: Vec<jmap_types::Id>,
796 /// Ids of objects that were updated since `sinceState`.
797 pub updated: Vec<jmap_types::Id>,
798 /// Ids of objects that were destroyed since `sinceState`.
799 pub destroyed: Vec<jmap_types::Id>,
800 /// `true` if there are more changes beyond this batch.
801 pub has_more_changes: bool,
802 /// The current state token after applying all reported changes.
803 pub new_state: jmap_types::State,
804}
805
806impl ChangesResult {
807 /// Construct a [`ChangesResult`].
808 pub fn new(
809 created: Vec<jmap_types::Id>,
810 updated: Vec<jmap_types::Id>,
811 destroyed: Vec<jmap_types::Id>,
812 has_more_changes: bool,
813 new_state: jmap_types::State,
814 ) -> Self {
815 Self {
816 created,
817 updated,
818 destroyed,
819 has_more_changes,
820 new_state,
821 }
822 }
823}
824
825/// Result of a `/query` call (RFC 8620 §5.5).
826#[derive(Debug)]
827#[non_exhaustive]
828pub struct QueryResult {
829 /// The ordered list of matching object ids.
830 pub ids: Vec<jmap_types::Id>,
831 /// The 0-based index of the first returned id in the complete result list.
832 ///
833 /// RFC 8620 §5.5 specifies this as `UnsignedInt` in the response —
834 /// a non-negative integer (bd:JMAP-wlip.25). The request-side
835 /// position parameter accepts negative values as end-relative
836 /// offsets, but the response position cannot validly be negative.
837 /// Backends that derive `position` from a request-side `i64`
838 /// offset MUST clamp / normalize to `u64` before constructing this
839 /// struct.
840 pub position: u64,
841 /// Total number of results, if the backend can calculate it.
842 pub total: Option<u64>,
843 /// Opaque query state token for subsequent `/queryChanges` calls.
844 pub query_state: jmap_types::State,
845 /// Whether the backend supports `/queryChanges` for this query.
846 pub can_calculate_changes: bool,
847}
848
849impl QueryResult {
850 /// Construct a [`QueryResult`].
851 pub fn new(
852 ids: Vec<jmap_types::Id>,
853 position: u64,
854 total: Option<u64>,
855 query_state: jmap_types::State,
856 can_calculate_changes: bool,
857 ) -> Self {
858 Self {
859 ids,
860 position,
861 total,
862 query_state,
863 can_calculate_changes,
864 }
865 }
866
867 /// Construct a [`QueryResult`] from a signed request-side position,
868 /// clamping negatives to `0` and normalizing to `u64`
869 /// (bd:JMAP-jfia.25).
870 ///
871 /// RFC 8620 §5.5 specifies the response `position` as `UnsignedInt`,
872 /// but the request-side `position` parameter accepts negative
873 /// values as end-relative offsets. Backends typically receive the
874 /// signed value, walk the offset into the result list, and need
875 /// to surface the resulting 0-based index. This constructor takes
876 /// the resolved-offset value and clamps to `u64`, matching the
877 /// spec contract.
878 ///
879 /// Negative inputs clamp to `0` (representing "the start of the
880 /// result list"). Backends that have already done the
881 /// offset-to-index resolution and have a `u64` already SHOULD use
882 /// the plain [`Self::new`] constructor instead.
883 pub fn new_clamped(
884 ids: Vec<jmap_types::Id>,
885 position_signed: i64,
886 total: Option<u64>,
887 query_state: jmap_types::State,
888 can_calculate_changes: bool,
889 ) -> Self {
890 // i64::max(_, 0) then cast to u64 — both fit in u64 because
891 // i64 >= 0 has range [0, i64::MAX], which is a strict subset
892 // of u64's range.
893 let position = u64::try_from(position_signed.max(0)).unwrap_or(0);
894 Self::new(ids, position, total, query_state, can_calculate_changes)
895 }
896}
897
898/// One entry in the `added` list of a `/queryChanges` response (RFC 8620 §5.6).
899#[derive(Debug)]
900#[non_exhaustive]
901pub struct AddedItem {
902 /// The id of the newly-added object.
903 pub id: jmap_types::Id,
904 /// Its 0-based position in the result list after applying all changes.
905 pub index: u64,
906}
907
908impl AddedItem {
909 /// Construct an [`AddedItem`].
910 pub fn new(id: jmap_types::Id, index: u64) -> Self {
911 Self { id, index }
912 }
913}
914
915/// Result of a `/queryChanges` call (RFC 8620 §5.6).
916#[derive(Debug)]
917#[non_exhaustive]
918pub struct QueryChangesResult {
919 /// The query state token supplied by the client in `sinceQueryState`.
920 pub old_query_state: jmap_types::State,
921 /// The current query state token.
922 pub new_query_state: jmap_types::State,
923 /// Total number of results in the new query, if the backend can calculate it.
924 pub total: Option<u64>,
925 /// Ids removed from the result set since `oldQueryState`.
926 pub removed: Vec<jmap_types::Id>,
927 /// Ids added to the result set since `oldQueryState`, with their positions.
928 pub added: Vec<AddedItem>,
929}
930
931impl QueryChangesResult {
932 /// Construct a [`QueryChangesResult`].
933 pub fn new(
934 old_query_state: jmap_types::State,
935 new_query_state: jmap_types::State,
936 total: Option<u64>,
937 removed: Vec<jmap_types::Id>,
938 added: Vec<AddedItem>,
939 ) -> Self {
940 Self {
941 old_query_state,
942 new_query_state,
943 total,
944 removed,
945 added,
946 }
947 }
948}
949
950// ---------------------------------------------------------------------------
951// JmapBackend — the read-side supertrait
952// ---------------------------------------------------------------------------
953
954/// Read-side backend supertrait shared by all JMAP server crates.
955///
956/// Domain-specific backend traits (`MailBackend`, `ChatBackend`, etc.) require
957/// this trait as a supertrait and add write-side methods on top.
958///
959/// Only the read operations that have an identical signature across all JMAP
960/// object types belong here. Write operations (`create_object`, `update_object`,
961/// `destroy_object`) and domain-specific operations remain in the domain crate.
962///
963/// The `collapse_threads` parameter on `query_changes` is included for
964/// `Email/queryChanges` (RFC 8621 §4.5). Non-mail backends should pass `false`
965/// and may ignore the parameter.
966///
967/// This trait is not object-safe by design (generic methods). Use
968/// `Arc<impl JmapBackend>` when sharing across tasks.
969///
970/// # CallerCtx
971///
972/// Every backend method takes a `caller: &Self::CallerCtx` parameter as the
973/// first argument after `&self`. This is the per-request authentication /
974/// authorisation context produced by the caller's auth layer and forwarded
975/// unchanged through [`crate::Dispatcher::dispatch`] → [`crate::JmapHandler`]
976/// → the registered closure → the backend.
977///
978/// Implementations that do not need an auth identity can use the unit type:
979///
980/// ```rust,ignore
981/// impl JmapBackend for MyBackend {
982/// type Error = MyError;
983/// type CallerCtx = ();
984/// // ...
985/// }
986/// ```
987///
988/// Implementations that do need to differentiate behaviour per caller (e.g.
989/// applying per-user visibility rules, or rejecting reads with
990/// `forbidden` when the caller is not the owner of the account) read the
991/// `caller` parameter to decide.
992///
993/// The trait bound `Clone + Send + 'static` is what [`crate::Dispatcher`]
994/// requires; the bound is repeated here so the supertrait can stand on its
995/// own without depending on the dispatcher.
996pub trait JmapBackend: Send + Sync + 'static {
997 /// The error type returned by storage operations.
998 ///
999 /// # Security
1000 ///
1001 /// The `Display` impl of this type is surfaced through
1002 /// [`BackendSetError::Other`]'s and [`BackendChangesError::Other`]'s
1003 /// own `Display` impls, which in turn flow into
1004 /// [`crate::request_error`]'s `RequestError::Display` output. When a
1005 /// downstream consumer wires tracing-style logging on top, the
1006 /// formatted error text lands in operator logs verbatim.
1007 ///
1008 /// Implementations MUST NOT include any of the following in this
1009 /// type's `Display` output:
1010 ///
1011 /// - **Credential material** — auth tokens, passwords, push
1012 /// verification codes, invite codes, session cookies, or anything
1013 /// derived byte-for-byte from an `Authorization`-header value.
1014 /// - **Blob content** — email bodies, sieve scripts, file contents,
1015 /// or any user-supplied opaque payload. An error like
1016 /// `"sieve parse error at line 42: <script excerpt>"` violates
1017 /// this — emit the line number and a short type-only summary
1018 /// ("sieve parse error at line 42: unexpected token") and let the
1019 /// server log the full script body separately under a redacted
1020 /// path.
1021 /// - **PII shaped like an email address** in any code path that an
1022 /// unauthenticated caller can trigger. Wrapping a downstream
1023 /// service error that interpolates the caller's email is the
1024 /// common foot-gun.
1025 ///
1026 /// Errors that wrap a downstream-service failure should sanitize
1027 /// the downstream error text — or strip it entirely and replace it
1028 /// with a static summary — before constructing the `Display`
1029 /// string. The same rule applies to every extension `*Backend`
1030 /// trait that inherits this associated type by transitivity:
1031 /// `MailBackend::Error`, `ChatBackend::Error`,
1032 /// `CalendarsBackend::Error`, `TasksBackend::Error`,
1033 /// `ContactsBackend::Error`, `FileNodeBackend::Error`, and
1034 /// `SharingBackend::Error` are all the same `JmapBackend::Error`
1035 /// associated type — the contract here governs all of them.
1036 ///
1037 /// Precedent: bd:JMAP-sc1b.79 redacted `BearerAuth` and `BasicAuth`
1038 /// at the type-derive level; bd:JMAP-sc1b.100 documents the
1039 /// equivalent contract at the trait-associated-type level.
1040 type Error: std::error::Error + Send + Sync + 'static;
1041
1042 /// The per-request caller context type produced by the auth layer and
1043 /// forwarded by [`crate::Dispatcher::dispatch`] into every method call.
1044 ///
1045 /// Use `()` when no auth context is needed.
1046 ///
1047 /// The bound is `Clone + Send + Sync + 'static`:
1048 /// - `Clone` because [`crate::Dispatcher`] clones the value once per
1049 /// method call in the batch.
1050 /// - `Send + 'static` because each method call is spawned on a
1051 /// [`tokio::task`].
1052 /// - `Sync` because handler method bodies take `&Self::CallerCtx`
1053 /// and hold that reference across `.await` boundaries inside a
1054 /// `Send` future (a `&T` is `Send` iff `T: Sync`).
1055 type CallerCtx: Clone + Send + Sync + 'static;
1056
1057 /// Return `true` if the given account exists in this backend.
1058 ///
1059 /// Handlers call this at the start of each method to return
1060 /// `accountNotFound` (RFC 8620 §3.6.2) rather than surfacing
1061 /// the wrong error when `accountId` is unknown.
1062 ///
1063 /// # Performance contract (bd:JMAP-jfia.27)
1064 ///
1065 /// Implementations SHOULD return in sub-millisecond time. The
1066 /// JMAP standard handlers (`handle_get`, `handle_changes`,
1067 /// `handle_query`, `handle_query_changes`) each call
1068 /// `account_exists` at the START of the method, BEFORE delegating
1069 /// to the per-domain backend. A typical JMAP request batch is
1070 /// 4–16 method calls; a naive remote round-trip per call would
1071 /// add 4–16× the network latency to every batch.
1072 ///
1073 /// Acceptable backing strategies: in-memory cache (the
1074 /// reference `MemoryBackend` impls all use this); an indexed
1075 /// primary-key lookup against a local database; a bloom filter
1076 /// for negative lookups paired with a cache for positives. A
1077 /// naive `SELECT 1 FROM accounts WHERE id = ?` against a remote
1078 /// database is INCORRECT for this method even though it would
1079 /// return the right value — the round-trip cost is the bug.
1080 ///
1081 /// The dispatcher does not cache this call across the method
1082 /// calls in a single batch (workspace-architectural decision —
1083 /// the dispatcher is intentionally stateless across the batch
1084 /// loop). Caching is the backend implementor's responsibility.
1085 fn account_exists(
1086 &self,
1087 caller: &Self::CallerCtx,
1088 account_id: &jmap_types::Id,
1089 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;
1090
1091 /// Fetch objects by id (or all objects when `ids` is `None`).
1092 ///
1093 /// `properties` is the list of property names requested by the client
1094 /// (RFC 8620 §5.1). `None` means the client did not send a `properties`
1095 /// field; the backend should return all properties. When `Some`, the backend
1096 /// MAY filter the response to only the named properties, but is not required
1097 /// to — implementations that always return all properties are correct.
1098 ///
1099 /// Returns `(found, not_found)` — objects that exist and ids that do not.
1100 fn get_objects<O: GetObject + Send + Sync>(
1101 &self,
1102 caller: &Self::CallerCtx,
1103 account_id: &jmap_types::Id,
1104 ids: Option<&[jmap_types::Id]>,
1105 properties: Option<&[String]>,
1106 ) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send;
1107
1108 /// Return the current state token for an object type in the given account.
1109 fn get_state<O: JmapObject + Send + Sync>(
1110 &self,
1111 caller: &Self::CallerCtx,
1112 account_id: &jmap_types::Id,
1113 ) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send;
1114
1115 /// Return changes since `since_state`, up to `max_changes` entries.
1116 fn get_changes<O: JmapObject + Send + Sync>(
1117 &self,
1118 caller: &Self::CallerCtx,
1119 account_id: &jmap_types::Id,
1120 since_state: &jmap_types::State,
1121 max_changes: Option<u64>,
1122 ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;
1123
1124 /// Execute a `/query` and return a page of matching ids.
1125 ///
1126 /// `position` may be negative — negative values are relative to the end of
1127 /// the result set per RFC 8620 §5.5 (e.g. -1 means the last result).
1128 ///
1129 /// `anchor` and `anchor_offset` are the RFC 8620 §5.5 `anchor` and
1130 /// `anchorOffset` arguments. With an `anchor`, `position` MUST be
1131 /// ignored and the page starts at the anchor's index in the filtered,
1132 /// sorted results plus `anchor_offset`, clamped to 0; an anchor not in
1133 /// the results is [`JmapError::anchor_not_found`] via
1134 /// [`BackendQueryError::Method`]. Without one, `anchor_offset` MUST be
1135 /// ignored. [`QueryResult::position`] is the page's actual start index.
1136 /// [`crate::resolve_query_start`] implements this over an in-memory id
1137 /// list.
1138 ///
1139 /// [`JmapError::anchor_not_found`]: jmap_types::JmapError::anchor_not_found
1140 ///
1141 /// # Filter and sort handling
1142 ///
1143 /// Implementations MUST honour the supplied `filter` and `sort` arguments
1144 /// efficiently — typically by pushing both into the indexed storage layer
1145 /// (database WHERE / ORDER BY, search index, etc.). Returning every
1146 /// matching id and relying on the caller to paginate after the fact
1147 /// degenerates to O(n) per page for IMAP-migration accounts.
1148 ///
1149 /// Handler implementations in `jmap-*-server` crates SHOULD NOT
1150 /// post-filter or post-sort the backend's result; doing so re-introduces
1151 /// the O(n) cost this method exists to avoid. The Mailbox handler in
1152 /// `jmap-mail-server` is the canonical example of pushing filter/sort
1153 /// fully into the backend.
1154 ///
1155 /// # Errors
1156 ///
1157 /// Return [`BackendQueryError::Method`] for an RFC 8620 §5.5 method
1158 /// error (`unsupportedFilter`, `unsupportedSort`, `anchorNotFound`,
1159 /// ...); handlers pass it to the client unchanged. Return
1160 /// [`BackendQueryError::Other`] (or use `?` on `Self::Error`) for an
1161 /// internal failure; handlers surface it as a redacted `serverFail`.
1162 #[allow(clippy::too_many_arguments)]
1163 fn query_objects<O: QueryObject + Send + Sync>(
1164 &self,
1165 caller: &Self::CallerCtx,
1166 account_id: &jmap_types::Id,
1167 filter: Option<&O::Filter>,
1168 sort: Option<&[O::Comparator]>,
1169 limit: Option<u64>,
1170 position: i64,
1171 anchor: Option<&jmap_types::Id>,
1172 anchor_offset: i64,
1173 ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;
1174
1175 /// Execute a `/queryChanges` and return deltas since `since_query_state`.
1176 ///
1177 /// `collapse_threads` is only meaningful for `Email/queryChanges`
1178 /// (RFC 8621 §4.5). Pass `false` for all other object types.
1179 #[allow(clippy::too_many_arguments)]
1180 fn query_changes<O: QueryObject + Send + Sync>(
1181 &self,
1182 caller: &Self::CallerCtx,
1183 account_id: &jmap_types::Id,
1184 since_query_state: &jmap_types::State,
1185 filter: Option<&O::Filter>,
1186 sort: Option<&[O::Comparator]>,
1187 max_changes: Option<u64>,
1188 up_to_id: Option<&jmap_types::Id>,
1189 collapse_threads: bool,
1190 ) -> impl std::future::Future<
1191 Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
1192 > + Send;
1193
1194 /// The caller's stable identity within this account namespace.
1195 ///
1196 /// Returns `None` for deployments that have not wired identity
1197 /// (test fixtures, single-user dev servers). A `None`-returning
1198 /// backend CANNOT honor JMAP semantics that depend on caller
1199 /// identity — chat role-hierarchy, calendar ACLs, sharing/myRights,
1200 /// per-user $seen on shared mailboxes, per-user metadata
1201 /// `privateMetadata` filtering, etc. Authentication is still the HTTP
1202 /// layer's job; this method exposes the result of that
1203 /// authentication to the JMAP layer for in-method semantics.
1204 ///
1205 /// Implementations MUST NOT mint identity — they MUST read it
1206 /// from the `CallerCtx` populated by the HTTP/auth middleware
1207 /// before `dispatch()` was called.
1208 ///
1209 /// Backends that honor identity-dependent semantics MUST override
1210 /// this method. Handlers and downstream backend traits MAY rely on
1211 /// it being correct when it returns `Some`.
1212 ///
1213 /// # Why an associated function and not a method (bd:JMAP-wlip.6 / bd:JMAP-jfia.13)
1214 ///
1215 /// The signature deliberately takes `caller: &Self::CallerCtx`
1216 /// without a `&self` receiver. Backends therefore have no access
1217 /// to their own storage state from inside `principal_id`. The
1218 /// auth-layer middleware MUST pre-resolve the principal (e.g. map
1219 /// a JWT `sub` claim to a local `Id` via an internal lookup) and
1220 /// stash the result inside `CallerCtx` *before* it calls
1221 /// `dispatch`. The JMAP layer reads the pre-resolved value here;
1222 /// no JIT lookup is possible.
1223 ///
1224 /// This is a structural enforcement of the "identity is not the
1225 /// JMAP layer's job to mint" rule. A consumer that wants
1226 /// JIT-resolved identity (e.g. database-backed JWT → principal
1227 /// mapping) wires that mapping into the HTTP layer's `CallerCtx`
1228 /// construction step instead of trying to fit it inside the
1229 /// backend's `principal_id` impl.
1230 ///
1231 /// **Decision record (bd:JMAP-jfia.13)**: a future reviewer or AI
1232 /// tool will reasonably suggest "this is an oversight, surely the
1233 /// backend wants `&self` access to its identity store" and propose
1234 /// `fn principal_id(&self, caller: ...) -> ...`. That suggestion
1235 /// is **WRONG** and must be rejected: the function-vs-method
1236 /// distinction is the structural enforcement of the no-JIT-lookup
1237 /// policy. Comments alone could be ignored; the type system makes
1238 /// the wrong thing impossible. Defending this shape protects the
1239 /// workspace identity-seam policy from drift.
1240 fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
1241 let _ = caller;
1242 None
1243 }
1244
1245 /// Maximum number of objects this account permits in a single
1246 /// `/set` call (RFC 8620 §5.3 `maxObjectsInSet`) (bd:JMAP-ayoz.41.1).
1247 ///
1248 /// Counts the sum of `create` + `update` + `destroy` entries in the
1249 /// wire arguments. Handlers MUST enforce this at the top of every
1250 /// `handle_*_set` via [`crate::helpers::enforce_max_objects_in_set`]
1251 /// so a single batched request cannot drive O(M·N) work against
1252 /// the storage layer.
1253 ///
1254 /// The default value `500` mirrors the workspace's testjig Session
1255 /// JSON advertised cap and matches common Fastmail / Cyrus IMAP
1256 /// server defaults. The cap is a *floor* on permissiveness, not a
1257 /// floor on capability — backends MAY override per account (Free vs
1258 /// Pro tier, multi-tenant SaaS, etc.). The `caller` and `account_id`
1259 /// arguments are passed even though the default impl ignores them
1260 /// so production backends can vary without an API break.
1261 ///
1262 /// Returning `0` makes every non-empty `/set` call fail with
1263 /// `requestTooLarge` (defensive read-only mode). Returning
1264 /// `u64::MAX` effectively disables the cap (NOT recommended — the
1265 /// cap is a DoS defence and disabling it forfeits that defence).
1266 ///
1267 /// # Why on `JmapBackend` and not a per-extension `XxxLimits` struct
1268 ///
1269 /// `maxObjectsInSet` is RFC 8620 §5.3 base-protocol scope, not an
1270 /// extension concept. Putting it on the foundation supertrait
1271 /// covers all 8 extension server crates with one default impl;
1272 /// per-extension `XxxLimits` structs are the right shape for
1273 /// extension-specific caps (per-Space content limits, per-Mailbox
1274 /// message size, etc. per workspace AGENTS.md "Backend caps and
1275 /// limits") but are out of scope here.
1276 fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1277 let _ = (caller, account_id);
1278 500
1279 }
1280
1281 /// Maximum number of ids this account permits in a single `/get`
1282 /// call (RFC 8620 §5.1 `maxObjectsInGet`) (bd:JMAP-yt1w.31).
1283 ///
1284 /// Handlers MUST enforce this at the top of every `/get` handler via
1285 /// [`crate::helpers::enforce_max_objects_in_get`]; the generic
1286 /// [`crate::handlers::handle_get`] already does. A null `ids` (fetch
1287 /// all) is not counted.
1288 ///
1289 /// The default value `500` is the RFC 8620 §2 suggested minimum and
1290 /// mirrors [`JmapBackend::max_objects_in_set`]. Backends MAY override
1291 /// per account; the `caller` and `account_id` arguments exist for
1292 /// that. Keep the value in step with the `maxObjectsInGet` advertised
1293 /// in the Session object.
1294 fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
1295 let _ = (caller, account_id);
1296 500
1297 }
1298}
1299
1300// ---------------------------------------------------------------------------
1301// Tests
1302// ---------------------------------------------------------------------------
1303
1304#[cfg(test)]
1305mod tests {
1306 use super::*;
1307
1308 /// Oracle: BackendChangesError::TooManyChanges { limit: 0 } must map to
1309 /// cannotCalculateChanges (RFC 8620 §5.6), not tooManyChanges with limit 0.
1310 ///
1311 /// limit=0 is the convention for "cannot calculate".
1312 #[test]
1313 fn backend_changes_error_limit_zero_maps_to_cannot_calculate() {
1314 let err = jmap_types::JmapError::from(
1315 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
1316 );
1317 assert_eq!(
1318 err.error_type.as_str(),
1319 "cannotCalculateChanges",
1320 "limit=0 must produce cannotCalculateChanges; got: {:?}",
1321 err.error_type
1322 );
1323 }
1324
1325 /// Oracle (bd:JMAP-jfia.31, bd:JMAP-jfia.37): the new
1326 /// `CannotCalculate` variant maps to `cannotCalculateChanges`
1327 /// on the wire, matching the permanent legacy
1328 /// `TooManyChanges { limit: 0 }` alias. New backends SHOULD
1329 /// emit `CannotCalculate` directly.
1330 #[test]
1331 fn backend_changes_error_cannot_calculate_maps_to_cannot_calculate_changes() {
1332 let err = jmap_types::JmapError::from(
1333 BackendChangesError::<std::convert::Infallible>::CannotCalculate,
1334 );
1335 assert_eq!(
1336 err.error_type.as_str(),
1337 "cannotCalculateChanges",
1338 "CannotCalculate must produce cannotCalculateChanges; got: {:?}",
1339 err.error_type
1340 );
1341
1342 // Display agrees with the permanent legacy-alias Display arm.
1343 let s = BackendChangesError::<std::convert::Infallible>::CannotCalculate.to_string();
1344 assert_eq!(
1345 s, "cannot calculate changes",
1346 "Display must produce the same string as TooManyChanges {{ limit: 0 }}"
1347 );
1348 }
1349
1350 /// Oracle: BackendChangesError::TooManyChanges { limit: N } (N > 0) maps to
1351 /// tooManyChanges with the suggested limit.
1352 #[test]
1353 fn backend_changes_error_nonzero_limit_maps_to_too_many_changes() {
1354 let err = jmap_types::JmapError::from(
1355 BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 50 },
1356 );
1357 assert_eq!(
1358 err.error_type.as_str(),
1359 "tooManyChanges",
1360 "limit=50 must produce tooManyChanges; got: {:?}",
1361 err.error_type
1362 );
1363 }
1364
1365 /// Oracle (bd:JMAP-jfia.1 / bd:JMAP-wlip.2): the
1366 /// `From<BackendChangesError<E>> for JmapError` impl MUST NOT echo
1367 /// the wrapped backend error's `Display` text into the resulting
1368 /// `JmapError`'s description. The defence-in-depth contract is that
1369 /// even if a backend implementor accidentally violates the
1370 /// [`JmapBackend::Error`] Display MUST-NOT (credential / blob /
1371 /// PII), the leaked text never reaches the wire — and the
1372 /// ergonomic `.map_err(JmapError::from)?` path that
1373 /// `handle_changes` / `handle_query_changes` take on
1374 /// `BackendChangesError` must redact identically to the explicit
1375 /// `server_fail_from_backend(&e)` helper used elsewhere.
1376 ///
1377 /// Test vector: an `Other` variant whose Display contains a canary
1378 /// string resembling a credential leak. The canary literal is
1379 /// hand-built and not derived from any production type's
1380 /// behaviour. Mirrors
1381 /// `server_fail_from_backend_drops_display_text` in
1382 /// `handlers.rs`.
1383 #[test]
1384 fn backend_changes_error_other_drops_display_text() {
1385 #[derive(Debug)]
1386 struct LeakyError(&'static str);
1387 impl std::fmt::Display for LeakyError {
1388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1389 f.write_str(self.0)
1390 }
1391 }
1392 impl std::error::Error for LeakyError {}
1393
1394 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1395 let err: BackendChangesError<LeakyError> = BackendChangesError::Other(LeakyError(CANARY));
1396
1397 let jmap_err = jmap_types::JmapError::from(err);
1398
1399 // Serialize to wire shape and assert the canary is absent from
1400 // the resulting JSON. The error_invocation wraps a JmapError as
1401 // { "type": "serverFail", "description": "..." } — both fields
1402 // are wire-visible.
1403 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1404 let wire_str = wire.to_string();
1405 assert!(
1406 !wire_str.contains(CANARY),
1407 "From<BackendChangesError<E>> for JmapError must not echo \
1408 backend error Display onto the wire; got {wire_str}"
1409 );
1410 // The description MUST be exactly SERVER_FAIL_INTERNAL_DESC.
1411 assert_eq!(
1412 wire["description"],
1413 crate::handlers::SERVER_FAIL_INTERNAL_DESC,
1414 "description must be the static 'internal error' string"
1415 );
1416 assert_eq!(wire["type"], "serverFail");
1417 }
1418
1419 /// Oracle (bd:JMAP-jfia.36): `into_set_error_or_method_error` on
1420 /// `Other` MUST NOT echo the wrapped error's `Display` text; the
1421 /// wire form is exactly `{"type":"serverFail","description":"internal
1422 /// error"}` (hand-written expected JSON). The canary literal is
1423 /// hand-built. Mirrors `backend_changes_error_other_drops_display_text`.
1424 #[test]
1425 fn backend_set_error_other_drops_display_text() {
1426 struct LeakyError(&'static str);
1427 impl std::fmt::Display for LeakyError {
1428 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1429 f.write_str(self.0)
1430 }
1431 }
1432
1433 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
1434 let err: BackendSetError<LeakyError> = BackendSetError::Other(LeakyError(CANARY));
1435
1436 let Err(jmap_err) = err.into_set_error_or_method_error() else {
1437 panic!("Other must map to a method-level JmapError");
1438 };
1439 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
1440 assert!(
1441 !wire.to_string().contains(CANARY),
1442 "into_set_error_or_method_error must not echo backend Display; got {wire}"
1443 );
1444 assert_eq!(
1445 wire,
1446 serde_json::json!({"type": "serverFail", "description": "internal error"})
1447 );
1448 }
1449
1450 /// Oracle (RFC 8620 §5.3): a per-object `SetError` belongs in the
1451 /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
1452 /// arm must come back as `Ok` with its wire form intact
1453 /// (hand-written expected JSON).
1454 #[test]
1455 fn backend_set_error_set_error_passes_through() {
1456 let err: BackendSetError<std::fmt::Error> =
1457 BackendSetError::SetError(SetError::new(SetErrorType::Forbidden));
1458 let se = err
1459 .into_set_error_or_method_error()
1460 .expect("SetError arm must be Ok");
1461 assert_eq!(
1462 serde_json::to_value(&se).expect("SetError must serialize"),
1463 serde_json::json!({"type": "forbidden"})
1464 );
1465 }
1466
1467 /// Oracle (bd:JMAP-wlip.22): `SetErrorType::custom("forbidden")` MUST
1468 /// return `SetErrorType::Forbidden`, not `Custom("forbidden")`. The
1469 /// asymmetry where `custom("forbidden") != Forbidden` was a real
1470 /// foot-gun: handler code intending to emit the typed variant via
1471 /// the `custom` builder produced a Custom that was wire-identical
1472 /// but PartialEq-distinct, breaking test assertions that compared
1473 /// the deserialised round-trip against the typed expected value.
1474 ///
1475 /// Test vector: every known typed variant name canonicalises to its
1476 /// typed variant; an unknown name stays Custom. The wire-name list
1477 /// is hand-built from the same RFC source as the round-trip test
1478 /// `set_error_type_all_known_variants_round_trip`.
1479 #[test]
1480 fn custom_canonicalises_known_wire_names_to_typed_variants() {
1481 // Spot-check a representative subset across the 23 known names.
1482 // The exhaustive round-trip from from_wire_str is exercised by
1483 // set_error_type_all_known_variants_round_trip; this test focuses
1484 // on the custom() → typed-variant direction the bead was about.
1485 let cases: &[(&str, SetErrorType)] = &[
1486 ("forbidden", SetErrorType::Forbidden),
1487 ("overQuota", SetErrorType::OverQuota),
1488 ("invalidPatch", SetErrorType::InvalidPatch),
1489 ("mailboxHasChild", SetErrorType::MailboxHasChild),
1490 ("tooManyRecipients", SetErrorType::TooManyRecipients),
1491 ("cannotUnsend", SetErrorType::CannotUnsend),
1492 ];
1493 for (name, expected) in cases {
1494 let from_custom = SetErrorType::custom(*name);
1495 assert_eq!(
1496 &from_custom, expected,
1497 "custom({name:?}) must canonicalise to the typed variant, not Custom"
1498 );
1499 assert!(
1500 !matches!(from_custom, SetErrorType::Custom(_)),
1501 "custom({name:?}) must NOT remain Custom — known wire-name asymmetry"
1502 );
1503 }
1504
1505 // Unknown names stay Custom — extension crates depend on this.
1506 let unknown = SetErrorType::custom("mdnAlreadySent");
1507 assert!(
1508 matches!(unknown, SetErrorType::Custom(ref s) if s == "mdnAlreadySent"),
1509 "custom('mdnAlreadySent') must remain Custom (not a known wire-name)"
1510 );
1511 }
1512
1513 /// Oracle: SetErrorType::Custom("mdnAlreadySent") must serialize as the bare
1514 /// string "mdnAlreadySent" and deserialize back to Custom("mdnAlreadySent").
1515 /// Extension crates depend on this round-trip to emit domain-specific errors.
1516 #[test]
1517 fn set_error_type_custom_round_trips_as_bare_string() {
1518 let original = SetErrorType::custom("mdnAlreadySent");
1519 let serialized = serde_json::to_string(&original).expect("serialize");
1520 assert_eq!(
1521 serialized, r#""mdnAlreadySent""#,
1522 "Custom must serialize as bare string"
1523 );
1524 let deserialized: SetErrorType = serde_json::from_str(&serialized).expect("deserialize");
1525 assert_eq!(
1526 deserialized, original,
1527 "Custom must deserialize back to Custom"
1528 );
1529 }
1530
1531 /// Oracle (bd:JMAP-dha0): SetError gains an `extra` map that captures
1532 /// extension-defined fields not covered by the typed `with_*` builders.
1533 /// A handler that emits `rateLimited` with `serverRetryAfter` must
1534 /// see the value round-trip through serialize / deserialize.
1535 #[test]
1536 fn set_error_extra_field_round_trips() {
1537 let original = SetError::new(SetErrorType::custom("rateLimited"))
1538 .with_description("Slow mode is active")
1539 .with_extra(
1540 "serverRetryAfter",
1541 serde_json::Value::String("2025-12-31T23:59:59Z".to_owned()),
1542 );
1543
1544 let wire = serde_json::to_value(&original).expect("serialize");
1545 assert_eq!(wire["type"], "rateLimited");
1546 assert_eq!(wire["description"], "Slow mode is active");
1547 assert_eq!(
1548 wire["serverRetryAfter"], "2025-12-31T23:59:59Z",
1549 "extra field must flatten into the SetError wire shape"
1550 );
1551
1552 let round: SetError = serde_json::from_value(wire).expect("deserialize");
1553 assert_eq!(round.error_type, original.error_type);
1554 assert_eq!(round.description, original.description);
1555 assert_eq!(
1556 round.extra.get("serverRetryAfter").and_then(|v| v.as_str()),
1557 Some("2025-12-31T23:59:59Z"),
1558 "extra field must survive deserialize"
1559 );
1560 }
1561
1562 /// Oracle (bd:JMAP-dha0): a SetError with no extras serializes to a
1563 /// wire shape byte-identical to the pre-extras layout. The
1564 /// `skip_serializing_if` on `extra` collapses the empty map.
1565 #[test]
1566 fn set_error_empty_extra_is_invisible_on_the_wire() {
1567 let err = SetError::new(SetErrorType::Forbidden);
1568 let wire = serde_json::to_value(&err).expect("serialize");
1569 let obj = wire.as_object().expect("object");
1570 assert!(
1571 !obj.contains_key("extra"),
1572 "empty `extra` map must not appear on the wire (got {wire})"
1573 );
1574 // The only key on the wire for a bare SetError must be `type`.
1575 assert_eq!(
1576 obj.len(),
1577 1,
1578 "bare SetError must have exactly one key on the wire"
1579 );
1580 assert_eq!(obj["type"], "forbidden");
1581 }
1582
1583 /// Oracle (bd:JMAP-dha0): unknown wire fields on a deserialized
1584 /// SetError land in `extra`. This means a future spec adding
1585 /// `someNewSetErrorField` will round-trip through current
1586 /// versions of the kit losslessly.
1587 #[test]
1588 fn set_error_unknown_field_lands_in_extra() {
1589 let wire = serde_json::json!({
1590 "type": "forbidden",
1591 "futureSpecField": "future-value",
1592 "anotherOne": 42
1593 });
1594 let err: SetError = serde_json::from_value(wire).expect("deserialize");
1595 assert_eq!(err.error_type, SetErrorType::Forbidden);
1596 assert_eq!(
1597 err.extra.get("futureSpecField").and_then(|v| v.as_str()),
1598 Some("future-value")
1599 );
1600 assert_eq!(
1601 err.extra.get("anotherOne").and_then(|v| v.as_u64()),
1602 Some(42)
1603 );
1604 }
1605
1606 /// Oracle (bd:JMAP-wlip.3): [`SetError::with_extra`] panics in debug
1607 /// builds when called with a reserved wire-name key. Catches the bug
1608 /// at first test run rather than letting a malformed-on-the-wire
1609 /// SetError ship through review. The assert is debug-only so release
1610 /// builds pay no runtime cost on correctly-written callers.
1611 ///
1612 /// Iterates every wire-name in [`RESERVED_SET_ERROR_WIRE_NAMES`] so
1613 /// adding a new typed field to SetError plus its rename to the
1614 /// constant list keeps the negative tests in sync automatically.
1615 #[test]
1616 #[cfg(debug_assertions)]
1617 fn with_extra_panics_on_reserved_wire_name() {
1618 for &reserved in RESERVED_SET_ERROR_WIRE_NAMES {
1619 let reserved_owned = reserved.to_owned();
1620 let result = std::panic::catch_unwind(move || {
1621 SetError::new(SetErrorType::Forbidden)
1622 .with_extra(&reserved_owned, serde_json::Value::Null);
1623 });
1624 assert!(
1625 result.is_err(),
1626 "with_extra({reserved:?}, ...) must panic in debug builds; \
1627 reserved wire-names collide with typed fields and would \
1628 produce a malformed SetError on the wire"
1629 );
1630 }
1631 }
1632
1633 /// Oracle (bd:JMAP-jfia.17): direct mutation of `SetError.extra`
1634 /// bypasses the `with_extra` debug_assert and can plant a
1635 /// reserved wire-name. [`SetError::validate_extras`] is the
1636 /// deterministic, build-profile-independent gate for the same
1637 /// invariant.
1638 ///
1639 /// Test vector: iterate every reserved wire-name, plant it
1640 /// directly into `extra`, and assert `validate_extras` returns
1641 /// `Err(ReservedExtrasKey { key: <name> })`.
1642 #[test]
1643 fn validate_extras_detects_reserved_key_planted_via_direct_mutation() {
1644 for &reserved in RESERVED_SET_ERROR_WIRE_NAMES {
1645 let mut err = SetError::new(SetErrorType::Forbidden);
1646 // Bypass with_extra entirely — this is the pattern the
1647 // `pub` field surface invites that the debug_assert cannot
1648 // see (bd:JMAP-jfia.17).
1649 err.extra
1650 .insert(reserved.to_owned(), serde_json::Value::Null);
1651 let collision = err
1652 .validate_extras()
1653 .expect_err("reserved-name extras key must be detected");
1654 assert_eq!(
1655 collision.key, reserved,
1656 "validate_extras must report the colliding key verbatim"
1657 );
1658 }
1659 }
1660
1661 /// Oracle (bd:JMAP-jfia.17): `validate_extras` returns `Ok(())` for
1662 /// a SetError whose `extra` map contains only extension-namespace
1663 /// keys. Positive control paired with the rejection test above.
1664 #[test]
1665 fn validate_extras_accepts_extension_namespace_keys() {
1666 let mut err = SetError::new(SetErrorType::custom("rateLimited"));
1667 err.extra.insert(
1668 "serverRetryAfter".to_owned(),
1669 serde_json::Value::String("2025-12-31T23:59:59Z".to_owned()),
1670 );
1671 err.extra
1672 .insert("retryAttempt".to_owned(), serde_json::Value::from(3));
1673 err.validate_extras()
1674 .expect("extension-namespace keys must pass validation");
1675 }
1676
1677 /// Oracle (bd:JMAP-wlip.3): a non-reserved key passes the
1678 /// [`SetError::with_extra`] debug_assert and lands in the `extra`
1679 /// map as before. Positive control paired with the panic test
1680 /// above.
1681 #[test]
1682 fn with_extra_accepts_extension_namespace_key() {
1683 // 'serverRetryAfter' is the JMAP Chat extension's rateLimited
1684 // SetError field; not in RESERVED_SET_ERROR_WIRE_NAMES.
1685 let err = SetError::new(SetErrorType::custom("rateLimited")).with_extra(
1686 "serverRetryAfter",
1687 serde_json::Value::String("2025-12-31T23:59:59Z".to_owned()),
1688 );
1689 assert_eq!(
1690 err.extra.get("serverRetryAfter").and_then(|v| v.as_str()),
1691 Some("2025-12-31T23:59:59Z"),
1692 "extension-namespace key must land in the extra map"
1693 );
1694 }
1695
1696 /// Oracle (bd:JMAP-wlip.3): the reserved-name constant covers every
1697 /// `#[serde(rename = ...)]` and camelCase-derived field name on the
1698 /// public [`SetError`] surface. A future contributor that adds a
1699 /// typed wire field without extending the constant is the failure
1700 /// mode this test guards against. The oracle is hand-derived from
1701 /// the SetError struct definition by reading off the wire-name of
1702 /// each field.
1703 #[test]
1704 fn reserved_set_error_wire_names_matches_serialized_surface() {
1705 // Build a SetError with every typed field populated, serialize,
1706 // and check that every JSON key (other than the extension extras)
1707 // appears in RESERVED_SET_ERROR_WIRE_NAMES.
1708 let err = SetError::new(SetErrorType::Forbidden)
1709 .with_description("desc")
1710 .with_properties(["p1"])
1711 .with_existing_id(jmap_types::Id::from("eid"))
1712 .with_max_recipients(10)
1713 .with_invalid_recipients(["bad@example"])
1714 .with_not_found(vec![jmap_types::Id::from("nfid")])
1715 .with_max_size(1024);
1716
1717 let wire = serde_json::to_value(&err).expect("serialize");
1718 let obj = wire.as_object().expect("SetError must serialize as object");
1719 for key in obj.keys() {
1720 assert!(
1721 RESERVED_SET_ERROR_WIRE_NAMES.contains(&key.as_str()),
1722 "wire-name {key:?} appears on the SetError surface but is \
1723 not in RESERVED_SET_ERROR_WIRE_NAMES — adding a typed \
1724 field to SetError requires extending the constant"
1725 );
1726 }
1727 }
1728
1729 /// Oracle (bd:JMAP-wlip.29): the Display arm, the Deserialize visitor
1730 /// match, and the round-trip behaviour MUST agree for every known
1731 /// variant of [`SetErrorType`]. The mapping is duplicated across three
1732 /// places (Display, Serialize via Display, Deserialize visitor); the
1733 /// workspace dep allowlist forbids strum / serde_with that would
1734 /// derive the round-trip from a single source. This table-driven
1735 /// test iterates ALL 23 typed variants and asserts:
1736 ///
1737 /// - Display produces the expected camelCase wire string
1738 /// - serde_json::to_string emits the same string
1739 /// - serde_json::from_str rebuilds the same variant (NOT a Custom)
1740 ///
1741 /// A drift between Display and Deserialize (e.g. adding "rateLimit"
1742 /// to Display but forgetting the Deserialize arm) would fail step 3
1743 /// at first test run because the wire string would round-trip into
1744 /// `Custom("rateLimit")` instead of `RateLimit`. This is the silent
1745 /// contract drift filed as bd:JMAP-wlip.22.
1746 ///
1747 /// The table is hand-built from the RFC 8620 / RFC 8621 spec text,
1748 /// not derived from the code under test (the workspace test-integrity
1749 /// rule requires an independent oracle). Adding a new typed variant
1750 /// requires extending this table — that is the intent.
1751 #[test]
1752 fn set_error_type_all_known_variants_round_trip() {
1753 // (variant constructor, expected wire string).
1754 // Source of truth: RFC 8620 §5.3 + RFC 8621 §2.5, §5.5, §6.3, §7.5.
1755 let cases: &[(SetErrorType, &str)] = &[
1756 (SetErrorType::Forbidden, "forbidden"),
1757 (SetErrorType::OverQuota, "overQuota"),
1758 (SetErrorType::TooLarge, "tooLarge"),
1759 (SetErrorType::RateLimit, "rateLimit"),
1760 (SetErrorType::NotFound, "notFound"),
1761 (SetErrorType::InvalidPatch, "invalidPatch"),
1762 (SetErrorType::WillDestroy, "willDestroy"),
1763 (SetErrorType::InvalidProperties, "invalidProperties"),
1764 (SetErrorType::Singleton, "singleton"),
1765 (SetErrorType::AlreadyExists, "alreadyExists"),
1766 (SetErrorType::MailboxHasChild, "mailboxHasChild"),
1767 (SetErrorType::MailboxHasEmail, "mailboxHasEmail"),
1768 (SetErrorType::TooManyKeywords, "tooManyKeywords"),
1769 (SetErrorType::TooManyMailboxes, "tooManyMailboxes"),
1770 (SetErrorType::BlobNotFound, "blobNotFound"),
1771 (SetErrorType::ForbiddenFrom, "forbiddenFrom"),
1772 (SetErrorType::InvalidEmail, "invalidEmail"),
1773 (SetErrorType::TooManyRecipients, "tooManyRecipients"),
1774 (SetErrorType::NoRecipients, "noRecipients"),
1775 (SetErrorType::InvalidRecipients, "invalidRecipients"),
1776 (SetErrorType::ForbiddenMailFrom, "forbiddenMailFrom"),
1777 (SetErrorType::ForbiddenToSend, "forbiddenToSend"),
1778 (SetErrorType::CannotUnsend, "cannotUnsend"),
1779 ];
1780
1781 for (variant, expected_wire) in cases {
1782 // Display
1783 assert_eq!(
1784 variant.to_string(),
1785 *expected_wire,
1786 "Display arm for {variant:?} produced wrong wire string"
1787 );
1788 // Serialize (delegates to Display)
1789 let serialized = serde_json::to_string(variant).expect("serialize");
1790 assert_eq!(
1791 serialized,
1792 format!("\"{expected_wire}\""),
1793 "Serialize for {variant:?} did not produce \"{expected_wire}\""
1794 );
1795 // Deserialize back — MUST rebuild the typed variant, NOT Custom.
1796 let deserialized: SetErrorType =
1797 serde_json::from_str(&serialized).expect("deserialize");
1798 assert_eq!(
1799 &deserialized, variant,
1800 "Deserialize of {expected_wire:?} did not rebuild {variant:?} \
1801 (likely fell through to Custom — Display and Deserialize \
1802 match arms have drifted)"
1803 );
1804 // Belt-and-braces: explicitly assert NOT Custom.
1805 assert!(
1806 !matches!(deserialized, SetErrorType::Custom(_)),
1807 "Deserialize of {expected_wire:?} fell through to Custom; \
1808 Display has an arm but Deserialize visitor doesn't"
1809 );
1810 }
1811 }
1812
1813 /// Oracle (bd:JMAP-ga0q.1): `JmapBackend::principal_id` has a default impl
1814 /// that returns `None`. A backend whose `CallerCtx = ()` and that does NOT
1815 /// override `principal_id` inherits that default and signals "identity not
1816 /// wired" to callers. JMAP semantics that depend on caller identity must
1817 /// treat `None` as a hard "cannot honor".
1818 #[test]
1819 fn principal_id_default_impl_returns_none_for_unit_caller_ctx() {
1820 // Minimal stub backend exercising only the default impl. All other
1821 // trait methods are stubbed with `unreachable!()` and never invoked.
1822 struct StubBackend;
1823
1824 #[derive(Debug)]
1825 struct StubError;
1826
1827 impl std::fmt::Display for StubError {
1828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1829 f.write_str("stub")
1830 }
1831 }
1832 impl std::error::Error for StubError {}
1833
1834 impl JmapBackend for StubBackend {
1835 type Error = StubError;
1836 type CallerCtx = ();
1837
1838 async fn account_exists(
1839 &self,
1840 _caller: &(),
1841 _account_id: &jmap_types::Id,
1842 ) -> Result<bool, Self::Error> {
1843 unreachable!("only principal_id is exercised in this test")
1844 }
1845
1846 async fn get_objects<O: GetObject + Send + Sync>(
1847 &self,
1848 _caller: &(),
1849 _account_id: &jmap_types::Id,
1850 _ids: Option<&[jmap_types::Id]>,
1851 _properties: Option<&[String]>,
1852 ) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
1853 unreachable!("only principal_id is exercised in this test")
1854 }
1855
1856 async fn get_state<O: JmapObject + Send + Sync>(
1857 &self,
1858 _caller: &(),
1859 _account_id: &jmap_types::Id,
1860 ) -> Result<jmap_types::State, Self::Error> {
1861 unreachable!("only principal_id is exercised in this test")
1862 }
1863
1864 async fn get_changes<O: JmapObject + Send + Sync>(
1865 &self,
1866 _caller: &(),
1867 _account_id: &jmap_types::Id,
1868 _since_state: &jmap_types::State,
1869 _max_changes: Option<u64>,
1870 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1871 unreachable!("only principal_id is exercised in this test")
1872 }
1873
1874 async fn query_objects<O: QueryObject + Send + Sync>(
1875 &self,
1876 _caller: &(),
1877 _account_id: &jmap_types::Id,
1878 _filter: Option<&O::Filter>,
1879 _sort: Option<&[O::Comparator]>,
1880 _limit: Option<u64>,
1881 _position: i64,
1882 _anchor: Option<&jmap_types::Id>,
1883 _anchor_offset: i64,
1884 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1885 unreachable!("only principal_id is exercised in this test")
1886 }
1887
1888 async fn query_changes<O: QueryObject + Send + Sync>(
1889 &self,
1890 _caller: &(),
1891 _account_id: &jmap_types::Id,
1892 _since_query_state: &jmap_types::State,
1893 _filter: Option<&O::Filter>,
1894 _sort: Option<&[O::Comparator]>,
1895 _max_changes: Option<u64>,
1896 _up_to_id: Option<&jmap_types::Id>,
1897 _collapse_threads: bool,
1898 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1899 unreachable!("only principal_id is exercised in this test")
1900 }
1901 }
1902
1903 let caller: <StubBackend as JmapBackend>::CallerCtx = ();
1904 let id = <StubBackend as JmapBackend>::principal_id(&caller);
1905 assert!(
1906 id.is_none(),
1907 "default principal_id impl must return None; got Some({:?})",
1908 id
1909 );
1910 }
1911
1912 /// Oracle (bd:JMAP-ayoz.41.1): `JmapBackend::max_objects_in_set`
1913 /// has a default impl that returns `500`. The constant is the
1914 /// workspace's testjig Session JSON advertised cap; a backend that
1915 /// does not override the method inherits a sane DoS-defence
1916 /// default rather than silently disabling the cap.
1917 #[test]
1918 fn max_objects_in_set_default_impl_returns_500() {
1919 struct StubBackend;
1920
1921 #[derive(Debug)]
1922 struct StubError;
1923
1924 impl std::fmt::Display for StubError {
1925 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1926 f.write_str("stub")
1927 }
1928 }
1929 impl std::error::Error for StubError {}
1930
1931 impl JmapBackend for StubBackend {
1932 type Error = StubError;
1933 type CallerCtx = ();
1934
1935 async fn account_exists(
1936 &self,
1937 _caller: &(),
1938 _account_id: &jmap_types::Id,
1939 ) -> Result<bool, Self::Error> {
1940 unreachable!("only max_objects_in_set is exercised in this test")
1941 }
1942
1943 async fn get_objects<O: GetObject + Send + Sync>(
1944 &self,
1945 _caller: &(),
1946 _account_id: &jmap_types::Id,
1947 _ids: Option<&[jmap_types::Id]>,
1948 _properties: Option<&[String]>,
1949 ) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
1950 unreachable!("only max_objects_in_set is exercised in this test")
1951 }
1952
1953 async fn get_state<O: JmapObject + Send + Sync>(
1954 &self,
1955 _caller: &(),
1956 _account_id: &jmap_types::Id,
1957 ) -> Result<jmap_types::State, Self::Error> {
1958 unreachable!("only max_objects_in_set is exercised in this test")
1959 }
1960
1961 async fn get_changes<O: JmapObject + Send + Sync>(
1962 &self,
1963 _caller: &(),
1964 _account_id: &jmap_types::Id,
1965 _since_state: &jmap_types::State,
1966 _max_changes: Option<u64>,
1967 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1968 unreachable!("only max_objects_in_set is exercised in this test")
1969 }
1970
1971 async fn query_objects<O: QueryObject + Send + Sync>(
1972 &self,
1973 _caller: &(),
1974 _account_id: &jmap_types::Id,
1975 _filter: Option<&O::Filter>,
1976 _sort: Option<&[O::Comparator]>,
1977 _limit: Option<u64>,
1978 _position: i64,
1979 _anchor: Option<&jmap_types::Id>,
1980 _anchor_offset: i64,
1981 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1982 unreachable!("only max_objects_in_set is exercised in this test")
1983 }
1984
1985 async fn query_changes<O: QueryObject + Send + Sync>(
1986 &self,
1987 _caller: &(),
1988 _account_id: &jmap_types::Id,
1989 _since_query_state: &jmap_types::State,
1990 _filter: Option<&O::Filter>,
1991 _sort: Option<&[O::Comparator]>,
1992 _max_changes: Option<u64>,
1993 _up_to_id: Option<&jmap_types::Id>,
1994 _collapse_threads: bool,
1995 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1996 unreachable!("only max_objects_in_set is exercised in this test")
1997 }
1998 }
1999
2000 let backend = StubBackend;
2001 let caller: <StubBackend as JmapBackend>::CallerCtx = ();
2002 let id = jmap_types::Id::from("any-account");
2003 assert_eq!(
2004 backend.max_objects_in_set(&caller, &id),
2005 500,
2006 "default max_objects_in_set must return 500"
2007 );
2008 }
2009}