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