Skip to main content

jmap_chat_server/
message.rs

1//! Message/* method handlers (draft-atwood-jmap-chat-00 §Message).
2//!
3//! # Wire-shape contract
4//!
5//! Every `handle_*` function in this module conforms to the canonical JMAP
6//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
7//! Object whose fields match the corresponding RFC 8620 §5 method shape
8//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
9//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
10//! arguments defined by draft-atwood-jmap-chat-00 §Message. The
11//! returned `Value` is the corresponding method-response object per the
12//! same section refs.
13//!
14//! The returned `HandlerOutput::extra_invocations` carries any invocations
15//! that this handler injected into the request stream (RFC 8620 §6.3);
16//! for the handlers in this module the vector is **always empty**.
17//!
18//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
19//! §3.6.2 and §5):
20//!
21//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
22//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
23//!   `maxObjectsInSet`;
24//! - `/set`: `stateMismatch`;
25//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
26//! - `/queryChanges`: `tooManyChanges`;
27//! - `/query`, `/queryChanges`: `unsupportedFilter`;
28//! - `/query`: `unsupportedSort`, `anchorNotFound`.
29//!
30//! Per-target failures inside `/set` (including the `slow_mode_check`
31//! `rateLimit` and reaction-patch `invalidPatch` paths) surface in the
32//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
33//! not as `Err`.
34
35use jmap_chat_types::{
36    Attachment, AttachmentCreate, BROADCAST_MENTION_SCOPES, BroadcastMention, Chat, DeliveryState,
37    Mention, Message, MessageAction, PresenceStatus, ReadPosition, Space,
38};
39use jmap_chat_types::{Filter, MessageComparator, MessageFilter, MessageFilterCondition};
40use jmap_types::{Id, JmapError, PatchObject, UTCDate};
41use serde::Deserialize;
42use serde_json::{Value, json};
43
44use crate::chat::record_unread_count_changes;
45use crate::outbound::{OutboundEvent, ReactionAction};
46use crate::{ChatBackend, ChatLimits};
47use jmap_server::{BackendSetError, SetError, SetErrorType};
48use std::collections::{BTreeMap, HashMap, HashSet};
49use subtle::ConstantTimeEq;
50
51use crate::helpers::{
52    PropType, check_metadata_entry, create_metadata, is_metadata_key, mistyped_create_props,
53};
54use crate::helpers::{
55    SetAccumulators, default_sort, enforce_max_objects_in_get, enforce_max_objects_in_set,
56    extract_account_id, filter_properties, finalize_set_response, iso8601_before, not_found_json,
57    now_utc_string, optional_arg, reject_unsupported_sort, serialize_value,
58};
59use crate::helpers::{parents_first, resolve_entry_refs, resolved_create};
60use jmap_server::{
61    HandlerOutput, MetadataProjection, QueryParams, backend_set_error_value, bool_arg, filter_arg,
62    is_client_updatable, query_anchor_args, reject_server_set, server_fail_from_backend,
63    server_fail_value_from_backend,
64};
65
66// ---------------------------------------------------------------------------
67// Message/get
68// ---------------------------------------------------------------------------
69
70/// Handle a `Message/get` method call (draft-atwood-jmap-chat-00 §Message).
71///
72/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
73/// `ids`, optional `properties`); the returned `Value` is the §5.1
74/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
75///
76/// `using` is the request's capability list (pass
77/// [`jmap_server::CallContext::using`]). When the backend lists Message for
78/// draft-ietf-jmap-metadata-04 ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)),
79/// `metadata` is returned as an object, by default only with
80/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
81/// `properties` may hold `metadata/<namespace>` subselectors (-04 §2,
82/// §3.1); see
83/// [`jmap_server::MetadataProjection`].
84///
85/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
86pub async fn handle_message_get<B: ChatBackend>(
87    backend: &B,
88    caller: &B::CallerCtx,
89    args: Value,
90    using: &[String],
91) -> Result<HandlerOutput, JmapError> {
92    let (account_id, mut args) = extract_account_id(args)?;
93
94    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
95    if !backend
96        .account_exists(caller, &account_id)
97        .await
98        .map_err(|e| server_fail_from_backend(&e))?
99    {
100        return Err(JmapError::account_not_found());
101    }
102    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
103
104    let ids: Option<Vec<Id>> = match args.remove("ids") {
105        None | Some(Value::Null) => None,
106        Some(v) => Some(
107            serde_json::from_value(v)
108                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
109        ),
110    };
111
112    // RFC 8620 §5.1: when `properties` is specified, return only those fields
113    // (plus `id` which is always included). `None` means return all fields.
114    let properties: Option<Vec<String>> = match args.remove("properties") {
115        None | Some(Value::Null) => None,
116        Some(v) => Some(
117            serde_json::from_value(v)
118                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
119        ),
120    };
121
122    let projection = MetadataProjection::new(
123        properties.as_deref(),
124        true,
125        using,
126        backend
127            .metadata_info::<Message>(caller, &account_id)
128            .as_ref(),
129    )?;
130
131    let ids_slice = ids.as_deref();
132    let (fetched, mut not_found) = backend
133        .get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
134        .await
135        .map_err(|e| server_fail_from_backend(&e))?;
136
137    // draft-atwood-jmap-chat-00 §Message/query: "messages in channels the
138    // caller cannot view MUST be omitted" from `Message/get`. A hidden
139    // message is reported like a missing one: a requested id goes to
140    // notFound, and a full fetch drops it (RFC 8620 §5.1 notFound lists
141    // only requested ids).
142    let mut viewable: HashMap<Id, bool> = HashMap::new();
143    let mut list = Vec::with_capacity(fetched.len());
144    for msg in fetched {
145        let visible = match viewable.get(&msg.chat_id) {
146            Some(&v) => v,
147            None => {
148                let v = backend
149                    .may_view_chat(caller, &account_id, &msg.chat_id)
150                    .await
151                    .map_err(|e| server_fail_from_backend(&e))?;
152                viewable.insert(msg.chat_id.clone(), v);
153                v
154            }
155        };
156        if visible {
157            list.push(msg);
158        } else if ids_slice.is_some() {
159            not_found.push(msg.id);
160        }
161    }
162
163    // Edit-history retention gate (draft-atwood-jmap-chat-00 commit
164    // `0783fc4` + §Message editHistory). When the backend does not
165    // retain edit history, the `editHistory` field MUST be omitted
166    // from every returned Message. Setting `edit_history = None`
167    // here causes serde's `skip_serializing_if = "Option::is_none"`
168    // to collapse it on the wire, satisfying the spec MUST.
169    //
170    // `Message/changes` per RFC 8620 §5.2 returns id arrays only
171    // (no Message objects), so the spec's "omit from /changes" has
172    // no wire-level effect — only `Message/get` needs this gate.
173    if !backend.retains_edit_history() {
174        for msg in list.iter_mut() {
175            msg.edit_history = None;
176        }
177    }
178
179    let wants_counts = properties.as_ref().is_none_or(|p| {
180        p.iter()
181            .any(|k| k == "replyCount" || k == "unreadReplyCount")
182    });
183    if wants_counts && backend.limits(caller, &account_id).supports_threads {
184        fill_reply_counts(backend, caller, &account_id, &mut list).await?;
185    }
186
187    let state = backend
188        .get_state::<Message>(caller, &account_id)
189        .await
190        .map_err(|e| server_fail_from_backend(&e))?;
191
192    let prop_set: Option<HashSet<&str>> = properties.as_ref().map(|props| {
193        let mut set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
194        set.insert("id");
195        set
196    });
197    let list_json: Vec<Value> = list
198        .iter()
199        .map(|obj| {
200            let val = serialize_value(obj)?;
201            let mut out = match &prop_set {
202                Some(set) => filter_properties(&val, set),
203                None => val.clone(),
204            };
205            projection.apply(&val, &mut out);
206            Ok(out)
207        })
208        .collect::<Result<Vec<_>, JmapError>>()?;
209
210    Ok(HandlerOutput::new(json!({
211        "accountId": account_id.as_ref(),
212        "state": state.as_ref(),
213        "list": list_json,
214        "notFound": not_found_json(&not_found),
215    })))
216}
217
218/// Set the server-computed thread counts on each Message in `list`
219/// (draft-atwood-jmap-chat-00 §Message, used when `supportsThreads` is
220/// `true`).
221///
222/// `replyCount`: "Count of messages in this chat with `replyTo` equal to
223/// this message's `id`." `unreadReplyCount`, only on a thread root
224/// (`threadRootId` absent): "Count of replies to this message received
225/// after the owner's `ReadPosition.lastReadMessageId` in this Chat".
226/// Message ids are ULIDs "lexicographically ordered by time" (§Message
227/// IDs), so a reply counts as unread when its `id` sorts after
228/// `lastReadMessageId`, or always when that is absent (as for
229/// `Chat.unreadCount`).
230// ponytail: scans every Message and ReadPosition in the account per
231// call (O(messages) per Message/get); a backend with many messages
232// needs a reply-count index behind a ChatBackend hook.
233async fn fill_reply_counts<B: ChatBackend>(
234    backend: &B,
235    caller: &B::CallerCtx,
236    account_id: &Id,
237    list: &mut [Message],
238) -> Result<(), JmapError> {
239    if list.is_empty() {
240        return Ok(());
241    }
242    let (all, _) = backend
243        .get_objects::<Message>(caller, account_id, None, None)
244        .await
245        .map_err(|e| server_fail_from_backend(&e))?;
246    let (positions, _) = backend
247        .get_objects::<ReadPosition>(caller, account_id, None, None)
248        .await
249        .map_err(|e| server_fail_from_backend(&e))?;
250    for msg in list.iter_mut() {
251        let replies = || {
252            all.iter()
253                .filter(|r| r.chat_id == msg.chat_id && r.reply_to.as_ref() == Some(&msg.id))
254        };
255        let reply_count = replies().count() as u64;
256        msg.unread_reply_count = if msg.thread_root_id.is_none() {
257            let last_read = positions
258                .iter()
259                .find(|p| p.chat_id == msg.chat_id)
260                .and_then(|p| p.last_read_message_id.as_ref());
261            let unread = replies()
262                .filter(|r| last_read.is_none_or(|l| r.id.as_ref() > l.as_ref()))
263                .count();
264            Some(unread as u64)
265        } else {
266            None
267        };
268        msg.reply_count = Some(reply_count);
269    }
270    Ok(())
271}
272
273// ---------------------------------------------------------------------------
274// Message/changes
275// ---------------------------------------------------------------------------
276
277/// Handle a `Message/changes` method call (draft-atwood-jmap-chat-00 §Message).
278///
279/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
280/// `sinceState`, optional `maxChanges`); the returned `Value` is the
281/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
282/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
283///
284/// `using` is the request's capability list (pass
285/// [`jmap_server::CallContext::using`]); with
286/// `urn:ietf:params:jmap:metadata` the request may set
287/// draft-ietf-jmap-metadata-04 §3.3 `ignoreMetadataOnlyChanges`, and
288/// without it metadata-only changes are left out (-04 §3).
289///
290/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
291pub async fn handle_message_changes<B: ChatBackend>(
292    backend: &B,
293    caller: &B::CallerCtx,
294    args: Value,
295    using: &[String],
296) -> Result<HandlerOutput, JmapError> {
297    jmap_server::handle_changes::<Message, B>(backend, caller, args, using).await
298}
299
300// ---------------------------------------------------------------------------
301// Message/query
302// ---------------------------------------------------------------------------
303
304/// Handle a `Message/query` method call (draft-atwood-jmap-chat-00 §Message).
305///
306/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
307/// `filter`, optional `sort`, optional `position` / `anchor` /
308/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
309/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
310/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
311/// `total`, optional `limit`).
312///
313/// Unknown filter clauses and sort properties are refused with
314/// `unsupportedFilter` / `unsupportedSort` (RFC 8620 §5.5).
315///
316/// `using` is the request's capability list (pass
317/// [`jmap_server::CallContext::using`]); without
318/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
319/// filter condition is `unsupportedFilter` (-04 §3).
320///
321/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
322pub async fn handle_message_query<B: ChatBackend>(
323    backend: &B,
324    caller: &B::CallerCtx,
325    args: Value,
326    using: &[String],
327) -> Result<HandlerOutput, JmapError> {
328    jmap_server::reject_metadata_filter_arg(
329        &args,
330        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
331        using,
332    )?;
333    let (account_id, mut args) = extract_account_id(args)?;
334
335    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
336    if !backend
337        .account_exists(caller, &account_id)
338        .await
339        .map_err(|e| server_fail_from_backend(&e))?
340    {
341        return Err(JmapError::account_not_found());
342    }
343
344    let calculate_total: bool = bool_arg(&args, "calculateTotal", false);
345
346    let limit: Option<u64> = match args.remove("limit") {
347        None | Some(Value::Null) => None,
348        Some(v) => match v.as_u64() {
349            Some(n) => Some(n),
350            None => {
351                return Err(JmapError::invalid_arguments(format!(
352                    "limit: expected a non-negative integer, got {}",
353                    jmap_server::json_type_name(&v)
354                )));
355            }
356        },
357    };
358
359    let position: i64 = match args.remove("position") {
360        None | Some(Value::Null) => 0,
361        Some(v) => v.as_i64().ok_or_else(|| {
362            JmapError::invalid_arguments(format!(
363                "position: expected an integer, got {}",
364                jmap_server::json_type_name(&v)
365            ))
366        })?,
367    };
368
369    let (anchor, anchor_offset) = query_anchor_args(&args)?;
370
371    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
372    let filter: Option<MessageFilter> = filter_arg(&mut args)?;
373
374    let supports_threads = backend.limits(caller, &account_id).supports_threads;
375    let top = check_message_filter(filter.as_ref(), supports_threads)?;
376
377    // §Message/query: "Default sort: `receivedAt` ascending when `chatId`
378    // is present; `receivedAt` descending when `chatId` is absent."
379    let in_one_chat = top.chat_id.is_some();
380    default_sort(
381        &mut args,
382        json!([{ "property": "receivedAt", "isAscending": in_one_chat }]),
383    );
384    let sort: Option<Vec<MessageComparator>> = optional_arg(&mut args, "sort", || {
385        JmapError::invalid_arguments("sort must be an array")
386    })?;
387
388    // draft-atwood-jmap-chat-00 §Message/query: "messages in channels the
389    // caller cannot view MUST be omitted". A query scoped to one Chat the
390    // caller cannot view matches nothing; a query without `chatId` relies
391    // on the backend (see `ChatBackend::may_view_chat`).
392    let hidden = match top.chat_id.as_ref() {
393        Some(chat_id) => !backend
394            .may_view_chat(caller, &account_id, chat_id)
395            .await
396            .map_err(|e| server_fail_from_backend(&e))?,
397        None => false,
398    };
399
400    let result = backend
401        .query_objects::<Message>(
402            caller,
403            &account_id,
404            QueryParams::new()
405                .filter(filter.as_ref())
406                .sort(sort.as_deref())
407                .limit(limit)
408                .position(position)
409                .anchor(anchor.as_ref())
410                .anchor_offset(anchor_offset),
411        )
412        .await
413        .map_err(JmapError::from)?;
414    let (ids, position, total) = if hidden {
415        (Vec::new(), 0, Some(0))
416    } else {
417        (result.ids, result.position, result.total)
418    };
419
420    let mut resp = json!({
421        "accountId": account_id.as_ref(),
422        "queryState": result.query_state.as_ref(),
423        "canCalculateChanges": result.can_calculate_changes,
424        "position": position,
425        "ids": ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
426    });
427    if calculate_total && let Some(t) = total {
428        resp["total"] = json!(t);
429    }
430
431    Ok(HandlerOutput::new(resp))
432}
433
434/// Apply the draft-atwood-jmap-chat-00 §Message/query `unsupportedFilter`
435/// refusals and return the top-level filter condition.
436///
437/// Shared by `Message/query` and `Message/queryChanges`, whose filter is
438/// that of the original query (RFC 8620 §5.6).
439///
440/// # Errors
441///
442/// `unsupportedFilter` when the filter is not a top-level condition with
443/// `chatId` or `hasMention: true` ("Servers MUST return an
444/// `unsupportedFilter` error for any request that omits `chatId` without
445/// also including `hasMention: true`"), sets `text` ("Servers that do not
446/// support full-text search MUST return `unsupportedFilter`"), or sets
447/// `threadRootId` while `supports_threads` is `false` ("Valid only when
448/// `supportsThreads` is `true`; otherwise servers MUST return
449/// `unsupportedFilter`").
450///
451/// ponytail: no backend implements `text`, so it is refused for every
452/// backend; a backend that adds it needs a ChatBackend capability hook to
453/// lift the refusal.
454fn check_message_filter(
455    filter: Option<&MessageFilter>,
456    supports_threads: bool,
457) -> Result<&MessageFilterCondition, JmapError> {
458    match filter {
459        Some(Filter::Condition(c))
460            if (c.chat_id.is_some() || c.has_mention == Some(true))
461                && c.text.is_none()
462                && (c.thread_root_id.is_none() || supports_threads) =>
463        {
464            Ok(c)
465        }
466        _ => Err(JmapError::unsupported_filter()),
467    }
468}
469
470// ---------------------------------------------------------------------------
471// Message/queryChanges
472// ---------------------------------------------------------------------------
473
474/// Handle a `Message/queryChanges` method call (draft-atwood-jmap-chat-00 §Message).
475///
476/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
477/// optional `filter`, optional `sort`, `sinceQueryState`, optional
478/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
479/// returned `Value` is the §5.6 `/queryChanges` response shape
480/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
481/// `removed`, `added`).
482///
483/// A query scoped to one Chat the caller cannot view fails with
484/// `cannotCalculateChanges`, so the client re-runs `Message/query`, which
485/// returns nothing for that Chat (see [`handle_message_query`]).
486///
487/// `using` is the request's capability list (pass
488/// [`jmap_server::CallContext::using`]); without
489/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
490/// filter condition is `unsupportedFilter` (-04 §3).
491///
492/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
493pub async fn handle_message_query_changes<B: ChatBackend>(
494    backend: &B,
495    caller: &B::CallerCtx,
496    mut args: Value,
497    using: &[String],
498) -> Result<HandlerOutput, JmapError> {
499    jmap_server::reject_metadata_filter_arg(
500        &args,
501        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
502        using,
503    )?;
504    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
505    // query, so the §Message/query default sort applies here too.
506    let chat_id = args
507        .get("filter")
508        .and_then(|f| f.get("chatId"))
509        .and_then(Value::as_str)
510        .map(Id::from);
511    if let Value::Object(map) = &mut args {
512        default_sort(
513            map,
514            json!([{ "property": "receivedAt", "isAscending": chat_id.is_some() }]),
515        );
516    }
517    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
518
519    // RFC 8620 §5.6: the filter is that of the original query, so the
520    // §Message/query `unsupportedFilter` refusals apply here too.
521    let account_id = args.get("accountId").and_then(Value::as_str).map(Id::from);
522    if let Some(account_id) = &account_id {
523        // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe), before the
524        // may_view_chat read below.
525        if !backend
526            .account_exists(caller, account_id)
527            .await
528            .map_err(|e| server_fail_from_backend(&e))?
529        {
530            return Err(JmapError::account_not_found());
531        }
532        let mut probe = serde_json::Map::new();
533        if let Some(f) = args.get("filter") {
534            probe.insert("filter".into(), f.clone());
535        }
536        let filter: Option<MessageFilter> = filter_arg(&mut probe)?;
537        let supports_threads = backend.limits(caller, account_id).supports_threads;
538        check_message_filter(filter.as_ref(), supports_threads)?;
539    }
540
541    // §Message/query: "messages in channels the caller cannot view MUST be
542    // omitted", so changes to such a Chat's messages are not reported.
543    if let (Some(account_id), Some(chat_id)) = (account_id, chat_id)
544        && !backend
545            .may_view_chat(caller, &account_id, &chat_id)
546            .await
547            .map_err(|e| server_fail_from_backend(&e))?
548    {
549        return Err(JmapError::cannot_calculate_changes());
550    }
551    jmap_server::handle_query_changes::<Message, B>(backend, caller, args).await
552}
553
554// ---------------------------------------------------------------------------
555// BroadcastMention validation
556// ---------------------------------------------------------------------------
557
558/// Validate broadcast mentions against spec §4.4.1 / §4.16 constraints.
559///
560/// Returns the SetError value on failure, None on success. §BroadcastMention:
561/// "Servers MUST reject a BroadcastMention with an unrecognized `scope`
562/// value; in `Message/set` the rejection is an `invalidProperties` SetError
563/// naming `broadcastMentions`." A missing or non-string `scope` takes the
564/// §Input Validation default, which is the same SetError.
565fn validate_broadcast_mentions(broadcast_mentions: &[serde_json::Value]) -> Option<Value> {
566    let invalid_properties = |desc: String| {
567        json!({
568            "type": "invalidProperties",
569            "properties": ["broadcastMentions"],
570            "description": desc,
571        })
572    };
573    for (i, bm) in broadcast_mentions.iter().enumerate() {
574        // scope validation
575        let scope = match bm.get("scope").and_then(|v| v.as_str()) {
576            Some(s) => s,
577            None => {
578                return Some(invalid_properties(format!(
579                    "broadcastMentions[{i}]: missing or non-string scope"
580                )));
581            }
582        };
583        if !BROADCAST_MENTION_SCOPES.contains(&scope) {
584            return Some(invalid_properties(format!(
585                "broadcastMentions[{i}]: unrecognized scope \"{scope}\""
586            )));
587        }
588    }
589    None
590}
591
592// ---------------------------------------------------------------------------
593// Optional create properties
594// ---------------------------------------------------------------------------
595
596/// Default `bodyType` values that indicate an end-to-end encrypted body:
597/// the one type draft-atwood-jmap-chat-00 §Message `body` names. A backend
598/// adds others, such as `"application/mimi-fanout"`
599/// (draft-atwood-jmap-chat-mimi-00 §MLS Messages), through
600/// [`ChatLimits::encrypted_body_types`](crate::ChatLimits::encrypted_body_types).
601pub const ENCRYPTED_BODY_TYPES: &[&str] = &["application/mls-ciphertext"];
602
603/// Default `bodyType` values this server accepts, advertised as the
604/// `supportedBodyTypes` capability (draft-atwood-jmap-chat-00
605/// §Account-Level Capability Object). A backend lists other types through
606/// [`ChatLimits::supported_body_types`](crate::ChatLimits::supported_body_types).
607pub const SUPPORTED_BODY_TYPES: &[&str] = &[
608    "text/plain",
609    "text/markdown",
610    "application/jmap-chat-rich",
611    "application/mls-ciphertext",
612];
613
614/// draft-atwood-jmap-chat-00 §Fields Inside the Ciphertext: Message fields
615/// that "MUST be empty or absent" when `bodyType` indicates an encrypted type.
616const CIPHERTEXT_ONLY_FIELDS: [&str; 8] = [
617    "mentions",
618    "broadcastMentions",
619    "attachments",
620    "actions",
621    "replyTo",
622    "threadRootId",
623    "topicId",
624    "subject",
625];
626
627/// Check the create fields that `bodyType` requires to be empty: all of
628/// [`CIPHERTEXT_ONLY_FIELDS`] when `body_type` is one of the account's
629/// `encrypted` types (§Fields Inside the Ciphertext).
630///
631/// Returns every offending field, in [`CIPHERTEXT_ONLY_FIELDS`] order, for
632/// an `invalidProperties` SetError "whose `properties` lists each such
633/// field"; empty on success.
634fn body_type_field_conflicts(
635    obj: &Value,
636    body_type: &str,
637    encrypted: &[&str],
638) -> Vec<&'static str> {
639    if !encrypted.contains(&body_type) {
640        return Vec::new();
641    }
642    let non_empty = |key: &str| {
643        obj.get(key)
644            .is_some_and(|v| !(v.is_null() || v == "" || v.as_array().is_some_and(Vec::is_empty)))
645    };
646    CIPHERTEXT_ONLY_FIELDS
647        .into_iter()
648        .filter(|&k| non_empty(k))
649        .collect()
650}
651
652/// Check a `Message/set` edit `patch` of the stored `msg` against
653/// `maxBodyBytes` and the encrypted-`bodyType` empty-field rule, which
654/// apply to updates as well as creates.
655///
656/// draft-atwood-jmap-chat-00 §Account-Level Capability Object
657/// `maxBodyBytes`: "in `Message/set` the rejection is a `tooLarge`
658/// SetError." §Fields Inside the Ciphertext: "Servers MUST reject a
659/// `Message/set` create or update that has an encrypted `bodyType` and any
660/// of these fields non-empty". The field rule runs on the Message as it
661/// would be after the patch, so a `bodyType`-only patch to an encrypted
662/// type is rejected when the stored Message keeps such a field.
663///
664/// Returns the SetError, or `None` when the edit passes.
665fn edit_limit_error(msg: &Message, patch: &Value, limits: &ChatLimits) -> Option<Value> {
666    if let Some(body) = patch.get("body").and_then(Value::as_str)
667        && u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes)
668    {
669        return Some(json!({
670            "type": "tooLarge",
671            "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
672        }));
673    }
674    let mut merged = serde_json::to_value(msg).ok()?;
675    if let (Some(dst), Some(src)) = (merged.as_object_mut(), patch.as_object()) {
676        dst.extend(src.iter().map(|(k, v)| (k.clone(), v.clone())));
677    }
678    let body_type = merged.get("bodyType").and_then(Value::as_str)?.to_owned();
679    let conflicts = body_type_field_conflicts(&merged, &body_type, limits.encrypted_body_types);
680    (!conflicts.is_empty()).then(|| {
681        json!({
682            "type": "invalidProperties",
683            "properties": conflicts,
684            "description": format!("must be empty or absent when bodyType is {body_type}"),
685        })
686    })
687}
688
689/// Implementation-defined maximum byte length of `subject`
690/// (draft-atwood-jmap-chat-00 §Input Validation).
691const MAX_SUBJECT_BYTES: usize = 1024;
692
693/// RFC 8620 §1.3 UnsignedInt upper bound, 2^53 - 1.
694const MAX_UNSIGNED_INT: u64 = (1 << 53) - 1;
695
696/// Parse the optional `Message/set` create properties `mentions`,
697/// `broadcastMentions`, `actions`, `topicId`, `subject` and
698/// `expiresAfterReadSeconds` from `obj`, applying the
699/// draft-atwood-jmap-chat-00 §Input Validation checks, and return a
700/// function that copies them onto a Message. An absent or `null`
701/// property keeps the default. `broadcastMentions` must already have
702/// passed [`validate_broadcast_mentions`].
703///
704/// On error, returns the wire name of the first offending property, for an
705/// `invalidProperties` SetError.
706fn apply_create_optionals(
707    obj: &Value,
708) -> Result<impl FnOnce(&mut Message) + Send + use<>, &'static str> {
709    let get = |key: &str| obj.get(key).filter(|v| !v.is_null());
710    let mentions = get("mentions")
711        .map(|v| Vec::<Mention>::deserialize(v).map_err(|_| "mentions"))
712        .transpose()?;
713    let broadcast_mentions = get("broadcastMentions")
714        .map(|v| Vec::<BroadcastMention>::deserialize(v).map_err(|_| "broadcastMentions"))
715        .transpose()?;
716    // §MessageAction: "Servers MUST store and forward MessageAction
717    // records without inspection or transformation."
718    let actions = get("actions")
719        .map(|v| Vec::<MessageAction>::deserialize(v).map_err(|_| "actions"))
720        .transpose()?;
721    let topic_id = match get("topicId") {
722        None => None,
723        Some(v) => match v.as_str() {
724            Some(s) if !s.is_empty() && s.len() <= 255 => Some(s.to_owned()),
725            _ => return Err("topicId"),
726        },
727    };
728    let subject = match get("subject") {
729        None => None,
730        Some(v) => match v.as_str() {
731            Some(s) if topic_id.is_some() && s.len() <= MAX_SUBJECT_BYTES => Some(s.to_owned()),
732            _ => return Err("subject"),
733        },
734    };
735    let expires_after_read_seconds = match get("expiresAfterReadSeconds") {
736        None => None,
737        Some(v) => match v.as_u64() {
738            Some(n) if n <= MAX_UNSIGNED_INT => Some(n),
739            _ => return Err("expiresAfterReadSeconds"),
740        },
741    };
742    Ok(move |msg: &mut Message| {
743        if let Some(v) = mentions {
744            msg.mentions = v;
745        }
746        if let Some(v) = broadcast_mentions {
747            msg.broadcast_mentions = v;
748        }
749        if let Some(v) = actions {
750            msg.actions = v;
751        }
752        if topic_id.is_some() {
753            msg.topic_id = topic_id;
754        }
755        if subject.is_some() {
756            msg.subject = subject;
757        }
758        if expires_after_read_seconds.is_some() {
759            msg.expires_after_read_seconds = expires_after_read_seconds;
760        }
761    })
762}
763
764/// Build a `Message/set` create's `attachments` from its wire value `v`
765/// for target Chat `chat`; `Err` holds the SetError value.
766///
767/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce
768/// `maxAttachmentsPerMessage` at creation and update time"; it is checked
769/// first, so no entry is resolved past the cap, and is `tooLarge`, the
770/// error §Account-Level Capability Object names for `maxBodyBytes`. An
771/// entry with `filenodeId` goes to [`ChatBackend::filenode_attachment`]
772/// (draft-atwood-jmap-chat-filenode-00 §filenodeId). Any other entry, or
773/// one the hook leaves unresolved, must carry every Attachment field. Each
774/// result must pass [`valid_attachment`]. A malformed entry is
775/// `invalidProperties` naming `attachments`.
776async fn create_attachments<B: ChatBackend>(
777    backend: &B,
778    caller: &B::CallerCtx,
779    account_id: &Id,
780    limits: &ChatLimits,
781    chat: &Chat,
782    v: &Value,
783) -> Result<Vec<Attachment>, Value> {
784    let invalid = || json!({ "type": "invalidProperties", "properties": ["attachments"] });
785    let entries = v.as_array().ok_or_else(invalid)?;
786    if u64::try_from(entries.len()).map_or(true, |n| n > limits.max_attachments_per_message) {
787        return Err(json!({
788            "type": "tooLarge",
789            "description": format!(
790                "attachments exceed maxAttachmentsPerMessage ({})",
791                limits.max_attachments_per_message
792            ),
793        }));
794    }
795    let mut attachments = Vec::with_capacity(entries.len());
796    for entry in entries {
797        let requested = AttachmentCreate::deserialize(entry).map_err(|_| invalid())?;
798        let filled = if requested.filenode_id.is_some() {
799            match backend
800                .filenode_attachment(caller, account_id, chat, &requested)
801                .await
802            {
803                Ok(Ok(filled)) => filled,
804                Ok(Err(set_err)) => return Err(serde_json::Value::from(&set_err)),
805                Err(e) => return Err(server_fail_value_from_backend(&e)),
806            }
807        } else {
808            None
809        };
810        let attachment = match filled {
811            Some(a) => a,
812            None => Attachment::deserialize(entry).map_err(|_| invalid())?,
813        };
814        if !valid_attachment(&attachment) {
815            return Err(invalid());
816        }
817        attachments.push(attachment);
818    }
819    Ok(attachments)
820}
821
822/// draft-atwood-jmap-chat-00 §Attachment and §Input Validation:
823/// `filename` holds no `/`, `\` or null byte and `contentType` is a
824/// syntactically valid MIME type. `sha256` is lowercase hex by its type.
825///
826/// `size` and `sha256` are checked against the blob in [`check_attachments`].
827fn valid_attachment(a: &Attachment) -> bool {
828    !a.filename.contains(['/', '\\', '\0']) && valid_media_type(&a.content_type)
829}
830
831/// Enforce the size limit and blob checks on a `Message/set` create's
832/// `attachments` from [`create_attachments`]; `None` on success, else the
833/// SetError value.
834///
835/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce `maxBodyBytes`
836/// and `maxAttachmentBytes` at parse time, before any fetch or storage."
837/// The limit is `tooLarge`, the error §Account-Level Capability Object
838/// names for `maxBodyBytes`. Then each Attachment's `size` and `sha256` are
839/// checked against [`ChatBackend::attachment_blob`]; a mismatch is
840/// `invalidProperties` naming `attachments` (§Input Validation).
841async fn check_attachments<B: ChatBackend>(
842    backend: &B,
843    caller: &B::CallerCtx,
844    account_id: &Id,
845    limits: &ChatLimits,
846    attachments: &[Attachment],
847) -> Option<Value> {
848    if attachments
849        .iter()
850        .any(|a| a.size > limits.max_attachment_bytes)
851    {
852        return Some(json!({
853            "type": "tooLarge",
854            "description": format!(
855                "an attachment exceeds maxAttachmentBytes ({})",
856                limits.max_attachment_bytes
857            ),
858        }));
859    }
860    for a in attachments {
861        match backend
862            .attachment_blob(caller, account_id, &a.blob_id)
863            .await
864        {
865            Ok(Ok(None)) => {}
866            Ok(Ok(Some(blob))) => {
867                // Constant-time digest comparison (compliance tests §14.13:
868                // "Verify that blob hash comparison uses constant-time
869                // comparison").
870                if blob.size != a.size || !bool::from(a.sha256.to_bytes().ct_eq(&blob.sha256)) {
871                    return Some(json!({
872                        "type": "invalidProperties",
873                        "properties": ["attachments"],
874                        "description": format!(
875                            "attachment {} does not match the blob's size or sha256",
876                            a.blob_id
877                        ),
878                    }));
879                }
880            }
881            Ok(Err(set_err)) => return Some(serde_json::Value::from(&set_err)),
882            Err(e) => return Some(server_fail_value_from_backend(&e)),
883        }
884    }
885    None
886}
887
888/// RFC 2045 §5.1 `type "/" subtype`, each an RFC 2045 `token`.
889///
890/// ponytail: parameters after `;` are not parsed; add an RFC 2045
891/// parameter parser if they ever need validating.
892fn valid_media_type(s: &str) -> bool {
893    let is_token = |t: &str| {
894        !t.is_empty()
895            && t.bytes()
896                .all(|b| b.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?=".contains(&b))
897    };
898    let essence = s.split(';').next().unwrap_or_default().trim();
899    essence
900        .split_once('/')
901        .is_some_and(|(t, sub)| is_token(t) && is_token(sub))
902}
903
904// ---------------------------------------------------------------------------
905// Message/set
906// ---------------------------------------------------------------------------
907
908/// Create the owner's ReadPosition for each Chat in `chat_ids` that has
909/// none yet. draft-atwood-jmap-chat-00 §ReadPosition: "For direct and
910/// group Chats, a ReadPosition is created when the first message is
911/// delivered. For channel Chats, a ReadPosition is created when the
912/// owner joins the containing Space." Called by `Message/set` and by
913/// `Space/join` ([`crate::space::handle_space_join`]).
914///
915/// Best effort: the Messages are already stored, so a backend failure
916/// here must not become a method-level error (RFC 8620 §3.6.2: "the
917/// externally visible state of the server MUST NOT have changed if an
918/// error is returned at the method level"). A record missed here is
919/// created by the next delivery to that Chat. `alreadyExists` means a
920/// concurrent delivery created it first (see the ReadPosition uniqueness
921/// contract on `ChatBackend::create_object`).
922///
923/// ponytail: does not look up the Chat's kind, so `Message/set` also
924/// fills in a missing channel position (for example a channel added
925/// after the owner joined). One full ReadPosition scan per `Message/set` call that created a
926/// message; a backend with a `(account, chatId)` index can replace it.
927pub(crate) async fn ensure_read_positions<B: ChatBackend>(
928    backend: &B,
929    caller: &B::CallerCtx,
930    account_id: &Id,
931    mut chat_ids: Vec<Id>,
932) {
933    if chat_ids.is_empty() {
934        return;
935    }
936    let Ok((existing, _)) = backend
937        .get_objects::<ReadPosition>(caller, account_id, None, None)
938        .await
939    else {
940        return;
941    };
942    chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
943    chat_ids.dedup();
944    chat_ids.retain(|c| !existing.iter().any(|p| p.chat_id == *c));
945    for chat_id in chat_ids {
946        let _ = backend
947            .create_object(caller, account_id, chat_id.as_ref(), |id: &Id| {
948                ReadPosition::new(id.clone(), chat_id.clone())
949            })
950            .await;
951    }
952}
953
954/// Find the Message in `chat_id` whose `senderMsgId` is `sender_msg_id`.
955///
956/// draft-atwood-jmap-chat-00 §Message: "Servers MUST maintain a durable
957/// index of `senderMsgId` values per chat to support idempotent
958/// delivery, `Peer/retract` lookup, and resolution of `replyTo` /
959/// `threadRootId` references." The same `senderMsgId` in another Chat is
960/// a different Message.
961///
962/// ponytail: one full Message scan of the account per call, not an
963/// index. A backend with a `(chatId, senderMsgId)` index can serve the
964/// same contract from it once this becomes a hot path.
965///
966/// # Errors
967///
968/// Returns the backend error if reading the account's Messages fails.
969pub async fn find_message_by_sender_msg_id<B: ChatBackend>(
970    backend: &B,
971    caller: &B::CallerCtx,
972    account_id: &Id,
973    chat_id: &Id,
974    sender_msg_id: &Id,
975) -> Result<Option<Message>, B::Error> {
976    let (messages, _) = backend
977        .get_objects::<Message>(caller, account_id, None, None)
978        .await?;
979    Ok(messages
980        .into_iter()
981        .find(|m| m.chat_id == *chat_id && m.sender_msg_id == *sender_msg_id))
982}
983
984/// The result of [`store_server_message`].
985#[derive(Debug, Clone, PartialEq, Eq)]
986#[non_exhaustive]
987pub enum StoreOutcome {
988    /// The Message was stored under this server-assigned id.
989    Stored(Id),
990    /// The Chat already holds a Message with the same `senderMsgId`; this
991    /// is its id, and nothing was written.
992    Duplicate(Id),
993}
994
995/// Store a Message that the server, not a client, creates: for example a
996/// MIMI fanout Message (draft-atwood-jmap-chat-mimi-00
997/// §application/mimi-fanout) or a federation `Peer/deliver` Message.
998///
999/// `build` makes the Message for the id the backend assigns, as for
1000/// [`ChatBackend::create_object`]. It sets every other field, including
1001/// the server-set `senderMsgId`, `senderId`, `sentAt` and `receivedAt` and
1002/// a body type that [`ChatLimits::server_reserved_body_types`] keeps out
1003/// of `Message/set`. Its `chatId` and `senderMsgId` are then overwritten
1004/// with `chat_id` and `sender_msg_id`, so the stored Message always matches
1005/// the duplicate check. None of the `Message/set` client-input checks run.
1006///
1007/// Before storing, `chat_id` is searched for `sender_msg_id` with
1008/// [`find_message_by_sender_msg_id`]. A hit returns
1009/// [`StoreOutcome::Duplicate`] and writes nothing. The mimi draft
1010/// requires this: "The server MUST NOT store a FanoutMessage whose
1011/// `senderMsgId` it has already stored in the Chat". After a store, the
1012/// owner's ReadPosition for the Chat is created if missing and the
1013/// Chat's `unreadCount` is recomputed, as for `Message/set`
1014/// (draft-atwood-jmap-chat-00 §ReadPosition: "For direct and group
1015/// Chats, a ReadPosition is created when the first message is
1016/// delivered.").
1017///
1018/// ponytail: the duplicate check and the create are separate backend
1019/// calls. Two concurrent calls with one `senderMsgId` can both store, so
1020/// a caller that can race (such as parallel `/notify` deliveries)
1021/// serializes calls per Chat.
1022///
1023/// # Errors
1024///
1025/// Returns the backend's error from the lookup (as
1026/// [`BackendSetError::Other`]) or from
1027/// [`ChatBackend::create_object`], unchanged.
1028// Same error type as `ChatBackend::create_object`, passed through unboxed.
1029pub async fn store_server_message<B, F>(
1030    backend: &B,
1031    caller: &B::CallerCtx,
1032    account_id: &Id,
1033    chat_id: &Id,
1034    sender_msg_id: &Id,
1035    build: F,
1036) -> Result<StoreOutcome, BackendSetError<B::Error>>
1037where
1038    B: ChatBackend,
1039    F: FnOnce(&Id) -> Message + Send,
1040{
1041    if let Some(existing) =
1042        find_message_by_sender_msg_id(backend, caller, account_id, chat_id, sender_msg_id)
1043            .await
1044            .map_err(BackendSetError::Other)?
1045    {
1046        return Ok(StoreOutcome::Duplicate(existing.id));
1047    }
1048    let (chat, smid) = (chat_id.clone(), sender_msg_id.clone());
1049    let (id, stored) = backend
1050        .create_object(
1051            caller,
1052            account_id,
1053            sender_msg_id.as_ref(),
1054            move |id: &Id| {
1055                let mut m = build(id);
1056                m.chat_id = chat;
1057                m.sender_msg_id = smid;
1058                m
1059            },
1060        )
1061        .await?;
1062    ensure_read_positions(backend, caller, account_id, vec![stored.chat_id.clone()]).await;
1063    record_unread_count_changes(backend, caller, account_id, vec![stored.chat_id]).await;
1064    Ok(StoreOutcome::Stored(id))
1065}
1066
1067/// The owner's effective receipt-sharing preference for `chat_id`.
1068///
1069/// draft-atwood-jmap-chat-federation-00 §Peer/receipt "Sender Behavior":
1070/// "if `Chat.receiptSharing` is present for the relevant Chat, that value
1071/// is used; otherwise the account-level `PresenceStatus.receiptSharing`
1072/// applies". A missing PresenceStatus takes the draft-atwood-jmap-chat-00
1073/// default, `true`. A failed lookup yields `false`: the read has already
1074/// been written, and a receipt not shown to be permitted is not sent.
1075async fn shares_receipts<B: ChatBackend>(
1076    backend: &B,
1077    caller: &B::CallerCtx,
1078    account_id: &Id,
1079    chat_id: &Id,
1080) -> bool {
1081    let chat_override = match backend
1082        .get_objects::<Chat>(
1083            caller,
1084            account_id,
1085            Some(std::slice::from_ref(chat_id)),
1086            None,
1087        )
1088        .await
1089    {
1090        Ok((found, _not_found)) => found.first().and_then(|c| c.receipt_sharing),
1091        Err(_) => return false,
1092    };
1093    if let Some(shares) = chat_override {
1094        return shares;
1095    }
1096    match backend
1097        .get_objects::<PresenceStatus>(caller, account_id, None, None)
1098        .await
1099    {
1100        Ok((found, _not_found)) => found.first().is_none_or(|p| p.receipt_sharing),
1101        Err(_) => false,
1102    }
1103}
1104
1105/// The Message create properties that hold the id of another record, which a
1106/// client may set to a `#creationId` reference (RFC 8620 §5.3).
1107const MESSAGE_ID_PROPERTIES: &[&str] = &["chatId", "replyTo", "threadRootId"];
1108
1109/// A Mention `id`, a ChatContact id (draft-atwood-jmap-chat-00 §Mention),
1110/// as `(property, entry field, property named on failure)` for
1111/// [`resolve_entry_refs`].
1112const MENTION_ID: (&str, &str, &str) = ("mentions", "id", "mentions");
1113
1114/// An Attachment `filenodeId`, a FileNode id; failed validation names
1115/// `filenodeId` (draft-atwood-jmap-chat-filenode-00 §filenodeId).
1116const ATTACHMENT_FILENODE_ID: (&str, &str, &str) = ("attachments", "filenodeId", "filenodeId");
1117
1118/// Handle a `Message/set` method call (draft-atwood-jmap-chat-00 §Message).
1119///
1120/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
1121/// `ifInState`, optional `create` / `update` / `destroy` maps); the
1122/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
1123/// `oldState`, `newState`, plus the per-operation `created` /
1124/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
1125/// maps).
1126///
1127/// Validation enforced here (not in the backend):
1128/// - `chatId` and `body` are required on create.
1129/// - `id`, `senderMsgId`, `senderId`, `sentAt`, `receivedAt`, `deliveryState`
1130///   are server-set and rejected in updates.
1131///
1132/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1133///
1134/// A `chatId`, `replyTo` or `threadRootId` that is a `#creationId`
1135/// reference names a record created earlier in the request and resolves
1136/// against `created_ids` (pass [`jmap_server::CallContext::created_ids`]) or
1137/// against a create of this call, which runs replied-to messages first (RFC
1138/// 8620 §5.3). So does a Mention `id` in a create or an edit, and an
1139/// Attachment `filenodeId` in a create. An unknown reference is
1140/// `invalidProperties` naming the property (`filenodeId` for an
1141/// Attachment).
1142///
1143/// `using` is the request's capability list (pass
1144/// [`jmap_server::CallContext::using`]): a write to `metadata` or
1145/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
1146/// `invalidProperties` (draft-ietf-jmap-metadata-04 §3), as is `null` for
1147/// either in a create (-04 §3.2). The backend validates the rest.
1148pub async fn handle_message_set<B: ChatBackend>(
1149    backend: &B,
1150    caller: &B::CallerCtx,
1151    created_ids: &BTreeMap<Id, Id>,
1152    args: Value,
1153    using: &[String],
1154) -> Result<HandlerOutput, JmapError> {
1155    let (account_id, mut args) = extract_account_id(args)?;
1156
1157    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
1158    if !backend
1159        .account_exists(caller, &account_id)
1160        .await
1161        .map_err(|e| server_fail_from_backend(&e))?
1162    {
1163        return Err(JmapError::account_not_found());
1164    }
1165
1166    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
1167    // unbounded /set batches before touching the storage layer.
1168    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
1169
1170    let old_state = backend
1171        .get_state::<Message>(caller, &account_id)
1172        .await
1173        .map_err(|e| server_fail_from_backend(&e))?;
1174
1175    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
1176        && if_in_state != old_state.as_ref()
1177    {
1178        return Err(JmapError::state_mismatch());
1179    }
1180
1181    let mut created = serde_json::Map::new();
1182    let mut not_created = serde_json::Map::new();
1183    let mut updated = serde_json::Map::new();
1184    let mut not_updated = serde_json::Map::new();
1185    let mut destroyed_list: Vec<Value> = Vec::new();
1186    let mut not_destroyed = serde_json::Map::new();
1187    let mut mutated = false;
1188    let limits = backend.limits(caller, &account_id);
1189
1190    // -----------------------------------------------------------------------
1191    // create
1192    // -----------------------------------------------------------------------
1193    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
1194        let mut delivered_chat_ids: Vec<Id> = Vec::new();
1195        // RFC 8620 §5.3: creates of this call join the request-wide map so
1196        // later creates in this call can reference them.
1197        let mut created_ids = created_ids.clone();
1198        for (create_id, obj_val) in parents_first(create_map, &["replyTo", "threadRootId"]) {
1199            let resolved = match resolved_create(obj_val, MESSAGE_ID_PROPERTIES, &created_ids)
1200                .and_then(|mut v| {
1201                    resolve_entry_refs(&mut v, &[MENTION_ID, ATTACHMENT_FILENODE_ID], &created_ids)
1202                        .map(|()| v)
1203                }) {
1204                Ok(v) => v,
1205                Err(err) => {
1206                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1207                    continue;
1208                }
1209            };
1210            let obj_val = &resolved;
1211            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Message>) {
1212                not_created.insert(create_id.clone(), serde_json::Value::from(&err));
1213                continue;
1214            }
1215            if let Some(Err(err)) = obj_val
1216                .as_object()
1217                .map(|o| check_metadata_entry(o, true, using))
1218            {
1219                not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1220                continue;
1221            }
1222            // draft-ietf-jmap-metadata-04 §3.2: the create sets the
1223            // metadata properties; the backend validates them.
1224            let (metadata, private_metadata) = match create_metadata(obj_val) {
1225                Ok(maps) => maps,
1226                Err(err) => {
1227                    not_created.insert(create_id.clone(), err);
1228                    continue;
1229                }
1230            };
1231            // Optional properties: a wrongly-typed value is invalidProperties
1232            // (RFC 8620 §5.3), not a silent absence.
1233            if let Some(err) = mistyped_create_props(
1234                obj_val,
1235                &[
1236                    ("broadcastMentions", PropType::Array),
1237                    ("replyTo", PropType::Str),
1238                    ("threadRootId", PropType::Str),
1239                    ("senderExpiresAt", PropType::Str),
1240                    ("burnOnRead", PropType::Bool),
1241                ],
1242            ) {
1243                not_created.insert(create_id.clone(), err);
1244                continue;
1245            }
1246            let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
1247                not_created.insert(
1248                    create_id.clone(),
1249                    json!({ "type": "invalidProperties", "properties": ["chatId"] }),
1250                );
1251                continue;
1252            };
1253            let chat_id = match jmap_server::parse_wire_id(chat_id_str, "chatId") {
1254                Ok(id) => id,
1255                Err(err) => {
1256                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1257                    continue;
1258                }
1259            };
1260
1261            let Some(body) = obj_val
1262                .get("body")
1263                .and_then(|v| v.as_str())
1264                .map(str::to_owned)
1265            else {
1266                not_created.insert(
1267                    create_id.clone(),
1268                    json!({ "type": "invalidProperties", "properties": ["body"] }),
1269                );
1270                continue;
1271            };
1272            // §Account-Level Capability Object `maxBodyBytes`: "Servers
1273            // MUST reject messages exceeding this limit; in `Message/set`
1274            // the rejection is a `tooLarge` SetError."
1275            if u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes) {
1276                not_created.insert(
1277                    create_id.clone(),
1278                    json!({
1279                        "type": "tooLarge",
1280                        "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
1281                    }),
1282                );
1283                continue;
1284            }
1285
1286            // sentAt is a UTCDate per RFC 8620 §1.4 (20-char
1287            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
1288            // UTCDate::new_validated; a malformed value produces
1289            // invalidProperties rather than silently flowing through
1290            // to storage where downstream lex-compares and slice ops
1291            // (helpers::iso8601_before) assume a validated 20-byte
1292            // ASCII shape.
1293            let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
1294                not_created.insert(
1295                    create_id.clone(),
1296                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
1297                );
1298                continue;
1299            };
1300            let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
1301                not_created.insert(
1302                    create_id.clone(),
1303                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
1304                );
1305                continue;
1306            };
1307
1308            // §Input Validation: "`bodyType`: reject a value not listed in
1309            // `supportedBodyTypes`; in `Message/set` create, also reject a
1310            // type that a companion specification reserves for
1311            // server-created Messages."
1312            let Some(body_type) = obj_val
1313                .get("bodyType")
1314                .filter(|v| !v.is_null())
1315                .map_or(Some("text/plain"), Value::as_str)
1316                .filter(|s| limits.supported_body_types.contains(s))
1317            else {
1318                not_created.insert(
1319                    create_id.clone(),
1320                    json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
1321                );
1322                continue;
1323            };
1324            // draft-atwood-jmap-chat-mimi-00 §application/mimi-fanout, the
1325            // one reserving companion: "the server MUST reject a
1326            // `Message/set` create with this body type with an
1327            // `invalidProperties` SetError naming `bodyType`."
1328            if limits.server_reserved_body_types.contains(&body_type) {
1329                not_created.insert(
1330                    create_id.clone(),
1331                    json!({
1332                        "type": "invalidProperties",
1333                        "properties": ["bodyType"],
1334                        "description": format!("bodyType {body_type} is reserved for server-created Messages")
1335                    }),
1336                );
1337                continue;
1338            }
1339            let body_type = body_type.to_owned();
1340
1341            // §Fields Inside the Ciphertext: "an `invalidProperties`
1342            // SetError whose `properties` lists each such field".
1343            let conflicts =
1344                body_type_field_conflicts(obj_val, &body_type, limits.encrypted_body_types);
1345            if !conflicts.is_empty() {
1346                not_created.insert(
1347                    create_id.clone(),
1348                    json!({
1349                        "type": "invalidProperties",
1350                        "properties": conflicts,
1351                        "description": format!("must be empty or absent when bodyType is {body_type}"),
1352                    }),
1353                );
1354                continue;
1355            }
1356
1357            // BroadcastMention structural validation (§4.4.1 / §4.16).
1358            let broadcast_mentions_val: Vec<Value> = obj_val
1359                .get("broadcastMentions")
1360                .and_then(|v| v.as_array())
1361                .cloned()
1362                .unwrap_or_default();
1363            if let Some(err) = validate_broadcast_mentions(&broadcast_mentions_val) {
1364                not_created.insert(create_id.clone(), err);
1365                continue;
1366            }
1367
1368            // draft-atwood-jmap-chat-00 §Input Validation: "`chatId`:
1369            // verify per {{chat-id}} — confirm match with stored id"; a
1370            // failed check is "an `invalidProperties` SetError ... whose
1371            // `properties` names the offending property".
1372            let chat = match backend
1373                .get_objects::<Chat>(
1374                    caller,
1375                    &account_id,
1376                    Some(std::slice::from_ref(&chat_id)),
1377                    None,
1378                )
1379                .await
1380            {
1381                Ok((found, _)) => match found.into_iter().next() {
1382                    Some(chat) => chat,
1383                    None => {
1384                        not_created.insert(
1385                            create_id.clone(),
1386                            json!({
1387                                "type": "invalidProperties",
1388                                "properties": ["chatId"],
1389                                "description": format!("no Chat with id {chat_id}"),
1390                            }),
1391                        );
1392                        continue;
1393                    }
1394                },
1395                Err(e) => {
1396                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1397                    continue;
1398                }
1399            };
1400
1401            match backend.may_create_message(caller, &account_id, &chat).await {
1402                Ok(Ok(())) => {}
1403                Ok(Err(set_err)) => {
1404                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1405                    continue;
1406                }
1407                Err(e) => {
1408                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1409                    continue;
1410                }
1411            }
1412
1413            // draft-atwood-jmap-chat-00 §Chat `closedAt`: "After it is
1414            // set, the server MUST reject with a `forbidden` SetError
1415            // every `Message/set` create in this Chat".
1416            if chat.closed_at.is_some() {
1417                not_created.insert(
1418                    create_id.clone(),
1419                    json!({ "type": "forbidden", "description": "the group is closed" }),
1420                );
1421                continue;
1422            }
1423
1424            // draft-atwood-jmap-chat-00 §Space `closedAt`: "After it is
1425            // set, the Space's channels are read-only: the server MUST
1426            // reject every `Message/set` create in them with a
1427            // `forbidden` SetError."
1428            if let Some(sid) = &chat.space_id {
1429                match backend
1430                    .get_objects::<Space>(
1431                        caller,
1432                        &account_id,
1433                        Some(std::slice::from_ref(sid)),
1434                        None,
1435                    )
1436                    .await
1437                {
1438                    Ok((spaces, _)) if spaces.first().is_some_and(|s| s.closed_at.is_some()) => {
1439                        not_created.insert(
1440                            create_id.clone(),
1441                            json!({ "type": "forbidden", "description": "the Space is closed" }),
1442                        );
1443                        continue;
1444                    }
1445                    Ok(_) => {}
1446                    Err(e) => {
1447                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1448                        continue;
1449                    }
1450                }
1451            }
1452
1453            // draft-atwood-jmap-chat-00 §Message/set: the sender MUST be a
1454            // current member of the target Chat and, in a channel, hold
1455            // `"send"`; otherwise `forbidden`.
1456            match backend
1457                .may_send_message(caller, &account_id, &chat_id)
1458                .await
1459            {
1460                Ok(Ok(())) => {}
1461                Ok(Err(set_err)) => {
1462                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1463                    continue;
1464                }
1465                Err(e) => {
1466                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1467                    continue;
1468                }
1469            }
1470
1471            // BroadcastMention permission check (§4.4.1).
1472            // Non-empty broadcastMentions in a Space-backed channel
1473            // requires mention_broadcast permission; rich-body spans are
1474            // display-only and never consulted (§Rich Body Format).
1475            // Group/direct chats (no spaceId) are unrestricted per spec.
1476            if let Some(sid) = chat
1477                .space_id
1478                .as_ref()
1479                .filter(|_| !broadcast_mentions_val.is_empty())
1480            {
1481                match backend
1482                    .may_broadcast_mention(caller, &account_id, sid, &chat_id)
1483                    .await
1484                {
1485                    Ok(Ok(())) => {}
1486                    Ok(Err(set_err)) => {
1487                        not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1488                        continue;
1489                    }
1490                    Err(e) => {
1491                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1492                        continue;
1493                    }
1494                }
1495            }
1496
1497            let reply_to: Option<Id> = match obj_val.get("replyTo").and_then(|v| v.as_str()) {
1498                Some(s) => match jmap_server::parse_wire_id(s, "replyTo") {
1499                    Ok(id) => Some(id),
1500                    Err(err) => {
1501                        not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1502                        continue;
1503                    }
1504                },
1505                None => None,
1506            };
1507
1508            let supplied_root: Option<Id> =
1509                match obj_val.get("threadRootId").and_then(|v| v.as_str()) {
1510                    Some(s) => match jmap_server::parse_wire_id(s, "threadRootId") {
1511                        Ok(id) => Some(id),
1512                        Err(err) => {
1513                            not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1514                            continue;
1515                        }
1516                    },
1517                    None => None,
1518                };
1519
1520            // §Message `replyTo`: "Servers MUST validate that this ID
1521            // exists in the same Chat before storing." §Thread Model:
1522            // the root of a reply is the referenced message's
1523            // `threadRootId`, or the referenced message itself when that
1524            // is absent; a message with no `replyTo` has no root.
1525            // "Servers SHOULD validate them and MAY correct
1526            // `threadRootId`": a wrong value is rejected and an omitted
1527            // one is filled in. §Input Validation names no other error,
1528            // so both failures are `invalidProperties`.
1529            let expected_root: Option<Id> = match reply_to.as_ref() {
1530                None => None,
1531                Some(parent_id) => {
1532                    let parent = match backend
1533                        .get_objects::<Message>(
1534                            caller,
1535                            &account_id,
1536                            Some(std::slice::from_ref(parent_id)),
1537                            None,
1538                        )
1539                        .await
1540                    {
1541                        Ok((found, _)) => found.into_iter().find(|m| m.chat_id == chat_id),
1542                        Err(e) => {
1543                            not_created
1544                                .insert(create_id.clone(), server_fail_value_from_backend(&e));
1545                            continue;
1546                        }
1547                    };
1548                    let Some(parent) = parent else {
1549                        not_created.insert(
1550                            create_id.clone(),
1551                            json!({
1552                                "type": "invalidProperties",
1553                                "properties": ["replyTo"],
1554                                "description": "replyTo is not a Message in this Chat",
1555                            }),
1556                        );
1557                        continue;
1558                    };
1559                    Some(parent.thread_root_id.unwrap_or(parent.id))
1560                }
1561            };
1562            if supplied_root.is_some() && supplied_root != expected_root {
1563                not_created.insert(
1564                    create_id.clone(),
1565                    json!({
1566                        "type": "invalidProperties",
1567                        "properties": ["threadRootId"],
1568                        "description": "threadRootId does not match the thread of replyTo",
1569                    }),
1570                );
1571                continue;
1572            }
1573            let thread_root_id = expected_root;
1574
1575            // senderExpiresAt is a UTCDate per RFC 8620 §1.4 (20-char
1576            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
1577            // UTCDate::new_validated; a malformed value produces
1578            // invalidProperties rather than silently flowing through to
1579            // a downstream string compare with undefined ordering.
1580            let sender_expires_at: Option<UTCDate> =
1581                if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
1582                    let Ok(d) = UTCDate::new_validated(s) else {
1583                        not_created.insert(
1584                            create_id.clone(),
1585                            json!({
1586                                "type": "invalidProperties",
1587                                "properties": ["senderExpiresAt"],
1588                            }),
1589                        );
1590                        continue;
1591                    };
1592                    Some(d)
1593                } else {
1594                    None
1595                };
1596
1597            let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
1598
1599            if let Some(ref expires_at) = sender_expires_at {
1600                let now = now_utc_string();
1601                if !iso8601_before(&now, expires_at) {
1602                    not_created.insert(
1603                        create_id.clone(),
1604                        json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
1605                    );
1606                    continue;
1607                }
1608            }
1609
1610            let now_str = now_utc_string();
1611            let received_at: UTCDate = UTCDate::from(now_str.as_ref());
1612
1613            let mut attachments = Vec::new();
1614            if let Some(v) = obj_val.get("attachments").filter(|v| !v.is_null()) {
1615                match create_attachments(backend, caller, &account_id, &limits, &chat, v).await {
1616                    Ok(a) => attachments = a,
1617                    Err(err) => {
1618                        not_created.insert(create_id.clone(), err);
1619                        continue;
1620                    }
1621                }
1622            }
1623            let apply_optionals = match apply_create_optionals(obj_val) {
1624                Ok(f) => f,
1625                Err(property) => {
1626                    not_created.insert(
1627                        create_id.clone(),
1628                        json!({ "type": "invalidProperties", "properties": [property] }),
1629                    );
1630                    continue;
1631                }
1632            };
1633            if let Some(err) =
1634                check_attachments(backend, caller, &account_id, &limits, &attachments).await
1635            {
1636                not_created.insert(create_id.clone(), err);
1637                continue;
1638            }
1639
1640            // Slow-mode rate-limit gate (draft-atwood-jmap-chat-00
1641            // §Chat `slowModeSeconds` + spec commit `de60acb`).
1642            //
1643            // Runs AFTER wire-format validation so malformed requests
1644            // don't consume rate-tracker slots, and BEFORE the
1645            // `create_object` call so a throttled sender never sees the
1646            // message touch storage. On a Throttled return the backend
1647            // tells us when the caller may retry; we surface that
1648            // verbatim as the `serverRetryAfter` extra field on the
1649            // `rateLimit` SetError, built via the typed
1650            // `SetError::with_extra` builder added in bd:JMAP-dha0.
1651            // The spec requires "a `rateLimit` SetError ({{RFC8620,
1652            // Section 5.3}}) on the offending `Message/set` create",
1653            // not the method-level `rateLimited` (which is reserved
1654            // for the Peer/* methods). `serverRetryAfter` is a
1655            // workspace extension field. The reference `MemoryBackend`
1656            // never returns an Err here.
1657            if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
1658                let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
1659                let set_err = SetError::new(SetErrorType::RateLimit)
1660                    .with_description("Slow mode is active for this chat")
1661                    .with_extra("serverRetryAfter", json!(retry_after_str));
1662                not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1663                continue;
1664            }
1665
1666            // draft-atwood-jmap-chat-00 §Message `senderMsgId`: "Equals
1667            // `id` for messages composed by the owner."
1668            let build = |id: &Id| {
1669                let mut msg = Message::new(
1670                    id.clone(),
1671                    id.clone(),
1672                    account_id.clone(),
1673                    chat_id,
1674                    body,
1675                    body_type,
1676                    sent_at,
1677                    received_at,
1678                    DeliveryState::Pending,
1679                );
1680                msg.reply_to = reply_to;
1681                msg.thread_root_id = thread_root_id;
1682                msg.sender_expires_at = sender_expires_at;
1683                msg.burn_on_read = burn_on_read;
1684                msg.attachments = attachments;
1685                msg.metadata = metadata;
1686                msg.private_metadata = private_metadata;
1687                apply_optionals(&mut msg);
1688                msg
1689            };
1690            match backend
1691                .create_object::<Message, _>(caller, &account_id, create_id, build)
1692                .await
1693            {
1694                Ok((server_id, created_obj)) => {
1695                    mutated = true;
1696                    created_ids.insert(Id::from(create_id.as_str()), server_id);
1697                    delivered_chat_ids.push(created_obj.chat_id.clone());
1698                    // draft-atwood-jmap-chat-00 §Message/set: the server
1699                    // sets the server-assigned fields "then enqueues the
1700                    // message for outbound delivery".
1701                    let event = OutboundEvent::NewMessage {
1702                        chat_id: created_obj.chat_id.clone(),
1703                        message_id: created_obj.id.clone(),
1704                        sender_msg_id: created_obj.sender_msg_id.clone(),
1705                    };
1706                    backend.on_outbound_event(caller, &account_id, &event).await;
1707                    created.insert(
1708                        create_id.clone(),
1709                        jmap_server::serialize_value(&created_obj)?,
1710                    );
1711                }
1712                Err(e) => {
1713                    not_created.insert(create_id.clone(), backend_set_error_value(e));
1714                }
1715            }
1716        }
1717        ensure_read_positions(backend, caller, &account_id, delivered_chat_ids.clone()).await;
1718        record_unread_count_changes(backend, caller, &account_id, delivered_chat_ids).await;
1719    }
1720
1721    // -----------------------------------------------------------------------
1722    // update
1723    // -----------------------------------------------------------------------
1724    if let Some(Value::Object(update_map)) = args.remove("update") {
1725        for (id_str, mut patch_val) in update_map {
1726            let id = match jmap_server::parse_wire_id(&id_str, "id") {
1727                Ok(id) => id,
1728                Err(err) => {
1729                    not_updated.insert(id_str, serde_json::Value::from(&*err));
1730                    continue;
1731                }
1732            };
1733            // An edit may replace `mentions`; `attachments` is immutable.
1734            if let Err(err) = resolve_entry_refs(&mut patch_val, &[MENTION_ID], created_ids) {
1735                not_updated.insert(id_str, serde_json::Value::from(&*err));
1736                continue;
1737            }
1738
1739            // RFC 8620 §5.3: "There MUST NOT be two patches in the
1740            // PatchObject where the pointer of one is the prefix of the
1741            // pointer of the other" or the update "MUST be rejected with an
1742            // "invalidPatch" error".
1743            if patch_val.get("reactions").is_some()
1744                && patch_val
1745                    .as_object()
1746                    .is_some_and(|obj| obj.keys().any(|k| k.starts_with("reactions/")))
1747            {
1748                not_updated.insert(
1749                    id_str,
1750                    json!({
1751                        "type": "invalidPatch",
1752                        "description":
1753                            "patch must not combine top-level `reactions` with `reactions/{id}` entries",
1754                    }),
1755                );
1756                continue;
1757            }
1758
1759            // draft-atwood-jmap-chat-00 §Message/set defines the only
1760            // client updates: Editing (`body`, `bodyType`, `mentions`,
1761            // `broadcastMentions`), Adding and Removing Reactions
1762            // (`reactions/<senderReactionId>` JSON Pointer keys), Deleting
1763            // (`deletedAt`, `deletedForAll`) and Marking as Read (`readAt`,
1764            // `readDisposition`): the client-settable Message properties
1765            // that are not immutable, with `reactions` changed only per
1766            // entry. Every other key names a server-set or immutable
1767            // property, so it is rejected with RFC 8620 §5.3
1768            // `invalidProperties`. draft-ietf-jmap-metadata-04 §3.2 adds
1769            // `metadata` and `privateMetadata`, written whole or by patch
1770            // path.
1771            let bad_props: Vec<&str> = patch_val
1772                .as_object()
1773                .map(|obj| {
1774                    obj.keys()
1775                        .map(String::as_str)
1776                        .filter(|&k| {
1777                            !(k.starts_with("reactions/")
1778                                || is_metadata_key(k)
1779                                || (k != "reactions" && is_client_updatable::<Message>(k)))
1780                        })
1781                        .collect()
1782                })
1783                .unwrap_or_default();
1784            if !bad_props.is_empty() {
1785                not_updated.insert(
1786                    id_str,
1787                    json!({ "type": "invalidProperties", "properties": bad_props }),
1788                );
1789                continue;
1790            }
1791            if let Some(Err(err)) = patch_val
1792                .as_object()
1793                .map(|o| check_metadata_entry(o, false, using))
1794            {
1795                not_updated.insert(id_str, serde_json::Value::from(&*err));
1796                continue;
1797            }
1798
1799            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "the
1800            // server MUST reject an update that sets `readDisposition`
1801            // without `readAt` with an `invalidProperties` SetError naming
1802            // `readDisposition`." A null `readAt` clears it, not sets it.
1803            let sets = |field: &str| patch_val.get(field).is_some_and(|v| !v.is_null());
1804            if sets("readDisposition") && !sets("readAt") {
1805                not_updated.insert(
1806                    id_str,
1807                    json!({ "type": "invalidProperties", "properties": ["readDisposition"] }),
1808                );
1809                continue;
1810            }
1811
1812            // §Input Validation: "`bodyType`: reject a value not listed in
1813            // `supportedBodyTypes`".
1814            if patch_val.get("bodyType").is_some_and(|v| {
1815                !v.as_str()
1816                    .is_some_and(|s| limits.supported_body_types.contains(&s))
1817            }) {
1818                not_updated.insert(
1819                    id_str,
1820                    json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
1821                );
1822                continue;
1823            }
1824
1825            // The stored Message and its Chat, read once for every check
1826            // below. A Message or Chat that does not resolve is left for
1827            // update_object to surface `notFound`.
1828            let stored = match backend
1829                .get_objects::<Message>(caller, &account_id, Some(std::slice::from_ref(&id)), None)
1830                .await
1831            {
1832                Ok((found, _)) => found.into_iter().next(),
1833                Err(e) => {
1834                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
1835                    continue;
1836                }
1837            };
1838            let stored_chat = match &stored {
1839                Some(msg) => match backend
1840                    .get_objects::<Chat>(
1841                        caller,
1842                        &account_id,
1843                        Some(std::slice::from_ref(&msg.chat_id)),
1844                        None,
1845                    )
1846                    .await
1847                {
1848                    Ok((found, _)) => found.into_iter().next(),
1849                    Err(e) => {
1850                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
1851                        continue;
1852                    }
1853                },
1854                None => None,
1855            };
1856
1857            // Per-Chat restrictions of extension-bound Chats; see
1858            // `ChatBackend::may_update_message`.
1859            if let (Some(msg), Some(chat)) = (&stored, &stored_chat) {
1860                let patch_keys: Vec<&str> = patch_val
1861                    .as_object()
1862                    .map(|obj| obj.keys().map(String::as_str).collect())
1863                    .unwrap_or_default();
1864                match backend
1865                    .may_update_message(caller, &account_id, chat, msg, &patch_keys)
1866                    .await
1867                {
1868                    Ok(Ok(())) => {}
1869                    Ok(Err(set_err)) => {
1870                        not_updated.insert(id_str, serde_json::Value::from(&set_err));
1871                        continue;
1872                    }
1873                    Err(e) => {
1874                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
1875                        continue;
1876                    }
1877                }
1878            }
1879
1880            // draft-atwood-jmap-chat-00 §Deleting a Message: servers MUST
1881            // reject `deletedForAll: true` when `senderId` is not the
1882            // accountId. §Editing a Message: an edit of `body`, `bodyType`,
1883            // `mentions` or `broadcastMentions` is only permitted where
1884            // `senderId` is the accountId and `deletedAt` is absent; any other edit is
1885            // `forbidden`. A missing target falls through to the normal
1886            // `notFound` from `update_object`.
1887            let deletes_for_all =
1888                patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
1889            let edits = ["body", "bodyType", "mentions", "broadcastMentions"]
1890                .iter()
1891                .any(|&field| patch_val.get(field).is_some());
1892            // The event for `ChatBackend::on_outbound_event`, built from
1893            // the stored Message once the checks below pass.
1894            let mut outbound: Option<OutboundEvent> = None;
1895            if deletes_for_all || edits {
1896                let description = stored.as_ref().and_then(|m| {
1897                    if deletes_for_all && m.sender_id != account_id {
1898                        Some("deletedForAll is only permitted on messages whose senderId is the accountId")
1899                    } else if edits && (m.sender_id != account_id || m.deleted_at.is_some()) {
1900                        Some("edits are only permitted on messages whose senderId is the accountId and deletedAt is absent")
1901                    } else {
1902                        None
1903                    }
1904                });
1905                if let Some(description) = description {
1906                    not_updated.insert(
1907                        id_str,
1908                        json!({ "type": "forbidden", "description": description }),
1909                    );
1910                    continue;
1911                }
1912                if let Some(err) = stored
1913                    .as_ref()
1914                    .and_then(|m| edit_limit_error(m, &patch_val, &limits))
1915                {
1916                    not_updated.insert(id_str, err);
1917                    continue;
1918                }
1919                outbound = stored.as_ref().map(|m| {
1920                    let (chat_id, message_id, sender_msg_id) =
1921                        (m.chat_id.clone(), m.id.clone(), m.sender_msg_id.clone());
1922                    if deletes_for_all {
1923                        OutboundEvent::Retract {
1924                            chat_id,
1925                            message_id,
1926                            sender_msg_id,
1927                        }
1928                    } else {
1929                        OutboundEvent::Edit {
1930                            chat_id,
1931                            message_id,
1932                            sender_msg_id,
1933                        }
1934                    }
1935                });
1936            }
1937
1938            // Build augmented patch with server-side timestamps.
1939            let mut augmented = patch_val;
1940            if augmented.get("body").is_some()
1941                && let Some(obj) = augmented.as_object_mut()
1942            {
1943                obj.insert("editedAt".to_owned(), json!(now_utc_string()));
1944            }
1945            // draft-atwood-jmap-chat-00 §Message deletedAt: a deleted
1946            // Message has an empty `body`, empty `attachments`, and no
1947            // `editHistory`, whether the deletion is local or for all. The
1948            // merge-patch null purges the stored revisions rather than
1949            // merely hiding them.
1950            let deletes =
1951                deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
1952            if deletes && let Some(obj) = augmented.as_object_mut() {
1953                if deletes_for_all {
1954                    obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
1955                }
1956                obj.insert("body".to_owned(), json!(""));
1957                obj.insert("attachments".to_owned(), json!([]));
1958                obj.insert("editHistory".to_owned(), Value::Null);
1959            }
1960            // Spec §557 + §1029: when readAt is set without readDisposition, default to "displayed".
1961            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "Absent
1962            // when `readAt` is not set." so clearing readAt clears it too.
1963            if let Some(obj) = augmented.as_object_mut() {
1964                match obj.get("readAt") {
1965                    Some(Value::Null) => {
1966                        obj.insert("readDisposition".to_owned(), Value::Null);
1967                    }
1968                    Some(_) if !obj.contains_key("readDisposition") => {
1969                        obj.insert("readDisposition".to_owned(), json!("displayed"));
1970                    }
1971                    _ => {}
1972                }
1973            }
1974
1975            // Reaction patch processing
1976            // (draft-atwood-jmap-chat-00 §Message/set, §Reaction).
1977            //
1978            // Reactions are added/removed by patching
1979            // `reactions/{senderReactionId}` as RFC 8620 §5.3 JSON
1980            // Pointer entries:
1981            //
1982            // - value is an object: add or modify the reaction
1983            // - value is `null`: remove the reaction
1984            //
1985            // The backend applies these paths into the stored
1986            // `reactions` map. Before forwarding, the handler:
1987            //
1988            // 1. Rejects `reactions/{id}` keys containing `/` or `~`
1989            //    (RFC 6901 escape characters — the chat-client also
1990            //    rejects them; this is defense-in-depth).
1991            // 2. Rejects non-null non-object values as `invalidPatch`.
1992            // 3. Pre-fetches the Message and rejects with `forbidden`
1993            //    if the patched key targets an existing reaction whose
1994            //    `senderId` is not the accountId — per spec, only the
1995            //    original sender may modify their own reactions.
1996            // 4. Server-overrides `senderId` to the accountId on every add
1997            //    (spec MUST; defense-in-depth).
1998            // 5. Server-injects `sentAt` to the current time on adds
1999            //    that lack it, so the resulting `Reaction` round-trips
2000            //    through the typed shape (which requires `sentAt`).
2001            let reaction_pointer_keys: Vec<String> = augmented
2002                .as_object()
2003                .map(|obj| {
2004                    obj.keys()
2005                        .filter(|k| k.starts_with("reactions/"))
2006                        .cloned()
2007                        .collect()
2008                })
2009                .unwrap_or_default();
2010
2011            // One `OutboundEvent::ReactionUpdate` per patched key, built
2012            // from the pre-fetched Message and reported after the write.
2013            let mut reaction_events: Vec<OutboundEvent> = Vec::new();
2014            if !reaction_pointer_keys.is_empty() {
2015                // Validate each pointer key + value shape. The
2016                // `.collect::<Result<Vec<_>, _>>()` form short-circuits
2017                // on the first Err and is the idiomatic Rust expression
2018                // of "validate-or-fail" over an iterator. A future
2019                // contributor adding a new validation rule appends an
2020                // `if ... { return Err(...) }` inside the closure; the
2021                // short-circuit behavior is structural, not a hand-coded
2022                // flag invariant.
2023                let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
2024                    .iter()
2025                    .map(|raw_key| {
2026                        let suffix = &raw_key["reactions/".len()..];
2027                        if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
2028                            return Err(format!(
2029                                "reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
2030                            ));
2031                        }
2032                        let val = augmented.get(raw_key).unwrap_or(&Value::Null);
2033                        if !val.is_null() {
2034                            let ok = val.as_object().is_some_and(|m| {
2035                                m.get("emoji")
2036                                    .and_then(|v| v.as_str())
2037                                    .is_some_and(|s| !s.is_empty())
2038                            });
2039                            if !ok {
2040                                return Err(format!(
2041                                    "reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
2042                                ));
2043                            }
2044                        }
2045                        Ok((raw_key.clone(), suffix.to_owned()))
2046                    })
2047                    .collect();
2048                let decoded = match decoded {
2049                    Ok(d) => d,
2050                    Err(desc) => {
2051                        not_updated.insert(
2052                            id_str,
2053                            json!({ "type": "invalidPatch", "description": desc }),
2054                        );
2055                        continue;
2056                    }
2057                };
2058
2059                // Inspect the stored Message's existing reactions. An
2060                // update target that doesn't exist on the backend will
2061                // surface a normal `notFound` from the subsequent
2062                // `update_object` call — we don't short-circuit here.
2063                let mut forbidden: Vec<String> = Vec::new();
2064                if let Some(msg) = &stored {
2065                    for (raw_key, suffix) in &decoded {
2066                        let existing = msg.reactions.get(suffix);
2067                        if existing.is_some_and(|r| r.sender_id != account_id) {
2068                            forbidden.push(suffix.clone());
2069                        }
2070                        // A null on a key with no stored reaction
2071                        // removes nothing, so nothing propagates.
2072                        let action = match augmented.get(raw_key) {
2073                            Some(Value::Object(_)) => Some(ReactionAction::Add),
2074                            _ => existing.map(|r| ReactionAction::Remove { removed: r.clone() }),
2075                        };
2076                        if let Some(action) = action {
2077                            reaction_events.push(OutboundEvent::ReactionUpdate {
2078                                chat_id: msg.chat_id.clone(),
2079                                message_id: msg.id.clone(),
2080                                sender_msg_id: msg.sender_msg_id.clone(),
2081                                sender_reaction_id: suffix.clone(),
2082                                action,
2083                            });
2084                        }
2085                    }
2086                }
2087                if !forbidden.is_empty() {
2088                    not_updated.insert(
2089                        id_str,
2090                        json!({
2091                            "type": "forbidden",
2092                            "description": format!(
2093                                "cannot modify reactions authored by another sender: {}",
2094                                forbidden.join(", "),
2095                            ),
2096                        }),
2097                    );
2098                    continue;
2099                }
2100
2101                // Server-override `senderId` and inject `sentAt` where
2102                // absent on every `reactions/{key}` add, so the stored
2103                // Reaction round-trips through the typed shape.
2104                let now_str = now_utc_string();
2105                if let Some(obj) = augmented.as_object_mut() {
2106                    for (raw_key, _) in &decoded {
2107                        if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
2108                            // Spec MUST: server overrides senderId to
2109                            // the accountId on every add, regardless of
2110                            // what the client supplied.
2111                            map.insert("senderId".to_owned(), json!(account_id));
2112                            map.entry("sentAt").or_insert_with(|| json!(now_str));
2113                        }
2114                    }
2115                }
2116            }
2117
2118            // Detect a non-null readAt assignment in the patch. A
2119            // `readAt: null` is a PatchObject clear (RFC 8620 §5.3), not a
2120            // "mark as read" event, so it does not trigger burn-on-read.
2121            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: the
2122            // receiving server MUST hard-delete immediately after setting
2123            // readAt on a message whose `burnOnRead` is `true`.
2124            let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
2125
2126            // If the patch sets readAt, the stored Message decides whether
2127            // it is burn-on-read. We deliberately consult the pre-patch
2128            // state: a recipient setting readAt for the first time should
2129            // fire the burn. draft-atwood-jmap-chat-00 §Message
2130            // `burnOnRead`: "Applies only to the receiving mailbox; the
2131            // sender's own copy is not affected."
2132            let pre_patch_read: Option<Message> = if patch_sets_read_at {
2133                stored.clone()
2134            } else {
2135                None
2136            };
2137            let pre_patch_burn_on_read = pre_patch_read
2138                .as_ref()
2139                .is_some_and(|m| m.burn_on_read == Some(true) && m.sender_id != account_id);
2140
2141            // BroadcastMention validation and permission check on edit
2142            // (§4.4.1 / §4.16). The post-patch broadcastMentions fall back
2143            // to the stored message where the patch leaves them unchanged,
2144            // so an edit that retains a broadcast mention is gated like one
2145            // that adds it.
2146            if edits {
2147                // A missing Message is left for update_object to surface
2148                // the normal notFound error downstream.
2149                let current_has_bm = stored
2150                    .as_ref()
2151                    .is_some_and(|msg| !msg.broadcast_mentions.is_empty());
2152                // Structural validation only when broadcastMentions is part
2153                // of the patch.
2154                let has_bm = match augmented.get("broadcastMentions") {
2155                    Some(bm) => {
2156                        let bm_arr: Vec<Value> = bm.as_array().cloned().unwrap_or_default();
2157                        if let Some(err) = validate_broadcast_mentions(&bm_arr) {
2158                            not_updated.insert(id_str, err);
2159                            continue;
2160                        }
2161                        !bm_arr.is_empty()
2162                    }
2163                    None => current_has_bm,
2164                };
2165
2166                // BroadcastMention permission check on update (§4.4.1).
2167                // A post-patch broadcastMentions entry in a Space-backed
2168                // channel requires mention_broadcast permission; rich-body
2169                // spans are display-only and never consulted. Group/direct
2170                // chats (no spaceId) are unrestricted per spec.
2171                // A Message or Chat not found is left for update_object
2172                // to surface downstream.
2173                let channel = stored_chat
2174                    .as_ref()
2175                    .and_then(|c| Some((c.space_id.as_ref()?, &c.id)));
2176                if let (true, Some((sid, chat_id))) = (has_bm, channel) {
2177                    match backend
2178                        .may_broadcast_mention(caller, &account_id, sid, chat_id)
2179                        .await
2180                    {
2181                        Ok(Ok(())) => {}
2182                        Ok(Err(set_err)) => {
2183                            not_updated.insert(id_str, serde_json::Value::from(&set_err));
2184                            continue;
2185                        }
2186                        Err(e) => {
2187                            not_updated.insert(id_str, server_fail_value_from_backend(&e));
2188                            continue;
2189                        }
2190                    }
2191                }
2192            }
2193
2194            // draft-atwood-jmap-chat-federation-00 §Peer/receipt: the
2195            // owner read a Message another participant sent. The read
2196            // fields come from the patch, since a burned Message is gone.
2197            let receipt = pre_patch_read
2198                .filter(|m| m.sender_id != account_id)
2199                .and_then(|m| {
2200                    let read_at =
2201                        serde_json::from_value::<UTCDate>(augmented.get("readAt")?.clone()).ok()?;
2202                    let read_disposition = augmented
2203                        .get("readDisposition")
2204                        .and_then(|v| serde_json::from_value(v.clone()).ok());
2205                    Some(OutboundEvent::Receipt {
2206                        chat_id: m.chat_id,
2207                        message_id: m.id,
2208                        sender_msg_id: m.sender_msg_id,
2209                        read_at,
2210                        read_disposition,
2211                    })
2212                });
2213            // Convert the augmented wire-format Value into a typed
2214            // PatchObject (RFC 8620 §5.3). Non-object values yield
2215            // invalidPatch.
2216            let patch = match serde_json::from_value::<PatchObject>(augmented) {
2217                Ok(p) => p,
2218                Err(e) => {
2219                    not_updated.insert(
2220                        id_str,
2221                        json!({ "type": "invalidPatch", "description": e.to_string() }),
2222                    );
2223                    continue;
2224                }
2225            };
2226            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: "MUST
2227            // permanently hard-delete this message (row removal, not
2228            // tombstone) immediately after setting `readAt`." One atomic
2229            // backend call, so a failure commits nothing and a retry
2230            // burns again.
2231            let burns = patch_sets_read_at && pre_patch_burn_on_read;
2232            let update_outcome = if burns {
2233                backend
2234                    .read_and_burn_message(caller, &account_id, &id, patch)
2235                    .await
2236                    .map(|()| None)
2237            } else {
2238                backend
2239                    .update_object::<Message>(caller, &account_id, &id, patch)
2240                    .await
2241            };
2242            let maybe_updated_obj = match update_outcome {
2243                Ok(maybe_obj) => maybe_obj,
2244                Err(e) => {
2245                    not_updated.insert(id_str, backend_set_error_value(e));
2246                    continue;
2247                }
2248            };
2249
2250            // Update (or burn) succeeded.
2251            mutated = true;
2252            // draft-atwood-jmap-chat-federation-00 §Peer/retract "Sender
2253            // Behavior": an update that sets `deletedForAll: true` "MUST
2254            // send `Peer/retract` to the server of every other participant
2255            // in the Chat". Reported only once the update is written, so a
2256            // failed write retracts nothing on peers.
2257            if let Some(event @ OutboundEvent::Retract { .. }) = &outbound {
2258                backend.on_outbound_event(caller, &account_id, event).await;
2259            }
2260            // draft-atwood-jmap-chat-00 §Editing a Message: "Send
2261            // `Peer/deliver` carrying an `edit` payload to all
2262            // recipients". A patch that also deletes or burns the Message
2263            // leaves nothing to deliver.
2264            if let Some(event @ OutboundEvent::Edit { .. }) = &outbound
2265                && !deletes
2266                && !burns
2267            {
2268                backend.on_outbound_event(caller, &account_id, event).await;
2269            }
2270            // draft-atwood-jmap-chat-00 §Adding and Removing Reactions:
2271            // propagate each add and removal "via `Peer/deliver`
2272            // `reactionUpdate` payload". As for edits, a patch that also
2273            // deletes or burns the Message leaves nothing to deliver.
2274            if !deletes && !burns {
2275                for event in &reaction_events {
2276                    backend.on_outbound_event(caller, &account_id, event).await;
2277                }
2278            }
2279            // §Peer/receipt "Sender Behavior": "If the effective preference
2280            // is `false`, the server MUST NOT invoke `Peer/receipt`". A
2281            // burned Message was still read, so its receipt is reported.
2282            if let Some(event @ OutboundEvent::Receipt { chat_id, .. }) = &receipt
2283                && shares_receipts(backend, caller, &account_id, chat_id).await
2284            {
2285                backend.on_outbound_event(caller, &account_id, event).await;
2286            }
2287            match maybe_updated_obj {
2288                Some(obj) => {
2289                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
2290                }
2291                None => {
2292                    updated.insert(id_str, Value::Null);
2293                }
2294            }
2295        }
2296    }
2297
2298    // -----------------------------------------------------------------------
2299    // destroy
2300    // -----------------------------------------------------------------------
2301    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
2302        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
2303        // Reject the whole request if any element is non-string rather than
2304        // silently skipping it, which would produce a misleading response.
2305        let id_strs: Vec<&str> = destroy_arr
2306            .iter()
2307            .map(|v| {
2308                v.as_str().ok_or_else(|| {
2309                    JmapError::invalid_arguments(format!(
2310                        "destroy: every element must be a string Id; got {}",
2311                        jmap_server::json_type_name(v)
2312                    ))
2313                })
2314            })
2315            .collect::<Result<_, _>>()?;
2316        // The destroyed Messages' Chats, read before the destroy, for
2317        // `record_unread_count_changes` (§Chat `unreadCount`).
2318        // A malformed id is skipped here and rejected per entry below.
2319        let destroy_ids: Vec<Id> = destroy_arr
2320            .iter()
2321            .filter_map(Value::as_str)
2322            .filter_map(|s| Id::new_validated(s).ok())
2323            .collect();
2324        let chat_of: HashMap<Id, Id> = backend
2325            .get_objects::<Message>(caller, &account_id, Some(&destroy_ids), None)
2326            .await
2327            .map(|(found, _)| found.into_iter().map(|m| (m.id, m.chat_id)).collect())
2328            .unwrap_or_default();
2329        let mut destroyed_chat_ids: Vec<Id> = Vec::new();
2330        for id_str in id_strs {
2331            let id = match jmap_server::parse_wire_id(id_str, "id") {
2332                Ok(id) => id,
2333                Err(err) => {
2334                    not_destroyed.insert(id_str.to_owned(), serde_json::Value::from(&*err));
2335                    continue;
2336                }
2337            };
2338
2339            match backend
2340                .destroy_object::<Message>(caller, &account_id, &id)
2341                .await
2342            {
2343                Ok(()) => {
2344                    mutated = true;
2345                    destroyed_chat_ids.extend(chat_of.get(&id).cloned());
2346                    destroyed_list.push(Value::String(id_str.to_owned()));
2347                }
2348                Err(e) => {
2349                    not_destroyed.insert(id_str.to_owned(), backend_set_error_value(e));
2350                }
2351            }
2352        }
2353        record_unread_count_changes(backend, caller, &account_id, destroyed_chat_ids).await;
2354    }
2355
2356    finalize_set_response::<B, Message>(
2357        backend,
2358        caller,
2359        &account_id,
2360        old_state,
2361        mutated,
2362        SetAccumulators {
2363            created,
2364            updated,
2365            destroyed: destroyed_list,
2366            not_created,
2367            not_updated,
2368            not_destroyed,
2369        },
2370    )
2371    .await
2372}
2373
2374#[cfg(test)]
2375mod tests {
2376    use super::*;
2377    use crate::memory::MemoryBackend;
2378    use serde_json::json;
2379
2380    const ACCOUNT_ID: &str = "a1";
2381
2382    // Oracles in this module are hand-built per workspace test-integrity
2383    // policy. Each test asserts the wire shape of a known-invalid or
2384    // known-valid broadcastMentions payload against the validation rules
2385    // from spec §4.4.1 / §4.16. The independent oracle is the spec text
2386    // itself; no assertion uses the code under test as its own reference.
2387
2388    /// §BroadcastMention: "Servers MUST reject a BroadcastMention with an
2389    /// unrecognized `scope` value; in `Message/set` the rejection is an
2390    /// `invalidProperties` SetError naming `broadcastMentions`."
2391    #[tokio::test]
2392    async fn broadcast_mention_validation_rejects_unknown_scope() {
2393        let backend = MemoryBackend::new();
2394        backend.register_account(&Id::from(ACCOUNT_ID));
2395        let HandlerOutput { primary: resp, .. } = handle_message_set(
2396            &backend,
2397            &(),
2398            &std::collections::BTreeMap::new(),
2399            json!({
2400                "accountId": ACCOUNT_ID,
2401                "create": {
2402                    "m0": {
2403                        "chatId": "c1",
2404                        "body": "Hello @channel",
2405                        "sentAt": "2024-01-01T00:00:00Z",
2406                        "broadcastMentions": [
2407                            { "scope": "channel", "offset": 6, "length": 8 }
2408                        ]
2409                    }
2410                }
2411            }),
2412            &[],
2413        )
2414        .await
2415        .expect("handle_message_set");
2416
2417        assert!(resp["notCreated"]["m0"].is_object());
2418        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidProperties");
2419        assert_eq!(
2420            resp["notCreated"]["m0"]["properties"],
2421            json!(["broadcastMentions"])
2422        );
2423        let desc = resp["notCreated"]["m0"]["description"]
2424            .as_str()
2425            .expect("description");
2426        assert!(
2427            desc.contains("unrecognized scope"),
2428            "expected 'unrecognized scope' in description, got: {desc}"
2429        );
2430    }
2431
2432    /// A valid @everyone mention at the correct body offset succeeds.
2433    #[tokio::test]
2434    async fn broadcast_mention_validation_accepts_valid() {
2435        let backend = MemoryBackend::new();
2436        let chat_id = make_group_chat(&backend).await;
2437        let body = "Hello @everyone!";
2438        let HandlerOutput { primary: resp, .. } = handle_message_set(
2439            &backend,
2440            &(),
2441            &std::collections::BTreeMap::new(),
2442            json!({
2443                "accountId": ACCOUNT_ID,
2444                "create": {
2445                    "m0": {
2446                        "chatId": chat_id,
2447                        "body": body,
2448                        "sentAt": "2024-01-01T00:00:00Z",
2449                        "broadcastMentions": [
2450                            { "scope": "everyone", "offset": 6, "length": 9 }
2451                        ]
2452                    }
2453                }
2454            }),
2455            &[],
2456        )
2457        .await
2458        .expect("handle_message_set");
2459
2460        assert!(
2461            resp["created"]["m0"].is_object(),
2462            "expected created, got notCreated: {}",
2463            resp["notCreated"]["m0"]
2464        );
2465    }
2466
2467    /// An empty broadcastMentions array is always valid.
2468    #[tokio::test]
2469    async fn broadcast_mention_validation_accepts_empty() {
2470        let backend = MemoryBackend::new();
2471        let chat_id = make_group_chat(&backend).await;
2472        let HandlerOutput { primary: resp, .. } = handle_message_set(
2473            &backend,
2474            &(),
2475            &std::collections::BTreeMap::new(),
2476            json!({
2477                "accountId": ACCOUNT_ID,
2478                "create": {
2479                    "m0": {
2480                        "chatId": chat_id,
2481                        "body": "Hello, world!",
2482                        "sentAt": "2024-01-01T00:00:00Z",
2483                        "broadcastMentions": []
2484                    }
2485                }
2486            }),
2487            &[],
2488        )
2489        .await
2490        .expect("handle_message_set");
2491
2492        assert!(
2493            resp["created"]["m0"].is_object(),
2494            "expected created, got notCreated: {}",
2495            resp["notCreated"]["m0"]
2496        );
2497    }
2498
2499    // -----------------------------------------------------------------------
2500    // BroadcastMention permission-check tests (§4.4.1 mention_broadcast)
2501    //
2502    // Oracle: the spec text itself. Group/direct chats without a spaceId
2503    // are unrestricted; channel chats with a spaceId must pass the
2504    // mention_broadcast gate. The channel fixture's owner role holds
2505    // mention_broadcast, so these tests verify the handler CODE PATH is
2506    // wired correctly and that the gate is skipped or invoked in the
2507    // right circumstances; tests/message_broadcast_permission_memory.rs
2508    // covers denial.
2509    // -----------------------------------------------------------------------
2510
2511    /// Helper: create a group Chat (no spaceId) via handle_chat_set and
2512    /// return its server-assigned id.
2513    async fn make_group_chat(backend: &MemoryBackend) -> String {
2514        backend.register_account(&Id::from(ACCOUNT_ID));
2515        let HandlerOutput { primary: resp, .. } = crate::chat::handle_chat_set(
2516            backend,
2517            &(),
2518            &std::collections::BTreeMap::new(),
2519            json!({
2520                "accountId": ACCOUNT_ID,
2521                "create": { "c0": { "kind": "group", "name": "test-group" } }
2522            }),
2523            &[],
2524        )
2525        .await
2526        .expect("make_group_chat");
2527        resp["created"]["c0"]["id"]
2528            .as_str()
2529            .expect("group chat id")
2530            .to_owned()
2531    }
2532
2533    /// Helper: seed a Space whose owner member (the accountId, per
2534    /// §SpaceMember `id`) holds `manage_channels` and `send` (§Message/set:
2535    /// "For channel Chats, the server MUST verify the sender holds the
2536    /// `"send"` permission"), then create a channel Chat inside it, and
2537    /// return the channel's server-assigned id.
2538    async fn make_channel_chat(backend: &MemoryBackend) -> String {
2539        let space_id = "s0";
2540        backend.insert_object_for_test(
2541            "Space",
2542            ACCOUNT_ID,
2543            space_id,
2544            json!({
2545                "id": space_id,
2546                "name": "test-space",
2547                "createdAt": "2026-01-01T00:00:00Z",
2548                "memberCount": 1,
2549                "categories": [],
2550                "uncategorizedChannelIds": [],
2551                "isPublic": false,
2552                "isPubliclyPreviewable": false,
2553                "roles": [{ "id": "r-owner", "name": "Owner", "permissions": ["manage_channels", "mention_broadcast", "send"], "position": 10 }],
2554                "members": [{ "id": ACCOUNT_ID, "roleIds": ["r-owner"], "joinedAt": "2026-01-01T00:00:00Z" }],
2555            }),
2556        );
2557
2558        // Create a channel Chat in that Space. §Chat/set: "Channel Chats
2559        // are created exclusively via the `addChannels` patch key in
2560        // `Space/set`." §Space/set `addChannels`: "Requires
2561        // `"manage_channels"`."
2562        crate::space::handle_space_set(
2563            backend,
2564            &(),
2565            &std::collections::BTreeMap::new(),
2566            json!({
2567                "accountId": ACCOUNT_ID,
2568                "update": { space_id: { "addChannels": [{ "name": "general" }] } }
2569            }),
2570            &[],
2571        )
2572        .await
2573        .expect("make_channel_chat: addChannels");
2574        let HandlerOutput {
2575            primary: get_resp, ..
2576        } = crate::space::handle_space_get(
2577            backend,
2578            &(),
2579            json!({ "accountId": ACCOUNT_ID, "ids": [space_id] }),
2580            &[],
2581        )
2582        .await
2583        .expect("make_channel_chat: Space/get");
2584        get_resp["list"][0]["uncategorizedChannelIds"][0]
2585            .as_str()
2586            .expect("channel chat id")
2587            .to_owned()
2588    }
2589
2590    /// Create a Message with broadcastMentions in a group chat (no spaceId).
2591    /// The permission check must be SKIPPED (unrestricted per spec),
2592    /// and the message must succeed.
2593    #[tokio::test]
2594    async fn broadcast_mention_create_without_space_unrestricted() {
2595        let backend = MemoryBackend::new();
2596        let chat_id = make_group_chat(&backend).await;
2597
2598        let body = "Hello @everyone!";
2599        let HandlerOutput { primary: resp, .. } = handle_message_set(
2600            &backend,
2601            &(),
2602            &std::collections::BTreeMap::new(),
2603            json!({
2604                "accountId": ACCOUNT_ID,
2605                "create": {
2606                    "m0": {
2607                        "chatId": chat_id,
2608                        "body": body,
2609                        "sentAt": "2024-01-01T00:00:00Z",
2610                        "broadcastMentions": [
2611                            { "scope": "everyone", "offset": 6, "length": 9 }
2612                        ]
2613                    }
2614                }
2615            }),
2616            &[],
2617        )
2618        .await
2619        .expect("handle_message_set");
2620
2621        assert!(
2622            resp["created"]["m0"].is_object(),
2623            "expected created in group chat (no spaceId), got notCreated: {}",
2624            resp["notCreated"]["m0"]
2625        );
2626    }
2627
2628    /// Create a Message with broadcastMentions in a channel chat (has spaceId).
2629    /// The owner holds mention_broadcast in the Space, so the message
2630    /// must succeed.
2631    #[tokio::test]
2632    async fn broadcast_mention_create_in_channel_succeeds() {
2633        let backend = MemoryBackend::new();
2634        let chat_id = make_channel_chat(&backend).await;
2635
2636        let body = "Hello @everyone!";
2637        let HandlerOutput { primary: resp, .. } = handle_message_set(
2638            &backend,
2639            &(),
2640            &std::collections::BTreeMap::new(),
2641            json!({
2642                "accountId": ACCOUNT_ID,
2643                "create": {
2644                    "m0": {
2645                        "chatId": chat_id,
2646                        "body": body,
2647                        "sentAt": "2024-01-01T00:00:00Z",
2648                        "broadcastMentions": [
2649                            { "scope": "everyone", "offset": 6, "length": 9 }
2650                        ]
2651                    }
2652                }
2653            }),
2654            &[],
2655        )
2656        .await
2657        .expect("handle_message_set");
2658
2659        assert!(
2660            resp["created"]["m0"].is_object(),
2661            "expected created in channel chat, got notCreated: {}",
2662            resp["notCreated"]["m0"]
2663        );
2664    }
2665
2666    /// Create a Message with empty broadcastMentions in a channel chat.
2667    /// The permission check must NOT fire (empty array skips the gate).
2668    #[tokio::test]
2669    async fn broadcast_mention_create_empty_skips_permission_check() {
2670        let backend = MemoryBackend::new();
2671        let chat_id = make_channel_chat(&backend).await;
2672
2673        let HandlerOutput { primary: resp, .. } = handle_message_set(
2674            &backend,
2675            &(),
2676            &std::collections::BTreeMap::new(),
2677            json!({
2678                "accountId": ACCOUNT_ID,
2679                "create": {
2680                    "m0": {
2681                        "chatId": chat_id,
2682                        "body": "Hello, world!",
2683                        "sentAt": "2024-01-01T00:00:00Z",
2684                        "broadcastMentions": []
2685                    }
2686                }
2687            }),
2688            &[],
2689        )
2690        .await
2691        .expect("handle_message_set");
2692
2693        assert!(
2694            resp["created"]["m0"].is_object(),
2695            "expected created with empty broadcastMentions, got notCreated: {}",
2696            resp["notCreated"]["m0"]
2697        );
2698    }
2699
2700    /// Update a Message to retain non-empty broadcastMentions in a channel chat.
2701    /// The owner holds mention_broadcast in the Space, so the update
2702    /// must succeed.
2703    #[tokio::test]
2704    async fn broadcast_mention_update_retaining_broadcast_succeeds() {
2705        let backend = MemoryBackend::new();
2706        let chat_id = make_channel_chat(&backend).await;
2707
2708        // Create a message with broadcastMentions first.
2709        let body = "Hello @everyone!";
2710        let HandlerOutput {
2711            primary: create_resp,
2712            ..
2713        } = handle_message_set(
2714            &backend,
2715            &(),
2716            &std::collections::BTreeMap::new(),
2717            json!({
2718                "accountId": ACCOUNT_ID,
2719                "create": {
2720                    "m0": {
2721                        "chatId": chat_id,
2722                        "body": body,
2723                        "sentAt": "2024-01-01T00:00:00Z",
2724                        "broadcastMentions": [
2725                            { "scope": "everyone", "offset": 6, "length": 9 }
2726                        ]
2727                    }
2728                }
2729            }),
2730            &[],
2731        )
2732        .await
2733        .expect("create message");
2734        let msg_id = create_resp["created"]["m0"]["id"]
2735            .as_str()
2736            .expect("message id");
2737
2738        // Update the message, retaining a non-empty broadcastMentions.
2739        let new_body = "Hey @here now!";
2740        let HandlerOutput {
2741            primary: update_resp,
2742            ..
2743        } = handle_message_set(
2744            &backend,
2745            &(),
2746            &std::collections::BTreeMap::new(),
2747            json!({
2748                "accountId": ACCOUNT_ID,
2749                "update": {
2750                    (msg_id): {
2751                        "body": new_body,
2752                        "broadcastMentions": [
2753                            { "scope": "here", "offset": 4, "length": 5 }
2754                        ]
2755                    }
2756                }
2757            }),
2758            &[],
2759        )
2760        .await
2761        .expect("update message");
2762
2763        assert!(
2764            update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
2765            "expected updated, got notUpdated: {}",
2766            update_resp["notUpdated"][msg_id]
2767        );
2768        assert!(
2769            update_resp["notUpdated"].is_null()
2770                || !update_resp["notUpdated"]
2771                    .as_object()
2772                    .is_some_and(|m| m.contains_key(msg_id)),
2773            "message should not be in notUpdated"
2774        );
2775    }
2776}