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