Skip to main content

jmap_server/
helpers.rs

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