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