jmap-server
Backend-agnostic JMAP server framework for Rust. Implements the RFC 8620 wire
protocol: request parsing, ResultReference resolution, and the Dispatcher
machinery. No opinion on authentication, method sets, capability URIs, or storage.
What it is
The foundation server crate for the jmap-* family — Dispatcher, the
JmapHandler trait, parse_request, ResultReference resolution, the
JmapBackend supertrait, generic /get / /changes / /query /
/queryChanges handlers, the CallerCtx identity seam, and panic isolation
via tokio::task::spawn. No HTTP / SSE / WebSocket transport — that is the
consumer's responsibility, per the workspace's library-kit posture.
What it's for
Every jmap-*-server extension in the workspace (mail, chat, contacts,
calendars, tasks, filenode, sharing, metadata) builds on this crate by
extending the JmapBackend supertrait with its own backend methods and
registering handlers via Dispatcher::register. Downstream consumers like
kith and stoa, and the in-workspace jmap-testjig, wire this crate into
their own HTTP transport, auth integration, and persistence story.
How to use
use Arc;
use ;
// 1. Implement JmapHandler for each method.
;
// 2. Register handlers and dispatch requests.
let mut dispatcher: = new;
dispatcher.register;
// In your handler:
// let request = jmap_server::parse_request_bytes(&body_bytes, 16)?;
// let response = dispatcher.dispatch(request, caller_identity, session_state).await;
CallerCtx
CallerCtx is whatever your authentication layer produces — an identity struct,
a session token, (), etc. The dispatcher clones it for each method call and
passes it through to the handler unchanged. It must be Clone + Send + 'static;
use Arc<T> to share non-static data (e.g. a database connection pool).
Request parsing
use ;
// Parse and validate the raw HTTP request body (after your body-size cap).
let req = parse_request_bytes
.map_err?; // returns RequestError on failure
parse_request_bytes returns notJSON if the body does not parse as JSON,
then validates as parse_request does. Use parse_request directly only
when you already hold a serde_json::Value. parse_request validates:
- The body is a valid JMAP Request object.
usingis non-empty.- The number of method calls does not exceed
max_calls.
Capability URI checking is NOT performed here — that is the caller's responsibility.
Error responses
use ;
// Request-level errors (HTTP 400/403/500 with RFC 7807 body):
let resp = request_error; // → HTTP 400
let resp = request_error; // → HTTP 400
// Method-level errors (HTTP 200, inside methodResponses):
// Return Err(JmapError::...) from your JmapHandler::call implementation.
Re-exports
The crate root re-exports three groups of items so consumers do not have to
take a direct dependency on jmap-types:
Wire types (from jmap_types)
pub use ;
DataTypeMetadataInfo is re-exported from jmap-metadata-types too,
since JmapAccounts::metadata_info returns it: a backend or a wrapper that
answers metadata_info names it as jmap_server::DataTypeMetadataInfo.
These are the RFC 8620 wire primitives: Id, UTCDate, and State for
typed identifier/timestamp/state-token fields; JmapRequest / JmapResponse
for the top-level request/response envelopes; Invocation for individual
method calls (a (method, args, callId) tuple); ResultReference and
Argument<T> for the back-reference machinery in RFC 8620 §3.7;
JmapError for both request-level and method-level errors;
PushSubscription for the RFC 8620 §7.2 push subscription object.
Backend infrastructure (from the backend module)
pub use ;
JmapBackend is the union of two traits, with a blanket impl:
JmapAccounts (the Error and CallerCtx types, account_exists,
principal_id, accept_language, the max_objects_* limits,
metadata_info, i18n_info) and JmapReads (get_objects, get_state,
get_changes, query_objects, query_changes). A backend implements
both; it never implements JmapBackend itself. A wrapper that keeps its
own JmapAccounts (an account_exists against a directory, say) and
serves the reads from the backend it wraps implements DelegateJmapReads
(type Target, fn jmap_reads(&self) -> &Self::Target) instead of
JmapReads. The target has the wrapper's Error and CallerCtx.
To keep the wrapped backend's other JmapAccounts answers too (its
metadata_info, i18n_info or limits, whichever it overrides), the
wrapper implements DelegateJmapAccounts instead of JmapAccounts:
type Target, fn jmap_accounts(&self) -> &Self::Target, and only the
methods it changes. Every method of DelegateJmapAccounts defaults to the
target's, so none falls back to a JmapAccounts default by mistake; the
wrapper's Error and CallerCtx are the target's. principal_id and
accept_language have no self, so their defaults call the target
type's functions (the caller context is the same type). A type implements
either DelegateJmapAccounts or JmapAccounts, not both. With both
JmapAccounts and DelegateJmapAccounts in scope, call a method on the
concrete wrapper as JmapAccounts::account_exists(&wrapper, ..), since
method-call syntax finds it in both traits.
Generic backend traits (JmapBackend, GetObject, QueryObject, SetObject),
result and error envelopes (ChangesResult, QueryResult, QueryChangesResult,
SetError / SetErrorType re-exported from jmap-types, BackendSetError,
BackendChangesError), and the
AddedItem row used in Foo/queryChanges responses. Extension server crates
(jmap-mail-server, jmap-chat-server, etc.) extend JmapBackend to add
their own write/extension methods.
Helpers (from the helpers module)
pub use ;
Small utilities used by every method handler: extract_account_id pulls the
accountId field from a method-arguments Value (returning accountNotFound
on absence), now_utc_string produces an RFC 3339 timestamp suitable for
RFC 8620 UTCDate fields, serialize_value serializes any Serialize value into a
Value (mapping serialization failure to serverFail), and not_found_json
builds the notFound: [...] array used by Foo/get responses for missing
ids.
Other entry points
pub use ;
pub use ;
pub use ;
pub use ;
// Plus the closure-based JmapHandler adapter defined in this crate's
// crate root: ClosureHandler.
Request parsing and capability validation; HTTP response shaping for
request-level errors; generic implementations of the four read-side JMAP
methods (Foo/get, Foo/changes, Foo/query, Foo/queryChanges) that
extension server crates plug their backend into; and the closure-based
JmapHandler adapter (ClosureHandler) used by register_*_handlers
macros across the extension server crates. ClosureHandler forwards the
dispatcher's CallerCtx value through to the wrapped closure as a fourth
argument, so backends that need per-request auth context can read it
without dropping down to a manual JmapHandler<C> impl.
register_push_subscription_handlers registers PushSubscription/get
(RFC 8620 §7.2.1) and PushSubscription/set (RFC 8620 §7.2.2) over a
PushSubscriptionBackend. Push subscriptions belong to the caller's
credentials, not to an account, so the backend's methods MUST see and change
only the caller's subscriptions. /get never returns url or keys and
answers forbidden when either is requested. /set takes no accountId or
ifInState and returns no oldState or newState. It requires an
https:// url, rejects changes to id, deviceClientId, url and keys,
compares a new verificationCode in constant time, and limits expires to
MAX_PUSH_EXPIRY_SECS (7 days) from now. The backend generates the
verification code, enforces the per-user cap, and may reject a create by
policy with its own SetError, which reaches the response verbatim.
The history module serves draft-ietf-jmap-object-history-03 (with the
-04 editor's copy changes, docs/design/object-history.md §2a) for data
types that opt in. ObjectHistoryBackend: JmapBackend has five required
hooks: object_history_capability, get_object_history,
query_destroyed, query_destroyed_changes and restore_object.
handle_get_with_history, handle_query_with_history and
handle_query_changes_with_history fall through to the plain handlers
when no history argument is set. A data-type crate's history-aware
Foo/set calls parse_restore_argument,
enforce_max_objects_in_set_with_restore and run_restore_phase (with
its RestoreHooks, e.g. ParentRestoreHooks("parentId") for
referenced-first order) before its create stage, and
append_restore_results at the end; apply_restore_patch and
restored_diff help backends. Dispatcher::register_history_aware marks a
method, and Dispatcher::object_history_gaps lists the methods of
advertised types that are not history-aware.
is_deliverable and state_change_for tell the consumer's delivery code
whether it may push to a subscription, and what StateChange to send.
Sending the pushes, and the SSRF, rate-limit, credential-revocation and
secure-erase MUSTs, are the consumer's job; the trait docs list them.
Examples
A runnable end-to-end demo lives in examples/dispatcher_minimal.rs:
It registers a single stub JmapHandler for "Core/echo", dispatches a
synthetic [JmapRequest], and prints both the wire-format [JmapResponse]
and the typed access paths a real server would consume.
How it works
parse_requestdecodes the body, validatesusingis non-empty, and caps the method-call count at the caller-suppliedmax_calls(see the Request parsing section). Capability-URI checking is the caller's job, not this crate's.Dispatcher<C>is generic over aCallerCtxtype the HTTP/auth layer produces; it walks the request'smethod_calls, resolvesResultReferenceback-references via JSON Pointer (RFC 6901), and invokes each handler undertokio::task::spawnso a panicking handler degrades toserverFailinstead of crashing the process. See CallerCtx for the identity seam.- Errors split cleanly between request-level (HTTP 400 / 403 / 500, RFC
7807 body — see Error responses) and method-level
(HTTP 200 inside
methodResponses, returned by the handler). - The crate re-exports the wire types from
jmap-types, the backend trait surface, and helper utilities so consumers do not have to take a directjmap-typesdependency — see Re-exports.
Gotchas
CallerCtxis cloned per method call.Dispatcher::dispatchperforms oneCloneof theCallerCtxvalue per method in the batch, plus twoStringclones for the method name and call_id (bd:JMAP-jfia.8). HeavyCallerCtxvalues — auth profiles, permission vectors, session tokens, anything embedding more than a pointer or a small POD — should be wrapped inArc<T>so the per-call clone is a pointer bump rather than a deep copy. A 16-call batch over a non-Arc-wrappedCallerCtxpays 16 deep clones.sortAsTreeandfilterAsTreeare RFC 8621-specific. Those two args are defined by RFC 8621 §5 forEmail/query, not by the base protocol. The generichandle_queryhandler in this crate has no knowledge of them and per RFC 8620 §3.6 silently ignores unknown args. Tree-mode traversal, when needed, must be implemented in a domain-specific handler (seehandle_email_queryin jmap-mail-server).- Filter / sort are delegated to the backend.
handle_queryparsesfilterandsortfrom method args into the backend trait'sO::FilterandO::Comparatortypes and passes them through to [JmapReads::query_objects]. The handler does no in-process re-filtering or re-sorting. The backend MUST push filter and sort into indexed storage — that contract is documented onJmapReads::query_objectsand a backend that ignores it degenerates to O(n) per page. - History arguments need the object-history URI and a history-aware
method. Without
urn:ietf:params:jmap:object-historyinusing, the dispatcher answersincludeReplaced/includeDestroyedtrue,onlyDestroyedtrue, a non-nulldestroyedAfter/destroyedBefore(on/queryand/queryChanges) and a non-emptyrestorewithinvalidArgumentsbefore any handler runs, and removes those arguments when they are at their defaults (decision 18). With the URI, a method not registered throughregister_history_aware(a type without history, or one registered plain) gets the sameinvalidArguments. - Single-process only. The dispatcher holds no shared state between requests and is safe to use concurrently; however, there is no built-in clustering support. State consistency across multiple processes is the backend's responsibility.