use crate::HandlerOutput;
use jmap_types::{Id, JmapError, State};
use serde_json::{Value, json};
use crate::backend::{
BackendChangesError, ChangesParams, GetObject, JmapBackend, JmapObject, QueryChangesParams,
QueryObject, QueryParams,
};
use crate::helpers::{
MetadataProjection, enforce_max_objects_in_get, extract_account_id, filter_arg, not_found_json,
optional_arg, query_anchor_args, serialize_value,
};
pub const SERVER_FAIL_INTERNAL_DESC: &str = "internal error";
pub fn server_fail_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> JmapError {
JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)
}
pub fn changes_error_from_backend<E: std::error::Error>(err: BackendChangesError<E>) -> JmapError {
match err {
BackendChangesError::TooManyChanges { .. } => JmapError::cannot_calculate_changes(),
other => JmapError::from(other),
}
}
pub fn server_fail_value_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> Value {
json!({
"type": "serverFail",
"description": SERVER_FAIL_INTERNAL_DESC,
})
}
pub async fn handle_get<O: GetObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
JmapError::invalid_arguments("ids must be an Id array")
})?;
let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
JmapError::invalid_arguments("properties must be a string array")
})?;
let ids_slice = ids.as_deref();
let (list, not_found) = backend
.get_objects::<O>(caller, &account_id, ids_slice, properties.as_deref())
.await
.map_err(|e| server_fail_from_backend(&e))?;
let state = backend
.get_state::<O>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let mut list_json = serialize_value(&list)?;
if let (Some(props), Value::Array(items)) = (&properties, &mut list_json) {
for item in items {
if let Value::Object(map) = item {
map.retain(|k, _| k == "id" || props.iter().any(|p| p == k));
}
}
}
Ok(HandlerOutput::new(json!({
"accountId": account_id.as_ref(),
"state": state.as_ref(),
"list": list_json,
"notFound": not_found_json(¬_found),
})))
}
pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
mut args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
let info = args
.get("accountId")
.and_then(Value::as_str)
.and_then(|s| Id::new_validated(s).ok())
.and_then(|id| backend.metadata_info::<O>(caller, &id));
let Some(info) = info else {
return handle_get::<O, B>(backend, caller, args).await;
};
let properties: Option<Vec<String>> = match args.get("properties") {
None | Some(Value::Null) => None,
Some(v) => match serde_json::from_value(v.clone()) {
Ok(props) => Some(props),
Err(_) => return handle_get::<O, B>(backend, caller, args).await,
},
};
let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
if let Some(props) = properties {
let mut roots: Vec<String> = Vec::with_capacity(props.len());
for p in props {
let root = match p.split_once('/') {
Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
_ => p,
};
if !roots.contains(&root) {
roots.push(root);
}
}
args["properties"] = json!(roots);
}
let mut out = handle_get::<O, B>(backend, caller, args).await?;
if let Some(Value::Array(list)) = out.primary.get_mut("list") {
for item in list {
let source = item.clone();
projection.apply(&source, item);
}
}
Ok(out)
}
pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
let (account_id, args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
Some(s) => State::from(s),
None => return Err(JmapError::invalid_arguments("sinceState is required")),
};
let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
let uses_metadata = using
.iter()
.any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
let ignore_metadata_only_changes = !uses_metadata
|| match args.get("ignoreMetadataOnlyChanges") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(v) => {
return Err(JmapError::invalid_arguments(format!(
"ignoreMetadataOnlyChanges: expected a boolean, got {}",
crate::helpers::json_type_name(v)
)));
}
};
let result = backend
.get_changes::<O>(
caller,
&account_id,
ChangesParams::new(&since_state)
.max_changes(max_changes)
.ignore_metadata_only_changes(ignore_metadata_only_changes),
)
.await
.map_err(changes_error_from_backend)?;
let updated_properties = if result.updated.is_empty() {
None
} else {
result.updated_properties
};
Ok(HandlerOutput::new(json!({
"accountId": account_id.as_ref(),
"oldState": since_state.as_ref(),
"newState": result.new_state.as_ref(),
"hasMoreChanges": result.has_more_changes,
"updatedProperties": updated_properties,
"created": result.created,
"updated": result.updated,
"destroyed": result.destroyed,
})))
}
pub async fn handle_query<O: QueryObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let limit: Option<u64> = match args.get("limit") {
None | Some(Value::Null) => None,
Some(v) => match v.as_u64() {
Some(n) => Some(n),
None => {
return Err(JmapError::invalid_arguments(format!(
"limit: expected a non-negative integer, got {}",
crate::helpers::json_type_name(v)
)));
}
},
};
let position: i64 = match args.get("position") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"position: expected an integer, got {}",
crate::helpers::json_type_name(v)
))
})?,
};
let (anchor, anchor_offset) = query_anchor_args(&args)?;
let filter: Option<O::Filter> = filter_arg(&mut args)?;
let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
JmapError::invalid_arguments("sort must be an array")
})?;
let result = backend
.query_objects::<O>(
caller,
&account_id,
QueryParams::new()
.filter(filter.as_ref())
.sort(sort.as_deref())
.limit(limit)
.position(position)
.anchor(anchor.as_ref())
.anchor_offset(anchor_offset),
)
.await
.map_err(JmapError::from)?;
let mut resp = json!({
"accountId": account_id.as_ref(),
"queryState": result.query_state.as_ref(),
"canCalculateChanges": result.can_calculate_changes,
"position": result.position,
"ids": result.ids,
});
if calculate_total && let Some(t) = result.total {
resp["total"] = json!(t);
}
Ok(HandlerOutput::new(resp))
}
pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
Some(s) => State::from(s),
None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
};
let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
let up_to_id: Option<Id> = match args.get("upToId") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(Id::from(s.as_str())),
Some(_) => {
return Err(JmapError::invalid_arguments(
"upToId must be a string Id or null",
));
}
};
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let filter: Option<O::Filter> = filter_arg(&mut args)?;
let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
JmapError::invalid_arguments("sort must be an array")
})?;
let result = backend
.query_changes::<O>(
caller,
&account_id,
QueryChangesParams::new(&since_query_state)
.filter(filter.as_ref())
.sort(sort.as_deref())
.max_changes(max_changes)
.up_to_id(up_to_id.as_ref()),
)
.await
.map_err(JmapError::from)?;
let added: Vec<Value> = result
.added
.iter()
.map(|item| {
json!({
"id": item.id.as_ref(),
"index": item.index,
})
})
.collect();
let mut resp = json!({
"accountId": account_id.as_ref(),
"oldQueryState": result.old_query_state.as_ref(),
"newQueryState": result.new_query_state.as_ref(),
"removed": result.removed,
"added": added,
});
if calculate_total && let Some(t) = result.total {
resp["total"] = json!(t);
}
Ok(HandlerOutput::new(resp))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_fail_from_backend_drops_display_text() {
#[derive(Debug)]
struct LeakyError(&'static str);
impl std::fmt::Display for LeakyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for LeakyError {}
const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
let err = LeakyError(CANARY);
let jmap_err = server_fail_from_backend(&err);
let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
let wire_str = wire.to_string();
assert!(
!wire_str.contains(CANARY),
"server_fail_from_backend must not echo backend error Display \
onto the wire; got {wire_str}"
);
assert_eq!(
wire["description"], SERVER_FAIL_INTERNAL_DESC,
"description must be the static 'internal error' string"
);
assert_eq!(wire["type"], "serverFail");
}
#[test]
fn server_fail_from_backend_accepts_generic_display() {
let _ = server_fail_from_backend("a string");
let _ = server_fail_from_backend(&"&str".to_owned());
let _ = server_fail_from_backend(&42_u64);
}
#[test]
fn server_fail_value_from_backend_drops_display_text() {
#[derive(Debug)]
struct LeakyError(&'static str);
impl std::fmt::Display for LeakyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for LeakyError {}
const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
let err = LeakyError(CANARY);
let wire = server_fail_value_from_backend(&err);
let wire_str = wire.to_string();
assert!(
!wire_str.contains(CANARY),
"server_fail_value_from_backend must not echo backend error \
Display onto the wire; got {wire_str}"
);
assert_eq!(wire["type"], "serverFail");
assert_eq!(
wire["description"], SERVER_FAIL_INTERNAL_DESC,
"description must be the static 'internal error' string"
);
}
#[test]
fn server_fail_value_from_backend_accepts_generic_display() {
let _ = server_fail_value_from_backend("a string");
let _ = server_fail_value_from_backend(&"owned-String".to_owned());
let owned: String = "owned".to_string();
let _ = server_fail_value_from_backend(&owned);
let _ = server_fail_value_from_backend(&42_u64);
}
use crate::backend::{
BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
QueryChangesResult, QueryParams,
};
#[derive(serde::Serialize, serde::Deserialize)]
struct QueryProbe;
impl JmapObject for QueryProbe {
const TYPE_NAME: &'static str = "QueryProbe";
type Property = ();
}
impl QueryObject for QueryProbe {
type Filter = Value;
type Comparator = Value;
}
#[derive(Debug)]
struct LeakyQueryError(&'static str);
impl std::fmt::Display for LeakyQueryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for LeakyQueryError {}
enum QueryFailure {
Method(JmapError),
Internal(&'static str),
}
struct QueryFailBackend(QueryFailure);
impl JmapBackend for QueryFailBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(true)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
unreachable!("only query_objects is exercised")
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
unreachable!("only query_objects is exercised")
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only query_objects is exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
Err(match &self.0 {
QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
})
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only query_objects is exercised")
}
}
async fn query_error_wire(failure: QueryFailure) -> Value {
let backend = QueryFailBackend(failure);
let args = json!({
"accountId": "a1",
"filter": { "text": "hello" },
"anchor": "m1",
});
let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
Ok(HandlerOutput { primary: resp, .. }) => {
panic!("query_objects failed but handle_query succeeded: {resp}")
}
Err(e) => e,
};
serde_json::to_value(&err).expect("JmapError must serialize")
}
#[tokio::test]
async fn handle_query_passes_backend_unsupported_filter_through() {
let mut expected = JmapError::unsupported_filter();
expected.description = Some("Message/query requires a chatId condition".into());
let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
assert_eq!(
wire,
serde_json::to_value(&expected).expect("JmapError must serialize"),
"backend unsupportedFilter must pass through handle_query unchanged"
);
}
#[tokio::test]
async fn handle_query_passes_backend_anchor_not_found_through() {
let expected = JmapError::anchor_not_found();
let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
assert_eq!(
wire,
serde_json::to_value(&expected).expect("JmapError must serialize"),
"backend anchorNotFound must pass through handle_query unchanged"
);
}
#[tokio::test]
async fn handle_query_redacts_backend_internal_error() {
const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
assert_eq!(wire["type"], "serverFail");
assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
assert!(
!wire.to_string().contains(CANARY),
"internal backend error Display must not reach the wire; got {wire}"
);
}
#[derive(serde::Serialize, serde::Deserialize)]
struct GetProbe;
impl JmapObject for GetProbe {
const TYPE_NAME: &'static str = "GetProbe";
type Property = ();
}
impl GetObject for GetProbe {}
struct GetProbeBackend;
impl JmapBackend for GetProbeBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(true)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
Ok(State::from("s0"))
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only /get is exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
unreachable!("only /get is exercised")
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only /get is exercised")
}
}
#[tokio::test]
async fn handle_get_over_max_objects_is_request_too_large() {
let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
let args = json!({ "accountId": "a1", "ids": ids });
match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
Ok(HandlerOutput { primary: resp, .. }) => panic!(
"501 ids exceed the maxObjectsInGet cap, but handle_get \
returned a response with {} notFound ids instead of \
requestTooLarge",
resp["notFound"].as_array().map_or(0, Vec::len)
),
Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
}
}
#[tokio::test]
async fn handle_get_null_ids_is_not_counted_against_cap() {
let args = json!({ "accountId": "a1", "ids": null });
let HandlerOutput { primary: resp, .. } =
handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
.await
.expect("null ids must not be rejected by the maxObjectsInGet cap");
assert_eq!(resp["list"], json!([]));
}
struct FullObjectBackend;
impl JmapBackend for FullObjectBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(true)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
let obj = serde_json::from_value(json!({
"id": "o1", "name": "n", "color": "c"
}))
.expect("fixture must deserialize");
Ok((vec![obj], vec![]))
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
Ok(State::from("s0"))
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only /get is exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
unreachable!("only /get is exercised")
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only /get is exercised")
}
}
#[derive(serde::Serialize, serde::Deserialize)]
struct Swatch {
id: String,
name: String,
color: String,
}
impl JmapObject for Swatch {
const TYPE_NAME: &'static str = "Swatch";
type Property = ();
}
impl GetObject for Swatch {}
#[tokio::test]
async fn handle_get_returns_only_requested_properties_and_id() {
let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": ["name"] });
let HandlerOutput { primary: resp, .. } =
handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
.await
.expect("valid /get must succeed");
assert_eq!(resp["list"], json!([{ "id": "o1", "name": "n" }]));
}
#[tokio::test]
async fn handle_get_null_properties_returns_all() {
let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": null });
let HandlerOutput { primary: resp, .. } =
handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
.await
.expect("valid /get must succeed");
assert_eq!(
resp["list"],
json!([{ "id": "o1", "name": "n", "color": "c" }])
);
}
#[derive(Default)]
struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
impl RecordingQueryBackend {
fn take(&self) -> Value {
self.0
.lock()
.unwrap()
.take()
.expect("backend query method was not called")
}
}
impl JmapBackend for RecordingQueryBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(true)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
unreachable!("only queries are exercised")
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
unreachable!("only queries are exercised")
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only queries are exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
*self.0.lock().unwrap() = Some(json!({
"filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
"sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
"limit": params.limit,
"position": params.position,
"anchor": params.anchor,
"anchorOffset": params.anchor_offset,
}));
Ok(crate::backend::QueryResult::new(
vec![],
0,
None,
State::from("q0"),
false,
))
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
*self.0.lock().unwrap() = Some(json!({
"sinceQueryState": params.since_query_state,
"filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
"sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
"maxChanges": params.max_changes,
"upToId": params.up_to_id,
"collapseThreads": params.collapse_threads,
}));
Ok(QueryChangesResult::new(
params.since_query_state.clone(),
State::from("q2"),
None,
vec![],
vec![],
))
}
}
#[tokio::test]
async fn handle_query_passes_every_argument_to_backend() {
let backend = RecordingQueryBackend::default();
let args = json!({
"accountId": "a1",
"filter": {"text": "hello"},
"sort": [{"property": "receivedAt", "isAscending": false}],
"position": 3,
"anchor": "m7",
"anchorOffset": -2,
"limit": 25,
});
handle_query::<QueryProbe, _>(&backend, &(), args)
.await
.expect("query must succeed");
assert_eq!(
backend.take(),
json!({
"filter": {"text": "hello"},
"sort": [{"property": "receivedAt", "isAscending": false}],
"limit": 25,
"position": 3,
"anchor": "m7",
"anchorOffset": -2,
})
);
}
#[tokio::test]
async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
let backend = RecordingQueryBackend::default();
handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
.await
.expect("query must succeed");
assert_eq!(
backend.take(),
json!({
"filter": null,
"sort": null,
"limit": null,
"position": 0,
"anchor": null,
"anchorOffset": 0,
})
);
}
#[tokio::test]
async fn handle_query_changes_passes_every_argument_to_backend() {
let backend = RecordingQueryBackend::default();
let args = json!({
"accountId": "a1",
"filter": {"text": "hello"},
"sort": [{"property": "receivedAt"}],
"sinceQueryState": "q1",
"maxChanges": 10,
"upToId": "m9",
});
handle_query_changes::<QueryProbe, _>(&backend, &(), args)
.await
.expect("queryChanges must succeed");
assert_eq!(
backend.take(),
json!({
"sinceQueryState": "q1",
"filter": {"text": "hello"},
"sort": [{"property": "receivedAt"}],
"maxChanges": 10,
"upToId": "m9",
"collapseThreads": false,
})
);
}
#[tokio::test]
async fn non_object_filter_is_invalid_arguments() {
for filter in [json!(42), json!("text"), json!(true), json!([])] {
let backend = RecordingQueryBackend::default();
let err = handle_query::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "filter": filter}),
)
.await
.expect_err("non-object filter must be rejected");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
let err = handle_query_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
)
.await
.expect_err("non-object filter must be rejected");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
assert!(backend.0.lock().unwrap().is_none(), "{filter}");
}
}
#[derive(Clone, Copy)]
enum Canned {
Ok,
CannotCalculate,
TooManyChanges(u64),
Internal(&'static str),
}
impl Canned {
fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
match self {
Canned::Ok => unreachable!("Canned::Ok is not an error"),
Canned::CannotCalculate => BackendChangesError::CannotCalculate,
Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
}
}
}
struct CannedBackend {
account_exists: bool,
outcome: Canned,
}
const CANNED_OK: CannedBackend = CannedBackend {
account_exists: true,
outcome: Canned::Ok,
};
impl JmapBackend for CannedBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(self.account_exists)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
unreachable!("/get is not exercised")
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
unreachable!("/get is not exercised")
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
match self.outcome {
Canned::Ok => Ok(ChangesResult::new(
vec![Id::from("c1")],
vec![Id::from("u1")],
vec![Id::from("d1")],
true,
State::from("s2"),
)),
other => Err(other.changes_error()),
}
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
Ok(crate::backend::QueryResult::new(
vec![Id::from("m1")],
0,
Some(7),
State::from("q1"),
true,
))
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
match self.outcome {
Canned::Ok => Ok(QueryChangesResult::new(
params.since_query_state.clone(),
State::from("q2"),
Some(7),
vec![Id::from("r1")],
vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
)),
other => Err(other.changes_error()),
}
}
}
#[tokio::test]
async fn handle_changes_response_matches_rfc_shape() {
let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
&CANNED_OK,
&(),
json!({"accountId": "a1", "sinceState": "s1"}),
&[],
)
.await
.expect("/changes must succeed");
assert_eq!(
resp,
json!({
"accountId": "a1",
"oldState": "s1",
"newState": "s2",
"hasMoreChanges": true,
"updatedProperties": null,
"created": ["c1"],
"updated": ["u1"],
"destroyed": ["d1"],
})
);
}
const CORE: &str = "urn:ietf:params:jmap:core";
const METADATA: &str = "urn:ietf:params:jmap:metadata";
struct MetadataChangesBackend {
updated: Vec<Id>,
updated_properties: Option<Vec<String>>,
seen_ignore: std::sync::Mutex<Option<bool>>,
}
impl MetadataChangesBackend {
fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
Self {
updated: updated.iter().map(|u| Id::from(*u)).collect(),
updated_properties: updated_properties
.map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
seen_ignore: std::sync::Mutex::new(None),
}
}
}
impl JmapBackend for MetadataChangesBackend {
type Error = LeakyQueryError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<bool, Self::Error> {
Ok(true)
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
unreachable!("only get_changes is exercised")
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
unreachable!("only get_changes is exercised")
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
*self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
Ok(ChangesResult::new(
Vec::new(),
self.updated.clone(),
Vec::new(),
false,
State::from("s2"),
)
.with_updated_properties(self.updated_properties.clone()))
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
unreachable!("only get_changes is exercised")
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only get_changes is exercised")
}
}
async fn ignore_seen(using: &[&str], extra: Value) -> bool {
let backend = MetadataChangesBackend::new(&["u1"], None);
let mut args = json!({"accountId": "a1", "sinceState": "s1"});
if let Value::Object(extra) = extra {
args.as_object_mut().unwrap().extend(extra);
}
let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
.await
.expect("/changes must succeed");
backend
.seen_ignore
.lock()
.unwrap()
.expect("backend must be called")
}
#[tokio::test]
async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
assert!(ignore_seen(&[CORE], json!({})).await);
assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
assert!(ignore_seen(&[], json!({})).await);
}
#[tokio::test]
async fn changes_with_metadata_capability_passes_ignore_argument() {
assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
assert!(
!ignore_seen(
&[CORE, METADATA],
json!({"ignoreMetadataOnlyChanges": null})
)
.await
);
assert!(
!ignore_seen(
&[CORE, METADATA],
json!({"ignoreMetadataOnlyChanges": false})
)
.await
);
assert!(
ignore_seen(
&[CORE, METADATA],
json!({"ignoreMetadataOnlyChanges": true})
)
.await
);
}
#[tokio::test]
async fn changes_rejects_non_boolean_ignore_argument() {
let backend = MetadataChangesBackend::new(&["u1"], None);
let err = handle_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
&[CORE.to_owned(), METADATA.to_owned()],
)
.await
.expect_err("a string ignoreMetadataOnlyChanges must fail");
assert_eq!(err.error_type.to_string(), "invalidArguments");
assert!(
backend.seen_ignore.lock().unwrap().is_none(),
"backend must not be called"
);
}
#[tokio::test]
async fn changes_reports_backend_updated_properties() {
let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "sinceState": "s1"}),
&[CORE.to_owned(), METADATA.to_owned()],
)
.await
.expect("/changes must succeed");
assert_eq!(
resp,
json!({
"accountId": "a1",
"oldState": "s1",
"newState": "s2",
"hasMoreChanges": false,
"updatedProperties": ["metadata"],
"created": [],
"updated": ["u1"],
"destroyed": [],
})
);
}
#[tokio::test]
async fn changes_updated_properties_null_when_updated_empty() {
let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "sinceState": "s1"}),
&[CORE.to_owned(), METADATA.to_owned()],
)
.await
.expect("/changes must succeed");
assert_eq!(resp["updatedProperties"], Value::Null);
assert!(
resp.as_object().unwrap().contains_key("updatedProperties"),
"updatedProperties must be present"
);
}
#[tokio::test]
async fn handle_query_changes_response_matches_rfc_shape() {
let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
&CANNED_OK,
&(),
json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
)
.await
.expect("/queryChanges must succeed");
assert_eq!(
resp,
json!({
"accountId": "a1",
"oldQueryState": "q1",
"newQueryState": "q2",
"total": 7,
"removed": ["r1"],
"added": [{"id": "n1", "index": 0}],
})
);
let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
&CANNED_OK,
&(),
json!({"accountId": "a1", "sinceQueryState": "q1"}),
)
.await
.expect("/queryChanges must succeed");
assert!(
resp.get("total").is_none(),
"total must be omitted without calculateTotal; got {resp}"
);
}
#[tokio::test]
async fn handle_query_total_only_when_requested() {
for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
&CANNED_OK,
&(),
json!({"accountId": "a1", "calculateTotal": calculate_total}),
)
.await
.expect("/query must succeed");
assert_eq!(resp.get("total").cloned(), expected, "{resp}");
}
}
#[tokio::test]
async fn missing_or_non_string_since_state_is_invalid_arguments() {
for since in [None, Some(json!(42))] {
let mut args = json!({"accountId": "a1"});
if let Some(v) = &since {
args["sinceState"] = v.clone();
}
let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
.await
.expect_err("/changes without a string sinceState must fail");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
let mut args = json!({"accountId": "a1"});
if let Some(v) = &since {
args["sinceQueryState"] = v.clone();
}
let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
.await
.expect_err("/queryChanges without a string sinceQueryState must fail");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
}
}
#[tokio::test]
async fn non_string_up_to_id_is_invalid_arguments() {
for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
let err = handle_query_changes::<QueryProbe, _>(
&CANNED_OK,
&(),
json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
)
.await
.expect_err("non-Id upToId must be rejected");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
}
}
#[tokio::test]
async fn handle_query_negative_limit_is_invalid_arguments() {
let backend = RecordingQueryBackend::default();
let err =
handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
.await
.expect_err("negative limit must be rejected");
assert_eq!(err.error_type.to_string(), "invalidArguments");
assert!(
backend.0.lock().unwrap().is_none(),
"backend must not be consulted"
);
}
#[tokio::test]
async fn handle_query_negative_position_reaches_backend() {
let backend = RecordingQueryBackend::default();
handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
.await
.expect("negative position is valid");
assert_eq!(backend.take()["position"], json!(-5));
}
#[tokio::test]
async fn changes_backend_errors_map_to_rfc_errors() {
const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
for (outcome, changes_type, query_changes_type) in [
(
Canned::CannotCalculate,
"cannotCalculateChanges",
"cannotCalculateChanges",
),
(
Canned::TooManyChanges(10),
"cannotCalculateChanges",
"tooManyChanges",
),
(Canned::Internal(CANARY), "serverFail", "serverFail"),
] {
let backend = CannedBackend {
account_exists: true,
outcome,
};
let changes = handle_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "sinceState": "s1"}),
&[],
)
.await;
let query_changes = handle_query_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "a1", "sinceQueryState": "q1"}),
)
.await;
for (result, expected_type) in
[(changes, changes_type), (query_changes, query_changes_type)]
{
let err = result.expect_err("backend error must fail the call");
let wire = serde_json::to_value(&err).expect("JmapError must serialize");
assert_eq!(wire["type"], expected_type, "{wire}");
assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
}
}
}
#[tokio::test]
async fn unknown_account_is_account_not_found() {
let backend = CannedBackend {
account_exists: false,
outcome: Canned::Ok,
};
let results = [
handle_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "nope", "sinceState": "s1"}),
&[],
)
.await,
handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
handle_query_changes::<QueryProbe, _>(
&backend,
&(),
json!({"accountId": "nope", "sinceQueryState": "q1"}),
)
.await,
];
for result in results {
let err = result.expect_err("unknown account must fail");
assert_eq!(err.error_type.to_string(), "accountNotFound");
}
}
#[tokio::test]
async fn handle_query_does_not_echo_wrongly_typed_value() {
for name in ["limit", "position"] {
let backend = RecordingQueryBackend::default();
let mut args = json!({ "accountId": "a1" });
args[name] = json!({ "note": "CANARY-zegc" });
let err = handle_query::<QueryProbe, _>(&backend, &(), args)
.await
.expect_err("wrongly typed argument must be rejected");
assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
let desc = err.description.as_deref().unwrap_or_default();
assert!(desc.starts_with(name), "{desc}");
assert!(desc.contains("got object"), "{desc}");
assert!(!desc.contains("CANARY"), "{desc}");
}
}
}