Skip to main content

jmap_server/
helpers.rs

1//! Shared helper utilities for JMAP method handlers.
2
3use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet};
5
6pub use jmap_types::json_type_name;
7use jmap_types::{GetObject, Id, JmapError, SetObject, UTCDate};
8
9use crate::backend::{JmapBackend, SetError, SetErrorType};
10use crate::handlers::server_fail_value_from_backend;
11use serde_json::{Map, Value};
12
13/// Serialize any [`serde::Serialize`] type to a [`serde_json::Value`],
14/// mapping serialization errors to [`JmapError::server_fail`].
15///
16/// Used by every `*-server` handler to project a typed domain object
17/// (e.g. `Email`, `Mailbox`, `Chat`) into the wire-format `list` /
18/// `created` payload.
19pub fn serialize_value<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
20    serde_json::to_value(val).map_err(|e| JmapError::server_fail(e.to_string()))
21}
22
23/// Convert a slice of [`Id`]s to a JSON `notFound` value.
24///
25/// RFC 8620 §5.1 specifies `notFound` as `Id[]` — always an array, never
26/// `null`. Returns an empty array when all requested ids were found.
27///
28/// Equivalent to `serde_json::to_value(ids)` but threads through
29/// `Value::Array` directly so the call site is infallible (bd:JMAP-wlip.28).
30pub fn not_found_json(ids: &[Id]) -> Value {
31    Value::Array(
32        ids.iter()
33            .map(|id| Value::String(id.as_ref().to_owned()))
34            .collect(),
35    )
36}
37
38/// Extract an optional, deserializable argument from a method-arguments
39/// envelope (bd:JMAP-wlip.32).
40///
41/// Looks up `name` in `args`, removing it. The result is:
42///
43/// - `Ok(None)` if the key is absent OR is present with `Value::Null`
44///   (RFC 8620 §3.3 treats absent and explicit-null the same for
45///   optional fields).
46/// - `Ok(Some(value))` if the key is present and the value
47///   deserializes successfully into `T`.
48/// - `Err(invalid_arguments_with(name))` if the value is present but
49///   fails to deserialize. The error message is built by the caller-
50///   supplied `invalid_arguments_with` so the resulting `JmapError`
51///   carries a domain-specific description ("ids must be an Id
52///   array", "filter must be a Filter object", etc.).
53///
54/// Collapses six near-identical
55/// `match args.remove(...).unwrap_or(Value::Null) { Value::Null => None,
56/// v => Some(serde_json::from_value(v)...) }` blocks in `handlers.rs`
57/// into one-liners.
58///
59/// # Interaction with `ResultReference` resolution (bd:JMAP-jfia.15)
60///
61/// [`crate::parse::resolve_args`] replaces a `#key` with the value
62/// produced by walking the JSON Pointer path against a prior
63/// response. RFC 6901 §4 makes no distinction between "key absent"
64/// and "key present with `null`", so the resolved value CAN be
65/// `Value::Null`. This function then treats that resolved-null
66/// identically to "key was not sent". The behaviour is
67/// RFC-compliant — both are "optional argument not provided" — but
68/// the asymmetry between an explicit `null` argument and a
69/// `#key`-resolved `null` argument may surprise a handler author
70/// who expects "I asked for the value via a ResultReference, so it
71/// must have been there". If a handler needs to distinguish
72/// resolved-null from unsent, it has to read the raw `args` map
73/// before calling this helper.
74pub fn optional_arg<T>(
75    args: &mut Map<String, Value>,
76    name: &str,
77    invalid_arguments_with: impl FnOnce() -> JmapError,
78) -> Result<Option<T>, JmapError>
79where
80    T: serde::de::DeserializeOwned,
81{
82    match args.remove(name).unwrap_or(Value::Null) {
83        Value::Null => Ok(None),
84        v => Ok(Some(
85            serde_json::from_value(v).map_err(|_| invalid_arguments_with())?,
86        )),
87    }
88}
89
90/// Remove and decode the optional `filter` argument of a hand-written
91/// `/query` or `/queryChanges` handler (RFC 8620 §5.5).
92///
93/// Absent or `null` yields `None`. A value that is not a JSON object is
94/// not a filter at all and yields `invalidArguments`. An object that does
95/// not decode as `T` yields `unsupportedFilter` ("The "filter" is
96/// syntactically valid, but the server cannot process it") with the serde
97/// message as its description. With `deny_unknown_fields` on the filter
98/// types, that covers an unknown or misspelt condition property at any
99/// depth and an operator tree sent to an object whose filter is a bare
100/// condition.
101pub fn filter_arg<T>(args: &mut Map<String, Value>) -> Result<Option<T>, JmapError>
102where
103    T: serde::de::DeserializeOwned,
104{
105    match args.remove("filter").unwrap_or(Value::Null) {
106        Value::Null => Ok(None),
107        v @ Value::Object(_) => serde_json::from_value(v).map(Some).map_err(|e| {
108            let mut err = JmapError::unsupported_filter();
109            err.description = Some(format!("filter: {e}"));
110            err
111        }),
112        v => Err(JmapError::invalid_arguments(format!(
113            "filter: expected an object, got {}",
114            json_type_name(&v)
115        ))),
116    }
117}
118
119/// Read an optional boolean argument from a method-arguments envelope without
120/// removing it (bd:JMAP-ic0j.39).
121///
122/// Returns `default` if `key` is absent, if the value is not a boolean, or if
123/// the value is `Value::Null`. This is the canonical workspace helper for
124/// JMAP's "permissive parsing" convention on optional boolean controls
125/// (RFC 8620 §3.6.1 — unknown / non-typed values coerce to the spec default).
126///
127/// Use [`take_bool_arg`] if the caller wants to consume the entry as part of
128/// a "walk the args map removing as we go" pattern.
129///
130/// Collapses ~50 near-identical
131/// `args.get(K).and_then(|v| v.as_bool()).unwrap_or(default)` blocks across
132/// the extension-server family into single-line calls.
133pub fn bool_arg(args: &Map<String, Value>, key: &str, default: bool) -> bool {
134    args.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
135}
136
137/// Read an optional boolean argument from a method-arguments envelope,
138/// removing it from the map (bd:JMAP-ic0j.39).
139///
140/// Returns `default` if `key` is absent, if the value is not a boolean, or if
141/// the value is `Value::Null`. Mirrors the semantics of [`bool_arg`] but
142/// consumes the entry from `args`. Matches the canonical mail-server
143/// "remove-as-we-go" parsing pattern.
144pub fn take_bool_arg(args: &mut Map<String, Value>, key: &str, default: bool) -> bool {
145    args.remove(key)
146        .and_then(|v| v.as_bool())
147        .unwrap_or(default)
148}
149
150/// Extract `accountId` from a JMAP method arguments envelope and return both
151/// the extracted [`Id`] and the remaining argument map.
152///
153/// The caller passes the full `args: Value` from the method invocation by
154/// value; this function destructures it once, so handlers do not have to
155/// repeat the `let Value::Object(mut args) = args else { ... }` pattern after
156/// every call.
157///
158/// # Errors
159///
160/// Returns `invalidArguments` with:
161///
162/// - `"arguments must be an object containing accountId"` when `args` is
163///   not a JSON object.
164/// - `"accountId is required"` when the field is missing or not a string.
165/// - `"accountId is not a valid Id: <reason>"` when the field is a string
166///   but does not satisfy the RFC 8620 §1.2 Id grammar
167///   (`Id::new_validated`). Catches empty strings, strings longer than
168///   255 bytes, and strings containing characters outside the SAFE-CHAR
169///   set (`%x21 / %x23-7E` — visible ASCII excluding `"`).
170///   bd:JMAP-wlip.5 closed the previous silent-pass-through behaviour
171///   where a malformed accountId reached the backend's `account_exists`
172///   call and surfaced as either `notFound` or a storage-layer parse
173///   error, depending on the backend.
174pub fn extract_account_id(args: Value) -> Result<(Id, Map<String, Value>), JmapError> {
175    let Value::Object(mut args) = args else {
176        return Err(JmapError::invalid_arguments(
177            "arguments must be an object containing accountId",
178        ));
179    };
180    // Remove (not get) the accountId entry so the returned args map no
181    // longer carries it (bd:JMAP-jfia.9). This matches optional_arg's
182    // remove-and-consume semantics and prevents downstream handlers
183    // from re-parsing the validated id or seeing it as an unexpected
184    // residual key.
185    let raw = args
186        .remove("accountId")
187        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
188    let s = raw
189        .as_str()
190        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
191    let id = Id::new_validated(s)
192        .map_err(|e| JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}")))?;
193    Ok((id, args))
194}
195
196/// Parse the optional `maxChanges` argument of `/changes` and
197/// `/queryChanges`. RFC 8620 §5.2: "If supplied by the client, the value
198/// MUST be a positive integer greater than 0. If a value outside of this
199/// range is given, the server MUST reject the call with an
200/// "invalidArguments" error." §5.6 gives no range of its own, so the same
201/// rule applies to `/queryChanges`.
202///
203/// Pass the raw argument as taken from the args map (`args.get(..)` or
204/// `args.remove(..).as_ref()`). Absent or `null` yields `Ok(None)`.
205///
206/// # Errors
207///
208/// Returns `invalidArguments` (`"maxChanges must be a positive integer"`)
209/// for `0`, negative numbers, non-integers, and non-number values.
210pub fn parse_max_changes(value: Option<&Value>) -> Result<Option<u64>, JmapError> {
211    match value {
212        None | Some(Value::Null) => Ok(None),
213        Some(v) => {
214            v.as_u64().filter(|&n| n > 0).map(Some).ok_or_else(|| {
215                JmapError::invalid_arguments("maxChanges must be a positive integer")
216            })
217        }
218    }
219}
220
221/// Return the current UTC instant as an [`UTCDate`] (RFC 3339,
222/// millisecond precision, format `YYYY-MM-DDTHH:MM:SS.mmmZ`, or
223/// `YYYY-MM-DDTHH:MM:SSZ` when the milliseconds are zero because
224/// RFC 8620 §1.4 says the "time-secfrac" "MUST always be omitted if
225/// zero"). For years `0000..=9999` the value passes
226/// [`UTCDate::new_validated`].
227///
228/// Uses `std::time::SystemTime` so no external dependency is needed.
229///
230/// Returns a typed [`UTCDate`] rather than a `String` (bd:JMAP-wlip.20)
231/// so callers do not need to wrap the result in
232/// `UTCDate::from(now_utc_string().as_str())`. The function name is
233/// retained for back-compat across the workspace's many call sites.
234///
235/// Pre-epoch handling: `SystemTime::now().duration_since(UNIX_EPOCH)`
236/// fails on clocks drifted before the epoch. The function uses
237/// `Err::duration()` to recover the magnitude and negates the seconds
238/// before formatting; the result is a correct RFC 3339 timestamp
239/// anywhere from the BCE proleptic Gregorian range up to
240/// `1970-01-01T00:00:00Z`. The rem_euclid / div_euclid math at
241/// the format step handles arbitrarily-large negative offsets, not
242/// only sub-day drifts. Pre-epoch correctness is best-effort —
243/// `SystemTime` is non-monotonic and the JMAP spec does not require
244/// pre-epoch timestamps. (bd:JMAP-wlip.11 corrected the previous
245/// docstring's incorrect "1969-12-31T… through 1970-01-01T00:00:00Z"
246/// range claim.)
247///
248/// Clock-overflow handling: on a corrupted clock (system clock
249/// reporting a Duration whose `as_secs()` exceeds `i64::MAX`,
250/// `civil_from_days` reporting a year outside `i32`, or any other
251/// `SystemTime` failure mode), this function **panics**. The
252/// previous sentinel-string behaviour (`UTCDate::from("clock-out-of-range")`)
253/// was an idiom-grade defect (bd:JMAP-jfia.30): the sentinel was not a
254/// valid wire-format timestamp, had no in-band signal to distinguish
255/// it from a real value, and could silently propagate into JSON
256/// responses, audit logs, and database rows.
257///
258/// Callers that need to handle clock failure without panicking MUST
259/// use [`now_utc_string_checked`], which returns `Option<UTCDate>`.
260/// Long-running daemons, schedulers, and persistence layers SHOULD
261/// prefer the checked variant; one-shot tools and request handlers
262/// MAY accept the panic since clock corruption is unrecoverable and
263/// the dispatcher's `task::spawn` isolation already converts the
264/// panic into a `serverFail` invocation rather than crashing the
265/// process.
266///
267/// # Panics
268///
269/// Panics if `SystemTime::now()` cannot be expressed as an RFC 3339
270/// timestamp — the same conditions under which
271/// [`now_utc_string_checked`] returns `None`.
272pub fn now_utc_string() -> UTCDate {
273    now_utc_string_checked().expect("system clock returned an out-of-range value (bd:JMAP-jfia.30)")
274}
275
276/// Return the current UTC instant as an [`UTCDate`] in the same
277/// format as [`now_utc_string`], or `None` if the system clock cannot be expressed as an RFC 3339
278/// timestamp.
279///
280/// Added in bd:JMAP-jfia.30 to replace the previous sentinel-string
281/// failure mode of [`now_utc_string`] with a typed `Option` shape.
282/// Callers that want to react to a clock fault (audit-log
283/// timestamps, last-seen markers, retention sweeps) SHOULD use this
284/// variant; callers for whom a panic at the first sign of clock
285/// corruption is acceptable MAY use [`now_utc_string`] directly.
286///
287/// Returns `None` when:
288/// - `SystemTime::now().duration_since(UNIX_EPOCH).as_secs()`
289///   exceeds `i64::MAX` (only reachable on a corrupted clock —
290///   approx ±292 billion years from epoch).
291/// - The negation of a pre-epoch duration overflows `i64`
292///   (unreachable on a `try_from`-validated input but checked
293///   defensively).
294/// - `civil_from_days` reports a year outside `i32`
295///   (bd:JMAP-jfia.2 — between the i32-year boundary and the
296///   i64::MAX-secs cap).
297///
298/// # Why `Option<UTCDate>` and not `Result<UTCDate, ClockError>` (bd:JMAP-jfia.38)
299///
300/// The three failure modes are all "corrupted clock" — each one is
301/// physically unreachable on a sane host (years 5.7M-to-292B,
302/// `try_from`-impossible negation, `i32`-overflowing year). A caller
303/// that wants to branch on which physical mechanism fired would be
304/// branching on states that don't happen. The shapes the workspace
305/// uses elsewhere for typed-variant-per-mode (`SetError`,
306/// `BackendChangesError`, `BackendSetError`, `MergePatchError`) all
307/// carry failure modes that DO occur in normal operation —
308/// `notFound`, `tooManyChanges`, `invalidPatch`, `depthExceeded`.
309/// The clock-corruption modes are different in kind. Erasing the
310/// discriminator here trades a hypothetical observability win for a
311/// cleaner contract: "the clock is unusable for RFC 3339, abandon
312/// timestamping." A future need for per-mode telemetry can be added
313/// non-breakingly as a parallel helper (e.g. `now_utc_string_diagnose
314/// -> Result<UTCDate, ClockError>`) without disturbing this shape.
315pub fn now_utc_string_checked() -> Option<UTCDate> {
316    use std::time::SystemTime;
317
318    let (secs, millis) = signed_seconds_since_epoch(SystemTime::now())?;
319    utc_date_from_epoch_millis(secs, millis)
320}
321
322/// Format `secs` seconds plus `millis` milliseconds since the Unix epoch
323/// in the [`now_utc_string`] format, or `None` if the year does not fit
324/// in `i32`.
325fn utc_date_from_epoch_millis(secs: i64, millis: u32) -> Option<UTCDate> {
326    let time_of_day = secs.rem_euclid(86400);
327    let (h, m, s) = (
328        time_of_day / 3600,
329        time_of_day % 3600 / 60,
330        time_of_day % 60,
331    );
332    let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;
333
334    // RFC 8620 §1.4: a zero time-secfrac MUST be omitted.
335    let frac = if millis == 0 {
336        String::new()
337    } else {
338        format!(".{millis:03}")
339    };
340    Some(UTCDate::from(format!(
341        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}{frac}Z"
342    )))
343}
344
345/// Convert a [`SystemTime`] into `(signed_seconds_since_epoch, millis)`,
346/// returning `None` when the system clock cannot be expressed as an
347/// `i64` second count.
348///
349/// Extracted from [`now_utc_string_checked`] in bd:JMAP-jfia.11 to
350/// flatten the previous three-level nested match
351/// (`duration_since` → `try_from` → `checked_neg`) into one
352/// linear function the reader can scan top-to-bottom. The
353/// `.checked_neg()` branch is unreachable on a `try_from`-validated
354/// input (its output is `[0, i64::MAX]` so negation cannot underflow)
355/// but is kept for defence in depth — the failure path stays total.
356pub(crate) fn signed_seconds_since_epoch(now: std::time::SystemTime) -> Option<(i64, u32)> {
357    use std::time::UNIX_EPOCH;
358    match now.duration_since(UNIX_EPOCH) {
359        Ok(d) => {
360            let s = i64::try_from(d.as_secs()).ok()?;
361            Some((s, d.subsec_millis()))
362        }
363        Err(e) => {
364            // Pre-epoch clock: the instant is -d. Floor it to whole
365            // milliseconds (as truncation does post-epoch), then split
366            // it so `millis` counts forward from the floored second:
367            // -1.2 s is (-2, 800), not (-1, 200) (bd:JMAP-yt1w.46).
368            let d = e.duration();
369            let s = i64::try_from(d.as_secs()).ok()?;
370            match d.subsec_nanos() {
371                0 => Some((s.checked_neg()?, 0)),
372                nanos => Some((
373                    s.checked_add(1)?.checked_neg()?,
374                    (1_000_000_000 - nanos) / 1_000_000,
375                )),
376            }
377        }
378    }
379}
380
381/// Format `secs` seconds since the Unix epoch as a seconds-precision
382/// [`UTCDate`] (`YYYY-MM-DDTHH:MM:SSZ`, RFC 8620 §1.4), or `None` if the
383/// year falls outside `0000..=9999`, which that four-digit form cannot
384/// express.
385///
386/// This is the inverse of [`UTCDate::to_epoch_seconds`], which truncates
387/// the milliseconds that [`now_utc_string`] may add.
388pub fn utc_date_from_epoch_seconds(secs: i64) -> Option<UTCDate> {
389    let time_of_day = secs.rem_euclid(86400);
390    let (h, m, s) = (
391        time_of_day / 3600,
392        time_of_day % 3600 / 60,
393        time_of_day % 60,
394    );
395    let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;
396    if !(0..=9999).contains(&year) {
397        return None;
398    }
399    Some(UTCDate::from(format!(
400        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}Z"
401    )))
402}
403
404/// Convert a count of days since the Unix epoch (1970-01-01) to a proleptic
405/// Gregorian (year, month, day) triple, or `None` if the resulting year
406/// does not fit in `i32`.
407///
408/// Algorithm by Howard Hinnant (public domain):
409/// <https://howardhinnant.github.io/date_algorithms.html>
410///
411/// The year-narrowing cast is fallible because the algorithm's intermediate
412/// `y` value is bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a subset
413/// of which fits in `i32` (~±2.1e9 years). For a sane `SystemTime`-derived
414/// input we stay well inside `i32::MIN..=i32::MAX`, but the outer
415/// `now_utc_string` only rejects `u64` seconds exceeding `i64::MAX`
416/// (bd:JMAP-wlip.27 sentinel) — inputs between the i32-year boundary
417/// (~5.7e6 years from epoch) and that sentinel reach this function and
418/// previously panicked the dispatcher worker (bd:JMAP-jfia.2). Returning
419/// `None` lets the caller fall through to its own sentinel rather than
420/// taking down the task.
421///
422/// Month and day cannot fail: the algorithm's modular structure pins them
423/// to `[1, 12]` and `[1, 31]` respectively, narrow casts handled with
424/// `try_from(...).expect(...)` documenting the invariant.
425fn civil_from_days(z: i64) -> Option<(i32, u8, u8)> {
426    let z = z + 719_468;
427    let era: i64 = if z >= 0 { z } else { z - 146_096 } / 146_097;
428    let doe = z - era * 146_097; // [0, 146096]
429    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
430    let y = yoe + era * 400;
431    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
432    let mp = (5 * doy + 2) / 153; // [0, 11]
433    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
434    let mo = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
435    let yr = if mo <= 2 { y + 1 } else { y };
436    Some((
437        i32::try_from(yr).ok()?,
438        u8::try_from(mo).expect("month bounded by algorithm to [1, 12]"),
439        u8::try_from(d).expect("day bounded by algorithm to [1, 31]"),
440    ))
441}
442
443/// Maximum recursion depth for [`json_merge_patch`] application.
444///
445/// Beyond this depth [`json_merge_patch`] returns
446/// [`MergePatchError::DepthExceeded`] without applying any further levels.
447/// Mitigates stack DoS from adversarial `PatchObject` values
448/// (bd:JMAP-sc1b.97). 32 levels comfortably exceeds any legitimate JMAP
449/// `/set update` shape — the deepest standard JMAP `/set update` shape
450/// (Email with nested `bodyStructure`) tops out around 6 levels, so the
451/// cap fires only on adversarial input.
452///
453/// Crate-private (bd:JMAP-wlip.4): consumers see the cap-exceeded
454/// behaviour via [`MergePatchError::DepthExceeded`], not by reading the
455/// constant directly. The crate reserves the right to tighten the
456/// value (e.g. 32 → 16) without a major-version bump because the
457/// contract is "the function may return DepthExceeded", not "the cap
458/// is exactly N".
459pub(crate) const MAX_MERGE_PATCH_DEPTH: usize = 32;
460
461/// Error returned by [`json_merge_patch`] when a patch cannot be applied.
462///
463/// Marked `#[non_exhaustive]` so future RFC 7396 failure modes (e.g. a
464/// size cap in addition to the depth cap) can be added without an API
465/// break.
466#[non_exhaustive]
467#[derive(Debug, Clone, PartialEq, Eq)]
468pub enum MergePatchError {
469    /// The patch nests deeper than the crate's `MAX_MERGE_PATCH_DEPTH`
470    /// DoS-guard cap.
471    ///
472    /// Callers SHOULD map this to
473    /// [`SetError`](crate::SetError) with
474    /// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch)
475    /// and MUST discard any partially-mutated `target` rather than
476    /// persisting it — see the contract on [`json_merge_patch`].
477    ///
478    /// # Why no `reached` / `max` payload (bd:JMAP-jfia.39)
479    ///
480    /// The variant is intentionally unit-shaped. The cap value is
481    /// available in the `Display` impl (which interpolates
482    /// `MAX_MERGE_PATCH_DEPTH`) for log-line and user-message use.
483    /// A typed payload `{ reached: usize, max: usize }` was
484    /// considered and rejected for now because (a) no current
485    /// consumer in the workspace destructures the reached depth or
486    /// the cap programmatically — all 6 call sites map to
487    /// `SetErrorType::InvalidPatch` with a generic description; and
488    /// (b) changing a unit variant to a struct variant is a breaking
489    /// pattern-match change even on a `#[non_exhaustive]` enum (the
490    /// existing `if let Err(MergePatchError::DepthExceeded)` pattern
491    /// would stop compiling). If a future consumer needs
492    /// programmatic access to the depth, the additive evolution is
493    /// to add a new variant alongside (e.g.
494    /// `DepthExceededDetail { reached: usize, max: usize }`) and
495    /// emit the new variant from `json_merge_patch`. The unit
496    /// variant would then become unreachable but remain valid
497    /// pattern syntax for any pinned-version consumer.
498    DepthExceeded,
499}
500
501impl std::fmt::Display for MergePatchError {
502    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
503        match self {
504            Self::DepthExceeded => write!(
505                f,
506                "merge patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels"
507            ),
508        }
509    }
510}
511
512impl std::error::Error for MergePatchError {}
513
514/// Apply a JSON Merge Patch (RFC 7396) to `target` in-place.
515///
516/// Used by every `*-server` backend's `update_object` implementation
517/// to merge a sparse `/set update` patch into the stored serialized
518/// object. Extracted from per-crate copies in bd:JMAP-sc1b.103 — keep
519/// edits here so all five reference backends stay byte-identical.
520///
521/// # Errors
522///
523/// Returns [`MergePatchError::DepthExceeded`] when the patch nests
524/// deeper than the crate's internal `MAX_MERGE_PATCH_DEPTH` DoS-guard
525/// cap (added in bd:JMAP-sc1b.97, made non-silent in bd:JMAP-wlip.1).
526/// The exact value is intentionally not exposed; consumers see the
527/// behaviour via the typed error rather than reading the constant.
528/// Below the cap the behaviour is exactly RFC 7396 and the call always
529/// returns `Ok(())`.
530///
531/// # Partial-mutation contract
532///
533/// On `Err(DepthExceeded)`, `target` may have been mutated up to the
534/// level where the cap fired — RFC 7396 merging is applied recursively
535/// in place and the function does not roll back on error. Callers MUST
536/// discard `target` rather than persist it. The standard pattern in
537/// every `*-server` `update_object` impl is to operate on a `.clone()`
538/// of the stored value and only `insert(...)` it back on `Ok(())`; that
539/// pattern is naturally safe because the stored value is left untouched
540/// on error.
541pub fn json_merge_patch(target: &mut Value, patch: Value) -> Result<(), MergePatchError> {
542    json_merge_patch_inner(target, patch, 0)
543}
544
545fn json_merge_patch_inner(
546    target: &mut Value,
547    patch: Value,
548    depth: usize,
549) -> Result<(), MergePatchError> {
550    if depth > MAX_MERGE_PATCH_DEPTH {
551        return Err(MergePatchError::DepthExceeded);
552    }
553    match patch {
554        Value::Object(patch_map) => {
555            // Per RFC 7396 §2: "If the target value is not a JSON object,
556            // the resulting value will be the merge patch." We therefore
557            // reset a non-Object target to an empty Object before merging
558            // — this is reachable when a Patch creates a nested field that
559            // is absent from the target (the parent recursion frame inserted
560            // Value::Null as a placeholder).
561            if !target.is_object() {
562                *target = Value::Object(Map::new());
563            }
564            let target_map = target
565                .as_object_mut()
566                .expect("target was just set to Value::Object above");
567            for (key, patch_val) in patch_map {
568                if patch_val.is_null() {
569                    target_map.remove(&key);
570                } else {
571                    let entry = target_map.entry(key).or_insert(Value::Null);
572                    json_merge_patch_inner(entry, patch_val, depth + 1)?;
573                }
574            }
575        }
576        other => *target = other,
577    }
578    Ok(())
579}
580
581/// Error returned by [`apply_jmap_patch`] and [`apply_patch_object`] when
582/// a PatchObject cannot be applied.
583///
584/// Every variant is an RFC 8620 §5.3 violation for which "the update
585/// MUST be rejected with an "invalidPatch" error". Callers SHOULD map
586/// any variant to [`SetError`](crate::SetError) with
587/// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch);
588/// the `Display` form is suitable as its description.
589///
590/// Marked `#[non_exhaustive]` so further §5.3 checks can be added
591/// without an API break.
592#[non_exhaustive]
593#[derive(Debug, Clone, PartialEq, Eq)]
594pub enum PatchPathError {
595    /// A part before the last does not exist on the patched object.
596    ParentMissing,
597    /// A part before the last names an array, so the pointer would
598    /// reference inside an array.
599    InsideArray,
600    /// A part before the last names a value that is neither an object nor
601    /// an array (string, number, boolean or null), which has no members.
602    ParentNotObject,
603    /// A `~` in the path is not followed by `0` or `1`, so the path is
604    /// not a valid RFC 6901 JSON Pointer.
605    InvalidEscape,
606    /// The pointer of one patch is a prefix of the pointer of another in
607    /// the same PatchObject (e.g. `"alerts/1/offset"` and `"alerts"`).
608    PrefixConflict,
609    /// The path's segment count plus the value's object/array nesting
610    /// exceeds the crate's `MAX_MERGE_PATCH_DEPTH` DoS-guard cap.
611    ///
612    /// Not an RFC 8620 §5.3 rule: it is this crate's server limit
613    /// (RFC 8620 §3.6.1 lets a server reject requests that exceed its
614    /// limits), so repeated path patches cannot grow a stored value's
615    /// depth without bound. It is still reported as invalidPatch.
616    DepthExceeded,
617    /// A part before the last is a Binary value inside a `metadata` or
618    /// `privateMetadata` namespace value: draft-ietf-jmap-metadata-05
619    /// §3.2, "a path that traverses an array or a Binary value (Section
620    /// 2.1.1) is rejected with an "invalidPatch" SetError".
621    InsideBinary,
622}
623
624impl std::fmt::Display for PatchPathError {
625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626        match self {
627            Self::ParentMissing => f.write_str("patch path parent does not exist"),
628            Self::InsideArray => f.write_str("patch path references inside an array"),
629            Self::ParentNotObject => f.write_str("patch path parent is not an object"),
630            Self::InvalidEscape => f.write_str("patch path has a '~' not followed by '0' or '1'"),
631            Self::PrefixConflict => {
632                f.write_str("patch has a path that is a prefix of another path")
633            }
634            Self::DepthExceeded => {
635                write!(f, "patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels")
636            }
637            Self::InsideBinary => {
638                f.write_str("patch path references inside a metadata Binary value")
639            }
640        }
641    }
642}
643
644impl std::error::Error for PatchPathError {}
645
646/// Apply one RFC 8620 §5.3 PatchObject entry (`path` → `value`) to
647/// `target` in-place.
648///
649/// `path` is a PatchObject key: an RFC 6901 JSON Pointer with the
650/// implicit leading `/` omitted (e.g. `"mailboxIds/abc123"`). Each
651/// `/`-separated reference token is decoded per RFC 6901 §4 (`~1` → `/`,
652/// then `~0` → `~`). Every token before the last must name an existing
653/// object member; the last token names the member to set. A `null`
654/// `value` removes that member (a no-op when it is absent); any other
655/// value inserts or replaces it.
656///
657/// Extracted from per-crate copies in bd:JMAP-j6ab. Extension servers
658/// MUST call this rather than reimplement it.
659///
660/// Empty tokens are legal: RFC 6901 §3 allows a zero-length
661/// `reference-token`, and its §5 example evaluates `"/"` to the member
662/// named `""`. The RFC 8620 §5.3 "null sets the property default" rule
663/// is type-specific and left to the caller. The rule that no two pointers
664/// in one PatchObject may be prefixes of each other is checked by
665/// [`apply_patch_object`].
666///
667/// # Errors
668///
669/// Returns [`PatchPathError`] when a part before the last does not exist
670/// ([`ParentMissing`](PatchPathError::ParentMissing)), is an array
671/// ([`InsideArray`](PatchPathError::InsideArray)) or is another
672/// non-object value ([`ParentNotObject`](PatchPathError::ParentNotObject))
673/// or is a Binary value below a `metadata/<namespace>` or
674/// `privateMetadata/<namespace>` prefix
675/// ([`InsideBinary`](PatchPathError::InsideBinary); an object with
676/// `"@type": "Binary"`, draft-ietf-jmap-metadata-05 §2.1.1),
677/// when `path` contains an invalid escape
678/// ([`InvalidEscape`](PatchPathError::InvalidEscape)), or when the
679/// number of `/`-separated segments in `path` plus the object/array
680/// nesting of `value` (a scalar nests 0 levels) exceeds the crate's
681/// `MAX_MERGE_PATCH_DEPTH` DoS-guard cap
682/// ([`DepthExceeded`](PatchPathError::DepthExceeded)).
683///
684/// # Mutation contract
685///
686/// A single call is all-or-nothing: on `Err`, `target` is unchanged.
687/// A PatchObject has several entries, and an error on a later entry
688/// does not undo earlier ones, so callers applying a whole PatchObject
689/// MUST use [`apply_patch_object`].
690pub fn apply_jmap_patch(
691    target: &mut Map<String, Value>,
692    path: &str,
693    value: Value,
694) -> Result<(), PatchPathError> {
695    let segments = path.split('/').count();
696    if segments > MAX_MERGE_PATCH_DEPTH
697        || nests_deeper_than(&value, MAX_MERGE_PATCH_DEPTH - segments)
698    {
699        return Err(PatchPathError::DepthExceeded);
700    }
701    let (parents, leaf) = match path.rsplit_once('/') {
702        Some((parents, leaf)) => (Some(parents), leaf),
703        None => (None, path),
704    };
705    let leaf = decode_pointer_token(leaf)?;
706    let in_metadata = matches!(path.split('/').next(), Some("metadata" | "privateMetadata"));
707    let mut parent = target;
708    for (i, token) in parents.into_iter().flat_map(|p| p.split('/')).enumerate() {
709        parent = match parent.get_mut(decode_pointer_token(token)?.as_ref()) {
710            // Token 0 is the property and token 1 the namespace; a Binary
711            // is an object within the namespace value.
712            Some(Value::Object(map))
713                if in_metadata
714                    && i >= 2
715                    && map.get("@type").and_then(Value::as_str) == Some("Binary") =>
716            {
717                return Err(PatchPathError::InsideBinary);
718            }
719            Some(Value::Object(map)) => map,
720            Some(Value::Array(_)) => return Err(PatchPathError::InsideArray),
721            Some(_) => return Err(PatchPathError::ParentNotObject),
722            None => return Err(PatchPathError::ParentMissing),
723        };
724    }
725    if value.is_null() {
726        parent.remove(leaf.as_ref());
727    } else {
728        parent.insert(leaf.into_owned(), value);
729    }
730    Ok(())
731}
732
733/// Check the RFC 8620 §5.3 PatchObject errors that `patch` alone
734/// determines, without the object it applies to.
735///
736/// A server whose spec orders these before other checks calls this
737/// first; draft-ietf-jmap-metadata-05 §3.2 says "Patch errors that can
738/// be determined from the request alone (for example, two paths where
739/// one is a prefix of the other) MUST be reported with "invalidPatch"
740/// before rule 1 is evaluated". [`apply_patch_object`] runs the same
741/// check, so calling both is redundant but harmless.
742///
743/// # Errors
744///
745/// Returns [`PatchPathError::InvalidEscape`] for a key with a `~` not
746/// followed by `0` or `1`, [`PatchPathError::DepthExceeded`] for an
747/// entry over the `MAX_MERGE_PATCH_DEPTH` cap, and
748/// [`PatchPathError::PrefixConflict`] when the decoded pointer of one key
749/// is a whole-segment prefix of another (`"alerts"` and
750/// `"alerts/1/offset"` conflict; `"alert"` and `"alerts/x"` do not).
751pub fn check_patch_paths(patch: &Map<String, Value>) -> Result<(), PatchPathError> {
752    let mut pointers = patch
753        .iter()
754        .map(|(k, v)| {
755            let segments = k
756                .split('/')
757                .map(decode_pointer_token)
758                .collect::<Result<Vec<_>, _>>()?;
759            if segments.len() > MAX_MERGE_PATCH_DEPTH
760                || nests_deeper_than(v, MAX_MERGE_PATCH_DEPTH - segments.len())
761            {
762                return Err(PatchPathError::DepthExceeded);
763            }
764            Ok(segments)
765        })
766        .collect::<Result<Vec<_>, _>>()?;
767    // Sorted, a pointer that prefixes any other also prefixes its successor.
768    pointers.sort_unstable();
769    if pointers.windows(2).any(|w| w[1].starts_with(&w[0])) {
770        return Err(PatchPathError::PrefixConflict);
771    }
772    Ok(())
773}
774
775/// Apply a whole RFC 8620 §5.3 PatchObject to `target`.
776///
777/// Each entry is applied with [`apply_jmap_patch`]. The value at each
778/// pointer is set as given: a top-level key such as `"name"` replaces that
779/// property wholesale, with no nested merge of object values (RFC 8620
780/// §5.3: "The value to set for this property").
781///
782/// # Errors
783///
784/// Returns any error [`check_patch_paths`] returns for `patch`, and
785/// otherwise any error [`apply_jmap_patch`] returns for an entry.
786///
787/// # Mutation contract
788///
789/// All-or-nothing: on `Err`, `target` is unchanged.
790pub fn apply_patch_object(
791    target: &mut Map<String, Value>,
792    patch: &Map<String, Value>,
793) -> Result<(), PatchPathError> {
794    check_patch_paths(patch)?;
795    let mut patched = target.clone();
796    for (path, value) in patch {
797        apply_jmap_patch(&mut patched, path, value.clone())?;
798    }
799    *target = patched;
800    Ok(())
801}
802
803/// Whether `value` nests objects or arrays more than `limit` levels deep
804/// (a scalar nests 0 levels). Recursion is bounded by `limit`, not by the
805/// input.
806fn nests_deeper_than(value: &Value, limit: usize) -> bool {
807    match value {
808        Value::Object(map) => limit == 0 || map.values().any(|v| nests_deeper_than(v, limit - 1)),
809        Value::Array(items) => limit == 0 || items.iter().any(|v| nests_deeper_than(v, limit - 1)),
810        _ => false,
811    }
812}
813
814/// Decode one RFC 6901 reference token: `~1` → `/`, then `~0` → `~`
815/// (RFC 6901 §4 order, so `~01` becomes `~1`, not `/`).
816pub(crate) fn decode_pointer_token(token: &str) -> Result<Cow<'_, str>, PatchPathError> {
817    if !token.contains('~') {
818        return Ok(Cow::Borrowed(token));
819    }
820    let escapes_valid = token
821        .match_indices('~')
822        .all(|(i, _)| matches!(token.as_bytes().get(i + 1), Some(b'0' | b'1')));
823    if !escapes_valid {
824        return Err(PatchPathError::InvalidEscape);
825    }
826    Ok(Cow::Owned(token.replace("~1", "/").replace("~0", "~")))
827}
828
829/// Resolve a request-side `position` argument (RFC 8620 §5.5) into a
830/// 0-based start index suitable for slicing the full ordered result
831/// list (bd:JMAP-qz9v.48).
832///
833/// `position` is the signed offset from the `/query` request. The
834/// foundation handler at [`handle_query`](crate::handle_query) parses it
835/// via [`serde_json::Value::as_i64`], so the value reaching the
836/// backend is any `i64` (including `i64::MIN`). Non-negative values
837/// are absolute offsets from the start of the result list; negative
838/// values are end-relative offsets per RFC 8620 §5.5 ("`-1` represents
839/// the last entry, `-2` the second to last, and so on").
840///
841/// Returns a `usize` clamped to `[0, total]`. The clamp at the high
842/// end matches the slice-safety property: `all_ids[start..]` is
843/// guaranteed not to panic regardless of the input `position`.
844///
845/// # Edge cases this helper exists to centralize
846///
847/// 1. `position == 0` → `0`.
848/// 2. `position > total` → `total` (yields an empty page, matching
849///    the RFC's silent-clamp semantics — `/query` does not error on
850///    out-of-range positions).
851/// 3. `position == i64::MIN` → handled via [`i64::saturating_neg`],
852///    which returns `i64::MAX` rather than overflowing. The resulting
853///    `usize::MAX`-magnitude offset is then absorbed by
854///    [`usize::saturating_sub`].
855/// 4. `position` exceeding `usize::MAX` on a 32-bit target (`i64`
856///    values above `2^32 - 1`) → clamped to `total` rather than
857///    truncated. The previous workspace idiom (`position as usize`)
858///    silently wrapped the high bits on 32-bit, returning a small
859///    `start` index that did not match the caller's intent.
860///
861/// # Why this lives in the foundation
862///
863/// The pattern is identical across every extension server's `/query`
864/// backend impl. Centralizing it eliminates the per-crate
865/// `(position as usize)` / `(position.saturating_neg() as usize)`
866/// idiom that clippy::pedantic flags as `cast_possible_truncation` +
867/// `cast_sign_loss`, and prevents future siblings from re-introducing
868/// the strictly-worse `(-position) as usize` variant (which panics on
869/// `i64::MIN` in debug builds and wraps in release).
870///
871/// # Example
872///
873/// ```
874/// use jmap_server::resolve_query_offset;
875///
876/// // Absolute offset.
877/// assert_eq!(resolve_query_offset(0, 100), 0);
878/// assert_eq!(resolve_query_offset(25, 100), 25);
879///
880/// // End-relative offset.
881/// assert_eq!(resolve_query_offset(-1, 100), 99);
882/// assert_eq!(resolve_query_offset(-100, 100), 0);
883///
884/// // Out-of-range clamps to total.
885/// assert_eq!(resolve_query_offset(1_000, 100), 100);
886/// assert_eq!(resolve_query_offset(-1_000, 100), 0);
887///
888/// // i64::MIN does not overflow.
889/// assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
890/// ```
891#[must_use]
892pub fn resolve_query_offset(position: i64, total: usize) -> usize {
893    if position >= 0 {
894        // `i64 >= 0` → fits in `u64`. `usize::try_from` returns the
895        // value on 64-bit targets and `Err` on 32-bit targets only
896        // when the magnitude exceeds `usize::MAX`; saturating to
897        // `usize::MAX` is then clamped to `total` by `.min`.
898        usize::try_from(position).unwrap_or(usize::MAX).min(total)
899    } else {
900        // `saturating_neg` maps `i64::MIN` to `i64::MAX` instead of
901        // overflowing. Every other negative `i64` negates exactly.
902        let neg = usize::try_from(position.saturating_neg()).unwrap_or(usize::MAX);
903        total.saturating_sub(neg)
904    }
905}
906
907/// Convert an RFC 8620 `limit` / `maxChanges` argument (`UnsignedInt|null`)
908/// to a `usize` item count for [`Iterator::take`] (bd:JMAP-pgj7).
909///
910/// RFC 8620 §5.5: "The maximum number of results to return. If null, no
911/// limit presumed." `None` therefore maps to `usize::MAX`. A `Some(n)`
912/// larger than `usize::MAX` (only possible on 32-bit targets) saturates
913/// to `usize::MAX` instead of truncating, which is the same "take
914/// everything" outcome, since no in-memory list can exceed `usize::MAX`.
915///
916/// This replaces the per-crate `n as usize` idiom, which silently drops
917/// the high bits on 32-bit targets (a `limit` of `2^32` became `0`).
918///
919/// # Example
920///
921/// ```
922/// use jmap_server::limit_or_max;
923///
924/// assert_eq!(limit_or_max(None), usize::MAX);
925/// assert_eq!(limit_or_max(Some(0)), 0);
926/// assert_eq!(limit_or_max(Some(25)), 25);
927/// ```
928#[must_use]
929pub fn limit_or_max(limit: Option<u64>) -> usize {
930    limit.map_or(usize::MAX, |n| usize::try_from(n).unwrap_or(usize::MAX))
931}
932
933/// Parse the RFC 8620 §5.5 `/query` arguments `anchor` (`Id|null`) and
934/// `anchorOffset` (`Int`, default `0`) from `args`.
935///
936/// # Errors
937///
938/// `invalidArguments` when `anchor` is neither a string nor `null`, is a
939/// string that is not an RFC 8620 §1.2 Id, or `anchorOffset` is neither an
940/// integer nor `null`.
941pub fn query_anchor_args(args: &Map<String, Value>) -> Result<(Option<Id>, i64), JmapError> {
942    let anchor = match args.get("anchor") {
943        None | Some(Value::Null) => None,
944        Some(Value::String(s)) => Some(
945            Id::new_validated(s.as_str())
946                .map_err(|e| JmapError::invalid_arguments(format!("anchor: {e}")))?,
947        ),
948        Some(v) => {
949            return Err(JmapError::invalid_arguments(format!(
950                "anchor: expected an Id string or null, got {}",
951                json_type_name(v)
952            )));
953        }
954    };
955    let anchor_offset = match args.get("anchorOffset") {
956        None | Some(Value::Null) => 0,
957        Some(v) => v.as_i64().ok_or_else(|| {
958            JmapError::invalid_arguments(format!(
959                "anchorOffset: expected an integer, got {}",
960                json_type_name(v)
961            ))
962        })?,
963    };
964    Ok((anchor, anchor_offset))
965}
966
967/// Start index of a `/query` page within the filtered, sorted `ids`
968/// (RFC 8620 §5.5), for [`JmapReads::query_objects`] implementations.
969///
970/// With an `anchor`, `position` is ignored and the start is the
971/// anchor's index plus `anchor_offset`, clamped to `0..=ids.len()`.
972/// Without one, `anchor_offset` is ignored and the start is
973/// [`resolve_query_offset`]`(position, ids.len())`.
974///
975/// # Errors
976///
977/// [`JmapError::anchor_not_found`] when `anchor` is not in `ids`.
978///
979/// [`JmapReads::query_objects`]: crate::JmapReads::query_objects
980pub fn resolve_query_start(
981    ids: &[Id],
982    position: i64,
983    anchor: Option<&Id>,
984    anchor_offset: i64,
985) -> Result<usize, JmapError> {
986    let Some(anchor) = anchor else {
987        return Ok(resolve_query_offset(position, ids.len()));
988    };
989    let index = ids
990        .iter()
991        .position(|id| id == anchor)
992        .ok_or_else(JmapError::anchor_not_found)?;
993    let start = i64::try_from(index)
994        .unwrap_or(i64::MAX)
995        .saturating_add(anchor_offset)
996        .max(0);
997    Ok(resolve_query_offset(start, ids.len()))
998}
999
1000/// Enforce RFC 8620 §5.3 `maxObjectsInSet` cap at the top of a `/set`
1001/// handler (bd:JMAP-ayoz.41.1).
1002///
1003/// Counts entries in the wire `create` (object), `update` (object), and
1004/// `destroy` (array) arguments. Returns the method-level error
1005/// [`JmapError::request_too_large`] (wire `type: "requestTooLarge"`,
1006/// `description: "maxObjectsInSet"`) when the sum exceeds `max`. Per
1007/// RFC 8620 §5.3 it is returned instead of the `Foo/set` response, so
1008/// the dispatcher emits an `error` invocation and later method calls
1009/// in the same request still run (bd:JMAP-yt1w.30).
1010///
1011/// Call at the top of every `handle_*_set` after the `account_exists`
1012/// gate and before any per-entry processing. A request carrying
1013/// megabytes of `/set` ops is rejected before the handler touches the
1014/// storage layer:
1015///
1016/// ```ignore
1017/// let (account_id, args) = extract_account_id(args)?;
1018/// if !backend.account_exists(caller, &account_id).await
1019///     .map_err(|e| server_fail_from_backend(&e))?
1020/// {
1021///     return Err(JmapError::account_not_found());
1022/// }
1023/// jmap_server::helpers::enforce_max_objects_in_set(
1024///     &args,
1025///     backend.max_objects_in_set(caller, &account_id),
1026/// )?;
1027/// ```
1028///
1029/// # Why this lives in the foundation
1030///
1031/// `maxObjectsInSet` is a RFC 8620 §5.3 base-protocol cap, not an
1032/// extension concept. Every `jmap-*-server` extension's `handle_*_set`
1033/// needs the same check; the helper is the single source of truth so a
1034/// future revision (different error shape, additional counting rule,
1035/// alternate semantics for non-object `create` / `update`) lands in one
1036/// place instead of being propagated through 28 handler sites.
1037///
1038/// # Counting rules
1039///
1040/// - `create` is counted as `args["create"].as_object()?.len()` —
1041///   missing key, `null`, or non-object types count as 0.
1042/// - `update` is counted the same way (RFC 8620 §5.3 `update` is
1043///   `Id[PatchObject]`).
1044/// - `destroy` is counted as `args["destroy"].as_array()?.len()` —
1045///   missing key, `null`, or non-array types count as 0.
1046///
1047/// Wire-shape validation of the individual `create` / `update` /
1048/// `destroy` arguments belongs to the per-handler argument parsing,
1049/// not to this cap-enforcement helper. A non-object `create` survives
1050/// the cap check (counts as 0) and is rejected by the handler's
1051/// downstream `args.remove("create")` match arm. Conversely, a
1052/// well-formed but over-limit `create` is rejected here before the
1053/// handler runs.
1054///
1055/// # Errors
1056///
1057/// Returns `JmapError::request_too_large()` with description
1058/// `"maxObjectsInSet"` when the sum exceeds `max` (RFC 8620 §5.3).
1059pub fn enforce_max_objects_in_set(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
1060    let create_count = args
1061        .get("create")
1062        .and_then(|v| v.as_object())
1063        .map_or(0u64, |m| m.len() as u64);
1064    let update_count = args
1065        .get("update")
1066        .and_then(|v| v.as_object())
1067        .map_or(0u64, |m| m.len() as u64);
1068    let destroy_count = args
1069        .get("destroy")
1070        .and_then(|v| v.as_array())
1071        .map_or(0u64, |a| a.len() as u64);
1072    // u64 saturation: each count is bounded by serde_json's body parse
1073    // (Map::len / Vec::len are usize; on 64-bit targets usize == u64,
1074    // on 32-bit targets usize < u64). The sum cannot exceed
1075    // 3 * u32::MAX even on 32-bit hosts, well within u64 range.
1076    let count = create_count
1077        .saturating_add(update_count)
1078        .saturating_add(destroy_count);
1079    if count > max {
1080        let mut err = JmapError::request_too_large();
1081        err.description = Some("maxObjectsInSet".into());
1082        return Err(err);
1083    }
1084    Ok(())
1085}
1086
1087/// Enforce RFC 8620 §5.1 `maxObjectsInGet` at the top of a `/get`
1088/// handler (bd:JMAP-yt1w.31).
1089///
1090/// Counts the entries in the wire `ids` argument. Returns the
1091/// method-level error [`JmapError::request_too_large`] (wire
1092/// `type: "requestTooLarge"`, `description: "maxObjectsInGet"`) when the
1093/// count exceeds `max`. Per RFC 8620 §5.1 it is returned instead of the
1094/// `Foo/get` response.
1095///
1096/// Call after the `account_exists` gate and before parsing `ids`:
1097///
1098/// ```ignore
1099/// jmap_server::helpers::enforce_max_objects_in_get(
1100///     &args,
1101///     backend.max_objects_in_get(caller, &account_id),
1102/// )?;
1103/// ```
1104///
1105/// # Counting rules
1106///
1107/// `ids` is counted as `args["ids"].as_array()?.len()`. A missing key,
1108/// `null` (fetch all), or a non-array value counts as 0: RFC 8620 §5.1
1109/// bounds "the number of ids requested by the client", and a null `ids`
1110/// requests none. Bounding a fetch-all by the number of records is the
1111/// backend's job, since only it knows how many records exist. Wire-shape
1112/// validation of `ids` belongs to the handler's argument parsing.
1113///
1114/// # Errors
1115///
1116/// Returns `JmapError::request_too_large()` with description
1117/// `"maxObjectsInGet"` when the count exceeds `max` (RFC 8620 §5.1).
1118pub fn enforce_max_objects_in_get(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
1119    let count = args
1120        .get("ids")
1121        .and_then(|v| v.as_array())
1122        .map_or(0u64, |a| a.len() as u64);
1123    if count > max {
1124        let mut err = JmapError::request_too_large();
1125        err.description = Some("maxObjectsInGet".into());
1126        return Err(err);
1127    }
1128    Ok(())
1129}
1130
1131/// Reject a `/set` create object that carries a DID-bearing property, or
1132/// an update PatchObject that changes one (draft-atwood-jmap-did-00
1133/// §The `did` Property).
1134///
1135/// `entry` is one value from the `create` or `update` argument and
1136/// `did_properties` names the data type's DID-bearing properties, which the
1137/// consuming specification defines. `current` is `None` for a create and
1138/// the stored object for an update.
1139///
1140/// "Clients omit DID-bearing properties when creating objects, as
1141/// {{RFC8620}} Section 1.1 requires for server-set properties; an update
1142/// can include one only with its current value ({{RFC8620}} Section 5.3).
1143/// Servers MUST reject a create that includes a DID-bearing property, or an
1144/// update that changes one, with a SetError of type `invalidProperties`"
1145/// (draft-atwood-jmap-did-00 L247). So a create that names the property is
1146/// rejected whatever the value, even `null`. An update key equal to the
1147/// property name passes when its value equals the stored value, where an
1148/// absent stored property counts as `null`, the value's other type. A
1149/// PatchObject key is a path, and a key whose first segment is the property
1150/// name but has further segments always changes it, so it is rejected.
1151/// Keeping the value unchanged on the server side, including across a DID
1152/// migration, is the backend's job.
1153///
1154/// Returns `None` when `entry` is acceptable. Otherwise returns an
1155/// `invalidProperties` [`SetError`] whose `properties` lists every rejected
1156/// DID-bearing property, in `did_properties` order.
1157#[must_use]
1158pub fn reject_did_bearing_properties(
1159    entry: &Map<String, Value>,
1160    did_properties: &[&str],
1161    current: Option<&Map<String, Value>>,
1162) -> Option<SetError> {
1163    // ponytail: compares the raw first segment, without RFC 6901 `~0`/`~1`
1164    // decoding. That is exact for property names with no `~` or `/`, which
1165    // covers every DID-bearing name in the drafts.
1166    let rejected: Vec<&str> = did_properties
1167        .iter()
1168        .copied()
1169        .filter(|prop| {
1170            entry.iter().any(|(k, v)| {
1171                k.split('/').next() == Some(*prop)
1172                    && !(k == prop
1173                        && current
1174                            .is_some_and(|stored| stored.get(*prop).unwrap_or(&Value::Null) == v))
1175            })
1176        })
1177        .collect();
1178    (!rejected.is_empty())
1179        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
1180}
1181
1182/// Reject a `/set` create that carries a server-set property of `O`.
1183///
1184/// RFC 8620 §1.1: for a "server-set" property, "The client MUST NOT send
1185/// this property when creating a new object of this type."; RFC 8620 §5.3
1186/// makes such a record `invalidProperties`.
1187///
1188/// A `null` value asserts nothing and is treated as absent.
1189///
1190/// Returns `None` when `create` carries none of [`SetObject::SERVER_SET`]
1191/// with a non-null value. Otherwise returns an `invalidProperties`
1192/// [`SetError`] whose `properties` lists each one carried, in `SERVER_SET`
1193/// order.
1194#[must_use]
1195pub fn reject_server_set<O: SetObject>(create: &Map<String, Value>) -> Option<SetError> {
1196    let rejected: Vec<&str> = O::SERVER_SET
1197        .iter()
1198        .copied()
1199        .filter(|prop| create.get(*prop).is_some_and(|v| !v.is_null()))
1200        .collect();
1201    (!rejected.is_empty())
1202        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
1203}
1204
1205/// Reject a `/set` update patch that names a server-set or immutable
1206/// property of `O`.
1207///
1208/// A patch key names a property when it equals the property name or starts
1209/// with `"<name>/"`, a JSON Pointer inside it (RFC 8620 §5.3). Changing a
1210/// [`SetObject::SERVER_SET`] property is `invalidProperties` (RFC 8620
1211/// §5.3), and a [`SetObject::IMMUTABLE`] value "MUST NOT change after the
1212/// object is created" (RFC 8620 §1.1).
1213///
1214/// `current` is the stored object, when the handler has it. RFC 8620 §5.3:
1215/// "Any server-set properties MAY be included in the patch if their value is
1216/// identical to the current server value", so a key that names the whole
1217/// property with its stored value passes. A key with further segments always
1218/// changes the property and is rejected.
1219///
1220/// Returns `None` when the patch names none. Otherwise returns an
1221/// `invalidProperties` [`SetError`] whose `properties` lists each property
1222/// named, `SERVER_SET` first, then `IMMUTABLE`, each in list order.
1223///
1224/// ponytail: compares the raw first segment, without RFC 6901 `~0`/`~1`
1225/// decoding, which is exact for property names with no `~` or `/`. With
1226/// `current` `None` an unchanged value is rejected too; a handler that can
1227/// fetch the stored object passes it.
1228#[must_use]
1229pub fn reject_read_only_patch<O: SetObject>(
1230    patch: &Map<String, Value>,
1231    current: Option<&Map<String, Value>>,
1232) -> Option<SetError> {
1233    let rejected: Vec<&str> = O::SERVER_SET
1234        .iter()
1235        .chain(O::IMMUTABLE)
1236        .copied()
1237        .filter(|prop| {
1238            patch.iter().any(|(k, v)| {
1239                k.split('/').next() == Some(*prop)
1240                    && !(k == prop
1241                        && current
1242                            .is_some_and(|stored| stored.get(*prop).unwrap_or(&Value::Null) == v))
1243            })
1244        })
1245        .collect();
1246    (!rejected.is_empty())
1247        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
1248}
1249
1250/// Whether patch key `key` names a [`SetObject::SERVER_SET`] or
1251/// [`SetObject::IMMUTABLE`] property of `O`: its first JSON Pointer segment
1252/// is the property name (RFC 8620 §5.3).
1253fn names_read_only<O: SetObject>(key: &str) -> bool {
1254    let prop = key.split('/').next().unwrap_or(key);
1255    O::SERVER_SET.contains(&prop) || O::IMMUTABLE.contains(&prop)
1256}
1257
1258/// Reject a `/set` update `patch` that changes a server-set or immutable
1259/// property of `O`, then drop the keys that repeat the stored value.
1260///
1261/// Runs [`reject_read_only_patch`] with `current`, the stored object. When
1262/// that passes, every key naming such a property holds its stored value
1263/// (RFC 8620 §5.3) and is removed, leaving only the client changes. An
1264/// empty result is a no-op update.
1265///
1266/// # Errors
1267///
1268/// The `invalidProperties` [`SetError`] from [`reject_read_only_patch`].
1269pub fn strip_read_only_patch<O: SetObject>(
1270    patch: &mut Map<String, Value>,
1271    current: Option<&Map<String, Value>>,
1272) -> Result<(), Box<SetError>> {
1273    if let Some(err) = reject_read_only_patch::<O>(patch, current) {
1274        return Err(Box::new(err));
1275    }
1276    patch.retain(|k, _| !names_read_only::<O>(k));
1277    Ok(())
1278}
1279
1280/// Check a `/set` update `patch` of the stored object `id` against the
1281/// server-set and immutable properties of `O`, and report a no-op.
1282///
1283/// RFC 8620 §5.3: "Any server-set properties MAY be included in the patch
1284/// if their value is identical to the current server value (before
1285/// applying the patches to the object).  Otherwise, the update MUST be
1286/// rejected with an "invalidProperties" SetError." The stored object is
1287/// fetched only when the patch names such a property or is empty; then
1288/// [`strip_read_only_patch`] rejects a changed value and drops the
1289/// identical ones, leaving only the client changes for the handler's own
1290/// checks.
1291///
1292/// Returns `Ok(true)` when nothing is left to apply, for a literal `{}` or
1293/// a patch of identical server-set values: the update succeeds as a no-op,
1294/// with no write, `updated` mapping `id` to `null`, and the state unchanged.
1295/// A missing object is `notFound`, whether the patch is empty or names a
1296/// read-only key: existence is checked before shape, so a caller learns
1297/// nothing about the properties of an object it cannot see.
1298///
1299/// # Errors
1300///
1301/// The `notUpdated` value: `notFound` for a missing object, the
1302/// `invalidProperties` SetError, or `serverFail` when the fetch fails.
1303pub async fn check_read_only_patch<B, O>(
1304    backend: &B,
1305    caller: &B::CallerCtx,
1306    account_id: &Id,
1307    id: &Id,
1308    patch: &mut Map<String, Value>,
1309) -> Result<bool, Value>
1310where
1311    B: JmapBackend,
1312    O: GetObject + SetObject + serde::Serialize + Send + Sync,
1313{
1314    if !patch.is_empty() && !patch.keys().any(|k| names_read_only::<O>(k)) {
1315        return Ok(false);
1316    }
1317    let (found, _) = backend
1318        .get_objects::<O>(caller, account_id, Some(std::slice::from_ref(id)), None)
1319        .await
1320        .map_err(|e| server_fail_value_from_backend(&e))?;
1321    let current = match found.first().map(serde_json::to_value).transpose() {
1322        Ok(Some(Value::Object(m))) => m,
1323        Ok(Some(_)) => {
1324            return Err(server_fail_value_from_backend(
1325                "stored object is not a JSON object",
1326            ));
1327        }
1328        Ok(None) => return Err(Value::from(&SetError::new(SetErrorType::NotFound))),
1329        Err(e) => return Err(server_fail_value_from_backend(&e)),
1330    };
1331    strip_read_only_patch::<O>(patch, Some(&current)).map_err(|e| Value::from(&*e))?;
1332    Ok(patch.is_empty())
1333}
1334
1335/// Whether a client may change `prop` of `O` in a `/set` update: it is in
1336/// [`SetObject::CLIENT_SETTABLE`] and not in [`SetObject::IMMUTABLE`].
1337///
1338/// For a handler whose spec lists the update keys it supports, so that any
1339/// other property is rejected rather than checked against the read-only
1340/// lists.
1341#[must_use]
1342pub fn is_client_updatable<O: SetObject>(prop: &str) -> bool {
1343    O::CLIENT_SETTABLE.contains(&prop) && !O::IMMUTABLE.contains(&prop)
1344}
1345
1346/// Resolve an Id-typed value that may be a creation-id reference
1347/// (RFC 8620 §5.3).
1348///
1349/// A value starting with `#` names a record created earlier in the same
1350/// request; it resolves to that record's server-assigned id from
1351/// `created_ids` (pass [`crate::CallContext::created_ids`]). Any other
1352/// value is a literal id and is returned as is. `None` means a `#`
1353/// reference with no matching creation; the caller rejects the
1354/// create/update, typically with an `invalidProperties` SetError naming
1355/// the property.
1356///
1357/// References to creates in the *same* `/set` call are not in
1358/// `created_ids` yet; the handler orders and resolves those itself
1359/// (RFC 8620 §5.3).
1360pub fn resolve_creation_ref(
1361    raw: &str,
1362    created_ids: &std::collections::BTreeMap<Id, Id>,
1363) -> Option<Id> {
1364    match raw.strip_prefix('#') {
1365        Some(creation_id) => created_ids.get(&Id::from(creation_id)).cloned(),
1366        None => Some(Id::from(raw)),
1367    }
1368}
1369
1370/// A blobId-typed value with a `#creationId` reference (RFC 8620 §5.3)
1371/// replaced by the id an earlier method call of the request created, such
1372/// as a blob from `Blob/upload`, `Blob/set` or `Blob/convert`
1373/// (draft-ietf-jmap-blobext-03 §8, "later method calls").
1374///
1375/// `created_ids` is the request's creation id map
1376/// ([`crate::CallContext::created_ids`]). A literal, or a reference that
1377/// matches no earlier creation, comes back unchanged, so the method's own
1378/// blobId check rejects an unknown reference exactly as it rejects any
1379/// other value that is not an Id.
1380#[must_use]
1381pub fn resolve_blob_ref<'a>(raw: &'a str, created_ids: &BTreeMap<Id, Id>) -> Cow<'a, str> {
1382    if raw.starts_with('#')
1383        && let Some(id) = resolve_creation_ref(raw, created_ids)
1384    {
1385        return Cow::Owned(id.as_ref().to_owned());
1386    }
1387    Cow::Borrowed(raw)
1388}
1389
1390/// Check that every blobId under one of `keys` in a `/set` create object or
1391/// update patch is an Id (RFC 8620 §1.2), at any depth: a key such as
1392/// `"blobId"`, or a patch path whose last segment is one (such as
1393/// `"media/p/blobId"`). `null` passes; the type decides whether it is
1394/// allowed.
1395///
1396/// Returns an `invalidProperties` [`SetError`] naming the top-level property
1397/// that holds the first malformed value (such as `"media"` for a Media
1398/// object's `blobId`, RFC 9610 §2), or `None`. Whether the blob exists is
1399/// for the backend to check.
1400///
1401/// Run it after [`resolve_blob_refs`], so a `#creationId` naming an
1402/// earlier creation has become an Id and an unknown one is rejected here.
1403#[must_use]
1404pub fn check_blob_ids(obj: &Map<String, Value>, keys: &[&str]) -> Option<SetError> {
1405    fn bad(value: &Value, keys: &[&str]) -> bool {
1406        match value {
1407            Value::Object(map) => map.iter().any(|(key, v)| {
1408                let last = key.rsplit('/').next().unwrap_or(key);
1409                if keys.contains(&last) && !v.is_object() && !v.is_array() {
1410                    match v {
1411                        Value::Null => false,
1412                        Value::String(s) => Id::new_validated(s.as_str()).is_err(),
1413                        _ => true,
1414                    }
1415                } else {
1416                    bad(v, keys)
1417                }
1418            }),
1419            Value::Array(items) => items.iter().any(|v| bad(v, keys)),
1420            _ => false,
1421        }
1422    }
1423    obj.iter()
1424        .find(|(key, v)| {
1425            bad(
1426                &Value::Object(Map::from_iter([((*key).clone(), (*v).clone())])),
1427                keys,
1428            )
1429        })
1430        .map(|(key, _)| {
1431            let top = key.split('/').next().unwrap_or(key);
1432            SetError::new(SetErrorType::InvalidProperties)
1433                .with_properties([top])
1434                .with_description("a blobId is not an Id (RFC 8620 §1.2)")
1435        })
1436}
1437
1438/// Rewrite the `update` keys and `destroy` entries of `/set` arguments that
1439/// are `#creationId` references (RFC 8620 §5.3) to the ids they name.
1440///
1441/// RFC 8620 §5.3 has a server order a call's creates "before their creation
1442/// ids are referenced by another create/update/destroy in the same call",
1443/// so an update or destroy may name a record created earlier in the
1444/// request by its creation id. A reference resolves first against
1445/// `created`, the call's own `created` map so far (creation id → object
1446/// with an `id`), then against `created_ids`, the request's map
1447/// ([`crate::CallContext::created_ids`]). A reference that names a create
1448/// still in `args`'s own `create` map, and not yet in `created`, is left
1449/// for the pass after the create phase: this call's create wins over an
1450/// earlier call's use of the same creation id. An unknown reference is
1451/// left as sent, so the handler rejects it as it rejects any other id that
1452/// is not an Id; responses then key a resolved entry by the real id.
1453///
1454/// [`Dispatcher::dispatch`](crate::Dispatcher::dispatch) runs it on every
1455/// `*/set` call before the handler, with an empty `created`, so earlier
1456/// calls' creations always resolve. A handler calls it again after its
1457/// create phase with the call's `created`, before updates and destroys
1458/// run, for references to its own creates.
1459pub fn resolve_set_id_refs(
1460    args: &mut Map<String, Value>,
1461    created_ids: &BTreeMap<Id, Id>,
1462    created: &Map<String, Value>,
1463) {
1464    let pending: BTreeSet<String> = match args.get("create") {
1465        Some(Value::Object(create)) => create
1466            .keys()
1467            .filter(|k| !created.contains_key(*k))
1468            .cloned()
1469            .collect(),
1470        _ => BTreeSet::new(),
1471    };
1472    let resolve = |raw: &str| -> Option<String> {
1473        let cid = raw.strip_prefix('#')?;
1474        if pending.contains(cid) {
1475            return None;
1476        }
1477        created
1478            .get(cid)
1479            .and_then(|obj| obj.get("id"))
1480            .and_then(Value::as_str)
1481            .map(str::to_owned)
1482            .or_else(|| {
1483                created_ids
1484                    .get(&Id::from(cid))
1485                    .map(|id| id.as_ref().to_owned())
1486            })
1487    };
1488    if let Some(Value::Object(update)) = args.get_mut("update")
1489        && update.keys().any(|k| resolve(k).is_some())
1490    {
1491        *update = std::mem::take(update)
1492            .into_iter()
1493            .map(|(k, v)| (resolve(&k).unwrap_or(k), v))
1494            .collect();
1495    }
1496    if let Some(Value::Array(destroy)) = args.get_mut("destroy") {
1497        for v in destroy {
1498            if let Value::String(raw) = v
1499                && let Some(id) = resolve(raw)
1500            {
1501                *raw = id;
1502            }
1503        }
1504    }
1505}
1506
1507/// Rewrite every blobId reference in a `/set` create object or update
1508/// patch through [`resolve_blob_ref`], before the handler parses it.
1509///
1510/// A string is rewritten when its object key is one of `keys` (such as
1511/// `"blobId"`), or a patch path whose last segment is one (such as
1512/// `"media/m1/blobId"`), at any depth. `blobIds`-style arrays are not
1513/// walked. Unknown references and literals are left for the handler's
1514/// own validation.
1515///
1516/// Pass the request's map, not one a handler grows with its own creates:
1517/// a blob is created by an earlier call, never by a create of this one.
1518pub fn resolve_blob_refs(value: &mut Value, keys: &[&str], created_ids: &BTreeMap<Id, Id>) {
1519    match value {
1520        Value::Object(map) => {
1521            for (key, v) in map.iter_mut() {
1522                let last = key.rsplit('/').next().unwrap_or(key);
1523                if let Value::String(raw) = v
1524                    && keys.contains(&last)
1525                {
1526                    if let Cow::Owned(id) = resolve_blob_ref(raw, created_ids) {
1527                        *raw = id;
1528                    }
1529                } else {
1530                    resolve_blob_refs(v, keys, created_ids);
1531                }
1532            }
1533        }
1534        Value::Array(items) => {
1535            for v in items {
1536                resolve_blob_refs(v, keys, created_ids);
1537            }
1538        }
1539        _ => {}
1540    }
1541}
1542
1543/// The `id` a `/set` create handler fills in before parsing the create
1544/// object into its typed struct, whose `id` is required.
1545///
1546/// The builder passed to the backend overwrites it with the minted id, so
1547/// it never reaches storage or the wire. It must still satisfy RFC 8620
1548/// §1.2 (at least 1 octet, URL-safe base64 alphabet) because deserializing
1549/// an [`Id`] validates it.
1550pub const CREATE_ID_PLACEHOLDER: &str = "pending";
1551
1552/// Parse a client-supplied id: a `/set` `update` key, a `destroy` element
1553/// or an Id-typed property value.
1554///
1555/// RFC 8620 §1.2: an Id "MUST be at least 1 and a maximum of 255 octets in
1556/// size, and it MUST only contain characters from the 'URL and Filename
1557/// Safe' base64 alphabet". [`Id::from`] does not check this, so every
1558/// handler routes wire ids through here instead.
1559///
1560/// # Errors
1561///
1562/// A boxed `invalidProperties` [`SetError`] naming `property` (`"id"` for an
1563/// `update` key or `destroy` element) whose description says why the
1564/// value is not an Id. The caller records it in `notCreated`,
1565/// `notUpdated` or `notDestroyed` for that entry.
1566pub fn parse_wire_id(raw: &str, property: &str) -> Result<Id, Box<SetError>> {
1567    Id::new_validated(raw).map_err(|e| {
1568        Box::new(
1569            SetError::new(SetErrorType::InvalidProperties)
1570                .with_properties([property])
1571                .with_description(e.to_string()),
1572        )
1573    })
1574}
1575
1576/// `true` if `using` includes `urn:ietf:params:jmap:metadata`
1577/// (draft-ietf-jmap-metadata-05 §3: the extensions "apply to requests
1578/// whose using includes urn:ietf:params:jmap:metadata").
1579pub fn uses_metadata(using: &[String]) -> bool {
1580    using
1581        .iter()
1582        .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI)
1583}
1584
1585/// draft-ietf-jmap-metadata-05 §3: the §3.6 filter conditions extend
1586/// `Foo/query` only for "requests whose using includes
1587/// urn:ietf:params:jmap:metadata". Without it a metadata leaf anywhere in
1588/// `filter`, as `is_metadata` judges a condition, is `unsupportedFilter`
1589/// (RFC 8620 §5.5: "The filter is syntactically valid, but the server
1590/// cannot process it"). `Foo/query` and `Foo/queryChanges` handlers call
1591/// it once the filter is decoded.
1592///
1593/// # Errors
1594///
1595/// `unsupportedFilter` as above.
1596pub fn reject_metadata_filter_without_capability<T>(
1597    filter: Option<&jmap_types::Filter<T>>,
1598    is_metadata: fn(&T) -> bool,
1599    using: &[String],
1600) -> Result<(), JmapError> {
1601    fn any_leaf<T>(f: &jmap_types::Filter<T>, is_metadata: fn(&T) -> bool) -> bool {
1602        match f {
1603            jmap_types::Filter::Condition(c) => is_metadata(c),
1604            jmap_types::Filter::Operator(op) => {
1605                op.conditions.iter().any(|f| any_leaf(f, is_metadata))
1606            }
1607            _ => false,
1608        }
1609    }
1610    if uses_metadata(using) || !filter.is_some_and(|f| any_leaf(f, is_metadata)) {
1611        return Ok(());
1612    }
1613    let mut err = JmapError::unsupported_filter();
1614    err.description = Some(
1615        "metadata filter conditions require urn:ietf:params:jmap:metadata in using".to_owned(),
1616    );
1617    Err(err)
1618}
1619
1620/// [`reject_metadata_filter_without_capability`] on the undecoded
1621/// `filter` argument of a `Foo/query` or `Foo/queryChanges` request, for
1622/// handlers that pass `args` on to [`handle_query`](crate::handle_query)
1623/// or [`handle_query_changes`](crate::handle_query_changes) and so never
1624/// hold the decoded filter. A `filter` that does not decode is left for
1625/// that handler to report.
1626///
1627/// # Errors
1628///
1629/// `unsupportedFilter` for a -05 §3.6 condition without
1630/// `urn:ietf:params:jmap:metadata` in `using` (-05 §3).
1631pub fn reject_metadata_filter_arg<T: serde::de::DeserializeOwned>(
1632    args: &Value,
1633    is_metadata: fn(&T) -> bool,
1634    using: &[String],
1635) -> Result<(), JmapError> {
1636    if uses_metadata(using) {
1637        return Ok(());
1638    }
1639    let Some(raw) = args.get("filter").filter(|v| !v.is_null()) else {
1640        return Ok(());
1641    };
1642    match serde_json::from_value::<jmap_types::Filter<T>>(raw.clone()) {
1643        Ok(filter) => reject_metadata_filter_without_capability(Some(&filter), is_metadata, using),
1644        Err(_) => Ok(()),
1645    }
1646}
1647
1648/// Which part of one metadata property a `Foo/get` returns.
1649#[derive(Debug, Default)]
1650enum Selection {
1651    /// Not returned.
1652    #[default]
1653    Omit,
1654    /// The whole stored object.
1655    All,
1656    /// Only these namespaces (-05 §3.1 subselectors, combined by union).
1657    Namespaces(BTreeSet<String>),
1658}
1659
1660impl Selection {
1661    fn add_namespace(&mut self, ns: &str) {
1662        match self {
1663            Self::All => {}
1664            Self::Omit => *self = Self::Namespaces(BTreeSet::from([ns.to_owned()])),
1665            Self::Namespaces(set) => {
1666                set.insert(ns.to_owned());
1667            }
1668        }
1669    }
1670
1671    /// The value to return for a property stored as `stored`; absent and
1672    /// `null` are `{}` (-05 §2: "When returned, its value MUST be an
1673    /// object ({} when no metadata is set), never null").
1674    fn select(&self, stored: Option<&Value>) -> Option<Value> {
1675        let stored = stored.and_then(Value::as_object);
1676        match self {
1677            Self::Omit => None,
1678            Self::All => Some(Value::Object(stored.cloned().unwrap_or_default())),
1679            Self::Namespaces(set) => Some(Value::Object(
1680                stored
1681                    .into_iter()
1682                    .flatten()
1683                    .filter(|(k, _)| set.contains(k.as_str()))
1684                    .map(|(k, v)| (k.clone(), v.clone()))
1685                    .collect(),
1686            )),
1687        }
1688    }
1689}
1690
1691/// How a `Foo/get` handler returns `metadata` and `privateMetadata`
1692/// (draft-ietf-jmap-metadata-05 §2 and §3.1).
1693///
1694/// Build one per request with [`MetadataProjection::new`], then call
1695/// [`MetadataProjection::apply`] on every returned object.
1696#[derive(Debug, Default)]
1697pub struct MetadataProjection {
1698    metadata: Selection,
1699    private_metadata: Selection,
1700}
1701
1702impl MetadataProjection {
1703    /// Build the projection for one `Foo/get` request.
1704    ///
1705    /// `properties` is the request's `properties` (`None` for the default
1706    /// list), `default_includes` is `false` for `Email/get`, whose
1707    /// "default property list ... is unchanged" (-05 §3.1), and `true` for
1708    /// every other type; `info` is the type's DataTypeMetadataInfo
1709    /// ([`JmapAccounts::metadata_info`](crate::JmapAccounts::metadata_info)),
1710    /// `None` when the type is not listed and so "does not gain the
1711    /// metadata or privateMetadata properties" (-05 §1.2.1). The rules:
1712    ///
1713    /// - Default list: both properties with the capability in `using`
1714    ///   ("the server MUST include metadata and, where supportsPrivate is
1715    ///   true, privateMetadata"), neither without it ("not default
1716    ///   properties of Foo/get") (-05 §3, §3.1).
1717    /// - A root name returns the whole property, with or without the
1718    ///   capability ("still returned when requested by name").
1719    /// - With the capability, `metadata/<namespace>` and
1720    ///   `privateMetadata/<namespace>` return only the stored namespaces
1721    ///   named; several combine by union and a root entry supersedes them.
1722    ///   A namespace with no stored data is left out, which covers "A
1723    ///   subselector naming a namespace that is not supported ... MUST be
1724    ///   silently omitted ... unless the object has data stored under that
1725    ///   namespace". Without the capability these entries are ignored like
1726    ///   any other unknown property.
1727    /// - `privateMetadata` is never returned when `supportsPrivate` is
1728    ///   false (-05 §2: "this property MUST NOT be returned").
1729    ///
1730    /// # Errors
1731    ///
1732    /// `invalidArguments` for an entry that begins with `metadata/` or
1733    /// `privateMetadata/` and is not followed by a namespace identifier
1734    /// (-05 §3.1: "Any other properties entry beginning with metadata/ or
1735    /// privateMetadata/ MUST be rejected with an "invalidArguments"
1736    /// method-level error").
1737    pub fn new(
1738        properties: Option<&[String]>,
1739        default_includes: bool,
1740        using: &[String],
1741        info: Option<&jmap_metadata_types::DataTypeMetadataInfo>,
1742    ) -> Result<Self, JmapError> {
1743        let Some(info) = info else {
1744            return Ok(Self::default());
1745        };
1746        let uses = uses_metadata(using);
1747        let mut projection = Self::default();
1748        match properties {
1749            None if uses && default_includes => {
1750                projection.metadata = Selection::All;
1751                projection.private_metadata = Selection::All;
1752            }
1753            None => {}
1754            Some(props) => {
1755                for p in props {
1756                    let (root, ns) = p
1757                        .split_once('/')
1758                        .map_or((p.as_str(), None), |(r, n)| (r, Some(n)));
1759                    let sel = match root {
1760                        "metadata" => &mut projection.metadata,
1761                        "privateMetadata" => &mut projection.private_metadata,
1762                        _ => continue,
1763                    };
1764                    match ns {
1765                        None => *sel = Selection::All,
1766                        Some(_) if !uses => {}
1767                        // A subselector names one namespace: nothing below
1768                        // it ("metadata/<namespace>/<key>" is an error).
1769                        // is_valid_namespace alone accepts '/' in a domain
1770                        // label.
1771                        Some(ns)
1772                            if !ns.contains('/') && jmap_metadata_types::is_valid_namespace(ns) =>
1773                        {
1774                            sel.add_namespace(ns);
1775                        }
1776                        Some(_) => {
1777                            return Err(JmapError::invalid_arguments(format!(
1778                                "properties: {p:?} is not a metadata subselector"
1779                            )));
1780                        }
1781                    }
1782                }
1783            }
1784        }
1785        if !info.supports_private {
1786            projection.private_metadata = Selection::Omit;
1787        }
1788        Ok(projection)
1789    }
1790
1791    /// Set or remove `metadata` and `privateMetadata` on the response
1792    /// object `target` from the stored object `source`.
1793    pub fn apply(&self, source: &Value, target: &mut Value) {
1794        let Value::Object(target) = target else {
1795            return;
1796        };
1797        for (root, sel) in [
1798            ("metadata", &self.metadata),
1799            ("privateMetadata", &self.private_metadata),
1800        ] {
1801            match sel.select(source.get(root)) {
1802                Some(v) => {
1803                    target.insert(root.to_owned(), v);
1804                }
1805                None => {
1806                    target.remove(root);
1807                }
1808            }
1809        }
1810    }
1811}
1812
1813/// The values of an RFC 8620 §5.3 PatchObject placed at their JSON Pointer
1814/// paths in an empty object, so checks written for a whole object can see
1815/// what a patch writes: `{"links/l1/uri": "x"}` becomes
1816/// `{"links": {"l1": {"uri": "x"}}}`. Paths are split on `/` and unescaped
1817/// (RFC 6901 `~1`, `~0`); a path that runs through a value already placed
1818/// as a non-object is skipped. `null` values (removals) are skipped.
1819///
1820/// ```rust
1821/// use serde_json::json;
1822///
1823/// let patch = json!({ "links/l1/uri": "x", "name": null, "media": { "m": { "uri": "y" } } });
1824/// let placed = jmap_server::patch_values_as_object(patch.as_object().unwrap());
1825/// assert_eq!(placed, *json!({ "links": { "l1": { "uri": "x" } }, "media": { "m": { "uri": "y" } } }).as_object().unwrap());
1826/// ```
1827pub fn patch_values_as_object(patch: &Map<String, Value>) -> Map<String, Value> {
1828    let mut out = Map::new();
1829    'paths: for (path, value) in patch {
1830        if value.is_null() {
1831            continue;
1832        }
1833        let segments: Vec<String> = path
1834            .split('/')
1835            .map(|s| s.replace("~1", "/").replace("~0", "~"))
1836            .collect();
1837        let Some((last, parents)) = segments.split_last() else {
1838            continue;
1839        };
1840        let mut target = &mut out;
1841        for seg in parents {
1842            let entry = target
1843                .entry(seg.clone())
1844                .or_insert_with(|| Value::Object(Map::new()));
1845            match entry {
1846                Value::Object(m) => target = m,
1847                _ => continue 'paths,
1848            }
1849        }
1850        target.insert(last.clone(), value.clone());
1851    }
1852    out
1853}
1854
1855#[cfg(test)]
1856mod tests {
1857    use super::{
1858        MAX_MERGE_PATCH_DEPTH, MergePatchError, PatchPathError, apply_jmap_patch,
1859        apply_patch_object, check_blob_ids, civil_from_days, enforce_max_objects_in_set,
1860        extract_account_id, filter_arg, is_client_updatable, json_merge_patch, json_type_name,
1861        limit_or_max, now_utc_string, parse_max_changes, parse_wire_id, query_anchor_args,
1862        reject_did_bearing_properties, reject_read_only_patch, reject_server_set, resolve_blob_ref,
1863        resolve_blob_refs, resolve_creation_ref, resolve_query_offset, resolve_query_start,
1864        resolve_set_id_refs, signed_seconds_since_epoch, utc_date_from_epoch_millis,
1865        utc_date_from_epoch_seconds,
1866    };
1867    use jmap_types::{Id, PushSubscription, UTCDate};
1868    use serde_json::json;
1869
1870    fn props(e: Option<crate::backend::SetError>) -> Option<Vec<String>> {
1871        e.map(|e| {
1872            serde_json::from_value(serde_json::to_value(e).unwrap()["properties"].clone()).unwrap()
1873        })
1874    }
1875
1876    /// Oracle: RFC 8620 §7.2, `id` is "(immutable; server-set)" and the
1877    /// other properties are client-sent. RFC 8620 §1.1: "The client MUST
1878    /// NOT send this property when creating". A null `id` is treated as
1879    /// absent.
1880    #[test]
1881    fn reject_server_set_names_server_set_create_properties() {
1882        let ok = json!({"id": null, "deviceClientId": "d", "url": "https://x.example/"});
1883        assert_eq!(
1884            props(reject_server_set::<PushSubscription>(
1885                ok.as_object().unwrap()
1886            )),
1887            None
1888        );
1889        let bad = json!({"id": "p1", "deviceClientId": "d"});
1890        assert_eq!(
1891            props(reject_server_set::<PushSubscription>(
1892                bad.as_object().unwrap()
1893            )),
1894            Some(vec!["id".to_owned()])
1895        );
1896    }
1897
1898    /// Oracle: RFC 8620 §7.2, `id` is server-set, `deviceClientId`, `url`
1899    /// and `keys` are "(immutable)", `expires` and `types` carry no
1900    /// attribute. `keys/auth` points inside `keys`; `urlX` is another name.
1901    #[test]
1902    fn reject_read_only_patch_names_server_set_and_immutable_keys() {
1903        let ok = json!({"expires": null, "types": ["Email"], "urlX": 1});
1904        assert_eq!(
1905            props(reject_read_only_patch::<PushSubscription>(
1906                ok.as_object().unwrap(),
1907                None
1908            )),
1909            None
1910        );
1911        let bad = json!({"keys/auth": "a", "id": "p2", "url": "https://y.example/"});
1912        assert_eq!(
1913            props(reject_read_only_patch::<PushSubscription>(
1914                bad.as_object().unwrap(),
1915                None
1916            )),
1917            Some(vec!["id".to_owned(), "url".to_owned(), "keys".to_owned()])
1918        );
1919    }
1920
1921    /// Oracle: RFC 8620 §7.2: `id` is "(immutable; server-set)",
1922    /// `deviceClientId` is "(immutable)", `expires` carries no attribute;
1923    /// `nope` is not a PushSubscription property.
1924    #[test]
1925    fn is_client_updatable_excludes_server_set_immutable_and_unknown() {
1926        assert!(is_client_updatable::<PushSubscription>("expires"));
1927        assert!(!is_client_updatable::<PushSubscription>("id"));
1928        assert!(!is_client_updatable::<PushSubscription>("deviceClientId"));
1929        assert!(!is_client_updatable::<PushSubscription>("nope"));
1930    }
1931
1932    /// Oracle: RFC 8620 §5.3, "Any server-set properties MAY be included in
1933    /// the patch if their value is identical to the current server value
1934    /// ... Otherwise, the update MUST be rejected with an
1935    /// "invalidProperties" SetError." `keys/auth` points inside `keys`, so
1936    /// it changes it even when the leaf value matches.
1937    #[test]
1938    fn reject_read_only_patch_allows_unchanged_whole_values() {
1939        let stored = json!({"id": "p1", "url": "https://x.example/", "keys": {"auth": "a"}});
1940        let stored = stored.as_object().unwrap();
1941        let same = json!({"id": "p1", "url": "https://x.example/"});
1942        assert_eq!(
1943            props(reject_read_only_patch::<PushSubscription>(
1944                same.as_object().unwrap(),
1945                Some(stored)
1946            )),
1947            None
1948        );
1949        let changed = json!({"id": "p1", "url": "https://y.example/", "keys/auth": "a"});
1950        assert_eq!(
1951            props(reject_read_only_patch::<PushSubscription>(
1952                changed.as_object().unwrap(),
1953                Some(stored)
1954            )),
1955            Some(vec!["url".to_owned(), "keys".to_owned()])
1956        );
1957    }
1958
1959    /// Oracle: RFC 8620 §5.3 — "the client refers to the new record
1960    /// using its creation id prefixed with a '#'"; the RFC 8620 §5.3
1961    /// example request sets `"subTodoIds": [ "#k15" ]` after creating
1962    /// `k15`. A bare value is an ordinary id.
1963    #[test]
1964    fn resolve_creation_ref_maps_hash_refs_and_passes_literals() {
1965        let created = std::collections::BTreeMap::from([(Id::from("k15"), Id::from("T15"))]);
1966        assert_eq!(
1967            resolve_creation_ref("#k15", &created),
1968            Some(Id::from("T15"))
1969        );
1970        assert_eq!(resolve_creation_ref("k15", &created), Some(Id::from("k15")));
1971        assert_eq!(resolve_creation_ref("#k16", &created), None);
1972    }
1973
1974    /// Oracle: RFC 8620 §5.3 (a `#` reference resolves to the id created
1975    /// earlier in the request); draft-ietf-jmap-blobext-03 §8 (a blob
1976    /// created earlier is named that way). Unknown references pass through.
1977    #[test]
1978    fn resolve_blob_ref_resolves_known_refs_only() {
1979        let created = std::collections::BTreeMap::from([(Id::from("b1"), Id::from("G1"))]);
1980        assert_eq!(resolve_blob_ref("#b1", &created), "G1");
1981        assert_eq!(resolve_blob_ref("#b2", &created), "#b2");
1982        assert_eq!(resolve_blob_ref("b1", &created), "b1");
1983    }
1984
1985    /// RFC 9610 §2 Media `blobId` (nested in a map), a patch path ending in
1986    /// `blobId`, a list of parts, and other keys left alone.
1987    #[test]
1988    fn resolve_blob_refs_walks_nested_values_and_patch_paths() {
1989        let created = std::collections::BTreeMap::from([(Id::from("b1"), Id::from("G1"))]);
1990        let mut v = serde_json::json!({
1991            "media": {"m1": {"blobId": "#b1", "uri": "#b1"}},
1992            "media/m2/blobId": "#b1",
1993            "parts": [{"blobId": "#b1"}, {"blobId": "#nope"}],
1994            "iconBlobId": "#b1",
1995            "parentId": "#b1"
1996        });
1997        resolve_blob_refs(&mut v, &["blobId", "iconBlobId"], &created);
1998        assert_eq!(
1999            v,
2000            serde_json::json!({
2001                "media": {"m1": {"blobId": "G1", "uri": "#b1"}},
2002                "media/m2/blobId": "G1",
2003                "parts": [{"blobId": "G1"}, {"blobId": "#nope"}],
2004                "iconBlobId": "G1",
2005                "parentId": "#b1"
2006            })
2007        );
2008    }
2009
2010    /// Oracle: RFC 8620 §5.3 — creates happen "before their creation ids
2011    /// are referenced by another create/update/destroy in the same call",
2012    /// so update keys and destroy ids may be creation ids, from this call
2013    /// or an earlier one. Unknown references and literals stay as sent.
2014    #[test]
2015    fn resolve_set_id_refs_rewrites_update_keys_and_destroy_ids() {
2016        let earlier = std::collections::BTreeMap::from([(Id::from("e"), Id::from("E1"))]);
2017        let created = serde_json::json!({"c": {"id": "C1"}});
2018        let mut args = serde_json::json!({
2019            "update": {"#e": {"a": 1}, "#c": {"b": 2}, "#nope": {}, "lit": {}},
2020            "destroy": ["#e", "#c", "#nope", "lit"]
2021        });
2022        resolve_set_id_refs(
2023            args.as_object_mut().expect("object"),
2024            &earlier,
2025            created.as_object().expect("object"),
2026        );
2027        assert_eq!(
2028            args,
2029            serde_json::json!({
2030                "update": {"E1": {"a": 1}, "C1": {"b": 2}, "#nope": {}, "lit": {}},
2031                "destroy": ["E1", "C1", "#nope", "lit"]
2032            })
2033        );
2034    }
2035
2036    /// RFC 9610 §2 Media `blobId: Id`; RFC 8620 §1.2 Id syntax. A
2037    /// malformed value names the top-level property, whether nested, a
2038    /// patch path, or a whole replaced object; `null` and valid Ids pass.
2039    #[test]
2040    fn check_blob_ids_names_the_top_level_property() {
2041        let check = |v: serde_json::Value| {
2042            check_blob_ids(v.as_object().expect("object"), &["blobId"])
2043                .map(|e| serde_json::Value::from(&e)["properties"].clone())
2044        };
2045        assert_eq!(
2046            check(serde_json::json!({"media": {"p": {"blobId": "G1"}}})),
2047            None
2048        );
2049        assert_eq!(
2050            check(serde_json::json!({"media": {"p": {"blobId": null}}})),
2051            None
2052        );
2053        assert_eq!(
2054            check(serde_json::json!({"name": "x", "media": {"p": {"blobId": "#nope"}}})),
2055            Some(serde_json::json!(["media"]))
2056        );
2057        assert_eq!(
2058            check(serde_json::json!({"media/p/blobId": 7})),
2059            Some(serde_json::json!(["media"]))
2060        );
2061        assert_eq!(
2062            check(serde_json::json!({"locations/r": {"links": {"m": {"blobId": "a b"}}}})),
2063            Some(serde_json::json!(["locations"]))
2064        );
2065    }
2066
2067    /// A creation id this call is about to create shadows an earlier
2068    /// call's: before the create phase it stays as sent.
2069    #[test]
2070    fn resolve_set_id_refs_leaves_this_calls_pending_creates() {
2071        let earlier = std::collections::BTreeMap::from([(Id::from("x"), Id::from("OLD"))]);
2072        let mut args = serde_json::json!({
2073            "create": {"x": {}},
2074            "update": {"#x": {}},
2075            "destroy": ["#x"]
2076        });
2077        let map = args.as_object_mut().expect("object");
2078        resolve_set_id_refs(map, &earlier, &serde_json::Map::new());
2079        assert_eq!(map["update"], serde_json::json!({"#x": {}}));
2080        assert_eq!(map["destroy"], serde_json::json!(["#x"]));
2081        let created = serde_json::json!({"x": {"id": "NEW"}});
2082        resolve_set_id_refs(map, &earlier, created.as_object().expect("object"));
2083        assert_eq!(map["update"], serde_json::json!({"NEW": {}}));
2084        assert_eq!(map["destroy"], serde_json::json!(["NEW"]));
2085    }
2086
2087    /// RFC 8620 §1.2: 1 to 255 octets from `A-Za-z0-9`, `-` and `_`.
2088    #[test]
2089    fn parse_wire_id_enforces_rfc8620_id_syntax() {
2090        assert_eq!(parse_wire_id("aZ09-_", "id"), Ok(Id::from("aZ09-_")));
2091        assert!(parse_wire_id(&"a".repeat(255), "id").is_ok());
2092        for bad in [
2093            "",
2094            "has space",
2095            "line\nbreak",
2096            "#c1",
2097            "a=",
2098            &"a".repeat(256),
2099        ] {
2100            let err = parse_wire_id(bad, "mailboxId").unwrap_err();
2101            assert_eq!(
2102                serde_json::to_value(&err).unwrap()["type"],
2103                "invalidProperties",
2104                "{bad:?}"
2105            );
2106            assert_eq!(
2107                err.properties.as_deref(),
2108                Some(&["mailboxId".to_owned()][..])
2109            );
2110        }
2111    }
2112
2113    #[test]
2114    fn query_anchor_args_rejects_non_id_anchor() {
2115        let args = serde_json::json!({ "anchor": "not an id" });
2116        let err = query_anchor_args(args.as_object().unwrap()).unwrap_err();
2117        assert_eq!(
2118            err.error_type,
2119            jmap_types::MethodErrorType::InvalidArguments
2120        );
2121        let args = serde_json::json!({ "anchor": "m1", "anchorOffset": -1 });
2122        assert_eq!(
2123            query_anchor_args(args.as_object().unwrap()).unwrap(),
2124            (Some(Id::from("m1")), -1)
2125        );
2126    }
2127
2128    #[derive(Debug, serde::Deserialize)]
2129    #[serde(rename_all = "camelCase", deny_unknown_fields)]
2130    struct NameCond {
2131        name: Option<String>,
2132    }
2133
2134    // draft-atwood-jmap-did-00 L247 (jmap-chat-spec 6bcd9d8): "Clients omit
2135    // DID-bearing properties when creating objects, as {{RFC8620}} Section
2136    // 1.1 requires for server-set properties; an update can include one only
2137    // with its current value ({{RFC8620}} Section 5.3). Servers MUST reject a
2138    // create that includes a DID-bearing property, or an update that changes
2139    // one, with a SetError of type `invalidProperties`, listing the
2140    // DID-bearing property name in the `properties` array."
2141    fn did_entry(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
2142        v.as_object().cloned().expect("object")
2143    }
2144
2145    fn invalid_did() -> serde_json::Value {
2146        json!({ "type": "invalidProperties", "properties": ["did"] })
2147    }
2148
2149    #[test]
2150    fn did_create_with_did_property_is_invalid_properties() {
2151        let entry = did_entry(json!({
2152            "name": "x",
2153            "did": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
2154        }));
2155        let err = reject_did_bearing_properties(&entry, &["did"], None).expect("L247: MUST reject");
2156        assert_eq!(
2157            serde_json::to_value(&err).expect("serialize"),
2158            invalid_did()
2159        );
2160    }
2161
2162    #[test]
2163    fn did_create_with_null_did_is_still_rejected() {
2164        // L247: "a create that includes a DID-bearing property"; null is included.
2165        let entry = did_entry(json!({ "did": null }));
2166        assert!(reject_did_bearing_properties(&entry, &["did"], None).is_some());
2167    }
2168
2169    #[test]
2170    fn did_lists_every_did_bearing_property_named() {
2171        // L247 rejects each included DID-bearing property. The two names
2172        // here are arbitrary DID-bearing names the caller declares; the
2173        // `properties` array follows `did_properties` order, not key order.
2174        let entry = did_entry(json!({
2175            "ownerDid": "did:web:example.com",
2176            "did": "did:web:example.org"
2177        }));
2178        let err = reject_did_bearing_properties(&entry, &["did", "ownerDid"], None)
2179            .expect("L247: MUST reject");
2180        assert_eq!(
2181            err.properties,
2182            Some(vec!["did".to_owned(), "ownerDid".to_owned()])
2183        );
2184    }
2185
2186    #[test]
2187    fn did_update_with_current_value_passes() {
2188        // L247: "an update can include one only with its current value".
2189        let stored = did_entry(json!({ "id": "a", "did": "did:web:example.com" }));
2190        let entry = did_entry(json!({ "name": "y", "did": "did:web:example.com" }));
2191        assert_eq!(
2192            reject_did_bearing_properties(&entry, &["did"], Some(&stored)),
2193            None
2194        );
2195
2196        let stored_null = did_entry(json!({ "id": "a", "did": null }));
2197        let entry_null = did_entry(json!({ "did": null }));
2198        assert_eq!(
2199            reject_did_bearing_properties(&entry_null, &["did"], Some(&stored_null)),
2200            None
2201        );
2202    }
2203
2204    #[test]
2205    fn did_update_with_null_over_absent_did_passes() {
2206        // L247: "an update can include one only with its current value".
2207        // RFC 8620 §5.3: "null ... to remove it (or reset it to its
2208        // default value)", so an absent property's current value is null.
2209        let stored = did_entry(json!({ "id": "a" }));
2210        let entry = did_entry(json!({ "did": null }));
2211        assert_eq!(
2212            reject_did_bearing_properties(&entry, &["did"], Some(&stored)),
2213            None
2214        );
2215    }
2216
2217    #[test]
2218    fn did_update_that_changes_did_is_rejected() {
2219        // L247: "Servers MUST reject ... an update that changes one". A
2220        // different value, null over a stored DID, and a path under the
2221        // property ("did/x", RFC 8620 §5.3 PatchObject path) all change it.
2222        let stored = did_entry(json!({ "id": "a", "did": "did:web:example.com" }));
2223        for entry in [
2224            did_entry(json!({ "did": "did:web:example.org" })),
2225            did_entry(json!({ "did": null })),
2226            did_entry(json!({ "did/x": 1 })),
2227        ] {
2228            let err = reject_did_bearing_properties(&entry, &["did"], Some(&stored))
2229                .expect("L247: update that changes one");
2230            assert_eq!(
2231                serde_json::to_value(&err).expect("serialize"),
2232                invalid_did()
2233            );
2234        }
2235    }
2236
2237    #[test]
2238    fn did_entry_without_did_bearing_property_passes() {
2239        // A property whose name merely starts with "did" is not "did".
2240        let entry = did_entry(json!({ "name": "x", "didx": 1, "keywords/did": true }));
2241        assert_eq!(reject_did_bearing_properties(&entry, &["did"], None), None);
2242    }
2243
2244    fn filter_of(v: serde_json::Value) -> Result<Option<NameCond>, jmap_types::JmapError> {
2245        let mut args = json!({ "filter": v }).as_object().cloned().expect("object");
2246        filter_arg::<NameCond>(&mut args)
2247    }
2248
2249    /// Oracle: RFC 8620 §5.5 — "unsupportedFilter: The "filter" is
2250    /// syntactically valid, but the server cannot process it"; RFC 8620
2251    /// §3.6.2 — invalidArguments for an argument of the wrong type.
2252    /// Hand-written JSON inputs.
2253    #[test]
2254    fn filter_arg_maps_object_and_non_object_failures() {
2255        assert!(filter_of(json!(null)).expect("null").is_none());
2256        let cond = filter_of(json!({ "name": "x" })).expect("known key");
2257        assert_eq!(cond.and_then(|c| c.name).as_deref(), Some("x"));
2258        let err = filter_of(json!({ "label": "x" })).expect_err("unknown key");
2259        assert_eq!(err.error_type.to_string(), "unsupportedFilter");
2260        assert!(
2261            err.description
2262                .as_deref()
2263                .is_some_and(|d| d.contains("label")),
2264            "{err:?}"
2265        );
2266        let err = filter_of(json!(42)).expect_err("scalar");
2267        assert_eq!(err.error_type.to_string(), "invalidArguments");
2268    }
2269
2270    /// Oracle (bd:JMAP-wlip.5): a malformed accountId — empty string,
2271    /// containing forbidden ASCII characters, or exceeding 255 bytes —
2272    /// MUST surface as `invalidArguments`, not silently pass through to
2273    /// the backend's `account_exists` call.
2274    ///
2275    /// Test vectors hand-built from RFC 8620 §1.2's Id grammar
2276    /// (SAFE-CHAR = `%x21 / %x23-7E`).
2277    #[test]
2278    fn extract_account_id_rejects_malformed_id() {
2279        // Empty string.
2280        let err = extract_account_id(json!({ "accountId": "" }))
2281            .expect_err("empty accountId must fail validation");
2282        assert_eq!(err.error_type.to_string(), "invalidArguments");
2283
2284        // Contains a space (0x20 — outside SAFE-CHAR's 0x21+ lower bound).
2285        let err = extract_account_id(json!({ "accountId": "my account" }))
2286            .expect_err("space in accountId must fail validation");
2287        assert_eq!(err.error_type.to_string(), "invalidArguments");
2288
2289        // Contains a DQUOTE (0x22 — explicitly excluded by SAFE-CHAR).
2290        let err = extract_account_id(json!({ "accountId": "a\"b" }))
2291            .expect_err("DQUOTE in accountId must fail validation");
2292        assert_eq!(err.error_type.to_string(), "invalidArguments");
2293
2294        // 256 bytes — exceeds the 255 cap.
2295        let long: String = "a".repeat(256);
2296        let err = extract_account_id(json!({ "accountId": long }))
2297            .expect_err("over-long accountId must fail validation");
2298        assert_eq!(err.error_type.to_string(), "invalidArguments");
2299    }
2300
2301    /// Oracle (bd:JMAP-wlip.5): a well-formed accountId passes
2302    /// validation and is returned intact. Positive control paired with
2303    /// the rejection test above.
2304    ///
2305    /// Also pins (bd:JMAP-jfia.9): the returned args map MUST NOT
2306    /// contain accountId. The helper consumes the field rather than
2307    /// leaving it as a residual key for downstream handlers to
2308    /// re-parse or surface as "unexpected key".
2309    #[test]
2310    fn extract_account_id_accepts_well_formed_id() {
2311        let (id, rest) = extract_account_id(json!({
2312            "accountId": "u123-abc_DEF",
2313            "ids": ["e1", "e2"]
2314        }))
2315        .expect("well-formed accountId must pass validation");
2316        assert_eq!(id.as_ref(), "u123-abc_DEF");
2317        // Remaining args still contain the unrelated keys.
2318        assert!(rest.contains_key("ids"));
2319        // accountId MUST have been removed from the args map
2320        // (bd:JMAP-jfia.9). matches optional_arg's consume semantics.
2321        assert!(
2322            !rest.contains_key("accountId"),
2323            "accountId must be removed from args after extraction"
2324        );
2325    }
2326
2327    /// Test vectors derived independently with Python's `datetime.date` module.
2328    /// `days` is the count of days since 1970-01-01.
2329    #[test]
2330    fn civil_from_days_known_dates() {
2331        let cases: &[(i64, (i32, u8, u8))] = &[
2332            (0, (1970, 1, 1)),       // Unix epoch
2333            (365, (1971, 1, 1)),     // one year later (1970 is not a leap year)
2334            (10957, (2000, 1, 1)),   // Y2K
2335            (11016, (2000, 2, 29)),  // leap day in a century-divisible leap year
2336            (11017, (2000, 3, 1)),   // day after the leap day (era boundary in algorithm)
2337            (19358, (2023, 1, 1)),   // a recent non-leap year start
2338            (19722, (2023, 12, 31)), // end of 2023
2339            (19782, (2024, 2, 29)),  // leap day in 2024
2340            (19783, (2024, 3, 1)),   // day after 2024 leap day
2341        ];
2342
2343        for &(days, expected) in cases {
2344            assert_eq!(
2345                civil_from_days(days),
2346                Some(expected),
2347                "civil_from_days({days}) mismatch"
2348            );
2349        }
2350    }
2351
2352    /// Oracle (bd:JMAP-jfia.2): civil_from_days MUST return None rather
2353    /// than panic on inputs whose computed year overflows i32. The
2354    /// Hinnant algorithm's intermediate `y = yoe + era * 400` value is
2355    /// bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a thin slice of
2356    /// which fits in i32. The outer `now_utc_string_checked`
2357    /// u64→i64 sentinel only catches u64 seconds exceeding `i64::MAX`,
2358    /// so corrupted-clock inputs between the i32-year boundary and
2359    /// i64::MAX reach this function. A panic here would surface as
2360    /// serverFail under dispatcher task::spawn isolation — degraded,
2361    /// but a contract violation versus the function's "fallible
2362    /// without panicking" contract.
2363    ///
2364    /// Test vectors: the maximum days-from-epoch derived from
2365    /// i64::MAX seconds (the regime that reaches civil_from_days
2366    /// after passing the outer u64→i64 sentinel), and the symmetric
2367    /// negative case. These years are deep enough into the i64
2368    /// algorithm range to definitely overflow i32. Plus a
2369    /// non-overflowing positive control just below the threshold to
2370    /// prove the boundary check fires only when warranted.
2371    #[test]
2372    fn civil_from_days_returns_none_on_year_overflow() {
2373        // i64::MAX / 86400 ≈ 1.07e14 days → year ≈ 2.92e11, well past i32::MAX (~2.15e9).
2374        let max_days = i64::MAX / 86400;
2375        assert_eq!(
2376            civil_from_days(max_days),
2377            None,
2378            "i64::MAX / 86400 days must overflow i32 year"
2379        );
2380
2381        // i64::MIN / 86400 ≈ -1.07e14 days — symmetric negative case.
2382        let min_days = i64::MIN / 86400;
2383        assert_eq!(
2384            civil_from_days(min_days),
2385            None,
2386            "i64::MIN / 86400 days must overflow i32 year"
2387        );
2388
2389        // Positive control: a far-future but i32-fitting year should
2390        // still succeed. Year ~58_798_075 (from 10 * i32::MAX days)
2391        // fits in i32 with room to spare, so this MUST return Some.
2392        let year_58m_days = 10_i64 * i64::from(i32::MAX);
2393        let result = civil_from_days(year_58m_days);
2394        assert!(
2395            result.is_some(),
2396            "i32-fitting year must return Some; got {result:?}"
2397        );
2398    }
2399
2400    /// Oracle (bd:JMAP-jfia.30): now_utc_string_checked MUST return
2401    /// `Some(UTCDate)` on a sane clock (every host the test runs on
2402    /// in practice). The civil_from_days_returns_none_on_year_overflow
2403    /// test above pins the underlying None-on-corrupted-clock
2404    /// behaviour at the algorithm level; this test pins the
2405    /// happy-path contract: a sane clock yields the typed wire format,
2406    /// not a sentinel string.
2407    #[test]
2408    fn now_utc_string_checked_returns_some_on_sane_clock() {
2409        use super::now_utc_string_checked;
2410        let dt = now_utc_string_checked().expect(
2411            "test host clock must be reasonable enough for now_utc_string_checked to succeed",
2412        );
2413        let s: &str = dt.as_ref();
2414        assert!(
2415            UTCDate::new_validated(s).is_ok(),
2416            "must be an RFC 8620 §1.4 UTCDate: {s:?}"
2417        );
2418    }
2419
2420    /// Oracle (bd:JMAP-jfia.30): now_utc_string (the panicking variant)
2421    /// MUST agree with now_utc_string_checked on a sane clock — i.e.
2422    /// the .expect() in now_utc_string does not introduce a wire-format
2423    /// discrepancy versus the Option-returning variant.
2424    #[test]
2425    fn now_utc_string_matches_checked_variant_on_sane_clock() {
2426        use super::now_utc_string_checked;
2427        let panicky = now_utc_string();
2428        let checked = now_utc_string_checked().expect("test host clock must be reasonable");
2429        // Both calls observe SystemTime::now() at slightly different
2430        // instants; the seconds part can differ if the test runs across
2431        // a second boundary. Compare the prefix up to the seconds
2432        // resolution.
2433        let panicky_s: &str = panicky.as_ref();
2434        let checked_s: &str = checked.as_ref();
2435        // Compare the date portion only (YYYY-MM-DD, 10 chars).
2436        assert_eq!(
2437            &panicky_s[..10],
2438            &checked_s[..10],
2439            "date portions must match: panicky={panicky_s:?} checked={checked_s:?}"
2440        );
2441    }
2442
2443    /// Oracle: GNU `date -u -d @<secs> +%FT%TZ` (coreutils), plus the
2444    /// RFC 8620 §7.2.3 example expiry (rfc8620.txt:3879) and the RFC 8620
2445    /// §1.4 example date. -62167219200 is 0000-01-01T00:00:00Z; one second
2446    /// earlier is year -1, which the four-digit form cannot express.
2447    #[test]
2448    fn utc_date_from_epoch_seconds_known_values() {
2449        for (secs, expected) in [
2450            (0, Some("1970-01-01T00:00:00Z")),
2451            (-1, Some("1969-12-31T23:59:59Z")),
2452            (1_414_649_520, Some("2014-10-30T06:12:00Z")),
2453            (1_531_448_069, Some("2018-07-13T02:14:29Z")),
2454            (253_402_300_799, Some("9999-12-31T23:59:59Z")),
2455            (253_402_300_800, None),
2456            (-62_167_219_200, Some("0000-01-01T00:00:00Z")),
2457            (-62_167_219_201, None),
2458        ] {
2459            assert_eq!(
2460                utc_date_from_epoch_seconds(secs)
2461                    .as_ref()
2462                    .map(AsRef::as_ref),
2463                expected,
2464                "secs = {secs}"
2465            );
2466        }
2467    }
2468
2469    /// Oracle: GNU `date -u -d @1414649520 +%FT%TZ` gives
2470    /// 2014-10-30T06:12:00Z (also the RFC 8620 §1.4 example). RFC 8620
2471    /// §1.4: "the "time-secfrac" MUST always be omitted if zero"
2472    /// (rfc8620.txt:346-347), so zero millis yield the 20-char form.
2473    #[test]
2474    fn utc_date_from_epoch_millis_omits_zero_secfrac() {
2475        for (millis, expected) in [
2476            (0, "2014-10-30T06:12:00Z"),
2477            (1, "2014-10-30T06:12:00.001Z"),
2478            (120, "2014-10-30T06:12:00.120Z"),
2479            (999, "2014-10-30T06:12:00.999Z"),
2480        ] {
2481            let d = utc_date_from_epoch_millis(1_414_649_520, millis).unwrap();
2482            assert_eq!(d.as_ref(), expected, "millis = {millis}");
2483            assert!(UTCDate::new_validated(expected).is_ok(), "{expected}");
2484        }
2485    }
2486
2487    /// Oracle: GNU `date -u -d @<secs> +%FT%TZ` (coreutils). Pre-epoch
2488    /// seconds must take the time of day from the floored day, not from
2489    /// truncating division (bd:JMAP-yt1w.40: -1 used to yield 00:00:59).
2490    #[test]
2491    fn utc_date_from_epoch_millis_pre_epoch_time_of_day() {
2492        for (secs, expected) in [
2493            (-1, "1969-12-31T23:59:59Z"),
2494            (-61, "1969-12-31T23:58:59Z"),
2495            (-3601, "1969-12-31T22:59:59Z"),
2496            (-86401, "1969-12-30T23:59:59Z"),
2497            (-90061, "1969-12-30T22:58:59Z"),
2498        ] {
2499            let d = utc_date_from_epoch_millis(secs, 0).unwrap();
2500            assert_eq!(d.as_ref(), expected, "secs = {secs}");
2501        }
2502    }
2503
2504    /// Oracle: GNU `date -u -d @<secs> +%FT%T.%3NZ` (coreutils), which
2505    /// floors to the millisecond. Pre-epoch sub-second clocks used to
2506    /// format as -s + millis instead of -s - millis (bd:JMAP-yt1w.46).
2507    #[test]
2508    fn signed_seconds_since_epoch_pre_epoch_subsec() {
2509        use std::time::{Duration, UNIX_EPOCH};
2510        for (before, expected) in [
2511            (Duration::from_millis(1200), "1969-12-31T23:59:58.800Z"),
2512            (Duration::from_millis(500), "1969-12-31T23:59:59.500Z"),
2513            (Duration::from_micros(1_200_500), "1969-12-31T23:59:58.799Z"),
2514            (
2515                Duration::from_millis(86_400_001),
2516                "1969-12-30T23:59:59.999Z",
2517            ),
2518            (Duration::from_secs(1), "1969-12-31T23:59:59Z"),
2519        ] {
2520            let (secs, millis) = signed_seconds_since_epoch(UNIX_EPOCH - before).unwrap();
2521            let d = utc_date_from_epoch_millis(secs, millis).unwrap();
2522            assert_eq!(d.as_ref(), expected, "before = {before:?}");
2523        }
2524    }
2525
2526    #[test]
2527    fn now_utc_string_format() {
2528        // bd:JMAP-wlip.20 — return type is UTCDate; AsRef<str> gives
2529        // the underlying wire-format string for shape assertions.
2530        let dt = now_utc_string();
2531        let s: &str = dt.as_ref();
2532        // YYYY-MM-DDTHH:MM:SS.mmmZ (24 chars), or YYYY-MM-DDTHH:MM:SSZ
2533        // (20 chars) when the milliseconds are zero (RFC 8620 §1.4).
2534        assert!(s.len() == 24 || s.len() == 20, "unexpected length: {s}");
2535        assert!(s.ends_with('Z'), "must end with Z: {s}");
2536        assert_eq!(&s[4..5], "-", "missing year-month separator: {s}");
2537        assert_eq!(&s[7..8], "-", "missing month-day separator: {s}");
2538        assert_eq!(&s[10..11], "T", "missing date-time separator: {s}");
2539        assert_eq!(&s[13..14], ":", "missing hour-minute separator: {s}");
2540        assert_eq!(&s[16..17], ":", "missing minute-second separator: {s}");
2541        if s.len() == 24 {
2542            assert_eq!(&s[19..20], ".", "missing decimal point before millis: {s}");
2543            assert!(
2544                s[20..23].chars().all(|c| c.is_ascii_digit()),
2545                "milliseconds must be 3 digits: {s}"
2546            );
2547        }
2548        assert!(
2549            s.starts_with("20"),
2550            "year should start with 20 in 21st century: {s}"
2551        );
2552    }
2553
2554    // -----------------------------------------------------------------------
2555    // json_merge_patch (RFC 7396)
2556    //
2557    // Test oracles are hand-built JSON values derived from RFC 7396 §2 and §3
2558    // examples, plus the regression case from bd:JMAP-sc1b.87. No oracle is
2559    // computed by the function under test (test-integrity rule from
2560    // workspace AGENTS.md).
2561    // -----------------------------------------------------------------------
2562
2563    /// Oracle: bd:JMAP-sc1b.97 — a 1000-deep merge patch must NOT crash
2564    /// via stack overflow. The depth cap returns
2565    /// [`MergePatchError::DepthExceeded`] beyond [`MAX_MERGE_PATCH_DEPTH`]
2566    /// rather than recursing further.
2567    ///
2568    /// The test does not use the function as its own oracle: the input
2569    /// is hand-built (a 1000-deep `{ "a": { "a": ... { "a": {} } } }`
2570    /// chain where every level is Object, matching the structural
2571    /// shape of a real PatchObject — the documented latent panic from
2572    /// bd:JMAP-sc1b.87 only fires on non-Object leaves, which a typed
2573    /// PatchObject cannot produce). The assertion checks that the
2574    /// call completes without panicking AND that it surfaces the
2575    /// depth-exceeded error rather than silently succeeding (the
2576    /// pre-bd:JMAP-wlip.1 silent-truncation bug).
2577    #[test]
2578    fn json_merge_patch_does_not_stack_overflow() {
2579        const DEPTH: usize = 1000;
2580        let mut target = serde_json::json!({});
2581        for _ in 0..DEPTH {
2582            target = serde_json::json!({ "a": target });
2583        }
2584        let mut patch = serde_json::json!({});
2585        for _ in 0..DEPTH {
2586            patch = serde_json::json!({ "a": patch });
2587        }
2588        let err = json_merge_patch(&mut target, patch)
2589            .expect_err("deep patch must surface DepthExceeded, not silently truncate");
2590        assert_eq!(
2591            err,
2592            MergePatchError::DepthExceeded,
2593            "deep patch must return MergePatchError::DepthExceeded"
2594        );
2595    }
2596
2597    /// Oracle: bd:JMAP-wlip.1 — a patch at exactly [`MAX_MERGE_PATCH_DEPTH`]
2598    /// levels (the deepest legal patch) MUST apply successfully. The cap
2599    /// fires only when the patch tries to recurse one level beyond. The
2600    /// expected target shape is hand-built level-by-level from the same
2601    /// counter the patch uses, so the oracle is independent of the
2602    /// recursion under test.
2603    #[test]
2604    fn json_merge_patch_at_exact_cap_applies() {
2605        // Build a patch nested exactly MAX_MERGE_PATCH_DEPTH levels deep.
2606        // Outermost level is depth=1; innermost leaf-Object is at depth
2607        // MAX_MERGE_PATCH_DEPTH. The first depth-cap check fires at
2608        // depth == MAX_MERGE_PATCH_DEPTH + 1, so this is the deepest
2609        // patch that still applies.
2610        let mut patch = serde_json::json!({ "leaf": "value" });
2611        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
2612            patch = serde_json::json!({ "a": patch });
2613        }
2614        let mut target = serde_json::json!({});
2615        json_merge_patch(&mut target, patch).expect("patch at the cap must apply");
2616        // Walk the resulting target down its 'a' chain to verify the
2617        // leaf field landed.
2618        let mut cursor = &target;
2619        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
2620            cursor = cursor.get("a").expect("each level must have 'a'");
2621        }
2622        assert_eq!(
2623            cursor.get("leaf"),
2624            Some(&serde_json::Value::String("value".to_owned())),
2625            "the leaf field at exactly MAX_MERGE_PATCH_DEPTH must be applied"
2626        );
2627    }
2628
2629    /// Oracle: a shallow merge patch under the cap still applies
2630    /// normally. Positive control paired with the stack-overflow test
2631    /// above to prove the depth cap only fires at the boundary, not on
2632    /// every call.
2633    #[test]
2634    fn json_merge_patch_shallow_applies_normally() {
2635        let mut target = serde_json::json!({ "a": 1, "b": { "c": 2 } });
2636        let patch = serde_json::json!({ "b": { "c": 99, "d": 7 }, "e": null });
2637        json_merge_patch(&mut target, patch).expect("shallow patch must succeed");
2638        assert_eq!(
2639            target,
2640            serde_json::json!({ "a": 1, "b": { "c": 99, "d": 7 } }),
2641            "RFC 7396 merge semantics broken at shallow depth"
2642        );
2643    }
2644
2645    /// Regression: a Patch that adds a nested Object to a previously-
2646    /// absent field used to panic with `expect("merge patch target
2647    /// must be an object")` because the parent recursion frame
2648    /// inserted Value::Null as the placeholder, then recursed into
2649    /// Null with an Object patch.
2650    ///
2651    /// Per RFC 7396 §2 the correct behaviour is to reset the non-Object
2652    /// target to an empty Object and merge into it. Oracle is hand-
2653    /// derived from RFC 7396 §2's pseudocode:
2654    /// `Target[Name] = MergePatch(Target[Name], Value)` where
2655    /// MergePatch resets a non-Object target to `{}`.
2656    #[test]
2657    fn json_merge_patch_adds_nested_object_to_absent_field() {
2658        let mut target = serde_json::json!({ "a": 1 });
2659        let patch = serde_json::json!({ "b": { "c": 2 } });
2660        json_merge_patch(&mut target, patch).expect("nested-add patch must succeed");
2661        assert_eq!(
2662            target,
2663            serde_json::json!({ "a": 1, "b": { "c": 2 } }),
2664            "patch must add the nested object at the previously-absent field"
2665        );
2666    }
2667
2668    /// Oracle: [`MergePatchError`] implements [`std::error::Error`] and
2669    /// has a stable Display form referencing the cap value. Pinning the
2670    /// Display string keeps the error message stable across refactors;
2671    /// the cap value is interpolated from the public constant so this
2672    /// test does not need updating if the cap changes.
2673    #[test]
2674    fn merge_patch_error_display() {
2675        let err = MergePatchError::DepthExceeded;
2676        let s = err.to_string();
2677        assert!(
2678            s.contains(&MAX_MERGE_PATCH_DEPTH.to_string()),
2679            "Display must mention the cap value; got {s:?}"
2680        );
2681        assert!(
2682            s.contains("merge patch"),
2683            "Display must identify the error source; got {s:?}"
2684        );
2685    }
2686
2687    // ------------------------------------------------------------------
2688    // apply_jmap_patch (RFC 8620 §5.3 PatchObject paths, RFC 6901)
2689    //
2690    // Oracles are hand-built JSON values derived from the quoted RFC
2691    // text; the function under test is never its own oracle.
2692    // ------------------------------------------------------------------
2693
2694    /// Build a `Map` from a JSON object literal.
2695    fn obj(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
2696        match v {
2697            serde_json::Value::Object(m) => m,
2698            other => panic!("fixture must be a JSON object, got {other}"),
2699        }
2700    }
2701
2702    /// Apply `path` → `value` to `before` and assert it fails with `want`
2703    /// and leaves the object unchanged.
2704    fn assert_patch_rejected(
2705        before: serde_json::Value,
2706        path: &str,
2707        value: serde_json::Value,
2708        want: PatchPathError,
2709    ) {
2710        let mut target = obj(before.clone());
2711        let err = apply_jmap_patch(&mut target, path, value).expect_err("patch must be rejected");
2712        assert_eq!(err, want, "wrong error for path {path:?}");
2713        assert_eq!(
2714            serde_json::Value::Object(target),
2715            before,
2716            "rejected patch {path:?} must leave the object unchanged"
2717        );
2718    }
2719
2720    /// Oracle: RFC 8620 §5.3 — "Anything else: The value to set for this
2721    /// property (this may be a replacement or addition to the object
2722    /// being patched)."
2723    #[test]
2724    fn apply_jmap_patch_non_null_adds_or_replaces() {
2725        let mut target = obj(json!({ "a": 1 }));
2726        apply_jmap_patch(&mut target, "a", json!(2)).expect("replace");
2727        apply_jmap_patch(&mut target, "b", json!("x")).expect("add");
2728        assert_eq!(
2729            serde_json::Value::Object(target),
2730            json!({ "a": 2, "b": "x" })
2731        );
2732    }
2733
2734    /// Oracle: RFC 8620 §5.3 — "If null, ... remove the property from the
2735    /// patched object.  If the key is not present in the parent, this a
2736    /// no-op."
2737    #[test]
2738    fn apply_jmap_patch_null_removes_and_absent_is_noop() {
2739        let mut target = obj(json!({ "a": 1, "m": { "k": true } }));
2740        apply_jmap_patch(&mut target, "a", serde_json::Value::Null).expect("remove");
2741        apply_jmap_patch(&mut target, "m/k", serde_json::Value::Null).expect("nested remove");
2742        apply_jmap_patch(&mut target, "m/absent", serde_json::Value::Null).expect("no-op");
2743        assert_eq!(serde_json::Value::Object(target), json!({ "m": {} }));
2744    }
2745
2746    /// Oracle: RFC 8620 §5.3 — "The keys are a path in JSON Pointer
2747    /// format [RFC6901], with an implicit leading "/"". `mailboxIds/abc`
2748    /// sets member `abc` of the existing `mailboxIds` object and leaves
2749    /// its siblings alone.
2750    #[test]
2751    fn apply_jmap_patch_nested_path_sets_member_of_existing_object() {
2752        let mut target = obj(json!({ "mailboxIds": { "inbox": true }, "x": { "y": { "z": 1 } } }));
2753        apply_jmap_patch(&mut target, "mailboxIds/abc", json!(true)).expect("set");
2754        apply_jmap_patch(&mut target, "x/y/w", json!(2)).expect("deep set");
2755        assert_eq!(
2756            serde_json::Value::Object(target),
2757            json!({ "mailboxIds": { "inbox": true, "abc": true }, "x": { "y": { "z": 1, "w": 2 } } })
2758        );
2759    }
2760
2761    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last (i.e., the
2762    /// value after the final slash) MUST already exist on the object
2763    /// being patched." A missing parent is rejected, never created, for
2764    /// both non-null and null values.
2765    #[test]
2766    fn apply_jmap_patch_missing_parent_is_rejected() {
2767        let before = json!({ "a": { "b": {} } });
2768        for value in [json!("v"), serde_json::Value::Null] {
2769            assert_patch_rejected(
2770                before.clone(),
2771                "x/y",
2772                value.clone(),
2773                PatchPathError::ParentMissing,
2774            );
2775            assert_patch_rejected(
2776                before.clone(),
2777                "a/c/d",
2778                value,
2779                PatchPathError::ParentMissing,
2780            );
2781        }
2782    }
2783
2784    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last ... MUST
2785    /// already exist on the object being patched." A string, number,
2786    /// boolean or null has no members, so a part beneath one does not
2787    /// exist; the existing value must not be clobbered.
2788    #[test]
2789    fn apply_jmap_patch_non_object_parent_is_rejected() {
2790        let before = json!({ "s": "text", "n": 42, "b": true, "z": null });
2791        for parent in ["s", "n", "b", "z"] {
2792            assert_patch_rejected(
2793                before.clone(),
2794                &format!("{parent}/sub"),
2795                json!("would-clobber"),
2796                PatchPathError::ParentNotObject,
2797            );
2798        }
2799    }
2800
2801    /// Oracle: RFC 8620 §5.3 — "The pointer MUST NOT reference inside an
2802    /// array (i.e., you MUST NOT insert/delete from an array; the array
2803    /// MUST be replaced in its entirety instead)." Applies to numeric
2804    /// tokens and to paths that would descend through an array element.
2805    #[test]
2806    fn apply_jmap_patch_inside_array_is_rejected() {
2807        let before = json!({ "list": ["a", { "k": 1 }] });
2808        assert_patch_rejected(
2809            before.clone(),
2810            "list/0",
2811            json!("x"),
2812            PatchPathError::InsideArray,
2813        );
2814        assert_patch_rejected(
2815            before.clone(),
2816            "list/1/k",
2817            json!(2),
2818            PatchPathError::InsideArray,
2819        );
2820        assert_patch_rejected(
2821            before,
2822            "list/0",
2823            serde_json::Value::Null,
2824            PatchPathError::InsideArray,
2825        );
2826    }
2827
2828    /// Oracle: draft-ietf-jmap-metadata-05 §3.2 — "a path that traverses
2829    /// an array or a Binary value (Section 2.1.1) is rejected with an
2830    /// "invalidPatch" SetError"; §2.1.1 — "a patch path ... cannot address
2831    /// its members". Fixture is the §2.1.1 example. The Binary itself can
2832    /// still be replaced or removed, since the path then ends at it.
2833    #[test]
2834    fn apply_jmap_patch_through_metadata_binary_is_rejected() {
2835        let before = json!({ "metadata": { "acme.example.com": {
2836            "label": "draft copy",
2837            "thumbprint": {
2838                "@type": "Binary",
2839                "base64": "VEVYVHR0eHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
2840            }
2841        } } });
2842        for (path, value) in [
2843            ("metadata/acme.example.com/thumbprint/base64", json!("AA==")),
2844            (
2845                "metadata/acme.example.com/thumbprint/base64",
2846                serde_json::Value::Null,
2847            ),
2848            ("metadata/acme.example.com/thumbprint/x", json!(1)),
2849        ] {
2850            assert_patch_rejected(before.clone(), path, value, PatchPathError::InsideBinary);
2851        }
2852        let private = json!({ "privateMetadata": { "x.example": {
2853            "b": { "@type": "Binary", "base64": "" }
2854        } } });
2855        assert_patch_rejected(
2856            private,
2857            "privateMetadata/x.example/b/base64",
2858            json!("Zg=="),
2859            PatchPathError::InsideBinary,
2860        );
2861
2862        let mut target = obj(before);
2863        let bin = json!({ "@type": "Binary", "base64": "Zg==" });
2864        apply_jmap_patch(
2865            &mut target,
2866            "metadata/acme.example.com/thumbprint",
2867            bin.clone(),
2868        )
2869        .expect("replace whole Binary");
2870        assert_eq!(target["metadata"]["acme.example.com"]["thumbprint"], bin);
2871    }
2872
2873    /// Oracle: RFC 8620 §5.3 — a path through an existing object is
2874    /// allowed. -05 §2.1.1 defines a Binary only "within a namespace
2875    /// value", so an `@type: "Binary"` object elsewhere is an ordinary
2876    /// object.
2877    #[test]
2878    fn apply_jmap_patch_binary_outside_metadata_is_ordinary() {
2879        let mut target = obj(json!({ "other": { "x": { "@type": "Binary", "base64": "" } } }));
2880        apply_jmap_patch(&mut target, "other/x/base64", json!("Zg==")).expect("plain object");
2881        assert_eq!(target["other"]["x"]["base64"], json!("Zg=="));
2882    }
2883
2884    /// Oracle: RFC 8620 §5.3 — "the array MUST be replaced in its entirety
2885    /// instead": setting the array-valued property itself is allowed.
2886    #[test]
2887    fn apply_jmap_patch_replaces_whole_array() {
2888        let mut target = obj(json!({ "list": ["a"] }));
2889        apply_jmap_patch(&mut target, "list", json!(["b", "c"])).expect("replace array");
2890        assert_eq!(
2891            serde_json::Value::Object(target),
2892            json!({ "list": ["b", "c"] })
2893        );
2894    }
2895
2896    /// Oracle: RFC 6901 §4 — "first transforming any occurrence of the
2897    /// sequence '~1' to '/', and then transforming any occurrence of the
2898    /// sequence '~0' to '~' ... (the string '~01' correctly becomes '~1'
2899    /// after transformation)." Decoding is per token, after splitting on
2900    /// `/`, so `a~1b/c` addresses member `c` of member `a/b`.
2901    #[test]
2902    fn apply_jmap_patch_decodes_rfc6901_escapes() {
2903        let mut target = obj(json!({ "a/b": {}, "m~n": {} }));
2904        apply_jmap_patch(&mut target, "foo~1bar", json!(1)).expect("~1");
2905        apply_jmap_patch(&mut target, "foo~0bar", json!(2)).expect("~0");
2906        apply_jmap_patch(&mut target, "~01", json!(3)).expect("~01");
2907        apply_jmap_patch(&mut target, "a~1b/c", json!(4)).expect("escaped parent");
2908        apply_jmap_patch(&mut target, "m~0n/~1", json!(5)).expect("escaped parent and leaf");
2909        assert_eq!(
2910            serde_json::Value::Object(target),
2911            json!({
2912                "foo/bar": 1,
2913                "foo~bar": 2,
2914                "~1": 3,
2915                "a/b": { "c": 4 },
2916                "m~n": { "/": 5 }
2917            })
2918        );
2919    }
2920
2921    /// Oracle: RFC 6901 §3 — `escaped = "~" ( "0" / "1" )` and "It is an
2922    /// error condition if a JSON Pointer value does not conform to this
2923    /// syntax". RFC 8620 §5.3 requires keys in JSON Pointer format, so a
2924    /// malformed escape in any token is rejected.
2925    #[test]
2926    fn apply_jmap_patch_invalid_escape_is_rejected() {
2927        let before = json!({ "a": {} });
2928        for path in ["~2", "x~", "a/~", "~x/b", "a/b~"] {
2929            assert_patch_rejected(
2930                before.clone(),
2931                path,
2932                json!(1),
2933                PatchPathError::InvalidEscape,
2934            );
2935        }
2936    }
2937
2938    /// Oracle: RFC 6901 §3 — `reference-token = *( unescaped / escaped )`
2939    /// permits an empty token, and the §5 example evaluates `"/"` to the
2940    /// member named `""` (`"" : 0`). The PatchObject key `""` is the
2941    /// pointer `"/"`; `"a/"` is the pointer `"/a/"`.
2942    #[test]
2943    fn apply_jmap_patch_empty_token_names_empty_member() {
2944        let mut target = obj(json!({ "a": {} }));
2945        apply_jmap_patch(&mut target, "", json!(0)).expect("empty top-level token");
2946        apply_jmap_patch(&mut target, "a/", json!(1)).expect("empty nested token");
2947        assert_eq!(
2948            serde_json::Value::Object(target),
2949            json!({ "": 0, "a": { "": 1 } })
2950        );
2951    }
2952
2953    /// Oracle: an empty token is an ordinary member name, so a missing
2954    /// empty-named parent is rejected like any other missing parent
2955    /// (RFC 8620 §5.3 "All parts prior to the last ... MUST already
2956    /// exist").
2957    #[test]
2958    fn apply_jmap_patch_missing_empty_parent_is_rejected() {
2959        assert_patch_rejected(
2960            json!({ "a": {} }),
2961            "a//b",
2962            json!(1),
2963            PatchPathError::ParentMissing,
2964        );
2965    }
2966
2967    // ------------------------------------------------------------------
2968    // apply_patch_object (RFC 8620 §5.3 whole PatchObject)
2969    // ------------------------------------------------------------------
2970
2971    /// Oracle: RFC 8620 §5.3 — "There MUST NOT be two patches in the
2972    /// PatchObject where the pointer of one is the prefix of the pointer
2973    /// of the other, e.g., "alerts/1/offset" and "alerts""; on violation
2974    /// "the update MUST be rejected with an "invalidPatch" error".
2975    #[test]
2976    fn apply_patch_object_prefix_conflict_is_rejected() {
2977        let before = json!({ "alerts": { "1": { "offset": 0 } } });
2978        let mut target = obj(before.clone());
2979        let patch = obj(json!({ "alerts/1/offset": 5, "alerts": {} }));
2980        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
2981        assert_eq!(err, PatchPathError::PrefixConflict);
2982        assert_eq!(serde_json::Value::Object(target), before);
2983    }
2984
2985    /// Oracle: RFC 8620 §5.3 forbids only a pointer that is "the prefix of
2986    /// the pointer of the other"; JSON Pointers are compared by reference
2987    /// token (RFC 6901 §3), so "alert" is not a prefix of "alerts/x".
2988    #[test]
2989    fn apply_patch_object_near_prefix_is_accepted() {
2990        let mut target = obj(json!({ "alerts": {} }));
2991        let patch = obj(json!({ "alert": 1, "alerts/x": 2 }));
2992        apply_patch_object(&mut target, &patch).expect("no prefix conflict");
2993        assert_eq!(
2994            serde_json::Value::Object(target),
2995            json!({ "alert": 1, "alerts": { "x": 2 } })
2996        );
2997    }
2998
2999    /// Oracle: RFC 8620 §5.3 — "if there is any violation, the update MUST
3000    /// be rejected"; the valid entry "a" must not be applied either.
3001    #[test]
3002    fn apply_patch_object_partial_failure_leaves_target_unchanged() {
3003        let before = json!({ "a": 1 });
3004        let mut target = obj(before.clone());
3005        let patch = obj(json!({ "a": 2, "m/k": 1 }));
3006        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
3007        assert_eq!(err, PatchPathError::ParentMissing);
3008        assert_eq!(serde_json::Value::Object(target), before);
3009    }
3010
3011    /// A value nesting `levels` objects deep (`0` is the scalar `1`).
3012    fn nested(levels: usize) -> serde_json::Value {
3013        (0..levels).fold(json!(1), |inner, _| json!({ "k": inner }))
3014    }
3015
3016    /// Oracle: this crate's DoS guard, not an RFC 8620 §5.3 rule (RFC 8620
3017    /// §3.6.1 lets a server reject requests beyond its limits). Path
3018    /// segments plus value nesting may not exceed `MAX_MERGE_PATCH_DEPTH`
3019    /// (32): 3 + 30 = 33 is rejected before any entry is applied.
3020    #[test]
3021    fn apply_patch_object_path_plus_value_over_depth_cap_is_rejected() {
3022        let before = json!({ "x": 1, "a": { "b": {} } });
3023        let mut target = obj(before.clone());
3024        let patch = obj(json!({ "x": 2, "a/b/c": nested(30) }));
3025        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
3026        assert_eq!(err, PatchPathError::DepthExceeded);
3027        assert_eq!(serde_json::Value::Object(target), before);
3028    }
3029
3030    /// Oracle: the crate's DoS guard rejects only depth beyond
3031    /// `MAX_MERGE_PATCH_DEPTH`; exactly 3 segments + 29 levels = 32 applies.
3032    #[test]
3033    fn apply_patch_object_path_plus_value_at_depth_cap_applies() {
3034        let mut target = obj(json!({ "a": { "b": {} } }));
3035        let patch = obj(json!({ "a/b/c": nested(29) }));
3036        apply_patch_object(&mut target, &patch).expect("at the cap must apply");
3037        assert_eq!(
3038            serde_json::Value::Object(target),
3039            json!({ "a": { "b": { "c": nested(29) } } })
3040        );
3041    }
3042
3043    /// Oracle: the crate's DoS guard; a key of 33 segments exceeds
3044    /// `MAX_MERGE_PATCH_DEPTH` even with a scalar value.
3045    #[test]
3046    fn apply_patch_object_path_over_depth_cap_is_rejected() {
3047        let before = json!({ "a": {} });
3048        let mut target = obj(before.clone());
3049        let path = format!("a{}", "/k".repeat(32));
3050        let patch = obj(json!({ path: 1 }));
3051        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
3052        assert_eq!(err, PatchPathError::DepthExceeded);
3053        assert_eq!(serde_json::Value::Object(target), before);
3054    }
3055
3056    // ------------------------------------------------------------------
3057    // enforce_max_objects_in_set (bd:JMAP-ayoz.41.1) — RFC 8620 §5.3
3058    //
3059    // Oracles for all tests below are hand-built JmapError comparisons
3060    // and hand-built JSON args; the helper itself is never the oracle.
3061    // ------------------------------------------------------------------
3062
3063    /// Oracle (RFC 8620 §5.3): an empty `/set` args envelope (no
3064    /// `create` / `update` / `destroy` keys) MUST pass any positive cap.
3065    #[test]
3066    fn enforce_max_objects_in_set_empty_args_is_ok() {
3067        let args = json!({}).as_object().unwrap().clone();
3068        enforce_max_objects_in_set(&args, 500).expect("empty args must be under any positive cap");
3069    }
3070
3071    /// Oracle (RFC 8620 §5.3): at the exact boundary count == max, the
3072    /// helper MUST return Ok. The cap is enforced as strictly-greater
3073    /// (`count > max`), not greater-or-equal.
3074    #[test]
3075    fn enforce_max_objects_in_set_at_limit_is_ok() {
3076        // 5 + 5 + 5 = 15 entries against max=15 must pass.
3077        let mut create = serde_json::Map::new();
3078        let mut update = serde_json::Map::new();
3079        let mut destroy = Vec::new();
3080        for i in 0..5 {
3081            create.insert(format!("c{i}"), json!({}));
3082            update.insert(format!("u{i}"), json!({}));
3083            destroy.push(json!(format!("d{i}")));
3084        }
3085        let args = json!({
3086            "create": create,
3087            "update": update,
3088            "destroy": destroy,
3089        })
3090        .as_object()
3091        .unwrap()
3092        .clone();
3093        enforce_max_objects_in_set(&args, 15).expect("exact-boundary count must be allowed");
3094    }
3095
3096    /// Oracle (RFC 8620 §5.3, bd:JMAP-yt1w.30): one entry over the cap
3097    /// MUST return the method error "requestTooLarge" — "The total number
3098    /// of objects to create, update, or destroy exceeds the maximum number
3099    /// the server is willing to process in a single method call." — with
3100    /// description "maxObjectsInSet". The wire shape is verified by
3101    /// hand-building the expected JmapError independently of the helper.
3102    #[test]
3103    fn enforce_max_objects_in_set_over_limit_returns_limit_error() {
3104        // 5 + 5 + 6 = 16 entries against max=15 must fail.
3105        let mut create = serde_json::Map::new();
3106        let mut update = serde_json::Map::new();
3107        let mut destroy = Vec::new();
3108        for i in 0..5 {
3109            create.insert(format!("c{i}"), json!({}));
3110            update.insert(format!("u{i}"), json!({}));
3111        }
3112        for i in 0..6 {
3113            destroy.push(json!(format!("d{i}")));
3114        }
3115        let args = json!({
3116            "create": create,
3117            "update": update,
3118            "destroy": destroy,
3119        })
3120        .as_object()
3121        .unwrap()
3122        .clone();
3123        let err = enforce_max_objects_in_set(&args, 15)
3124            .expect_err("16-entry args against max=15 must fail");
3125        // Independent oracle — hand-built JmapError, not derived from
3126        // the function under test.
3127        let expected = jmap_types::JmapError::request_too_large();
3128        assert_eq!(
3129            err.error_type.to_string(),
3130            expected.error_type.to_string(),
3131            "type must be \"requestTooLarge\""
3132        );
3133        assert_eq!(
3134            err.description.as_deref(),
3135            Some("maxObjectsInSet"),
3136            "description must name the exceeded cap"
3137        );
3138    }
3139
3140    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
3141    /// "The following additional errors may be returned instead of the
3142    /// "Foo/set" response: "requestTooLarge": The total number of objects
3143    /// to create, update, or destroy exceeds the maximum number the server
3144    /// is willing to process in a single method call." Exceeding
3145    /// maxObjectsInSet is therefore the method-level error
3146    /// `requestTooLarge`, not the request-level `limit` error.
3147    #[test]
3148    fn enforce_max_objects_in_set_over_limit_returns_request_too_large() {
3149        let mut create = serde_json::Map::new();
3150        for i in 0..3 {
3151            create.insert(format!("c{i}"), json!({}));
3152        }
3153        let args = json!({
3154            "create": create,
3155            "destroy": ["d0"],
3156        })
3157        .as_object()
3158        .unwrap()
3159        .clone();
3160        let err =
3161            enforce_max_objects_in_set(&args, 3).expect_err("4-entry args against max=3 must fail");
3162        assert_eq!(
3163            err.error_type.to_string(),
3164            "requestTooLarge",
3165            "RFC 8620 §5.3: over-cap /set must yield method error requestTooLarge"
3166        );
3167    }
3168
3169    /// Oracle (RFC 8620 §5.3): a non-object `create` argument (e.g.
3170    /// `null` or a string) counts as 0 — wire-shape validation belongs
3171    /// to the per-handler argument parsing, not this cap helper. The
3172    /// handler will reject the malformed `create` downstream; this
3173    /// helper only counts well-formed entries.
3174    #[test]
3175    fn enforce_max_objects_in_set_ignores_non_object_create() {
3176        let args = json!({
3177            "create": null,
3178            "update": null,
3179            "destroy": ["id1"],
3180        })
3181        .as_object()
3182        .unwrap()
3183        .clone();
3184        // Only the 1 destroy entry counts.
3185        enforce_max_objects_in_set(&args, 1).expect("non-object create/update count as 0");
3186    }
3187
3188    /// Oracle (RFC 8620 §5.3): a non-array `destroy` argument counts
3189    /// as 0. Same rationale as the create/update test above.
3190    #[test]
3191    fn enforce_max_objects_in_set_ignores_non_array_destroy() {
3192        let args = json!({
3193            "create": { "c0": {} },
3194            "destroy": "not-an-array",
3195        })
3196        .as_object()
3197        .unwrap()
3198        .clone();
3199        // Only the 1 create entry counts.
3200        enforce_max_objects_in_set(&args, 1).expect("non-array destroy counts as 0");
3201    }
3202
3203    /// Oracle (RFC 8620 §5.3): the cap counts the SUM of all three
3204    /// sources. A request whose individual create/update/destroy
3205    /// counts are each below the cap can still trip the cap when
3206    /// summed.
3207    #[test]
3208    fn enforce_max_objects_in_set_sums_all_three() {
3209        // 3 + 3 + 3 = 9; against max=5, must fail because the SUM > max
3210        // even though each individual count <= max.
3211        let args = json!({
3212            "create": { "c0": {}, "c1": {}, "c2": {} },
3213            "update": { "u0": {}, "u1": {}, "u2": {} },
3214            "destroy": ["d0", "d1", "d2"],
3215        })
3216        .as_object()
3217        .unwrap()
3218        .clone();
3219        let err =
3220            enforce_max_objects_in_set(&args, 5).expect_err("sum-of-all-three must trip the cap");
3221        assert_eq!(err.error_type.to_string(), "requestTooLarge");
3222        assert_eq!(err.description.as_deref(), Some("maxObjectsInSet"));
3223    }
3224
3225    /// Oracle (RFC 8620 §5.5 + bd:JMAP-qz9v.48): `position` is a signed
3226    /// offset where non-negative is absolute and negative is
3227    /// end-relative. All hand-computed values below come from reading
3228    /// the spec text, NOT from the implementation under test.
3229    #[test]
3230    fn resolve_query_offset_absolute() {
3231        // Non-negative position: absolute offset, clamped at total.
3232        assert_eq!(resolve_query_offset(0, 100), 0);
3233        assert_eq!(resolve_query_offset(1, 100), 1);
3234        assert_eq!(resolve_query_offset(50, 100), 50);
3235        assert_eq!(resolve_query_offset(99, 100), 99);
3236        assert_eq!(resolve_query_offset(100, 100), 100);
3237        // Past-the-end → clamped to total (RFC 8620 §5.5 silent-clamp).
3238        assert_eq!(resolve_query_offset(101, 100), 100);
3239        assert_eq!(resolve_query_offset(10_000, 100), 100);
3240        assert_eq!(resolve_query_offset(i64::MAX, 100), 100);
3241    }
3242
3243    #[test]
3244    fn resolve_query_offset_end_relative() {
3245        // RFC 8620 §5.5: "-1 represents the last entry, -2 the second
3246        // to last". Implemented as `total - |position|`, saturating at
3247        // 0 from below.
3248        assert_eq!(resolve_query_offset(-1, 100), 99);
3249        assert_eq!(resolve_query_offset(-2, 100), 98);
3250        assert_eq!(resolve_query_offset(-99, 100), 1);
3251        assert_eq!(resolve_query_offset(-100, 100), 0);
3252        // Past-the-start → clamped to 0.
3253        assert_eq!(resolve_query_offset(-101, 100), 0);
3254        assert_eq!(resolve_query_offset(-10_000, 100), 0);
3255    }
3256
3257    /// Oracle: with total=0 (empty result list), every position
3258    /// resolves to 0 (the only valid index, and a no-op slice).
3259    #[test]
3260    fn resolve_query_offset_empty_total() {
3261        assert_eq!(resolve_query_offset(0, 0), 0);
3262        assert_eq!(resolve_query_offset(1, 0), 0);
3263        assert_eq!(resolve_query_offset(-1, 0), 0);
3264        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
3265        assert_eq!(resolve_query_offset(i64::MIN, 0), 0);
3266    }
3267
3268    /// Oracle: `i64::MIN` would overflow `-position` (the previous
3269    /// workspace idiom at mail-server `memory/mod.rs:980`) but
3270    /// `saturating_neg` returns `i64::MAX`. The resulting end-relative
3271    /// offset of `i64::MAX` is well past any realistic `total`, so for
3272    /// any realistic total the result is 0.
3273    ///
3274    /// For the synthetic case `total == usize::MAX`, the offset stays
3275    /// within the saturation range and the result is
3276    /// `usize::MAX - i64::MAX`, which on a 64-bit target is exactly
3277    /// `0x8000_0000_0000_0000`. The point of the regression guard is
3278    /// that the call does NOT panic (which it would under the prior
3279    /// `(-position) as usize` idiom in debug builds).
3280    /// Oracle: RFC 8620 §5.5 `limit` -- "If null, no limit presumed" --
3281    /// so `None` is unbounded; `Some(n)` is exactly `n` items.
3282    #[test]
3283    fn limit_or_max_follows_rfc8620_limit_semantics() {
3284        let items = [1u8, 2, 3, 4, 5];
3285        assert_eq!(items.iter().take(limit_or_max(None)).count(), 5);
3286        assert_eq!(items.iter().take(limit_or_max(Some(0))).count(), 0);
3287        assert_eq!(items.iter().take(limit_or_max(Some(2))).count(), 2);
3288        // u64::MAX never truncates to a small count: on 64-bit it is
3289        // exactly usize::MAX, on 32-bit it saturates to usize::MAX.
3290        assert_eq!(limit_or_max(Some(u64::MAX)), usize::MAX);
3291    }
3292
3293    #[test]
3294    fn resolve_query_offset_i64_min_does_not_overflow() {
3295        assert_eq!(resolve_query_offset(i64::MIN, 1), 0);
3296        assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
3297        assert_eq!(resolve_query_offset(i64::MIN, i64::MAX as usize), 0);
3298        // Synthetic upper bound: the answer is computable but not 0.
3299        // What matters is no overflow / no panic, and start <= total.
3300        let start = resolve_query_offset(i64::MIN, usize::MAX);
3301        assert_eq!(start, usize::MAX - (i64::MAX as usize));
3302        // And `i64::MAX` on the positive side is also handled.
3303        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
3304        assert_eq!(resolve_query_offset(i64::MAX, 1), 1);
3305    }
3306
3307    /// Oracle: the bead's specific concern was that `position as usize`
3308    /// truncates on 32-bit targets. On 64-bit (this test host) the
3309    /// `i64`-to-`usize` conversion is lossless within `[0, i64::MAX]`,
3310    /// so the truncation cannot be directly demonstrated; what we CAN
3311    /// verify is that the helper uses `usize::try_from` semantics, so
3312    /// a value above `i64::MAX` (only reachable here via direct cast
3313    /// from an unsigned constant) clamps to `total` rather than
3314    /// wrapping. The `i64::MIN` case in the prior test is the real
3315    /// regression guard.
3316    #[test]
3317    fn resolve_query_offset_truncation_resistant() {
3318        // The slice-safety property: `total..=total` is always a valid
3319        // start index for `slice[start..]` (yields empty slice). The
3320        // helper MUST return a value in `0..=total`.
3321        for &pos in &[i64::MIN, -1_000_000, -1, 0, 1, 1_000_000, i64::MAX] {
3322            for &total in &[0usize, 1, 100, 10_000] {
3323                let start = resolve_query_offset(pos, total);
3324                assert!(
3325                    start <= total,
3326                    "resolve_query_offset({pos}, {total}) = {start} violates start <= total"
3327                );
3328            }
3329        }
3330    }
3331    /// Oracle: RFC 8620 §5.5 (https://www.rfc-editor.org/rfc/rfc8620.txt):
3332    /// "If found, the "anchorOffset" is then added to its index.  If the
3333    /// resulting index is now negative, it is clamped to 0. ... If the
3334    /// anchor is not found, the call is rejected with an "anchorNotFound"
3335    /// error.  If an "anchor" is specified, any position argument supplied
3336    /// by the client MUST be ignored.  If no "anchor" is supplied, any
3337    /// "anchorOffset" argument MUST be ignored."
3338    ///
3339    /// `ids` is `[a, b, c, d]`, so anchor `c` is index 2.
3340    #[test]
3341    fn resolve_query_start_follows_rfc8620_anchor_rules() {
3342        let ids: Vec<jmap_types::Id> = ["a", "b", "c", "d"].map(jmap_types::Id::from).to_vec();
3343        let c = jmap_types::Id::from("c");
3344        let start = |position, anchor, offset| resolve_query_start(&ids, position, anchor, offset);
3345        assert_eq!(start(0, Some(&c), 1), Ok(3));
3346        assert_eq!(start(0, Some(&c), -1), Ok(1));
3347        assert_eq!(start(0, Some(&c), -5), Ok(0));
3348        assert_eq!(start(3, Some(&c), 0), Ok(2));
3349        assert_eq!(start(1, None, 2), Ok(1));
3350        let missing = jmap_types::Id::from("z");
3351        assert_eq!(
3352            start(0, Some(&missing), 0).map_err(|e| e.error_type.to_string()),
3353            Err("anchorNotFound".to_owned())
3354        );
3355    }
3356
3357    /// RFC 8620 §5.2: "the value MUST be a positive integer greater than
3358    /// 0. If a value outside of this range is given, the server MUST
3359    /// reject the call with an "invalidArguments" error." The argument is
3360    /// `UnsignedInt|null`, so absent and `null` mean "not given".
3361    #[test]
3362    fn parse_max_changes_follows_rfc8620_5_2() {
3363        assert_eq!(parse_max_changes(None).ok(), Some(None));
3364        assert_eq!(parse_max_changes(Some(&json!(null))).ok(), Some(None));
3365        assert_eq!(parse_max_changes(Some(&json!(1))).ok(), Some(Some(1)));
3366        assert_eq!(parse_max_changes(Some(&json!(50))).ok(), Some(Some(50)));
3367        for bad in [json!(0), json!(-1), json!(1.5), json!("5"), json!(true)] {
3368            assert_eq!(
3369                parse_max_changes(Some(&bad)).map_err(|e| e.error_type.to_string()),
3370                Err("invalidArguments".to_owned()),
3371                "maxChanges = {bad} must be rejected"
3372            );
3373        }
3374    }
3375
3376    /// Oracle: the six JSON value kinds of RFC 8259 §3 ("object, array,
3377    /// number, string ... false, null, true"), with `true`/`false` named
3378    /// "boolean", written out by hand.
3379    #[test]
3380    fn json_type_name_names_each_json_kind() {
3381        let cases = [
3382            (json!(null), "null"),
3383            (json!(true), "boolean"),
3384            (json!(false), "boolean"),
3385            (json!(-1.5), "number"),
3386            (json!("CANARY-zegc"), "string"),
3387            (json!([1, 2]), "array"),
3388            (json!({ "note": "CANARY-zegc" }), "object"),
3389        ];
3390        for (value, want) in cases {
3391            assert_eq!(json_type_name(&value), want, "{value}");
3392        }
3393    }
3394
3395    /// RFC 8620 §5.5 types `anchor` as "Id|null" and `anchorOffset` as
3396    /// "Int"; wrong types are `invalidArguments` (§3.6.2). The description
3397    /// names only the JSON type and never echoes the client value
3398    /// (§3.6.1: "unstructured English text"; bd JMAP-zegc).
3399    #[test]
3400    fn query_anchor_args_does_not_echo_wrongly_typed_value() {
3401        for (name, args) in [
3402            ("anchor", json!({ "anchor": { "note": "CANARY-zegc" } })),
3403            (
3404                "anchorOffset",
3405                json!({ "anchorOffset": { "note": "CANARY-zegc" } }),
3406            ),
3407        ] {
3408            let err = query_anchor_args(args.as_object().expect("object"))
3409                .expect_err("wrongly typed argument must be rejected");
3410            assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
3411            let desc = err.description.as_deref().unwrap_or_default();
3412            assert!(desc.starts_with(name), "{desc}");
3413            assert!(desc.contains("got object"), "{desc}");
3414            assert!(!desc.contains("CANARY"), "{desc}");
3415        }
3416    }
3417}