Skip to main content

jmap_server/
handlers.rs

1//! Generic JMAP method handlers shared across all server crates.
2//!
3//! Each function handles one RFC 8620 operation type for any object type `O`
4//! and any backend `B: JmapBackend`. Domain crates call these for types that
5//! have no domain-specific logic beyond the standard wire protocol.
6//!
7//! # Backend-error leak policy (bd:JMAP-wlip.2)
8//!
9//! Every handler in this module that maps a [`JmapBackend::Error`] to a
10//! wire-format [`JmapError::server_fail`] MUST use the static description
11//! [`SERVER_FAIL_INTERNAL_DESC`] rather than interpolating the backend
12//! error's [`Display`](std::fmt::Display) output. The backend-error
13//! contract on [`JmapBackend::Error`] (`crate::backend::JmapBackend`'s
14//! associated-type doc comment) forbids credential / blob / PII in
15//! `Display`, but a single accidental violation by a backend implementor
16//! would land the leaked text in `serverFail.description` on every
17//! affected response. Stripping the description at the handler layer
18//! changes that from a wire-format security incident into a server-side
19//! diagnostic gap that the operator can close with its own structured
20//! logger wrapping the backend call.
21//!
22//! Extension `*-server` crates with their own per-method handlers
23//! SHOULD follow the same pattern; the helper [`server_fail_from_backend`]
24//! exists so each call site is one line and reviewable at a glance.
25
26use crate::HandlerOutput;
27use jmap_types::{Id, JmapError, State};
28use serde_json::{Value, json};
29
30use crate::backend::{
31    BackendChangesError, ChangesParams, GetObject, JmapBackend, JmapObject, QueryChangesParams,
32    QueryObject, QueryParams,
33};
34use crate::helpers::{
35    MetadataProjection, enforce_max_objects_in_get, extract_account_id, filter_arg, not_found_json,
36    optional_arg, query_anchor_args, serialize_value,
37};
38
39/// Static description used for every `serverFail` invocation that wraps a
40/// [`JmapBackend::Error`] (bd:JMAP-wlip.2).
41///
42/// RFC 8620 §3.6.2 explicitly permits omitting the description; a static
43/// "internal error" is RFC-compliant and forecloses the backend-error
44/// Display leak path documented on `JmapBackend::Error`.
45pub const SERVER_FAIL_INTERNAL_DESC: &str = "internal error";
46
47/// Construct a [`JmapError::server_fail`] for a backend-originated error
48/// without echoing the backend error's [`Display`](std::fmt::Display) output
49/// onto the wire (bd:JMAP-wlip.2).
50///
51/// **The `err` parameter is intentionally discarded** (bd:JMAP-jfia.22).
52/// It exists only to keep the call site ergonomic
53/// (`.map_err(|e| server_fail_from_backend(&e))`) — the function never
54/// reads it, logs it, or stashes it. Callers that want their backend
55/// error visible in operator logs MUST log it explicitly at the call
56/// site before invoking this helper; no logging happens here, because
57/// a backend error's text can carry data that must not reach logs.
58///
59/// The backend error parameter is accepted by reference (and discarded) so
60/// callers retain it for their own structured logging if they wire one. The
61/// returned `JmapError` always carries the static
62/// [`SERVER_FAIL_INTERNAL_DESC`] description; no caller-controlled text
63/// reaches the wire from this helper.
64///
65/// The function is generic over any `Display` (not just
66/// `JmapBackend::Error`) so the extension `*-server` crates' own per-method
67/// handlers — which mix [`JmapBackend::Error`], domain-specific error
68/// envelopes (`BackendSetError::Other`, `BackendChangesError::Other`), and
69/// trait-method errors — can call it uniformly.
70///
71/// # Use at every site that maps a backend error to `serverFail`
72///
73/// Replace:
74///
75/// ```ignore
76/// .map_err(|e| JmapError::server_fail(e.to_string()))
77/// ```
78///
79/// with:
80///
81/// ```ignore
82/// .map_err(|e| server_fail_from_backend(&e))
83/// ```
84pub fn server_fail_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> JmapError {
85    JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)
86}
87
88/// Map a [`JmapBackend::get_changes`](crate::JmapBackend::get_changes)
89/// error to the `Foo/changes` method error (RFC 8620 §5.2).
90///
91/// `tooManyChanges` is a `Foo/queryChanges` error only (§5.6); §5.2 lists
92/// `cannotCalculateChanges` as the sole changes-specific error, and a
93/// server over `maxChanges` that "is unable to calculate an intermediate
94/// state ... MUST return a "cannotCalculateChanges" error response
95/// instead". So [`BackendChangesError::TooManyChanges`] becomes
96/// `cannotCalculateChanges` here; every other variant maps as its
97/// [`From`] impl does. Every `/changes` handler uses this instead of
98/// `JmapError::from`; `/queryChanges` handlers keep `JmapError::from`.
99pub fn changes_error_from_backend<E: std::error::Error>(err: BackendChangesError<E>) -> JmapError {
100    match err {
101        BackendChangesError::TooManyChanges { .. } => JmapError::cannot_calculate_changes(),
102        other => JmapError::from(other),
103    }
104}
105
106/// Construct the per-id `serverFail` [`Value`] used inside the
107/// `notCreated`/`notUpdated`/`notDestroyed` maps of `/set` responses
108/// (bd:JMAP-ic0j.68), without echoing the backend error's
109/// [`Display`](std::fmt::Display) output onto the wire.
110///
111/// This is the [`Value`]-shaped sibling of [`server_fail_from_backend`].
112/// The handler-layer helper returns a [`JmapError`] which is only useful
113/// where the entire method invocation fails. Per-id `/set` failures are
114/// expressed as a [`serde_json::Value`] keyed under each failing id in
115/// `notCreated` / `notUpdated` / `notDestroyed`; the existing
116/// `JmapError`-shaped helper does not fit those sites, so each crate
117/// previously hand-rolled
118/// `json!({ "type": "serverFail", "description": e.to_string() })` —
119/// every one of which leaks the backend error's `Display` onto the wire,
120/// in direct violation of the [`JmapBackend::Error`](crate::JmapBackend)
121/// Display MUST-NOT contract.
122///
123/// **The `err` parameter is intentionally discarded** (bd:JMAP-jfia.22),
124/// matching the contract on [`server_fail_from_backend`]. It exists only
125/// to keep the call site ergonomic — the function never reads it, logs
126/// it, or stashes it. Callers that want their backend error visible in
127/// operator logs MUST log it explicitly at the call site before invoking
128/// this helper.
129///
130/// The function is generic over any [`Display`](std::fmt::Display) so it
131/// applies uniformly to [`JmapBackend::Error`](crate::JmapBackend),
132/// [`BackendSetError::Other`](crate::BackendSetError),
133/// [`BackendChangesError::Other`](crate::BackendChangesError), and any
134/// extension-trait-specific error envelope. It also accepts the
135/// `&String` shape produced by some legacy helpers that flattened a
136/// backend error to `String` before propagating.
137///
138/// # Use at every per-id /set serverFail site
139///
140/// Replace:
141///
142/// ```ignore
143/// json!({ "type": "serverFail", "description": e.to_string() })
144/// ```
145///
146/// with:
147///
148/// ```ignore
149/// server_fail_value_from_backend(&e)
150/// ```
151pub fn server_fail_value_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> Value {
152    json!({
153        "type": "serverFail",
154        "description": SERVER_FAIL_INTERNAL_DESC,
155    })
156}
157
158// ---------------------------------------------------------------------------
159// handle_get
160// ---------------------------------------------------------------------------
161
162/// Generic `*/get` handler (RFC 8620 §5.1).
163///
164/// Fetches objects by id (or all objects when `ids` is absent or `null`) and
165/// returns the standard `get` response shape. Returns the method-level
166/// `requestTooLarge` error when `ids` holds more entries than
167/// [`JmapBackend::max_objects_in_get`] allows; a null `ids` is not counted.
168pub async fn handle_get<O: GetObject, B: JmapBackend>(
169    backend: &B,
170    caller: &B::CallerCtx,
171    args: Value,
172) -> Result<HandlerOutput, JmapError> {
173    let (account_id, mut args) = extract_account_id(args)?;
174    if !backend
175        .account_exists(caller, &account_id)
176        .await
177        .map_err(|e| server_fail_from_backend(&e))?
178    {
179        return Err(JmapError::account_not_found());
180    }
181    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
182
183    let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
184        JmapError::invalid_arguments("ids must be an Id array")
185    })?;
186
187    let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
188        JmapError::invalid_arguments("properties must be a string array")
189    })?;
190
191    let ids_slice = ids.as_deref();
192    let (list, not_found) = backend
193        .get_objects::<O>(caller, &account_id, ids_slice, properties.as_deref())
194        .await
195        .map_err(|e| server_fail_from_backend(&e))?;
196
197    let state = backend
198        .get_state::<O>(caller, &account_id)
199        .await
200        .map_err(|e| server_fail_from_backend(&e))?;
201
202    // bd:JMAP-jfia.10 — batch-serialize the entire Vec<O> rather than
203    // calling to_value per element. One serializer construction
204    // instead of N. For Mailbox/get / Email/get over large accounts
205    // (~100k+ objects) the saving is measurable. serde_json::to_value
206    // on a Vec<O> always produces Value::Array(Vec<Value>) so the
207    // wire shape is identical.
208    let mut list_json = serialize_value(&list)?;
209
210    // RFC 8620 §5.1: "If supplied, only the properties listed in the array
211    // are returned for each Foo object. ... The id property of the object
212    // is *always* returned". Backends MAY ignore `properties`, so project
213    // here. ponytail: unknown property names are not rejected with
214    // invalidArguments; the generic handler has no per-type property list.
215    if let (Some(props), Value::Array(items)) = (&properties, &mut list_json) {
216        for item in items {
217            if let Value::Object(map) = item {
218                map.retain(|k, _| k == "id" || props.iter().any(|p| p == k));
219            }
220        }
221    }
222
223    Ok(HandlerOutput::new(json!({
224        "accountId": account_id.as_ref(),
225        "state": state.as_ref(),
226        "list": list_json,
227        "notFound": not_found_json(&not_found),
228    })))
229}
230
231/// [`handle_get`] for a type the backend may list for
232/// draft-ietf-jmap-metadata-05 ([`JmapBackend::metadata_info`]).
233///
234/// `using` is the request's capability list ([`crate::CallContext::using`]).
235/// When `O` is listed in `accountId`, `metadata` and `privateMetadata`
236/// follow [`MetadataProjection`]: returned as an object (`{}` when nothing
237/// is stored), included by default only with
238/// `urn:ietf:params:jmap:metadata` in `using`, `metadata/<namespace>`
239/// subselectors applied, and `privateMetadata` never returned when
240/// `supportsPrivate` is false (-05 §2, §3, §3.1). The backend is asked for
241/// the root property in place of each subselector. When `O` is not listed
242/// this is exactly [`handle_get`], so an unrelated property that happens to
243/// be named `metadata` is left alone.
244///
245/// # Errors
246///
247/// Those of [`handle_get`], and `invalidArguments` for a malformed
248/// `metadata/` or `privateMetadata/` entry (-05 §3.1).
249pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
250    backend: &B,
251    caller: &B::CallerCtx,
252    mut args: Value,
253    using: &[String],
254) -> Result<HandlerOutput, JmapError> {
255    let info = args
256        .get("accountId")
257        .and_then(Value::as_str)
258        .and_then(|s| Id::new_validated(s).ok())
259        .and_then(|id| backend.metadata_info::<O>(caller, &id));
260    let Some(info) = info else {
261        return handle_get::<O, B>(backend, caller, args).await;
262    };
263    let properties: Option<Vec<String>> = match args.get("properties") {
264        None | Some(Value::Null) => None,
265        Some(v) => match serde_json::from_value(v.clone()) {
266            Ok(props) => Some(props),
267            // handle_get reports the malformed argument.
268            Err(_) => return handle_get::<O, B>(backend, caller, args).await,
269        },
270    };
271    let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
272    if let Some(props) = properties {
273        let mut roots: Vec<String> = Vec::with_capacity(props.len());
274        for p in props {
275            let root = match p.split_once('/') {
276                Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
277                _ => p,
278            };
279            if !roots.contains(&root) {
280                roots.push(root);
281            }
282        }
283        args["properties"] = json!(roots);
284    }
285    let mut out = handle_get::<O, B>(backend, caller, args).await?;
286    if let Some(Value::Array(list)) = out.primary.get_mut("list") {
287        for item in list {
288            let source = item.clone();
289            projection.apply(&source, item);
290        }
291    }
292    Ok(out)
293}
294
295// ---------------------------------------------------------------------------
296// handle_changes
297// ---------------------------------------------------------------------------
298
299/// Generic `*/changes` handler (RFC 8620 §5.2).
300///
301/// `using` is the request's capability list ([`crate::CallContext::using`]).
302/// When it includes `urn:ietf:params:jmap:metadata`, the optional
303/// `ignoreMetadataOnlyChanges` argument (draft-ietf-jmap-metadata-05 §3.3)
304/// is parsed, and must be a boolean; otherwise the backend is told to
305/// ignore metadata-only changes, because -05 §3 says such a request "MUST
306/// behave as if ignoreMetadataOnlyChanges were true".
307///
308/// `updatedProperties` is [`ChangesResult::updated_properties`]
309/// (RFC 8621 §2.2, -05 §3.3), and `null` whenever `updated` is empty
310/// (-05 §3.3: "It is always present, and is null when updated is empty").
311/// Backends that do not track per-property change detail MUST leave it
312/// `None`: an empty array would mean "nothing about the listed objects
313/// actually changed".
314///
315/// [`ChangesResult::updated_properties`]: crate::ChangesResult::updated_properties
316pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
317    backend: &B,
318    caller: &B::CallerCtx,
319    args: Value,
320    using: &[String],
321) -> Result<HandlerOutput, JmapError> {
322    let (account_id, args) = extract_account_id(args)?;
323    if !backend
324        .account_exists(caller, &account_id)
325        .await
326        .map_err(|e| server_fail_from_backend(&e))?
327    {
328        return Err(JmapError::account_not_found());
329    }
330
331    let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
332        Some(s) => State::from(s),
333        None => return Err(JmapError::invalid_arguments("sinceState is required")),
334    };
335
336    let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
337
338    let uses_metadata = using
339        .iter()
340        .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
341    let ignore_metadata_only_changes = !uses_metadata
342        || match args.get("ignoreMetadataOnlyChanges") {
343            None | Some(Value::Null) => false,
344            Some(Value::Bool(b)) => *b,
345            Some(v) => {
346                return Err(JmapError::invalid_arguments(format!(
347                    "ignoreMetadataOnlyChanges: expected a boolean, got {}",
348                    crate::helpers::json_type_name(v)
349                )));
350            }
351        };
352
353    let result = backend
354        .get_changes::<O>(
355            caller,
356            &account_id,
357            ChangesParams::new(&since_state)
358                .max_changes(max_changes)
359                .ignore_metadata_only_changes(ignore_metadata_only_changes),
360        )
361        .await
362        .map_err(changes_error_from_backend)?;
363    let updated_properties = if result.updated.is_empty() {
364        None
365    } else {
366        result.updated_properties
367    };
368
369    Ok(HandlerOutput::new(json!({
370        "accountId": account_id.as_ref(),
371        "oldState": since_state.as_ref(),
372        "newState": result.new_state.as_ref(),
373        "hasMoreChanges": result.has_more_changes,
374        "updatedProperties": updated_properties,
375        // bd:JMAP-wlip.28 — Vec<Id> serializes directly via Id's
376        // #[serde(transparent)] impl; no intermediate &str Vec needed.
377        "created":   result.created,
378        "updated":   result.updated,
379        "destroyed": result.destroyed,
380    })))
381}
382
383// ---------------------------------------------------------------------------
384// handle_query
385// ---------------------------------------------------------------------------
386
387/// Generic `*/query` handler (RFC 8620 §5.5).
388///
389/// Parses filter and sort from args as `O::Filter` and `O::Comparator`, and
390/// `anchor`/`anchorOffset` via [`query_anchor_args`], then delegates to
391/// [`JmapBackend::query_objects`]. A
392/// [`BackendQueryError::Method`](crate::backend::BackendQueryError::Method)
393/// is returned to the client unchanged; any other backend error becomes the
394/// redacted `serverFail`.
395pub async fn handle_query<O: QueryObject, B: JmapBackend>(
396    backend: &B,
397    caller: &B::CallerCtx,
398    args: Value,
399) -> Result<HandlerOutput, JmapError> {
400    let (account_id, mut args) = extract_account_id(args)?;
401    if !backend
402        .account_exists(caller, &account_id)
403        .await
404        .map_err(|e| server_fail_from_backend(&e))?
405    {
406        return Err(JmapError::account_not_found());
407    }
408
409    let calculate_total: bool = args
410        .get("calculateTotal")
411        .and_then(|v| v.as_bool())
412        .unwrap_or(false);
413
414    let limit: Option<u64> = match args.get("limit") {
415        None | Some(Value::Null) => None,
416        Some(v) => match v.as_u64() {
417            Some(n) => Some(n),
418            None => {
419                return Err(JmapError::invalid_arguments(format!(
420                    "limit: expected a non-negative integer, got {}",
421                    crate::helpers::json_type_name(v)
422                )));
423            }
424        },
425    };
426
427    let position: i64 = match args.get("position") {
428        None | Some(Value::Null) => 0,
429        Some(v) => v.as_i64().ok_or_else(|| {
430            JmapError::invalid_arguments(format!(
431                "position: expected an integer, got {}",
432                crate::helpers::json_type_name(v)
433            ))
434        })?,
435    };
436
437    let (anchor, anchor_offset) = query_anchor_args(&args)?;
438
439    let filter: Option<O::Filter> = filter_arg(&mut args)?;
440
441    let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
442        JmapError::invalid_arguments("sort must be an array")
443    })?;
444
445    let result = backend
446        .query_objects::<O>(
447            caller,
448            &account_id,
449            QueryParams::new()
450                .filter(filter.as_ref())
451                .sort(sort.as_deref())
452                .limit(limit)
453                .position(position)
454                .anchor(anchor.as_ref())
455                .anchor_offset(anchor_offset),
456        )
457        .await
458        .map_err(JmapError::from)?;
459
460    let mut resp = json!({
461        "accountId": account_id.as_ref(),
462        "queryState": result.query_state.as_ref(),
463        "canCalculateChanges": result.can_calculate_changes,
464        "position": result.position,
465        // bd:JMAP-wlip.28 — Vec<Id> serializes directly via Id's
466        // #[serde(transparent)] impl.
467        "ids": result.ids,
468    });
469    if calculate_total && let Some(t) = result.total {
470        resp["total"] = json!(t);
471    }
472
473    Ok(HandlerOutput::new(resp))
474}
475
476// ---------------------------------------------------------------------------
477// handle_query_changes
478// ---------------------------------------------------------------------------
479
480/// Generic `*/queryChanges` handler (RFC 8620 §5.6).
481///
482/// Parses filter and sort from args, then delegates to
483/// [`JmapBackend::query_changes`] with `collapse_threads: false`. For
484/// `Email/queryChanges` (which may need `collapseThreads: true`), use the
485/// domain-specific handler in jmap-mail-server instead.
486pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
487    backend: &B,
488    caller: &B::CallerCtx,
489    args: Value,
490) -> Result<HandlerOutput, JmapError> {
491    let (account_id, mut args) = extract_account_id(args)?;
492    if !backend
493        .account_exists(caller, &account_id)
494        .await
495        .map_err(|e| server_fail_from_backend(&e))?
496    {
497        return Err(JmapError::account_not_found());
498    }
499
500    let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
501        Some(s) => State::from(s),
502        None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
503    };
504
505    let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
506
507    let up_to_id: Option<Id> = match args.get("upToId") {
508        None | Some(Value::Null) => None,
509        Some(Value::String(s)) => Some(Id::from(s.as_str())),
510        Some(_) => {
511            return Err(JmapError::invalid_arguments(
512                "upToId must be a string Id or null",
513            ));
514        }
515    };
516
517    let calculate_total: bool = args
518        .get("calculateTotal")
519        .and_then(|v| v.as_bool())
520        .unwrap_or(false);
521
522    let filter: Option<O::Filter> = filter_arg(&mut args)?;
523
524    let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
525        JmapError::invalid_arguments("sort must be an array")
526    })?;
527
528    let result = backend
529        .query_changes::<O>(
530            caller,
531            &account_id,
532            QueryChangesParams::new(&since_query_state)
533                .filter(filter.as_ref())
534                .sort(sort.as_deref())
535                .max_changes(max_changes)
536                .up_to_id(up_to_id.as_ref()),
537        )
538        .await
539        .map_err(JmapError::from)?;
540
541    let added: Vec<Value> = result
542        .added
543        .iter()
544        .map(|item| {
545            json!({
546                "id": item.id.as_ref(),
547                "index": item.index,
548            })
549        })
550        .collect();
551
552    let mut resp = json!({
553        "accountId": account_id.as_ref(),
554        "oldQueryState": result.old_query_state.as_ref(),
555        "newQueryState": result.new_query_state.as_ref(),
556        // bd:JMAP-wlip.28 — Vec<Id> serializes directly.
557        "removed": result.removed,
558        "added": added,
559    });
560    if calculate_total && let Some(t) = result.total {
561        resp["total"] = json!(t);
562    }
563
564    Ok(HandlerOutput::new(resp))
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    /// Oracle (bd:JMAP-wlip.2): [`server_fail_from_backend`] MUST NOT echo
572    /// the backend error's `Display` text into the resulting JmapError's
573    /// description. The defence-in-depth contract is that even if a
574    /// backend implementor accidentally violates the
575    /// [`JmapBackend::Error`](crate::JmapBackend) Display MUST-NOT
576    /// (credential / blob / PII), the leaked text never reaches the wire.
577    ///
578    /// Test vector: an error whose Display contains a canary string
579    /// resembling a credential leak. The canary literal is hand-built and
580    /// not derived from any production type's behaviour.
581    #[test]
582    fn server_fail_from_backend_drops_display_text() {
583        #[derive(Debug)]
584        struct LeakyError(&'static str);
585        impl std::fmt::Display for LeakyError {
586            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587                f.write_str(self.0)
588            }
589        }
590        impl std::error::Error for LeakyError {}
591
592        const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
593        let err = LeakyError(CANARY);
594
595        let jmap_err = server_fail_from_backend(&err);
596
597        // Serialize to wire shape and assert the canary is absent from
598        // every value in the resulting JSON. The error_invocation wraps
599        // a JmapError as { "type": "serverFail", "description": "..." }
600        // — both fields are wire-visible.
601        let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
602        let wire_str = wire.to_string();
603        assert!(
604            !wire_str.contains(CANARY),
605            "server_fail_from_backend must not echo backend error Display \
606             onto the wire; got {wire_str}"
607        );
608        // The description MUST be exactly SERVER_FAIL_INTERNAL_DESC.
609        assert_eq!(
610            wire["description"], SERVER_FAIL_INTERNAL_DESC,
611            "description must be the static 'internal error' string"
612        );
613        assert_eq!(wire["type"], "serverFail");
614    }
615
616    /// Oracle: the helper accepts any `Display` — not just
617    /// [`JmapBackend::Error`](crate::JmapBackend) — so the extension
618    /// `*-server` crates' per-method handlers can use the same call
619    /// site for `BackendSetError`, `BackendChangesError`, and any
620    /// trait-method-specific error envelope.
621    #[test]
622    fn server_fail_from_backend_accepts_generic_display() {
623        // String, &str, and a custom Display all compile-check that the
624        // bound is `Display + ?Sized`.
625        let _ = server_fail_from_backend("a string");
626        let _ = server_fail_from_backend(&"&str".to_owned());
627        let _ = server_fail_from_backend(&42_u64);
628    }
629
630    /// Oracle (bd:JMAP-ic0j.68): [`server_fail_value_from_backend`] MUST
631    /// NOT echo the backend error's `Display` text into the per-id
632    /// `serverFail` Value used inside `/set`'s `notCreated`/`notUpdated`/
633    /// `notDestroyed` maps. Mirrors the
634    /// [`server_fail_from_backend_drops_display_text`] oracle for the
635    /// `JmapError`-shaped sibling helper.
636    ///
637    /// Test vector: an error whose `Display` contains a canary string
638    /// resembling a credential leak. The canary literal is hand-built and
639    /// not derived from any production type's behaviour.
640    #[test]
641    fn server_fail_value_from_backend_drops_display_text() {
642        #[derive(Debug)]
643        struct LeakyError(&'static str);
644        impl std::fmt::Display for LeakyError {
645            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646                f.write_str(self.0)
647            }
648        }
649        impl std::error::Error for LeakyError {}
650
651        const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
652        let err = LeakyError(CANARY);
653
654        let wire = server_fail_value_from_backend(&err);
655
656        // The canary MUST NOT appear anywhere in the serialized wire shape.
657        let wire_str = wire.to_string();
658        assert!(
659            !wire_str.contains(CANARY),
660            "server_fail_value_from_backend must not echo backend error \
661             Display onto the wire; got {wire_str}"
662        );
663        // Wire shape: { "type": "serverFail", "description": "internal error" }.
664        assert_eq!(wire["type"], "serverFail");
665        assert_eq!(
666            wire["description"], SERVER_FAIL_INTERNAL_DESC,
667            "description must be the static 'internal error' string"
668        );
669    }
670
671    /// Oracle: the helper accepts any `Display` — not just
672    /// [`JmapBackend::Error`](crate::JmapBackend) — so the extension
673    /// `*-server` crates' per-method handlers can use the same call
674    /// site for `BackendSetError::Other`, `BackendChangesError::Other`,
675    /// and the `&String` shape produced by some legacy helpers.
676    #[test]
677    fn server_fail_value_from_backend_accepts_generic_display() {
678        // String, &str, &String, and a custom Display all compile-check
679        // that the bound is `Display + ?Sized`.
680        let _ = server_fail_value_from_backend("a string");
681        let _ = server_fail_value_from_backend(&"owned-String".to_owned());
682        let owned: String = "owned".to_string();
683        let _ = server_fail_value_from_backend(&owned);
684        let _ = server_fail_value_from_backend(&42_u64);
685    }
686
687    // -----------------------------------------------------------------
688    // handle_query: backend method errors pass through (bd:JMAP-yt1w.21)
689    // -----------------------------------------------------------------
690
691    use crate::backend::{
692        BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
693        QueryChangesResult, QueryParams,
694    };
695
696    /// Minimal `QueryObject` used only to instantiate [`handle_query`].
697    #[derive(serde::Serialize, serde::Deserialize)]
698    struct QueryProbe;
699
700    impl JmapObject for QueryProbe {
701        const TYPE_NAME: &'static str = "QueryProbe";
702        type Property = ();
703    }
704
705    impl QueryObject for QueryProbe {
706        type Filter = Value;
707        type Comparator = Value;
708    }
709
710    #[derive(Debug)]
711    struct LeakyQueryError(&'static str);
712
713    impl std::fmt::Display for LeakyQueryError {
714        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
715            f.write_str(self.0)
716        }
717    }
718
719    impl std::error::Error for LeakyQueryError {}
720
721    /// What [`QueryFailBackend::query_objects`] returns.
722    enum QueryFailure {
723        /// An RFC 8620 §5.5 method error the backend chose deliberately.
724        Method(JmapError),
725        /// An internal storage-layer failure whose `Display` must never
726        /// reach the wire.
727        Internal(&'static str),
728    }
729
730    /// Backend whose account exists and whose `query_objects` always fails
731    /// with the configured [`QueryFailure`]. Every other method is unused.
732    struct QueryFailBackend(QueryFailure);
733
734    impl JmapBackend for QueryFailBackend {
735        type Error = LeakyQueryError;
736        type CallerCtx = ();
737
738        async fn account_exists(
739            &self,
740            _caller: &(),
741            _account_id: &Id,
742        ) -> Result<bool, Self::Error> {
743            Ok(true)
744        }
745
746        async fn get_objects<O: GetObject + Send + Sync>(
747            &self,
748            _caller: &(),
749            _account_id: &Id,
750            _ids: Option<&[Id]>,
751            _properties: Option<&[String]>,
752        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
753            unreachable!("only query_objects is exercised")
754        }
755
756        async fn get_state<O: JmapObject + Send + Sync>(
757            &self,
758            _caller: &(),
759            _account_id: &Id,
760        ) -> Result<State, Self::Error> {
761            unreachable!("only query_objects is exercised")
762        }
763
764        async fn get_changes<O: JmapObject + Send + Sync>(
765            &self,
766            _caller: &(),
767            _account_id: &Id,
768            _params: ChangesParams<'_>,
769        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
770            unreachable!("only query_objects is exercised")
771        }
772
773        async fn query_objects<O: QueryObject + Send + Sync>(
774            &self,
775            _caller: &(),
776            _account_id: &Id,
777            _params: QueryParams<'_, O>,
778        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
779            Err(match &self.0 {
780                QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
781                QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
782            })
783        }
784
785        async fn query_changes<O: QueryObject + Send + Sync>(
786            &self,
787            _caller: &(),
788            _account_id: &Id,
789            _params: QueryChangesParams<'_, O>,
790        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
791            unreachable!("only query_objects is exercised")
792        }
793    }
794
795    /// Run `QueryProbe/query` against a [`QueryFailBackend`] and return the
796    /// method-level error serialized in its wire shape.
797    async fn query_error_wire(failure: QueryFailure) -> Value {
798        let backend = QueryFailBackend(failure);
799        let args = json!({
800            "accountId": "a1",
801            "filter": { "text": "hello" },
802            "anchor": "m1",
803        });
804        let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
805            Ok(HandlerOutput { primary: resp, .. }) => {
806                panic!("query_objects failed but handle_query succeeded: {resp}")
807            }
808            Err(e) => e,
809        };
810        serde_json::to_value(&err).expect("JmapError must serialize")
811    }
812
813    /// Oracle: RFC 8620 §5.5 (/home/mark/PROJECT/IETF/specs/rfc8620.txt,
814    /// Section 5.5 "/query"):
815    ///
816    /// > The following additional errors may be returned instead of the
817    /// > "Foo/query" response:
818    /// >
819    /// > "unsupportedFilter": The "filter" is syntactically valid, but the
820    /// > server cannot process it.
821    ///
822    /// Whether a syntactically valid filter can be processed is known only
823    /// to the backend, so a backend-returned `unsupportedFilter` MUST reach
824    /// the client unchanged (type and description), not as `serverFail`.
825    #[tokio::test]
826    async fn handle_query_passes_backend_unsupported_filter_through() {
827        let mut expected = JmapError::unsupported_filter();
828        expected.description = Some("Message/query requires a chatId condition".into());
829
830        let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
831
832        assert_eq!(
833            wire,
834            serde_json::to_value(&expected).expect("JmapError must serialize"),
835            "backend unsupportedFilter must pass through handle_query unchanged"
836        );
837    }
838
839    /// Oracle: RFC 8620 §5.5 (/home/mark/PROJECT/IETF/specs/rfc8620.txt,
840    /// Section 5.5 "/query"):
841    ///
842    /// > "anchorNotFound": An anchor argument was supplied, but it cannot be
843    /// > found in the results of the query.
844    ///
845    /// Only the backend evaluates the query results, so a backend-returned
846    /// `anchorNotFound` MUST reach the client unchanged.
847    #[tokio::test]
848    async fn handle_query_passes_backend_anchor_not_found_through() {
849        let expected = JmapError::anchor_not_found();
850
851        let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
852
853        assert_eq!(
854            wire,
855            serde_json::to_value(&expected).expect("JmapError must serialize"),
856            "backend anchorNotFound must pass through handle_query unchanged"
857        );
858    }
859
860    /// Oracle: the [`server_fail_from_backend_drops_display_text`] contract
861    /// still holds on the `/query` path. An internal backend error is not
862    /// one of the RFC 8620 §5.5 method errors and MUST surface as the
863    /// redacted `serverFail`, never echoing the error's `Display`.
864    #[tokio::test]
865    async fn handle_query_redacts_backend_internal_error() {
866        const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
867
868        let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
869
870        assert_eq!(wire["type"], "serverFail");
871        assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
872        assert!(
873            !wire.to_string().contains(CANARY),
874            "internal backend error Display must not reach the wire; got {wire}"
875        );
876    }
877
878    // -----------------------------------------------------------------
879    // handle_get: maxObjectsInGet cap (bd:JMAP-yt1w.31)
880    // -----------------------------------------------------------------
881
882    /// Minimal `GetObject` used only to instantiate [`handle_get`].
883    #[derive(serde::Serialize, serde::Deserialize)]
884    struct GetProbe;
885
886    impl JmapObject for GetProbe {
887        const TYPE_NAME: &'static str = "GetProbe";
888        type Property = ();
889    }
890
891    impl GetObject for GetProbe {}
892
893    /// Backend whose account exists, holds no objects (every requested id
894    /// is `notFound`), and keeps the default [`JmapBackend`] caps.
895    struct GetProbeBackend;
896
897    impl JmapBackend for GetProbeBackend {
898        type Error = LeakyQueryError;
899        type CallerCtx = ();
900
901        async fn account_exists(
902            &self,
903            _caller: &(),
904            _account_id: &Id,
905        ) -> Result<bool, Self::Error> {
906            Ok(true)
907        }
908
909        async fn get_objects<O: GetObject + Send + Sync>(
910            &self,
911            _caller: &(),
912            _account_id: &Id,
913            ids: Option<&[Id]>,
914            _properties: Option<&[String]>,
915        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
916            Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
917        }
918
919        async fn get_state<O: JmapObject + Send + Sync>(
920            &self,
921            _caller: &(),
922            _account_id: &Id,
923        ) -> Result<State, Self::Error> {
924            Ok(State::from("s0"))
925        }
926
927        async fn get_changes<O: JmapObject + Send + Sync>(
928            &self,
929            _caller: &(),
930            _account_id: &Id,
931            _params: ChangesParams<'_>,
932        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
933            unreachable!("only /get is exercised")
934        }
935
936        async fn query_objects<O: QueryObject + Send + Sync>(
937            &self,
938            _caller: &(),
939            _account_id: &Id,
940            _params: QueryParams<'_, O>,
941        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
942            unreachable!("only /get is exercised")
943        }
944
945        async fn query_changes<O: QueryObject + Send + Sync>(
946            &self,
947            _caller: &(),
948            _account_id: &Id,
949            _params: QueryChangesParams<'_, O>,
950        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
951            unreachable!("only /get is exercised")
952        }
953    }
954
955    /// Oracle: RFC 8620 §5.1 "/get" (/home/mark/PROJECT/IETF/specs/rfc8620.txt
956    /// L1660-1665):
957    ///
958    /// > The following additional error may be returned instead of the "Foo/
959    /// > get" response:
960    /// >
961    /// > "requestTooLarge": The number of ids requested by the client exceeds
962    /// > the maximum number the server is willing to process in a single
963    /// > method call.
964    ///
965    /// The backend keeps the default cap, mirroring the `max_objects_in_set`
966    /// default of 500, which is RFC 8620 §2 (L546-547) "maxObjectsInGet ...
967    /// Suggested minimum: 500." Requesting 501 ids MUST yield the
968    /// method-level `requestTooLarge` instead of a `GetProbe/get` response.
969    #[tokio::test]
970    async fn handle_get_over_max_objects_is_request_too_large() {
971        let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
972        let args = json!({ "accountId": "a1", "ids": ids });
973
974        match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
975            Ok(HandlerOutput { primary: resp, .. }) => panic!(
976                "501 ids exceed the maxObjectsInGet cap, but handle_get \
977                 returned a response with {} notFound ids instead of \
978                 requestTooLarge",
979                resp["notFound"].as_array().map_or(0, Vec::len)
980            ),
981            Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
982        }
983    }
984
985    /// Oracle: RFC 8620 §5.1 "/get" (/home/mark/PROJECT/IETF/specs/rfc8620.txt
986    /// L1596-1601): "ids: "Id[]|null" The ids of the Foo objects to return.
987    /// If null, then *all* records of the data type are returned, if this is
988    /// supported for that data type and the number of records does not
989    /// exceed the "maxObjectsInGet" limit."
990    ///
991    /// `requestTooLarge` counts "the number of ids requested by the client"
992    /// (L1663), and a null `ids` requests none, so the generic handler MUST
993    /// NOT reject it as over the cap; the record-count bound for fetch-all
994    /// belongs to the backend, which knows how many records exist.
995    #[tokio::test]
996    async fn handle_get_null_ids_is_not_counted_against_cap() {
997        let args = json!({ "accountId": "a1", "ids": null });
998
999        let HandlerOutput { primary: resp, .. } =
1000            handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
1001                .await
1002                .expect("null ids must not be rejected by the maxObjectsInGet cap");
1003        assert_eq!(resp["list"], json!([]));
1004    }
1005
1006    /// Backend whose account exists and which returns one fixed object for
1007    /// every `/get`, ignoring `properties` (which
1008    /// [`JmapBackend::get_objects`] permits).
1009    struct FullObjectBackend;
1010
1011    impl JmapBackend for FullObjectBackend {
1012        type Error = LeakyQueryError;
1013        type CallerCtx = ();
1014
1015        async fn account_exists(
1016            &self,
1017            _caller: &(),
1018            _account_id: &Id,
1019        ) -> Result<bool, Self::Error> {
1020            Ok(true)
1021        }
1022
1023        async fn get_objects<O: GetObject + Send + Sync>(
1024            &self,
1025            _caller: &(),
1026            _account_id: &Id,
1027            _ids: Option<&[Id]>,
1028            _properties: Option<&[String]>,
1029        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1030            let obj = serde_json::from_value(json!({
1031                "id": "o1", "name": "n", "color": "c"
1032            }))
1033            .expect("fixture must deserialize");
1034            Ok((vec![obj], vec![]))
1035        }
1036
1037        async fn get_state<O: JmapObject + Send + Sync>(
1038            &self,
1039            _caller: &(),
1040            _account_id: &Id,
1041        ) -> Result<State, Self::Error> {
1042            Ok(State::from("s0"))
1043        }
1044
1045        async fn get_changes<O: JmapObject + Send + Sync>(
1046            &self,
1047            _caller: &(),
1048            _account_id: &Id,
1049            _params: ChangesParams<'_>,
1050        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1051            unreachable!("only /get is exercised")
1052        }
1053
1054        async fn query_objects<O: QueryObject + Send + Sync>(
1055            &self,
1056            _caller: &(),
1057            _account_id: &Id,
1058            _params: QueryParams<'_, O>,
1059        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1060            unreachable!("only /get is exercised")
1061        }
1062
1063        async fn query_changes<O: QueryObject + Send + Sync>(
1064            &self,
1065            _caller: &(),
1066            _account_id: &Id,
1067            _params: QueryChangesParams<'_, O>,
1068        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1069            unreachable!("only /get is exercised")
1070        }
1071    }
1072
1073    /// `GetObject` with three properties, built by [`FullObjectBackend`].
1074    #[derive(serde::Serialize, serde::Deserialize)]
1075    struct Swatch {
1076        id: String,
1077        name: String,
1078        color: String,
1079    }
1080
1081    impl JmapObject for Swatch {
1082        const TYPE_NAME: &'static str = "Swatch";
1083        type Property = ();
1084    }
1085
1086    impl GetObject for Swatch {}
1087
1088    /// Oracle: RFC 8620 §5.1 (/home/mark/PROJECT/IETF/specs/rfc8620.txt
1089    /// L1605-1609): "If supplied, only the properties listed in the array
1090    /// are returned for each Foo object. ... The id property of the object
1091    /// is *always* returned, even if not explicitly requested." The backend
1092    /// returns `id`, `name` and `color` regardless; asking for `name` alone
1093    /// MUST yield exactly `id` and `name`.
1094    #[tokio::test]
1095    async fn handle_get_returns_only_requested_properties_and_id() {
1096        let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": ["name"] });
1097
1098        let HandlerOutput { primary: resp, .. } =
1099            handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1100                .await
1101                .expect("valid /get must succeed");
1102        assert_eq!(resp["list"], json!([{ "id": "o1", "name": "n" }]));
1103    }
1104
1105    /// Oracle: RFC 8620 §5.1 (rfc8620.txt L1607-1608): "If null, all
1106    /// properties of the object are returned."
1107    #[tokio::test]
1108    async fn handle_get_null_properties_returns_all() {
1109        let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": null });
1110
1111        let HandlerOutput { primary: resp, .. } =
1112            handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1113                .await
1114                .expect("valid /get must succeed");
1115        assert_eq!(
1116            resp["list"],
1117            json!([{ "id": "o1", "name": "n", "color": "c" }])
1118        );
1119    }
1120
1121    /// Backend whose account exists and which records the
1122    /// [`QueryParams`] / [`QueryChangesParams`] it receives as JSON, so a
1123    /// test can compare them with the request's wire arguments.
1124    #[derive(Default)]
1125    struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
1126
1127    impl RecordingQueryBackend {
1128        fn take(&self) -> Value {
1129            self.0
1130                .lock()
1131                .unwrap()
1132                .take()
1133                .expect("backend query method was not called")
1134        }
1135    }
1136
1137    impl JmapBackend for RecordingQueryBackend {
1138        type Error = LeakyQueryError;
1139        type CallerCtx = ();
1140
1141        async fn account_exists(
1142            &self,
1143            _caller: &(),
1144            _account_id: &Id,
1145        ) -> Result<bool, Self::Error> {
1146            Ok(true)
1147        }
1148
1149        async fn get_objects<O: GetObject + Send + Sync>(
1150            &self,
1151            _caller: &(),
1152            _account_id: &Id,
1153            _ids: Option<&[Id]>,
1154            _properties: Option<&[String]>,
1155        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1156            unreachable!("only queries are exercised")
1157        }
1158
1159        async fn get_state<O: JmapObject + Send + Sync>(
1160            &self,
1161            _caller: &(),
1162            _account_id: &Id,
1163        ) -> Result<State, Self::Error> {
1164            unreachable!("only queries are exercised")
1165        }
1166
1167        async fn get_changes<O: JmapObject + Send + Sync>(
1168            &self,
1169            _caller: &(),
1170            _account_id: &Id,
1171            _params: ChangesParams<'_>,
1172        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1173            unreachable!("only queries are exercised")
1174        }
1175
1176        async fn query_objects<O: QueryObject + Send + Sync>(
1177            &self,
1178            _caller: &(),
1179            _account_id: &Id,
1180            params: QueryParams<'_, O>,
1181        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1182            *self.0.lock().unwrap() = Some(json!({
1183                "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1184                "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1185                "limit": params.limit,
1186                "position": params.position,
1187                "anchor": params.anchor,
1188                "anchorOffset": params.anchor_offset,
1189            }));
1190            Ok(crate::backend::QueryResult::new(
1191                vec![],
1192                0,
1193                None,
1194                State::from("q0"),
1195                false,
1196            ))
1197        }
1198
1199        async fn query_changes<O: QueryObject + Send + Sync>(
1200            &self,
1201            _caller: &(),
1202            _account_id: &Id,
1203            params: QueryChangesParams<'_, O>,
1204        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1205            *self.0.lock().unwrap() = Some(json!({
1206                "sinceQueryState": params.since_query_state,
1207                "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1208                "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1209                "maxChanges": params.max_changes,
1210                "upToId": params.up_to_id,
1211                "collapseThreads": params.collapse_threads,
1212            }));
1213            Ok(QueryChangesResult::new(
1214                params.since_query_state.clone(),
1215                State::from("q2"),
1216                None,
1217                vec![],
1218                vec![],
1219            ))
1220        }
1221    }
1222
1223    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2368-2501) defines the
1224    /// `/query` arguments `filter`, `sort`, `position`, `anchor`,
1225    /// `anchorOffset` and `limit`. Every one the client sends MUST reach
1226    /// the backend unchanged in [`QueryParams`].
1227    #[tokio::test]
1228    async fn handle_query_passes_every_argument_to_backend() {
1229        let backend = RecordingQueryBackend::default();
1230        let args = json!({
1231            "accountId": "a1",
1232            "filter": {"text": "hello"},
1233            "sort": [{"property": "receivedAt", "isAscending": false}],
1234            "position": 3,
1235            "anchor": "m7",
1236            "anchorOffset": -2,
1237            "limit": 25,
1238        });
1239        handle_query::<QueryProbe, _>(&backend, &(), args)
1240            .await
1241            .expect("query must succeed");
1242        assert_eq!(
1243            backend.take(),
1244            json!({
1245                "filter": {"text": "hello"},
1246                "sort": [{"property": "receivedAt", "isAscending": false}],
1247                "limit": 25,
1248                "position": 3,
1249                "anchor": "m7",
1250                "anchorOffset": -2,
1251            })
1252        );
1253    }
1254
1255    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2471, L2493): `position` and
1256    /// `anchorOffset` default to 0; `filter`, `sort`, `anchor` and `limit`
1257    /// are optional. A request with none of them reaches the backend as
1258    /// those defaults.
1259    #[tokio::test]
1260    async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
1261        let backend = RecordingQueryBackend::default();
1262        handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
1263            .await
1264            .expect("query must succeed");
1265        assert_eq!(
1266            backend.take(),
1267            json!({
1268                "filter": null,
1269                "sort": null,
1270                "limit": null,
1271                "position": 0,
1272                "anchor": null,
1273                "anchorOffset": 0,
1274            })
1275        );
1276    }
1277
1278    /// Oracle: RFC 8620 §5.6 (rfc8620.txt L2649-2669) defines the
1279    /// `/queryChanges` arguments `filter`, `sort`, `sinceQueryState`,
1280    /// `maxChanges` and `upToId`; each MUST reach the backend unchanged in
1281    /// [`QueryChangesParams`]. `collapseThreads` exists only on
1282    /// `Email/queryChanges` (RFC 8621 §4.5), so the generic handler passes
1283    /// `false`.
1284    #[tokio::test]
1285    async fn handle_query_changes_passes_every_argument_to_backend() {
1286        let backend = RecordingQueryBackend::default();
1287        let args = json!({
1288            "accountId": "a1",
1289            "filter": {"text": "hello"},
1290            "sort": [{"property": "receivedAt"}],
1291            "sinceQueryState": "q1",
1292            "maxChanges": 10,
1293            "upToId": "m9",
1294        });
1295        handle_query_changes::<QueryProbe, _>(&backend, &(), args)
1296            .await
1297            .expect("queryChanges must succeed");
1298        assert_eq!(
1299            backend.take(),
1300            json!({
1301                "sinceQueryState": "q1",
1302                "filter": {"text": "hello"},
1303                "sort": [{"property": "receivedAt"}],
1304                "maxChanges": 10,
1305                "upToId": "m9",
1306                "collapseThreads": false,
1307            })
1308        );
1309    }
1310
1311    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2368) types `filter` as
1312    /// "FilterOperator|FilterCondition|null", and both are objects
1313    /// (L2391 "A *FilterCondition* is an "object""); §5.6 (L2649) reuses
1314    /// that type. A non-object value is therefore "of the wrong type"
1315    /// (L1189 `invalidArguments`), not a filter that is "syntactically
1316    /// valid, but the server cannot process it" (L2626
1317    /// `unsupportedFilter`). The backend is never consulted.
1318    #[tokio::test]
1319    async fn non_object_filter_is_invalid_arguments() {
1320        for filter in [json!(42), json!("text"), json!(true), json!([])] {
1321            let backend = RecordingQueryBackend::default();
1322            let err = handle_query::<QueryProbe, _>(
1323                &backend,
1324                &(),
1325                json!({"accountId": "a1", "filter": filter}),
1326            )
1327            .await
1328            .expect_err("non-object filter must be rejected");
1329            assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1330
1331            let err = handle_query_changes::<QueryProbe, _>(
1332                &backend,
1333                &(),
1334                json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
1335            )
1336            .await
1337            .expect_err("non-object filter must be rejected");
1338            assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1339            assert!(backend.0.lock().unwrap().is_none(), "{filter}");
1340        }
1341    }
1342
1343    // -----------------------------------------------------------------
1344    // handle_changes / handle_query_changes / handle_query: response
1345    // shape and error branches (bd:JMAP-w8fu.17)
1346    // -----------------------------------------------------------------
1347
1348    /// What [`CannedBackend`] returns from its `/changes`, `/query` and
1349    /// `/queryChanges` methods.
1350    #[derive(Clone, Copy)]
1351    enum Canned {
1352        /// The fixed hand-built result of each method.
1353        Ok,
1354        /// [`BackendChangesError::CannotCalculate`].
1355        CannotCalculate,
1356        /// [`BackendChangesError::TooManyChanges`] with this limit.
1357        TooManyChanges(u64),
1358        /// [`BackendChangesError::Other`] whose `Display` is this canary.
1359        Internal(&'static str),
1360    }
1361
1362    impl Canned {
1363        fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
1364            match self {
1365                Canned::Ok => unreachable!("Canned::Ok is not an error"),
1366                Canned::CannotCalculate => BackendChangesError::CannotCalculate,
1367                Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
1368                Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
1369            }
1370        }
1371    }
1372
1373    /// Backend that answers `/changes`, `/query` and `/queryChanges` with
1374    /// fixed hand-built values (or the configured error), and reports
1375    /// whether the account exists as configured.
1376    struct CannedBackend {
1377        account_exists: bool,
1378        outcome: Canned,
1379    }
1380
1381    const CANNED_OK: CannedBackend = CannedBackend {
1382        account_exists: true,
1383        outcome: Canned::Ok,
1384    };
1385
1386    impl JmapBackend for CannedBackend {
1387        type Error = LeakyQueryError;
1388        type CallerCtx = ();
1389
1390        async fn account_exists(
1391            &self,
1392            _caller: &(),
1393            _account_id: &Id,
1394        ) -> Result<bool, Self::Error> {
1395            Ok(self.account_exists)
1396        }
1397
1398        async fn get_objects<O: GetObject + Send + Sync>(
1399            &self,
1400            _caller: &(),
1401            _account_id: &Id,
1402            _ids: Option<&[Id]>,
1403            _properties: Option<&[String]>,
1404        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1405            unreachable!("/get is not exercised")
1406        }
1407
1408        async fn get_state<O: JmapObject + Send + Sync>(
1409            &self,
1410            _caller: &(),
1411            _account_id: &Id,
1412        ) -> Result<State, Self::Error> {
1413            unreachable!("/get is not exercised")
1414        }
1415
1416        async fn get_changes<O: JmapObject + Send + Sync>(
1417            &self,
1418            _caller: &(),
1419            _account_id: &Id,
1420            _params: ChangesParams<'_>,
1421        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1422            match self.outcome {
1423                Canned::Ok => Ok(ChangesResult::new(
1424                    vec![Id::from("c1")],
1425                    vec![Id::from("u1")],
1426                    vec![Id::from("d1")],
1427                    true,
1428                    State::from("s2"),
1429                )),
1430                other => Err(other.changes_error()),
1431            }
1432        }
1433
1434        async fn query_objects<O: QueryObject + Send + Sync>(
1435            &self,
1436            _caller: &(),
1437            _account_id: &Id,
1438            _params: QueryParams<'_, O>,
1439        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1440            Ok(crate::backend::QueryResult::new(
1441                vec![Id::from("m1")],
1442                0,
1443                Some(7),
1444                State::from("q1"),
1445                true,
1446            ))
1447        }
1448
1449        async fn query_changes<O: QueryObject + Send + Sync>(
1450            &self,
1451            _caller: &(),
1452            _account_id: &Id,
1453            params: QueryChangesParams<'_, O>,
1454        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1455            match self.outcome {
1456                Canned::Ok => Ok(QueryChangesResult::new(
1457                    params.since_query_state.clone(),
1458                    State::from("q2"),
1459                    Some(7),
1460                    vec![Id::from("r1")],
1461                    vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
1462                )),
1463                other => Err(other.changes_error()),
1464            }
1465        }
1466    }
1467
1468    /// Oracle: RFC 8620 §5.2 (rfc8620.txt L1708-1739) lists the
1469    /// `/changes` response arguments `accountId`, `oldState` ("the
1470    /// "sinceState" argument echoed back"), `newState`, `hasMoreChanges`,
1471    /// `updatedProperties`, `created`, `updated` and `destroyed`. The
1472    /// expected JSON is hand-written from that list and the backend's
1473    /// fixed result.
1474    #[tokio::test]
1475    async fn handle_changes_response_matches_rfc_shape() {
1476        let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1477            &CANNED_OK,
1478            &(),
1479            json!({"accountId": "a1", "sinceState": "s1"}),
1480            &[],
1481        )
1482        .await
1483        .expect("/changes must succeed");
1484        assert_eq!(
1485            resp,
1486            json!({
1487                "accountId": "a1",
1488                "oldState": "s1",
1489                "newState": "s2",
1490                "hasMoreChanges": true,
1491                "updatedProperties": null,
1492                "created": ["c1"],
1493                "updated": ["u1"],
1494                "destroyed": ["d1"],
1495            })
1496        );
1497    }
1498
1499    // -----------------------------------------------------------------
1500    // handle_changes: draft-ietf-jmap-metadata-05 §3, §3.3 (bd:JMAP-cbhv)
1501    // -----------------------------------------------------------------
1502
1503    const CORE: &str = "urn:ietf:params:jmap:core";
1504    const METADATA: &str = "urn:ietf:params:jmap:metadata";
1505
1506    /// `/changes`-only backend: records the [`ChangesParams`] it was
1507    /// given and answers with the configured `updated` list and
1508    /// `updated_properties`.
1509    struct MetadataChangesBackend {
1510        updated: Vec<Id>,
1511        updated_properties: Option<Vec<String>>,
1512        seen_ignore: std::sync::Mutex<Option<bool>>,
1513    }
1514
1515    impl MetadataChangesBackend {
1516        fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
1517            Self {
1518                updated: updated.iter().map(|u| Id::from(*u)).collect(),
1519                updated_properties: updated_properties
1520                    .map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
1521                seen_ignore: std::sync::Mutex::new(None),
1522            }
1523        }
1524    }
1525
1526    impl JmapBackend for MetadataChangesBackend {
1527        type Error = LeakyQueryError;
1528        type CallerCtx = ();
1529
1530        async fn account_exists(
1531            &self,
1532            _caller: &(),
1533            _account_id: &Id,
1534        ) -> Result<bool, Self::Error> {
1535            Ok(true)
1536        }
1537
1538        async fn get_objects<O: GetObject + Send + Sync>(
1539            &self,
1540            _caller: &(),
1541            _account_id: &Id,
1542            _ids: Option<&[Id]>,
1543            _properties: Option<&[String]>,
1544        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1545            unreachable!("only get_changes is exercised")
1546        }
1547
1548        async fn get_state<O: JmapObject + Send + Sync>(
1549            &self,
1550            _caller: &(),
1551            _account_id: &Id,
1552        ) -> Result<State, Self::Error> {
1553            unreachable!("only get_changes is exercised")
1554        }
1555
1556        async fn get_changes<O: JmapObject + Send + Sync>(
1557            &self,
1558            _caller: &(),
1559            _account_id: &Id,
1560            params: ChangesParams<'_>,
1561        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1562            *self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
1563            Ok(ChangesResult::new(
1564                Vec::new(),
1565                self.updated.clone(),
1566                Vec::new(),
1567                false,
1568                State::from("s2"),
1569            )
1570            .with_updated_properties(self.updated_properties.clone()))
1571        }
1572
1573        async fn query_objects<O: QueryObject + Send + Sync>(
1574            &self,
1575            _caller: &(),
1576            _account_id: &Id,
1577            _params: QueryParams<'_, O>,
1578        ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1579            unreachable!("only get_changes is exercised")
1580        }
1581
1582        async fn query_changes<O: QueryObject + Send + Sync>(
1583            &self,
1584            _caller: &(),
1585            _account_id: &Id,
1586            _params: QueryChangesParams<'_, O>,
1587        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1588            unreachable!("only get_changes is exercised")
1589        }
1590    }
1591
1592    /// Run `QueryProbe/changes` with `extra` merged into the arguments and
1593    /// return the `ignoreMetadataOnlyChanges` value the backend received.
1594    async fn ignore_seen(using: &[&str], extra: Value) -> bool {
1595        let backend = MetadataChangesBackend::new(&["u1"], None);
1596        let mut args = json!({"accountId": "a1", "sinceState": "s1"});
1597        if let Value::Object(extra) = extra {
1598            args.as_object_mut().unwrap().extend(extra);
1599        }
1600        let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
1601        handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
1602            .await
1603            .expect("/changes must succeed");
1604        backend
1605            .seen_ignore
1606            .lock()
1607            .unwrap()
1608            .expect("backend must be called")
1609    }
1610
1611    /// Oracle: draft-ietf-jmap-metadata-05 §3 (draft-ietf-jmap-metadata-05.txt
1612    /// L509-514): "These extensions apply to requests whose using includes
1613    /// urn:ietf:params:jmap:metadata. For other requests, ... Foo/changes
1614    /// MUST behave as if ignoreMetadataOnlyChanges were true." The
1615    /// argument is not defined for such requests, so a malformed value is
1616    /// not an error.
1617    #[tokio::test]
1618    async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
1619        assert!(ignore_seen(&[CORE], json!({})).await);
1620        assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
1621        assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
1622        assert!(ignore_seen(&[], json!({})).await);
1623    }
1624
1625    /// Oracle: draft-ietf-jmap-metadata-05 §3.3 (L650):
1626    /// "*ignoreMetadataOnlyChanges*: Boolean (default: false)".
1627    #[tokio::test]
1628    async fn changes_with_metadata_capability_passes_ignore_argument() {
1629        assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
1630        assert!(
1631            !ignore_seen(
1632                &[CORE, METADATA],
1633                json!({"ignoreMetadataOnlyChanges": null})
1634            )
1635            .await
1636        );
1637        assert!(
1638            !ignore_seen(
1639                &[CORE, METADATA],
1640                json!({"ignoreMetadataOnlyChanges": false})
1641            )
1642            .await
1643        );
1644        assert!(
1645            ignore_seen(
1646                &[CORE, METADATA],
1647                json!({"ignoreMetadataOnlyChanges": true})
1648            )
1649            .await
1650        );
1651    }
1652
1653    /// Oracle: draft-ietf-jmap-metadata-05 §3.3 (L650) types the argument
1654    /// "Boolean"; RFC 8620 §3.6.2 "invalidArguments: One of the arguments
1655    /// is of the wrong type".
1656    #[tokio::test]
1657    async fn changes_rejects_non_boolean_ignore_argument() {
1658        let backend = MetadataChangesBackend::new(&["u1"], None);
1659        let err = handle_changes::<QueryProbe, _>(
1660            &backend,
1661            &(),
1662            json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
1663            &[CORE.to_owned(), METADATA.to_owned()],
1664        )
1665        .await
1666        .expect_err("a string ignoreMetadataOnlyChanges must fail");
1667        assert_eq!(err.error_type.to_string(), "invalidArguments");
1668        assert!(
1669            backend.seen_ignore.lock().unwrap().is_none(),
1670            "backend must not be called"
1671        );
1672    }
1673
1674    /// Oracle: draft-ietf-jmap-metadata-05 §3.3 (L668-695): when "the only
1675    /// properties that have changed on every id in the updated array ...
1676    /// are metadata and/or privateMetadata, this argument MUST be set to a
1677    /// list containing only those property names (e.g., ["metadata"]"; and
1678    /// the §3.3 example response (L1381) carries
1679    /// `"updatedProperties": ["metadata"]`.
1680    #[tokio::test]
1681    async fn changes_reports_backend_updated_properties() {
1682        let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
1683        let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1684            &backend,
1685            &(),
1686            json!({"accountId": "a1", "sinceState": "s1"}),
1687            &[CORE.to_owned(), METADATA.to_owned()],
1688        )
1689        .await
1690        .expect("/changes must succeed");
1691        assert_eq!(
1692            resp,
1693            json!({
1694                "accountId": "a1",
1695                "oldState": "s1",
1696                "newState": "s2",
1697                "hasMoreChanges": false,
1698                "updatedProperties": ["metadata"],
1699                "created": [],
1700                "updated": ["u1"],
1701                "destroyed": [],
1702            })
1703        );
1704    }
1705
1706    /// Oracle: draft-ietf-jmap-metadata-05 §3.3 (L690-691): updatedProperties
1707    /// "is always present, and is null when updated is empty".
1708    #[tokio::test]
1709    async fn changes_updated_properties_null_when_updated_empty() {
1710        let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
1711        let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1712            &backend,
1713            &(),
1714            json!({"accountId": "a1", "sinceState": "s1"}),
1715            &[CORE.to_owned(), METADATA.to_owned()],
1716        )
1717        .await
1718        .expect("/changes must succeed");
1719        assert_eq!(resp["updatedProperties"], Value::Null);
1720        assert!(
1721            resp.as_object().unwrap().contains_key("updatedProperties"),
1722            "updatedProperties must be present"
1723        );
1724    }
1725
1726    /// Oracle: RFC 8620 §5.6 (rfc8620.txt L2699-2730) lists the
1727    /// `/queryChanges` response arguments; `oldQueryState` is "the
1728    /// "sinceQueryState" argument echoed back", each `added` entry is an
1729    /// AddedItem `{id, index}`, and `total` "MUST be omitted if the
1730    /// "calculateTotal" request argument is not true" (L2714).
1731    #[tokio::test]
1732    async fn handle_query_changes_response_matches_rfc_shape() {
1733        let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1734            &CANNED_OK,
1735            &(),
1736            json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
1737        )
1738        .await
1739        .expect("/queryChanges must succeed");
1740        assert_eq!(
1741            resp,
1742            json!({
1743                "accountId": "a1",
1744                "oldQueryState": "q1",
1745                "newQueryState": "q2",
1746                "total": 7,
1747                "removed": ["r1"],
1748                "added": [{"id": "n1", "index": 0}],
1749            })
1750        );
1751
1752        let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1753            &CANNED_OK,
1754            &(),
1755            json!({"accountId": "a1", "sinceQueryState": "q1"}),
1756        )
1757        .await
1758        .expect("/queryChanges must succeed");
1759        assert!(
1760            resp.get("total").is_none(),
1761            "total must be omitted without calculateTotal; got {resp}"
1762        );
1763    }
1764
1765    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2604-2608): `total` is "only if
1766    /// requested" and "MUST be omitted if the "calculateTotal" request
1767    /// argument is not true", even when the backend computed one.
1768    #[tokio::test]
1769    async fn handle_query_total_only_when_requested() {
1770        for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
1771            let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
1772                &CANNED_OK,
1773                &(),
1774                json!({"accountId": "a1", "calculateTotal": calculate_total}),
1775            )
1776            .await
1777            .expect("/query must succeed");
1778            assert_eq!(resp.get("total").cloned(), expected, "{resp}");
1779        }
1780    }
1781
1782    /// Oracle: RFC 8620 §5.2 (rfc8620.txt L1687) and §5.6 (L2657) type
1783    /// `sinceState` / `sinceQueryState` as a required "String"; a missing
1784    /// or non-string value is "of the wrong type" (L1189
1785    /// `invalidArguments`).
1786    #[tokio::test]
1787    async fn missing_or_non_string_since_state_is_invalid_arguments() {
1788        for since in [None, Some(json!(42))] {
1789            let mut args = json!({"accountId": "a1"});
1790            if let Some(v) = &since {
1791                args["sinceState"] = v.clone();
1792            }
1793            let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
1794                .await
1795                .expect_err("/changes without a string sinceState must fail");
1796            assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1797
1798            let mut args = json!({"accountId": "a1"});
1799            if let Some(v) = &since {
1800                args["sinceQueryState"] = v.clone();
1801            }
1802            let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
1803                .await
1804                .expect_err("/queryChanges without a string sinceQueryState must fail");
1805            assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1806        }
1807    }
1808
1809    /// Oracle: RFC 8620 §5.6 (rfc8620.txt L2669) types `upToId` as
1810    /// "Id|null"; any other JSON type is `invalidArguments` (L1189).
1811    #[tokio::test]
1812    async fn non_string_up_to_id_is_invalid_arguments() {
1813        for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
1814            let err = handle_query_changes::<QueryProbe, _>(
1815                &CANNED_OK,
1816                &(),
1817                json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
1818            )
1819            .await
1820            .expect_err("non-Id upToId must be rejected");
1821            assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
1822        }
1823    }
1824
1825    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2501-2508): `limit` is
1826    /// "UnsignedInt|null" and "If a negative value is given, the call MUST
1827    /// be rejected with an "invalidArguments" error."
1828    #[tokio::test]
1829    async fn handle_query_negative_limit_is_invalid_arguments() {
1830        let backend = RecordingQueryBackend::default();
1831        let err =
1832            handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
1833                .await
1834                .expect_err("negative limit must be rejected");
1835        assert_eq!(err.error_type.to_string(), "invalidArguments");
1836        assert!(
1837            backend.0.lock().unwrap().is_none(),
1838            "backend must not be consulted"
1839        );
1840    }
1841
1842    /// Oracle: RFC 8620 §5.5 (rfc8620.txt L2471-2480): `position` is "Int"
1843    /// and "If a negative value is given, it is an offset from the end of
1844    /// the list", resolved against "the total number of results", which
1845    /// only the backend knows. The generic handler MUST pass the negative
1846    /// value through rather than reject or clamp it.
1847    #[tokio::test]
1848    async fn handle_query_negative_position_reaches_backend() {
1849        let backend = RecordingQueryBackend::default();
1850        handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
1851            .await
1852            .expect("negative position is valid");
1853        assert_eq!(backend.take()["position"], json!(-5));
1854    }
1855
1856    /// Oracle: RFC 8620 §5.2 (rfc8620.txt L1822-1829) lists only
1857    /// `cannotCalculateChanges` as an error returned "instead of the
1858    /// Foo/changes response", and L1766-1768: a server over `maxChanges`
1859    /// that "is unable to calculate an intermediate state ... MUST return a
1860    /// "cannotCalculateChanges" error response instead"; §5.6 (L2806-2813)
1861    /// adds `tooManyChanges` for Foo/queryChanges only. An internal backend
1862    /// failure is neither and MUST surface as the redacted `serverFail`
1863    /// (the [`server_fail_from_backend_drops_display_text`] contract).
1864    #[tokio::test]
1865    async fn changes_backend_errors_map_to_rfc_errors() {
1866        const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
1867        for (outcome, changes_type, query_changes_type) in [
1868            (
1869                Canned::CannotCalculate,
1870                "cannotCalculateChanges",
1871                "cannotCalculateChanges",
1872            ),
1873            (
1874                Canned::TooManyChanges(10),
1875                "cannotCalculateChanges",
1876                "tooManyChanges",
1877            ),
1878            (Canned::Internal(CANARY), "serverFail", "serverFail"),
1879        ] {
1880            let backend = CannedBackend {
1881                account_exists: true,
1882                outcome,
1883            };
1884            let changes = handle_changes::<QueryProbe, _>(
1885                &backend,
1886                &(),
1887                json!({"accountId": "a1", "sinceState": "s1"}),
1888                &[],
1889            )
1890            .await;
1891            let query_changes = handle_query_changes::<QueryProbe, _>(
1892                &backend,
1893                &(),
1894                json!({"accountId": "a1", "sinceQueryState": "q1"}),
1895            )
1896            .await;
1897            for (result, expected_type) in
1898                [(changes, changes_type), (query_changes, query_changes_type)]
1899            {
1900                let err = result.expect_err("backend error must fail the call");
1901                let wire = serde_json::to_value(&err).expect("JmapError must serialize");
1902                assert_eq!(wire["type"], expected_type, "{wire}");
1903                assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
1904            }
1905        }
1906    }
1907
1908    /// Oracle: RFC 8620 §3.6.2 (rfc8620.txt L1202-1203): "accountNotFound":
1909    /// The accountId does not correspond to a valid account.
1910    #[tokio::test]
1911    async fn unknown_account_is_account_not_found() {
1912        let backend = CannedBackend {
1913            account_exists: false,
1914            outcome: Canned::Ok,
1915        };
1916        let results = [
1917            handle_changes::<QueryProbe, _>(
1918                &backend,
1919                &(),
1920                json!({"accountId": "nope", "sinceState": "s1"}),
1921                &[],
1922            )
1923            .await,
1924            handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
1925            handle_query_changes::<QueryProbe, _>(
1926                &backend,
1927                &(),
1928                json!({"accountId": "nope", "sinceQueryState": "q1"}),
1929            )
1930            .await,
1931        ];
1932        for result in results {
1933            let err = result.expect_err("unknown account must fail");
1934            assert_eq!(err.error_type.to_string(), "accountNotFound");
1935        }
1936    }
1937
1938    /// RFC 8620 §5.5 types `limit` as "UnsignedInt|null" and `position` as
1939    /// "Int"; wrong types are `invalidArguments` (§3.6.2). The description
1940    /// names only the JSON type and never echoes the client value
1941    /// (§3.6.1: "unstructured English text"; bd JMAP-zegc).
1942    #[tokio::test]
1943    async fn handle_query_does_not_echo_wrongly_typed_value() {
1944        for name in ["limit", "position"] {
1945            let backend = RecordingQueryBackend::default();
1946            let mut args = json!({ "accountId": "a1" });
1947            args[name] = json!({ "note": "CANARY-zegc" });
1948            let err = handle_query::<QueryProbe, _>(&backend, &(), args)
1949                .await
1950                .expect_err("wrongly typed argument must be rejected");
1951            assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
1952            let desc = err.description.as_deref().unwrap_or_default();
1953            assert!(desc.starts_with(name), "{desc}");
1954            assert!(desc.contains("got object"), "{desc}");
1955            assert!(!desc.contains("CANARY"), "{desc}");
1956        }
1957    }
1958}