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