Skip to main content

jmap_server/
helpers.rs

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