use jmap_chat_types::query::{Filter, MessageComparator, MessageFilter};
use jmap_chat_types::{
Attachment, BroadcastMention, Chat, DeliveryState, Mention, Message, MessageAction,
ReadPosition, Space, BROADCAST_MENTION_SCOPES,
};
use jmap_types::{Id, JmapError, PatchObject, State, UTCDate};
use serde::Deserialize;
use serde_json::{json, Value};
use crate::backend::{BackendSetError, ChatBackend, SetError, SetErrorType};
use std::collections::HashSet;
use crate::helpers::{
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, set_error_value, SetAccumulators,
};
use crate::helpers::{mistyped_create_props, PropType, PLACEHOLDER_ID};
use jmap_server::{
query_anchor_args, server_fail_from_backend, server_fail_value_from_backend, HandlerOutput,
};
pub async fn handle_message_get<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
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 ids_slice = ids.as_deref();
let (mut list, not_found) = backend
.get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
.await
.map_err(|e| server_fail_from_backend(&e))?;
if !backend.retains_edit_history() {
for msg in list.iter_mut() {
msg.edit_history = None;
}
}
let state = backend
.get_state::<Message>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let list_json: Vec<Value> = if let Some(ref props) = properties {
let mut prop_set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
prop_set.insert("id");
list.iter()
.map(|obj| {
let val = serialize_value(obj)?;
Ok(filter_properties(&val, &prop_set))
})
.collect::<Result<Vec<_>, JmapError>>()?
} else {
list.iter()
.map(serialize_value)
.collect::<Result<Vec<_>, _>>()?
};
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_message_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
jmap_server::handlers::handle_changes::<Message, B>(backend, caller, args).await
}
pub async fn handle_message_query<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(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 {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 {v}"))
})?,
};
let (anchor, anchor_offset) = query_anchor_args(&args)?;
reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
let filter: Option<MessageFilter> =
optional_arg(&mut args, "filter", JmapError::unsupported_filter)?;
let top = match &filter {
Some(Filter::Condition(c)) => Some(c),
_ => None,
};
if !top.is_some_and(|c| c.chat_id.is_some() || c.has_mention == Some(true)) {
return Err(JmapError::unsupported_filter());
}
if top.is_some_and(|c| c.text.is_some() || c.thread_root_id.is_some()) {
return Err(JmapError::unsupported_filter());
}
let sort: Option<Vec<MessageComparator>> = optional_arg(&mut args, "sort", || {
JmapError::invalid_arguments("sort must be an array")
})?;
let result = backend
.query_objects::<Message>(
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.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok(HandlerOutput::new(resp))
}
pub async fn handle_message_query_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, args) = extract_account_id(args)?;
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 result = backend
.query_changes::<Message>(
caller,
&account_id,
&since_query_state,
None,
None,
max_changes,
up_to_id.as_ref(),
false,
)
.await
.map_err(JmapError::from)?;
let removed: Vec<&str> = result.removed.iter().map(|id| id.as_ref()).collect();
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": removed,
"added": added,
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok(HandlerOutput::new(resp))
}
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
}
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) -> Vec<&'static str> {
if !ENCRYPTED_BODY_TYPES.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()
}
const MAX_SUBJECT_BYTES: usize = 1024;
const MAX_UNSIGNED_INT: u64 = (1 << 53) - 1;
fn apply_create_optionals(obj: &Value, msg: &mut Message) -> Result<(), &'static str> {
let get = |key: &str| obj.get(key).filter(|v| !v.is_null());
if let Some(v) = get("attachments") {
let attachments = Vec::<Attachment>::deserialize(v).map_err(|_| "attachments")?;
if !attachments.iter().all(valid_attachment) {
return Err("attachments");
}
msg.attachments = attachments;
}
if let Some(v) = get("mentions") {
msg.mentions = Vec::<Mention>::deserialize(v).map_err(|_| "mentions")?;
}
if let Some(v) = get("broadcastMentions") {
msg.broadcast_mentions =
Vec::<BroadcastMention>::deserialize(v).map_err(|_| "broadcastMentions")?;
}
if let Some(v) = get("actions") {
msg.actions = Vec::<MessageAction>::deserialize(v).map_err(|_| "actions")?;
}
if let Some(v) = get("topicId") {
match v.as_str() {
Some(s) if !s.is_empty() && s.len() <= 255 => msg.topic_id = Some(s.to_owned()),
_ => return Err("topicId"),
}
}
if let Some(v) = get("subject") {
match v.as_str() {
Some(s) if msg.topic_id.is_some() && s.len() <= MAX_SUBJECT_BYTES => {
msg.subject = Some(s.to_owned());
}
_ => return Err("subject"),
}
}
if let Some(v) = get("expiresAfterReadSeconds") {
match v.as_u64() {
Some(n) if n <= MAX_UNSIGNED_INT => msg.expires_after_read_seconds = Some(n),
_ => return Err("expiresAfterReadSeconds"),
}
}
Ok(())
}
fn valid_attachment(a: &Attachment) -> bool {
!a.filename.contains(['/', '\\', '\0'])
&& valid_media_type(&a.content_type)
&& a.sha256.len() == 64
&& a.sha256
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
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))
}
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::<ReadPosition>(
caller,
account_id,
chat_id.as_ref(),
ReadPosition::new(Id::from(PLACEHOLDER_ID), chat_id.clone()),
)
.await;
}
}
pub async fn handle_message_set<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
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 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();
for (create_id, obj_val) in create_map {
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 = Id::from(chat_id_str);
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 body.len() > 100_000 {
not_created.insert(
create_id.clone(),
json!({
"type": "tooLarge",
"description": "body exceeds maxBodyBytes (100000)"
}),
);
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);
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, _)) => found.into_iter().next(),
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
};
if chat.as_ref().is_some_and(|c| c.closed_at.is_some()) {
not_created.insert(
create_id.clone(),
json!({ "type": "forbidden", "description": "the group is closed" }),
);
continue;
}
if let Some(sid) = chat.as_ref().and_then(|c| c.space_id.as_ref()) {
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;
}
}
}
if let Some(sid) = chat
.as_ref()
.and_then(|c| c.space_id.as_ref())
.filter(|_| !broadcast_mentions_val.is_empty())
{
match backend
.may_broadcast_mention(caller, &account_id, sid)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_created.insert(create_id.clone(), set_error_value(&set_err));
continue;
}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
}
let reply_to: Option<Id> = obj_val
.get("replyTo")
.and_then(|v| v.as_str())
.map(Id::from);
let thread_root_id: Option<Id> = obj_val
.get("threadRootId")
.and_then(|v| v.as_str())
.map(Id::from);
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 msg = Message::new(
Id::from(PLACEHOLDER_ID),
Id::from(create_id.as_str()),
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;
if let Some(d) = sender_expires_at {
msg.sender_expires_at = Some(d);
}
msg.burn_on_read = burn_on_read;
if let Err(property) = apply_create_optionals(obj_val, &mut msg) {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": [property] }),
);
continue;
}
if let Err(slow_err) = backend
.slow_mode_check(caller, &account_id, &msg.chat_id)
.await
{
let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
let set_err = SetError::new(SetErrorType::custom("rateLimited"))
.with_description("Slow mode is active for this chat")
.with_extra("serverRetryAfter", json!(retry_after_str));
not_created.insert(create_id.clone(), set_error_value(&set_err));
continue;
}
match backend
.create_object::<Message>(caller, &account_id, create_id, msg)
.await
{
Ok((_server_id, created_obj)) => {
mutated = true;
delivered_chat_ids.push(created_obj.chat_id.clone());
created.insert(
create_id.clone(),
serde_json::to_value(&created_obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Err(BackendSetError::SetError(set_err)) => {
not_created.insert(create_id.clone(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
}
Err(_) => {
not_created.insert(
create_id.clone(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
ensure_read_positions(backend, caller, &account_id, delivered_chat_ids).await;
}
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, patch_val) in update_map {
let id = Id::from(id_str.as_str());
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;
}
const MESSAGE_UPDATE_ALLOWED: &[&str] = &[
"body",
"bodyType",
"mentions",
"broadcastMentions",
"deletedAt",
"deletedForAll",
"readAt",
"readDisposition",
];
let bad_props: Vec<&str> = patch_val
.as_object()
.map(|obj| {
obj.keys()
.map(String::as_str)
.filter(|k| {
!MESSAGE_UPDATE_ALLOWED.contains(k) && !k.starts_with("reactions/")
})
.collect()
})
.unwrap_or_default();
if !bad_props.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": bad_props }),
);
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 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());
if deletes_for_all || edits {
match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
let description = found.first().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;
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
let mut augmented = patch_val;
if augmented.get("body").is_some() {
if 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 {
if 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();
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 forbidden = match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
let mut bad: Vec<String> = Vec::new();
if let Some(msg) = found.first() {
for (_, suffix) in &decoded {
if let Some(existing) = msg.reactions.get(suffix) {
if existing.sender_id != account_id {
bad.push(suffix.clone());
}
}
}
}
bad
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
};
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_burn_on_read = if patch_sets_read_at {
match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
found.first().and_then(|m| m.burn_on_read) == Some(true)
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
} else {
false
};
if edits {
let (current_has_bm, msg_chat_id) = match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _)) => {
if let Some(msg) = found.first() {
(
!msg.broadcast_mentions.is_empty(),
Some(msg.chat_id.clone()),
)
} else {
(false, None)
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
};
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,
};
if has_bm {
if let Some(ref cid) = msg_chat_id {
let chat_lookup = backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(cid)),
None,
)
.await;
match chat_lookup {
Ok((found, _)) => {
if let Some(chat) = found.first() {
if let Some(ref sid) = chat.space_id {
match backend
.may_broadcast_mention(caller, &account_id, sid)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_updated
.insert(id_str, set_error_value(&set_err));
continue;
}
Err(e) => {
not_updated.insert(
id_str,
server_fail_value_from_backend(&e),
);
continue;
}
}
}
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
}
}
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 update_outcome = if patch_sets_read_at && pre_patch_burn_on_read {
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(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
continue;
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
continue;
}
};
mutated = true;
match maybe_updated_obj {
Some(obj) => {
updated.insert(
id_str,
serde_json::to_value(&obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
None => {
updated.insert(id_str, Value::Null);
}
}
}
}
if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
return Err(JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {bad}"
)));
}
for id_val in destroy_arr {
let Some(id_str) = id_val.as_str() else {
continue; };
let id = Id::from(id_str);
match backend
.destroy_object::<Message>(caller, &account_id, &id)
.await
{
Ok(()) => {
mutated = true;
destroyed_list.push(Value::String(id_str.to_owned()));
}
Err(BackendSetError::SetError(set_err)) => {
not_destroyed.insert(id_str.to_owned(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_destroyed.insert(id_str.to_owned(), server_fail_value_from_backend(&e));
}
Err(_) => {
not_destroyed.insert(
id_str.to_owned(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
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();
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
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 body = "Hello @everyone!";
let HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"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 HandlerOutput { primary: resp, .. } = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"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 {
let HandlerOutput { primary: resp, .. } = crate::chat::handle_chat_set(
backend,
&(),
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"], "position": 10 }],
"members": [{ "id": ACCOUNT_ID, "roleIds": ["r-owner"], "joinedAt": "2026-01-01T00:00:00Z" }],
}),
);
crate::space::handle_space_set(
backend,
&(),
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,
&(),
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,
&(),
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,
&(),
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,
&(),
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,
&(),
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"
);
}
}