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 `Vec<Invocation>` carries any back-reference 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
19//! (`accountNotFound`, `invalidArguments`, `stateMismatch`, `serverFail`,
20//! `unsupportedFilter`, `unsupportedSort`, `cannotCalculateChanges` —
21//! per RFC 8620 §3.6 and §5). Per-target failures inside `/set`
22//! (including the `slow_mode_check` `rateLimited` and reaction-patch
23//! `invalidPatch` paths) surface in the `notCreated` / `notUpdated` /
24//! `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.
25
26use jmap_chat_types::{Chat, DeliveryState, Message, SenderId, BROADCAST_MENTION_SCOPES};
27use jmap_types::{Id, Invocation, JmapError, PatchObject, State, UTCDate};
28use serde_json::{json, Value};
29
30use crate::backend::{BackendSetError, ChatBackend, SetError, SetErrorType};
31use std::collections::HashSet;
32
33use crate::helpers::{
34    enforce_max_objects_in_set, extract_account_id, filter_properties, finalize_set_response,
35    iso8601_before, not_found_json, now_utc_string, serialize_value, set_error_value,
36    SetAccumulators,
37};
38use jmap_server::{server_fail_from_backend, server_fail_value_from_backend};
39
40// ---------------------------------------------------------------------------
41// Message/get
42// ---------------------------------------------------------------------------
43
44/// Handle a `Message/get` method call (draft-atwood-jmap-chat-00 §Message).
45///
46/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
47/// `ids`, optional `properties`); the returned `Value` is the §5.1
48/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
49///
50/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
51pub async fn handle_message_get<B: ChatBackend>(
52    backend: &B,
53    caller: &B::CallerCtx,
54    args: Value,
55) -> Result<(Value, Vec<Invocation>), JmapError> {
56    let (account_id, mut args) = extract_account_id(args)?;
57
58    let ids: Option<Vec<Id>> = match args.remove("ids") {
59        None | Some(Value::Null) => None,
60        Some(v) => Some(
61            serde_json::from_value(v)
62                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
63        ),
64    };
65
66    // RFC 8620 §5.1: when `properties` is specified, return only those fields
67    // (plus `id` which is always included). `None` means return all fields.
68    let properties: Option<Vec<String>> = match args.remove("properties") {
69        None | Some(Value::Null) => None,
70        Some(v) => Some(
71            serde_json::from_value(v)
72                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
73        ),
74    };
75
76    let ids_slice = ids.as_deref();
77    let (mut list, not_found) = backend
78        .get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
79        .await
80        .map_err(|e| server_fail_from_backend(&e))?;
81
82    // Edit-history retention gate (draft-atwood-jmap-chat-00 commit
83    // `0783fc4` + §Message editHistory). When the backend does not
84    // retain edit history, the `editHistory` field MUST be omitted
85    // from every returned Message. Setting `edit_history = None`
86    // here causes serde's `skip_serializing_if = "Option::is_none"`
87    // to collapse it on the wire, satisfying the spec MUST.
88    //
89    // `Message/changes` per RFC 8620 §5.2 returns id arrays only
90    // (no Message objects), so the spec's "omit from /changes" has
91    // no wire-level effect — only `Message/get` needs this gate.
92    if !backend.retains_edit_history() {
93        for msg in list.iter_mut() {
94            msg.edit_history = None;
95        }
96    }
97
98    let state = backend
99        .get_state::<Message>(caller, &account_id)
100        .await
101        .map_err(|e| server_fail_from_backend(&e))?;
102
103    let list_json: Vec<Value> = if let Some(ref props) = properties {
104        let mut prop_set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
105        prop_set.insert("id");
106        list.iter()
107            .map(|obj| {
108                let val = serialize_value(obj)?;
109                Ok(filter_properties(&val, &prop_set))
110            })
111            .collect::<Result<Vec<_>, JmapError>>()?
112    } else {
113        list.iter()
114            .map(serialize_value)
115            .collect::<Result<Vec<_>, _>>()?
116    };
117
118    Ok((
119        json!({
120            "accountId": account_id.as_ref(),
121            "state": state.as_ref(),
122            "list": list_json,
123            "notFound": not_found_json(&not_found),
124        }),
125        vec![],
126    ))
127}
128
129// ---------------------------------------------------------------------------
130// Message/changes
131// ---------------------------------------------------------------------------
132
133/// Handle a `Message/changes` method call (draft-atwood-jmap-chat-00 §Message).
134///
135/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
136/// `sinceState`, optional `maxChanges`); the returned `Value` is the
137/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
138/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
139///
140/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
141pub async fn handle_message_changes<B: ChatBackend>(
142    backend: &B,
143    caller: &B::CallerCtx,
144    args: Value,
145) -> Result<(Value, Vec<Invocation>), JmapError> {
146    jmap_server::handlers::handle_changes::<Message, B>(backend, caller, args).await
147}
148
149// ---------------------------------------------------------------------------
150// Message/query
151// ---------------------------------------------------------------------------
152
153/// Handle a `Message/query` method call (draft-atwood-jmap-chat-00 §Message).
154///
155/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
156/// `filter`, optional `sort`, optional `position` / `anchor` /
157/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
158/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
159/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
160/// `total`, optional `limit`).
161///
162/// Filter and sort are passed through to the backend unchanged.
163///
164/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
165pub async fn handle_message_query<B: ChatBackend>(
166    backend: &B,
167    caller: &B::CallerCtx,
168    args: Value,
169) -> Result<(Value, Vec<Invocation>), JmapError> {
170    let (account_id, mut args) = extract_account_id(args)?;
171
172    let calculate_total: bool = args
173        .get("calculateTotal")
174        .and_then(|v| v.as_bool())
175        .unwrap_or(false);
176
177    let limit: Option<u64> = match args.remove("limit") {
178        None | Some(Value::Null) => None,
179        Some(v) => match v.as_u64() {
180            Some(n) => Some(n),
181            None => {
182                return Err(JmapError::invalid_arguments(format!(
183                    "limit: expected a non-negative integer, got {v}"
184                )))
185            }
186        },
187    };
188
189    let position: i64 = match args.remove("position") {
190        None | Some(Value::Null) => 0,
191        Some(v) => v.as_i64().ok_or_else(|| {
192            JmapError::invalid_arguments(format!("position: expected an integer, got {v}"))
193        })?,
194    };
195
196    let filter: Option<serde_json::Value> = match args.remove("filter") {
197        None | Some(Value::Null) => None,
198        Some(v) => Some(v),
199    };
200
201    // JMAP Chat spec §Message — chatId filter is required unless hasMention: true.
202    let has_chat_id = filter
203        .as_ref()
204        .and_then(|f| f.get("chatId"))
205        .map(|v| !v.is_null())
206        .unwrap_or(false);
207    let has_mention_true = filter
208        .as_ref()
209        .and_then(|f| f.get("hasMention"))
210        .and_then(|v| v.as_bool())
211        .unwrap_or(false);
212    if !has_chat_id && !has_mention_true {
213        return Err(JmapError::unsupported_filter());
214    }
215
216    let sort: Option<Vec<serde_json::Value>> = match args.remove("sort") {
217        None | Some(Value::Null) => None,
218        Some(v) => Some(
219            serde_json::from_value(v)
220                .map_err(|_| JmapError::invalid_arguments("sort must be an array"))?,
221        ),
222    };
223
224    let result = backend
225        .query_objects::<Message>(
226            caller,
227            &account_id,
228            filter.as_ref(),
229            sort.as_deref(),
230            limit,
231            position,
232        )
233        .await
234        .map_err(|e| server_fail_from_backend(&e))?;
235
236    let mut resp = json!({
237        "accountId": account_id.as_ref(),
238        "queryState": result.query_state.as_ref(),
239        "canCalculateChanges": result.can_calculate_changes,
240        "position": result.position,
241        "ids": result.ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
242    });
243    if calculate_total {
244        if let Some(t) = result.total {
245            resp["total"] = json!(t);
246        }
247    }
248
249    Ok((resp, vec![]))
250}
251
252// ---------------------------------------------------------------------------
253// Message/queryChanges
254// ---------------------------------------------------------------------------
255
256/// Handle a `Message/queryChanges` method call (draft-atwood-jmap-chat-00 §Message).
257///
258/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
259/// optional `filter`, optional `sort`, `sinceQueryState`, optional
260/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
261/// returned `Value` is the §5.6 `/queryChanges` response shape
262/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
263/// `removed`, `added`).
264///
265/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
266pub async fn handle_message_query_changes<B: ChatBackend>(
267    backend: &B,
268    caller: &B::CallerCtx,
269    args: Value,
270) -> Result<(Value, Vec<Invocation>), JmapError> {
271    let (account_id, args) = extract_account_id(args)?;
272
273    let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
274        Some(s) => State::from(s),
275        None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
276    };
277
278    let max_changes: Option<u64> = match args.get("maxChanges") {
279        None | Some(Value::Null) => None,
280        Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
281            JmapError::invalid_arguments("maxChanges must be a positive integer")
282        })?),
283    };
284
285    let up_to_id: Option<Id> = match args.get("upToId") {
286        None | Some(Value::Null) => None,
287        // Id::from: wire-boundary validation deferred to JMAP-k9va; backend rejects unknown IDs.
288        Some(Value::String(s)) => Some(Id::from(s.as_str())),
289        Some(_) => {
290            return Err(JmapError::invalid_arguments(
291                "upToId must be a string Id or null",
292            ))
293        }
294    };
295
296    let calculate_total: bool = args
297        .get("calculateTotal")
298        .and_then(|v| v.as_bool())
299        .unwrap_or(false);
300
301    let result = backend
302        .query_changes::<Message>(
303            caller,
304            &account_id,
305            &since_query_state,
306            None,
307            None,
308            max_changes,
309            up_to_id.as_ref(),
310            false,
311        )
312        .await
313        .map_err(JmapError::from)?;
314
315    let removed: Vec<&str> = result.removed.iter().map(|id| id.as_ref()).collect();
316    let added: Vec<Value> = result
317        .added
318        .iter()
319        .map(|item| {
320            json!({
321                "id": item.id.as_ref(),
322                "index": item.index,
323            })
324        })
325        .collect();
326
327    let mut resp = json!({
328        "accountId": account_id.as_ref(),
329        "oldQueryState": result.old_query_state.as_ref(),
330        "newQueryState": result.new_query_state.as_ref(),
331        "removed": removed,
332        "added": added,
333    });
334    if calculate_total {
335        if let Some(t) = result.total {
336            resp["total"] = json!(t);
337        }
338    }
339
340    Ok((resp, vec![]))
341}
342
343// ---------------------------------------------------------------------------
344// BroadcastMention validation
345// ---------------------------------------------------------------------------
346
347/// Validate broadcast mentions against spec §4.4.1 / §4.16 constraints.
348///
349/// Returns an error description string on failure, None on success.
350fn validate_broadcast_mentions(
351    broadcast_mentions: &[serde_json::Value],
352    body: &str,
353    body_type: &str,
354) -> Option<String> {
355    // Rich body: broadcastMentions MUST be empty
356    if body_type == "application/jmap-chat-rich" && !broadcast_mentions.is_empty() {
357        return Some(
358            "broadcastMentions must be empty when bodyType is application/jmap-chat-rich".into(),
359        );
360    }
361    for (i, bm) in broadcast_mentions.iter().enumerate() {
362        // scope validation
363        let scope = match bm.get("scope").and_then(|v| v.as_str()) {
364            Some(s) => s,
365            None => {
366                return Some(format!(
367                    "broadcastMentions[{i}]: missing or non-string scope"
368                ));
369            }
370        };
371        if !BROADCAST_MENTION_SCOPES.contains(&scope) {
372            return Some(format!(
373                "broadcastMentions[{i}]: unrecognized scope \"{scope}\""
374            ));
375        }
376        // offset + length bounds check with overflow protection
377        let offset = bm.get("offset").and_then(|v| v.as_u64()).unwrap_or(0);
378        let length = bm.get("length").and_then(|v| v.as_u64()).unwrap_or(0);
379        let end = match offset.checked_add(length) {
380            Some(e) => e,
381            None => {
382                return Some(format!(
383                    "broadcastMentions[{i}]: offset + length overflows u64"
384                ));
385            }
386        };
387        let body_len = body.len() as u64;
388        if end > body_len {
389            return Some(format!(
390                "broadcastMentions[{i}]: offset({offset}) + length({length}) = {end} exceeds body byte length {body_len}"
391            ));
392        }
393    }
394    None
395}
396
397// ---------------------------------------------------------------------------
398// Message/set
399// ---------------------------------------------------------------------------
400
401/// Handle a `Message/set` method call (draft-atwood-jmap-chat-00 §Message).
402///
403/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
404/// `ifInState`, optional `create` / `update` / `destroy` maps); the
405/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
406/// `oldState`, `newState`, plus the per-operation `created` /
407/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
408/// maps).
409///
410/// Validation enforced here (not in the backend):
411/// - `chatId` and `body` are required on create.
412/// - `id`, `senderMsgId`, `senderId`, `sentAt`, `receivedAt`, `deliveryState`
413///   are server-set and rejected in updates.
414///
415/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
416pub async fn handle_message_set<B: ChatBackend>(
417    backend: &B,
418    caller: &B::CallerCtx,
419    args: Value,
420) -> Result<(Value, Vec<Invocation>), JmapError> {
421    let (account_id, mut args) = extract_account_id(args)?;
422
423    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
424    // unbounded /set batches before touching the storage layer.
425    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
426
427    let old_state = backend
428        .get_state::<Message>(caller, &account_id)
429        .await
430        .map_err(|e| server_fail_from_backend(&e))?;
431
432    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
433        if if_in_state != old_state.as_ref() {
434            return Err(JmapError::state_mismatch());
435        }
436    }
437
438    let mut created = serde_json::Map::new();
439    let mut not_created = serde_json::Map::new();
440    let mut updated = serde_json::Map::new();
441    let mut not_updated = serde_json::Map::new();
442    let mut destroyed_list: Vec<Value> = Vec::new();
443    let mut not_destroyed = serde_json::Map::new();
444    let mut mutated = false;
445
446    // -----------------------------------------------------------------------
447    // create
448    // -----------------------------------------------------------------------
449    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
450        for (create_id, obj_val) in create_map {
451            let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
452                not_created.insert(
453                    create_id.clone(),
454                    json!({ "type": "invalidProperties", "properties": ["chatId"] }),
455                );
456                continue;
457            };
458            let chat_id = Id::from(chat_id_str);
459
460            let Some(body) = obj_val
461                .get("body")
462                .and_then(|v| v.as_str())
463                .map(str::to_owned)
464            else {
465                not_created.insert(
466                    create_id.clone(),
467                    json!({ "type": "invalidProperties", "properties": ["body"] }),
468                );
469                continue;
470            };
471            if body.len() > 100_000 {
472                not_created.insert(
473                    create_id.clone(),
474                    json!({ "type": "invalidProperties", "properties": ["body"] }),
475                );
476                continue;
477            }
478
479            // sentAt is a UTCDate per RFC 8620 §1.4 (20-char
480            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
481            // UTCDate::new_validated; a malformed value produces
482            // invalidProperties rather than silently flowing through
483            // to storage where downstream lex-compares and slice ops
484            // (helpers::iso8601_before) assume a validated 20-byte
485            // ASCII shape.
486            let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
487                not_created.insert(
488                    create_id.clone(),
489                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
490                );
491                continue;
492            };
493            let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
494                not_created.insert(
495                    create_id.clone(),
496                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
497                );
498                continue;
499            };
500
501            let body_type = obj_val
502                .get("bodyType")
503                .and_then(|v| v.as_str())
504                .unwrap_or("text/plain")
505                .to_owned();
506
507            // BroadcastMention structural validation (§4.4.1 / §4.16).
508            let broadcast_mentions_val: Vec<Value> = obj_val
509                .get("broadcastMentions")
510                .and_then(|v| v.as_array())
511                .cloned()
512                .unwrap_or_default();
513            if let Some(desc) =
514                validate_broadcast_mentions(&broadcast_mentions_val, &body, &body_type)
515            {
516                not_created.insert(
517                    create_id.clone(),
518                    json!({ "type": "invalidArguments", "description": desc }),
519                );
520                continue;
521            }
522
523            // BroadcastMention permission check (§4.4.1).
524            // Non-empty broadcastMentions in a Space-backed channel
525            // requires mention_broadcast permission. Group/direct chats
526            // (no spaceId) are unrestricted per spec.
527            if !broadcast_mentions_val.is_empty() {
528                let chat_lookup = backend
529                    .get_objects::<Chat>(
530                        caller,
531                        &account_id,
532                        Some(std::slice::from_ref(&chat_id)),
533                        None,
534                    )
535                    .await;
536                match chat_lookup {
537                    Ok((found, _)) => {
538                        if let Some(chat) = found.first() {
539                            if let Some(ref sid) = chat.space_id {
540                                match backend
541                                    .may_broadcast_mention(caller, &account_id, sid)
542                                    .await
543                                {
544                                    Ok(Ok(())) => {}
545                                    Ok(Err(set_err)) => {
546                                        not_created
547                                            .insert(create_id.clone(), set_error_value(&set_err));
548                                        continue;
549                                    }
550                                    Err(e) => {
551                                        not_created.insert(
552                                            create_id.clone(),
553                                            server_fail_value_from_backend(&e),
554                                        );
555                                        continue;
556                                    }
557                                }
558                            }
559                            // else: no spaceId — unrestricted per spec
560                        }
561                        // else: Chat not found — let create_object surface
562                        // the normal error downstream
563                    }
564                    Err(e) => {
565                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
566                        continue;
567                    }
568                }
569            }
570
571            let reply_to: Option<Id> = obj_val
572                .get("replyTo")
573                .and_then(|v| v.as_str())
574                .map(Id::from);
575
576            let thread_root_id: Option<Id> = obj_val
577                .get("threadRootId")
578                .and_then(|v| v.as_str())
579                .map(Id::from);
580
581            // senderExpiresAt is a UTCDate per RFC 8620 §1.4 (20-char
582            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
583            // UTCDate::new_validated; a malformed value produces
584            // invalidProperties rather than silently flowing through to
585            // a downstream string compare with undefined ordering.
586            let sender_expires_at: Option<UTCDate> =
587                if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
588                    let Ok(d) = UTCDate::new_validated(s) else {
589                        not_created.insert(
590                            create_id.clone(),
591                            json!({
592                                "type": "invalidProperties",
593                                "properties": ["senderExpiresAt"],
594                            }),
595                        );
596                        continue;
597                    };
598                    Some(d)
599                } else {
600                    None
601                };
602
603            let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
604
605            if let Some(ref expires_at) = sender_expires_at {
606                let now = now_utc_string();
607                if !iso8601_before(&now, expires_at) {
608                    not_created.insert(
609                        create_id.clone(),
610                        json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
611                    );
612                    continue;
613                }
614            }
615
616            // Slow-mode rate-limit gate (draft-atwood-jmap-chat-00
617            // §Chat `slowModeSeconds` + spec commit `de60acb`).
618            //
619            // Runs AFTER wire-format validation so malformed requests
620            // don't consume rate-tracker slots, and BEFORE the
621            // `create_object` call so a throttled sender never sees the
622            // message touch storage. On a Throttled return the backend
623            // tells us when the caller may retry; we surface that
624            // verbatim as the `serverRetryAfter` extra field on the
625            // `rateLimited` SetError, built via the typed
626            // `SetError::with_extra` builder added in bd:JMAP-dha0.
627            // `serverRetryAfter` is the workspace convention paired
628            // with `rateLimited` (read by
629            // `jmap_chat_client::server_retry_after` on the client
630            // side); `SetErrorType::custom("rateLimited")` produces
631            // the spec wire string. The reference `MemoryBackend`
632            // never returns an Err here.
633            if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
634                let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
635                let set_err = SetError::new(SetErrorType::custom("rateLimited"))
636                    .with_description("Slow mode is active for this chat")
637                    .with_extra("serverRetryAfter", json!(retry_after_str));
638                not_created.insert(create_id.clone(), set_error_value(&set_err));
639                continue;
640            }
641
642            let now_str = now_utc_string();
643            let received_at: UTCDate = UTCDate::from(now_str.as_ref());
644
645            let mut msg = Message::new(
646                Id::from("placeholder"),
647                Id::from(create_id.as_str()),
648                SenderId::Owner,
649                chat_id,
650                body,
651                body_type,
652                sent_at,
653                received_at,
654                DeliveryState::Pending,
655            );
656
657            msg.reply_to = reply_to;
658            msg.thread_root_id = thread_root_id;
659            if let Some(d) = sender_expires_at {
660                msg.sender_expires_at = Some(d);
661            }
662            msg.burn_on_read = burn_on_read;
663
664            match backend
665                .create_object::<Message>(caller, &account_id, create_id, msg)
666                .await
667            {
668                Ok((_server_id, created_obj)) => {
669                    mutated = true;
670                    created.insert(
671                        create_id.clone(),
672                        serde_json::to_value(&created_obj)
673                            .expect("derive(Serialize) on plain data is infallible"),
674                    );
675                }
676                Err(BackendSetError::SetError(set_err)) => {
677                    not_created.insert(create_id.clone(), set_error_value(&set_err));
678                }
679                Err(BackendSetError::Other(e)) => {
680                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
681                }
682                Err(_) => {
683                    not_created.insert(
684                        create_id.clone(),
685                        json!({
686                            "type": "serverFail",
687                            "description": "unhandled backend error variant",
688                        }),
689                    );
690                }
691            }
692        }
693    }
694
695    // -----------------------------------------------------------------------
696    // update
697    // -----------------------------------------------------------------------
698    if let Some(Value::Object(update_map)) = args.remove("update") {
699        for (id_str, patch_val) in update_map {
700            let id = Id::from(id_str.as_str());
701
702            // Reject patches that include server-set fields.
703            // MAINTENANCE: when adding a server-set field to Message in
704            // jmap-chat-types, add its wire name here too.  A missing entry
705            // silently allows clients to overwrite server-managed state.
706            const MESSAGE_READONLY: &[&str] = &[
707                "id",
708                "senderMsgId",
709                "senderId",
710                "chatId",
711                "sentAt",
712                "receivedAt",
713                "deliveryState",
714            ];
715            let bad_props: Vec<&str> = MESSAGE_READONLY
716                .iter()
717                .copied()
718                .filter(|&field| patch_val.get(field).is_some())
719                .collect();
720            if !bad_props.is_empty() {
721                not_updated.insert(
722                    id_str,
723                    json!({ "type": "invalidProperties", "properties": bad_props }),
724                );
725                continue;
726            }
727
728            // draft-atwood-jmap-chat-00 §Deleting a Message: servers MUST
729            // reject `deletedForAll: true` when `senderId` is not "self".
730            // A missing target falls through to the normal `notFound` from
731            // `update_object`.
732            let deletes_for_all =
733                patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
734            if deletes_for_all {
735                match backend
736                    .get_objects::<Message>(
737                        caller,
738                        &account_id,
739                        Some(std::slice::from_ref(&id)),
740                        None,
741                    )
742                    .await
743                {
744                    Ok((found, _not_found)) => {
745                        if found
746                            .first()
747                            .is_some_and(|m| m.sender_id != SenderId::Owner)
748                        {
749                            not_updated.insert(
750                                id_str,
751                                json!({
752                                    "type": "forbidden",
753                                    "description": "deletedForAll is only permitted on messages whose senderId is \"self\"",
754                                }),
755                            );
756                            continue;
757                        }
758                    }
759                    Err(e) => {
760                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
761                        continue;
762                    }
763                }
764            }
765
766            // Build augmented patch with server-side timestamps.
767            let mut augmented = patch_val;
768            if augmented.get("body").is_some() {
769                if let Some(obj) = augmented.as_object_mut() {
770                    obj.insert("editedAt".to_owned(), json!(now_utc_string()));
771                }
772            }
773            // draft-atwood-jmap-chat-00 §Message deletedAt: a deleted
774            // Message has an empty `body`, empty `attachments`, and no
775            // `editHistory`, whether the deletion is local or for all. The
776            // merge-patch null purges the stored revisions rather than
777            // merely hiding them.
778            let deletes =
779                deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
780            if deletes {
781                if let Some(obj) = augmented.as_object_mut() {
782                    if deletes_for_all {
783                        obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
784                    }
785                    obj.insert("body".to_owned(), json!(""));
786                    obj.insert("attachments".to_owned(), json!([]));
787                    obj.insert("editHistory".to_owned(), Value::Null);
788                }
789            }
790            // Spec §557 + §1029: when readAt is set without readDisposition, default to "displayed".
791            if let Some(obj) = augmented.as_object_mut() {
792                if obj.contains_key("readAt") && !obj.contains_key("readDisposition") {
793                    obj.insert("readDisposition".to_owned(), json!("displayed"));
794                }
795            }
796
797            // Reaction patch processing
798            // (draft-atwood-jmap-chat-00 §Message/set, §Reaction).
799            //
800            // Reactions are added/removed by patching
801            // `reactions/{senderReactionId}` as RFC 8620 §5.3 JSON
802            // Pointer entries:
803            //
804            // - value is an object: add or modify the reaction
805            // - value is `null`: remove the reaction
806            //
807            // The backend applies these paths into the stored
808            // `reactions` map. Before forwarding, the handler:
809            //
810            // 1. Rejects `reactions/{id}` keys containing `/` or `~`
811            //    (RFC 6901 escape characters — the chat-client also
812            //    rejects them; this is defense-in-depth).
813            // 2. Rejects non-null non-object values as `invalidPatch`.
814            // 3. Pre-fetches the Message and rejects with `forbidden`
815            //    if the patched key targets an existing reaction whose
816            //    `senderId` is not `"self"` — per spec, only the
817            //    original sender may modify their own reactions.
818            // 4. Server-overrides `senderId` to `"self"` on every add
819            //    (spec MUST; defense-in-depth).
820            // 5. Server-injects `sentAt` to the current time on adds
821            //    that lack it, so the resulting `Reaction` round-trips
822            //    through the typed shape (which requires `sentAt`).
823            let reaction_pointer_keys: Vec<String> = augmented
824                .as_object()
825                .map(|obj| {
826                    obj.keys()
827                        .filter(|k| k.starts_with("reactions/"))
828                        .cloned()
829                        .collect()
830                })
831                .unwrap_or_default();
832
833            if !reaction_pointer_keys.is_empty() {
834                // Reject mixing top-level `reactions` with
835                // `reactions/{id}` — the two have incompatible
836                // semantics (wholesale replace vs per-key merge) and
837                // a single patch should not attempt both.
838                if augmented
839                    .as_object()
840                    .is_some_and(|obj| obj.contains_key("reactions"))
841                {
842                    not_updated.insert(
843                        id_str,
844                        json!({
845                            "type": "invalidPatch",
846                            "description":
847                                "patch must not combine top-level `reactions` with `reactions/{id}` entries",
848                        }),
849                    );
850                    continue;
851                }
852
853                // Validate each pointer key + value shape. The
854                // `.collect::<Result<Vec<_>, _>>()` form short-circuits
855                // on the first Err and is the idiomatic Rust expression
856                // of "validate-or-fail" over an iterator. A future
857                // contributor adding a new validation rule appends an
858                // `if ... { return Err(...) }` inside the closure; the
859                // short-circuit behavior is structural, not a hand-coded
860                // flag invariant.
861                let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
862                    .iter()
863                    .map(|raw_key| {
864                        let suffix = &raw_key["reactions/".len()..];
865                        if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
866                            return Err(format!(
867                                "reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
868                            ));
869                        }
870                        let val = augmented.get(raw_key).unwrap_or(&Value::Null);
871                        if !val.is_null() {
872                            let ok = val.as_object().is_some_and(|m| {
873                                m.get("emoji")
874                                    .and_then(|v| v.as_str())
875                                    .is_some_and(|s| !s.is_empty())
876                            });
877                            if !ok {
878                                return Err(format!(
879                                    "reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
880                                ));
881                            }
882                        }
883                        Ok((raw_key.clone(), suffix.to_owned()))
884                    })
885                    .collect();
886                let decoded = match decoded {
887                    Ok(d) => d,
888                    Err(desc) => {
889                        not_updated.insert(
890                            id_str,
891                            json!({ "type": "invalidPatch", "description": desc }),
892                        );
893                        continue;
894                    }
895                };
896
897                // Pre-fetch the Message to inspect existing
898                // reactions. An update target that doesn't exist on
899                // the backend will surface a normal `notFound` from
900                // the subsequent `update_object` call — we don't
901                // short-circuit here. A backend storage error becomes
902                // `serverFail`.
903                let forbidden = match backend
904                    .get_objects::<Message>(
905                        caller,
906                        &account_id,
907                        Some(std::slice::from_ref(&id)),
908                        None,
909                    )
910                    .await
911                {
912                    Ok((found, _not_found)) => {
913                        let mut bad: Vec<String> = Vec::new();
914                        if let Some(msg) = found.first() {
915                            for (_, suffix) in &decoded {
916                                if let Some(existing) = msg.reactions.get(suffix) {
917                                    if existing.sender_id != SenderId::Owner {
918                                        bad.push(suffix.clone());
919                                    }
920                                }
921                            }
922                        }
923                        bad
924                    }
925                    Err(e) => {
926                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
927                        continue;
928                    }
929                };
930                if !forbidden.is_empty() {
931                    not_updated.insert(
932                        id_str,
933                        json!({
934                            "type": "forbidden",
935                            "description": format!(
936                                "cannot modify reactions authored by another sender: {}",
937                                forbidden.join(", "),
938                            ),
939                        }),
940                    );
941                    continue;
942                }
943
944                // Server-override `senderId` and inject `sentAt` where
945                // absent on every `reactions/{key}` add, so the stored
946                // Reaction round-trips through the typed shape.
947                let now_str = now_utc_string();
948                if let Some(obj) = augmented.as_object_mut() {
949                    for (raw_key, _) in &decoded {
950                        if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
951                            // Spec MUST: server overrides senderId to
952                            // "self" on every add, regardless of what
953                            // the client supplied.
954                            map.insert("senderId".to_owned(), json!("self"));
955                            map.entry("sentAt").or_insert_with(|| json!(now_str));
956                        }
957                    }
958                }
959            }
960
961            // Detect a non-null readAt assignment in the patch. A
962            // `readAt: null` is a PatchObject clear (RFC 8620 §5.3), not a
963            // "mark as read" event, so it does not trigger burn-on-read.
964            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: the
965            // receiving server MUST hard-delete immediately after setting
966            // readAt on a message whose `burnOnRead` is `true`.
967            let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
968
969            // If the patch sets readAt, pre-fetch the message so we can
970            // decide whether it is burn-on-read. We deliberately consult
971            // the pre-patch state: a recipient setting readAt for the
972            // first time should fire the burn, regardless of whether the
973            // same patch attempts to also clear `burnOnRead` (which is a
974            // sender-set field and the spec does not authorize a
975            // recipient to flip).
976            let pre_patch_burn_on_read = if patch_sets_read_at {
977                match backend
978                    .get_objects::<Message>(
979                        caller,
980                        &account_id,
981                        Some(std::slice::from_ref(&id)),
982                        None,
983                    )
984                    .await
985                {
986                    Ok((found, _not_found)) => {
987                        found.first().and_then(|m| m.burn_on_read) == Some(true)
988                    }
989                    Err(_) => false,
990                }
991            } else {
992                false
993            };
994
995            // BroadcastMention structural validation on update (§4.4.1 / §4.16).
996            // Only triggered when broadcastMentions is part of the patch.
997            let patch_has_bm = augmented
998                .as_object()
999                .is_some_and(|obj| obj.contains_key("broadcastMentions"));
1000            if patch_has_bm {
1001                // Pre-fetch the current message to obtain the post-patch
1002                // body/bodyType and chatId for the permission check. If the
1003                // patch also updates body or bodyType, use the patch value;
1004                // otherwise fall back to the stored value.
1005                let (current_body, current_body_type, msg_chat_id) = match backend
1006                    .get_objects::<Message>(
1007                        caller,
1008                        &account_id,
1009                        Some(std::slice::from_ref(&id)),
1010                        None,
1011                    )
1012                    .await
1013                {
1014                    Ok((found, _)) => {
1015                        if let Some(msg) = found.first() {
1016                            (
1017                                msg.body.clone(),
1018                                msg.body_type.clone(),
1019                                Some(msg.chat_id.clone()),
1020                            )
1021                        } else {
1022                            // Message not found — let update_object surface
1023                            // the normal notFound error downstream.
1024                            (String::new(), String::from("text/plain"), None)
1025                        }
1026                    }
1027                    Err(e) => {
1028                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
1029                        continue;
1030                    }
1031                };
1032                let post_patch_body = augmented
1033                    .get("body")
1034                    .and_then(|v| v.as_str())
1035                    .unwrap_or(&current_body);
1036                let post_patch_body_type = augmented
1037                    .get("bodyType")
1038                    .and_then(|v| v.as_str())
1039                    .unwrap_or(&current_body_type);
1040                let bm_arr: Vec<Value> = augmented
1041                    .get("broadcastMentions")
1042                    .and_then(|v| v.as_array())
1043                    .cloned()
1044                    .unwrap_or_default();
1045                if let Some(desc) =
1046                    validate_broadcast_mentions(&bm_arr, post_patch_body, post_patch_body_type)
1047                {
1048                    not_updated.insert(
1049                        id_str,
1050                        json!({ "type": "invalidArguments", "description": desc }),
1051                    );
1052                    continue;
1053                }
1054
1055                // BroadcastMention permission check on update (§4.4.1).
1056                // Non-empty post-patch broadcastMentions in a Space-backed
1057                // channel requires mention_broadcast permission. Group/direct
1058                // chats (no spaceId) are unrestricted per spec.
1059                if !bm_arr.is_empty() {
1060                    if let Some(ref cid) = msg_chat_id {
1061                        let chat_lookup = backend
1062                            .get_objects::<Chat>(
1063                                caller,
1064                                &account_id,
1065                                Some(std::slice::from_ref(cid)),
1066                                None,
1067                            )
1068                            .await;
1069                        match chat_lookup {
1070                            Ok((found, _)) => {
1071                                if let Some(chat) = found.first() {
1072                                    if let Some(ref sid) = chat.space_id {
1073                                        match backend
1074                                            .may_broadcast_mention(caller, &account_id, sid)
1075                                            .await
1076                                        {
1077                                            Ok(Ok(())) => {}
1078                                            Ok(Err(set_err)) => {
1079                                                not_updated
1080                                                    .insert(id_str, set_error_value(&set_err));
1081                                                continue;
1082                                            }
1083                                            Err(e) => {
1084                                                not_updated.insert(
1085                                                    id_str,
1086                                                    server_fail_value_from_backend(&e),
1087                                                );
1088                                                continue;
1089                                            }
1090                                        }
1091                                    }
1092                                    // else: no spaceId — unrestricted per spec
1093                                }
1094                                // else: Chat not found — let update_object
1095                                // surface the normal error downstream
1096                            }
1097                            Err(e) => {
1098                                not_updated.insert(id_str, server_fail_value_from_backend(&e));
1099                                continue;
1100                            }
1101                        }
1102                    }
1103                    // else: msg_chat_id is None — message not found,
1104                    // let update_object surface notFound downstream
1105                }
1106            }
1107
1108            // Convert the augmented wire-format Value into a typed
1109            // PatchObject (RFC 8620 §5.3). Non-object values yield
1110            // invalidPatch.
1111            let patch = match serde_json::from_value::<PatchObject>(augmented) {
1112                Ok(p) => p,
1113                Err(e) => {
1114                    not_updated.insert(
1115                        id_str,
1116                        json!({ "type": "invalidPatch", "description": e.to_string() }),
1117                    );
1118                    continue;
1119                }
1120            };
1121            let update_outcome = backend
1122                .update_object::<Message>(caller, &account_id, &id, patch)
1123                .await;
1124            let maybe_updated_obj = match update_outcome {
1125                Ok(maybe_obj) => maybe_obj,
1126                Err(BackendSetError::SetError(set_err)) => {
1127                    not_updated.insert(id_str, set_error_value(&set_err));
1128                    continue;
1129                }
1130                Err(BackendSetError::Other(e)) => {
1131                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
1132                    continue;
1133                }
1134                Err(_) => {
1135                    not_updated.insert(
1136                        id_str,
1137                        json!({
1138                            "type": "serverFail",
1139                            "description": "unhandled backend error variant",
1140                        }),
1141                    );
1142                    continue;
1143                }
1144            };
1145
1146            // Burn-on-read fires AFTER the readAt patch has been applied.
1147            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: hard-delete
1148            // immediately. The patch already succeeded above; the hard
1149            // delete is its own backend call so that a production backend
1150            // can either (a) leave the default no-op and override
1151            // `update_object` for atomic write+delete, or (b) override
1152            // this method for a separate two-step deletion. The reference
1153            // `MemoryBackend` uses (b). Both are conforming.
1154            if patch_sets_read_at && pre_patch_burn_on_read {
1155                if let Err(burn_err) = backend.expire_message(caller, &account_id, &id).await {
1156                    // The readAt patch already landed in storage but
1157                    // the spec-mandated hard-delete failed. Surface
1158                    // as serverFail; the recipient will retry, and
1159                    // the next pre-fetch will still see
1160                    // `burnOnRead: true` (a sender-set field a
1161                    // recipient cannot flip), so the burn will be
1162                    // attempted again. Production backends that
1163                    // need atomic readAt-and-burn semantics SHOULD
1164                    // override `update_object` to perform both
1165                    // inside a single transaction; the reference
1166                    // `MemoryBackend::expire_message` does not
1167                    // surface failures and so this branch is
1168                    // unreachable for it.
1169                    //
1170                    // Route through server_fail_value_from_backend to
1171                    // redact backend Display text from the wire
1172                    // description per workspace redaction discipline
1173                    // (otherwise the backend error message leaks to
1174                    // the JMAP client).
1175                    not_updated.insert(id_str, server_fail_value_from_backend(&burn_err));
1176                    // Bump mutated regardless, because the readAt
1177                    // write is committed even though we report
1178                    // notUpdated for the wire response. Callers
1179                    // relying on `mutated` to decide whether to
1180                    // rotate the state token will rotate, which
1181                    // correctly reflects that something changed in
1182                    // storage.
1183                    mutated = true;
1184                    continue;
1185                }
1186            }
1187
1188            // Update succeeded (and burn, if applicable, succeeded too).
1189            mutated = true;
1190            match maybe_updated_obj {
1191                Some(obj) => {
1192                    updated.insert(
1193                        id_str,
1194                        serde_json::to_value(&obj)
1195                            .expect("derive(Serialize) on plain data is infallible"),
1196                    );
1197                }
1198                None => {
1199                    updated.insert(id_str, Value::Null);
1200                }
1201            }
1202        }
1203    }
1204
1205    // -----------------------------------------------------------------------
1206    // destroy
1207    // -----------------------------------------------------------------------
1208    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
1209        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
1210        // Reject the whole request if any element is non-string rather than
1211        // silently skipping it, which would produce a misleading response.
1212        if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
1213            return Err(JmapError::invalid_arguments(format!(
1214                "destroy: every element must be a string Id; got {bad}"
1215            )));
1216        }
1217        for id_val in destroy_arr {
1218            let Some(id_str) = id_val.as_str() else {
1219                continue; // unreachable: validated above
1220            };
1221            let id = Id::from(id_str);
1222
1223            match backend
1224                .destroy_object::<Message>(caller, &account_id, &id)
1225                .await
1226            {
1227                Ok(()) => {
1228                    mutated = true;
1229                    destroyed_list.push(Value::String(id_str.to_owned()));
1230                }
1231                Err(BackendSetError::SetError(set_err)) => {
1232                    not_destroyed.insert(id_str.to_owned(), set_error_value(&set_err));
1233                }
1234                Err(BackendSetError::Other(e)) => {
1235                    not_destroyed.insert(id_str.to_owned(), server_fail_value_from_backend(&e));
1236                }
1237                Err(_) => {
1238                    not_destroyed.insert(
1239                        id_str.to_owned(),
1240                        json!({
1241                            "type": "serverFail",
1242                            "description": "unhandled backend error variant",
1243                        }),
1244                    );
1245                }
1246            }
1247        }
1248    }
1249
1250    finalize_set_response::<B, Message>(
1251        backend,
1252        caller,
1253        &account_id,
1254        old_state,
1255        mutated,
1256        SetAccumulators {
1257            created,
1258            updated,
1259            destroyed: destroyed_list,
1260            not_created,
1261            not_updated,
1262            not_destroyed,
1263        },
1264    )
1265    .await
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270    use super::*;
1271    use crate::memory::MemoryBackend;
1272    use serde_json::json;
1273
1274    const ACCOUNT_ID: &str = "a1";
1275
1276    // Oracles in this module are hand-built per workspace test-integrity
1277    // policy. Each test asserts the wire shape of a known-invalid or
1278    // known-valid broadcastMentions payload against the validation rules
1279    // from spec §4.4.1 / §4.16. The independent oracle is the spec text
1280    // itself; no assertion uses the code under test as its own reference.
1281
1282    /// An unrecognized scope like "channel" must be rejected with
1283    /// invalidArguments.
1284    #[tokio::test]
1285    async fn broadcast_mention_validation_rejects_unknown_scope() {
1286        let backend = MemoryBackend::new();
1287        let (resp, _) = handle_message_set(
1288            &backend,
1289            &(),
1290            json!({
1291                "accountId": ACCOUNT_ID,
1292                "create": {
1293                    "m0": {
1294                        "chatId": "c1",
1295                        "body": "Hello @channel",
1296                        "sentAt": "2024-01-01T00:00:00Z",
1297                        "broadcastMentions": [
1298                            { "scope": "channel", "offset": 6, "length": 8 }
1299                        ]
1300                    }
1301                }
1302            }),
1303        )
1304        .await
1305        .expect("handle_message_set");
1306
1307        assert!(resp["notCreated"]["m0"].is_object());
1308        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
1309        let desc = resp["notCreated"]["m0"]["description"]
1310            .as_str()
1311            .expect("description");
1312        assert!(
1313            desc.contains("unrecognized scope"),
1314            "expected 'unrecognized scope' in description, got: {desc}"
1315        );
1316    }
1317
1318    /// offset=u64::MAX + length=1 overflows u64; must be rejected.
1319    #[tokio::test]
1320    async fn broadcast_mention_validation_rejects_overflow() {
1321        let backend = MemoryBackend::new();
1322        let (resp, _) = handle_message_set(
1323            &backend,
1324            &(),
1325            json!({
1326                "accountId": ACCOUNT_ID,
1327                "create": {
1328                    "m0": {
1329                        "chatId": "c1",
1330                        "body": "Hello @everyone",
1331                        "sentAt": "2024-01-01T00:00:00Z",
1332                        "broadcastMentions": [
1333                            { "scope": "everyone", "offset": u64::MAX, "length": 1 }
1334                        ]
1335                    }
1336                }
1337            }),
1338        )
1339        .await
1340        .expect("handle_message_set");
1341
1342        assert!(resp["notCreated"]["m0"].is_object());
1343        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
1344        let desc = resp["notCreated"]["m0"]["description"]
1345            .as_str()
1346            .expect("description");
1347        assert!(
1348            desc.contains("overflows u64"),
1349            "expected 'overflows u64' in description, got: {desc}"
1350        );
1351    }
1352
1353    /// offset + length exceeding body byte length must be rejected.
1354    #[tokio::test]
1355    async fn broadcast_mention_validation_rejects_exceeds_body() {
1356        let backend = MemoryBackend::new();
1357        let (resp, _) = handle_message_set(
1358            &backend,
1359            &(),
1360            json!({
1361                "accountId": ACCOUNT_ID,
1362                "create": {
1363                    "m0": {
1364                        "chatId": "c1",
1365                        "body": "short",
1366                        "sentAt": "2024-01-01T00:00:00Z",
1367                        "broadcastMentions": [
1368                            { "scope": "everyone", "offset": 0, "length": 999 }
1369                        ]
1370                    }
1371                }
1372            }),
1373        )
1374        .await
1375        .expect("handle_message_set");
1376
1377        assert!(resp["notCreated"]["m0"].is_object());
1378        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
1379        let desc = resp["notCreated"]["m0"]["description"]
1380            .as_str()
1381            .expect("description");
1382        assert!(
1383            desc.contains("exceeds body byte length"),
1384            "expected 'exceeds body byte length' in description, got: {desc}"
1385        );
1386    }
1387
1388    /// broadcastMentions must be empty when bodyType is
1389    /// "application/jmap-chat-rich".
1390    #[tokio::test]
1391    async fn broadcast_mention_validation_rejects_rich_body_nonempty() {
1392        let backend = MemoryBackend::new();
1393        let (resp, _) = handle_message_set(
1394            &backend,
1395            &(),
1396            json!({
1397                "accountId": ACCOUNT_ID,
1398                "create": {
1399                    "m0": {
1400                        "chatId": "c1",
1401                        "body": "Hello @everyone in rich",
1402                        "bodyType": "application/jmap-chat-rich",
1403                        "sentAt": "2024-01-01T00:00:00Z",
1404                        "broadcastMentions": [
1405                            { "scope": "everyone", "offset": 6, "length": 9 }
1406                        ]
1407                    }
1408                }
1409            }),
1410        )
1411        .await
1412        .expect("handle_message_set");
1413
1414        assert!(resp["notCreated"]["m0"].is_object());
1415        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
1416        let desc = resp["notCreated"]["m0"]["description"]
1417            .as_str()
1418            .expect("description");
1419        assert!(
1420            desc.contains("application/jmap-chat-rich"),
1421            "expected 'application/jmap-chat-rich' in description, got: {desc}"
1422        );
1423    }
1424
1425    /// A valid @everyone mention at the correct body offset succeeds.
1426    #[tokio::test]
1427    async fn broadcast_mention_validation_accepts_valid() {
1428        let backend = MemoryBackend::new();
1429        let body = "Hello @everyone!";
1430        let (resp, _) = handle_message_set(
1431            &backend,
1432            &(),
1433            json!({
1434                "accountId": ACCOUNT_ID,
1435                "create": {
1436                    "m0": {
1437                        "chatId": "c1",
1438                        "body": body,
1439                        "sentAt": "2024-01-01T00:00:00Z",
1440                        "broadcastMentions": [
1441                            { "scope": "everyone", "offset": 6, "length": 9 }
1442                        ]
1443                    }
1444                }
1445            }),
1446        )
1447        .await
1448        .expect("handle_message_set");
1449
1450        assert!(
1451            resp["created"]["m0"].is_object(),
1452            "expected created, got notCreated: {}",
1453            resp["notCreated"]["m0"]
1454        );
1455    }
1456
1457    /// An empty broadcastMentions array is always valid.
1458    #[tokio::test]
1459    async fn broadcast_mention_validation_accepts_empty() {
1460        let backend = MemoryBackend::new();
1461        let (resp, _) = handle_message_set(
1462            &backend,
1463            &(),
1464            json!({
1465                "accountId": ACCOUNT_ID,
1466                "create": {
1467                    "m0": {
1468                        "chatId": "c1",
1469                        "body": "Hello, world!",
1470                        "sentAt": "2024-01-01T00:00:00Z",
1471                        "broadcastMentions": []
1472                    }
1473                }
1474            }),
1475        )
1476        .await
1477        .expect("handle_message_set");
1478
1479        assert!(
1480            resp["created"]["m0"].is_object(),
1481            "expected created, got notCreated: {}",
1482            resp["notCreated"]["m0"]
1483        );
1484    }
1485
1486    // -----------------------------------------------------------------------
1487    // BroadcastMention permission-check tests (§4.4.1 mention_broadcast)
1488    //
1489    // Oracle: the spec text itself. Group/direct chats without a spaceId
1490    // are unrestricted; channel chats with a spaceId must pass the
1491    // mention_broadcast gate. The MemoryBackend's default
1492    // may_broadcast_mention returns Ok(Ok(())) (always permits), so
1493    // these tests verify the handler CODE PATH is wired correctly and
1494    // that the gate is skipped or invoked in the right circumstances.
1495    // -----------------------------------------------------------------------
1496
1497    /// Helper: create a group Chat (no spaceId) via handle_chat_set and
1498    /// return its server-assigned id.
1499    async fn make_group_chat(backend: &MemoryBackend) -> String {
1500        let (resp, _) = crate::chat::handle_chat_set(
1501            backend,
1502            &(),
1503            json!({
1504                "accountId": ACCOUNT_ID,
1505                "create": { "c0": { "kind": "group", "name": "test-group" } }
1506            }),
1507        )
1508        .await
1509        .expect("make_group_chat");
1510        resp["created"]["c0"]["id"]
1511            .as_str()
1512            .expect("group chat id")
1513            .to_owned()
1514    }
1515
1516    /// Helper: create a Space, then a channel Chat inside it, and return
1517    /// the channel's server-assigned id.
1518    async fn make_channel_chat(backend: &MemoryBackend) -> String {
1519        // Create a Space first.
1520        let (space_resp, _) = crate::space::handle_space_set(
1521            backend,
1522            &(),
1523            json!({
1524                "accountId": ACCOUNT_ID,
1525                "create": { "s0": { "name": "test-space" } }
1526            }),
1527        )
1528        .await
1529        .expect("make_channel_chat: space");
1530        let space_id = space_resp["created"]["s0"]["id"]
1531            .as_str()
1532            .expect("space id");
1533
1534        // Create a channel Chat in that Space.
1535        let (chat_resp, _) = crate::chat::handle_chat_set(
1536            backend,
1537            &(),
1538            json!({
1539                "accountId": ACCOUNT_ID,
1540                "create": { "c0": {
1541                    "kind": "channel",
1542                    "name": "general",
1543                    "spaceId": space_id
1544                } }
1545            }),
1546        )
1547        .await
1548        .expect("make_channel_chat: chat");
1549        chat_resp["created"]["c0"]["id"]
1550            .as_str()
1551            .expect("channel chat id")
1552            .to_owned()
1553    }
1554
1555    /// Create a Message with broadcastMentions in a group chat (no spaceId).
1556    /// The permission check must be SKIPPED (unrestricted per spec),
1557    /// and the message must succeed.
1558    #[tokio::test]
1559    async fn broadcast_mention_create_without_space_unrestricted() {
1560        let backend = MemoryBackend::new();
1561        let chat_id = make_group_chat(&backend).await;
1562
1563        let body = "Hello @everyone!";
1564        let (resp, _) = handle_message_set(
1565            &backend,
1566            &(),
1567            json!({
1568                "accountId": ACCOUNT_ID,
1569                "create": {
1570                    "m0": {
1571                        "chatId": chat_id,
1572                        "body": body,
1573                        "sentAt": "2024-01-01T00:00:00Z",
1574                        "broadcastMentions": [
1575                            { "scope": "everyone", "offset": 6, "length": 9 }
1576                        ]
1577                    }
1578                }
1579            }),
1580        )
1581        .await
1582        .expect("handle_message_set");
1583
1584        assert!(
1585            resp["created"]["m0"].is_object(),
1586            "expected created in group chat (no spaceId), got notCreated: {}",
1587            resp["notCreated"]["m0"]
1588        );
1589    }
1590
1591    /// Create a Message with broadcastMentions in a channel chat (has spaceId).
1592    /// The MemoryBackend's default may_broadcast_mention permits all,
1593    /// so the message must succeed.
1594    #[tokio::test]
1595    async fn broadcast_mention_create_in_channel_succeeds() {
1596        let backend = MemoryBackend::new();
1597        let chat_id = make_channel_chat(&backend).await;
1598
1599        let body = "Hello @everyone!";
1600        let (resp, _) = handle_message_set(
1601            &backend,
1602            &(),
1603            json!({
1604                "accountId": ACCOUNT_ID,
1605                "create": {
1606                    "m0": {
1607                        "chatId": chat_id,
1608                        "body": body,
1609                        "sentAt": "2024-01-01T00:00:00Z",
1610                        "broadcastMentions": [
1611                            { "scope": "everyone", "offset": 6, "length": 9 }
1612                        ]
1613                    }
1614                }
1615            }),
1616        )
1617        .await
1618        .expect("handle_message_set");
1619
1620        assert!(
1621            resp["created"]["m0"].is_object(),
1622            "expected created in channel chat, got notCreated: {}",
1623            resp["notCreated"]["m0"]
1624        );
1625    }
1626
1627    /// Create a Message with empty broadcastMentions in a channel chat.
1628    /// The permission check must NOT fire (empty array skips the gate).
1629    #[tokio::test]
1630    async fn broadcast_mention_create_empty_skips_permission_check() {
1631        let backend = MemoryBackend::new();
1632        let chat_id = make_channel_chat(&backend).await;
1633
1634        let (resp, _) = handle_message_set(
1635            &backend,
1636            &(),
1637            json!({
1638                "accountId": ACCOUNT_ID,
1639                "create": {
1640                    "m0": {
1641                        "chatId": chat_id,
1642                        "body": "Hello, world!",
1643                        "sentAt": "2024-01-01T00:00:00Z",
1644                        "broadcastMentions": []
1645                    }
1646                }
1647            }),
1648        )
1649        .await
1650        .expect("handle_message_set");
1651
1652        assert!(
1653            resp["created"]["m0"].is_object(),
1654            "expected created with empty broadcastMentions, got notCreated: {}",
1655            resp["notCreated"]["m0"]
1656        );
1657    }
1658
1659    /// Update a Message to retain non-empty broadcastMentions in a channel chat.
1660    /// The MemoryBackend's default may_broadcast_mention permits all,
1661    /// so the update must succeed.
1662    #[tokio::test]
1663    async fn broadcast_mention_update_retaining_broadcast_succeeds() {
1664        let backend = MemoryBackend::new();
1665        let chat_id = make_channel_chat(&backend).await;
1666
1667        // Create a message with broadcastMentions first.
1668        let body = "Hello @everyone!";
1669        let (create_resp, _) = handle_message_set(
1670            &backend,
1671            &(),
1672            json!({
1673                "accountId": ACCOUNT_ID,
1674                "create": {
1675                    "m0": {
1676                        "chatId": chat_id,
1677                        "body": body,
1678                        "sentAt": "2024-01-01T00:00:00Z",
1679                        "broadcastMentions": [
1680                            { "scope": "everyone", "offset": 6, "length": 9 }
1681                        ]
1682                    }
1683                }
1684            }),
1685        )
1686        .await
1687        .expect("create message");
1688        let msg_id = create_resp["created"]["m0"]["id"]
1689            .as_str()
1690            .expect("message id");
1691
1692        // Update the message, retaining a non-empty broadcastMentions.
1693        let new_body = "Hey @here now!";
1694        let (update_resp, _) = handle_message_set(
1695            &backend,
1696            &(),
1697            json!({
1698                "accountId": ACCOUNT_ID,
1699                "update": {
1700                    (msg_id): {
1701                        "body": new_body,
1702                        "broadcastMentions": [
1703                            { "scope": "here", "offset": 4, "length": 5 }
1704                        ]
1705                    }
1706                }
1707            }),
1708        )
1709        .await
1710        .expect("update message");
1711
1712        assert!(
1713            update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
1714            "expected updated, got notUpdated: {}",
1715            update_resp["notUpdated"][msg_id]
1716        );
1717        assert!(
1718            update_resp["notUpdated"].is_null()
1719                || !update_resp["notUpdated"]
1720                    .as_object()
1721                    .is_some_and(|m| m.contains_key(msg_id)),
1722            "message should not be in notUpdated"
1723        );
1724    }
1725}