#![forbid(unsafe_code)]
pub use jmap_types::{
Argument, Id, Invocation, JmapError, JmapRequest, JmapResponse, PushSubscription,
ResultReference, State, UTCDate,
};
mod backend;
mod handlers;
mod helpers;
pub use backend::{
AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesParams,
ChangesResult, GetObject, JmapBackend, JmapObject, QueryChangesParams, QueryChangesResult,
QueryObject, QueryParams, QueryResult, ReservedExtrasKey, SetError, SetErrorType, SetObject,
backend_set_error_value,
};
pub use handlers::{
SERVER_FAIL_INTERNAL_DESC, changes_error_from_backend, handle_changes, handle_get,
handle_get_with_metadata, handle_query, handle_query_changes, server_fail_from_backend,
server_fail_value_from_backend,
};
pub use helpers::{
CREATE_ID_PLACEHOLDER, MergePatchError, MetadataProjection, PatchPathError, apply_jmap_patch,
apply_patch_object, bool_arg, check_patch_paths, enforce_max_objects_in_get,
enforce_max_objects_in_set, extract_account_id, filter_arg, is_client_updatable,
json_merge_patch, json_type_name, limit_or_max, not_found_json, now_utc_string,
now_utc_string_checked, optional_arg, parse_max_changes, parse_wire_id, query_anchor_args,
reject_did_bearing_properties, reject_metadata_filter_arg,
reject_metadata_filter_without_capability, reject_read_only_patch, reject_server_set,
resolve_creation_ref, resolve_query_offset, resolve_query_start, serialize_value,
take_bool_arg, uses_metadata, utc_date_from_epoch_seconds,
};
mod parse;
mod push;
mod response;
pub use parse::{check_known_capabilities, parse_request, parse_request_bytes, resolve_args};
pub use push::{
MAX_PUSH_EXPIRY_SECS, PushSubscriptionBackend, StoredPushSubscription, is_deliverable,
register_push_subscription_handlers, state_change_for,
};
pub use response::{RequestError, error_invocation, error_status, request_error};
use std::{
collections::{BTreeMap, HashMap},
fmt,
future::Future,
pin::Pin,
sync::Arc,
};
use serde_json::Value;
use tokio::task;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HandlerOutput {
pub primary: Value,
pub extra_invocations: Vec<Invocation>,
}
impl HandlerOutput {
pub fn new(primary: Value) -> Self {
Self {
primary,
extra_invocations: Vec::new(),
}
}
pub fn with_extra(mut self, extra_invocations: Vec<Invocation>) -> Self {
self.extra_invocations = extra_invocations;
self
}
}
pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<HandlerOutput, JmapError>> + Send>>;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CallContext<CallerCtx> {
pub method: String,
pub call_id: String,
pub args: Value,
pub caller: CallerCtx,
pub created_ids: BTreeMap<Id, Id>,
pub using: Vec<String>,
}
impl<CallerCtx> CallContext<CallerCtx> {
pub fn new(
method: impl Into<String>,
call_id: impl Into<String>,
args: Value,
caller: CallerCtx,
) -> Self {
Self {
method: method.into(),
call_id: call_id.into(),
args,
caller,
created_ids: BTreeMap::new(),
using: Vec::new(),
}
}
pub fn with_created_ids(mut self, created_ids: BTreeMap<Id, Id>) -> Self {
self.created_ids = created_ids;
self
}
pub fn with_using(mut self, using: Vec<String>) -> Self {
self.using = using;
self
}
}
pub trait JmapHandler<CallerCtx>: Send + Sync {
fn call(&self, cx: CallContext<CallerCtx>) -> HandlerFuture;
}
fn extract_created_ids_into(primary: &Value, sink: &mut BTreeMap<Id, Id>) {
let Some(map) = primary.get("created").and_then(|v| v.as_object()) else {
return;
};
for (client_id, created_obj) in map {
if let Some(id_val) = created_obj.get("id").and_then(|v| v.as_str()) {
sink.insert(Id::from(client_id.as_str()), Id::from(id_val));
}
}
}
pub struct Dispatcher<CallerCtx> {
handlers: HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>,
guard: Option<MethodGuard<CallerCtx>>,
}
type MethodGuard<CallerCtx> = Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync>;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateMethodError {
pub method: String,
}
impl std::fmt::Display for DuplicateMethodError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "handler already registered for method {:?}", self.method)
}
}
impl std::error::Error for DuplicateMethodError {}
impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx> {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
guard: None,
}
}
pub fn set_guard(
&mut self,
guard: impl Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync + 'static,
) {
self.guard = Some(Box::new(guard));
}
pub fn register(
&mut self,
method: impl Into<String>,
handler: Arc<dyn JmapHandler<CallerCtx>>,
) {
self.handlers.insert(method.into(), handler);
}
pub fn try_register(
&mut self,
method: impl Into<String>,
handler: Arc<dyn JmapHandler<CallerCtx>>,
) -> Result<(), DuplicateMethodError> {
let method = method.into();
if self.handlers.contains_key(&method) {
return Err(DuplicateMethodError { method });
}
self.handlers.insert(method, handler);
Ok(())
}
pub async fn dispatch(
&self,
request: JmapRequest,
caller: CallerCtx,
session_state: State,
) -> JmapResponse {
let mut method_responses: Vec<Invocation> = Vec::with_capacity(request.method_calls.len());
let client_sent_created_ids = request.created_ids.is_some();
let mut created_ids: BTreeMap<Id, Id> = request.created_ids.unwrap_or_default();
for Invocation {
name: method,
arguments: mut args,
call_id,
} in request.method_calls
{
if let Err(e) = resolve_args(&mut args, &method_responses)
.and_then(|()| parse::check_filter_depth(&args))
{
method_responses.push(error_invocation(&call_id, e));
continue;
}
if let Some(Err(e)) = self.guard.as_ref().map(|guard| guard(&method, &caller)) {
method_responses.push(error_invocation(&call_id, e));
continue;
}
let Some(handler) = self.handlers.get(&method).map(Arc::clone) else {
method_responses.push(error_invocation(&call_id, JmapError::unknown_method()));
continue;
};
let caller_clone = caller.clone();
let method_clone = method.clone();
let call_id_clone = call_id.clone();
let created_ids_snapshot = created_ids.clone();
let using = request.using.clone();
let result: Result<Result<HandlerOutput, JmapError>, tokio::task::JoinError> =
task::spawn(async move {
handler
.call(
CallContext::new(method_clone, call_id_clone, args, caller_clone)
.with_created_ids(created_ids_snapshot)
.with_using(using),
)
.await
})
.await;
match result {
Ok(Ok(HandlerOutput {
primary: primary_value,
extra_invocations,
})) => {
extract_created_ids_into(&primary_value, &mut created_ids);
method_responses.push(Invocation::new(method, primary_value, call_id));
method_responses.extend(extra_invocations);
}
Ok(Err(e)) => {
method_responses.push(error_invocation(&call_id, e));
}
Err(join_err) => {
let desc = if join_err.is_cancelled() {
"task cancelled"
} else {
"internal error"
};
if join_err.is_panic() {
tracing::error!(
method = method.as_str(),
call_id = call_id.as_str(),
"method handler panicked"
);
}
method_responses.push(error_invocation(&call_id, JmapError::server_fail(desc)));
}
}
}
let created_ids = client_sent_created_ids.then_some(created_ids);
JmapResponse::new(method_responses, session_state, created_ids)
}
}
impl<CallerCtx: Clone + Send + 'static> Default for Dispatcher<CallerCtx> {
fn default() -> Self {
Self::new()
}
}
impl<CallerCtx> fmt::Debug for Dispatcher<CallerCtx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Dispatcher")
.field("methods", &self.handlers.keys())
.field("guard", &self.guard.is_some())
.finish()
}
}
pub type BackendCallFn<B, C> =
dyn Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static;
#[non_exhaustive]
pub struct ClosureHandler<B: Send + Sync + 'static, C: Clone + Send + 'static> {
pub(crate) backend: Arc<B>,
pub(crate) call_fn: Box<BackendCallFn<B, C>>,
}
impl<B: Send + Sync + 'static, C: Clone + Send + 'static> ClosureHandler<B, C> {
pub fn new<F>(backend: Arc<B>, call_fn: F) -> Self
where
F: Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static,
{
Self {
backend,
call_fn: Box::new(call_fn),
}
}
}
impl<B: Send + Sync + 'static, C: Clone + Send + 'static> JmapHandler<C> for ClosureHandler<B, C> {
fn call(&self, cx: CallContext<C>) -> HandlerFuture {
(self.call_fn)(Arc::clone(&self.backend), cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
use std::sync::{Arc, Mutex};
#[allow(dead_code)]
fn assert_dispatcher_send_sync() {
fn check<T: Send + Sync>() {}
check::<Dispatcher<String>>();
check::<Dispatcher<()>>();
}
struct EchoHandler(Value);
impl<C: Clone + Send + 'static> JmapHandler<C> for EchoHandler {
fn call(&self, _cx: CallContext<C>) -> HandlerFuture {
let v = self.0.clone();
Box::pin(async move { Ok(HandlerOutput::new(v)) })
}
}
struct ErrorHandler(JmapError);
impl JmapHandler<String> for ErrorHandler {
fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
let e = self.0.clone();
Box::pin(async move { Err(e) })
}
}
struct CaptureArgsHandler(Arc<Mutex<Option<Value>>>);
impl JmapHandler<String> for CaptureArgsHandler {
fn call(&self, cx: CallContext<String>) -> HandlerFuture {
let args = cx.args;
let slot = self.0.clone();
Box::pin(async move {
*slot.lock().expect("test: mutex poisoned") = Some(args);
Ok(HandlerOutput::new(json!({})))
})
}
}
struct CaptureCallerHandler(Arc<Mutex<Option<String>>>);
impl JmapHandler<String> for CaptureCallerHandler {
fn call(&self, cx: CallContext<String>) -> HandlerFuture {
let caller = cx.caller;
let slot = self.0.clone();
Box::pin(async move {
*slot.lock().expect("test: mutex poisoned") = Some(caller);
Ok(HandlerOutput::new(json!({})))
})
}
}
struct PanicHandler;
impl JmapHandler<String> for PanicHandler {
fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
Box::pin(async move { panic!("deliberate test panic") })
}
}
fn single_call(method: &str, args: Value, call_id: &str) -> JmapRequest {
JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![Invocation::new(method, args, call_id)],
None,
)
}
#[tokio::test]
async fn unknown_method_returns_error_invocation() {
let d: Dispatcher<String> = Dispatcher::new();
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
let Invocation {
arguments: args,
call_id,
..
} = &resp.method_responses[0];
assert_eq!(call_id, "c0");
assert_eq!(args["type"], "unknownMethod");
}
#[tokio::test]
async fn known_method_success() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
let req = single_call("Foo/get", json!({}), "c1");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
let Invocation {
name: method,
arguments: args,
call_id,
} = &resp.method_responses[0];
assert_eq!(method, "Foo/get");
assert_eq!(call_id, "c1");
assert_eq!(args["list"], json!([]));
}
fn nested_filter(levels: usize) -> Value {
(0..levels).fold(
json!({ "text": "x" }),
|inner, _| json!({ "operator": "AND", "conditions": [inner] }),
)
}
#[tokio::test]
async fn filter_nested_past_cap_is_unsupported_filter() {
let slot = Arc::new(Mutex::new(None));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
let req = single_call("Foo/query", json!({ "filter": nested_filter(33) }), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let Invocation {
name, arguments, ..
} = &resp.method_responses[0];
assert_eq!(name, "error");
assert_eq!(arguments["type"], "unsupportedFilter");
assert!(
slot.lock().expect("test: mutex poisoned").is_none(),
"handler must not run on a refused filter"
);
}
#[tokio::test]
async fn filter_nested_at_cap_reaches_handler() {
let slot = Arc::new(Mutex::new(None));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
let args = json!({ "filter": nested_filter(32) });
let req = single_call("Foo/query", args.clone(), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses[0].name, "Foo/query");
assert_eq!(*slot.lock().expect("test: mutex poisoned"), Some(args));
}
#[tokio::test]
async fn handler_returns_error() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/get", Arc::new(ErrorHandler(JmapError::forbidden())));
let req = single_call("Foo/get", json!({}), "c2");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert_eq!(args["type"], "forbidden");
}
#[tokio::test]
async fn set_over_max_objects_is_method_error_request_too_large() {
struct CappedSetHandler;
impl JmapHandler<String> for CappedSetHandler {
fn call(&self, cx: CallContext<String>) -> HandlerFuture {
let args = cx.args;
Box::pin(async move {
let map = args.as_object().cloned().unwrap_or_default();
enforce_max_objects_in_set(&map, 1)?;
Ok(HandlerOutput::new(json!({"created": {}})))
})
}
}
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/set", Arc::new(CappedSetHandler));
d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new(
"Foo/set",
json!({"accountId": "a1", "destroy": ["x1", "x2"]}),
"c0",
),
Invocation::new("Foo/get", json!({"accountId": "a1"}), "c1"),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 2);
let Invocation {
name,
arguments: args,
call_id,
} = &resp.method_responses[0];
assert_eq!(name, "error");
assert_eq!(call_id, "c0");
assert_eq!(args["type"], "requestTooLarge");
let Invocation {
name,
arguments: args,
call_id,
} = &resp.method_responses[1];
assert_eq!(name, "Foo/get");
assert_eq!(call_id, "c1");
assert_eq!(args["list"], json!([]));
}
#[tokio::test]
async fn try_register_succeeds_then_errors_on_duplicate() {
let mut d: Dispatcher<String> = Dispatcher::new();
let first = Arc::new(EchoHandler(json!({"v": "first"})));
let second = Arc::new(EchoHandler(json!({"v": "second"})));
d.try_register("Foo/get", first)
.expect("first registration must succeed");
let err = d
.try_register("Foo/get", second)
.expect_err("second registration must error");
assert_eq!(err.method, "Foo/get");
assert_eq!(
err.to_string(),
"handler already registered for method \"Foo/get\""
);
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert_eq!(
args["v"], "first",
"try_register error path must not replace the existing handler"
);
}
#[tokio::test]
async fn register_silently_overwrites_on_duplicate() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "first"}))));
d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "second"}))));
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert_eq!(args["v"], "second", "register must replace on duplicate");
}
#[tokio::test]
async fn session_state_echoed() {
let d: Dispatcher<String> = Dispatcher::new();
let req = JmapRequest::new(vec!["urn:ietf:params:jmap:core".into()], vec![], None);
let resp = d.dispatch(req, "alice".into(), "my-state-123".into()).await;
assert_eq!(resp.session_state.as_ref(), "my-state-123");
}
#[tokio::test]
async fn mixed_batch_all_responses_in_order() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("M/a", Arc::new(EchoHandler(json!({"ok": true}))));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("M/a", json!({}), "c0"),
Invocation::new("M/b", json!({}), "c1"),
Invocation::new("M/a", json!({}), "c2"),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(
resp.method_responses.len(),
3,
"all three calls must produce a response"
);
assert_eq!(resp.method_responses[0].call_id, "c0");
assert!(
resp.method_responses[0].arguments.get("type").is_none(),
"c0 must not be an error"
);
assert_eq!(resp.method_responses[1].call_id, "c1");
assert_eq!(resp.method_responses[1].arguments["type"], "unknownMethod");
assert_eq!(resp.method_responses[2].call_id, "c2");
assert!(
resp.method_responses[2].arguments.get("type").is_none(),
"c2 must not be an error"
);
}
#[tokio::test]
async fn error_does_not_abort_subsequent_calls() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("M/ok", Arc::new(EchoHandler(json!({"ok": true}))));
d.register("M/err", Arc::new(ErrorHandler(JmapError::forbidden())));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("M/err", json!({}), "c0"),
Invocation::new("M/ok", json!({}), "c1"),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 2);
assert_eq!(resp.method_responses[0].arguments["type"], "forbidden");
assert!(
resp.method_responses[1].arguments.get("type").is_none(),
"second call must succeed"
);
}
#[tokio::test]
async fn panicking_handler_returns_server_fail() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Panic/now", Arc::new(PanicHandler));
let req = single_call("Panic/now", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert_eq!(
args["type"], "serverFail",
"panicking handler must produce serverFail"
);
}
#[tokio::test]
async fn panic_message_not_in_response() {
fn value_contains_recursive(v: &Value, needle: &str) -> bool {
match v {
Value::String(s) => s.contains(needle),
Value::Array(arr) => arr.iter().any(|x| value_contains_recursive(x, needle)),
Value::Object(o) => o.values().any(|x| value_contains_recursive(x, needle)),
Value::Null | Value::Bool(_) | Value::Number(_) => false,
}
}
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Panic/now", Arc::new(PanicHandler));
let req = single_call("Panic/now", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert!(
!value_contains_recursive(args, "deliberate test panic"),
"panic message must not leak into ANY field of the response: {args}"
);
}
#[tokio::test]
async fn result_reference_resolved_before_dispatch() {
let captured = Arc::new(Mutex::new(None::<Value>));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Foo/get",
Arc::new(EchoHandler(json!({"list": [{"id": "item-1"}]}))),
);
d.register(
"Bar/query",
Arc::new(CaptureArgsHandler(Arc::clone(&captured))),
);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("Foo/get", json!({}), "c0"),
Invocation::new(
"Bar/query",
json!({"#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}}),
"c1",
),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 2);
assert!(
resp.method_responses[1].arguments.get("type").is_none(),
"Bar/query must succeed after ResultReference resolution"
);
let got = captured
.lock()
.unwrap()
.clone()
.expect("CaptureArgsHandler was not called");
assert_eq!(
got["ids"],
json!("item-1"),
"resolved value must be the string item-1"
);
assert!(
got.get("#ids").is_none(),
"#ids key must have been replaced"
);
}
#[tokio::test]
async fn result_reference_failure_stops_that_call() {
let d: Dispatcher<String> = Dispatcher::new();
let req = single_call(
"Foo/get",
json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
"c0",
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
let Invocation {
arguments: args, ..
} = &resp.method_responses[0];
assert!(
args.get("type").is_some(),
"failed ResultReference must produce an error invocation"
);
}
#[tokio::test]
async fn created_ids_accumulated_from_set_response() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Foo/set",
Arc::new(EchoHandler(
json!({"created": {"client-1": {"id": "server-abc"}}}),
)),
);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![Invocation::new("Foo/set", json!({}), "c0")],
Some(std::collections::BTreeMap::new()),
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let ids = resp
.created_ids
.as_ref()
.expect("created_ids must be Some when client sent createdIds");
assert_eq!(
ids.get(&Id::from("client-1")),
Some(&Id::from("server-abc")),
"client-1 must map to server-abc"
);
}
struct CaptureCreatedIdsHandler(Arc<Mutex<Option<BTreeMap<Id, Id>>>>);
impl JmapHandler<String> for CaptureCreatedIdsHandler {
fn call(&self, cx: CallContext<String>) -> HandlerFuture {
*self.0.lock().expect("test: mutex poisoned") = Some(cx.created_ids);
Box::pin(async move { Ok(HandlerOutput::new(json!({}))) })
}
}
#[tokio::test]
async fn created_ids_reach_later_call_without_client_created_ids() {
let slot = Arc::new(Mutex::new(None));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Graph/set",
Arc::new(EchoHandler(json!({"created": {"g": {"id": "G1"}}}))),
);
d.register(
"GraphNode/set",
Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("Graph/set", json!({}), "c0"),
Invocation::new("GraphNode/set", json!({}), "c1"),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let seen = slot
.lock()
.expect("test: mutex poisoned")
.take()
.expect("GraphNode/set handler must run");
assert_eq!(
seen,
BTreeMap::from([(Id::from("g"), Id::from("G1"))]),
"later call must see the earlier creation"
);
assert!(
resp.created_ids.is_none(),
"response omits createdIds when the client did not send it"
);
}
#[tokio::test]
async fn created_ids_initial_map_reaches_first_call() {
let slot = Arc::new(Mutex::new(None));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Email/set",
Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
);
let initial = BTreeMap::from([(Id::from("m"), Id::from("M1"))]);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![Invocation::new("Email/set", json!({}), "c0")],
Some(initial.clone()),
);
d.dispatch(req, "alice".into(), "s0".into()).await;
let seen = slot.lock().expect("test: mutex poisoned").take();
assert_eq!(seen, Some(initial));
}
#[tokio::test]
async fn created_ids_absent_when_no_set() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert!(
resp.created_ids.is_none(),
"created_ids must be None when no /set call created objects"
);
}
#[tokio::test]
async fn created_ids_accumulated_across_multiple_set_calls() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"A/set",
Arc::new(EchoHandler(json!({"created": {"cA": {"id": "sA"}}}))),
);
d.register(
"B/set",
Arc::new(EchoHandler(json!({"created": {"cB": {"id": "sB"}}}))),
);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("A/set", json!({}), "c0"),
Invocation::new("B/set", json!({}), "c1"),
],
Some(std::collections::BTreeMap::new()),
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let ids = resp
.created_ids
.as_ref()
.expect("created_ids must be Some when client sent createdIds");
assert_eq!(
ids.get(&Id::from("cA")),
Some(&Id::from("sA")),
"cA must be present"
);
assert_eq!(
ids.get(&Id::from("cB")),
Some(&Id::from("sB")),
"cB must be present"
);
}
#[tokio::test]
async fn created_ids_merges_with_pre_populated_map() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Foo/set",
Arc::new(EchoHandler(
json!({"created": {"client-new": {"id": "server-new"}}}),
)),
);
let mut initial = std::collections::BTreeMap::new();
initial.insert(Id::from("client-old"), Id::from("server-old"));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![Invocation::new("Foo/set", json!({}), "c0")],
Some(initial),
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let ids = resp
.created_ids
.as_ref()
.expect("created_ids must be Some when client sent createdIds");
assert_eq!(
ids.get(&Id::from("client-old")),
Some(&Id::from("server-old")),
"pre-populated entry must be preserved"
);
assert_eq!(
ids.get(&Id::from("client-new")),
Some(&Id::from("server-new")),
"new /set entry must be merged in"
);
}
#[tokio::test]
async fn created_ids_pre_populated_collision_last_write_wins() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Foo/set",
Arc::new(EchoHandler(
json!({"created": {"client-X": {"id": "server-B"}}}),
)),
);
let mut initial = std::collections::BTreeMap::new();
initial.insert(Id::from("client-X"), Id::from("server-A"));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![Invocation::new("Foo/set", json!({}), "c0")],
Some(initial),
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let ids = resp
.created_ids
.as_ref()
.expect("created_ids must be Some when client sent createdIds");
assert_eq!(
ids.get(&Id::from("client-X")),
Some(&Id::from("server-B")),
"last-write-wins: /set response overrides pre-populated entry"
);
assert_eq!(
ids.len(),
1,
"no extra entries should appear from the collision"
);
}
#[tokio::test]
async fn created_ids_intra_batch_collision_last_write_wins() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"A/set",
Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sA"}}}))),
);
d.register(
"B/set",
Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sB"}}}))),
);
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("A/set", json!({}), "c0"),
Invocation::new("B/set", json!({}), "c1"),
],
Some(std::collections::BTreeMap::new()),
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
let ids = resp
.created_ids
.as_ref()
.expect("created_ids must be Some when client sent createdIds");
assert_eq!(
ids.get(&Id::from("cX")),
Some(&Id::from("sB")),
"last-write-wins: second /set call's mapping for cX preserved"
);
assert_eq!(
ids.len(),
1,
"no extra entries should appear from the collision"
);
}
#[tokio::test]
async fn guard_rejection_replaces_only_that_call() {
let captured = Arc::new(Mutex::new(None::<String>));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
d.register(
"Bar/set",
Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
);
d.set_guard(|method, caller: &String| {
if method == "Bar/set" && caller == "mallory" {
Err(JmapError::forbidden())
} else {
Ok(())
}
});
let batch = || {
JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new("Foo/get", json!({}), "c0"),
Invocation::new("Bar/set", json!({}), "c1"),
Invocation::new("Foo/get", json!({}), "c2"),
],
None,
)
};
let resp = d.dispatch(batch(), "mallory".into(), "s0".into()).await;
let got: Vec<(String, Value, String)> = resp
.method_responses
.into_iter()
.map(|i| (i.name, i.arguments, i.call_id))
.collect();
assert_eq!(
got,
vec![
("Foo/get".into(), json!({"list": []}), "c0".into()),
("error".into(), json!({"type": "forbidden"}), "c1".into()),
("Foo/get".into(), json!({"list": []}), "c2".into()),
]
);
assert!(
captured.lock().unwrap().is_none(),
"rejected call's handler must not run"
);
let resp = d.dispatch(batch(), "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses[1].name, "Bar/set");
assert_eq!(captured.lock().unwrap().as_deref(), Some("alice"));
}
#[tokio::test]
async fn guard_runs_after_reference_resolution_before_lookup() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.set_guard(|_, _: &String| Err(JmapError::forbidden()));
let req = JmapRequest::new(
vec!["urn:ietf:params:jmap:core".into()],
vec![
Invocation::new(
"Foo/get",
json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
"c0",
),
Invocation::new("Unregistered/get", json!({}), "c1"),
],
None,
);
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 2);
assert_eq!(
resp.method_responses[0].arguments["type"],
"invalidResultReference"
);
assert_eq!(resp.method_responses[1].arguments["type"], "forbidden");
}
#[tokio::test]
async fn caller_ctx_passed_to_handler() {
let captured = Arc::new(Mutex::new(None::<String>));
let mut d: Dispatcher<String> = Dispatcher::new();
d.register(
"Foo/get",
Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
);
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert!(
resp.method_responses[0].arguments.get("type").is_none(),
"must succeed"
);
let got = captured
.lock()
.unwrap()
.clone()
.expect("handler was not called");
assert_eq!(got, "alice", "caller must be passed through unchanged");
}
#[tokio::test]
async fn unit_caller_ctx_works() {
let mut d: Dispatcher<()> = Dispatcher::new();
d.register("Foo/get", Arc::new(EchoHandler(json!({"ok": true}))));
let req = single_call("Foo/get", json!({}), "c0");
let resp = d.dispatch(req, (), "s0".into()).await;
assert_eq!(resp.method_responses.len(), 1);
assert!(
resp.method_responses[0].arguments.get("type").is_none(),
"must succeed with () caller"
);
}
struct ExtraInvocationHandler;
impl JmapHandler<String> for ExtraInvocationHandler {
fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
Box::pin(async move {
let primary = json!({"type": "primary"});
let extra: Vec<Invocation> = vec![Invocation::new(
"Extra/call",
json!({"type": "extra"}),
"x0",
)];
Ok(HandlerOutput::new(primary).with_extra(extra))
})
}
}
#[tokio::test]
async fn extra_invocations_appended_after_primary() {
let mut d: Dispatcher<String> = Dispatcher::new();
d.register("Sub/set", Arc::new(ExtraInvocationHandler));
let req = single_call("Sub/set", json!({}), "c0");
let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
assert_eq!(
resp.method_responses.len(),
2,
"primary + 1 extra = 2 total invocations"
);
assert_eq!(resp.method_responses[0].name, "Sub/set");
assert_eq!(resp.method_responses[0].call_id, "c0");
assert_eq!(resp.method_responses[0].arguments["type"], "primary");
assert_eq!(resp.method_responses[1].name, "Extra/call");
assert_eq!(resp.method_responses[1].call_id, "x0");
assert_eq!(resp.method_responses[1].arguments["type"], "extra");
}
#[tokio::test]
async fn closure_handler_forwards_caller() {
#[derive(Clone)]
struct Ctx(String);
struct DummyBackend;
let received: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
let received_clone = Arc::clone(&received);
let handler: Arc<ClosureHandler<DummyBackend, Ctx>> = Arc::new(ClosureHandler::new(
Arc::new(DummyBackend),
move |_b: Arc<DummyBackend>, cx: CallContext<Ctx>| {
let cap = Arc::clone(&received_clone);
Box::pin(async move {
*cap.lock().unwrap() = Some(cx.caller.0.clone());
Ok(HandlerOutput::new(serde_json::json!({})))
})
},
));
let ctx = Ctx("alice".to_owned());
handler
.call(CallContext::new(
"Test/get",
"c1",
serde_json::json!({}),
ctx,
))
.await
.expect("handler must succeed");
assert_eq!(
received.lock().unwrap().as_deref(),
Some("alice"),
"CallerCtx must be forwarded to the closure"
);
}
#[tokio::test]
async fn closure_handler_receives_method_call_id_and_args() {
struct DummyBackend;
let seen: Arc<Mutex<Option<(String, String, Value)>>> = Arc::new(Mutex::new(None));
let seen_clone = Arc::clone(&seen);
let handler = ClosureHandler::new(
Arc::new(DummyBackend),
move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
*seen_clone.lock().unwrap() = Some((cx.method, cx.call_id, cx.args));
Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
},
);
let mut d: Dispatcher<()> = Dispatcher::new();
d.register("Foo/get", Arc::new(handler));
d.dispatch(
single_call("Foo/get", json!({"accountId": "a1"}), "c7"),
(),
"s0".into(),
)
.await;
assert_eq!(
seen.lock().unwrap().take(),
Some((
"Foo/get".to_owned(),
"c7".to_owned(),
json!({"accountId": "a1"})
))
);
}
#[tokio::test]
async fn dispatch_passes_request_using_to_handler() {
struct DummyBackend;
let seen: Arc<Mutex<Option<Vec<String>>>> = Arc::new(Mutex::new(None));
let seen_clone = Arc::clone(&seen);
let handler = ClosureHandler::new(
Arc::new(DummyBackend),
move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
*seen_clone.lock().unwrap() = Some(cx.using);
Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
},
);
let mut d: Dispatcher<()> = Dispatcher::new();
d.register("Foo/changes", Arc::new(handler));
let req = JmapRequest::new(
vec![
"urn:ietf:params:jmap:core".into(),
"urn:ietf:params:jmap:metadata".into(),
],
vec![Invocation::new(
"Foo/changes",
json!({"accountId": "a1", "sinceState": "s1"}),
"c0",
)],
None,
);
d.dispatch(req, (), "s0".into()).await;
assert_eq!(
seen.lock().unwrap().take(),
Some(vec![
"urn:ietf:params:jmap:core".to_owned(),
"urn:ietf:params:jmap:metadata".to_owned(),
])
);
}
#[test]
fn closure_handler_is_jmap_handler() {
fn assert_handler<C: Clone + Send + 'static, H: JmapHandler<C>>(_: &H) {}
struct DummyBackend;
#[derive(Clone)]
struct Ctx;
let h = ClosureHandler::new(Arc::new(DummyBackend), |_b, _cx| {
Box::pin(async { Ok(HandlerOutput::new(serde_json::json!({}))) })
});
assert_handler::<Ctx, _>(&h);
}
}