#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(async_fn_in_trait)]
use jmap_server::HandlerOutput;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
pub use jmap_chat_server::memory::{MemoryBackend, MemoryError};
use jmap_chat_server::{
AttachmentBlob, ChatAccessPolicy, ChatBackend, ChatEvents, ChatLimits, ChatMessageLifecycle,
ChatModeration, ChatResolvers, ChatRestrictions, ChatSettings, ChatSpaces, ChatStore,
DelegateChatMessageLifecycle, DelegateChatResolvers, EmojiSetOp, InviteJoinRefusal, OpResult,
SlowModeError, SpacePatchOp, SpacePolicy,
};
use jmap_server::{
BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
JmapAccounts, JmapBackend, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult,
QueryObject, QueryParams, QueryResult, SetError, SetErrorType, SetObject,
};
use jmap_types::{Id, PatchObject, State, UTCDate};
#[derive(Clone, Default)]
pub struct FaultyBackend;
impl JmapAccounts for FaultyBackend {
type Error = MemoryError;
type CallerCtx = ();
async fn account_exists(&self, _caller: &(), _account_id: &Id) -> Result<bool, Self::Error> {
Err(MemoryError::new("storage unavailable"))
}
}
impl JmapReads for FaultyBackend {
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> {
Err(MemoryError::new("storage unavailable"))
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<State, Self::Error> {
Err(MemoryError::new("storage unavailable"))
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: jmap_server::ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
Err(BackendChangesError::Other(MemoryError::new(
"storage unavailable",
)))
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
Err(BackendQueryError::Other(MemoryError::new(
"storage unavailable",
)))
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
Err(BackendChangesError::Other(MemoryError::new(
"storage unavailable",
)))
}
}
impl ChatStore for FaultyBackend {
async fn create_object<O, F>(
&self,
_caller: &(),
_account_id: &Id,
_create_id: &str,
_build: F,
) -> Result<(Id, O), BackendSetError<Self::Error>>
where
O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send,
{
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_id: &Id,
_patch: O::Patch,
) -> Result<Option<O>, BackendSetError<Self::Error>> {
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &Id,
_id: &Id,
) -> Result<(), BackendSetError<Self::Error>> {
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
fn supports_type<O: JmapObject>(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
) -> bool {
false
}
}
impl ChatSpaces for FaultyBackend {
async fn join_space_with_invite(
&self,
_caller: &(),
_account_id: &Id,
_invite_id: &Id,
_joined_at: &UTCDate,
) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
Err(MemoryError::new("storage unavailable"))
}
async fn generate_invite_code(
&self,
_caller: &(),
_account_id: &Id,
) -> Result<String, MemoryError> {
Ok(format!(
"{:012x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
& 0xffff_ffff_ffff,
))
}
async fn everyone_permissions(
&self,
_caller: &(),
_account_id: &Id,
_space: &jmap_chat_types::Space,
) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
Err(MemoryError::new("storage unavailable"))
}
async fn apply_space_patch(
&self,
_caller: &(),
_account_id: &Id,
_space_id: &Id,
_ops: Vec<SpacePatchOp>,
) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
async fn apply_space_metadata_patch(
&self,
_caller: &(),
_account_id: &Id,
_space_id: &Id,
_patch: jmap_chat_types::SpaceMetadataPatch,
) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
}
impl SpacePolicy for FaultyBackend {}
impl ChatAccessPolicy for FaultyBackend {}
impl ChatRestrictions for FaultyBackend {}
impl ChatModeration for FaultyBackend {}
impl ChatMessageLifecycle for FaultyBackend {
async fn read_and_burn_message(
&self,
_caller: &(),
_account_id: &Id,
_message_id: &Id,
_patch: PatchObject,
) -> Result<(), BackendSetError<Self::Error>> {
Err(BackendSetError::Other(MemoryError::new(
"storage unavailable",
)))
}
}
impl ChatEvents for FaultyBackend {}
impl ChatSettings for FaultyBackend {}
impl ChatResolvers for FaultyBackend {
async fn attachment_blob(
&self,
_caller: &(),
_account_id: &Id,
_blob_id: &Id,
) -> Result<Result<Option<jmap_chat_server::AttachmentBlob>, jmap_server::SetError>, MemoryError>
{
Ok(Ok(None))
}
}
#[derive(Clone, Default)]
pub struct TrackingBackend {
inner: MemoryBackend<()>,
slow_mode_block: Option<UTCDate>,
emoji_set_deny: bool,
emoji_set_fail: bool,
emoji_set_calls: Arc<Mutex<Vec<EmojiSetCall>>>,
broadcast_mention_deny: bool,
chat_view_deny: bool,
is_contact_blocked_calls: Arc<AtomicU64>,
room_restricted: bool,
get_objects_calls: Arc<Mutex<HashMap<&'static str, u64>>>,
get_objects_fail: Option<&'static str>,
create_input_ids: Arc<Mutex<Vec<serde_json::Value>>>,
attachment_blob_reject: Option<SetError>,
attachment_blob_fail: bool,
filenode_attachment: Option<Result<jmap_chat_types::Attachment, SetError>>,
filenode_attachment_calls: Arc<AtomicU64>,
kick_calls: Arc<Mutex<Vec<KickCall>>>,
}
pub type KickCall = (String, Vec<String>);
pub type EmojiSetCall = (Option<Id>, EmojiSetOp);
const ROOM_FORBIDDEN_CHAT_KEYS: &[&str] = &[
"name",
"description",
"avatarBlobId",
"addMembers",
"removeMembers",
"updateMemberRoles",
];
const ROOM_FROZEN_MESSAGE_PROPS: &[&str] = &["body", "bodyType", "reactions"];
fn is_room_chat(chat: &jmap_chat_types::Chat) -> bool {
chat.extra.contains_key("roomId")
}
impl TrackingBackend {
pub fn new() -> Self {
Self {
inner: account_backend(),
..Self::default()
}
}
pub fn with_slow_mode_blocking(retry_after: UTCDate) -> Self {
Self {
slow_mode_block: Some(retry_after),
..Self::new()
}
}
pub fn with_emoji_set_denied() -> Self {
Self {
emoji_set_deny: true,
..Self::new()
}
}
pub fn with_emoji_set_failing() -> Self {
Self {
emoji_set_fail: true,
..Self::new()
}
}
pub fn emoji_set_calls(&self) -> Vec<EmojiSetCall> {
self.emoji_set_calls.lock().unwrap().clone()
}
pub fn with_broadcast_mention_denied() -> Self {
Self {
broadcast_mention_deny: true,
..Self::new()
}
}
pub fn with_chat_view_denied() -> Self {
Self {
chat_view_deny: true,
..Self::new()
}
}
pub fn with_room_restrictions() -> Self {
Self {
room_restricted: true,
..Self::new()
}
}
pub fn with_get_objects_failing(type_name: &'static str) -> Self {
Self {
get_objects_fail: Some(type_name),
..Self::new()
}
}
pub fn with_attachment_blob_rejected(set_error: SetError) -> Self {
Self {
attachment_blob_reject: Some(set_error),
..Self::new()
}
}
pub fn with_attachment_blob_failing() -> Self {
Self {
attachment_blob_fail: true,
..Self::new()
}
}
pub fn with_filenode_attachment(result: Result<jmap_chat_types::Attachment, SetError>) -> Self {
Self {
filenode_attachment: Some(result),
..Self::new()
}
}
pub fn filenode_attachment_call_count(&self) -> u64 {
self.filenode_attachment_calls.load(Ordering::SeqCst)
}
pub fn inner(&self) -> &MemoryBackend<()> {
&self.inner
}
pub fn get_objects_call_count(&self, type_name: &str) -> u64 {
let calls = self.get_objects_calls.lock().expect("lock poisoned");
calls.get(type_name).copied().unwrap_or(0)
}
pub fn create_input_ids(&self) -> Vec<serde_json::Value> {
self.create_input_ids.lock().expect("lock poisoned").clone()
}
pub fn is_contact_blocked_call_count(&self) -> u64 {
self.is_contact_blocked_calls.load(Ordering::SeqCst)
}
pub fn kick_calls(&self) -> Vec<KickCall> {
self.kick_calls.lock().expect("lock poisoned").clone()
}
}
impl JmapAccounts for TrackingBackend {
type Error = MemoryError;
type CallerCtx = ();
async fn account_exists(&self, caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
self.inner.account_exists(caller, account_id).await
}
}
impl JmapReads for TrackingBackend {
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> {
*self
.get_objects_calls
.lock()
.expect("lock poisoned")
.entry(O::TYPE_NAME)
.or_default() += 1;
if self.get_objects_fail == Some(O::TYPE_NAME) {
return Err(MemoryError::new("injected get_objects failure"));
}
self.inner
.get_objects::<O>(caller, account_id, ids, properties)
.await
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
) -> Result<State, Self::Error> {
self.inner.get_state::<O>(caller, account_id).await
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: jmap_server::ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
self.inner
.get_changes::<O>(caller, account_id, params)
.await
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
self.inner
.query_objects::<O>(caller, account_id, params)
.await
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
self.inner
.query_changes::<O>(caller, account_id, params)
.await
}
}
impl ChatStore for TrackingBackend {
async fn create_object<O, F>(
&self,
caller: &(),
account_id: &Id,
create_id: &str,
build: F,
) -> Result<(Id, O), BackendSetError<Self::Error>>
where
O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send,
{
let ids = Arc::clone(&self.create_input_ids);
self.inner
.create_object(caller, account_id, create_id, move |id: &Id| {
let obj = build(id);
let built = serde_json::to_value(&obj).expect("JmapObject serializes");
ids.lock().expect("lock poisoned").push(built["id"].clone());
obj
})
.await
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> Result<Option<O>, BackendSetError<Self::Error>> {
self.inner
.update_object::<O>(caller, account_id, id, patch)
.await
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
id: &Id,
) -> Result<(), BackendSetError<Self::Error>> {
self.inner.destroy_object::<O>(caller, account_id, id).await
}
fn supports_type<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> bool {
self.inner.supports_type::<O>(caller, account_id)
}
}
impl ChatSpaces for TrackingBackend {
async fn join_space_with_invite(
&self,
caller: &(),
account_id: &Id,
invite_id: &Id,
joined_at: &UTCDate,
) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
self.inner
.join_space_with_invite(caller, account_id, invite_id, joined_at)
.await
}
async fn generate_invite_code(
&self,
_caller: &(),
account_id: &Id,
) -> Result<String, MemoryError> {
self.inner.generate_invite_code(&(), account_id).await
}
async fn everyone_permissions(
&self,
_caller: &(),
account_id: &Id,
space: &jmap_chat_types::Space,
) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
self.inner
.everyone_permissions(&(), account_id, space)
.await
}
async fn apply_space_patch(
&self,
caller: &(),
account_id: &Id,
space_id: &Id,
ops: Vec<SpacePatchOp>,
) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
self.inner
.apply_space_patch(caller, account_id, space_id, ops)
.await
}
async fn apply_space_metadata_patch(
&self,
caller: &(),
account_id: &Id,
space_id: &Id,
patch: jmap_chat_types::SpaceMetadataPatch,
) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
self.inner
.apply_space_metadata_patch(caller, account_id, space_id, patch)
.await
}
}
impl SpacePolicy for TrackingBackend {
async fn may_set_custom_emoji(
&self,
caller: &(),
account_id: &Id,
target_space_id: Option<&Id>,
op: EmojiSetOp,
) -> Result<Result<(), SetError>, Self::Error> {
self.emoji_set_calls
.lock()
.unwrap()
.push((target_space_id.cloned(), op));
if self.emoji_set_fail {
return Err(MemoryError::new(INJECTABLE_BACKEND_CANARY));
}
if self.emoji_set_deny {
Ok(Err(SetError::new(SetErrorType::Forbidden)
.with_description(
"TrackingBackend deny_set_custom_emoji: emoji authorization denied for test.",
)))
} else {
self.inner
.may_set_custom_emoji(caller, account_id, target_space_id, op)
.await
}
}
}
impl ChatAccessPolicy for TrackingBackend {
async fn slow_mode_check(
&self,
caller: &(),
account_id: &Id,
chat_id: &Id,
) -> Result<(), SlowModeError> {
match &self.slow_mode_block {
Some(d) => Err(SlowModeError::new(d.clone())),
None => {
self.inner
.slow_mode_check(caller, account_id, chat_id)
.await
}
}
}
async fn may_broadcast_mention(
&self,
caller: &(),
account_id: &Id,
space_id: &Id,
chat_id: &Id,
) -> Result<Result<(), SetError>, Self::Error> {
if self.broadcast_mention_deny {
Ok(Err(SetError::new(SetErrorType::Forbidden)
.with_description(
"TrackingBackend deny_broadcast_mention: mention_broadcast denied for test.",
)))
} else {
self.inner
.may_broadcast_mention(caller, account_id, space_id, chat_id)
.await
}
}
async fn may_view_chat(
&self,
caller: &(),
account_id: &Id,
chat_id: &Id,
) -> Result<bool, Self::Error> {
if self.chat_view_deny {
Ok(false)
} else {
self.inner.may_view_chat(caller, account_id, chat_id).await
}
}
async fn is_contact_blocked(
&self,
caller: &(),
account_id: &Id,
contact_id: &Id,
) -> Result<bool, Self::Error> {
self.is_contact_blocked_calls.fetch_add(1, Ordering::SeqCst);
self.inner
.is_contact_blocked(caller, account_id, contact_id)
.await
}
}
impl ChatRestrictions for TrackingBackend {
async fn may_create_message(
&self,
caller: &(),
account_id: &Id,
chat: &jmap_chat_types::Chat,
) -> Result<Result<(), SetError>, Self::Error> {
if self.room_restricted && is_room_chat(chat) {
return Ok(Err(SetError::new(SetErrorType::Forbidden)
.with_description(
"messages in a MIMI room are sent with Room/send",
)));
}
self.inner
.may_create_message(caller, account_id, chat)
.await
}
async fn may_update_message(
&self,
caller: &(),
account_id: &Id,
chat: &jmap_chat_types::Chat,
message: &jmap_chat_types::Message,
patch_keys: &[&str],
) -> Result<Result<(), SetError>, Self::Error> {
if self.room_restricted && is_room_chat(chat) {
let mut changed: Vec<String> = Vec::new();
for key in patch_keys {
let top = key.split('/').next().unwrap_or(key);
if ROOM_FROZEN_MESSAGE_PROPS.contains(&top) && !changed.iter().any(|c| c == top) {
changed.push(top.to_owned());
}
}
if !changed.is_empty() {
return Ok(Err(
SetError::new(SetErrorType::InvalidProperties).with_properties(changed)
));
}
}
self.inner
.may_update_message(caller, account_id, chat, message, patch_keys)
.await
}
async fn may_update_chat(
&self,
caller: &(),
account_id: &Id,
chat: &jmap_chat_types::Chat,
patch_keys: &[&str],
) -> Result<Result<(), SetError>, Self::Error> {
if self.room_restricted
&& is_room_chat(chat)
&& patch_keys
.iter()
.any(|k| ROOM_FORBIDDEN_CHAT_KEYS.contains(k))
{
return Ok(Err(SetError::new(SetErrorType::Forbidden)
.with_description("a MIMI room is changed with Room/update")));
}
self.inner
.may_update_chat(caller, account_id, chat, patch_keys)
.await
}
}
impl ChatModeration for TrackingBackend {
async fn kick_chat_members(
&self,
caller: &(),
account_id: &Id,
chat: &jmap_chat_types::Chat,
user_ids: &[Id],
) -> Result<Result<(), SetError>, Self::Error> {
if self.room_restricted && is_room_chat(chat) {
self.kick_calls.lock().expect("lock poisoned").push((
chat.id.as_ref().to_owned(),
user_ids.iter().map(|u| u.as_ref().to_owned()).collect(),
));
return Ok(Ok(()));
}
self.inner
.kick_chat_members(caller, account_id, chat, user_ids)
.await
}
}
impl DelegateChatMessageLifecycle for TrackingBackend {
type Target = MemoryBackend<()>;
fn chat_message_lifecycle(&self) -> &MemoryBackend<()> {
&self.inner
}
}
impl ChatEvents for TrackingBackend {
async fn on_outbound_event(
&self,
caller: &(),
account_id: &Id,
event: &jmap_chat_server::OutboundEvent,
) {
self.inner
.on_outbound_event(caller, account_id, event)
.await
}
}
impl ChatSettings for TrackingBackend {
fn limits(&self, caller: &(), account_id: &Id) -> ChatLimits {
self.inner.limits(caller, account_id)
}
fn retains_edit_history(&self) -> bool {
self.inner.retains_edit_history()
}
}
impl ChatResolvers for TrackingBackend {
async fn attachment_blob(
&self,
caller: &(),
account_id: &Id,
blob_id: &Id,
) -> Result<Result<Option<AttachmentBlob>, SetError>, Self::Error> {
if self.attachment_blob_fail {
return Err(MemoryError::new("injected attachment_blob failure"));
}
if let Some(set_error) = &self.attachment_blob_reject {
return Ok(Err(set_error.clone()));
}
self.inner
.attachment_blob(caller, account_id, blob_id)
.await
}
async fn filenode_attachment(
&self,
caller: &(),
account_id: &Id,
chat: &jmap_chat_types::Chat,
attachment: &jmap_chat_types::AttachmentCreate,
) -> Result<Result<Option<jmap_chat_types::Attachment>, SetError>, Self::Error> {
self.filenode_attachment_calls
.fetch_add(1, Ordering::SeqCst);
match &self.filenode_attachment {
Some(result) => Ok(result.clone().map(Some)),
None => {
self.inner
.filenode_attachment(caller, account_id, chat, attachment)
.await
}
}
}
}
#[derive(Clone, Default)]
pub struct IdentityBackend {
inner: MemoryBackend<()>,
invite_code_fails: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl IdentityBackend {
pub fn new() -> Self {
Self::default()
}
pub fn fail_invite_codes(&self) {
self.invite_code_fails
.store(true, std::sync::atomic::Ordering::SeqCst);
}
pub fn inner(&self) -> &MemoryBackend<()> {
&self.inner
}
}
impl JmapAccounts for IdentityBackend {
type Error = MemoryError;
type CallerCtx = Id;
fn principal_id(caller: &Self::CallerCtx) -> Option<&Id> {
Some(caller)
}
async fn account_exists(&self, _caller: &Id, account_id: &Id) -> Result<bool, Self::Error> {
self.inner.account_exists(&(), account_id).await
}
}
impl JmapReads for IdentityBackend {
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
ids: Option<&[Id]>,
properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
self.inner
.get_objects::<O>(&(), account_id, ids, properties)
.await
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
) -> Result<State, Self::Error> {
self.inner.get_state::<O>(&(), account_id).await
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
params: jmap_server::ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
self.inner.get_changes::<O>(&(), account_id, params).await
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
self.inner.query_objects::<O>(&(), account_id, params).await
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
self.inner.query_changes::<O>(&(), account_id, params).await
}
}
impl ChatStore for IdentityBackend {
async fn create_object<O, F>(
&self,
_caller: &Id,
account_id: &Id,
create_id: &str,
build: F,
) -> Result<(Id, O), BackendSetError<Self::Error>>
where
O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send,
{
self.inner
.create_object(&(), account_id, create_id, build)
.await
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> Result<Option<O>, BackendSetError<Self::Error>> {
self.inner
.update_object::<O>(&(), account_id, id, patch)
.await
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
_caller: &Id,
account_id: &Id,
id: &Id,
) -> Result<(), BackendSetError<Self::Error>> {
self.inner.destroy_object::<O>(&(), account_id, id).await
}
fn supports_type<O: JmapObject>(&self, _caller: &Id, account_id: &Id) -> bool {
self.inner.supports_type::<O>(&(), account_id)
}
}
impl ChatSpaces for IdentityBackend {
async fn join_space_with_invite(
&self,
_caller: &Id,
account_id: &Id,
invite_id: &Id,
joined_at: &UTCDate,
) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
self.inner
.join_space_with_invite(&(), account_id, invite_id, joined_at)
.await
}
async fn generate_invite_code(
&self,
_caller: &Id,
account_id: &Id,
) -> Result<String, MemoryError> {
if self
.invite_code_fails
.load(std::sync::atomic::Ordering::SeqCst)
{
return Err(MemoryError::new("entropy source unavailable"));
}
self.inner.generate_invite_code(&(), account_id).await
}
async fn everyone_permissions(
&self,
_caller: &Id,
account_id: &Id,
space: &jmap_chat_types::Space,
) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
self.inner
.everyone_permissions(&(), account_id, space)
.await
}
fn protect_last_admin(&self, _caller: &Id, account_id: &Id) -> bool {
self.inner.protect_last_admin(&(), account_id)
}
async fn apply_space_patch(
&self,
_caller: &Id,
account_id: &Id,
space_id: &Id,
ops: Vec<SpacePatchOp>,
) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
self.inner
.apply_space_patch(&(), account_id, space_id, ops)
.await
}
async fn apply_space_metadata_patch(
&self,
_caller: &Id,
account_id: &Id,
space_id: &Id,
patch: jmap_chat_types::SpaceMetadataPatch,
) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
self.inner
.apply_space_metadata_patch(&(), account_id, space_id, patch)
.await
}
}
impl SpacePolicy for IdentityBackend {
async fn may_set_custom_emoji(
&self,
_caller: &Id,
account_id: &Id,
target_space_id: Option<&Id>,
op: EmojiSetOp,
) -> Result<Result<(), SetError>, Self::Error> {
self.inner
.may_set_custom_emoji(&(), account_id, target_space_id, op)
.await
}
async fn may_set_space_ban(
&self,
_caller: &Id,
account_id: &Id,
space_id: &Id,
) -> Result<Result<(), SetError>, Self::Error> {
self.inner
.may_set_space_ban(&(), account_id, space_id)
.await
}
async fn may_set_space_invite(
&self,
_caller: &Id,
account_id: &Id,
space_id: &Id,
created_by: Option<&Id>,
) -> Result<Result<(), SetError>, Self::Error> {
self.inner
.may_set_space_invite(&(), account_id, space_id, created_by)
.await
}
async fn may_get_space_invite(
&self,
_caller: &Id,
account_id: &Id,
invite: &jmap_chat_types::SpaceInvite,
) -> Result<bool, Self::Error> {
self.inner
.may_get_space_invite(&(), account_id, invite)
.await
}
async fn may_get_space_ban(
&self,
_caller: &Id,
account_id: &Id,
ban: &jmap_chat_types::SpaceBan,
) -> Result<bool, Self::Error> {
self.inner.may_get_space_ban(&(), account_id, ban).await
}
}
impl ChatAccessPolicy for IdentityBackend {
async fn slow_mode_check(
&self,
_caller: &Id,
account_id: &Id,
chat_id: &Id,
) -> Result<(), SlowModeError> {
self.inner.slow_mode_check(&(), account_id, chat_id).await
}
async fn may_set_pinned_messages(
&self,
_caller: &Id,
account_id: &Id,
chat_id: &Id,
) -> Result<Result<(), SetError>, Self::Error> {
self.inner
.may_set_pinned_messages(&(), account_id, chat_id)
.await
}
async fn may_send_message(
&self,
_caller: &Id,
account_id: &Id,
chat_id: &Id,
) -> Result<Result<(), SetError>, Self::Error> {
self.inner.may_send_message(&(), account_id, chat_id).await
}
async fn may_view_chat(
&self,
_caller: &Id,
account_id: &Id,
chat_id: &Id,
) -> Result<bool, Self::Error> {
self.inner.may_view_chat(&(), account_id, chat_id).await
}
async fn is_contact_blocked(
&self,
_caller: &Id,
account_id: &Id,
contact_id: &Id,
) -> Result<bool, Self::Error> {
self.inner
.is_contact_blocked(&(), account_id, contact_id)
.await
}
}
impl ChatRestrictions for IdentityBackend {}
impl ChatModeration for IdentityBackend {}
impl ChatMessageLifecycle for IdentityBackend {
async fn expire_message(
&self,
_caller: &Id,
account_id: &Id,
message_id: &Id,
) -> Result<(), Self::Error> {
self.inner.expire_message(&(), account_id, message_id).await
}
async fn read_and_burn_message(
&self,
_caller: &Id,
account_id: &Id,
message_id: &Id,
patch: PatchObject,
) -> Result<(), BackendSetError<Self::Error>> {
self.inner
.read_and_burn_message(&(), account_id, message_id, patch)
.await
}
}
impl ChatEvents for IdentityBackend {}
impl ChatSettings for IdentityBackend {
fn limits(&self, _caller: &Id, account_id: &Id) -> ChatLimits {
self.inner.limits(&(), account_id)
}
fn retains_edit_history(&self) -> bool {
self.inner.retains_edit_history()
}
}
impl ChatResolvers for IdentityBackend {
async fn attachment_blob(
&self,
_caller: &Id,
account_id: &Id,
blob_id: &Id,
) -> Result<Result<Option<jmap_chat_server::AttachmentBlob>, jmap_server::SetError>, MemoryError>
{
self.inner.attachment_blob(&(), account_id, blob_id).await
}
}
pub const INJECTABLE_BACKEND_CANARY: &str = "BACKEND-CANARY-LEAK-DO-NOT-WIRE-7f3a2";
pub const INJECTED_QUERY_METHOD_ERROR_DESCRIPTION: &str = "backend cannot process this filter";
pub struct InjectableBackend {
pub inner: MemoryBackend<()>,
failures:
std::sync::Arc<std::sync::Mutex<std::collections::HashSet<(&'static str, &'static str)>>>,
chat_race_phantom: std::sync::Arc<std::sync::Mutex<Option<ChatRacePhantom>>>,
chat_get_fault_after_create: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
struct ChatRacePhantom {
account_id: String,
phantom_id: String,
contact_id: String,
}
impl InjectableBackend {
pub fn new() -> Self {
Self {
inner: account_backend(),
failures: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
chat_race_phantom: std::sync::Arc::new(std::sync::Mutex::new(None)),
chat_get_fault_after_create: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
false,
)),
}
}
pub fn inject(&self, type_name: &'static str, op: &'static str) {
self.failures.lock().unwrap().insert((type_name, op));
}
pub fn queue_chat_race_phantom(&self, account_id: &str, phantom_id: &str, contact_id: &str) {
*self.chat_race_phantom.lock().unwrap() = Some(ChatRacePhantom {
account_id: account_id.to_owned(),
phantom_id: phantom_id.to_owned(),
contact_id: contact_id.to_owned(),
});
}
pub fn queue_chat_get_fault_after_create(&self) {
self.chat_get_fault_after_create
.store(true, std::sync::atomic::Ordering::SeqCst);
}
fn take_fault(&self, type_name: &'static str, op: &'static str) -> bool {
self.failures.lock().unwrap().remove(&(type_name, op))
}
fn take_chat_race_phantom(&self) -> Option<ChatRacePhantom> {
self.chat_race_phantom.lock().unwrap().take()
}
}
impl Default for InjectableBackend {
fn default() -> Self {
Self::new()
}
}
impl JmapAccounts for InjectableBackend {
type Error = MemoryError;
type CallerCtx = ();
async fn account_exists(&self, caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
self.inner.account_exists(caller, account_id).await
}
}
impl JmapReads for InjectableBackend {
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> {
if self.take_fault(O::TYPE_NAME, "get") {
return Err(MemoryError::new(format!(
"injected get error {INJECTABLE_BACKEND_CANARY}"
)));
}
self.inner
.get_objects::<O>(caller, account_id, ids, properties)
.await
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
) -> Result<State, Self::Error> {
self.inner.get_state::<O>(caller, account_id).await
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: jmap_server::ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
self.inner
.get_changes::<O>(caller, account_id, params)
.await
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
if self.take_fault(O::TYPE_NAME, "query") {
let mut err = jmap_types::JmapError::unsupported_filter();
err.description = Some(INJECTED_QUERY_METHOD_ERROR_DESCRIPTION.into());
return Err(BackendQueryError::Method(err));
}
self.inner
.query_objects::<O>(caller, account_id, params)
.await
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
self.inner
.query_changes::<O>(caller, account_id, params)
.await
}
}
impl ChatStore for InjectableBackend {
async fn create_object<O, F>(
&self,
caller: &(),
account_id: &Id,
create_id: &str,
build: F,
) -> Result<(Id, O), BackendSetError<Self::Error>>
where
O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send,
{
if self.take_fault(O::TYPE_NAME, "create") {
return Err(BackendSetError::Other(MemoryError::new(format!(
"injected create error {INJECTABLE_BACKEND_CANARY}"
))));
}
let result = self
.inner
.create_object(caller, account_id, create_id, build)
.await;
if O::TYPE_NAME == "Chat" && result.is_ok() {
if self
.chat_get_fault_after_create
.swap(false, std::sync::atomic::Ordering::SeqCst)
{
self.inject("Chat", "get");
}
if let Some(phantom) = self.take_chat_race_phantom() {
let phantom_val = serde_json::json!({
"id": &phantom.phantom_id,
"kind": "direct",
"createdAt": "2024-01-01T00:00:00Z",
"unreadCount": 0,
"pinnedMessageIds": [],
"muted": false,
"receiveTypingIndicators": true,
"contactId": &phantom.contact_id,
});
self.inner.insert_object_for_test(
"Chat",
&phantom.account_id,
&phantom.phantom_id,
phantom_val,
);
}
}
result
}
async fn create_message<F>(
&self,
caller: &(),
account_id: &Id,
create_id: &str,
build: F,
) -> Result<(Id, jmap_chat_types::Message), BackendSetError<Self::Error>>
where
F: FnOnce(&Id) -> jmap_chat_types::Message + Send,
{
if self.take_fault("Message", "create_message") {
return Err(BackendSetError::Other(MemoryError::new(format!(
"injected create_message error {INJECTABLE_BACKEND_CANARY}"
))));
}
let (id, message) = self
.create_object::<jmap_chat_types::Message, _>(caller, account_id, create_id, build)
.await?;
let event = jmap_chat_server::OutboundEvent::NewMessage {
chat_id: message.chat_id.clone(),
message_id: message.id.clone(),
sender_msg_id: message.sender_msg_id.clone(),
};
self.on_outbound_event(caller, account_id, &event).await;
Ok((id, message))
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> Result<Option<O>, BackendSetError<Self::Error>> {
if self.take_fault(O::TYPE_NAME, "update") {
return Err(BackendSetError::Other(MemoryError::new(format!(
"injected update error {INJECTABLE_BACKEND_CANARY}"
))));
}
self.inner
.update_object::<O>(caller, account_id, id, patch)
.await
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
id: &Id,
) -> Result<(), BackendSetError<Self::Error>> {
if self.take_fault(O::TYPE_NAME, "destroy") {
return Err(BackendSetError::Other(MemoryError::new(format!(
"injected destroy error {INJECTABLE_BACKEND_CANARY}"
))));
}
self.inner.destroy_object::<O>(caller, account_id, id).await
}
fn supports_type<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> bool {
self.inner.supports_type::<O>(caller, account_id)
}
}
impl ChatSpaces for InjectableBackend {
async fn join_space_with_invite(
&self,
caller: &(),
account_id: &Id,
invite_id: &Id,
joined_at: &UTCDate,
) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
self.inner
.join_space_with_invite(caller, account_id, invite_id, joined_at)
.await
}
async fn generate_invite_code(
&self,
_caller: &(),
account_id: &Id,
) -> Result<String, MemoryError> {
self.inner.generate_invite_code(&(), account_id).await
}
async fn everyone_permissions(
&self,
_caller: &(),
account_id: &Id,
space: &jmap_chat_types::Space,
) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
self.inner
.everyone_permissions(&(), account_id, space)
.await
}
async fn apply_space_patch(
&self,
caller: &(),
account_id: &Id,
space_id: &Id,
ops: Vec<SpacePatchOp>,
) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
self.inner
.apply_space_patch(caller, account_id, space_id, ops)
.await
}
async fn apply_space_metadata_patch(
&self,
caller: &(),
account_id: &Id,
space_id: &Id,
patch: jmap_chat_types::SpaceMetadataPatch,
) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
self.inner
.apply_space_metadata_patch(caller, account_id, space_id, patch)
.await
}
}
impl SpacePolicy for InjectableBackend {}
impl ChatAccessPolicy for InjectableBackend {}
impl ChatRestrictions for InjectableBackend {}
impl ChatModeration for InjectableBackend {}
impl ChatMessageLifecycle for InjectableBackend {
async fn expire_message(
&self,
caller: &(),
account_id: &Id,
message_id: &Id,
) -> Result<(), Self::Error> {
self.inner
.expire_message(caller, account_id, message_id)
.await
}
async fn read_and_burn_message(
&self,
caller: &(),
account_id: &Id,
message_id: &Id,
patch: PatchObject,
) -> Result<(), BackendSetError<Self::Error>> {
if self.take_fault("Message", "read_and_burn") {
return Err(BackendSetError::Other(MemoryError::new(format!(
"injected read_and_burn error {INJECTABLE_BACKEND_CANARY}"
))));
}
self.inner
.read_and_burn_message(caller, account_id, message_id, patch)
.await
}
}
impl ChatEvents for InjectableBackend {
async fn on_outbound_event(
&self,
caller: &(),
account_id: &Id,
event: &jmap_chat_server::OutboundEvent,
) {
self.inner
.on_outbound_event(caller, account_id, event)
.await
}
}
impl ChatSettings for InjectableBackend {
fn limits(&self, caller: &(), account_id: &Id) -> ChatLimits {
self.inner.limits(caller, account_id)
}
}
impl DelegateChatResolvers for InjectableBackend {
type Target = MemoryBackend<()>;
fn chat_resolvers(&self) -> &MemoryBackend<()> {
&self.inner
}
}
pub const ACCOUNT_ID: &str = "a1";
pub const ACCOUNT_ID_B: &str = "a2";
pub fn account_backend() -> MemoryBackend<()> {
let backend = MemoryBackend::<()>::default();
backend.register_account(&Id::from(ACCOUNT_ID));
backend
}
pub const SPACE_ID: &str = "s1";
pub fn seed_space(
backend: &IdentityBackend,
roles: serde_json::Value,
members: serde_json::Value,
) -> Id {
let space_val = serde_json::json!({
"id": SPACE_ID,
"name": "Test Space",
"description": "original",
"createdAt": "2026-01-01T00:00:00Z",
"memberCount": members.as_array().map(Vec::len).unwrap_or(0),
"categories": [],
"uncategorizedChannelIds": [],
"isPublic": false,
"isPubliclyPreviewable": false,
"roles": roles,
"members": members,
});
backend.inner().register_account(&Id::from(ACCOUNT_ID));
backend
.inner()
.insert_object_for_test("Space", ACCOUNT_ID, SPACE_ID, space_val);
Id::from(SPACE_ID)
}
pub fn seed_with_admin(backend: &IdentityBackend, admin_id: &str) -> Id {
seed_space(
backend,
serde_json::json!([{
"id": "r-admin",
"name": "Admin",
"permissions": [
"manage_space",
"manage_roles",
"manage_members",
"manage_channels"
],
"position": 100
}]),
serde_json::json!([{
"id": admin_id,
"roleIds": ["r-admin"],
"joinedAt": "2026-01-01T00:00:00Z"
}]),
)
}
pub fn seed_with_non_admin_caller(backend: &IdentityBackend, caller_id: &str) {
seed_space(
backend,
serde_json::json!([{
"id": "r-admin",
"name": "Admin",
"permissions": [
"manage_space",
"manage_roles",
"manage_members",
"manage_channels"
],
"position": 100
}]),
serde_json::json!([
{ "id": "admin-user", "roleIds": ["r-admin"], "joinedAt": "2026-01-01T00:00:00Z" },
{ "id": caller_id, "roleIds": [], "joinedAt": "2026-01-02T00:00:00Z" }
]),
);
}
pub async fn make_space(backend: &MemoryBackend<()>, name: &str) -> String {
let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_space_set(
backend,
&(),
&std::collections::BTreeMap::new(),
serde_json::json!({
"accountId": ACCOUNT_ID,
"create": { "s0": { "name": name } }
}),
&[],
)
.await
.expect("make_space: handle_space_set");
resp["created"]["s0"]["id"]
.as_str()
.expect("make_space: server-assigned id")
.to_owned()
}
pub async fn make_space_with_props(
backend: &MemoryBackend<()>,
props: serde_json::Value,
) -> String {
let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_space_set(
backend,
&(),
&std::collections::BTreeMap::new(),
serde_json::json!({
"accountId": ACCOUNT_ID,
"create": { "s0": props }
}),
&[],
)
.await
.expect("make_space_with_props: handle_space_set");
resp["created"]["s0"]["id"]
.as_str()
.expect("make_space_with_props: server-assigned id")
.to_owned()
}
pub async fn make_chat_group(backend: &MemoryBackend<()>, name: &str) -> String {
let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_chat_set(
backend,
&(),
&std::collections::BTreeMap::new(),
serde_json::json!({
"accountId": ACCOUNT_ID,
"create": { "c0": { "kind": "group", "name": name } }
}),
&[],
)
.await
.expect("make_chat_group: handle_chat_set");
resp["created"]["c0"]["id"]
.as_str()
.expect("make_chat_group: server-assigned id")
.to_owned()
}
pub fn seed_group_chat(backend: &MemoryBackend<()>, id: &str) {
backend.insert_object_for_test(
"Chat",
ACCOUNT_ID,
id,
serde_json::json!({
"id": id,
"kind": "group",
"name": "G",
"createdAt": "2026-01-01T00:00:00Z",
"unreadCount": 0,
"pinnedMessageIds": [],
"members": [{ "id": ACCOUNT_ID, "role": "admin", "joinedAt": "2026-01-01T00:00:00Z" }],
}),
);
}
pub async fn make_received(backend: &MemoryBackend<()>, id: &str) {
let HandlerOutput { primary: get, .. } = jmap_chat_server::message::handle_message_get(
backend,
&(),
serde_json::json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
&[],
)
.await
.expect("Message/get");
let mut msg = get["list"][0].clone();
assert!(msg.is_object(), "message {id} not found: {get}");
msg["senderId"] = serde_json::json!("bob");
backend.insert_object_for_test("Message", ACCOUNT_ID, id, msg);
}