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