Skip to main content

jmap_server/
helpers.rs

1//! Shared helper utilities for JMAP method handlers.
2
3use std::borrow::Cow;
4
5use jmap_types::{Id, JmapError, UTCDate};
6use serde_json::{Map, Value};
7
8/// Serialize any [`serde::Serialize`] type to a [`serde_json::Value`],
9/// mapping serialization errors to [`JmapError::server_fail`].
10///
11/// Used by every `*-server` handler to project a typed domain object
12/// (e.g. `Email`, `Mailbox`, `Chat`) into the wire-format `list` /
13/// `created` payload.
14pub fn serialize_value<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
15    serde_json::to_value(val).map_err(|e| JmapError::server_fail(e.to_string()))
16}
17
18/// Deprecated alias for [`serialize_value`] (bd:JMAP-wlip.21).
19///
20/// The opaque 3-letter name was hard to read in consumer code
21/// (`let v = ser(x)?;` left readers grepping three crates to learn
22/// what `ser` did) and collided with the common local-variable name
23/// `ser`. Use [`serialize_value`] instead. This alias is preserved
24/// for one release as a deprecation runway; it will be removed in
25/// the next major.
26// bd:JMAP-jfia.6 — the `since` field was previously set to "0.1.3"
27// while the crate version was still 0.1.2, which rendered as
28// "deprecated in the FUTURE" in cargo doc / docs.rs. Drop `since`
29// until the release that ships the renaming actually goes out; the
30// version-pinned form will be reintroduced when 0.1.3 is published.
31#[deprecated(note = "renamed to serialize_value (bd:JMAP-wlip.21)")]
32pub fn ser<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
33    serialize_value(val)
34}
35
36/// Convert a slice of [`Id`]s to a JSON `notFound` value.
37///
38/// RFC 8620 §5.1 specifies `notFound` as `Id[]` — always an array, never
39/// `null`. Returns an empty array when all requested ids were found.
40///
41/// Equivalent to `serde_json::to_value(ids)` but threads through
42/// `Value::Array` directly so the call site is infallible (bd:JMAP-wlip.28).
43pub fn not_found_json(ids: &[Id]) -> Value {
44    Value::Array(
45        ids.iter()
46            .map(|id| Value::String(id.as_ref().to_owned()))
47            .collect(),
48    )
49}
50
51/// Extract an optional, deserializable argument from a method-arguments
52/// envelope (bd:JMAP-wlip.32).
53///
54/// Looks up `name` in `args`, removing it. The result is:
55///
56/// - `Ok(None)` if the key is absent OR is present with `Value::Null`
57///   (RFC 8620 §3.3 treats absent and explicit-null the same for
58///   optional fields).
59/// - `Ok(Some(value))` if the key is present and the value
60///   deserializes successfully into `T`.
61/// - `Err(invalid_arguments_with(name))` if the value is present but
62///   fails to deserialize. The error message is built by the caller-
63///   supplied `invalid_arguments_with` so the resulting `JmapError`
64///   carries a domain-specific description ("ids must be an Id
65///   array", "filter must be a Filter object", etc.).
66///
67/// Collapses six near-identical
68/// `match args.remove(...).unwrap_or(Value::Null) { Value::Null => None,
69/// v => Some(serde_json::from_value(v)...) }` blocks in `handlers.rs`
70/// into one-liners.
71///
72/// # Interaction with `ResultReference` resolution (bd:JMAP-jfia.15)
73///
74/// [`crate::parse::resolve_args`] replaces a `#key` with the value
75/// produced by walking the JSON Pointer path against a prior
76/// response. RFC 6901 §4 makes no distinction between "key absent"
77/// and "key present with `null`", so the resolved value CAN be
78/// `Value::Null`. This function then treats that resolved-null
79/// identically to "key was not sent". The behaviour is
80/// RFC-compliant — both are "optional argument not provided" — but
81/// the asymmetry between an explicit `null` argument and a
82/// `#key`-resolved `null` argument may surprise a handler author
83/// who expects "I asked for the value via a ResultReference, so it
84/// must have been there". If a handler needs to distinguish
85/// resolved-null from unsent, it has to read the raw `args` map
86/// before calling this helper.
87pub fn optional_arg<T>(
88    args: &mut Map<String, Value>,
89    name: &str,
90    invalid_arguments_with: impl FnOnce() -> JmapError,
91) -> Result<Option<T>, JmapError>
92where
93    T: serde::de::DeserializeOwned,
94{
95    match args.remove(name).unwrap_or(Value::Null) {
96        Value::Null => Ok(None),
97        v => Ok(Some(
98            serde_json::from_value(v).map_err(|_| invalid_arguments_with())?,
99        )),
100    }
101}
102
103/// Remove and decode the optional `filter` argument of a hand-written
104/// `/query` or `/queryChanges` handler (RFC 8620 §5.5).
105///
106/// Absent or `null` yields `None`. A value that is not a JSON object is
107/// not a filter at all and yields `invalidArguments`. An object that does
108/// not decode as `T` yields `unsupportedFilter` ("The "filter" is
109/// syntactically valid, but the server cannot process it") with the serde
110/// message as its description. With `deny_unknown_fields` on the filter
111/// types, that covers an unknown or misspelt condition property at any
112/// depth and an operator tree sent to an object whose filter is a bare
113/// condition.
114pub fn filter_arg<T>(args: &mut Map<String, Value>) -> Result<Option<T>, JmapError>
115where
116    T: serde::de::DeserializeOwned,
117{
118    match args.remove("filter").unwrap_or(Value::Null) {
119        Value::Null => Ok(None),
120        v @ Value::Object(_) => serde_json::from_value(v).map(Some).map_err(|e| {
121            let mut err = JmapError::unsupported_filter();
122            err.description = Some(format!("filter: {e}"));
123            err
124        }),
125        v => Err(JmapError::invalid_arguments(format!(
126            "filter: expected an object, got {v}"
127        ))),
128    }
129}
130
131/// Read an optional boolean argument from a method-arguments envelope without
132/// removing it (bd:JMAP-ic0j.39).
133///
134/// Returns `default` if `key` is absent, if the value is not a boolean, or if
135/// the value is `Value::Null`. This is the canonical workspace helper for
136/// JMAP's "permissive parsing" convention on optional boolean controls
137/// (RFC 8620 §3.6.1 — unknown / non-typed values coerce to the spec default).
138///
139/// Use [`take_bool_arg`] if the caller wants to consume the entry as part of
140/// a "walk the args map removing as we go" pattern.
141///
142/// Collapses ~50 near-identical
143/// `args.get(K).and_then(|v| v.as_bool()).unwrap_or(default)` blocks across
144/// the extension-server family into single-line calls.
145pub fn bool_arg(args: &Map<String, Value>, key: &str, default: bool) -> bool {
146    args.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
147}
148
149/// Read an optional boolean argument from a method-arguments envelope,
150/// removing it from the map (bd:JMAP-ic0j.39).
151///
152/// Returns `default` if `key` is absent, if the value is not a boolean, or if
153/// the value is `Value::Null`. Mirrors the semantics of [`bool_arg`] but
154/// consumes the entry from `args`. Matches the canonical mail-server
155/// "remove-as-we-go" parsing pattern.
156pub fn take_bool_arg(args: &mut Map<String, Value>, key: &str, default: bool) -> bool {
157    args.remove(key)
158        .and_then(|v| v.as_bool())
159        .unwrap_or(default)
160}
161
162/// Extract `accountId` from a JMAP method arguments envelope and return both
163/// the extracted [`Id`] and the remaining argument map.
164///
165/// The caller passes the full `args: Value` from the method invocation by
166/// value; this function destructures it once, so handlers do not have to
167/// repeat the `let Value::Object(mut args) = args else { ... }` pattern after
168/// every call.
169///
170/// # Errors
171///
172/// Returns `invalidArguments` with:
173///
174/// - `"arguments must be an object containing accountId"` when `args` is
175///   not a JSON object.
176/// - `"accountId is required"` when the field is missing or not a string.
177/// - `"accountId is not a valid Id: <reason>"` when the field is a string
178///   but does not satisfy the RFC 8620 §1.2 Id grammar
179///   (`Id::new_validated`). Catches empty strings, strings longer than
180///   255 bytes, and strings containing characters outside the SAFE-CHAR
181///   set (`%x21 / %x23-7E` — visible ASCII excluding `"`).
182///   bd:JMAP-wlip.5 closed the previous silent-pass-through behaviour
183///   where a malformed accountId reached the backend's `account_exists`
184///   call and surfaced as either `notFound` or a storage-layer parse
185///   error, depending on the backend.
186pub fn extract_account_id(args: Value) -> Result<(Id, Map<String, Value>), JmapError> {
187    let Value::Object(mut args) = args else {
188        return Err(JmapError::invalid_arguments(
189            "arguments must be an object containing accountId",
190        ));
191    };
192    // Remove (not get) the accountId entry so the returned args map no
193    // longer carries it (bd:JMAP-jfia.9). This matches optional_arg's
194    // remove-and-consume semantics and prevents downstream handlers
195    // from re-parsing the validated id or seeing it as an unexpected
196    // residual key.
197    let raw = args
198        .remove("accountId")
199        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
200    let s = raw
201        .as_str()
202        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
203    let id = Id::new_validated(s)
204        .map_err(|e| JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}")))?;
205    Ok((id, args))
206}
207
208/// Return the current UTC instant as an [`UTCDate`] (RFC 3339,
209/// millisecond precision, format `YYYY-MM-DDTHH:MM:SS.mmmZ`).
210///
211/// Uses `std::time::SystemTime` so no external dependency is needed.
212///
213/// Returns a typed [`UTCDate`] rather than a `String` (bd:JMAP-wlip.20)
214/// so callers do not need to wrap the result in
215/// `UTCDate::from(now_utc_string().as_str())`. The function name is
216/// retained for back-compat across the workspace's many call sites.
217///
218/// The string the [`UTCDate`] wraps does not pass
219/// [`UTCDate::new_validated`] because that validator requires exactly
220/// the 20-char `YYYY-MM-DDTHH:MM:SSZ` form (no millis) and this helper
221/// emits the 24-char form with millis. The workspace convention is to
222/// use the 24-char form on the wire — consumers wanting strict
223/// validation should construct their own `UTCDate::new_validated` value
224/// from a `chrono`-formatted source.
225///
226/// Pre-epoch handling: `SystemTime::now().duration_since(UNIX_EPOCH)`
227/// fails on clocks drifted before the epoch. The function uses
228/// `Err::duration()` to recover the magnitude and negates the seconds
229/// before formatting; the result is a correct RFC 3339 timestamp
230/// anywhere from the BCE proleptic Gregorian range up to
231/// `1970-01-01T00:00:00.000Z`. The rem_euclid / div_euclid math at
232/// the format step handles arbitrarily-large negative offsets, not
233/// only sub-day drifts. Pre-epoch correctness is best-effort —
234/// `SystemTime` is non-monotonic and the JMAP spec does not require
235/// pre-epoch timestamps. (bd:JMAP-wlip.11 corrected the previous
236/// docstring's incorrect "1969-12-31T… through 1970-01-01T00:00:00Z"
237/// range claim.)
238///
239/// Clock-overflow handling: on a corrupted clock (system clock
240/// reporting a Duration whose `as_secs()` exceeds `i64::MAX`,
241/// `civil_from_days` reporting a year outside `i32`, or any other
242/// `SystemTime` failure mode), this function **panics**. The
243/// previous sentinel-string behaviour (`UTCDate::from("clock-out-of-range")`)
244/// was an idiom-grade defect (bd:JMAP-jfia.30): the sentinel was not a
245/// valid wire-format timestamp, had no in-band signal to distinguish
246/// it from a real value, and could silently propagate into JSON
247/// responses, audit logs, and database rows.
248///
249/// Callers that need to handle clock failure without panicking MUST
250/// use [`now_utc_string_checked`], which returns `Option<UTCDate>`.
251/// Long-running daemons, schedulers, and persistence layers SHOULD
252/// prefer the checked variant; one-shot tools and request handlers
253/// MAY accept the panic since clock corruption is unrecoverable and
254/// the dispatcher's `task::spawn` isolation already converts the
255/// panic into a `serverFail` invocation rather than crashing the
256/// process.
257///
258/// # Panics
259///
260/// Panics if `SystemTime::now()` cannot be expressed as an RFC 3339
261/// timestamp — the same conditions under which
262/// [`now_utc_string_checked`] returns `None`.
263pub fn now_utc_string() -> UTCDate {
264    now_utc_string_checked().expect("system clock returned an out-of-range value (bd:JMAP-jfia.30)")
265}
266
267/// Return the current UTC instant as an [`UTCDate`] (RFC 3339,
268/// millisecond precision, format `YYYY-MM-DDTHH:MM:SS.mmmZ`), or
269/// `None` if the system clock cannot be expressed as an RFC 3339
270/// timestamp.
271///
272/// Added in bd:JMAP-jfia.30 to replace the previous sentinel-string
273/// failure mode of [`now_utc_string`] with a typed `Option` shape.
274/// Callers that want to react to a clock fault (audit-log
275/// timestamps, last-seen markers, retention sweeps) SHOULD use this
276/// variant; callers for whom a panic at the first sign of clock
277/// corruption is acceptable MAY use [`now_utc_string`] directly.
278///
279/// Returns `None` when:
280/// - `SystemTime::now().duration_since(UNIX_EPOCH).as_secs()`
281///   exceeds `i64::MAX` (only reachable on a corrupted clock —
282///   approx ±292 billion years from epoch).
283/// - The negation of a pre-epoch duration overflows `i64`
284///   (unreachable on a `try_from`-validated input but checked
285///   defensively).
286/// - `civil_from_days` reports a year outside `i32`
287///   (bd:JMAP-jfia.2 — between the i32-year boundary and the
288///   i64::MAX-secs cap).
289///
290/// # Why `Option<UTCDate>` and not `Result<UTCDate, ClockError>` (bd:JMAP-jfia.38)
291///
292/// The three failure modes are all "corrupted clock" — each one is
293/// physically unreachable on a sane host (years 5.7M-to-292B,
294/// `try_from`-impossible negation, `i32`-overflowing year). A caller
295/// that wants to branch on which physical mechanism fired would be
296/// branching on states that don't happen. The shapes the workspace
297/// uses elsewhere for typed-variant-per-mode (`SetError`,
298/// `BackendChangesError`, `BackendSetError`, `MergePatchError`) all
299/// carry failure modes that DO occur in normal operation —
300/// `notFound`, `tooManyChanges`, `invalidPatch`, `depthExceeded`.
301/// The clock-corruption modes are different in kind. Erasing the
302/// discriminator here trades a hypothetical observability win for a
303/// cleaner contract: "the clock is unusable for RFC 3339, abandon
304/// timestamping." A future need for per-mode telemetry can be added
305/// non-breakingly as a parallel helper (e.g. `now_utc_string_diagnose
306/// -> Result<UTCDate, ClockError>`) without disturbing this shape.
307pub fn now_utc_string_checked() -> Option<UTCDate> {
308    use std::time::SystemTime;
309
310    let (secs, millis) = signed_seconds_since_epoch(SystemTime::now())?;
311
312    let s = secs.rem_euclid(60);
313    let m = (secs / 60).rem_euclid(60);
314    let h = (secs / 3600).rem_euclid(24);
315    let days = secs.div_euclid(86400);
316    let (year, month, day) = civil_from_days(days)?;
317
318    Some(UTCDate::from(format!(
319        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{millis:03}Z"
320    )))
321}
322
323/// Convert a [`SystemTime`] into `(signed_seconds_since_epoch, millis)`,
324/// returning `None` when the system clock cannot be expressed as an
325/// `i64` second count.
326///
327/// Extracted from [`now_utc_string_checked`] in bd:JMAP-jfia.11 to
328/// flatten the previous three-level nested match
329/// (`duration_since` → `try_from` → `checked_neg`) into one
330/// linear function the reader can scan top-to-bottom. The
331/// `.checked_neg()` branch is unreachable on a `try_from`-validated
332/// input (its output is `[0, i64::MAX]` so negation cannot underflow)
333/// but is kept for defence in depth — the failure path stays total.
334pub(crate) fn signed_seconds_since_epoch(now: std::time::SystemTime) -> Option<(i64, u32)> {
335    use std::time::UNIX_EPOCH;
336    match now.duration_since(UNIX_EPOCH) {
337        Ok(d) => {
338            let s = i64::try_from(d.as_secs()).ok()?;
339            Some((s, d.subsec_millis()))
340        }
341        Err(e) => {
342            // Pre-epoch clock — negate after the fallible widen so we
343            // can return a real (negative) epoch offset rather than
344            // silently snapping to 1970-01-01T00:00:00Z.
345            let d = e.duration();
346            let s = i64::try_from(d.as_secs()).ok()?;
347            let neg = s.checked_neg()?;
348            Some((neg, d.subsec_millis()))
349        }
350    }
351}
352
353/// Format `secs` seconds since the Unix epoch as a seconds-precision
354/// [`UTCDate`] (`YYYY-MM-DDTHH:MM:SSZ`, RFC 8620 §1.4), or `None` if the
355/// year falls outside `0000..=9999`, which that four-digit form cannot
356/// express.
357///
358/// This is the inverse of [`UTCDate::to_epoch_seconds`], which accepts only
359/// this form. [`now_utc_string`] adds milliseconds, so its output does not
360/// round-trip through `to_epoch_seconds`.
361pub fn utc_date_from_epoch_seconds(secs: i64) -> Option<UTCDate> {
362    let time_of_day = secs.rem_euclid(86400);
363    let (h, m, s) = (
364        time_of_day / 3600,
365        time_of_day % 3600 / 60,
366        time_of_day % 60,
367    );
368    let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;
369    if !(0..=9999).contains(&year) {
370        return None;
371    }
372    Some(UTCDate::from(format!(
373        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}Z"
374    )))
375}
376
377/// Convert a count of days since the Unix epoch (1970-01-01) to a proleptic
378/// Gregorian (year, month, day) triple, or `None` if the resulting year
379/// does not fit in `i32`.
380///
381/// Algorithm by Howard Hinnant (public domain):
382/// <https://howardhinnant.github.io/date_algorithms.html>
383///
384/// The year-narrowing cast is fallible because the algorithm's intermediate
385/// `y` value is bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a subset
386/// of which fits in `i32` (~±2.1e9 years). For a sane `SystemTime`-derived
387/// input we stay well inside `i32::MIN..=i32::MAX`, but the outer
388/// `now_utc_string` only rejects `u64` seconds exceeding `i64::MAX`
389/// (bd:JMAP-wlip.27 sentinel) — inputs between the i32-year boundary
390/// (~5.7e6 years from epoch) and that sentinel reach this function and
391/// previously panicked the dispatcher worker (bd:JMAP-jfia.2). Returning
392/// `None` lets the caller fall through to its own sentinel rather than
393/// taking down the task.
394///
395/// Month and day cannot fail: the algorithm's modular structure pins them
396/// to `[1, 12]` and `[1, 31]` respectively, narrow casts handled with
397/// `try_from(...).expect(...)` documenting the invariant.
398fn civil_from_days(z: i64) -> Option<(i32, u8, u8)> {
399    let z = z + 719_468;
400    let era: i64 = if z >= 0 { z } else { z - 146_096 } / 146_097;
401    let doe = z - era * 146_097; // [0, 146096]
402    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
403    let y = yoe + era * 400;
404    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
405    let mp = (5 * doy + 2) / 153; // [0, 11]
406    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
407    let mo = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
408    let yr = if mo <= 2 { y + 1 } else { y };
409    Some((
410        i32::try_from(yr).ok()?,
411        u8::try_from(mo).expect("month bounded by algorithm to [1, 12]"),
412        u8::try_from(d).expect("day bounded by algorithm to [1, 31]"),
413    ))
414}
415
416/// Maximum recursion depth for [`json_merge_patch`] application.
417///
418/// Beyond this depth [`json_merge_patch`] returns
419/// [`MergePatchError::DepthExceeded`] without applying any further levels.
420/// Mitigates stack DoS from adversarial `PatchObject` values
421/// (bd:JMAP-sc1b.97). 32 levels comfortably exceeds any legitimate JMAP
422/// `/set update` shape — the deepest standard JMAP `/set update` shape
423/// (Email with nested `bodyStructure`) tops out around 6 levels, so the
424/// cap fires only on adversarial input.
425///
426/// Crate-private (bd:JMAP-wlip.4): consumers see the cap-exceeded
427/// behaviour via [`MergePatchError::DepthExceeded`], not by reading the
428/// constant directly. The crate reserves the right to tighten the
429/// value (e.g. 32 → 16) without a major-version bump because the
430/// contract is "the function may return DepthExceeded", not "the cap
431/// is exactly N".
432pub(crate) const MAX_MERGE_PATCH_DEPTH: usize = 32;
433
434/// Error returned by [`json_merge_patch`] when a patch cannot be applied.
435///
436/// Marked `#[non_exhaustive]` so future RFC 7396 failure modes (e.g. a
437/// size cap in addition to the depth cap) can be added without an API
438/// break.
439#[non_exhaustive]
440#[derive(Debug, Clone, PartialEq, Eq)]
441pub enum MergePatchError {
442    /// The patch nests deeper than the crate's `MAX_MERGE_PATCH_DEPTH`
443    /// DoS-guard cap.
444    ///
445    /// Callers SHOULD map this to
446    /// [`SetError`](crate::SetError) with
447    /// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch)
448    /// and MUST discard any partially-mutated `target` rather than
449    /// persisting it — see the contract on [`json_merge_patch`].
450    ///
451    /// # Why no `reached` / `max` payload (bd:JMAP-jfia.39)
452    ///
453    /// The variant is intentionally unit-shaped. The cap value is
454    /// available in the `Display` impl (which interpolates
455    /// `MAX_MERGE_PATCH_DEPTH`) for log-line and user-message use.
456    /// A typed payload `{ reached: usize, max: usize }` was
457    /// considered and rejected for now because (a) no current
458    /// consumer in the workspace destructures the reached depth or
459    /// the cap programmatically — all 6 call sites map to
460    /// `SetErrorType::InvalidPatch` with a generic description; and
461    /// (b) changing a unit variant to a struct variant is a breaking
462    /// pattern-match change even on a `#[non_exhaustive]` enum (the
463    /// existing `if let Err(MergePatchError::DepthExceeded)` pattern
464    /// would stop compiling). If a future consumer needs
465    /// programmatic access to the depth, the additive evolution is
466    /// to add a new variant alongside (e.g.
467    /// `DepthExceededDetail { reached: usize, max: usize }`) and
468    /// emit the new variant from `json_merge_patch`. The unit
469    /// variant would then become unreachable but remain valid
470    /// pattern syntax for any pinned-version consumer.
471    DepthExceeded,
472}
473
474impl std::fmt::Display for MergePatchError {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        match self {
477            Self::DepthExceeded => write!(
478                f,
479                "merge patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels"
480            ),
481        }
482    }
483}
484
485impl std::error::Error for MergePatchError {}
486
487/// Apply a JSON Merge Patch (RFC 7396) to `target` in-place.
488///
489/// Used by every `*-server` backend's `update_object` implementation
490/// to merge a sparse `/set update` patch into the stored serialized
491/// object. Extracted from per-crate copies in bd:JMAP-sc1b.103 — keep
492/// edits here so all five reference backends stay byte-identical.
493///
494/// # Errors
495///
496/// Returns [`MergePatchError::DepthExceeded`] when the patch nests
497/// deeper than the crate's internal `MAX_MERGE_PATCH_DEPTH` DoS-guard
498/// cap (added in bd:JMAP-sc1b.97, made non-silent in bd:JMAP-wlip.1).
499/// The exact value is intentionally not exposed; consumers see the
500/// behaviour via the typed error rather than reading the constant.
501/// Below the cap the behaviour is exactly RFC 7396 and the call always
502/// returns `Ok(())`.
503///
504/// # Partial-mutation contract
505///
506/// On `Err(DepthExceeded)`, `target` may have been mutated up to the
507/// level where the cap fired — RFC 7396 merging is applied recursively
508/// in place and the function does not roll back on error. Callers MUST
509/// discard `target` rather than persist it. The standard pattern in
510/// every `*-server` `update_object` impl is to operate on a `.clone()`
511/// of the stored value and only `insert(...)` it back on `Ok(())`; that
512/// pattern is naturally safe because the stored value is left untouched
513/// on error.
514pub fn json_merge_patch(target: &mut Value, patch: Value) -> Result<(), MergePatchError> {
515    json_merge_patch_inner(target, patch, 0)
516}
517
518fn json_merge_patch_inner(
519    target: &mut Value,
520    patch: Value,
521    depth: usize,
522) -> Result<(), MergePatchError> {
523    if depth > MAX_MERGE_PATCH_DEPTH {
524        return Err(MergePatchError::DepthExceeded);
525    }
526    match patch {
527        Value::Object(patch_map) => {
528            // Per RFC 7396 §2: "If the target value is not a JSON object,
529            // the resulting value will be the merge patch." We therefore
530            // reset a non-Object target to an empty Object before merging
531            // — this is reachable when a Patch creates a nested field that
532            // is absent from the target (the parent recursion frame inserted
533            // Value::Null as a placeholder).
534            if !target.is_object() {
535                *target = Value::Object(Map::new());
536            }
537            let target_map = target
538                .as_object_mut()
539                .expect("target was just set to Value::Object above");
540            for (key, patch_val) in patch_map {
541                if patch_val.is_null() {
542                    target_map.remove(&key);
543                } else {
544                    let entry = target_map.entry(key).or_insert(Value::Null);
545                    json_merge_patch_inner(entry, patch_val, depth + 1)?;
546                }
547            }
548        }
549        other => *target = other,
550    }
551    Ok(())
552}
553
554/// Error returned by [`apply_jmap_patch`] and [`apply_patch_object`] when
555/// a PatchObject cannot be applied.
556///
557/// Every variant is an RFC 8620 §5.3 violation for which "the update
558/// MUST be rejected with an "invalidPatch" error". Callers SHOULD map
559/// any variant to [`SetError`](crate::SetError) with
560/// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch);
561/// the `Display` form is suitable as its description.
562///
563/// Marked `#[non_exhaustive]` so further §5.3 checks can be added
564/// without an API break.
565#[non_exhaustive]
566#[derive(Debug, Clone, PartialEq, Eq)]
567pub enum PatchPathError {
568    /// A part before the last does not exist on the patched object.
569    ParentMissing,
570    /// A part before the last names an array, so the pointer would
571    /// reference inside an array.
572    InsideArray,
573    /// A part before the last names a value that is neither an object nor
574    /// an array (string, number, boolean or null), which has no members.
575    ParentNotObject,
576    /// A `~` in the path is not followed by `0` or `1`, so the path is
577    /// not a valid RFC 6901 JSON Pointer.
578    InvalidEscape,
579    /// The pointer of one patch is a prefix of the pointer of another in
580    /// the same PatchObject (e.g. `"alerts/1/offset"` and `"alerts"`).
581    PrefixConflict,
582    /// The path's segment count plus the value's object/array nesting
583    /// exceeds the crate's `MAX_MERGE_PATCH_DEPTH` DoS-guard cap.
584    ///
585    /// Not an RFC 8620 §5.3 rule: it is this crate's server limit
586    /// (RFC 8620 §3.6.1 lets a server reject requests that exceed its
587    /// limits), so repeated path patches cannot grow a stored value's
588    /// depth without bound. It is still reported as invalidPatch.
589    DepthExceeded,
590}
591
592impl std::fmt::Display for PatchPathError {
593    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594        match self {
595            Self::ParentMissing => f.write_str("patch path parent does not exist"),
596            Self::InsideArray => f.write_str("patch path references inside an array"),
597            Self::ParentNotObject => f.write_str("patch path parent is not an object"),
598            Self::InvalidEscape => f.write_str("patch path has a '~' not followed by '0' or '1'"),
599            Self::PrefixConflict => {
600                f.write_str("patch has a path that is a prefix of another path")
601            }
602            Self::DepthExceeded => {
603                write!(f, "patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels")
604            }
605        }
606    }
607}
608
609impl std::error::Error for PatchPathError {}
610
611/// Apply one RFC 8620 §5.3 PatchObject entry (`path` → `value`) to
612/// `target` in-place.
613///
614/// `path` is a PatchObject key: an RFC 6901 JSON Pointer with the
615/// implicit leading `/` omitted (e.g. `"mailboxIds/abc123"`). Each
616/// `/`-separated reference token is decoded per RFC 6901 §4 (`~1` → `/`,
617/// then `~0` → `~`). Every token before the last must name an existing
618/// object member; the last token names the member to set. A `null`
619/// `value` removes that member (a no-op when it is absent); any other
620/// value inserts or replaces it.
621///
622/// Extracted from per-crate copies in bd:JMAP-j6ab. Extension servers
623/// MUST call this rather than reimplement it.
624///
625/// Empty tokens are legal: RFC 6901 §3 allows a zero-length
626/// `reference-token`, and its §5 example evaluates `"/"` to the member
627/// named `""`. The RFC 8620 §5.3 "null sets the property default" rule
628/// is type-specific and left to the caller. The rule that no two pointers
629/// in one PatchObject may be prefixes of each other is checked by
630/// [`apply_patch_object`].
631///
632/// # Errors
633///
634/// Returns [`PatchPathError`] when a part before the last does not exist
635/// ([`ParentMissing`](PatchPathError::ParentMissing)), is an array
636/// ([`InsideArray`](PatchPathError::InsideArray)) or is another
637/// non-object value ([`ParentNotObject`](PatchPathError::ParentNotObject)),
638/// when `path` contains an invalid escape
639/// ([`InvalidEscape`](PatchPathError::InvalidEscape)), or when the
640/// number of `/`-separated segments in `path` plus the object/array
641/// nesting of `value` (a scalar nests 0 levels) exceeds the crate's
642/// `MAX_MERGE_PATCH_DEPTH` DoS-guard cap
643/// ([`DepthExceeded`](PatchPathError::DepthExceeded)).
644///
645/// # Mutation contract
646///
647/// A single call is all-or-nothing: on `Err`, `target` is unchanged.
648/// A PatchObject has several entries, and an error on a later entry
649/// does not undo earlier ones, so callers applying a whole PatchObject
650/// MUST use [`apply_patch_object`].
651pub fn apply_jmap_patch(
652    target: &mut Map<String, Value>,
653    path: &str,
654    value: Value,
655) -> Result<(), PatchPathError> {
656    let segments = path.split('/').count();
657    if segments > MAX_MERGE_PATCH_DEPTH
658        || nests_deeper_than(&value, MAX_MERGE_PATCH_DEPTH - segments)
659    {
660        return Err(PatchPathError::DepthExceeded);
661    }
662    let (parents, leaf) = match path.rsplit_once('/') {
663        Some((parents, leaf)) => (Some(parents), leaf),
664        None => (None, path),
665    };
666    let leaf = decode_pointer_token(leaf)?;
667    let mut parent = target;
668    for token in parents.into_iter().flat_map(|p| p.split('/')) {
669        parent = match parent.get_mut(decode_pointer_token(token)?.as_ref()) {
670            Some(Value::Object(map)) => map,
671            Some(Value::Array(_)) => return Err(PatchPathError::InsideArray),
672            Some(_) => return Err(PatchPathError::ParentNotObject),
673            None => return Err(PatchPathError::ParentMissing),
674        };
675    }
676    if value.is_null() {
677        parent.remove(leaf.as_ref());
678    } else {
679        parent.insert(leaf.into_owned(), value);
680    }
681    Ok(())
682}
683
684/// Apply a whole RFC 8620 §5.3 PatchObject to `target`.
685///
686/// Each entry is applied with [`apply_jmap_patch`]. The value at each
687/// pointer is set as given: a top-level key such as `"name"` replaces that
688/// property wholesale, with no nested merge of object values (RFC 8620
689/// §5.3: "The value to set for this property").
690///
691/// # Errors
692///
693/// Returns [`PatchPathError::PrefixConflict`] when the decoded pointer of
694/// one key is a whole-segment prefix of another (`"alerts"` and
695/// `"alerts/1/offset"` conflict; `"alert"` and `"alerts/x"` do not), and
696/// otherwise any error [`apply_jmap_patch`] returns for an entry.
697///
698/// # Mutation contract
699///
700/// All-or-nothing: on `Err`, `target` is unchanged.
701pub fn apply_patch_object(
702    target: &mut Map<String, Value>,
703    patch: &Map<String, Value>,
704) -> Result<(), PatchPathError> {
705    let mut pointers = patch
706        .keys()
707        .map(|k| {
708            k.split('/')
709                .map(decode_pointer_token)
710                .collect::<Result<Vec<_>, _>>()
711        })
712        .collect::<Result<Vec<_>, _>>()?;
713    // Sorted, a pointer that prefixes any other also prefixes its successor.
714    pointers.sort_unstable();
715    if pointers.windows(2).any(|w| w[1].starts_with(&w[0])) {
716        return Err(PatchPathError::PrefixConflict);
717    }
718    let mut patched = target.clone();
719    for (path, value) in patch {
720        apply_jmap_patch(&mut patched, path, value.clone())?;
721    }
722    *target = patched;
723    Ok(())
724}
725
726/// Whether `value` nests objects or arrays more than `limit` levels deep
727/// (a scalar nests 0 levels). Recursion is bounded by `limit`, not by the
728/// input.
729fn nests_deeper_than(value: &Value, limit: usize) -> bool {
730    match value {
731        Value::Object(map) => limit == 0 || map.values().any(|v| nests_deeper_than(v, limit - 1)),
732        Value::Array(items) => limit == 0 || items.iter().any(|v| nests_deeper_than(v, limit - 1)),
733        _ => false,
734    }
735}
736
737/// Decode one RFC 6901 reference token: `~1` → `/`, then `~0` → `~`
738/// (RFC 6901 §4 order, so `~01` becomes `~1`, not `/`).
739fn decode_pointer_token(token: &str) -> Result<Cow<'_, str>, PatchPathError> {
740    if !token.contains('~') {
741        return Ok(Cow::Borrowed(token));
742    }
743    let escapes_valid = token
744        .match_indices('~')
745        .all(|(i, _)| matches!(token.as_bytes().get(i + 1), Some(b'0' | b'1')));
746    if !escapes_valid {
747        return Err(PatchPathError::InvalidEscape);
748    }
749    Ok(Cow::Owned(token.replace("~1", "/").replace("~0", "~")))
750}
751
752/// Resolve a request-side `position` argument (RFC 8620 §5.5) into a
753/// 0-based start index suitable for slicing the full ordered result
754/// list (bd:JMAP-qz9v.48).
755///
756/// `position` is the signed offset from the `/query` request. The
757/// foundation handler at [`crate::handlers::handle_query`] parses it
758/// via [`serde_json::Value::as_i64`], so the value reaching the
759/// backend is any `i64` (including `i64::MIN`). Non-negative values
760/// are absolute offsets from the start of the result list; negative
761/// values are end-relative offsets per RFC 8620 §5.5 ("`-1` represents
762/// the last entry, `-2` the second to last, and so on").
763///
764/// Returns a `usize` clamped to `[0, total]`. The clamp at the high
765/// end matches the slice-safety property: `all_ids[start..]` is
766/// guaranteed not to panic regardless of the input `position`.
767///
768/// # Edge cases this helper exists to centralize
769///
770/// 1. `position == 0` → `0`.
771/// 2. `position > total` → `total` (yields an empty page, matching
772///    the RFC's silent-clamp semantics — `/query` does not error on
773///    out-of-range positions).
774/// 3. `position == i64::MIN` → handled via [`i64::saturating_neg`],
775///    which returns `i64::MAX` rather than overflowing. The resulting
776///    `usize::MAX`-magnitude offset is then absorbed by
777///    [`usize::saturating_sub`].
778/// 4. `position` exceeding `usize::MAX` on a 32-bit target (`i64`
779///    values above `2^32 - 1`) → clamped to `total` rather than
780///    truncated. The previous workspace idiom (`position as usize`)
781///    silently wrapped the high bits on 32-bit, returning a small
782///    `start` index that did not match the caller's intent.
783///
784/// # Why this lives in the foundation
785///
786/// The pattern is identical across every extension server's `/query`
787/// backend impl. Centralizing it eliminates the per-crate
788/// `(position as usize)` / `(position.saturating_neg() as usize)`
789/// idiom that clippy::pedantic flags as `cast_possible_truncation` +
790/// `cast_sign_loss`, and prevents future siblings from re-introducing
791/// the strictly-worse `(-position) as usize` variant (which panics on
792/// `i64::MIN` in debug builds and wraps in release).
793///
794/// # Example
795///
796/// ```
797/// use jmap_server::resolve_query_offset;
798///
799/// // Absolute offset.
800/// assert_eq!(resolve_query_offset(0, 100), 0);
801/// assert_eq!(resolve_query_offset(25, 100), 25);
802///
803/// // End-relative offset.
804/// assert_eq!(resolve_query_offset(-1, 100), 99);
805/// assert_eq!(resolve_query_offset(-100, 100), 0);
806///
807/// // Out-of-range clamps to total.
808/// assert_eq!(resolve_query_offset(1_000, 100), 100);
809/// assert_eq!(resolve_query_offset(-1_000, 100), 0);
810///
811/// // i64::MIN does not overflow.
812/// assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
813/// ```
814#[must_use]
815pub fn resolve_query_offset(position: i64, total: usize) -> usize {
816    if position >= 0 {
817        // `i64 >= 0` → fits in `u64`. `usize::try_from` returns the
818        // value on 64-bit targets and `Err` on 32-bit targets only
819        // when the magnitude exceeds `usize::MAX`; saturating to
820        // `usize::MAX` is then clamped to `total` by `.min`.
821        usize::try_from(position).unwrap_or(usize::MAX).min(total)
822    } else {
823        // `saturating_neg` maps `i64::MIN` to `i64::MAX` instead of
824        // overflowing. Every other negative `i64` negates exactly.
825        let neg = usize::try_from(position.saturating_neg()).unwrap_or(usize::MAX);
826        total.saturating_sub(neg)
827    }
828}
829
830/// Parse the RFC 8620 §5.5 `/query` arguments `anchor` (`Id|null`) and
831/// `anchorOffset` (`Int`, default `0`) from `args`.
832///
833/// # Errors
834///
835/// `invalidArguments` when `anchor` is neither a string nor `null`, or
836/// `anchorOffset` is neither an integer nor `null`.
837pub fn query_anchor_args(args: &Map<String, Value>) -> Result<(Option<Id>, i64), JmapError> {
838    let anchor = match args.get("anchor") {
839        None | Some(Value::Null) => None,
840        // Id::from: wire-boundary validation deferred to JMAP-k9va; a
841        // malformed id is never in the results, so it is anchorNotFound.
842        Some(Value::String(s)) => Some(Id::from(s.as_str())),
843        Some(v) => {
844            return Err(JmapError::invalid_arguments(format!(
845                "anchor: expected an Id string or null, got {v}"
846            )))
847        }
848    };
849    let anchor_offset = match args.get("anchorOffset") {
850        None | Some(Value::Null) => 0,
851        Some(v) => v.as_i64().ok_or_else(|| {
852            JmapError::invalid_arguments(format!("anchorOffset: expected an integer, got {v}"))
853        })?,
854    };
855    Ok((anchor, anchor_offset))
856}
857
858/// Start index of a `/query` page within the filtered, sorted `ids`
859/// (RFC 8620 §5.5), for [`JmapBackend::query_objects`] implementations.
860///
861/// With an `anchor`, `position` is ignored and the start is the
862/// anchor's index plus `anchor_offset`, clamped to `0..=ids.len()`.
863/// Without one, `anchor_offset` is ignored and the start is
864/// [`resolve_query_offset`]`(position, ids.len())`.
865///
866/// # Errors
867///
868/// [`JmapError::anchor_not_found`] when `anchor` is not in `ids`.
869///
870/// [`JmapBackend::query_objects`]: crate::JmapBackend::query_objects
871pub fn resolve_query_start(
872    ids: &[Id],
873    position: i64,
874    anchor: Option<&Id>,
875    anchor_offset: i64,
876) -> Result<usize, JmapError> {
877    let Some(anchor) = anchor else {
878        return Ok(resolve_query_offset(position, ids.len()));
879    };
880    let index = ids
881        .iter()
882        .position(|id| id == anchor)
883        .ok_or_else(JmapError::anchor_not_found)?;
884    let start = i64::try_from(index)
885        .unwrap_or(i64::MAX)
886        .saturating_add(anchor_offset)
887        .max(0);
888    Ok(resolve_query_offset(start, ids.len()))
889}
890
891/// Enforce RFC 8620 §5.3 `maxObjectsInSet` cap at the top of a `/set`
892/// handler (bd:JMAP-ayoz.41.1).
893///
894/// Counts entries in the wire `create` (object), `update` (object), and
895/// `destroy` (array) arguments. Returns the method-level error
896/// [`JmapError::request_too_large`] (wire `type: "requestTooLarge"`,
897/// `description: "maxObjectsInSet"`) when the sum exceeds `max`. Per
898/// RFC 8620 §5.3 it is returned instead of the `Foo/set` response, so
899/// the dispatcher emits an `error` invocation and later method calls
900/// in the same request still run (bd:JMAP-yt1w.30).
901///
902/// Call at the top of every `handle_*_set` after the `account_exists`
903/// gate and before any per-entry processing. A request carrying
904/// megabytes of `/set` ops is rejected before the handler touches the
905/// storage layer:
906///
907/// ```ignore
908/// let (account_id, args) = extract_account_id(args)?;
909/// if !backend.account_exists(caller, &account_id).await
910///     .map_err(|e| server_fail_from_backend(&e))?
911/// {
912///     return Err(JmapError::account_not_found());
913/// }
914/// jmap_server::helpers::enforce_max_objects_in_set(
915///     &args,
916///     backend.max_objects_in_set(caller, &account_id),
917/// )?;
918/// ```
919///
920/// # Why this lives in the foundation
921///
922/// `maxObjectsInSet` is a RFC 8620 §5.3 base-protocol cap, not an
923/// extension concept. Every `jmap-*-server` extension's `handle_*_set`
924/// needs the same check; the helper is the single source of truth so a
925/// future revision (different error shape, additional counting rule,
926/// alternate semantics for non-object `create` / `update`) lands in one
927/// place instead of being propagated through 28 handler sites.
928///
929/// # Counting rules
930///
931/// - `create` is counted as `args["create"].as_object()?.len()` —
932///   missing key, `null`, or non-object types count as 0.
933/// - `update` is counted the same way (RFC 8620 §5.3 `update` is
934///   `Id[PatchObject]`).
935/// - `destroy` is counted as `args["destroy"].as_array()?.len()` —
936///   missing key, `null`, or non-array types count as 0.
937///
938/// Wire-shape validation of the individual `create` / `update` /
939/// `destroy` arguments belongs to the per-handler argument parsing,
940/// not to this cap-enforcement helper. A non-object `create` survives
941/// the cap check (counts as 0) and is rejected by the handler's
942/// downstream `args.remove("create")` match arm. Conversely, a
943/// well-formed but over-limit `create` is rejected here before the
944/// handler runs.
945///
946/// # Errors
947///
948/// Returns `JmapError::request_too_large()` with description
949/// `"maxObjectsInSet"` when the sum exceeds `max` (RFC 8620 §5.3).
950pub fn enforce_max_objects_in_set(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
951    let create_count = args
952        .get("create")
953        .and_then(|v| v.as_object())
954        .map_or(0u64, |m| m.len() as u64);
955    let update_count = args
956        .get("update")
957        .and_then(|v| v.as_object())
958        .map_or(0u64, |m| m.len() as u64);
959    let destroy_count = args
960        .get("destroy")
961        .and_then(|v| v.as_array())
962        .map_or(0u64, |a| a.len() as u64);
963    // u64 saturation: each count is bounded by serde_json's body parse
964    // (Map::len / Vec::len are usize; on 64-bit targets usize == u64,
965    // on 32-bit targets usize < u64). The sum cannot exceed
966    // 3 * u32::MAX even on 32-bit hosts, well within u64 range.
967    let count = create_count
968        .saturating_add(update_count)
969        .saturating_add(destroy_count);
970    if count > max {
971        let mut err = JmapError::request_too_large();
972        err.description = Some("maxObjectsInSet".into());
973        return Err(err);
974    }
975    Ok(())
976}
977
978/// Enforce RFC 8620 §5.1 `maxObjectsInGet` at the top of a `/get`
979/// handler (bd:JMAP-yt1w.31).
980///
981/// Counts the entries in the wire `ids` argument. Returns the
982/// method-level error [`JmapError::request_too_large`] (wire
983/// `type: "requestTooLarge"`, `description: "maxObjectsInGet"`) when the
984/// count exceeds `max`. Per RFC 8620 §5.1 it is returned instead of the
985/// `Foo/get` response.
986///
987/// Call after the `account_exists` gate and before parsing `ids`:
988///
989/// ```ignore
990/// jmap_server::helpers::enforce_max_objects_in_get(
991///     &args,
992///     backend.max_objects_in_get(caller, &account_id),
993/// )?;
994/// ```
995///
996/// # Counting rules
997///
998/// `ids` is counted as `args["ids"].as_array()?.len()`. A missing key,
999/// `null` (fetch all), or a non-array value counts as 0: RFC 8620 §5.1
1000/// bounds "the number of ids requested by the client", and a null `ids`
1001/// requests none. Bounding a fetch-all by the number of records is the
1002/// backend's job, since only it knows how many records exist. Wire-shape
1003/// validation of `ids` belongs to the handler's argument parsing.
1004///
1005/// # Errors
1006///
1007/// Returns `JmapError::request_too_large()` with description
1008/// `"maxObjectsInGet"` when the count exceeds `max` (RFC 8620 §5.1).
1009pub fn enforce_max_objects_in_get(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
1010    let count = args
1011        .get("ids")
1012        .and_then(|v| v.as_array())
1013        .map_or(0u64, |a| a.len() as u64);
1014    if count > max {
1015        let mut err = JmapError::request_too_large();
1016        err.description = Some("maxObjectsInGet".into());
1017        return Err(err);
1018    }
1019    Ok(())
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use super::{
1025        apply_jmap_patch, apply_patch_object, civil_from_days, enforce_max_objects_in_set,
1026        extract_account_id, filter_arg, json_merge_patch, now_utc_string, resolve_query_offset,
1027        resolve_query_start, utc_date_from_epoch_seconds, MergePatchError, PatchPathError,
1028        MAX_MERGE_PATCH_DEPTH,
1029    };
1030    use serde_json::json;
1031
1032    #[derive(Debug, serde::Deserialize)]
1033    #[serde(rename_all = "camelCase", deny_unknown_fields)]
1034    struct NameCond {
1035        name: Option<String>,
1036    }
1037
1038    fn filter_of(v: serde_json::Value) -> Result<Option<NameCond>, jmap_types::JmapError> {
1039        let mut args = json!({ "filter": v }).as_object().cloned().expect("object");
1040        filter_arg::<NameCond>(&mut args)
1041    }
1042
1043    /// Oracle: RFC 8620 §5.5 — "unsupportedFilter: The "filter" is
1044    /// syntactically valid, but the server cannot process it"; RFC 8620
1045    /// §3.6.2 — invalidArguments for an argument of the wrong type.
1046    /// Hand-written JSON inputs.
1047    #[test]
1048    fn filter_arg_maps_object_and_non_object_failures() {
1049        assert!(filter_of(json!(null)).expect("null").is_none());
1050        let cond = filter_of(json!({ "name": "x" })).expect("known key");
1051        assert_eq!(cond.and_then(|c| c.name).as_deref(), Some("x"));
1052        let err = filter_of(json!({ "label": "x" })).expect_err("unknown key");
1053        assert_eq!(err.error_type, "unsupportedFilter");
1054        assert!(
1055            err.description
1056                .as_deref()
1057                .is_some_and(|d| d.contains("label")),
1058            "{err:?}"
1059        );
1060        let err = filter_of(json!(42)).expect_err("scalar");
1061        assert_eq!(err.error_type, "invalidArguments");
1062    }
1063
1064    /// Oracle (bd:JMAP-wlip.5): a malformed accountId — empty string,
1065    /// containing forbidden ASCII characters, or exceeding 255 bytes —
1066    /// MUST surface as `invalidArguments`, not silently pass through to
1067    /// the backend's `account_exists` call.
1068    ///
1069    /// Test vectors hand-built from RFC 8620 §1.2's Id grammar
1070    /// (SAFE-CHAR = `%x21 / %x23-7E`).
1071    #[test]
1072    fn extract_account_id_rejects_malformed_id() {
1073        // Empty string.
1074        let err = extract_account_id(json!({ "accountId": "" }))
1075            .expect_err("empty accountId must fail validation");
1076        assert_eq!(err.error_type.as_str(), "invalidArguments");
1077
1078        // Contains a space (0x20 — outside SAFE-CHAR's 0x21+ lower bound).
1079        let err = extract_account_id(json!({ "accountId": "my account" }))
1080            .expect_err("space in accountId must fail validation");
1081        assert_eq!(err.error_type.as_str(), "invalidArguments");
1082
1083        // Contains a DQUOTE (0x22 — explicitly excluded by SAFE-CHAR).
1084        let err = extract_account_id(json!({ "accountId": "a\"b" }))
1085            .expect_err("DQUOTE in accountId must fail validation");
1086        assert_eq!(err.error_type.as_str(), "invalidArguments");
1087
1088        // 256 bytes — exceeds the 255 cap.
1089        let long: String = "a".repeat(256);
1090        let err = extract_account_id(json!({ "accountId": long }))
1091            .expect_err("over-long accountId must fail validation");
1092        assert_eq!(err.error_type.as_str(), "invalidArguments");
1093    }
1094
1095    /// Oracle (bd:JMAP-wlip.5): a well-formed accountId passes
1096    /// validation and is returned intact. Positive control paired with
1097    /// the rejection test above.
1098    ///
1099    /// Also pins (bd:JMAP-jfia.9): the returned args map MUST NOT
1100    /// contain accountId. The helper consumes the field rather than
1101    /// leaving it as a residual key for downstream handlers to
1102    /// re-parse or surface as "unexpected key".
1103    #[test]
1104    fn extract_account_id_accepts_well_formed_id() {
1105        let (id, rest) = extract_account_id(json!({
1106            "accountId": "u123-abc_DEF",
1107            "ids": ["e1", "e2"]
1108        }))
1109        .expect("well-formed accountId must pass validation");
1110        assert_eq!(id.as_ref(), "u123-abc_DEF");
1111        // Remaining args still contain the unrelated keys.
1112        assert!(rest.contains_key("ids"));
1113        // accountId MUST have been removed from the args map
1114        // (bd:JMAP-jfia.9). matches optional_arg's consume semantics.
1115        assert!(
1116            !rest.contains_key("accountId"),
1117            "accountId must be removed from args after extraction"
1118        );
1119    }
1120
1121    /// Test vectors derived independently with Python's `datetime.date` module.
1122    /// `days` is the count of days since 1970-01-01.
1123    #[test]
1124    fn civil_from_days_known_dates() {
1125        let cases: &[(i64, (i32, u8, u8))] = &[
1126            (0, (1970, 1, 1)),       // Unix epoch
1127            (365, (1971, 1, 1)),     // one year later (1970 is not a leap year)
1128            (10957, (2000, 1, 1)),   // Y2K
1129            (11016, (2000, 2, 29)),  // leap day in a century-divisible leap year
1130            (11017, (2000, 3, 1)),   // day after the leap day (era boundary in algorithm)
1131            (19358, (2023, 1, 1)),   // a recent non-leap year start
1132            (19722, (2023, 12, 31)), // end of 2023
1133            (19782, (2024, 2, 29)),  // leap day in 2024
1134            (19783, (2024, 3, 1)),   // day after 2024 leap day
1135        ];
1136
1137        for &(days, expected) in cases {
1138            assert_eq!(
1139                civil_from_days(days),
1140                Some(expected),
1141                "civil_from_days({days}) mismatch"
1142            );
1143        }
1144    }
1145
1146    /// Oracle (bd:JMAP-jfia.2): civil_from_days MUST return None rather
1147    /// than panic on inputs whose computed year overflows i32. The
1148    /// Hinnant algorithm's intermediate `y = yoe + era * 400` value is
1149    /// bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a thin slice of
1150    /// which fits in i32. The outer `now_utc_string_checked`
1151    /// u64→i64 sentinel only catches u64 seconds exceeding `i64::MAX`,
1152    /// so corrupted-clock inputs between the i32-year boundary and
1153    /// i64::MAX reach this function. A panic here would surface as
1154    /// serverFail under dispatcher task::spawn isolation — degraded,
1155    /// but a contract violation versus the function's "fallible
1156    /// without panicking" contract.
1157    ///
1158    /// Test vectors: the maximum days-from-epoch derived from
1159    /// i64::MAX seconds (the regime that reaches civil_from_days
1160    /// after passing the outer u64→i64 sentinel), and the symmetric
1161    /// negative case. These years are deep enough into the i64
1162    /// algorithm range to definitely overflow i32. Plus a
1163    /// non-overflowing positive control just below the threshold to
1164    /// prove the boundary check fires only when warranted.
1165    #[test]
1166    fn civil_from_days_returns_none_on_year_overflow() {
1167        // i64::MAX / 86400 ≈ 1.07e14 days → year ≈ 2.92e11, well past i32::MAX (~2.15e9).
1168        let max_days = i64::MAX / 86400;
1169        assert_eq!(
1170            civil_from_days(max_days),
1171            None,
1172            "i64::MAX / 86400 days must overflow i32 year"
1173        );
1174
1175        // i64::MIN / 86400 ≈ -1.07e14 days — symmetric negative case.
1176        let min_days = i64::MIN / 86400;
1177        assert_eq!(
1178            civil_from_days(min_days),
1179            None,
1180            "i64::MIN / 86400 days must overflow i32 year"
1181        );
1182
1183        // Positive control: a far-future but i32-fitting year should
1184        // still succeed. Year ~58_798_075 (from 10 * i32::MAX days)
1185        // fits in i32 with room to spare, so this MUST return Some.
1186        let year_58m_days = 10_i64 * i64::from(i32::MAX);
1187        let result = civil_from_days(year_58m_days);
1188        assert!(
1189            result.is_some(),
1190            "i32-fitting year must return Some; got {result:?}"
1191        );
1192    }
1193
1194    /// Oracle (bd:JMAP-jfia.30): now_utc_string_checked MUST return
1195    /// `Some(UTCDate)` on a sane clock (every host the test runs on
1196    /// in practice). The civil_from_days_returns_none_on_year_overflow
1197    /// test above pins the underlying None-on-corrupted-clock
1198    /// behaviour at the algorithm level; this test pins the
1199    /// happy-path contract: a sane clock yields the typed wire format,
1200    /// not a sentinel string.
1201    #[test]
1202    fn now_utc_string_checked_returns_some_on_sane_clock() {
1203        use super::now_utc_string_checked;
1204        let dt = now_utc_string_checked().expect(
1205            "test host clock must be reasonable enough for now_utc_string_checked to succeed",
1206        );
1207        let s: &str = dt.as_ref();
1208        assert_eq!(s.len(), 24, "wire shape must be 24 chars: {s:?}");
1209        assert!(s.ends_with('Z'), "must end with Z: {s:?}");
1210    }
1211
1212    /// Oracle (bd:JMAP-jfia.30): now_utc_string (the panicking variant)
1213    /// MUST agree with now_utc_string_checked on a sane clock — i.e.
1214    /// the .expect() in now_utc_string does not introduce a wire-format
1215    /// discrepancy versus the Option-returning variant.
1216    #[test]
1217    fn now_utc_string_matches_checked_variant_on_sane_clock() {
1218        use super::now_utc_string_checked;
1219        let panicky = now_utc_string();
1220        let checked = now_utc_string_checked().expect("test host clock must be reasonable");
1221        // Both calls observe SystemTime::now() at slightly different
1222        // instants; the seconds part can differ if the test runs across
1223        // a second boundary. Compare the prefix up to the seconds
1224        // resolution.
1225        let panicky_s: &str = panicky.as_ref();
1226        let checked_s: &str = checked.as_ref();
1227        assert_eq!(
1228            panicky_s.len(),
1229            checked_s.len(),
1230            "wire-format lengths must match: panicky={panicky_s:?} checked={checked_s:?}"
1231        );
1232        // Compare the date portion only (YYYY-MM-DD, 10 chars).
1233        assert_eq!(
1234            &panicky_s[..10],
1235            &checked_s[..10],
1236            "date portions must match: panicky={panicky_s:?} checked={checked_s:?}"
1237        );
1238    }
1239
1240    /// Oracle: GNU `date -u -d @<secs> +%FT%TZ` (coreutils), plus the
1241    /// RFC 8620 §7.2.3 example expiry (rfc8620.txt:3879) and the RFC 8620
1242    /// §1.4 example date. -62167219200 is 0000-01-01T00:00:00Z; one second
1243    /// earlier is year -1, which the four-digit form cannot express.
1244    #[test]
1245    fn utc_date_from_epoch_seconds_known_values() {
1246        for (secs, expected) in [
1247            (0, Some("1970-01-01T00:00:00Z")),
1248            (-1, Some("1969-12-31T23:59:59Z")),
1249            (1_414_649_520, Some("2014-10-30T06:12:00Z")),
1250            (1_531_448_069, Some("2018-07-13T02:14:29Z")),
1251            (253_402_300_799, Some("9999-12-31T23:59:59Z")),
1252            (253_402_300_800, None),
1253            (-62_167_219_200, Some("0000-01-01T00:00:00Z")),
1254            (-62_167_219_201, None),
1255        ] {
1256            assert_eq!(
1257                utc_date_from_epoch_seconds(secs)
1258                    .as_ref()
1259                    .map(AsRef::as_ref),
1260                expected,
1261                "secs = {secs}"
1262            );
1263        }
1264    }
1265
1266    #[test]
1267    fn now_utc_string_format() {
1268        // bd:JMAP-wlip.20 — return type is UTCDate; AsRef<str> gives
1269        // the underlying wire-format string for shape assertions.
1270        let dt = now_utc_string();
1271        let s: &str = dt.as_ref();
1272        // Must match YYYY-MM-DDTHH:MM:SS.mmmZ (24 chars)
1273        assert_eq!(s.len(), 24, "unexpected length: {s}");
1274        assert!(s.ends_with('Z'), "must end with Z: {s}");
1275        assert_eq!(&s[4..5], "-", "missing year-month separator: {s}");
1276        assert_eq!(&s[7..8], "-", "missing month-day separator: {s}");
1277        assert_eq!(&s[10..11], "T", "missing date-time separator: {s}");
1278        assert_eq!(&s[13..14], ":", "missing hour-minute separator: {s}");
1279        assert_eq!(&s[16..17], ":", "missing minute-second separator: {s}");
1280        assert_eq!(&s[19..20], ".", "missing decimal point before millis: {s}");
1281        // milliseconds are 3 decimal digits
1282        assert!(
1283            s[20..23].chars().all(|c| c.is_ascii_digit()),
1284            "milliseconds must be 3 digits: {s}"
1285        );
1286        assert!(
1287            s.starts_with("20"),
1288            "year should start with 20 in 21st century: {s}"
1289        );
1290    }
1291
1292    // -----------------------------------------------------------------------
1293    // json_merge_patch (RFC 7396)
1294    //
1295    // Test oracles are hand-built JSON values derived from RFC 7396 §2 and §3
1296    // examples, plus the regression case from bd:JMAP-sc1b.87. No oracle is
1297    // computed by the function under test (test-integrity rule from
1298    // workspace AGENTS.md).
1299    // -----------------------------------------------------------------------
1300
1301    /// Oracle: bd:JMAP-sc1b.97 — a 1000-deep merge patch must NOT crash
1302    /// via stack overflow. The depth cap returns
1303    /// [`MergePatchError::DepthExceeded`] beyond [`MAX_MERGE_PATCH_DEPTH`]
1304    /// rather than recursing further.
1305    ///
1306    /// The test does not use the function as its own oracle: the input
1307    /// is hand-built (a 1000-deep `{ "a": { "a": ... { "a": {} } } }`
1308    /// chain where every level is Object, matching the structural
1309    /// shape of a real PatchObject — the documented latent panic from
1310    /// bd:JMAP-sc1b.87 only fires on non-Object leaves, which a typed
1311    /// PatchObject cannot produce). The assertion checks that the
1312    /// call completes without panicking AND that it surfaces the
1313    /// depth-exceeded error rather than silently succeeding (the
1314    /// pre-bd:JMAP-wlip.1 silent-truncation bug).
1315    #[test]
1316    fn json_merge_patch_does_not_stack_overflow() {
1317        const DEPTH: usize = 1000;
1318        let mut target = serde_json::json!({});
1319        for _ in 0..DEPTH {
1320            target = serde_json::json!({ "a": target });
1321        }
1322        let mut patch = serde_json::json!({});
1323        for _ in 0..DEPTH {
1324            patch = serde_json::json!({ "a": patch });
1325        }
1326        let err = json_merge_patch(&mut target, patch)
1327            .expect_err("deep patch must surface DepthExceeded, not silently truncate");
1328        assert_eq!(
1329            err,
1330            MergePatchError::DepthExceeded,
1331            "deep patch must return MergePatchError::DepthExceeded"
1332        );
1333    }
1334
1335    /// Oracle: bd:JMAP-wlip.1 — a patch at exactly [`MAX_MERGE_PATCH_DEPTH`]
1336    /// levels (the deepest legal patch) MUST apply successfully. The cap
1337    /// fires only when the patch tries to recurse one level beyond. The
1338    /// expected target shape is hand-built level-by-level from the same
1339    /// counter the patch uses, so the oracle is independent of the
1340    /// recursion under test.
1341    #[test]
1342    fn json_merge_patch_at_exact_cap_applies() {
1343        // Build a patch nested exactly MAX_MERGE_PATCH_DEPTH levels deep.
1344        // Outermost level is depth=1; innermost leaf-Object is at depth
1345        // MAX_MERGE_PATCH_DEPTH. The first depth-cap check fires at
1346        // depth == MAX_MERGE_PATCH_DEPTH + 1, so this is the deepest
1347        // patch that still applies.
1348        let mut patch = serde_json::json!({ "leaf": "value" });
1349        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
1350            patch = serde_json::json!({ "a": patch });
1351        }
1352        let mut target = serde_json::json!({});
1353        json_merge_patch(&mut target, patch).expect("patch at the cap must apply");
1354        // Walk the resulting target down its 'a' chain to verify the
1355        // leaf field landed.
1356        let mut cursor = &target;
1357        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
1358            cursor = cursor.get("a").expect("each level must have 'a'");
1359        }
1360        assert_eq!(
1361            cursor.get("leaf"),
1362            Some(&serde_json::Value::String("value".to_owned())),
1363            "the leaf field at exactly MAX_MERGE_PATCH_DEPTH must be applied"
1364        );
1365    }
1366
1367    /// Oracle: a shallow merge patch under the cap still applies
1368    /// normally. Positive control paired with the stack-overflow test
1369    /// above to prove the depth cap only fires at the boundary, not on
1370    /// every call.
1371    #[test]
1372    fn json_merge_patch_shallow_applies_normally() {
1373        let mut target = serde_json::json!({ "a": 1, "b": { "c": 2 } });
1374        let patch = serde_json::json!({ "b": { "c": 99, "d": 7 }, "e": null });
1375        json_merge_patch(&mut target, patch).expect("shallow patch must succeed");
1376        assert_eq!(
1377            target,
1378            serde_json::json!({ "a": 1, "b": { "c": 99, "d": 7 } }),
1379            "RFC 7396 merge semantics broken at shallow depth"
1380        );
1381    }
1382
1383    /// Regression: a Patch that adds a nested Object to a previously-
1384    /// absent field used to panic with `expect("merge patch target
1385    /// must be an object")` because the parent recursion frame
1386    /// inserted Value::Null as the placeholder, then recursed into
1387    /// Null with an Object patch.
1388    ///
1389    /// Per RFC 7396 §2 the correct behaviour is to reset the non-Object
1390    /// target to an empty Object and merge into it. Oracle is hand-
1391    /// derived from RFC 7396 §2's pseudocode:
1392    /// `Target[Name] = MergePatch(Target[Name], Value)` where
1393    /// MergePatch resets a non-Object target to `{}`.
1394    #[test]
1395    fn json_merge_patch_adds_nested_object_to_absent_field() {
1396        let mut target = serde_json::json!({ "a": 1 });
1397        let patch = serde_json::json!({ "b": { "c": 2 } });
1398        json_merge_patch(&mut target, patch).expect("nested-add patch must succeed");
1399        assert_eq!(
1400            target,
1401            serde_json::json!({ "a": 1, "b": { "c": 2 } }),
1402            "patch must add the nested object at the previously-absent field"
1403        );
1404    }
1405
1406    /// Oracle: [`MergePatchError`] implements [`std::error::Error`] and
1407    /// has a stable Display form referencing the cap value. Pinning the
1408    /// Display string keeps the error message stable across refactors;
1409    /// the cap value is interpolated from the public constant so this
1410    /// test does not need updating if the cap changes.
1411    #[test]
1412    fn merge_patch_error_display() {
1413        let err = MergePatchError::DepthExceeded;
1414        let s = err.to_string();
1415        assert!(
1416            s.contains(&MAX_MERGE_PATCH_DEPTH.to_string()),
1417            "Display must mention the cap value; got {s:?}"
1418        );
1419        assert!(
1420            s.contains("merge patch"),
1421            "Display must identify the error source; got {s:?}"
1422        );
1423    }
1424
1425    // ------------------------------------------------------------------
1426    // apply_jmap_patch (RFC 8620 §5.3 PatchObject paths, RFC 6901)
1427    //
1428    // Oracles are hand-built JSON values derived from the quoted RFC
1429    // text; the function under test is never its own oracle.
1430    // ------------------------------------------------------------------
1431
1432    /// Build a `Map` from a JSON object literal.
1433    fn obj(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
1434        match v {
1435            serde_json::Value::Object(m) => m,
1436            other => panic!("fixture must be a JSON object, got {other}"),
1437        }
1438    }
1439
1440    /// Apply `path` → `value` to `before` and assert it fails with `want`
1441    /// and leaves the object unchanged.
1442    fn assert_patch_rejected(
1443        before: serde_json::Value,
1444        path: &str,
1445        value: serde_json::Value,
1446        want: PatchPathError,
1447    ) {
1448        let mut target = obj(before.clone());
1449        let err = apply_jmap_patch(&mut target, path, value).expect_err("patch must be rejected");
1450        assert_eq!(err, want, "wrong error for path {path:?}");
1451        assert_eq!(
1452            serde_json::Value::Object(target),
1453            before,
1454            "rejected patch {path:?} must leave the object unchanged"
1455        );
1456    }
1457
1458    /// Oracle: RFC 8620 §5.3 — "Anything else: The value to set for this
1459    /// property (this may be a replacement or addition to the object
1460    /// being patched)."
1461    #[test]
1462    fn apply_jmap_patch_non_null_adds_or_replaces() {
1463        let mut target = obj(json!({ "a": 1 }));
1464        apply_jmap_patch(&mut target, "a", json!(2)).expect("replace");
1465        apply_jmap_patch(&mut target, "b", json!("x")).expect("add");
1466        assert_eq!(
1467            serde_json::Value::Object(target),
1468            json!({ "a": 2, "b": "x" })
1469        );
1470    }
1471
1472    /// Oracle: RFC 8620 §5.3 — "If null, ... remove the property from the
1473    /// patched object.  If the key is not present in the parent, this a
1474    /// no-op."
1475    #[test]
1476    fn apply_jmap_patch_null_removes_and_absent_is_noop() {
1477        let mut target = obj(json!({ "a": 1, "m": { "k": true } }));
1478        apply_jmap_patch(&mut target, "a", serde_json::Value::Null).expect("remove");
1479        apply_jmap_patch(&mut target, "m/k", serde_json::Value::Null).expect("nested remove");
1480        apply_jmap_patch(&mut target, "m/absent", serde_json::Value::Null).expect("no-op");
1481        assert_eq!(serde_json::Value::Object(target), json!({ "m": {} }));
1482    }
1483
1484    /// Oracle: RFC 8620 §5.3 — "The keys are a path in JSON Pointer
1485    /// format [RFC6901], with an implicit leading "/"". `mailboxIds/abc`
1486    /// sets member `abc` of the existing `mailboxIds` object and leaves
1487    /// its siblings alone.
1488    #[test]
1489    fn apply_jmap_patch_nested_path_sets_member_of_existing_object() {
1490        let mut target = obj(json!({ "mailboxIds": { "inbox": true }, "x": { "y": { "z": 1 } } }));
1491        apply_jmap_patch(&mut target, "mailboxIds/abc", json!(true)).expect("set");
1492        apply_jmap_patch(&mut target, "x/y/w", json!(2)).expect("deep set");
1493        assert_eq!(
1494            serde_json::Value::Object(target),
1495            json!({ "mailboxIds": { "inbox": true, "abc": true }, "x": { "y": { "z": 1, "w": 2 } } })
1496        );
1497    }
1498
1499    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last (i.e., the
1500    /// value after the final slash) MUST already exist on the object
1501    /// being patched." A missing parent is rejected, never created, for
1502    /// both non-null and null values.
1503    #[test]
1504    fn apply_jmap_patch_missing_parent_is_rejected() {
1505        let before = json!({ "a": { "b": {} } });
1506        for value in [json!("v"), serde_json::Value::Null] {
1507            assert_patch_rejected(
1508                before.clone(),
1509                "x/y",
1510                value.clone(),
1511                PatchPathError::ParentMissing,
1512            );
1513            assert_patch_rejected(
1514                before.clone(),
1515                "a/c/d",
1516                value,
1517                PatchPathError::ParentMissing,
1518            );
1519        }
1520    }
1521
1522    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last ... MUST
1523    /// already exist on the object being patched." A string, number,
1524    /// boolean or null has no members, so a part beneath one does not
1525    /// exist; the existing value must not be clobbered.
1526    #[test]
1527    fn apply_jmap_patch_non_object_parent_is_rejected() {
1528        let before = json!({ "s": "text", "n": 42, "b": true, "z": null });
1529        for parent in ["s", "n", "b", "z"] {
1530            assert_patch_rejected(
1531                before.clone(),
1532                &format!("{parent}/sub"),
1533                json!("would-clobber"),
1534                PatchPathError::ParentNotObject,
1535            );
1536        }
1537    }
1538
1539    /// Oracle: RFC 8620 §5.3 — "The pointer MUST NOT reference inside an
1540    /// array (i.e., you MUST NOT insert/delete from an array; the array
1541    /// MUST be replaced in its entirety instead)." Applies to numeric
1542    /// tokens and to paths that would descend through an array element.
1543    #[test]
1544    fn apply_jmap_patch_inside_array_is_rejected() {
1545        let before = json!({ "list": ["a", { "k": 1 }] });
1546        assert_patch_rejected(
1547            before.clone(),
1548            "list/0",
1549            json!("x"),
1550            PatchPathError::InsideArray,
1551        );
1552        assert_patch_rejected(
1553            before.clone(),
1554            "list/1/k",
1555            json!(2),
1556            PatchPathError::InsideArray,
1557        );
1558        assert_patch_rejected(
1559            before,
1560            "list/0",
1561            serde_json::Value::Null,
1562            PatchPathError::InsideArray,
1563        );
1564    }
1565
1566    /// Oracle: RFC 8620 §5.3 — "the array MUST be replaced in its entirety
1567    /// instead": setting the array-valued property itself is allowed.
1568    #[test]
1569    fn apply_jmap_patch_replaces_whole_array() {
1570        let mut target = obj(json!({ "list": ["a"] }));
1571        apply_jmap_patch(&mut target, "list", json!(["b", "c"])).expect("replace array");
1572        assert_eq!(
1573            serde_json::Value::Object(target),
1574            json!({ "list": ["b", "c"] })
1575        );
1576    }
1577
1578    /// Oracle: RFC 6901 §4 — "first transforming any occurrence of the
1579    /// sequence '~1' to '/', and then transforming any occurrence of the
1580    /// sequence '~0' to '~' ... (the string '~01' correctly becomes '~1'
1581    /// after transformation)." Decoding is per token, after splitting on
1582    /// `/`, so `a~1b/c` addresses member `c` of member `a/b`.
1583    #[test]
1584    fn apply_jmap_patch_decodes_rfc6901_escapes() {
1585        let mut target = obj(json!({ "a/b": {}, "m~n": {} }));
1586        apply_jmap_patch(&mut target, "foo~1bar", json!(1)).expect("~1");
1587        apply_jmap_patch(&mut target, "foo~0bar", json!(2)).expect("~0");
1588        apply_jmap_patch(&mut target, "~01", json!(3)).expect("~01");
1589        apply_jmap_patch(&mut target, "a~1b/c", json!(4)).expect("escaped parent");
1590        apply_jmap_patch(&mut target, "m~0n/~1", json!(5)).expect("escaped parent and leaf");
1591        assert_eq!(
1592            serde_json::Value::Object(target),
1593            json!({
1594                "foo/bar": 1,
1595                "foo~bar": 2,
1596                "~1": 3,
1597                "a/b": { "c": 4 },
1598                "m~n": { "/": 5 }
1599            })
1600        );
1601    }
1602
1603    /// Oracle: RFC 6901 §3 — `escaped = "~" ( "0" / "1" )` and "It is an
1604    /// error condition if a JSON Pointer value does not conform to this
1605    /// syntax". RFC 8620 §5.3 requires keys in JSON Pointer format, so a
1606    /// malformed escape in any token is rejected.
1607    #[test]
1608    fn apply_jmap_patch_invalid_escape_is_rejected() {
1609        let before = json!({ "a": {} });
1610        for path in ["~2", "x~", "a/~", "~x/b", "a/b~"] {
1611            assert_patch_rejected(
1612                before.clone(),
1613                path,
1614                json!(1),
1615                PatchPathError::InvalidEscape,
1616            );
1617        }
1618    }
1619
1620    /// Oracle: RFC 6901 §3 — `reference-token = *( unescaped / escaped )`
1621    /// permits an empty token, and the §5 example evaluates `"/"` to the
1622    /// member named `""` (`"" : 0`). The PatchObject key `""` is the
1623    /// pointer `"/"`; `"a/"` is the pointer `"/a/"`.
1624    #[test]
1625    fn apply_jmap_patch_empty_token_names_empty_member() {
1626        let mut target = obj(json!({ "a": {} }));
1627        apply_jmap_patch(&mut target, "", json!(0)).expect("empty top-level token");
1628        apply_jmap_patch(&mut target, "a/", json!(1)).expect("empty nested token");
1629        assert_eq!(
1630            serde_json::Value::Object(target),
1631            json!({ "": 0, "a": { "": 1 } })
1632        );
1633    }
1634
1635    /// Oracle: an empty token is an ordinary member name, so a missing
1636    /// empty-named parent is rejected like any other missing parent
1637    /// (RFC 8620 §5.3 "All parts prior to the last ... MUST already
1638    /// exist").
1639    #[test]
1640    fn apply_jmap_patch_missing_empty_parent_is_rejected() {
1641        assert_patch_rejected(
1642            json!({ "a": {} }),
1643            "a//b",
1644            json!(1),
1645            PatchPathError::ParentMissing,
1646        );
1647    }
1648
1649    // ------------------------------------------------------------------
1650    // apply_patch_object (RFC 8620 §5.3 whole PatchObject)
1651    // ------------------------------------------------------------------
1652
1653    /// Oracle: RFC 8620 §5.3 — "There MUST NOT be two patches in the
1654    /// PatchObject where the pointer of one is the prefix of the pointer
1655    /// of the other, e.g., "alerts/1/offset" and "alerts""; on violation
1656    /// "the update MUST be rejected with an "invalidPatch" error".
1657    #[test]
1658    fn apply_patch_object_prefix_conflict_is_rejected() {
1659        let before = json!({ "alerts": { "1": { "offset": 0 } } });
1660        let mut target = obj(before.clone());
1661        let patch = obj(json!({ "alerts/1/offset": 5, "alerts": {} }));
1662        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
1663        assert_eq!(err, PatchPathError::PrefixConflict);
1664        assert_eq!(serde_json::Value::Object(target), before);
1665    }
1666
1667    /// Oracle: RFC 8620 §5.3 forbids only a pointer that is "the prefix of
1668    /// the pointer of the other"; JSON Pointers are compared by reference
1669    /// token (RFC 6901 §3), so "alert" is not a prefix of "alerts/x".
1670    #[test]
1671    fn apply_patch_object_near_prefix_is_accepted() {
1672        let mut target = obj(json!({ "alerts": {} }));
1673        let patch = obj(json!({ "alert": 1, "alerts/x": 2 }));
1674        apply_patch_object(&mut target, &patch).expect("no prefix conflict");
1675        assert_eq!(
1676            serde_json::Value::Object(target),
1677            json!({ "alert": 1, "alerts": { "x": 2 } })
1678        );
1679    }
1680
1681    /// Oracle: RFC 8620 §5.3 — "if there is any violation, the update MUST
1682    /// be rejected"; the valid entry "a" must not be applied either.
1683    #[test]
1684    fn apply_patch_object_partial_failure_leaves_target_unchanged() {
1685        let before = json!({ "a": 1 });
1686        let mut target = obj(before.clone());
1687        let patch = obj(json!({ "a": 2, "m/k": 1 }));
1688        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
1689        assert_eq!(err, PatchPathError::ParentMissing);
1690        assert_eq!(serde_json::Value::Object(target), before);
1691    }
1692
1693    /// A value nesting `levels` objects deep (`0` is the scalar `1`).
1694    fn nested(levels: usize) -> serde_json::Value {
1695        (0..levels).fold(json!(1), |inner, _| json!({ "k": inner }))
1696    }
1697
1698    /// Oracle: this crate's DoS guard, not an RFC 8620 §5.3 rule (RFC 8620
1699    /// §3.6.1 lets a server reject requests beyond its limits). Path
1700    /// segments plus value nesting may not exceed `MAX_MERGE_PATCH_DEPTH`
1701    /// (32): 3 + 30 = 33 is rejected before any entry is applied.
1702    #[test]
1703    fn apply_patch_object_path_plus_value_over_depth_cap_is_rejected() {
1704        let before = json!({ "x": 1, "a": { "b": {} } });
1705        let mut target = obj(before.clone());
1706        let patch = obj(json!({ "x": 2, "a/b/c": nested(30) }));
1707        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
1708        assert_eq!(err, PatchPathError::DepthExceeded);
1709        assert_eq!(serde_json::Value::Object(target), before);
1710    }
1711
1712    /// Oracle: the crate's DoS guard rejects only depth beyond
1713    /// `MAX_MERGE_PATCH_DEPTH`; exactly 3 segments + 29 levels = 32 applies.
1714    #[test]
1715    fn apply_patch_object_path_plus_value_at_depth_cap_applies() {
1716        let mut target = obj(json!({ "a": { "b": {} } }));
1717        let patch = obj(json!({ "a/b/c": nested(29) }));
1718        apply_patch_object(&mut target, &patch).expect("at the cap must apply");
1719        assert_eq!(
1720            serde_json::Value::Object(target),
1721            json!({ "a": { "b": { "c": nested(29) } } })
1722        );
1723    }
1724
1725    /// Oracle: the crate's DoS guard; a key of 33 segments exceeds
1726    /// `MAX_MERGE_PATCH_DEPTH` even with a scalar value.
1727    #[test]
1728    fn apply_patch_object_path_over_depth_cap_is_rejected() {
1729        let before = json!({ "a": {} });
1730        let mut target = obj(before.clone());
1731        let path = format!("a{}", "/k".repeat(32));
1732        let patch = obj(json!({ path: 1 }));
1733        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
1734        assert_eq!(err, PatchPathError::DepthExceeded);
1735        assert_eq!(serde_json::Value::Object(target), before);
1736    }
1737
1738    // ------------------------------------------------------------------
1739    // enforce_max_objects_in_set (bd:JMAP-ayoz.41.1) — RFC 8620 §5.3
1740    //
1741    // Oracles for all tests below are hand-built JmapError comparisons
1742    // and hand-built JSON args; the helper itself is never the oracle.
1743    // ------------------------------------------------------------------
1744
1745    /// Oracle (RFC 8620 §5.3): an empty `/set` args envelope (no
1746    /// `create` / `update` / `destroy` keys) MUST pass any positive cap.
1747    #[test]
1748    fn enforce_max_objects_in_set_empty_args_is_ok() {
1749        let args = json!({}).as_object().unwrap().clone();
1750        enforce_max_objects_in_set(&args, 500).expect("empty args must be under any positive cap");
1751    }
1752
1753    /// Oracle (RFC 8620 §5.3): at the exact boundary count == max, the
1754    /// helper MUST return Ok. The cap is enforced as strictly-greater
1755    /// (`count > max`), not greater-or-equal.
1756    #[test]
1757    fn enforce_max_objects_in_set_at_limit_is_ok() {
1758        // 5 + 5 + 5 = 15 entries against max=15 must pass.
1759        let mut create = serde_json::Map::new();
1760        let mut update = serde_json::Map::new();
1761        let mut destroy = Vec::new();
1762        for i in 0..5 {
1763            create.insert(format!("c{i}"), json!({}));
1764            update.insert(format!("u{i}"), json!({}));
1765            destroy.push(json!(format!("d{i}")));
1766        }
1767        let args = json!({
1768            "create": create,
1769            "update": update,
1770            "destroy": destroy,
1771        })
1772        .as_object()
1773        .unwrap()
1774        .clone();
1775        enforce_max_objects_in_set(&args, 15).expect("exact-boundary count must be allowed");
1776    }
1777
1778    /// Oracle (RFC 8620 §5.3, bd:JMAP-yt1w.30): one entry over the cap
1779    /// MUST return the method error "requestTooLarge" — "The total number
1780    /// of objects to create, update, or destroy exceeds the maximum number
1781    /// the server is willing to process in a single method call." — with
1782    /// description "maxObjectsInSet". The wire shape is verified by
1783    /// hand-building the expected JmapError independently of the helper.
1784    #[test]
1785    fn enforce_max_objects_in_set_over_limit_returns_limit_error() {
1786        // 5 + 5 + 6 = 16 entries against max=15 must fail.
1787        let mut create = serde_json::Map::new();
1788        let mut update = serde_json::Map::new();
1789        let mut destroy = Vec::new();
1790        for i in 0..5 {
1791            create.insert(format!("c{i}"), json!({}));
1792            update.insert(format!("u{i}"), json!({}));
1793        }
1794        for i in 0..6 {
1795            destroy.push(json!(format!("d{i}")));
1796        }
1797        let args = json!({
1798            "create": create,
1799            "update": update,
1800            "destroy": destroy,
1801        })
1802        .as_object()
1803        .unwrap()
1804        .clone();
1805        let err = enforce_max_objects_in_set(&args, 15)
1806            .expect_err("16-entry args against max=15 must fail");
1807        // Independent oracle — hand-built JmapError, not derived from
1808        // the function under test.
1809        let expected = jmap_types::JmapError::request_too_large();
1810        assert_eq!(
1811            err.error_type.as_str(),
1812            expected.error_type.as_str(),
1813            "type must be \"requestTooLarge\""
1814        );
1815        assert_eq!(
1816            err.description.as_deref(),
1817            Some("maxObjectsInSet"),
1818            "description must name the exceeded cap"
1819        );
1820    }
1821
1822    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
1823    /// "The following additional errors may be returned instead of the
1824    /// "Foo/set" response: "requestTooLarge": The total number of objects
1825    /// to create, update, or destroy exceeds the maximum number the server
1826    /// is willing to process in a single method call." Exceeding
1827    /// maxObjectsInSet is therefore the method-level error
1828    /// `requestTooLarge`, not the request-level `limit` error.
1829    #[test]
1830    fn enforce_max_objects_in_set_over_limit_returns_request_too_large() {
1831        let mut create = serde_json::Map::new();
1832        for i in 0..3 {
1833            create.insert(format!("c{i}"), json!({}));
1834        }
1835        let args = json!({
1836            "create": create,
1837            "destroy": ["d0"],
1838        })
1839        .as_object()
1840        .unwrap()
1841        .clone();
1842        let err =
1843            enforce_max_objects_in_set(&args, 3).expect_err("4-entry args against max=3 must fail");
1844        assert_eq!(
1845            err.error_type.as_str(),
1846            "requestTooLarge",
1847            "RFC 8620 §5.3: over-cap /set must yield method error requestTooLarge"
1848        );
1849    }
1850
1851    /// Oracle (RFC 8620 §5.3): a non-object `create` argument (e.g.
1852    /// `null` or a string) counts as 0 — wire-shape validation belongs
1853    /// to the per-handler argument parsing, not this cap helper. The
1854    /// handler will reject the malformed `create` downstream; this
1855    /// helper only counts well-formed entries.
1856    #[test]
1857    fn enforce_max_objects_in_set_ignores_non_object_create() {
1858        let args = json!({
1859            "create": null,
1860            "update": null,
1861            "destroy": ["id1"],
1862        })
1863        .as_object()
1864        .unwrap()
1865        .clone();
1866        // Only the 1 destroy entry counts.
1867        enforce_max_objects_in_set(&args, 1).expect("non-object create/update count as 0");
1868    }
1869
1870    /// Oracle (RFC 8620 §5.3): a non-array `destroy` argument counts
1871    /// as 0. Same rationale as the create/update test above.
1872    #[test]
1873    fn enforce_max_objects_in_set_ignores_non_array_destroy() {
1874        let args = json!({
1875            "create": { "c0": {} },
1876            "destroy": "not-an-array",
1877        })
1878        .as_object()
1879        .unwrap()
1880        .clone();
1881        // Only the 1 create entry counts.
1882        enforce_max_objects_in_set(&args, 1).expect("non-array destroy counts as 0");
1883    }
1884
1885    /// Oracle (RFC 8620 §5.3): the cap counts the SUM of all three
1886    /// sources. A request whose individual create/update/destroy
1887    /// counts are each below the cap can still trip the cap when
1888    /// summed.
1889    #[test]
1890    fn enforce_max_objects_in_set_sums_all_three() {
1891        // 3 + 3 + 3 = 9; against max=5, must fail because the SUM > max
1892        // even though each individual count <= max.
1893        let args = json!({
1894            "create": { "c0": {}, "c1": {}, "c2": {} },
1895            "update": { "u0": {}, "u1": {}, "u2": {} },
1896            "destroy": ["d0", "d1", "d2"],
1897        })
1898        .as_object()
1899        .unwrap()
1900        .clone();
1901        let err =
1902            enforce_max_objects_in_set(&args, 5).expect_err("sum-of-all-three must trip the cap");
1903        assert_eq!(err.error_type.as_str(), "requestTooLarge");
1904        assert_eq!(err.description.as_deref(), Some("maxObjectsInSet"));
1905    }
1906
1907    /// Oracle (RFC 8620 §5.5 + bd:JMAP-qz9v.48): `position` is a signed
1908    /// offset where non-negative is absolute and negative is
1909    /// end-relative. All hand-computed values below come from reading
1910    /// the spec text, NOT from the implementation under test.
1911    #[test]
1912    fn resolve_query_offset_absolute() {
1913        // Non-negative position: absolute offset, clamped at total.
1914        assert_eq!(resolve_query_offset(0, 100), 0);
1915        assert_eq!(resolve_query_offset(1, 100), 1);
1916        assert_eq!(resolve_query_offset(50, 100), 50);
1917        assert_eq!(resolve_query_offset(99, 100), 99);
1918        assert_eq!(resolve_query_offset(100, 100), 100);
1919        // Past-the-end → clamped to total (RFC 8620 §5.5 silent-clamp).
1920        assert_eq!(resolve_query_offset(101, 100), 100);
1921        assert_eq!(resolve_query_offset(10_000, 100), 100);
1922        assert_eq!(resolve_query_offset(i64::MAX, 100), 100);
1923    }
1924
1925    #[test]
1926    fn resolve_query_offset_end_relative() {
1927        // RFC 8620 §5.5: "-1 represents the last entry, -2 the second
1928        // to last". Implemented as `total - |position|`, saturating at
1929        // 0 from below.
1930        assert_eq!(resolve_query_offset(-1, 100), 99);
1931        assert_eq!(resolve_query_offset(-2, 100), 98);
1932        assert_eq!(resolve_query_offset(-99, 100), 1);
1933        assert_eq!(resolve_query_offset(-100, 100), 0);
1934        // Past-the-start → clamped to 0.
1935        assert_eq!(resolve_query_offset(-101, 100), 0);
1936        assert_eq!(resolve_query_offset(-10_000, 100), 0);
1937    }
1938
1939    /// Oracle: with total=0 (empty result list), every position
1940    /// resolves to 0 (the only valid index, and a no-op slice).
1941    #[test]
1942    fn resolve_query_offset_empty_total() {
1943        assert_eq!(resolve_query_offset(0, 0), 0);
1944        assert_eq!(resolve_query_offset(1, 0), 0);
1945        assert_eq!(resolve_query_offset(-1, 0), 0);
1946        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
1947        assert_eq!(resolve_query_offset(i64::MIN, 0), 0);
1948    }
1949
1950    /// Oracle: `i64::MIN` would overflow `-position` (the previous
1951    /// workspace idiom at mail-server `memory/mod.rs:980`) but
1952    /// `saturating_neg` returns `i64::MAX`. The resulting end-relative
1953    /// offset of `i64::MAX` is well past any realistic `total`, so for
1954    /// any realistic total the result is 0.
1955    ///
1956    /// For the synthetic case `total == usize::MAX`, the offset stays
1957    /// within the saturation range and the result is
1958    /// `usize::MAX - i64::MAX`, which on a 64-bit target is exactly
1959    /// `0x8000_0000_0000_0000`. The point of the regression guard is
1960    /// that the call does NOT panic (which it would under the prior
1961    /// `(-position) as usize` idiom in debug builds).
1962    #[test]
1963    fn resolve_query_offset_i64_min_does_not_overflow() {
1964        assert_eq!(resolve_query_offset(i64::MIN, 1), 0);
1965        assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
1966        assert_eq!(resolve_query_offset(i64::MIN, i64::MAX as usize), 0);
1967        // Synthetic upper bound: the answer is computable but not 0.
1968        // What matters is no overflow / no panic, and start <= total.
1969        let start = resolve_query_offset(i64::MIN, usize::MAX);
1970        assert_eq!(start, usize::MAX - (i64::MAX as usize));
1971        // And `i64::MAX` on the positive side is also handled.
1972        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
1973        assert_eq!(resolve_query_offset(i64::MAX, 1), 1);
1974    }
1975
1976    /// Oracle: the bead's specific concern was that `position as usize`
1977    /// truncates on 32-bit targets. On 64-bit (this test host) the
1978    /// `i64`-to-`usize` conversion is lossless within `[0, i64::MAX]`,
1979    /// so the truncation cannot be directly demonstrated; what we CAN
1980    /// verify is that the helper uses `usize::try_from` semantics, so
1981    /// a value above `i64::MAX` (only reachable here via direct cast
1982    /// from an unsigned constant) clamps to `total` rather than
1983    /// wrapping. The `i64::MIN` case in the prior test is the real
1984    /// regression guard.
1985    #[test]
1986    fn resolve_query_offset_truncation_resistant() {
1987        // The slice-safety property: `total..=total` is always a valid
1988        // start index for `slice[start..]` (yields empty slice). The
1989        // helper MUST return a value in `0..=total`.
1990        for &pos in &[i64::MIN, -1_000_000, -1, 0, 1, 1_000_000, i64::MAX] {
1991            for &total in &[0usize, 1, 100, 10_000] {
1992                let start = resolve_query_offset(pos, total);
1993                assert!(
1994                    start <= total,
1995                    "resolve_query_offset({pos}, {total}) = {start} violates start <= total"
1996                );
1997            }
1998        }
1999    }
2000    /// Oracle: RFC 8620 §5.5 (https://www.rfc-editor.org/rfc/rfc8620.txt):
2001    /// "If found, the "anchorOffset" is then added to its index.  If the
2002    /// resulting index is now negative, it is clamped to 0. ... If the
2003    /// anchor is not found, the call is rejected with an "anchorNotFound"
2004    /// error.  If an "anchor" is specified, any position argument supplied
2005    /// by the client MUST be ignored.  If no "anchor" is supplied, any
2006    /// "anchorOffset" argument MUST be ignored."
2007    ///
2008    /// `ids` is `[a, b, c, d]`, so anchor `c` is index 2.
2009    #[test]
2010    fn resolve_query_start_follows_rfc8620_anchor_rules() {
2011        let ids: Vec<jmap_types::Id> = ["a", "b", "c", "d"].map(jmap_types::Id::from).to_vec();
2012        let c = jmap_types::Id::from("c");
2013        let start = |position, anchor, offset| resolve_query_start(&ids, position, anchor, offset);
2014        assert_eq!(start(0, Some(&c), 1), Ok(3));
2015        assert_eq!(start(0, Some(&c), -1), Ok(1));
2016        assert_eq!(start(0, Some(&c), -5), Ok(0));
2017        assert_eq!(start(3, Some(&c), 0), Ok(2));
2018        assert_eq!(start(1, None, 2), Ok(1));
2019        let missing = jmap_types::Id::from("z");
2020        assert_eq!(
2021            start(0, Some(&missing), 0).map_err(|e| e.error_type),
2022            Err("anchorNotFound".to_owned())
2023        );
2024    }
2025}