jmap_server/parse.rs
1//! Request parsing and ResultReference resolution (RFC 8620 §3.3, §3.7).
2
3use crate::{Invocation, JmapError, JmapRequest, ResultReference};
4use serde_json::Value;
5
6/// Parse and validate a JMAP request from a raw JSON value.
7///
8/// Validates:
9/// - The body deserializes as a [`JmapRequest`].
10/// - The number of method calls does not exceed `max_calls` (RFC 8620 §3.3).
11///
12/// An empty `using` array is **not** rejected here. Per the jmap-test-suite
13/// conformance ruling (Q4 / `error-empty-using`), the server must process the
14/// request and return `unknownMethod` for every call — not a 400-level
15/// `notRequest`. Capability URI validation is the caller's responsibility;
16/// call [`check_known_capabilities`] immediately after this function and map
17/// any `Err` to an HTTP 400 response.
18///
19/// # Caller responsibility: `notJSON`
20///
21/// This function takes a pre-parsed [`serde_json::Value`], not raw bytes. The
22/// caller is responsible for the initial JSON parse of the HTTP request body.
23/// If that parse fails (the body is not valid JSON), the caller must produce the
24/// `notJSON` error response itself — [`crate::error_invocation`] and
25/// [`crate::request_error`] with [`JmapError::not_json()`] handle that case.
26/// `parse_request` only validates the JMAP structure of an already-parsed value.
27///
28/// # Caller responsibility: resource limits
29///
30/// Because this function works on an already-parsed [`serde_json::Value`], it
31/// cannot enforce the byte-size or JSON-nesting-depth limits that determine
32/// whether the input is safe to walk on a worker thread. Those limits MUST
33/// be applied by the HTTP integration before `parse_request` is called:
34///
35/// - **Body size cap.** Apply a maximum request-body size before reading the
36/// body into memory. RFC 8620 §3 defines `maxSizeRequest` as a session
37/// capability the server advertises; the byte cap MUST be `<=` that value.
38/// A sensible default is 10 MiB. In `axum`, wrap your router with
39/// `tower_http::limit::RequestBodyLimitLayer`; in `hyper`, use
40/// `http_body_util::Limited`; in `warp`, pair `warp::body::content_length_limit`
41/// with `warp::body::bytes`.
42/// - **JSON nesting depth cap.** Use `serde_json::from_slice` (which honours
43/// `serde_json`'s recursion limit) rather than constructing a [`Value`] by
44/// hand. `serde_json`'s default 128-level recursion limit is intentionally
45/// loose; deployments that face untrusted clients should consider rejecting
46/// request bodies that exceed ~32 levels of JSON nesting before passing
47/// them here. 32 levels is well above any legitimate JMAP request shape.
48/// - **Per-pointer recursion.** ResultReference paths are walked by an
49/// internal helper that carries its own depth cap, so integrators do not
50/// need additional guards on the path string itself once the body-size
51/// and JSON-depth limits are in place.
52///
53/// Failing to enforce these limits exposes the dispatcher to memory and
54/// stack-exhaustion DoS on adversarial input. The library cannot apply them
55/// itself because they belong to the HTTP layer, not the JMAP layer.
56///
57/// # Errors
58///
59/// Returns [`JmapError::not_request()`] if the value does not match the
60/// `JmapRequest` schema. Returns
61/// [`JmapError::limit("maxCallsInRequest")`][JmapError::limit] if the method
62/// call count exceeds `max_calls`.
63pub fn parse_request(body: Value, max_calls: usize) -> Result<JmapRequest, JmapError> {
64 let req: JmapRequest = serde_json::from_value(body).map_err(|_| JmapError::not_request())?;
65
66 if req.method_calls.len() > max_calls {
67 return Err(JmapError::limit("maxCallsInRequest"));
68 }
69
70 Ok(req)
71}
72
73/// Validate that every capability URI in `req.using` is in the `known` set.
74///
75/// RFC 8620 §3.3 requires the server to return an `unknownCapability` error
76/// (HTTP 400) if the request declares a capability the server does not support.
77/// This library cannot enforce that check because it has no knowledge of which
78/// capabilities a given deployment supports — that is the caller's
79/// responsibility.
80///
81/// Call this immediately after [`parse_request`] and map any `Err` to an HTTP
82/// 400 response using [`crate::request_error`].
83///
84/// # Errors
85///
86/// Returns [`JmapError::unknown_capability_with_detail`] for the first URI in
87/// `req.using` that is not present in `known`. If all URIs are known,
88/// returns `Ok(())`.
89///
90/// # Example
91///
92/// ```rust
93/// # use jmap_server::check_known_capabilities;
94/// # use jmap_types::JmapRequest;
95/// let req = JmapRequest::new(
96/// vec!["urn:ietf:params:jmap:core".into()],
97/// vec![],
98/// None,
99/// );
100/// let known = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
101/// check_known_capabilities(&req, known).expect("all URIs in known — Ok(()) expected (doctest)");
102/// ```
103pub fn check_known_capabilities<S: AsRef<str>>(
104 req: &JmapRequest,
105 known: &[S],
106) -> Result<(), JmapError> {
107 for uri in &req.using {
108 if !known.iter().any(|k| k.as_ref() == uri.as_str()) {
109 return Err(JmapError::unknown_capability_with_detail(uri));
110 }
111 }
112 Ok(())
113}
114
115/// Resolve all `#key` ResultReference fields in `args` against `prior_responses`.
116///
117/// For every key in `args` that starts with `#`:
118/// 1. Parse the value as a [`ResultReference`].
119/// 2. Find the prior response whose call-id matches `rr.result_of` (index 2 of tuple).
120/// 3. Verify `rr.name` matches the method name of that response (index 0 of tuple).
121/// 4. Apply `rr.path` as an RFC 6901 JSON Pointer (with RFC 8620 §3.7 `*` extension)
122/// to the response args (index 1 of tuple).
123/// 5. Collect `(plain_key, resolved_value)` pairs.
124///
125/// This is two-phase atomic: `args` is not modified at all unless every
126/// `#key` resolves successfully. If any resolution fails, `args` is returned
127/// unchanged and an error is returned.
128///
129/// `prior_responses` entries are `(method_name, response_args, call_id)` — same
130/// layout as [`Invocation`].
131///
132/// # Why two-phase? (bd:JMAP-jfia.12 decision record)
133///
134/// A future contributor will reasonably suggest "this is one extra
135/// pass over the keys — just resolve-and-mutate inline, that's
136/// simpler". That suggestion is **WRONG**. The two-phase structure
137/// is load-bearing:
138///
139/// 1. RFC 8620 §3.7 semantics are atomic: if ANY `ResultReference`
140/// fails to resolve, the entire method call gets
141/// `invalidResultReference`. A partial-mutation would leave a
142/// malformed `args` object that handlers could observe.
143/// 2. `args` is taken by `&mut`, so it remains observable to the
144/// caller after the function returns `Err`. A test that checks
145/// `args` contents on the error path would see a partial state
146/// under inline-mutation.
147/// 3. The test `parse::tests::resolve_args_atomic_on_partial_failure`
148/// directly encodes this contract ("args must be completely
149/// unchanged on error"). Without two-phase, that test would
150/// fail.
151///
152/// The cost is one `Vec<(ref_key, plain_key, resolved_value)>`
153/// allocation per call; that cost is the price of the atomicity
154/// contract.
155pub fn resolve_args(args: &mut Value, prior_responses: &[Invocation]) -> Result<(), JmapError> {
156 let Some(obj) = args.as_object_mut() else {
157 return Ok(()); // non-object args cannot contain #-key references
158 };
159
160 // Collect (#key, value) pairs up front; cannot borrow obj mutably while iterating.
161 // obj.len() is an upper bound (not all keys need the # prefix).
162 let mut ref_pairs: Vec<(String, Value)> = Vec::with_capacity(obj.len());
163 ref_pairs.extend(
164 obj.iter()
165 .filter(|(k, _)| k.starts_with('#'))
166 .map(|(k, v)| (k.clone(), v.clone())),
167 );
168
169 if ref_pairs.is_empty() {
170 return Ok(());
171 }
172
173 // Phase 1: resolve every reference read-only; args are not touched yet.
174 // If any step fails, return the error immediately without modifying args.
175 let mut resolutions: Vec<(String, String, Value)> = Vec::with_capacity(ref_pairs.len());
176
177 for (ref_key, ref_value) in ref_pairs {
178 let plain_key = ref_key[1..].to_owned();
179
180 // Parse the value as a ResultReference.
181 let rr: ResultReference = serde_json::from_value(ref_value).map_err(|e| {
182 JmapError::invalid_arguments(format!("invalid ResultReference for #{plain_key}: {e}"))
183 })?;
184
185 // Find the prior response by call-id.
186 let prior = prior_responses
187 .iter()
188 .find(|inv| inv.call_id == rr.result_of)
189 .ok_or_else(JmapError::invalid_result_reference)?;
190 let prior_value = &prior.arguments;
191
192 // Verify the name field matches the method name (RFC 8620 §3.7).
193 if rr.name != prior.name {
194 return Err(JmapError::invalid_result_reference());
195 }
196
197 // Apply the RFC 6901 JSON Pointer path with RFC 8620 §3.7 `*` wildcard.
198 let resolved = json_pointer_ext(prior_value, &rr.path)
199 .ok_or_else(JmapError::invalid_result_reference)?;
200
201 // Check for key conflict: plain_key must not already exist in args.
202 if obj.contains_key(&plain_key) {
203 return Err(JmapError::invalid_arguments(format!(
204 "argument key conflict: '{}' and '#{}' both present",
205 plain_key, plain_key
206 )));
207 }
208
209 resolutions.push((ref_key, plain_key, resolved));
210 }
211
212 // Phase 2: all resolutions succeeded — apply mutations atomically.
213 for (ref_key, plain_key, resolved) in resolutions {
214 obj.remove(&ref_key);
215 obj.insert(plain_key, resolved);
216 }
217
218 Ok(())
219}
220
221/// Maximum recursion depth for JSON Pointer resolution.
222///
223/// `json_pointer_ext` walks one token of the path per recursive call. A
224/// client-supplied ResultReference path can specify arbitrary depth; without
225/// a cap, an attacker can force unbounded recursion and crash the dispatcher
226/// worker via stack overflow (bd:JMAP-sc1b.95).
227///
228/// 32 levels comfortably exceeds any legitimate JMAP ResultReference shape
229/// (the deepest standard JMAP response — `Email/get` with nested
230/// `bodyStructure` — tops out around 6 levels), while keeping per-request
231/// stack use bounded.
232const MAX_JSON_POINTER_DEPTH: usize = 32;
233
234/// Apply a path to a JSON value, supporting the RFC 8620 §3.7 `*` wildcard extension.
235///
236/// This is RFC 6901 JSON Pointer extended with `*` as an array-map operator.
237/// When the current value is an array and the token is `*`, the remaining tokens
238/// are applied to each element; array results are flattened into the output.
239///
240/// Returns `None` if the path is malformed, the structure doesn't match, or
241/// the path exceeds [`MAX_JSON_POINTER_DEPTH`] tokens. The depth cap exists
242/// to bound stack use on adversarial input (bd:JMAP-sc1b.95).
243fn json_pointer_ext(value: &Value, path: &str) -> Option<Value> {
244 json_pointer_ext_inner(value, path, 0)
245}
246
247fn json_pointer_ext_inner(value: &Value, path: &str, depth: usize) -> Option<Value> {
248 if depth > MAX_JSON_POINTER_DEPTH {
249 // Reject deep pointers rather than walking them — the call site
250 // treats `None` as "resolution failed", which surfaces as a
251 // ResultReference error per RFC 8620 §3.7 and is the same
252 // behaviour the dispatcher already produces for any malformed path.
253 return None;
254 }
255 if path.is_empty() {
256 return Some(value.clone());
257 }
258 // bd:JMAP-jfia.34 — strip_prefix communicates the prefix check at
259 // the type level (Option<&str>) and avoids the byte-index slicing
260 // that would silently break if the prefix character ever changed
261 // to a multi-byte char.
262 let after_slash = path.strip_prefix('/')?;
263
264 // Split off the first token.
265 let (token, remaining) = match after_slash.find('/') {
266 Some(pos) => (&after_slash[..pos], &after_slash[pos..]),
267 None => (after_slash, ""),
268 };
269
270 if token == "*" {
271 // RFC 8620 §3.7 wildcard: map over array, flatten array results.
272 let arr = value.as_array()?;
273 let mut result: Vec<Value> = Vec::new();
274 for item in arr {
275 match json_pointer_ext_inner(item, remaining, depth + 1) {
276 Some(Value::Array(inner)) => result.extend(inner),
277 Some(other) => result.push(other),
278 None => return None, // any failure = whole resolution fails
279 }
280 }
281 Some(Value::Array(result))
282 } else {
283 // RFC 6901: unescape ~1 → /, ~0 → ~ (in that order).
284 // Skip allocation when the token contains no ~ characters (common case).
285 let key: std::borrow::Cow<str> = if token.contains('~') {
286 token.replace("~1", "/").replace("~0", "~").into()
287 } else {
288 token.into()
289 };
290 let next = match value {
291 Value::Object(obj) => obj.get(key.as_ref())?,
292 Value::Array(arr) => {
293 // RFC 6901 §4: leading zeros are not allowed in array index tokens.
294 if key.len() > 1 && key.starts_with('0') {
295 return None;
296 }
297 let idx: usize = key.parse().ok()?;
298 arr.get(idx)?
299 }
300 _ => return None,
301 };
302 json_pointer_ext_inner(next, remaining, depth + 1)
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use serde_json::json;
310
311 // Oracle: RFC 8620 §3 (request format), §7.1 (error type strings).
312
313 #[test]
314 fn parse_request_valid() {
315 let body = json!({
316 "using": ["urn:ietf:params:jmap:core"],
317 "methodCalls": [
318 ["Foo/get", {"accountId": "a1"}, "0"]
319 ]
320 });
321 let req = parse_request(body, 16).expect("valid request must parse");
322 assert_eq!(req.using, vec!["urn:ietf:params:jmap:core"]);
323 assert_eq!(req.method_calls.len(), 1);
324 }
325
326 // Oracle: jmap-test-suite Q4 / error-empty-using — empty using[] must be
327 // accepted by parse_request; the dispatcher returns unknownMethod per call.
328 #[test]
329 fn parse_request_empty_using_is_ok() {
330 let body = json!({
331 "using": [],
332 "methodCalls": []
333 });
334 parse_request(body, 16)
335 .expect("empty using must be accepted — unknownMethod is dispatcher's job");
336 }
337
338 #[test]
339 fn parse_request_too_many_calls() {
340 let call = json!(["Foo/get", {}, "0"]);
341 let calls: Vec<_> = (0..5).map(|_| call.clone()).collect();
342 let body = json!({
343 "using": ["urn:ietf:params:jmap:core"],
344 "methodCalls": calls
345 });
346 let err = parse_request(body, 4).unwrap_err();
347 assert_eq!(
348 err.error_type, "limit",
349 "exceeding maxCallsInRequest must return limit per RFC 8620 §3.6.1"
350 );
351 }
352
353 #[test]
354 fn parse_request_at_max_calls_is_ok() {
355 let call = json!(["Foo/get", {}, "0"]);
356 let calls: Vec<_> = (0..4).map(|_| call.clone()).collect();
357 let body = json!({
358 "using": ["urn:ietf:params:jmap:core"],
359 "methodCalls": calls
360 });
361 parse_request(body, 4).expect("exactly max_calls must be accepted");
362 }
363
364 #[test]
365 fn parse_request_malformed_body() {
366 let body = json!("not an object");
367 let err = parse_request(body, 16).unwrap_err();
368 assert_eq!(
369 err.error_type, "notRequest",
370 "malformed body does not match Request type — must be notRequest per RFC 8620 §3.6.1"
371 );
372 }
373
374 // Oracle: RFC 8620 §3.7 — #ids resolves to prior response's value at path.
375 #[test]
376 fn resolve_args_basic() {
377 let prior = vec![Invocation::new(
378 "Foo/get",
379 json!({"list": [{"id": "x1"}], "state": "s0"}),
380 "c0",
381 )];
382 let mut args = json!({
383 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}
384 });
385 resolve_args(&mut args, &prior).expect("must resolve");
386 assert_eq!(args, json!({"ids": "x1"}));
387 }
388
389 // Oracle: RFC 8620 §3.7 — unknown resultOf → invalidResultReference.
390 #[test]
391 fn resolve_args_unknown_result_of() {
392 let prior: Vec<Invocation> = vec![];
393 let mut args = json!({
394 "#ids": {"resultOf": "missing", "name": "Foo/get", "path": "/ids"}
395 });
396 let original = args.clone();
397 let err = resolve_args(&mut args, &prior).unwrap_err();
398 assert_eq!(err.error_type, "invalidResultReference");
399 // args must be unchanged on error (atomicity).
400 assert_eq!(args, original);
401 }
402
403 // Oracle: RFC 8620 §3.7 — name mismatch → invalidResultReference.
404 #[test]
405 fn resolve_args_name_mismatch() {
406 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a"]}), "c0")];
407 let mut args = json!({
408 "#ids": {"resultOf": "c0", "name": "Bar/get", "path": "/ids"}
409 });
410 let original = args.clone();
411 let err = resolve_args(&mut args, &prior).unwrap_err();
412 assert_eq!(err.error_type, "invalidResultReference");
413 assert_eq!(args, original);
414 }
415
416 // Oracle: RFC 8620 §3.7 — path not found → invalidResultReference.
417 #[test]
418 fn resolve_args_path_not_found() {
419 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a"]}), "c0")];
420 let mut args = json!({
421 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/nonexistent"}
422 });
423 let original = args.clone();
424 let err = resolve_args(&mut args, &prior).unwrap_err();
425 assert_eq!(err.error_type, "invalidResultReference");
426 assert_eq!(args, original);
427 }
428
429 // Oracle: atomicity — if one of two refs fails, args must be completely unchanged.
430 #[test]
431 fn resolve_args_atomic_on_partial_failure() {
432 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a", "b"]}), "c0")];
433 // #ids is valid; #properties references a non-existent call.
434 let mut args = json!({
435 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/ids"},
436 "#properties": {"resultOf": "missing", "name": "Foo/get", "path": "/props"}
437 });
438 let original = args.clone();
439 let err = resolve_args(&mut args, &prior).unwrap_err();
440 assert_eq!(err.error_type, "invalidResultReference");
441 assert_eq!(args, original);
442 }
443
444 // Oracle: non-object args pass through unchanged.
445 #[test]
446 fn resolve_args_non_object_passthrough() {
447 let prior: Vec<Invocation> = vec![];
448 let mut args = json!("not-an-object");
449 resolve_args(&mut args, &prior).expect("non-object must not error");
450 assert_eq!(args, json!("not-an-object"));
451 }
452
453 // Oracle: no #-prefixed keys → args unchanged, Ok returned.
454 #[test]
455 fn resolve_args_no_ref_keys() {
456 let prior: Vec<Invocation> = vec![];
457 let mut args = json!({"ids": ["a", "b"]});
458 resolve_args(&mut args, &prior).expect("no ref keys must not error");
459 assert_eq!(args, json!({"ids": ["a", "b"]}));
460 }
461
462 // Oracle: kith-jmap deviation — unknown capability URIs are silently accepted
463 // at this layer; capability checking is the caller's responsibility.
464 #[test]
465 fn parse_request_unknown_capability_accepted() {
466 let body = json!({
467 "using": ["urn:ietf:params:jmap:core", "urn:example:unknown"],
468 "methodCalls": [
469 ["Foo/get", {}, "0"]
470 ]
471 });
472 let req = parse_request(body, 16).expect("unknown capability must be accepted");
473 assert_eq!(req.using.len(), 2);
474 }
475
476 // Oracle: RFC 8620 §3.3 — `using` is valid with any non-empty array.
477 #[test]
478 fn parse_request_core_only_accepted() {
479 let body = json!({
480 "using": ["urn:ietf:params:jmap:core"],
481 "methodCalls": [
482 ["Foo/get", {}, "0"]
483 ]
484 });
485 parse_request(body, 16).expect("core-only using must be accepted");
486 }
487
488 // Oracle: boundary condition — max_calls=0, one call → limit (RFC 8620 §3.6.1).
489 #[test]
490 fn parse_request_zero_max_calls_rejects_any_call() {
491 let body = json!({
492 "using": ["urn:ietf:params:jmap:core"],
493 "methodCalls": [
494 ["Foo/get", {}, "0"]
495 ]
496 });
497 let err = parse_request(body, 0).unwrap_err();
498 assert_eq!(
499 err.error_type, "limit",
500 "zero max_calls means any call exceeds limit — must be limit per RFC 8620 §3.6.1"
501 );
502 }
503
504 // Oracle: RFC 8620 §3.7 — multiple #-keys in the same args object all resolve
505 // independently against the same prior response.
506 #[test]
507 fn resolve_args_multiple_refs_all_resolve() {
508 let prior = vec![Invocation::new(
509 "Foo/get",
510 json!({"list": [{"id": "x1"}], "state": "s0"}),
511 "c0",
512 )];
513 let mut args = json!({
514 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list"},
515 "#state": {"resultOf": "c0", "name": "Foo/get", "path": "/state"}
516 });
517 resolve_args(&mut args, &prior).expect("both refs must resolve");
518 // No #-keys must remain.
519 let obj = args.as_object().expect("must still be an object");
520 assert!(!obj.contains_key("#ids"), "#ids must be removed");
521 assert!(!obj.contains_key("#state"), "#state must be removed");
522 assert_eq!(args["ids"], json!([{"id": "x1"}]));
523 assert_eq!(args["state"], json!("s0"));
524 }
525
526 // Oracle: RFC 8620 §3.7 — having both `key` and `#key` in the same args
527 // object is an error (key conflict).
528 #[test]
529 fn resolve_args_key_conflict_is_error() {
530 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a"]}), "c0")];
531 let mut args = json!({
532 "ids": "existing",
533 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/ids"}
534 });
535 let original = args.clone();
536 let err = resolve_args(&mut args, &prior).unwrap_err();
537 assert_eq!(err.error_type, "invalidArguments");
538 // args must be completely unchanged on error (atomicity).
539 assert_eq!(args, original);
540 }
541
542 // Oracle: RFC 8620 §3.7 — `#key` value must be a valid ResultReference object;
543 // a non-object value is rejected with invalidArguments.
544 #[test]
545 fn resolve_args_invalid_ref_value_is_error() {
546 let prior: Vec<Invocation> = vec![];
547 let mut args = json!({"#ids": "not-an-object"});
548 let original = args.clone();
549 let err = resolve_args(&mut args, &prior).unwrap_err();
550 assert_eq!(err.error_type, "invalidArguments");
551 assert_eq!(args, original);
552 }
553
554 // Oracle: RFC 8620 §3.7, JSON Pointer RFC 6901 §4 — path pointing to an
555 // array resolves to that array value.
556 #[test]
557 fn resolve_args_array_path_resolves_to_array() {
558 let prior = vec![Invocation::new(
559 "List/query",
560 json!({"ids": ["a", "b", "c"]}),
561 "c0",
562 )];
563 let mut args = json!({
564 "#ids": {"resultOf": "c0", "name": "List/query", "path": "/ids"}
565 });
566 resolve_args(&mut args, &prior).expect("array path must resolve");
567 assert_eq!(args, json!({"ids": ["a", "b", "c"]}));
568 }
569
570 // Oracle: RFC 8620 §3.7, JSON Pointer RFC 6901 §4 — multi-segment path
571 // drills into nested structures.
572 #[test]
573 fn resolve_args_nested_path_resolves() {
574 let prior = vec![Invocation::new(
575 "Foo/get",
576 json!({"list": [{"id": "deep1"}]}),
577 "c0",
578 )];
579 let mut args = json!({
580 "#id": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}
581 });
582 resolve_args(&mut args, &prior).expect("nested path must resolve");
583 assert_eq!(args, json!({"id": "deep1"}));
584 }
585
586 // Oracle: RFC 6901 §7 — an array index that is out of bounds causes the
587 // pointer to fail, which maps to invalidResultReference.
588 #[test]
589 fn resolve_args_path_array_oob_is_error() {
590 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a"]}), "c0")];
591 let mut args = json!({
592 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/ids/5"}
593 });
594 let original = args.clone();
595 let err = resolve_args(&mut args, &prior).unwrap_err();
596 assert_eq!(err.error_type, "invalidResultReference");
597 assert_eq!(args, original);
598 }
599
600 // Oracle: RFC 6901 §4 — array index tokens with a leading zero (other than
601 // the single character "0") MUST be rejected as invalid.
602 #[test]
603 fn resolve_args_path_leading_zero_index_is_error() {
604 let prior = vec![Invocation::new("Foo/get", json!({"ids": ["a", "b"]}), "c0")];
605 let mut args = json!({
606 "#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/ids/01"}
607 });
608 let original = args.clone();
609 let err = resolve_args(&mut args, &prior).unwrap_err();
610 assert_eq!(err.error_type, "invalidResultReference");
611 assert_eq!(args, original, "args must be unchanged on error");
612 }
613
614 // Oracle: RFC 6901 §3 — `~1` is the escape sequence for `/` and `~0` for `~`
615 // in JSON Pointer tokens.
616 #[test]
617 fn resolve_args_path_tilde_escaping() {
618 let prior = vec![Invocation::new(
619 "Foo/get",
620 json!({"a/b": "slash-value"}),
621 "c0",
622 )];
623 let mut args = json!({
624 "#val": {"resultOf": "c0", "name": "Foo/get", "path": "/a~1b"}
625 });
626 resolve_args(&mut args, &prior).expect("tilde-escaped path must resolve");
627 assert_eq!(args, json!({"val": "slash-value"}));
628 }
629
630 // Oracle: RFC 6901 §3 — `~0` is the escape sequence for `~`.
631 // Replacement order must be ~1 first then ~0; otherwise `~01` would
632 // incorrectly become `/` instead of `~1`.
633 #[test]
634 fn resolve_args_path_tilde0_escaping() {
635 let prior = vec![Invocation::new(
636 "Foo/get",
637 json!({"a~b": "tilde-value"}),
638 "c0",
639 )];
640 let mut args = json!({
641 "#val": {"resultOf": "c0", "name": "Foo/get", "path": "/a~0b"}
642 });
643 resolve_args(&mut args, &prior).expect("~0-escaped path must resolve");
644 assert_eq!(args, json!({"val": "tilde-value"}));
645 }
646
647 // Oracle: RFC 6901 §3 — `~01` must decode to the literal string `~1`,
648 // NOT to `/`. ~1 is replaced first (yielding `~1`), then ~0 on what
649 // remains would replace `~0` — but after the first pass `~01` → `~1`
650 // there is no `~0` left; the result is `/`.
651 // Wait — `~01`: replace ~1 first: `~01` has no `~1` at position 0 (it's `~0` then `1`).
652 // So `~01` → replace ~1 → no match → `~01` → replace ~0 → `~` → result: `~1`.
653 // i.e. `~01` decodes to `~1` (literal tilde followed by 1), NOT to `/`.
654 #[test]
655 fn resolve_args_path_tilde01_decodes_to_tilde1() {
656 let prior = vec![Invocation::new(
657 "Foo/get",
658 json!({"~1": "tilde-one-value"}),
659 "c0",
660 )];
661 let mut args = json!({
662 "#val": {"resultOf": "c0", "name": "Foo/get", "path": "/~01"}
663 });
664 resolve_args(&mut args, &prior).expect("~01 must decode to literal key ~1");
665 assert_eq!(args, json!({"val": "tilde-one-value"}));
666 }
667
668 // Oracle: RFC 8620 §3.7 — /list/*/threadId maps threadId from each list element.
669 #[test]
670 fn resolve_args_wildcard_maps_over_array() {
671 let prior = vec![Invocation::new(
672 "Thread/get",
673 json!({
674 "list": [{"threadId": "t1"}, {"threadId": "t2"}]
675 }),
676 "c0",
677 )];
678 let mut args =
679 json!({"#ids": {"resultOf": "c0", "name": "Thread/get", "path": "/list/*/threadId"}});
680 resolve_args(&mut args, &prior).expect("wildcard must resolve");
681 assert_eq!(args, json!({"ids": ["t1", "t2"]}));
682 }
683
684 // Oracle: Fastmail jmap-samples top-ten.py uses path '/ids/*' where `ids` is
685 // a flat string array. RFC 8620 §3.7 wildcard with empty `remaining` path
686 // must return a copy of the source array — each element maps to itself.
687 #[test]
688 fn resolve_args_wildcard_over_flat_string_array() {
689 // Simulates: Email/query → ids:["a","b","c"], then Email/get with
690 // #ids:{resultOf:"c0", name:"Email/query", path:"/ids/*"}.
691 let prior = vec![Invocation::new(
692 "Email/query",
693 json!({ "ids": ["a", "b", "c"] }),
694 "c0",
695 )];
696 let mut args = json!({"#ids": {"resultOf": "c0", "name": "Email/query", "path": "/ids/*"}});
697 resolve_args(&mut args, &prior).expect("flat-array wildcard must resolve");
698 // * over a flat string array with empty remaining path returns the same array.
699 assert_eq!(args, json!({"ids": ["a", "b", "c"]}));
700 }
701
702 // Oracle: RFC 8620 §3.7 — when wildcard result is an array, it is flattened.
703 #[test]
704 fn resolve_args_wildcard_flattens_array_results() {
705 let prior = vec![Invocation::new(
706 "Email/get",
707 json!({
708 "list": [{"emailIds": ["e1", "e2"]}, {"emailIds": ["e3"]}]
709 }),
710 "c0",
711 )];
712 let mut args =
713 json!({"#ids": {"resultOf": "c0", "name": "Email/get", "path": "/list/*/emailIds"}});
714 resolve_args(&mut args, &prior).expect("wildcard flatten must resolve");
715 assert_eq!(args, json!({"ids": ["e1", "e2", "e3"]}));
716 }
717
718 // Oracle: RFC 6901 §4 — basic path navigation.
719 #[test]
720 fn json_pointer_ext_plain_path() {
721 let v = json!({"a": {"b": 42}});
722 assert_eq!(json_pointer_ext(&v, "/a/b"), Some(json!(42)));
723 }
724
725 // Oracle: RFC 6901 §4 — empty path returns whole document.
726 #[test]
727 fn json_pointer_ext_empty_path_returns_root() {
728 let v = json!({"x": 1});
729 assert_eq!(json_pointer_ext(&v, ""), Some(v.clone()));
730 }
731
732 // Oracle: bd:JMAP-sc1b.95 — a path longer than MAX_JSON_POINTER_DEPTH
733 // tokens must be rejected as `None` (resolution failure) rather than
734 // walked recursively. The depth cap is a stack-DoS mitigation; the test
735 // builds a synthetic deep object and a matching deep path to confirm
736 // the cap fires before any real-world JMAP request shape would.
737 //
738 // The test does NOT use the code under test as its own oracle: it
739 // hand-builds a 1000-deep `{ "a": { "a": ... } }` document and a
740 // matching `/a/a/a/...` path, both via tight loops in the test body.
741 // The expected outcome (`None`) is derived from the documented depth
742 // cap, not from running the function.
743 #[test]
744 fn json_pointer_ext_rejects_deep_path() {
745 const DEPTH: usize = 1000;
746 // Build a nested object 1000 levels deep.
747 let mut value = json!(42);
748 for _ in 0..DEPTH {
749 value = json!({ "a": value });
750 }
751 // Build the matching pointer: "/a" repeated DEPTH times.
752 let path: String = "/a".repeat(DEPTH);
753 assert_eq!(
754 json_pointer_ext(&value, &path),
755 None,
756 "pointer with {DEPTH} tokens must be rejected by the depth cap"
757 );
758 }
759
760 // Oracle: paths up to MAX_JSON_POINTER_DEPTH tokens still resolve. This
761 // is the positive control for the depth cap: it confirms the cap fires
762 // strictly at the boundary, not for paths legitimate JMAP integrations
763 // will produce.
764 #[test]
765 fn json_pointer_ext_accepts_path_within_depth_cap() {
766 // Build an object of exactly MAX_JSON_POINTER_DEPTH-1 levels so the
767 // resolution succeeds (depth-1 increments fit within the cap).
768 const LEN: usize = MAX_JSON_POINTER_DEPTH - 1;
769 let mut value = json!("leaf");
770 for _ in 0..LEN {
771 value = json!({ "a": value });
772 }
773 let path: String = "/a".repeat(LEN);
774 assert_eq!(
775 json_pointer_ext(&value, &path),
776 Some(json!("leaf")),
777 "pointer with {LEN} tokens must still resolve under the depth cap"
778 );
779 }
780
781 // -----------------------------------------------------------------------
782 // check_known_capabilities
783 // -----------------------------------------------------------------------
784
785 // Oracle: RFC 8620 §3.3 — unknown capability URI returns unknownCapability.
786 #[test]
787 fn check_known_capabilities_unknown_uri_is_error() {
788 let req = JmapRequest::new(
789 vec![
790 "urn:ietf:params:jmap:core".into(),
791 "urn:example:unknown".into(),
792 ],
793 vec![],
794 None,
795 );
796 let known = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
797 let err = check_known_capabilities(&req, known).unwrap_err();
798 assert_eq!(
799 err.error_type, "unknownCapability",
800 "unrecognised URI must produce unknownCapability per RFC 8620 §3.3"
801 );
802 assert_eq!(
803 err.description.as_deref(),
804 Some("urn:example:unknown"),
805 "unknownCapability error must name the unrecognised URI in description"
806 );
807 }
808
809 // Oracle: RFC 8620 §3.3 — all known URIs accepted.
810 #[test]
811 fn check_known_capabilities_all_known_is_ok() {
812 let req = JmapRequest::new(
813 vec![
814 "urn:ietf:params:jmap:core".into(),
815 "urn:ietf:params:jmap:mail".into(),
816 ],
817 vec![],
818 None,
819 );
820 let known = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
821 check_known_capabilities(&req, known).expect("all URIs are in known — must return Ok");
822 }
823
824 // Oracle: boundary — empty using[] with any known set returns Ok.
825 #[test]
826 fn check_known_capabilities_empty_using_is_ok() {
827 let req = JmapRequest::new(vec![], vec![], None);
828 let known = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
829 check_known_capabilities(&req, known)
830 .expect("empty using[] must return Ok even when known is non-empty");
831 }
832}