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