use std::borrow::Cow;
use jmap_types::{Id, JmapError, UTCDate};
use serde_json::{Map, Value};
pub fn serialize_value<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
serde_json::to_value(val).map_err(|e| JmapError::server_fail(e.to_string()))
}
#[deprecated(note = "renamed to serialize_value (bd:JMAP-wlip.21)")]
pub fn ser<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
serialize_value(val)
}
pub fn not_found_json(ids: &[Id]) -> Value {
Value::Array(
ids.iter()
.map(|id| Value::String(id.as_ref().to_owned()))
.collect(),
)
}
pub fn optional_arg<T>(
args: &mut Map<String, Value>,
name: &str,
invalid_arguments_with: impl FnOnce() -> JmapError,
) -> Result<Option<T>, JmapError>
where
T: serde::de::DeserializeOwned,
{
match args.remove(name).unwrap_or(Value::Null) {
Value::Null => Ok(None),
v => Ok(Some(
serde_json::from_value(v).map_err(|_| invalid_arguments_with())?,
)),
}
}
pub fn filter_arg<T>(args: &mut Map<String, Value>) -> Result<Option<T>, JmapError>
where
T: serde::de::DeserializeOwned,
{
match args.remove("filter").unwrap_or(Value::Null) {
Value::Null => Ok(None),
v @ Value::Object(_) => serde_json::from_value(v).map(Some).map_err(|e| {
let mut err = JmapError::unsupported_filter();
err.description = Some(format!("filter: {e}"));
err
}),
v => Err(JmapError::invalid_arguments(format!(
"filter: expected an object, got {v}"
))),
}
}
pub fn bool_arg(args: &Map<String, Value>, key: &str, default: bool) -> bool {
args.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
}
pub fn take_bool_arg(args: &mut Map<String, Value>, key: &str, default: bool) -> bool {
args.remove(key)
.and_then(|v| v.as_bool())
.unwrap_or(default)
}
pub fn extract_account_id(args: Value) -> Result<(Id, Map<String, Value>), JmapError> {
let Value::Object(mut args) = args else {
return Err(JmapError::invalid_arguments(
"arguments must be an object containing accountId",
));
};
let raw = args
.remove("accountId")
.ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
let s = raw
.as_str()
.ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
let id = Id::new_validated(s)
.map_err(|e| JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}")))?;
Ok((id, args))
}
pub fn now_utc_string() -> UTCDate {
now_utc_string_checked().expect("system clock returned an out-of-range value (bd:JMAP-jfia.30)")
}
pub fn now_utc_string_checked() -> Option<UTCDate> {
use std::time::SystemTime;
let (secs, millis) = signed_seconds_since_epoch(SystemTime::now())?;
let s = secs.rem_euclid(60);
let m = (secs / 60).rem_euclid(60);
let h = (secs / 3600).rem_euclid(24);
let days = secs.div_euclid(86400);
let (year, month, day) = civil_from_days(days)?;
Some(UTCDate::from(format!(
"{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{millis:03}Z"
)))
}
pub(crate) fn signed_seconds_since_epoch(now: std::time::SystemTime) -> Option<(i64, u32)> {
use std::time::UNIX_EPOCH;
match now.duration_since(UNIX_EPOCH) {
Ok(d) => {
let s = i64::try_from(d.as_secs()).ok()?;
Some((s, d.subsec_millis()))
}
Err(e) => {
let d = e.duration();
let s = i64::try_from(d.as_secs()).ok()?;
let neg = s.checked_neg()?;
Some((neg, d.subsec_millis()))
}
}
}
pub fn utc_date_from_epoch_seconds(secs: i64) -> Option<UTCDate> {
let time_of_day = secs.rem_euclid(86400);
let (h, m, s) = (
time_of_day / 3600,
time_of_day % 3600 / 60,
time_of_day % 60,
);
let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;
if !(0..=9999).contains(&year) {
return None;
}
Some(UTCDate::from(format!(
"{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}Z"
)))
}
fn civil_from_days(z: i64) -> Option<(i32, u8, u8)> {
let z = z + 719_468;
let era: i64 = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let mo = if mp < 10 { mp + 3 } else { mp - 9 }; let yr = if mo <= 2 { y + 1 } else { y };
Some((
i32::try_from(yr).ok()?,
u8::try_from(mo).expect("month bounded by algorithm to [1, 12]"),
u8::try_from(d).expect("day bounded by algorithm to [1, 31]"),
))
}
pub(crate) const MAX_MERGE_PATCH_DEPTH: usize = 32;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergePatchError {
DepthExceeded,
}
impl std::fmt::Display for MergePatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DepthExceeded => write!(
f,
"merge patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels"
),
}
}
}
impl std::error::Error for MergePatchError {}
pub fn json_merge_patch(target: &mut Value, patch: Value) -> Result<(), MergePatchError> {
json_merge_patch_inner(target, patch, 0)
}
fn json_merge_patch_inner(
target: &mut Value,
patch: Value,
depth: usize,
) -> Result<(), MergePatchError> {
if depth > MAX_MERGE_PATCH_DEPTH {
return Err(MergePatchError::DepthExceeded);
}
match patch {
Value::Object(patch_map) => {
if !target.is_object() {
*target = Value::Object(Map::new());
}
let target_map = target
.as_object_mut()
.expect("target was just set to Value::Object above");
for (key, patch_val) in patch_map {
if patch_val.is_null() {
target_map.remove(&key);
} else {
let entry = target_map.entry(key).or_insert(Value::Null);
json_merge_patch_inner(entry, patch_val, depth + 1)?;
}
}
}
other => *target = other,
}
Ok(())
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatchPathError {
ParentMissing,
InsideArray,
ParentNotObject,
InvalidEscape,
PrefixConflict,
DepthExceeded,
}
impl std::fmt::Display for PatchPathError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ParentMissing => f.write_str("patch path parent does not exist"),
Self::InsideArray => f.write_str("patch path references inside an array"),
Self::ParentNotObject => f.write_str("patch path parent is not an object"),
Self::InvalidEscape => f.write_str("patch path has a '~' not followed by '0' or '1'"),
Self::PrefixConflict => {
f.write_str("patch has a path that is a prefix of another path")
}
Self::DepthExceeded => {
write!(f, "patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels")
}
}
}
}
impl std::error::Error for PatchPathError {}
pub fn apply_jmap_patch(
target: &mut Map<String, Value>,
path: &str,
value: Value,
) -> Result<(), PatchPathError> {
let segments = path.split('/').count();
if segments > MAX_MERGE_PATCH_DEPTH
|| nests_deeper_than(&value, MAX_MERGE_PATCH_DEPTH - segments)
{
return Err(PatchPathError::DepthExceeded);
}
let (parents, leaf) = match path.rsplit_once('/') {
Some((parents, leaf)) => (Some(parents), leaf),
None => (None, path),
};
let leaf = decode_pointer_token(leaf)?;
let mut parent = target;
for token in parents.into_iter().flat_map(|p| p.split('/')) {
parent = match parent.get_mut(decode_pointer_token(token)?.as_ref()) {
Some(Value::Object(map)) => map,
Some(Value::Array(_)) => return Err(PatchPathError::InsideArray),
Some(_) => return Err(PatchPathError::ParentNotObject),
None => return Err(PatchPathError::ParentMissing),
};
}
if value.is_null() {
parent.remove(leaf.as_ref());
} else {
parent.insert(leaf.into_owned(), value);
}
Ok(())
}
pub fn apply_patch_object(
target: &mut Map<String, Value>,
patch: &Map<String, Value>,
) -> Result<(), PatchPathError> {
let mut pointers = patch
.keys()
.map(|k| {
k.split('/')
.map(decode_pointer_token)
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()?;
pointers.sort_unstable();
if pointers.windows(2).any(|w| w[1].starts_with(&w[0])) {
return Err(PatchPathError::PrefixConflict);
}
let mut patched = target.clone();
for (path, value) in patch {
apply_jmap_patch(&mut patched, path, value.clone())?;
}
*target = patched;
Ok(())
}
fn nests_deeper_than(value: &Value, limit: usize) -> bool {
match value {
Value::Object(map) => limit == 0 || map.values().any(|v| nests_deeper_than(v, limit - 1)),
Value::Array(items) => limit == 0 || items.iter().any(|v| nests_deeper_than(v, limit - 1)),
_ => false,
}
}
fn decode_pointer_token(token: &str) -> Result<Cow<'_, str>, PatchPathError> {
if !token.contains('~') {
return Ok(Cow::Borrowed(token));
}
let escapes_valid = token
.match_indices('~')
.all(|(i, _)| matches!(token.as_bytes().get(i + 1), Some(b'0' | b'1')));
if !escapes_valid {
return Err(PatchPathError::InvalidEscape);
}
Ok(Cow::Owned(token.replace("~1", "/").replace("~0", "~")))
}
#[must_use]
pub fn resolve_query_offset(position: i64, total: usize) -> usize {
if position >= 0 {
usize::try_from(position).unwrap_or(usize::MAX).min(total)
} else {
let neg = usize::try_from(position.saturating_neg()).unwrap_or(usize::MAX);
total.saturating_sub(neg)
}
}
pub fn query_anchor_args(args: &Map<String, Value>) -> Result<(Option<Id>, i64), JmapError> {
let anchor = match args.get("anchor") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(Id::from(s.as_str())),
Some(v) => {
return Err(JmapError::invalid_arguments(format!(
"anchor: expected an Id string or null, got {v}"
)))
}
};
let anchor_offset = match args.get("anchorOffset") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!("anchorOffset: expected an integer, got {v}"))
})?,
};
Ok((anchor, anchor_offset))
}
pub fn resolve_query_start(
ids: &[Id],
position: i64,
anchor: Option<&Id>,
anchor_offset: i64,
) -> Result<usize, JmapError> {
let Some(anchor) = anchor else {
return Ok(resolve_query_offset(position, ids.len()));
};
let index = ids
.iter()
.position(|id| id == anchor)
.ok_or_else(JmapError::anchor_not_found)?;
let start = i64::try_from(index)
.unwrap_or(i64::MAX)
.saturating_add(anchor_offset)
.max(0);
Ok(resolve_query_offset(start, ids.len()))
}
pub fn enforce_max_objects_in_set(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
let create_count = args
.get("create")
.and_then(|v| v.as_object())
.map_or(0u64, |m| m.len() as u64);
let update_count = args
.get("update")
.and_then(|v| v.as_object())
.map_or(0u64, |m| m.len() as u64);
let destroy_count = args
.get("destroy")
.and_then(|v| v.as_array())
.map_or(0u64, |a| a.len() as u64);
let count = create_count
.saturating_add(update_count)
.saturating_add(destroy_count);
if count > max {
let mut err = JmapError::request_too_large();
err.description = Some("maxObjectsInSet".into());
return Err(err);
}
Ok(())
}
pub fn enforce_max_objects_in_get(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
let count = args
.get("ids")
.and_then(|v| v.as_array())
.map_or(0u64, |a| a.len() as u64);
if count > max {
let mut err = JmapError::request_too_large();
err.description = Some("maxObjectsInGet".into());
return Err(err);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{
apply_jmap_patch, apply_patch_object, civil_from_days, enforce_max_objects_in_set,
extract_account_id, filter_arg, json_merge_patch, now_utc_string, resolve_query_offset,
resolve_query_start, utc_date_from_epoch_seconds, MergePatchError, PatchPathError,
MAX_MERGE_PATCH_DEPTH,
};
use serde_json::json;
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct NameCond {
name: Option<String>,
}
fn filter_of(v: serde_json::Value) -> Result<Option<NameCond>, jmap_types::JmapError> {
let mut args = json!({ "filter": v }).as_object().cloned().expect("object");
filter_arg::<NameCond>(&mut args)
}
#[test]
fn filter_arg_maps_object_and_non_object_failures() {
assert!(filter_of(json!(null)).expect("null").is_none());
let cond = filter_of(json!({ "name": "x" })).expect("known key");
assert_eq!(cond.and_then(|c| c.name).as_deref(), Some("x"));
let err = filter_of(json!({ "label": "x" })).expect_err("unknown key");
assert_eq!(err.error_type, "unsupportedFilter");
assert!(
err.description
.as_deref()
.is_some_and(|d| d.contains("label")),
"{err:?}"
);
let err = filter_of(json!(42)).expect_err("scalar");
assert_eq!(err.error_type, "invalidArguments");
}
#[test]
fn extract_account_id_rejects_malformed_id() {
let err = extract_account_id(json!({ "accountId": "" }))
.expect_err("empty accountId must fail validation");
assert_eq!(err.error_type.as_str(), "invalidArguments");
let err = extract_account_id(json!({ "accountId": "my account" }))
.expect_err("space in accountId must fail validation");
assert_eq!(err.error_type.as_str(), "invalidArguments");
let err = extract_account_id(json!({ "accountId": "a\"b" }))
.expect_err("DQUOTE in accountId must fail validation");
assert_eq!(err.error_type.as_str(), "invalidArguments");
let long: String = "a".repeat(256);
let err = extract_account_id(json!({ "accountId": long }))
.expect_err("over-long accountId must fail validation");
assert_eq!(err.error_type.as_str(), "invalidArguments");
}
#[test]
fn extract_account_id_accepts_well_formed_id() {
let (id, rest) = extract_account_id(json!({
"accountId": "u123-abc_DEF",
"ids": ["e1", "e2"]
}))
.expect("well-formed accountId must pass validation");
assert_eq!(id.as_ref(), "u123-abc_DEF");
assert!(rest.contains_key("ids"));
assert!(
!rest.contains_key("accountId"),
"accountId must be removed from args after extraction"
);
}
#[test]
fn civil_from_days_known_dates() {
let cases: &[(i64, (i32, u8, u8))] = &[
(0, (1970, 1, 1)), (365, (1971, 1, 1)), (10957, (2000, 1, 1)), (11016, (2000, 2, 29)), (11017, (2000, 3, 1)), (19358, (2023, 1, 1)), (19722, (2023, 12, 31)), (19782, (2024, 2, 29)), (19783, (2024, 3, 1)), ];
for &(days, expected) in cases {
assert_eq!(
civil_from_days(days),
Some(expected),
"civil_from_days({days}) mismatch"
);
}
}
#[test]
fn civil_from_days_returns_none_on_year_overflow() {
let max_days = i64::MAX / 86400;
assert_eq!(
civil_from_days(max_days),
None,
"i64::MAX / 86400 days must overflow i32 year"
);
let min_days = i64::MIN / 86400;
assert_eq!(
civil_from_days(min_days),
None,
"i64::MIN / 86400 days must overflow i32 year"
);
let year_58m_days = 10_i64 * i64::from(i32::MAX);
let result = civil_from_days(year_58m_days);
assert!(
result.is_some(),
"i32-fitting year must return Some; got {result:?}"
);
}
#[test]
fn now_utc_string_checked_returns_some_on_sane_clock() {
use super::now_utc_string_checked;
let dt = now_utc_string_checked().expect(
"test host clock must be reasonable enough for now_utc_string_checked to succeed",
);
let s: &str = dt.as_ref();
assert_eq!(s.len(), 24, "wire shape must be 24 chars: {s:?}");
assert!(s.ends_with('Z'), "must end with Z: {s:?}");
}
#[test]
fn now_utc_string_matches_checked_variant_on_sane_clock() {
use super::now_utc_string_checked;
let panicky = now_utc_string();
let checked = now_utc_string_checked().expect("test host clock must be reasonable");
let panicky_s: &str = panicky.as_ref();
let checked_s: &str = checked.as_ref();
assert_eq!(
panicky_s.len(),
checked_s.len(),
"wire-format lengths must match: panicky={panicky_s:?} checked={checked_s:?}"
);
assert_eq!(
&panicky_s[..10],
&checked_s[..10],
"date portions must match: panicky={panicky_s:?} checked={checked_s:?}"
);
}
#[test]
fn utc_date_from_epoch_seconds_known_values() {
for (secs, expected) in [
(0, Some("1970-01-01T00:00:00Z")),
(-1, Some("1969-12-31T23:59:59Z")),
(1_414_649_520, Some("2014-10-30T06:12:00Z")),
(1_531_448_069, Some("2018-07-13T02:14:29Z")),
(253_402_300_799, Some("9999-12-31T23:59:59Z")),
(253_402_300_800, None),
(-62_167_219_200, Some("0000-01-01T00:00:00Z")),
(-62_167_219_201, None),
] {
assert_eq!(
utc_date_from_epoch_seconds(secs)
.as_ref()
.map(AsRef::as_ref),
expected,
"secs = {secs}"
);
}
}
#[test]
fn now_utc_string_format() {
let dt = now_utc_string();
let s: &str = dt.as_ref();
assert_eq!(s.len(), 24, "unexpected length: {s}");
assert!(s.ends_with('Z'), "must end with Z: {s}");
assert_eq!(&s[4..5], "-", "missing year-month separator: {s}");
assert_eq!(&s[7..8], "-", "missing month-day separator: {s}");
assert_eq!(&s[10..11], "T", "missing date-time separator: {s}");
assert_eq!(&s[13..14], ":", "missing hour-minute separator: {s}");
assert_eq!(&s[16..17], ":", "missing minute-second separator: {s}");
assert_eq!(&s[19..20], ".", "missing decimal point before millis: {s}");
assert!(
s[20..23].chars().all(|c| c.is_ascii_digit()),
"milliseconds must be 3 digits: {s}"
);
assert!(
s.starts_with("20"),
"year should start with 20 in 21st century: {s}"
);
}
#[test]
fn json_merge_patch_does_not_stack_overflow() {
const DEPTH: usize = 1000;
let mut target = serde_json::json!({});
for _ in 0..DEPTH {
target = serde_json::json!({ "a": target });
}
let mut patch = serde_json::json!({});
for _ in 0..DEPTH {
patch = serde_json::json!({ "a": patch });
}
let err = json_merge_patch(&mut target, patch)
.expect_err("deep patch must surface DepthExceeded, not silently truncate");
assert_eq!(
err,
MergePatchError::DepthExceeded,
"deep patch must return MergePatchError::DepthExceeded"
);
}
#[test]
fn json_merge_patch_at_exact_cap_applies() {
let mut patch = serde_json::json!({ "leaf": "value" });
for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
patch = serde_json::json!({ "a": patch });
}
let mut target = serde_json::json!({});
json_merge_patch(&mut target, patch).expect("patch at the cap must apply");
let mut cursor = ⌖
for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
cursor = cursor.get("a").expect("each level must have 'a'");
}
assert_eq!(
cursor.get("leaf"),
Some(&serde_json::Value::String("value".to_owned())),
"the leaf field at exactly MAX_MERGE_PATCH_DEPTH must be applied"
);
}
#[test]
fn json_merge_patch_shallow_applies_normally() {
let mut target = serde_json::json!({ "a": 1, "b": { "c": 2 } });
let patch = serde_json::json!({ "b": { "c": 99, "d": 7 }, "e": null });
json_merge_patch(&mut target, patch).expect("shallow patch must succeed");
assert_eq!(
target,
serde_json::json!({ "a": 1, "b": { "c": 99, "d": 7 } }),
"RFC 7396 merge semantics broken at shallow depth"
);
}
#[test]
fn json_merge_patch_adds_nested_object_to_absent_field() {
let mut target = serde_json::json!({ "a": 1 });
let patch = serde_json::json!({ "b": { "c": 2 } });
json_merge_patch(&mut target, patch).expect("nested-add patch must succeed");
assert_eq!(
target,
serde_json::json!({ "a": 1, "b": { "c": 2 } }),
"patch must add the nested object at the previously-absent field"
);
}
#[test]
fn merge_patch_error_display() {
let err = MergePatchError::DepthExceeded;
let s = err.to_string();
assert!(
s.contains(&MAX_MERGE_PATCH_DEPTH.to_string()),
"Display must mention the cap value; got {s:?}"
);
assert!(
s.contains("merge patch"),
"Display must identify the error source; got {s:?}"
);
}
fn obj(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
match v {
serde_json::Value::Object(m) => m,
other => panic!("fixture must be a JSON object, got {other}"),
}
}
fn assert_patch_rejected(
before: serde_json::Value,
path: &str,
value: serde_json::Value,
want: PatchPathError,
) {
let mut target = obj(before.clone());
let err = apply_jmap_patch(&mut target, path, value).expect_err("patch must be rejected");
assert_eq!(err, want, "wrong error for path {path:?}");
assert_eq!(
serde_json::Value::Object(target),
before,
"rejected patch {path:?} must leave the object unchanged"
);
}
#[test]
fn apply_jmap_patch_non_null_adds_or_replaces() {
let mut target = obj(json!({ "a": 1 }));
apply_jmap_patch(&mut target, "a", json!(2)).expect("replace");
apply_jmap_patch(&mut target, "b", json!("x")).expect("add");
assert_eq!(
serde_json::Value::Object(target),
json!({ "a": 2, "b": "x" })
);
}
#[test]
fn apply_jmap_patch_null_removes_and_absent_is_noop() {
let mut target = obj(json!({ "a": 1, "m": { "k": true } }));
apply_jmap_patch(&mut target, "a", serde_json::Value::Null).expect("remove");
apply_jmap_patch(&mut target, "m/k", serde_json::Value::Null).expect("nested remove");
apply_jmap_patch(&mut target, "m/absent", serde_json::Value::Null).expect("no-op");
assert_eq!(serde_json::Value::Object(target), json!({ "m": {} }));
}
#[test]
fn apply_jmap_patch_nested_path_sets_member_of_existing_object() {
let mut target = obj(json!({ "mailboxIds": { "inbox": true }, "x": { "y": { "z": 1 } } }));
apply_jmap_patch(&mut target, "mailboxIds/abc", json!(true)).expect("set");
apply_jmap_patch(&mut target, "x/y/w", json!(2)).expect("deep set");
assert_eq!(
serde_json::Value::Object(target),
json!({ "mailboxIds": { "inbox": true, "abc": true }, "x": { "y": { "z": 1, "w": 2 } } })
);
}
#[test]
fn apply_jmap_patch_missing_parent_is_rejected() {
let before = json!({ "a": { "b": {} } });
for value in [json!("v"), serde_json::Value::Null] {
assert_patch_rejected(
before.clone(),
"x/y",
value.clone(),
PatchPathError::ParentMissing,
);
assert_patch_rejected(
before.clone(),
"a/c/d",
value,
PatchPathError::ParentMissing,
);
}
}
#[test]
fn apply_jmap_patch_non_object_parent_is_rejected() {
let before = json!({ "s": "text", "n": 42, "b": true, "z": null });
for parent in ["s", "n", "b", "z"] {
assert_patch_rejected(
before.clone(),
&format!("{parent}/sub"),
json!("would-clobber"),
PatchPathError::ParentNotObject,
);
}
}
#[test]
fn apply_jmap_patch_inside_array_is_rejected() {
let before = json!({ "list": ["a", { "k": 1 }] });
assert_patch_rejected(
before.clone(),
"list/0",
json!("x"),
PatchPathError::InsideArray,
);
assert_patch_rejected(
before.clone(),
"list/1/k",
json!(2),
PatchPathError::InsideArray,
);
assert_patch_rejected(
before,
"list/0",
serde_json::Value::Null,
PatchPathError::InsideArray,
);
}
#[test]
fn apply_jmap_patch_replaces_whole_array() {
let mut target = obj(json!({ "list": ["a"] }));
apply_jmap_patch(&mut target, "list", json!(["b", "c"])).expect("replace array");
assert_eq!(
serde_json::Value::Object(target),
json!({ "list": ["b", "c"] })
);
}
#[test]
fn apply_jmap_patch_decodes_rfc6901_escapes() {
let mut target = obj(json!({ "a/b": {}, "m~n": {} }));
apply_jmap_patch(&mut target, "foo~1bar", json!(1)).expect("~1");
apply_jmap_patch(&mut target, "foo~0bar", json!(2)).expect("~0");
apply_jmap_patch(&mut target, "~01", json!(3)).expect("~01");
apply_jmap_patch(&mut target, "a~1b/c", json!(4)).expect("escaped parent");
apply_jmap_patch(&mut target, "m~0n/~1", json!(5)).expect("escaped parent and leaf");
assert_eq!(
serde_json::Value::Object(target),
json!({
"foo/bar": 1,
"foo~bar": 2,
"~1": 3,
"a/b": { "c": 4 },
"m~n": { "/": 5 }
})
);
}
#[test]
fn apply_jmap_patch_invalid_escape_is_rejected() {
let before = json!({ "a": {} });
for path in ["~2", "x~", "a/~", "~x/b", "a/b~"] {
assert_patch_rejected(
before.clone(),
path,
json!(1),
PatchPathError::InvalidEscape,
);
}
}
#[test]
fn apply_jmap_patch_empty_token_names_empty_member() {
let mut target = obj(json!({ "a": {} }));
apply_jmap_patch(&mut target, "", json!(0)).expect("empty top-level token");
apply_jmap_patch(&mut target, "a/", json!(1)).expect("empty nested token");
assert_eq!(
serde_json::Value::Object(target),
json!({ "": 0, "a": { "": 1 } })
);
}
#[test]
fn apply_jmap_patch_missing_empty_parent_is_rejected() {
assert_patch_rejected(
json!({ "a": {} }),
"a//b",
json!(1),
PatchPathError::ParentMissing,
);
}
#[test]
fn apply_patch_object_prefix_conflict_is_rejected() {
let before = json!({ "alerts": { "1": { "offset": 0 } } });
let mut target = obj(before.clone());
let patch = obj(json!({ "alerts/1/offset": 5, "alerts": {} }));
let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
assert_eq!(err, PatchPathError::PrefixConflict);
assert_eq!(serde_json::Value::Object(target), before);
}
#[test]
fn apply_patch_object_near_prefix_is_accepted() {
let mut target = obj(json!({ "alerts": {} }));
let patch = obj(json!({ "alert": 1, "alerts/x": 2 }));
apply_patch_object(&mut target, &patch).expect("no prefix conflict");
assert_eq!(
serde_json::Value::Object(target),
json!({ "alert": 1, "alerts": { "x": 2 } })
);
}
#[test]
fn apply_patch_object_partial_failure_leaves_target_unchanged() {
let before = json!({ "a": 1 });
let mut target = obj(before.clone());
let patch = obj(json!({ "a": 2, "m/k": 1 }));
let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
assert_eq!(err, PatchPathError::ParentMissing);
assert_eq!(serde_json::Value::Object(target), before);
}
fn nested(levels: usize) -> serde_json::Value {
(0..levels).fold(json!(1), |inner, _| json!({ "k": inner }))
}
#[test]
fn apply_patch_object_path_plus_value_over_depth_cap_is_rejected() {
let before = json!({ "x": 1, "a": { "b": {} } });
let mut target = obj(before.clone());
let patch = obj(json!({ "x": 2, "a/b/c": nested(30) }));
let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
assert_eq!(err, PatchPathError::DepthExceeded);
assert_eq!(serde_json::Value::Object(target), before);
}
#[test]
fn apply_patch_object_path_plus_value_at_depth_cap_applies() {
let mut target = obj(json!({ "a": { "b": {} } }));
let patch = obj(json!({ "a/b/c": nested(29) }));
apply_patch_object(&mut target, &patch).expect("at the cap must apply");
assert_eq!(
serde_json::Value::Object(target),
json!({ "a": { "b": { "c": nested(29) } } })
);
}
#[test]
fn apply_patch_object_path_over_depth_cap_is_rejected() {
let before = json!({ "a": {} });
let mut target = obj(before.clone());
let path = format!("a{}", "/k".repeat(32));
let patch = obj(json!({ path: 1 }));
let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
assert_eq!(err, PatchPathError::DepthExceeded);
assert_eq!(serde_json::Value::Object(target), before);
}
#[test]
fn enforce_max_objects_in_set_empty_args_is_ok() {
let args = json!({}).as_object().unwrap().clone();
enforce_max_objects_in_set(&args, 500).expect("empty args must be under any positive cap");
}
#[test]
fn enforce_max_objects_in_set_at_limit_is_ok() {
let mut create = serde_json::Map::new();
let mut update = serde_json::Map::new();
let mut destroy = Vec::new();
for i in 0..5 {
create.insert(format!("c{i}"), json!({}));
update.insert(format!("u{i}"), json!({}));
destroy.push(json!(format!("d{i}")));
}
let args = json!({
"create": create,
"update": update,
"destroy": destroy,
})
.as_object()
.unwrap()
.clone();
enforce_max_objects_in_set(&args, 15).expect("exact-boundary count must be allowed");
}
#[test]
fn enforce_max_objects_in_set_over_limit_returns_limit_error() {
let mut create = serde_json::Map::new();
let mut update = serde_json::Map::new();
let mut destroy = Vec::new();
for i in 0..5 {
create.insert(format!("c{i}"), json!({}));
update.insert(format!("u{i}"), json!({}));
}
for i in 0..6 {
destroy.push(json!(format!("d{i}")));
}
let args = json!({
"create": create,
"update": update,
"destroy": destroy,
})
.as_object()
.unwrap()
.clone();
let err = enforce_max_objects_in_set(&args, 15)
.expect_err("16-entry args against max=15 must fail");
let expected = jmap_types::JmapError::request_too_large();
assert_eq!(
err.error_type.as_str(),
expected.error_type.as_str(),
"type must be \"requestTooLarge\""
);
assert_eq!(
err.description.as_deref(),
Some("maxObjectsInSet"),
"description must name the exceeded cap"
);
}
#[test]
fn enforce_max_objects_in_set_over_limit_returns_request_too_large() {
let mut create = serde_json::Map::new();
for i in 0..3 {
create.insert(format!("c{i}"), json!({}));
}
let args = json!({
"create": create,
"destroy": ["d0"],
})
.as_object()
.unwrap()
.clone();
let err =
enforce_max_objects_in_set(&args, 3).expect_err("4-entry args against max=3 must fail");
assert_eq!(
err.error_type.as_str(),
"requestTooLarge",
"RFC 8620 §5.3: over-cap /set must yield method error requestTooLarge"
);
}
#[test]
fn enforce_max_objects_in_set_ignores_non_object_create() {
let args = json!({
"create": null,
"update": null,
"destroy": ["id1"],
})
.as_object()
.unwrap()
.clone();
enforce_max_objects_in_set(&args, 1).expect("non-object create/update count as 0");
}
#[test]
fn enforce_max_objects_in_set_ignores_non_array_destroy() {
let args = json!({
"create": { "c0": {} },
"destroy": "not-an-array",
})
.as_object()
.unwrap()
.clone();
enforce_max_objects_in_set(&args, 1).expect("non-array destroy counts as 0");
}
#[test]
fn enforce_max_objects_in_set_sums_all_three() {
let args = json!({
"create": { "c0": {}, "c1": {}, "c2": {} },
"update": { "u0": {}, "u1": {}, "u2": {} },
"destroy": ["d0", "d1", "d2"],
})
.as_object()
.unwrap()
.clone();
let err =
enforce_max_objects_in_set(&args, 5).expect_err("sum-of-all-three must trip the cap");
assert_eq!(err.error_type.as_str(), "requestTooLarge");
assert_eq!(err.description.as_deref(), Some("maxObjectsInSet"));
}
#[test]
fn resolve_query_offset_absolute() {
assert_eq!(resolve_query_offset(0, 100), 0);
assert_eq!(resolve_query_offset(1, 100), 1);
assert_eq!(resolve_query_offset(50, 100), 50);
assert_eq!(resolve_query_offset(99, 100), 99);
assert_eq!(resolve_query_offset(100, 100), 100);
assert_eq!(resolve_query_offset(101, 100), 100);
assert_eq!(resolve_query_offset(10_000, 100), 100);
assert_eq!(resolve_query_offset(i64::MAX, 100), 100);
}
#[test]
fn resolve_query_offset_end_relative() {
assert_eq!(resolve_query_offset(-1, 100), 99);
assert_eq!(resolve_query_offset(-2, 100), 98);
assert_eq!(resolve_query_offset(-99, 100), 1);
assert_eq!(resolve_query_offset(-100, 100), 0);
assert_eq!(resolve_query_offset(-101, 100), 0);
assert_eq!(resolve_query_offset(-10_000, 100), 0);
}
#[test]
fn resolve_query_offset_empty_total() {
assert_eq!(resolve_query_offset(0, 0), 0);
assert_eq!(resolve_query_offset(1, 0), 0);
assert_eq!(resolve_query_offset(-1, 0), 0);
assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
assert_eq!(resolve_query_offset(i64::MIN, 0), 0);
}
#[test]
fn resolve_query_offset_i64_min_does_not_overflow() {
assert_eq!(resolve_query_offset(i64::MIN, 1), 0);
assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
assert_eq!(resolve_query_offset(i64::MIN, i64::MAX as usize), 0);
let start = resolve_query_offset(i64::MIN, usize::MAX);
assert_eq!(start, usize::MAX - (i64::MAX as usize));
assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
assert_eq!(resolve_query_offset(i64::MAX, 1), 1);
}
#[test]
fn resolve_query_offset_truncation_resistant() {
for &pos in &[i64::MIN, -1_000_000, -1, 0, 1, 1_000_000, i64::MAX] {
for &total in &[0usize, 1, 100, 10_000] {
let start = resolve_query_offset(pos, total);
assert!(
start <= total,
"resolve_query_offset({pos}, {total}) = {start} violates start <= total"
);
}
}
}
#[test]
fn resolve_query_start_follows_rfc8620_anchor_rules() {
let ids: Vec<jmap_types::Id> = ["a", "b", "c", "d"].map(jmap_types::Id::from).to_vec();
let c = jmap_types::Id::from("c");
let start = |position, anchor, offset| resolve_query_start(&ids, position, anchor, offset);
assert_eq!(start(0, Some(&c), 1), Ok(3));
assert_eq!(start(0, Some(&c), -1), Ok(1));
assert_eq!(start(0, Some(&c), -5), Ok(0));
assert_eq!(start(3, Some(&c), 0), Ok(2));
assert_eq!(start(1, None, 2), Ok(1));
let missing = jmap_types::Id::from("z");
assert_eq!(
start(0, Some(&missing), 0).map_err(|e| e.error_type),
Err("anchorNotFound".to_owned())
);
}
}