Skip to main content

jmap_server/
helpers.rs

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