Skip to main content

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