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