use jmap_chat_types::{
Attachment, AttachmentCreate, BROADCAST_MENTION_SCOPES, BroadcastMention, Chat, DeliveryState,
Mention, Message, MessageAction, PresenceStatus, ReadPosition, Space,
};
use jmap_chat_types::{Filter, MessageComparator, MessageFilter, MessageFilterCondition};
use jmap_types::{Id, JmapError, PatchObject, UTCDate};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::chat::record_unread_count_changes;
use crate::outbound::{OutboundEvent, ReactionAction};
use crate::{ChatBackend, ChatLimits};
use jmap_server::{BackendSetError, SetError, SetErrorType};
use std::collections::{BTreeMap, HashMap, HashSet};
use subtle::ConstantTimeEq;
use crate::helpers::{
PropType, check_metadata_entry, create_metadata, is_metadata_key, mistyped_create_props,
};
use crate::helpers::{
SetAccumulators, default_sort, enforce_max_objects_in_get, enforce_max_objects_in_set,
extract_account_id, filter_properties, finalize_set_response, iso8601_before, not_found_json,
now_utc_string, optional_arg, reject_unsupported_sort, serialize_value,
};
use crate::helpers::{parents_first, resolve_entry_refs, resolved_create};
use jmap_server::{
HandlerOutput, MetadataProjection, QueryParams, backend_set_error_value, bool_arg, filter_arg,
is_client_updatable, query_anchor_args, reject_server_set, server_fail_from_backend,
server_fail_value_from_backend,
};
pub async fn handle_message_get<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> 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>> = match args.remove("ids") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
),
};
let properties: Option<Vec<String>> = match args.remove("properties") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
),
};
let projection = MetadataProjection::new(
properties.as_deref(),
true,
using,
backend
.metadata_info::<Message>(caller, &account_id)
.as_ref(),
)?;
let ids_slice = ids.as_deref();
let (fetched, mut not_found) = backend
.get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
.await
.map_err(|e| server_fail_from_backend(&e))?;
let mut viewable: HashMap<Id, bool> = HashMap::new();
let mut list = Vec::with_capacity(fetched.len());
for msg in fetched {
let visible = match viewable.get(&msg.chat_id) {
Some(&v) => v,
None => {
let v = backend
.may_view_chat(caller, &account_id, &msg.chat_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
viewable.insert(msg.chat_id.clone(), v);
v
}
};
if visible {
list.push(msg);
} else if ids_slice.is_some() {
not_found.push(msg.id);
}
}
if !backend.retains_edit_history() {
for msg in list.iter_mut() {
msg.edit_history = None;
}
}
let wants_counts = properties.as_ref().is_none_or(|p| {
p.iter()
.any(|k| k == "replyCount" || k == "unreadReplyCount")
});
if wants_counts && backend.limits(caller, &account_id).supports_threads {
fill_reply_counts(backend, caller, &account_id, &mut list).await?;
}
let state = backend
.get_state::<Message>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let prop_set: Option<HashSet<&str>> = properties.as_ref().map(|props| {
let mut set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
set.insert("id");
set
});
let list_json: Vec<Value> = list
.iter()
.map(|obj| {
let val = serialize_value(obj)?;
let mut out = match &prop_set {
Some(set) => filter_properties(&val, set),
None => val.clone(),
};
projection.apply(&val, &mut out);
Ok(out)
})
.collect::<Result<Vec<_>, JmapError>>()?;
Ok(HandlerOutput::new(json!({
"accountId": account_id.as_ref(),
"state": state.as_ref(),
"list": list_json,
"notFound": not_found_json(¬_found),
})))
}
async fn fill_reply_counts<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
list: &mut [Message],
) -> Result<(), JmapError> {
if list.is_empty() {
return Ok(());
}
let (all, _) = backend
.get_objects::<Message>(caller, account_id, None, None)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let (positions, _) = backend
.get_objects::<ReadPosition>(caller, account_id, None, None)
.await
.map_err(|e| server_fail_from_backend(&e))?;
for msg in list.iter_mut() {
let replies = || {
all.iter()
.filter(|r| r.chat_id == msg.chat_id && r.reply_to.as_ref() == Some(&msg.id))
};
let reply_count = replies().count() as u64;
msg.unread_reply_count = if msg.thread_root_id.is_none() {
let last_read = positions
.iter()
.find(|p| p.chat_id == msg.chat_id)
.and_then(|p| p.last_read_message_id.as_ref());
let unread = replies()
.filter(|r| r.sender_id != *account_id)
.filter(|r| last_read.is_none_or(|l| r.id.as_ref() > l.as_ref()))
.count();
Some(unread as u64)
} else {
None
};
msg.reply_count = Some(reply_count);
}
Ok(())
}
pub async fn handle_message_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::handle_changes::<Message, B>(backend, caller, args, using).await
}
pub async fn handle_message_query<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::reject_metadata_filter_arg(
&args,
jmap_chat_types::MessageFilterCondition::has_metadata_condition,
using,
)?;
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 = bool_arg(&args, "calculateTotal", false);
let limit: Option<u64> = match args.remove("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 {}",
jmap_server::json_type_name(&v)
)));
}
},
};
let position: i64 = match args.remove("position") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"position: expected an integer, got {}",
jmap_server::json_type_name(&v)
))
})?,
};
let (anchor, anchor_offset) = query_anchor_args(&args)?;
reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
let filter: Option<MessageFilter> = filter_arg(&mut args)?;
let supports_threads = backend.limits(caller, &account_id).supports_threads;
let top = check_message_filter(filter.as_ref(), supports_threads)?;
let in_one_chat = top.chat_id.is_some();
default_sort(
&mut args,
json!([{ "property": "receivedAt", "isAscending": in_one_chat }]),
);
let sort: Option<Vec<MessageComparator>> = optional_arg(&mut args, "sort", || {
JmapError::invalid_arguments("sort must be an array")
})?;
let hidden = match top.chat_id.as_ref() {
Some(chat_id) => !backend
.may_view_chat(caller, &account_id, chat_id)
.await
.map_err(|e| server_fail_from_backend(&e))?,
None => false,
};
let result = backend
.query_objects::<Message>(
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 (ids, position, total) = if hidden {
(Vec::new(), 0, Some(0))
} else {
(result.ids, result.position, result.total)
};
let mut resp = json!({
"accountId": account_id.as_ref(),
"queryState": result.query_state.as_ref(),
"canCalculateChanges": result.can_calculate_changes,
"position": position,
"ids": ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
});
if calculate_total && let Some(t) = total {
resp["total"] = json!(t);
}
Ok(HandlerOutput::new(resp))
}
fn check_message_filter(
filter: Option<&MessageFilter>,
supports_threads: bool,
) -> Result<&MessageFilterCondition, JmapError> {
match filter {
Some(Filter::Condition(c))
if (c.chat_id.is_some() || c.has_mention == Some(true))
&& c.text.is_none()
&& (c.thread_root_id.is_none() || supports_threads) =>
{
Ok(c)
}
_ => Err(JmapError::unsupported_filter()),
}
}
pub async fn handle_message_query_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
mut args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::reject_metadata_filter_arg(
&args,
jmap_chat_types::MessageFilterCondition::has_metadata_condition,
using,
)?;
let chat_id = args
.get("filter")
.and_then(|f| f.get("chatId"))
.and_then(Value::as_str)
.map(Id::from);
if let Value::Object(map) = &mut args {
default_sort(
map,
json!([{ "property": "receivedAt", "isAscending": chat_id.is_some() }]),
);
}
reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
let account_id = args.get("accountId").and_then(Value::as_str).map(Id::from);
if let Some(account_id) = &account_id {
if !backend
.account_exists(caller, account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
let mut probe = serde_json::Map::new();
if let Some(f) = args.get("filter") {
probe.insert("filter".into(), f.clone());
}
let filter: Option<MessageFilter> = filter_arg(&mut probe)?;
let supports_threads = backend.limits(caller, account_id).supports_threads;
check_message_filter(filter.as_ref(), supports_threads)?;
}
if let (Some(account_id), Some(chat_id)) = (account_id, chat_id)
&& !backend
.may_view_chat(caller, &account_id, &chat_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::cannot_calculate_changes());
}
jmap_server::handle_query_changes::<Message, B>(backend, caller, args).await
}
fn validate_broadcast_mentions(broadcast_mentions: &[serde_json::Value]) -> Option<Value> {
let invalid_properties = |desc: String| {
json!({
"type": "invalidProperties",
"properties": ["broadcastMentions"],
"description": desc,
})
};
for (i, bm) in broadcast_mentions.iter().enumerate() {
let scope = match bm.get("scope").and_then(|v| v.as_str()) {
Some(s) => s,
None => {
return Some(invalid_properties(format!(
"broadcastMentions[{i}]: missing or non-string scope"
)));
}
};
if !BROADCAST_MENTION_SCOPES.contains(&scope) {
return Some(invalid_properties(format!(
"broadcastMentions[{i}]: unrecognized scope \"{scope}\""
)));
}
}
None
}
pub const ENCRYPTED_BODY_TYPES: &[&str] = &["application/mls-ciphertext"];
pub const SUPPORTED_BODY_TYPES: &[&str] = &[
"text/plain",
"text/markdown",
"application/jmap-chat-rich",
"application/mls-ciphertext",
];
const CIPHERTEXT_ONLY_FIELDS: [&str; 8] = [
"mentions",
"broadcastMentions",
"attachments",
"actions",
"replyTo",
"threadRootId",
"topicId",
"subject",
];
fn body_type_field_conflicts(
obj: &Value,
body_type: &str,
encrypted: &[&str],
) -> Vec<&'static str> {
if !encrypted.contains(&body_type) {
return Vec::new();
}
let non_empty = |key: &str| {
obj.get(key)
.is_some_and(|v| !(v.is_null() || v == "" || v.as_array().is_some_and(Vec::is_empty)))
};
CIPHERTEXT_ONLY_FIELDS
.into_iter()
.filter(|&k| non_empty(k))
.collect()
}
fn edit_limit_error(msg: &Message, patch: &Value, limits: &ChatLimits) -> Option<Value> {
if let Some(body) = patch.get("body").and_then(Value::as_str)
&& u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes)
{
return Some(json!({
"type": "tooLarge",
"description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
}));
}
let mut merged = serde_json::to_value(msg).ok()?;
if let (Some(dst), Some(src)) = (merged.as_object_mut(), patch.as_object()) {
dst.extend(src.iter().map(|(k, v)| (k.clone(), v.clone())));
}
let body_type = merged.get("bodyType").and_then(Value::as_str)?.to_owned();
let conflicts = body_type_field_conflicts(&merged, &body_type, limits.encrypted_body_types);
(!conflicts.is_empty()).then(|| {
json!({
"type": "invalidProperties",
"properties": conflicts,
"description": format!("must be empty or absent when bodyType is {body_type}"),
})
})
}
const MAX_SUBJECT_BYTES: usize = 1024;
const MAX_UNSIGNED_INT: u64 = (1 << 53) - 1;
fn apply_create_optionals(
obj: &Value,
) -> Result<impl FnOnce(&mut Message) + Send + use<>, &'static str> {
let get = |key: &str| obj.get(key).filter(|v| !v.is_null());
let mentions = get("mentions")
.map(|v| Vec::<Mention>::deserialize(v).map_err(|_| "mentions"))
.transpose()?;
let broadcast_mentions = get("broadcastMentions")
.map(|v| Vec::<BroadcastMention>::deserialize(v).map_err(|_| "broadcastMentions"))
.transpose()?;
let actions = get("actions")
.map(|v| Vec::<MessageAction>::deserialize(v).map_err(|_| "actions"))
.transpose()?;
let topic_id = match get("topicId") {
None => None,
Some(v) => match v.as_str() {
Some(s) if !s.is_empty() && s.len() <= 255 => Some(s.to_owned()),
_ => return Err("topicId"),
},
};
let subject = match get("subject") {
None => None,
Some(v) => match v.as_str() {
Some(s) if topic_id.is_some() && s.len() <= MAX_SUBJECT_BYTES => Some(s.to_owned()),
_ => return Err("subject"),
},
};
let expires_after_read_seconds = match get("expiresAfterReadSeconds") {
None => None,
Some(v) => match v.as_u64() {
Some(n) if n <= MAX_UNSIGNED_INT => Some(n),
_ => return Err("expiresAfterReadSeconds"),
},
};
Ok(move |msg: &mut Message| {
if let Some(v) = mentions {
msg.mentions = v;
}
if let Some(v) = broadcast_mentions {
msg.broadcast_mentions = v;
}
if let Some(v) = actions {
msg.actions = v;
}
if topic_id.is_some() {
msg.topic_id = topic_id;
}
if subject.is_some() {
msg.subject = subject;
}
if expires_after_read_seconds.is_some() {
msg.expires_after_read_seconds = expires_after_read_seconds;
}
})
}
async fn create_attachments<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
limits: &ChatLimits,
chat: &Chat,
v: &Value,
) -> Result<Vec<Attachment>, Value> {
let invalid = || json!({ "type": "invalidProperties", "properties": ["attachments"] });
let entries = v.as_array().ok_or_else(invalid)?;
if u64::try_from(entries.len()).map_or(true, |n| n > limits.max_attachments_per_message) {
return Err(json!({
"type": "tooLarge",
"description": format!(
"attachments exceed maxAttachmentsPerMessage ({})",
limits.max_attachments_per_message
),
}));
}
let mut attachments = Vec::with_capacity(entries.len());
for entry in entries {
let requested = AttachmentCreate::deserialize(entry).map_err(|_| invalid())?;
let filled = if requested.filenode_id.is_some() {
match backend
.filenode_attachment(caller, account_id, chat, &requested)
.await
{
Ok(Ok(filled)) => filled,
Ok(Err(set_err)) => return Err(serde_json::Value::from(&set_err)),
Err(e) => return Err(server_fail_value_from_backend(&e)),
}
} else {
None
};
let attachment = match filled {
Some(a) => a,
None => Attachment::deserialize(entry).map_err(|_| invalid())?,
};
if !valid_attachment(&attachment) {
return Err(invalid());
}
attachments.push(attachment);
}
Ok(attachments)
}
fn valid_attachment(a: &Attachment) -> bool {
!a.filename.contains(['/', '\\', '\0']) && valid_media_type(&a.content_type)
}
async fn check_attachments<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
limits: &ChatLimits,
attachments: &[Attachment],
) -> Option<Value> {
if attachments
.iter()
.any(|a| a.size > limits.max_attachment_bytes)
{
return Some(json!({
"type": "tooLarge",
"description": format!(
"an attachment exceeds maxAttachmentBytes ({})",
limits.max_attachment_bytes
),
}));
}
for a in attachments {
match backend
.attachment_blob(caller, account_id, &a.blob_id)
.await
{
Ok(Ok(None)) => {}
Ok(Ok(Some(blob))) => {
if blob.size != a.size || !bool::from(a.sha256.to_bytes().ct_eq(&blob.sha256)) {
return Some(json!({
"type": "invalidProperties",
"properties": ["attachments"],
"description": format!(
"attachment {} does not match the blob's size or sha256",
a.blob_id
),
}));
}
}
Ok(Err(set_err)) => return Some(serde_json::Value::from(&set_err)),
Err(e) => return Some(server_fail_value_from_backend(&e)),
}
}
None
}
fn valid_media_type(s: &str) -> bool {
let is_token = |t: &str| {
!t.is_empty()
&& t.bytes()
.all(|b| b.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?=".contains(&b))
};
let essence = s.split(';').next().unwrap_or_default().trim();
essence
.split_once('/')
.is_some_and(|(t, sub)| is_token(t) && is_token(sub))
}
pub(crate) async fn ensure_read_positions<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
mut chat_ids: Vec<Id>,
) {
if chat_ids.is_empty() {
return;
}
let Ok((existing, _)) = backend
.get_objects::<ReadPosition>(caller, account_id, None, None)
.await
else {
return;
};
chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
chat_ids.dedup();
chat_ids.retain(|c| !existing.iter().any(|p| p.chat_id == *c));
for chat_id in chat_ids {
let _ = backend
.create_object(caller, account_id, chat_id.as_ref(), |id: &Id| {
ReadPosition::new(id.clone(), chat_id.clone())
})
.await;
}
}
pub async fn find_message_by_sender_msg_id<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
chat_id: &Id,
sender_msg_id: &Id,
) -> Result<Option<Message>, B::Error> {
let (messages, _) = backend
.get_objects::<Message>(caller, account_id, None, None)
.await?;
Ok(messages
.into_iter()
.find(|m| m.chat_id == *chat_id && m.sender_msg_id == *sender_msg_id))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StoreOutcome {
Stored(Id),
Duplicate(Id),
}
pub async fn store_server_message<B, F>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
chat_id: &Id,
sender_msg_id: &Id,
build: F,
) -> Result<StoreOutcome, BackendSetError<B::Error>>
where
B: ChatBackend,
F: FnOnce(&Id) -> Message + Send,
{
if let Some(existing) =
find_message_by_sender_msg_id(backend, caller, account_id, chat_id, sender_msg_id)
.await
.map_err(BackendSetError::Other)?
{
return Ok(StoreOutcome::Duplicate(existing.id));
}
let (chat, smid) = (chat_id.clone(), sender_msg_id.clone());
let (id, stored) = backend
.create_object(
caller,
account_id,
sender_msg_id.as_ref(),
move |id: &Id| {
let mut m = build(id);
m.chat_id = chat;
m.sender_msg_id = smid;
m
},
)
.await?;
ensure_read_positions(backend, caller, account_id, vec![stored.chat_id.clone()]).await;
record_unread_count_changes(backend, caller, account_id, vec![stored.chat_id]).await;
Ok(StoreOutcome::Stored(id))
}
async fn shares_receipts<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
chat_id: &Id,
) -> bool {
let chat_override = match backend
.get_objects::<Chat>(
caller,
account_id,
Some(std::slice::from_ref(chat_id)),
None,
)
.await
{
Ok((found, _not_found)) => found.first().and_then(|c| c.receipt_sharing),
Err(_) => return false,
};
if let Some(shares) = chat_override {
return shares;
}
match backend
.get_objects::<PresenceStatus>(caller, account_id, None, None)
.await
{
Ok((found, _not_found)) => found.first().is_none_or(|p| p.receipt_sharing),
Err(_) => false,
}
}
const MESSAGE_ID_PROPERTIES: &[&str] = &["chatId", "replyTo", "threadRootId"];
const MENTION_ID: (&str, &str, &str) = ("mentions", "id", "mentions");
const ATTACHMENT_FILENODE_ID: (&str, &str, &str) = ("attachments", "filenodeId", "filenodeId");
pub async fn handle_message_set<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
created_ids: &BTreeMap<Id, Id>,
args: Value,
using: &[String],
) -> 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_set(&args, backend.max_objects_in_set(caller, &account_id))?;
let old_state = backend
.get_state::<Message>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
&& if_in_state != old_state.as_ref()
{
return Err(JmapError::state_mismatch());
}
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut updated = serde_json::Map::new();
let mut not_updated = serde_json::Map::new();
let mut destroyed_list: Vec<Value> = Vec::new();
let mut not_destroyed = serde_json::Map::new();
let mut mutated = false;
let limits = backend.limits(caller, &account_id);
if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
let mut delivered_chat_ids: Vec<Id> = Vec::new();
let mut created_ids = created_ids.clone();
for (create_id, obj_val) in parents_first(create_map, &["replyTo", "threadRootId"]) {
let resolved = match resolved_create(obj_val, MESSAGE_ID_PROPERTIES, &created_ids)
.and_then(|mut v| {
resolve_entry_refs(&mut v, &[MENTION_ID, ATTACHMENT_FILENODE_ID], &created_ids)
.map(|()| v)
}) {
Ok(v) => v,
Err(err) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
continue;
}
};
let obj_val = &resolved;
if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Message>) {
not_created.insert(create_id.clone(), serde_json::Value::from(&err));
continue;
}
if let Some(Err(err)) = obj_val
.as_object()
.map(|o| check_metadata_entry(o, true, using))
{
not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
continue;
}
let (metadata, private_metadata) = match create_metadata(obj_val) {
Ok(maps) => maps,
Err(err) => {
not_created.insert(create_id.clone(), err);
continue;
}
};
if let Some(err) = mistyped_create_props(
obj_val,
&[
("broadcastMentions", PropType::Array),
("replyTo", PropType::Str),
("threadRootId", PropType::Str),
("senderExpiresAt", PropType::Str),
("burnOnRead", PropType::Bool),
],
) {
not_created.insert(create_id.clone(), err);
continue;
}
let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["chatId"] }),
);
continue;
};
let chat_id = match jmap_server::parse_wire_id(chat_id_str, "chatId") {
Ok(id) => id,
Err(err) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
continue;
}
};
let Some(body) = obj_val
.get("body")
.and_then(|v| v.as_str())
.map(str::to_owned)
else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["body"] }),
);
continue;
};
if u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes) {
not_created.insert(
create_id.clone(),
json!({
"type": "tooLarge",
"description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
}),
);
continue;
}
let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
);
continue;
};
let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
);
continue;
};
let Some(body_type) = obj_val
.get("bodyType")
.filter(|v| !v.is_null())
.map_or(Some("text/plain"), Value::as_str)
.filter(|s| limits.supported_body_types.contains(s))
else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
);
continue;
};
if limits.server_reserved_body_types.contains(&body_type) {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["bodyType"],
"description": format!("bodyType {body_type} is reserved for server-created Messages")
}),
);
continue;
}
let body_type = body_type.to_owned();
let conflicts =
body_type_field_conflicts(obj_val, &body_type, limits.encrypted_body_types);
if !conflicts.is_empty() {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": conflicts,
"description": format!("must be empty or absent when bodyType is {body_type}"),
}),
);
continue;
}
let broadcast_mentions_val: Vec<Value> = obj_val
.get("broadcastMentions")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if let Some(err) = validate_broadcast_mentions(&broadcast_mentions_val) {
not_created.insert(create_id.clone(), err);
continue;
}
let chat = match backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(&chat_id)),
None,
)
.await
{
Ok((found, _)) => match found.into_iter().next() {
Some(chat) => chat,
None => {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["chatId"],
"description": format!("no Chat with id {chat_id}"),
}),
);
continue;
}
},
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
};
match backend.may_create_message(caller, &account_id, &chat).await {
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
continue;
}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
if chat.closed_at.is_some() {
not_created.insert(
create_id.clone(),
json!({ "type": "forbidden", "description": "the group is closed" }),
);
continue;
}
if let Some(sid) = &chat.space_id {
match backend
.get_objects::<Space>(
caller,
&account_id,
Some(std::slice::from_ref(sid)),
None,
)
.await
{
Ok((spaces, _)) if spaces.first().is_some_and(|s| s.closed_at.is_some()) => {
not_created.insert(
create_id.clone(),
json!({ "type": "forbidden", "description": "the Space is closed" }),
);
continue;
}
Ok(_) => {}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
}
match backend
.may_send_message(caller, &account_id, &chat_id)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
continue;
}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
if let Some(sid) = chat
.space_id
.as_ref()
.filter(|_| !broadcast_mentions_val.is_empty())
{
match backend
.may_broadcast_mention(caller, &account_id, sid, &chat_id)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
continue;
}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
}
let reply_to: Option<Id> = match obj_val.get("replyTo").and_then(|v| v.as_str()) {
Some(s) => match jmap_server::parse_wire_id(s, "replyTo") {
Ok(id) => Some(id),
Err(err) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
continue;
}
},
None => None,
};
let supplied_root: Option<Id> =
match obj_val.get("threadRootId").and_then(|v| v.as_str()) {
Some(s) => match jmap_server::parse_wire_id(s, "threadRootId") {
Ok(id) => Some(id),
Err(err) => {
not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
continue;
}
},
None => None,
};
let expected_root: Option<Id> = match reply_to.as_ref() {
None => None,
Some(parent_id) => {
let parent = match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(parent_id)),
None,
)
.await
{
Ok((found, _)) => found.into_iter().find(|m| m.chat_id == chat_id),
Err(e) => {
not_created
.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
};
let Some(parent) = parent else {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["replyTo"],
"description": "replyTo is not a Message in this Chat",
}),
);
continue;
};
Some(parent.thread_root_id.unwrap_or(parent.id))
}
};
if supplied_root.is_some() && supplied_root != expected_root {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["threadRootId"],
"description": "threadRootId does not match the thread of replyTo",
}),
);
continue;
}
let thread_root_id = expected_root;
let sender_expires_at: Option<UTCDate> =
if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
let Ok(d) = UTCDate::new_validated(s) else {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["senderExpiresAt"],
}),
);
continue;
};
Some(d)
} else {
None
};
let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
if let Some(ref expires_at) = sender_expires_at {
let now = now_utc_string();
if !iso8601_before(&now, expires_at) {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
);
continue;
}
}
let now_str = now_utc_string();
let received_at: UTCDate = UTCDate::from(now_str.as_ref());
let mut attachments = Vec::new();
if let Some(v) = obj_val.get("attachments").filter(|v| !v.is_null()) {
match create_attachments(backend, caller, &account_id, &limits, &chat, v).await {
Ok(a) => attachments = a,
Err(err) => {
not_created.insert(create_id.clone(), err);
continue;
}
}
}
let apply_optionals = match apply_create_optionals(obj_val) {
Ok(f) => f,
Err(property) => {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": [property] }),
);
continue;
}
};
if let Some(err) =
check_attachments(backend, caller, &account_id, &limits, &attachments).await
{
not_created.insert(create_id.clone(), err);
continue;
}
if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
let set_err = SetError::new(SetErrorType::RateLimit)
.with_description("Slow mode is active for this chat")
.with_extra("serverRetryAfter", json!(retry_after_str));
not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
continue;
}
let build = |id: &Id| {
let mut msg = Message::new(
id.clone(),
id.clone(),
account_id.clone(),
chat_id,
body,
body_type,
sent_at,
received_at,
DeliveryState::Pending,
);
msg.reply_to = reply_to;
msg.thread_root_id = thread_root_id;
msg.sender_expires_at = sender_expires_at;
msg.burn_on_read = burn_on_read;
msg.attachments = attachments;
msg.metadata = metadata;
msg.private_metadata = private_metadata;
apply_optionals(&mut msg);
msg
};
match backend
.create_object::<Message, _>(caller, &account_id, create_id, build)
.await
{
Ok((server_id, created_obj)) => {
mutated = true;
created_ids.insert(Id::from(create_id.as_str()), server_id);
delivered_chat_ids.push(created_obj.chat_id.clone());
let event = OutboundEvent::NewMessage {
chat_id: created_obj.chat_id.clone(),
message_id: created_obj.id.clone(),
sender_msg_id: created_obj.sender_msg_id.clone(),
};
backend.on_outbound_event(caller, &account_id, &event).await;
created.insert(
create_id.clone(),
jmap_server::serialize_value(&created_obj)?,
);
}
Err(e) => {
not_created.insert(create_id.clone(), backend_set_error_value(e));
}
}
}
ensure_read_positions(backend, caller, &account_id, delivered_chat_ids.clone()).await;
record_unread_count_changes(backend, caller, &account_id, delivered_chat_ids).await;
}
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, mut patch_val) in update_map {
let id = match jmap_server::parse_wire_id(&id_str, "id") {
Ok(id) => id,
Err(err) => {
not_updated.insert(id_str, serde_json::Value::from(&*err));
continue;
}
};
if let Err(err) = resolve_entry_refs(&mut patch_val, &[MENTION_ID], created_ids) {
not_updated.insert(id_str, serde_json::Value::from(&*err));
continue;
}
if patch_val.get("reactions").is_some()
&& patch_val
.as_object()
.is_some_and(|obj| obj.keys().any(|k| k.starts_with("reactions/")))
{
not_updated.insert(
id_str,
json!({
"type": "invalidPatch",
"description":
"patch must not combine top-level `reactions` with `reactions/{id}` entries",
}),
);
continue;
}
let bad_props: Vec<&str> = patch_val
.as_object()
.map(|obj| {
obj.keys()
.map(String::as_str)
.filter(|&k| {
!(k.starts_with("reactions/")
|| is_metadata_key(k)
|| (k != "reactions" && is_client_updatable::<Message>(k)))
})
.collect()
})
.unwrap_or_default();
if !bad_props.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": bad_props }),
);
continue;
}
if let Some(Err(err)) = patch_val
.as_object()
.map(|o| check_metadata_entry(o, false, using))
{
not_updated.insert(id_str, serde_json::Value::from(&*err));
continue;
}
let sets = |field: &str| patch_val.get(field).is_some_and(|v| !v.is_null());
if sets("readDisposition") && !sets("readAt") {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": ["readDisposition"] }),
);
continue;
}
if patch_val.get("bodyType").is_some_and(|v| {
!v.as_str()
.is_some_and(|s| limits.supported_body_types.contains(&s))
}) {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
);
continue;
}
let stored = match backend
.get_objects::<Message>(caller, &account_id, Some(std::slice::from_ref(&id)), None)
.await
{
Ok((found, _)) => found.into_iter().next(),
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
};
let stored_chat = match &stored {
Some(msg) => match backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(&msg.chat_id)),
None,
)
.await
{
Ok((found, _)) => found.into_iter().next(),
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
},
None => None,
};
if let (Some(msg), Some(chat)) = (&stored, &stored_chat) {
let patch_keys: Vec<&str> = patch_val
.as_object()
.map(|obj| obj.keys().map(String::as_str).collect())
.unwrap_or_default();
match backend
.may_update_message(caller, &account_id, chat, msg, &patch_keys)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_updated.insert(id_str, serde_json::Value::from(&set_err));
continue;
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
let deletes_for_all =
patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
let edits = ["body", "bodyType", "mentions", "broadcastMentions"]
.iter()
.any(|&field| patch_val.get(field).is_some());
let mut outbound: Option<OutboundEvent> = None;
if deletes_for_all || edits {
let description = stored.as_ref().and_then(|m| {
if deletes_for_all && m.sender_id != account_id {
Some("deletedForAll is only permitted on messages whose senderId is the accountId")
} else if edits && (m.sender_id != account_id || m.deleted_at.is_some()) {
Some("edits are only permitted on messages whose senderId is the accountId and deletedAt is absent")
} else {
None
}
});
if let Some(description) = description {
not_updated.insert(
id_str,
json!({ "type": "forbidden", "description": description }),
);
continue;
}
if let Some(err) = stored
.as_ref()
.and_then(|m| edit_limit_error(m, &patch_val, &limits))
{
not_updated.insert(id_str, err);
continue;
}
outbound = stored.as_ref().map(|m| {
let (chat_id, message_id, sender_msg_id) =
(m.chat_id.clone(), m.id.clone(), m.sender_msg_id.clone());
if deletes_for_all {
OutboundEvent::Retract {
chat_id,
message_id,
sender_msg_id,
}
} else {
OutboundEvent::Edit {
chat_id,
message_id,
sender_msg_id,
}
}
});
}
let mut augmented = patch_val;
if augmented.get("body").is_some()
&& let Some(obj) = augmented.as_object_mut()
{
obj.insert("editedAt".to_owned(), json!(now_utc_string()));
}
let deletes =
deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
if deletes && let Some(obj) = augmented.as_object_mut() {
if deletes_for_all {
obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
}
obj.insert("body".to_owned(), json!(""));
obj.insert("attachments".to_owned(), json!([]));
obj.insert("editHistory".to_owned(), Value::Null);
}
if let Some(obj) = augmented.as_object_mut() {
match obj.get("readAt") {
Some(Value::Null) => {
obj.insert("readDisposition".to_owned(), Value::Null);
}
Some(_) if !obj.contains_key("readDisposition") => {
obj.insert("readDisposition".to_owned(), json!("displayed"));
}
_ => {}
}
}
let reaction_pointer_keys: Vec<String> = augmented
.as_object()
.map(|obj| {
obj.keys()
.filter(|k| k.starts_with("reactions/"))
.cloned()
.collect()
})
.unwrap_or_default();
let mut reaction_events: Vec<OutboundEvent> = Vec::new();
if !reaction_pointer_keys.is_empty() {
let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
.iter()
.map(|raw_key| {
let suffix = &raw_key["reactions/".len()..];
if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
return Err(format!(
"reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
));
}
let val = augmented.get(raw_key).unwrap_or(&Value::Null);
if !val.is_null() {
let ok = val.as_object().is_some_and(|m| {
m.get("emoji")
.and_then(|v| v.as_str())
.is_some_and(|s| !s.is_empty())
});
if !ok {
return Err(format!(
"reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
));
}
}
Ok((raw_key.clone(), suffix.to_owned()))
})
.collect();
let decoded = match decoded {
Ok(d) => d,
Err(desc) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": desc }),
);
continue;
}
};
let mut forbidden: Vec<String> = Vec::new();
if let Some(msg) = &stored {
for (raw_key, suffix) in &decoded {
let existing = msg.reactions.get(suffix);
if existing.is_some_and(|r| r.sender_id != account_id) {
forbidden.push(suffix.clone());
}
let action = match augmented.get(raw_key) {
Some(Value::Object(_)) => Some(ReactionAction::Add),
_ => existing.map(|r| ReactionAction::Remove { removed: r.clone() }),
};
if let Some(action) = action {
reaction_events.push(OutboundEvent::ReactionUpdate {
chat_id: msg.chat_id.clone(),
message_id: msg.id.clone(),
sender_msg_id: msg.sender_msg_id.clone(),
sender_reaction_id: suffix.clone(),
action,
});
}
}
}
if !forbidden.is_empty() {
not_updated.insert(
id_str,
json!({
"type": "forbidden",
"description": format!(
"cannot modify reactions authored by another sender: {}",
forbidden.join(", "),
),
}),
);
continue;
}
let now_str = now_utc_string();
if let Some(obj) = augmented.as_object_mut() {
for (raw_key, _) in &decoded {
if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
map.insert("senderId".to_owned(), json!(account_id));
map.entry("sentAt").or_insert_with(|| json!(now_str));
}
}
}
}
let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
let pre_patch_read: Option<Message> = if patch_sets_read_at {
stored.clone()
} else {
None
};
let pre_patch_burn_on_read = pre_patch_read
.as_ref()
.is_some_and(|m| m.burn_on_read == Some(true) && m.sender_id != account_id);
if edits {
let current_has_bm = stored
.as_ref()
.is_some_and(|msg| !msg.broadcast_mentions.is_empty());
let has_bm = match augmented.get("broadcastMentions") {
Some(bm) => {
let bm_arr: Vec<Value> = bm.as_array().cloned().unwrap_or_default();
if let Some(err) = validate_broadcast_mentions(&bm_arr) {
not_updated.insert(id_str, err);
continue;
}
!bm_arr.is_empty()
}
None => current_has_bm,
};
let channel = stored_chat
.as_ref()
.and_then(|c| Some((c.space_id.as_ref()?, &c.id)));
if let (true, Some((sid, chat_id))) = (has_bm, channel) {
match backend
.may_broadcast_mention(caller, &account_id, sid, chat_id)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_updated.insert(id_str, serde_json::Value::from(&set_err));
continue;
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
}
let receipt = pre_patch_read
.filter(|m| m.sender_id != account_id)
.and_then(|m| {
let read_at =
serde_json::from_value::<UTCDate>(augmented.get("readAt")?.clone()).ok()?;
let read_disposition = augmented
.get("readDisposition")
.and_then(|v| serde_json::from_value(v.clone()).ok());
Some(OutboundEvent::Receipt {
chat_id: m.chat_id,
message_id: m.id,
sender_msg_id: m.sender_msg_id,
read_at,
read_disposition,
})
});
let patch = match serde_json::from_value::<PatchObject>(augmented) {
Ok(p) => p,
Err(e) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": e.to_string() }),
);
continue;
}
};
let burns = patch_sets_read_at && pre_patch_burn_on_read;
let update_outcome = if burns {
backend
.read_and_burn_message(caller, &account_id, &id, patch)
.await
.map(|()| None)
} else {
backend
.update_object::<Message>(caller, &account_id, &id, patch)
.await
};
let maybe_updated_obj = match update_outcome {
Ok(maybe_obj) => maybe_obj,
Err(e) => {
not_updated.insert(id_str, backend_set_error_value(e));
continue;
}
};
mutated = true;
if let Some(event @ OutboundEvent::Retract { .. }) = &outbound {
backend.on_outbound_event(caller, &account_id, event).await;
}
if let Some(event @ OutboundEvent::Edit { .. }) = &outbound
&& !deletes
&& !burns
{
backend.on_outbound_event(caller, &account_id, event).await;
}
if !deletes && !burns {
for event in &reaction_events {
backend.on_outbound_event(caller, &account_id, event).await;
}
}
if let Some(event @ OutboundEvent::Receipt { chat_id, .. }) = &receipt
&& shares_receipts(backend, caller, &account_id, chat_id).await
{
backend.on_outbound_event(caller, &account_id, event).await;
}
match maybe_updated_obj {
Some(obj) => {
updated.insert(id_str, jmap_server::serialize_value(&obj)?);
}
None => {
updated.insert(id_str, Value::Null);
}
}
}
}
if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
let id_strs: Vec<&str> = destroy_arr
.iter()
.map(|v| {
v.as_str().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {}",
jmap_server::json_type_name(v)
))
})
})
.collect::<Result<_, _>>()?;
let destroy_ids: Vec<Id> = destroy_arr
.iter()
.filter_map(Value::as_str)
.filter_map(|s| Id::new_validated(s).ok())
.collect();
let chat_of: HashMap<Id, Id> = backend
.get_objects::<Message>(caller, &account_id, Some(&destroy_ids), None)
.await
.map(|(found, _)| found.into_iter().map(|m| (m.id, m.chat_id)).collect())
.unwrap_or_default();
let mut destroyed_chat_ids: Vec<Id> = Vec::new();
for id_str in id_strs {
let id = match jmap_server::parse_wire_id(id_str, "id") {
Ok(id) => id,
Err(err) => {
not_destroyed.insert(id_str.to_owned(), serde_json::Value::from(&*err));
continue;
}
};
match backend
.destroy_object::<Message>(caller, &account_id, &id)
.await
{
Ok(()) => {
mutated = true;
destroyed_chat_ids.extend(chat_of.get(&id).cloned());
destroyed_list.push(Value::String(id_str.to_owned()));
}
Err(e) => {
not_destroyed.insert(id_str.to_owned(), backend_set_error_value(e));
}
}
}
record_unread_count_changes(backend, caller, &account_id, destroyed_chat_ids).await;
}
finalize_set_response::<B, Message>(
backend,
caller,
&account_id,
old_state,
mutated,
SetAccumulators {
created,
updated,
destroyed: destroyed_list,
not_created,
not_updated,
not_destroyed,
},
)
.await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryBackend;
use serde_json::json;
const ACCOUNT_ID: &str = "a1";
#[tokio::test]
async fn broadcast_mention_validation_rejects_unknown_scope() {
let backend = MemoryBackend::new();
backend.register_account(&Id::from(ACCOUNT_ID));
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "Hello @channel",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "channel", "offset": 6, "length": 8 }
]
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(resp["notCreated"]["m0"].is_object());
assert_eq!(resp["notCreated"]["m0"]["type"], "invalidProperties");
assert_eq!(
resp["notCreated"]["m0"]["properties"],
json!(["broadcastMentions"])
);
let desc = resp["notCreated"]["m0"]["description"]
.as_str()
.expect("description");
assert!(
desc.contains("unrecognized scope"),
"expected 'unrecognized scope' in description, got: {desc}"
);
}
#[tokio::test]
async fn broadcast_mention_validation_accepts_valid() {
let backend = MemoryBackend::new();
let chat_id = make_group_chat(&backend).await;
let body = "Hello @everyone!";
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_validation_accepts_empty() {
let backend = MemoryBackend::new();
let chat_id = make_group_chat(&backend).await;
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": "Hello, world!",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": []
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
async fn make_group_chat(backend: &MemoryBackend) -> String {
backend.register_account(&Id::from(ACCOUNT_ID));
let HandlerOutput { primary: resp, .. } = crate::chat::handle_chat_set(
backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": { "c0": { "kind": "group", "name": "test-group" } }
}),
&[],
)
.await
.expect("make_group_chat");
resp["created"]["c0"]["id"]
.as_str()
.expect("group chat id")
.to_owned()
}
async fn make_channel_chat(backend: &MemoryBackend) -> String {
let space_id = "s0";
backend.insert_object_for_test(
"Space",
ACCOUNT_ID,
space_id,
json!({
"id": space_id,
"name": "test-space",
"createdAt": "2026-01-01T00:00:00Z",
"memberCount": 1,
"categories": [],
"uncategorizedChannelIds": [],
"isPublic": false,
"isPubliclyPreviewable": false,
"roles": [{ "id": "r-owner", "name": "Owner", "permissions": ["manage_channels", "mention_broadcast", "send"], "position": 10 }],
"members": [{ "id": ACCOUNT_ID, "roleIds": ["r-owner"], "joinedAt": "2026-01-01T00:00:00Z" }],
}),
);
crate::space::handle_space_set(
backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"update": { space_id: { "addChannels": [{ "name": "general" }] } }
}),
&[],
)
.await
.expect("make_channel_chat: addChannels");
let HandlerOutput {
primary: get_resp, ..
} = crate::space::handle_space_get(
backend,
&(),
json!({ "accountId": ACCOUNT_ID, "ids": [space_id] }),
&[],
)
.await
.expect("make_channel_chat: Space/get");
get_resp["list"][0]["uncategorizedChannelIds"][0]
.as_str()
.expect("channel chat id")
.to_owned()
}
#[tokio::test]
async fn broadcast_mention_create_without_space_unrestricted() {
let backend = MemoryBackend::new();
let chat_id = make_group_chat(&backend).await;
let body = "Hello @everyone!";
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created in group chat (no spaceId), got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_create_in_channel_succeeds() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let body = "Hello @everyone!";
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created in channel chat, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_create_empty_skips_permission_check() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": "Hello, world!",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": []
}
}
}),
&[],
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created with empty broadcastMentions, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_update_retaining_broadcast_succeeds() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let body = "Hello @everyone!";
let HandlerOutput {
primary: create_resp,
..
} = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
&[],
)
.await
.expect("create message");
let msg_id = create_resp["created"]["m0"]["id"]
.as_str()
.expect("message id");
let new_body = "Hey @here now!";
let HandlerOutput {
primary: update_resp,
..
} = handle_message_set(
&backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"update": {
(msg_id): {
"body": new_body,
"broadcastMentions": [
{ "scope": "here", "offset": 4, "length": 5 }
]
}
}
}),
&[],
)
.await
.expect("update message");
assert!(
update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
"expected updated, got notUpdated: {}",
update_resp["notUpdated"][msg_id]
);
assert!(
update_resp["notUpdated"].is_null()
|| !update_resp["notUpdated"]
.as_object()
.is_some_and(|m| m.contains_key(msg_id)),
"message should not be in notUpdated"
);
}
}