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