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