use crate::HandlerOutput;
use jmap_types::{Id, JmapError, State};
use serde_json::{json, Value};
use crate::backend::{GetObject, JmapBackend, JmapObject, QueryObject};
use crate::helpers::{
enforce_max_objects_in_get, extract_account_id, 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 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 list_json = serialize_value(&list)?;
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_changes<O: JmapObject, B: JmapBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> 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: Option<u64> = match args.get("maxChanges") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
JmapError::invalid_arguments("maxChanges must be a positive integer")
})?),
};
let result = backend
.get_changes::<O>(caller, &account_id, &since_state, max_changes)
.await
.map_err(JmapError::from)?;
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": Value::Null,
"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 {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 {v}"))
})?,
};
let (anchor, anchor_offset) = query_anchor_args(&args)?;
let filter: Option<O::Filter> =
optional_arg(&mut args, "filter", JmapError::unsupported_filter)?;
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,
filter.as_ref(),
sort.as_deref(),
limit,
position,
anchor.as_ref(),
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 {
if 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: Option<u64> = match args.get("maxChanges") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
JmapError::invalid_arguments("maxChanges must be a positive integer")
})?),
};
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> =
optional_arg(&mut args, "filter", JmapError::unsupported_filter)?;
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,
&since_query_state,
filter.as_ref(),
sort.as_deref(),
max_changes,
up_to_id.as_ref(),
false, )
.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 {
if 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, QueryChangesResult,
};
#[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,
_since_state: &State,
_max_changes: Option<u64>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only query_objects is exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_filter: Option<&O::Filter>,
_sort: Option<&[O::Comparator]>,
_limit: Option<u64>,
_position: i64,
_anchor: Option<&Id>,
_anchor_offset: i64,
) -> 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,
_since_query_state: &State,
_filter: Option<&O::Filter>,
_sort: Option<&[O::Comparator]>,
_max_changes: Option<u64>,
_up_to_id: Option<&Id>,
_collapse_threads: bool,
) -> 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,
_since_state: &State,
_max_changes: Option<u64>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("only /get is exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_filter: Option<&O::Filter>,
_sort: Option<&[O::Comparator]>,
_limit: Option<u64>,
_position: i64,
_anchor: Option<&Id>,
_anchor_offset: i64,
) -> 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,
_since_query_state: &State,
_filter: Option<&O::Filter>,
_sort: Option<&[O::Comparator]>,
_max_changes: Option<u64>,
_up_to_id: Option<&Id>,
_collapse_threads: bool,
) -> 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.as_str(), "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!([]));
}
}