Skip to main content

jmap_chat_server/
space.rs

1//! Space/* method handlers (draft-atwood-jmap-chat-00 §Space).
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 §Space. The returned
11//! `Value` is the corresponding method-response object per the same
12//! section refs. `Space/join` (draft §Space) is a Chat-specific method
13//! with its own request/response shape (`accountId`, `inviteCode` →
14//! `accountId`, `spaceId`).
15//!
16//! The returned `HandlerOutput::extra_invocations` carries any invocations
17//! that this handler injected into the request stream (RFC 8620 §6.3);
18//! for the handlers in this module the vector is **always empty**.
19//!
20//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
21//! §3.6.2 and §5):
22//!
23//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
24//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
25//!   `maxObjectsInSet`;
26//! - `/set`: `stateMismatch`;
27//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
28//! - `/queryChanges`: `tooManyChanges`;
29//! - `/query`, `/queryChanges`: `unsupportedFilter`;
30//! - `/query`: `unsupportedSort`, `anchorNotFound`;
31//! - `/join`: `forbidden`, `notPermitted`.
32//!
33//! Per-target failures inside `/set` (including the structural-mutation
34//! pipeline rejections — `addRoles`/`removeRoles`/`addMembers` etc. — and the
35//! position-0 / cap-exceeded enforcement) surface in the `notCreated` /
36//! `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.
37
38use std::collections::BTreeMap;
39
40use jmap_chat_types::SPEC_PERMISSION_NAMES;
41use jmap_chat_types::{
42    CategoryCreate, CategoryPatch, ChannelCreate, ChannelPatch, MemberPatch, RolePatch,
43};
44use jmap_chat_types::{
45    Chat, ChatKind, RoleCreate, Space, SpaceBan, SpaceInvite, SpaceMember, SpaceRole,
46};
47use jmap_chat_types::{SpaceComparator, SpaceFilter};
48use jmap_types::{Id, JmapError, PatchObject, SetObject, UTCDate};
49use serde_json::{Value, json};
50use subtle::ConstantTimeEq;
51
52use crate::helpers::check_read_only_patch;
53use crate::helpers::{
54    PropType, check_metadata_entry, create_metadata, is_metadata_key, mistyped_create_props,
55};
56use crate::helpers::{
57    SetAccumulators, count_add_ops, default_sort, enforce_max_objects_in_get,
58    enforce_max_objects_in_set, extract_account_id, finalize_set_response, iso8601_before,
59    not_found_json, now_utc_string, optional_arg, reject_unsupported_sort, serialize_value,
60};
61use crate::helpers::{resolve_entry_refs, resolve_ref, resolve_refs};
62use crate::{ChatBackend, ChatLimits, InviteJoinRefusal, SpacePatchOp};
63use jmap_server::{
64    HandlerOutput, MetadataProjection, QueryParams, backend_set_error_value, bool_arg, filter_arg,
65    is_client_updatable, query_anchor_args, reject_server_set, server_fail_from_backend,
66    server_fail_value_from_backend,
67};
68use jmap_server::{SetError, SetErrorType};
69
70// ---------------------------------------------------------------------------
71// Space/set structural-mutation parsing
72// ---------------------------------------------------------------------------
73
74/// The 12 structural mutation keys on a Space patch
75/// (draft-atwood-jmap-chat-00 §Space/set). Each variant maps one-to-one
76/// to a family of [`SpacePatchOp`] values.
77///
78/// Used to type-dispatch wire-key classification and per-key parsing
79/// without stringly-typed matches in the hot path.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81enum StructuralKey {
82    AddRoles,
83    UpdateRoles,
84    RemoveRoles,
85    AddMembers,
86    UpdateMembers,
87    RemoveMembers,
88    AddChannels,
89    UpdateChannels,
90    RemoveChannels,
91    AddCategories,
92    UpdateCategories,
93    RemoveCategories,
94}
95
96impl StructuralKey {
97    /// Parse a wire-format key string into a [`StructuralKey`]. Returns
98    /// `None` if the key is not one of the 12 structural keys (callers
99    /// then classify it as metadata or unknown).
100    fn from_wire(key: &str) -> Option<Self> {
101        Some(match key {
102            "addRoles" => Self::AddRoles,
103            "updateRoles" => Self::UpdateRoles,
104            "removeRoles" => Self::RemoveRoles,
105            "addMembers" => Self::AddMembers,
106            "updateMembers" => Self::UpdateMembers,
107            "removeMembers" => Self::RemoveMembers,
108            "addChannels" => Self::AddChannels,
109            "updateChannels" => Self::UpdateChannels,
110            "removeChannels" => Self::RemoveChannels,
111            "addCategories" => Self::AddCategories,
112            "updateCategories" => Self::UpdateCategories,
113            "removeCategories" => Self::RemoveCategories,
114            _ => return None,
115        })
116    }
117
118    /// The canonical wire-format spelling of this key, for use in error
119    /// messages and `invalidProperties.properties` payloads.
120    fn wire_name(self) -> &'static str {
121        match self {
122            Self::AddRoles => "addRoles",
123            Self::UpdateRoles => "updateRoles",
124            Self::RemoveRoles => "removeRoles",
125            Self::AddMembers => "addMembers",
126            Self::UpdateMembers => "updateMembers",
127            Self::RemoveMembers => "removeMembers",
128            Self::AddChannels => "addChannels",
129            Self::UpdateChannels => "updateChannels",
130            Self::RemoveChannels => "removeChannels",
131            Self::AddCategories => "addCategories",
132            Self::UpdateCategories => "updateCategories",
133            Self::RemoveCategories => "removeCategories",
134        }
135    }
136}
137
138/// Parse one structural wire key's payload
139/// (draft-atwood-jmap-chat-00 §Space/set) into a `Vec<SpacePatchOp>`.
140///
141/// The 12 structural keys are pluralized arrays whose elements have a
142/// per-key shape; this helper handles all of them.
143///
144/// Returns an error string describing why parsing failed, suitable for use
145/// as the `description` field of an `invalidProperties` `SetError`. The
146/// returned error is fatal for the containing update target — the handler
147/// inserts the failing wire key into `notUpdated[id].properties` and skips
148/// any remaining keys.
149fn parse_structural_entries(key: StructuralKey, value: Value) -> Result<Vec<SpacePatchOp>, String> {
150    let canonical = key.wire_name();
151    let arr = match value {
152        Value::Array(a) => a,
153        other => {
154            return Err(format!(
155                "{canonical} must be a JSON array, got {}",
156                jmap_server::json_type_name(&other)
157            ));
158        }
159    };
160
161    let mut out = Vec::with_capacity(arr.len());
162    for (idx, entry) in arr.into_iter().enumerate() {
163        let op = match key {
164            StructuralKey::AddRoles => {
165                SpacePatchOp::AddRole(parse_entry::<RoleCreate>(canonical, idx, entry)?)
166            }
167            StructuralKey::RemoveRoles => {
168                SpacePatchOp::RemoveRole(parse_id_entry(canonical, idx, entry)?)
169            }
170            StructuralKey::UpdateRoles => {
171                let (id, patch) = parse_update_entry::<RolePatch>(canonical, idx, entry)?;
172                SpacePatchOp::UpdateRole { id, patch }
173            }
174            StructuralKey::AddMembers => {
175                let (user_id, role_ids) = parse_add_member_entry(canonical, idx, entry)?;
176                SpacePatchOp::AddMember(jmap_chat_types::MemberCreate::new(user_id, role_ids))
177            }
178            StructuralKey::RemoveMembers => {
179                SpacePatchOp::RemoveMember(parse_id_entry(canonical, idx, entry)?)
180            }
181            StructuralKey::UpdateMembers => {
182                let (id, patch) = parse_update_entry::<MemberPatch>(canonical, idx, entry)?;
183                SpacePatchOp::UpdateMember { user_id: id, patch }
184            }
185            StructuralKey::AddChannels => {
186                SpacePatchOp::AddChannel(parse_entry::<ChannelCreate>(canonical, idx, entry)?)
187            }
188            StructuralKey::RemoveChannels => {
189                SpacePatchOp::RemoveChannel(parse_id_entry(canonical, idx, entry)?)
190            }
191            StructuralKey::UpdateChannels => {
192                let (id, patch) = parse_update_entry::<ChannelPatch>(canonical, idx, entry)?;
193                SpacePatchOp::UpdateChannel { id, patch }
194            }
195            StructuralKey::AddCategories => {
196                SpacePatchOp::AddCategory(parse_entry::<CategoryCreate>(canonical, idx, entry)?)
197            }
198            StructuralKey::RemoveCategories => {
199                SpacePatchOp::RemoveCategory(parse_id_entry(canonical, idx, entry)?)
200            }
201            StructuralKey::UpdateCategories => {
202                let (id, patch) = parse_update_entry::<CategoryPatch>(canonical, idx, entry)?;
203                SpacePatchOp::UpdateCategory { id, patch }
204            }
205        };
206        out.push(op);
207    }
208    Ok(out)
209}
210
211/// Deserialize one Add* entry into the per-key payload type.
212fn parse_entry<T: serde::de::DeserializeOwned>(
213    canonical: &'static str,
214    idx: usize,
215    entry: Value,
216) -> Result<T, String> {
217    serde_json::from_value(entry)
218        .map_err(|e| format!("{canonical}[{idx}]: failed to parse entry: {e}"))
219}
220
221/// Remove duplicate member entries whose `id` matches `caller_identity`,
222/// keeping the first such entry. Other members are passed through unchanged.
223///
224/// Used by [`handle_space_join`]'s TOCTOU recovery when two concurrent
225/// joins from the same caller both wrote member entries. Per RFC 8620
226/// §1.6's forward-compat posture, the join is idempotent: repeated writes
227/// that converge on the same state are not failures. After dedup the
228/// caller appears exactly once in the members list, which is the join's
229/// contract.
230fn dedup_caller_members(members: Vec<Value>, caller_identity: &str) -> Vec<Value> {
231    let mut seen_ours = false;
232    members
233        .into_iter()
234        .filter(|m| {
235            if m.get("id").and_then(|v| v.as_str()) == Some(caller_identity) {
236                if seen_ours {
237                    false
238                } else {
239                    seen_ours = true;
240                    true
241                }
242            } else {
243                true
244            }
245        })
246        .collect()
247}
248
249/// Parse one Remove* entry — a bare string id.
250fn parse_id_entry(canonical: &'static str, idx: usize, entry: Value) -> Result<Id, String> {
251    match entry {
252        Value::String(s) => Id::new_validated(s).map_err(|e| format!("{canonical}[{idx}]: {e}")),
253        other => Err(format!(
254            "{canonical}[{idx}] must be a string Id, got {}",
255            jmap_server::json_type_name(&other)
256        )),
257    }
258}
259
260/// Parse one Update* entry into (id, patch). The wire form is an object
261/// with an `id` property plus the patch fields at the top level; we split
262/// `id` off and deserialize the remainder as the typed patch.
263fn parse_update_entry<P: serde::de::DeserializeOwned>(
264    canonical: &'static str,
265    idx: usize,
266    entry: Value,
267) -> Result<(Id, P), String> {
268    let mut obj = match entry {
269        Value::Object(o) => o,
270        other => {
271            return Err(format!(
272                "{canonical}[{idx}] must be a JSON object, got {}",
273                jmap_server::json_type_name(&other)
274            ));
275        }
276    };
277    let id_val = obj
278        .remove("id")
279        .ok_or_else(|| format!("{canonical}[{idx}] missing required \"id\" property"))?;
280    let id = match id_val {
281        Value::String(s) => {
282            Id::new_validated(s).map_err(|e| format!("{canonical}[{idx}].id: {e}"))?
283        }
284        other => {
285            return Err(format!(
286                "{canonical}[{idx}].id must be a string, got {}",
287                jmap_server::json_type_name(&other)
288            ));
289        }
290    };
291    let patch: P = serde_json::from_value(Value::Object(obj))
292        .map_err(|e| format!("{canonical}[{idx}]: failed to parse patch fields: {e}"))?;
293    Ok((id, patch))
294}
295
296/// Parse one `addMembers` entry. Wire form:
297/// `{"id": "<ChatContact.id>", "roleIds": ["<RoleId>", …] (optional)}`.
298fn parse_add_member_entry(
299    canonical: &'static str,
300    idx: usize,
301    entry: Value,
302) -> Result<(Id, Vec<Id>), String> {
303    let mut obj = match entry {
304        Value::Object(o) => o,
305        other => {
306            return Err(format!(
307                "{canonical}[{idx}] must be a JSON object, got {}",
308                jmap_server::json_type_name(&other)
309            ));
310        }
311    };
312    let id_val = obj
313        .remove("id")
314        .ok_or_else(|| format!("{canonical}[{idx}] missing required \"id\" property"))?;
315    let user_id = match id_val {
316        Value::String(s) => {
317            Id::new_validated(s).map_err(|e| format!("{canonical}[{idx}].id: {e}"))?
318        }
319        other => {
320            return Err(format!(
321                "{canonical}[{idx}].id must be a string, got {}",
322                jmap_server::json_type_name(&other)
323            ));
324        }
325    };
326    let role_ids: Vec<Id> = match obj.remove("roleIds") {
327        None | Some(Value::Null) => Vec::new(),
328        Some(v) => serde_json::from_value(v)
329            .map_err(|e| format!("{canonical}[{idx}].roleIds must be a string array: {e}"))?,
330    };
331    if let Some(extra) = obj.keys().next() {
332        return Err(format!(
333            "{canonical}[{idx}] has unexpected property \"{extra}\""
334        ));
335    }
336    Ok((user_id, role_ids))
337}
338
339// ---------------------------------------------------------------------------
340// Space/get
341// ---------------------------------------------------------------------------
342
343/// Handle a `Space/get` method call (draft-atwood-jmap-chat-00 §Space).
344///
345/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
346/// `ids`, optional `properties`); the returned `Value` is the §5.1
347/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
348///
349/// `using` is the request's capability list (pass
350/// [`jmap_server::CallContext::using`]). When the backend lists Space for
351/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
352/// `metadata` is returned as an object, by default only with
353/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
354/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
355/// §3.1); see
356/// [`jmap_server::MetadataProjection`].
357///
358/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
359///
360/// # Errors
361///
362/// Returns a method-level [`JmapError`]:
363///
364/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
365///   when `ids` or `properties` is malformed or holds a malformed
366///   `metadata/` subselector;
367/// - `accountNotFound` when the backend does not know `accountId`;
368/// - `requestTooLarge` when `ids` holds more than `maxObjectsInGet` ids;
369/// - `serverFail` when the backend fails.
370pub async fn handle_space_get<B: ChatBackend>(
371    backend: &B,
372    caller: &B::CallerCtx,
373    args: Value,
374    using: &[String],
375) -> Result<HandlerOutput, JmapError> {
376    let (account_id, mut args) = extract_account_id(args)?;
377
378    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
379    if !backend
380        .account_exists(caller, &account_id)
381        .await
382        .map_err(|e| server_fail_from_backend(&e))?
383    {
384        return Err(JmapError::account_not_found());
385    }
386    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
387
388    let ids: Option<Vec<Id>> = match args.remove("ids") {
389        None | Some(Value::Null) => None,
390        Some(v) => Some(
391            serde_json::from_value(v)
392                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
393        ),
394    };
395
396    // Parse the `properties` request argument per RFC 8620 §5.1. The
397    // reference `MemoryBackend` returns full Space objects regardless;
398    // this handler applies the projection post-hoc (which is also
399    // where the non-member field trim layers on, per
400    // draft-atwood-jmap-chat-00 §Space/get + bd:JMAP-v9py.4).
401    let properties: Option<Vec<String>> = match args.remove("properties") {
402        None | Some(Value::Null) => None,
403        Some(v) => Some(
404            serde_json::from_value(v)
405                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
406        ),
407    };
408
409    let projection = MetadataProjection::new(
410        properties.as_deref(),
411        true,
412        using,
413        backend.metadata_info::<Space>(caller, &account_id).as_ref(),
414    )?;
415
416    let ids_slice = ids.as_deref();
417    let (list, mut not_found) = backend
418        .get_objects::<Space>(caller, &account_id, ids_slice, properties.as_deref())
419        .await
420        .map_err(|e| server_fail_from_backend(&e))?;
421
422    let state = backend
423        .get_state::<Space>(caller, &account_id)
424        .await
425        .map_err(|e| server_fail_from_backend(&e))?;
426
427    // Resolve the caller's member id once for the whole request. The
428    // membership check fires per Space; the per-Space cost is a
429    // linear scan over `members` (small in the reference impl).
430    // The caller is the owner, whose member entry is the accountId
431    // (draft-atwood-jmap-chat-00 §Terminology, §SpaceMember.id). This
432    // holds whether or not `principal_id` resolves a caller identity
433    // (bd:JMAP-yt1w.36).
434    let caller_member_id: &Id = &account_id;
435
436    // First pass: classify each backend-returned Space against the
437    // non-member-vs-non-previewable rule (bd:JMAP-v9py.20). Spaces
438    // that fall in that bucket are lifted out of `list` into
439    // `not_found` so a non-member caller cannot distinguish "Space
440    // exists but is not publicly previewable" from "Space does not
441    // exist" — both produce an identical `notFound` entry per
442    // draft-atwood-jmap-chat-00 §Space/get.
443    let mut visible_list: Vec<&Space> = Vec::with_capacity(list.len());
444    for space in &list {
445        if non_member_non_previewable(space, caller_member_id) {
446            not_found.push(space.id.clone());
447        } else {
448            visible_list.push(space);
449        }
450    }
451
452    let list_json: Vec<Value> = visible_list
453        .iter()
454        .map(|space| {
455            project_space_for_caller(space, caller_member_id, properties.as_deref(), &projection)
456        })
457        .collect::<Result<Vec<_>, _>>()?;
458
459    Ok(HandlerOutput::new(json!({
460        "accountId": account_id.as_ref(),
461        "state": state.as_ref(),
462        "list": list_json,
463        "notFound": not_found_json(&not_found),
464    })))
465}
466
467/// Returns `true` when the caller is a non-member of `space` AND the
468/// Space is not publicly previewable.
469///
470/// Per draft-atwood-jmap-chat-00 §Space/get, such Spaces MUST be
471/// classified as `notFound` for the caller — the
472/// kit's `handle_space_get` lifts them out of `list` and into
473/// `not_found` before the response is shaped. The response is then
474/// indistinguishable from the "Space does not exist" outcome, so a
475/// non-member caller cannot probe for the existence of a private
476/// Space.
477///
478/// `caller_member_id` is the caller's member entry id: the accountId,
479/// since the caller is the owner (draft-atwood-jmap-chat-00
480/// §Terminology). The rule fires when no entry in the Space's
481/// `members` carries that id AND `isPubliclyPreviewable: false`.
482fn non_member_non_previewable(space: &Space, caller_member_id: &Id) -> bool {
483    let is_member = space
484        .members
485        .iter()
486        .any(|m| m.id.as_ref() == caller_member_id.as_ref());
487    !is_member && !space.is_publicly_previewable
488}
489
490/// Fields a non-member caller may see on a publicly-previewable Space,
491/// per draft-atwood-jmap-chat-00 §Space/get.
492///
493/// The list is exhaustive — any field NOT named here MUST be omitted
494/// from the returned object even when the caller explicitly requests
495/// it via the `/get` `properties` argument. The handler treats the
496/// list as a hard cap, intersected against any `properties` filter.
497const NON_MEMBER_PREVIEWABLE_FIELDS: &[&str] = &[
498    "id",
499    "name",
500    "description",
501    "iconBlobId",
502    "memberCount",
503    "createdAt",
504    "isPublic",
505    "isPubliclyPreviewable",
506    "closedAt",
507];
508
509/// Apply the JMAP `/get` `properties` filter plus the
510/// non-member-previewable field trim to a single Space object before
511/// it lands in the response `list`.
512///
513/// Three cases (draft-atwood-jmap-chat-00 §Space/get):
514///
515/// 1. **Member caller** (`caller_member_id`, the accountId per
516///    §Terminology, matches a `members[i].id`) → return the full Space, intersected with
517///    `properties` if specified. No restricted-view trim.
518/// 2. **Non-member caller AND `isPubliclyPreviewable: true`** →
519///    return the 8-field restricted view, intersected with
520///    `properties` if specified. Fields outside
521///    [`NON_MEMBER_PREVIEWABLE_FIELDS`] are omitted even when the
522///    caller asked for them.
523/// 3. **Non-member caller AND `isPubliclyPreviewable: false`** —
524///    handled BEFORE this function: `handle_space_get` lifts the
525///    Space out of `list` and into `not_found` via
526///    [`non_member_non_previewable`]. By the time
527///    a Space reaches this projection function, it has already
528///    been confirmed visible to the caller. This branch is
529///    therefore unreachable in normal flow; if it WERE reached
530///    (e.g. via a direct call from outside `handle_space_get`),
531///    the conservative fallback is "no field cap, no trim" — same
532///    as a member. Production callers SHOULD route through
533///    `handle_space_get` rather than calling this function
534///    directly so the notFound classification fires.
535fn project_space_for_caller(
536    space: &Space,
537    caller_member_id: &Id,
538    properties: Option<&[String]>,
539    projection: &MetadataProjection,
540) -> Result<Value, JmapError> {
541    let full = serialize_value(space)?;
542
543    // Compute the field set the caller is allowed to see.
544    let is_member = space
545        .members
546        .iter()
547        .any(|m| m.id.as_ref() == caller_member_id.as_ref());
548    let allowed_fields: Option<Vec<&str>> = if is_member {
549        None
550    } else if space.is_publicly_previewable {
551        // Non-member, but the Space is publicly
552        // previewable. Apply the 8-field restricted view.
553        Some(NON_MEMBER_PREVIEWABLE_FIELDS.to_vec())
554    } else {
555        // Non-member of a non-previewable Space — the
556        // outer handler has already lifted this Space
557        // into `not_found` before calling us; reaching
558        // here implies a non-handler call site. Fall back
559        // to full visibility to keep `project_space_for_caller`
560        // a pure projection function with no
561        // notFound side-effect; the caller is responsible
562        // for the visibility decision.
563        None
564    };
565
566    // Intersect the allowed set with the request `properties`
567    // filter, then apply both. Either filter being `None` means
568    // "no constraint from this layer".
569    let request_filter: Option<&[String]> = properties;
570    // draft-ietf-jmap-metadata-05 §2, §3.1 only where the caller sees the
571    // whole Space: metadata is not one of the restricted-view fields.
572    let metadata_source = allowed_fields.is_none().then(|| full.clone());
573    let mut out = match (allowed_fields, request_filter) {
574        (None, None) => full,
575        (None, Some(props)) => filter_object_fields(full, |k| props.iter().any(|p| p == k)),
576        (Some(cap), None) => filter_object_fields(full, |k| cap.contains(&k)),
577        (Some(cap), Some(props)) => {
578            filter_object_fields(full, |k| cap.contains(&k) && props.iter().any(|p| p == k))
579        }
580    };
581    if let Some(source) = &metadata_source {
582        projection.apply(source, &mut out);
583    }
584    Ok(out)
585}
586
587/// Retain only the top-level fields of `value` for which `keep`
588/// returns true. If `value` is not a JSON object, return it
589/// unchanged.
590///
591/// The filter operates on TOP-LEVEL keys only. Nested objects
592/// (e.g. inside `roles[].permissions`) are unaffected. This matches
593/// the RFC 8620 `/get` `properties` semantics and the spec's
594/// restricted-view rule (both reference top-level Space fields).
595fn filter_object_fields<F: Fn(&str) -> bool>(value: Value, keep: F) -> Value {
596    match value {
597        Value::Object(map) => {
598            Value::Object(map.into_iter().filter(|(k, _)| keep(k.as_str())).collect())
599        }
600        other => other,
601    }
602}
603
604// ---------------------------------------------------------------------------
605// Space/changes
606// ---------------------------------------------------------------------------
607
608/// Handle a `Space/changes` method call (draft-atwood-jmap-chat-00 §Space).
609///
610/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
611/// `sinceState`, optional `maxChanges`); the returned `Value` is the
612/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
613/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
614///
615/// `using` is the request's capability list (pass
616/// [`jmap_server::CallContext::using`]); with
617/// `urn:ietf:params:jmap:metadata` the request may set
618/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
619/// without it metadata-only changes are left out (-05 §3).
620///
621/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
622///
623/// # Errors
624///
625/// Returns a method-level [`JmapError`]:
626///
627/// - `invalidArguments` when `accountId` is missing or not a valid Id,
628///   `sinceState` is missing, `maxChanges` is not a positive integer, or
629///   `ignoreMetadataOnlyChanges` is not a boolean;
630/// - `accountNotFound` when the backend does not know `accountId`;
631/// - `cannotCalculateChanges` when the backend cannot compute the changes
632///   since `sinceState`;
633/// - `serverFail` when the backend fails.
634pub async fn handle_space_changes<B: ChatBackend>(
635    backend: &B,
636    caller: &B::CallerCtx,
637    args: Value,
638    using: &[String],
639) -> Result<HandlerOutput, JmapError> {
640    jmap_server::handle_changes::<Space, B>(backend, caller, args, using).await
641}
642
643// ---------------------------------------------------------------------------
644// Space/query
645// ---------------------------------------------------------------------------
646
647/// Handle a `Space/query` method call (draft-atwood-jmap-chat-00 §Space).
648///
649/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
650/// `filter`, optional `sort`, optional `position` / `anchor` /
651/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
652/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
653/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
654/// `total`, optional `limit`).
655///
656/// Unknown filter clauses and sort properties are refused with
657/// `unsupportedFilter` / `unsupportedSort` (RFC 8620 §5.5).
658///
659/// `using` is the request's capability list (pass
660/// [`jmap_server::CallContext::using`]); without
661/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
662/// filter condition is `unsupportedFilter` (-05 §3).
663///
664/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
665///
666/// # Errors
667///
668/// Returns a method-level [`JmapError`]:
669///
670/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
671///   when `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit`
672///   is malformed;
673/// - `accountNotFound` when the backend does not know `accountId`;
674/// - `unsupportedFilter` when the filter does not decode as a Space filter, or
675///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
676///   `urn:ietf:params:jmap:metadata` in `using`;
677/// - `unsupportedSort` when `sort` names a property this server does not
678///   define;
679/// - `anchorNotFound` when `anchor` is not in the results;
680/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
681///   the backend returns.
682pub async fn handle_space_query<B: ChatBackend>(
683    backend: &B,
684    caller: &B::CallerCtx,
685    args: Value,
686    using: &[String],
687) -> Result<HandlerOutput, JmapError> {
688    jmap_server::reject_metadata_filter_arg(
689        &args,
690        jmap_chat_types::SpaceFilterCondition::has_metadata_condition,
691        using,
692    )?;
693    let (account_id, mut args) = extract_account_id(args)?;
694
695    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
696    if !backend
697        .account_exists(caller, &account_id)
698        .await
699        .map_err(|e| server_fail_from_backend(&e))?
700    {
701        return Err(JmapError::account_not_found());
702    }
703
704    let calculate_total: bool = bool_arg(&args, "calculateTotal", false);
705
706    let limit: Option<u64> = match args.remove("limit") {
707        None | Some(Value::Null) => None,
708        Some(v) => match v.as_u64() {
709            Some(n) => Some(n),
710            None => {
711                return Err(JmapError::invalid_arguments(format!(
712                    "limit: expected a non-negative integer, got {}",
713                    jmap_server::json_type_name(&v)
714                )));
715            }
716        },
717    };
718
719    let position: i64 = match args.remove("position") {
720        None | Some(Value::Null) => 0,
721        Some(v) => v.as_i64().ok_or_else(|| {
722            JmapError::invalid_arguments(format!(
723                "position: expected an integer, got {}",
724                jmap_server::json_type_name(&v)
725            ))
726        })?,
727    };
728
729    let (anchor, anchor_offset) = query_anchor_args(&args)?;
730
731    // §Space/query: "Default sort: `name` ascending."
732    default_sort(&mut args, json!([{ "property": "name" }]));
733    reject_unsupported_sort::<SpaceComparator>(args.get("sort"))?;
734    let filter: Option<SpaceFilter> = filter_arg(&mut args)?;
735
736    let sort: Option<Vec<SpaceComparator>> = optional_arg(&mut args, "sort", || {
737        JmapError::invalid_arguments("sort must be an array")
738    })?;
739
740    let result = backend
741        .query_objects::<Space>(
742            caller,
743            &account_id,
744            QueryParams::new()
745                .filter(filter.as_ref())
746                .sort(sort.as_deref())
747                .limit(limit)
748                .position(position)
749                .anchor(anchor.as_ref())
750                .anchor_offset(anchor_offset),
751        )
752        .await
753        .map_err(JmapError::from)?;
754
755    let mut resp = json!({
756        "accountId": account_id.as_ref(),
757        "queryState": result.query_state.as_ref(),
758        "canCalculateChanges": result.can_calculate_changes,
759        "position": result.position,
760        "ids": result.ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
761    });
762    if calculate_total && let Some(t) = result.total {
763        resp["total"] = json!(t);
764    }
765
766    Ok(HandlerOutput::new(resp))
767}
768
769// ---------------------------------------------------------------------------
770// Space/queryChanges
771// ---------------------------------------------------------------------------
772
773/// Handle a `Space/queryChanges` method call (draft-atwood-jmap-chat-00 §Space).
774///
775/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
776/// optional `filter`, optional `sort`, `sinceQueryState`, optional
777/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
778/// returned `Value` is the §5.6 `/queryChanges` response shape
779/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
780/// `removed`, `added`).
781///
782/// `using` is the request's capability list (pass
783/// [`jmap_server::CallContext::using`]); without
784/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
785/// filter condition is `unsupportedFilter` (-05 §3).
786///
787/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
788///
789/// # Errors
790///
791/// Returns a method-level [`JmapError`]:
792///
793/// - `invalidArguments` when `accountId` is missing or not a valid Id,
794///   `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
795///   `upToId` is malformed;
796/// - `accountNotFound` when the backend does not know `accountId`;
797/// - `unsupportedFilter` when the filter does not decode as a Space filter, or
798///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
799///   `urn:ietf:params:jmap:metadata` in `using`;
800/// - `unsupportedSort` when `sort` names a property this server does not
801///   define;
802/// - `cannotCalculateChanges` when the backend cannot compute the changes
803///   since `sinceQueryState`;
804/// - `serverFail` when the backend fails, or any other RFC 8620 §5.6 error
805///   the backend returns.
806pub async fn handle_space_query_changes<B: ChatBackend>(
807    backend: &B,
808    caller: &B::CallerCtx,
809    mut args: Value,
810    using: &[String],
811) -> Result<HandlerOutput, JmapError> {
812    jmap_server::reject_metadata_filter_arg(
813        &args,
814        jmap_chat_types::SpaceFilterCondition::has_metadata_condition,
815        using,
816    )?;
817    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
818    // query, so the §Space/query default sort applies here too.
819    if let Value::Object(map) = &mut args {
820        default_sort(map, json!([{ "property": "name" }]));
821    }
822    reject_unsupported_sort::<SpaceComparator>(args.get("sort"))?;
823    jmap_server::handle_query_changes::<Space, B>(backend, caller, args).await
824}
825
826// ---------------------------------------------------------------------------
827// Space/set count-limit enforcement (bd:JMAP-g7wu.2.4.8, bd:JMAP-x2gd.44)
828// ---------------------------------------------------------------------------
829
830// `count_add_ops` is shared with the reference `MemoryBackend`'s
831// backend-canonical cap enforcement via `crate::helpers::count_add_ops`.
832
833/// Enforce per-Space count limits before dispatching structural ops to
834/// [`ChatSpaces::apply_space_patch`](crate::ChatSpaces::apply_space_patch).
835///
836/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
837/// 2026-05-11), each of the four `add*` ops MUST return an `overQuota`
838/// [`SetError`] (RFC 8620 §5.3) when the resulting count would exceed a
839/// server-defined limit. The handler queries the backend's
840/// [`ChatSettings::limits`](crate::ChatSettings::limits) for the cap values, fetches the current
841/// Space to count existing roles/members/channels/categories, then
842/// compares `existing + add` against the cap for each affected
843/// collection.
844///
845/// Atomicity: if any aggregate would exceed its cap, the whole update
846/// target is rejected with one `overQuota` `SetError` — matching
847/// RFC 8620 §5.3 `/set` semantics at the target level. The handler
848/// surfaces the failure in `notUpdated[id]` and skips the
849/// `apply_space_patch` call entirely.
850///
851/// # Returns
852///
853/// - `Ok(None)` — no Add* ops in the patch, or all caps satisfied.
854/// - `Ok(Some(SetError))` — one or more caps would be exceeded; the
855///   `SetError` is `overQuota` with a description naming the offending
856///   collection.
857/// - `Err(JmapError)` — the backend read failed; the caller propagates
858///   as a `serverFail` for the whole `Space/set` request.
859///
860/// If `get_objects` returns the Space as missing (e.g. the id was
861/// destroyed since `get_state` was read), this helper returns
862/// `Ok(None)` and lets `apply_space_patch` return the canonical
863/// `notFound` `SetError` for consistency with the existing not-found
864/// path.
865async fn check_space_count_limits<B: ChatBackend>(
866    backend: &B,
867    caller: &B::CallerCtx,
868    account_id: &Id,
869    space_id: &Id,
870    ops: &[SpacePatchOp],
871    limits: &ChatLimits,
872) -> Result<Option<SetError>, JmapError> {
873    let (add_roles, add_members, add_channels, add_categories) = count_add_ops(ops);
874    if add_roles == 0 && add_members == 0 && add_channels == 0 && add_categories == 0 {
875        return Ok(None);
876    }
877
878    let (found, _not_found) = backend
879        .get_objects::<Space>(
880            caller,
881            account_id,
882            Some(std::slice::from_ref(space_id)),
883            None,
884        )
885        .await
886        .map_err(|e| server_fail_from_backend(&e))?;
887
888    // If the Space is missing, let apply_space_patch surface notFound
889    // through its existing path. The cap check has nothing to do.
890    let Some(space) = found.into_iter().next() else {
891        return Ok(None);
892    };
893
894    let cur_roles = u32::try_from(space.roles.len()).unwrap_or(u32::MAX);
895    let cur_members = u32::try_from(space.members.len()).unwrap_or(u32::MAX);
896    let cur_categories = u32::try_from(space.categories.len()).unwrap_or(u32::MAX);
897    let cur_channels = u32::try_from(
898        space.uncategorized_channel_ids.len()
899            + space
900                .categories
901                .iter()
902                .map(|c| c.channel_ids.len())
903                .sum::<usize>(),
904    )
905    .unwrap_or(u32::MAX);
906
907    // First cap to trip determines the SetError. `find_map` expresses
908    // that ordered "first hit wins" semantic in one combinator chain
909    // rather than four sequential `if-let-Some` early-returns. Mirrors
910    // the backend-canonical sibling [`crate::memory::check_count_caps`].
911    Ok([
912        (
913            "too many roles",
914            cur_roles,
915            add_roles,
916            limits.max_roles_per_space,
917        ),
918        (
919            "too many members",
920            cur_members,
921            add_members,
922            limits.max_space_members,
923        ),
924        (
925            "too many channels",
926            cur_channels,
927            add_channels,
928            limits.max_channels_per_space,
929        ),
930        (
931            "too many categories",
932            cur_categories,
933            add_categories,
934            limits.max_categories_per_space,
935        ),
936    ]
937    .into_iter()
938    .find_map(|(description, current, add, cap)| count_exceeded(description, current, add, cap)))
939}
940
941/// The `overQuota` [`SetError`] with `description` when adding `add` items
942/// to a collection of `current` would pass `cap`, or `None` (also when
943/// nothing is added).
944///
945/// Build an `overQuota` `SetError` naming the first offending collection.
946/// The handler emits a single error per target, so we surface the
947/// first cap to trip; a client retry after fixing that collection
948/// would expose any second offender on the next request.
949///
950/// Per-aggregate static description — names which aggregate was
951/// exceeded without disclosing the per-Space count or the per-account
952/// cap value. See bd:JMAP-x2gd.107: leaking either through an error
953/// description back-channels deployment policy and membership counts
954/// to any caller who can propose a /set patch. The aggregate name
955/// alone is enough for a client to know which collection to retry
956/// without; numeric counts and caps are deployment-private. Byte-
957/// identical to the backend-canonical description in
958/// `memory::check_count_caps` for response-shape parity.
959fn count_exceeded(description: &'static str, current: u32, add: u32, cap: u32) -> Option<SetError> {
960    if add == 0 {
961        return None;
962    }
963    if current.saturating_add(add) > cap {
964        Some(SetError::new(SetErrorType::OverQuota).with_description(description))
965    } else {
966        None
967    }
968}
969
970// ---------------------------------------------------------------------------
971// Space/set
972// ---------------------------------------------------------------------------
973
974/// Id of the bootstrap `"Admin"` role [`handle_space_set`] gives every
975/// newly created Space (bd:JMAP-yt1w.34).
976const BOOTSTRAP_ADMIN_ROLE_ID: &str = "admin";
977
978/// Position of the bootstrap `"Admin"` role: 2^53-1, the largest JMAP
979/// `UnsignedInt` (RFC 8620 §1.3), so no later role can outrank it.
980const BOOTSTRAP_ADMIN_ROLE_POSITION: u64 = 9_007_199_254_740_991;
981
982/// Resolve `#creationId` references in each `updateChannels[]` entry's
983/// `permissionOverrides[].targetId` (RFC 8620 §5.3).
984///
985/// draft-atwood-jmap-chat-00 §`ChannelPermission`: `targetId` is "A
986/// [`SpaceRole`] id or a [`SpaceMember`] `id`", or the Space id for `@everyone`;
987/// a `SpaceMember` id is a `ChatContact` id. `SpaceRole` ids are server-set and
988/// never start with `#`, so every `targetId` is resolved regardless of
989/// `targetType`. An unknown reference is `invalidProperties` naming
990/// `updateChannels`.
991fn resolve_override_targets(
992    patch: &mut Value,
993    created_ids: &std::collections::BTreeMap<Id, Id>,
994) -> Result<(), Box<jmap_server::SetError>> {
995    let Some(Value::Array(channels)) = patch.get_mut("updateChannels") else {
996        return Ok(());
997    };
998    for channel in channels {
999        let Some(Value::Array(overrides)) = channel.get_mut("permissionOverrides") else {
1000            continue;
1001        };
1002        for entry in overrides {
1003            if let Some(Value::String(raw)) = entry.get_mut("targetId") {
1004                *raw = resolve_ref(raw, "updateChannels", created_ids)?
1005                    .as_ref()
1006                    .to_owned();
1007            }
1008        }
1009    }
1010    Ok(())
1011}
1012
1013/// Handle a `Space/set` method call (draft-atwood-jmap-chat-00 §Space).
1014///
1015/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
1016/// `ifInState`, optional `create` / `update` / `destroy` maps), augmented
1017/// with the JMAP Chat structural-mutation pipeline (addRoles / removeRoles
1018/// / updateRoles / addMembers / removeMembers / updateMembers / addCategories
1019/// / removeCategories / updateCategories / addChannels / removeChannels /
1020/// updateChannels / metadata-patch surface); the returned `Value` is the
1021/// §5.3 `/set` response shape (`accountId`, `oldState`, `newState`, plus
1022/// the per-operation `created` / `notCreated` / `updated` / `notUpdated`
1023/// / `destroyed` / `notDestroyed` maps).
1024///
1025/// On create the Space is born with one role, `"Admin"` (id `"admin"`,
1026/// every permission in [`SPEC_PERMISSION_NAMES`], position 2^53-1), and
1027/// one member, the owner (id = `accountId`) holding that role, per
1028/// draft-atwood-jmap-chat-00 §Space/set "Creating a Space".
1029///
1030/// Validation enforced here (not in the backend):
1031/// - `name` is required on create.
1032/// - `id`, `createdAt`, `memberCount` are server-set and rejected in updates
1033///   unless identical to the stored value (RFC 8620 §5.3); an empty patch is a no-op success.
1034/// - Keys listed by [`ChatSpaces::space_extension_properties`](crate::ChatSpaces::space_extension_properties) are
1035///   accepted on create and update, except a core Space property or a
1036///   structural patch key, which keeps its core meaning (`closedAt` in an
1037///   update is `invalidProperties`); any other unknown create or update
1038///   key is `invalidProperties`.
1039/// - draft-ietf-jmap-metadata-05 `metadata` and `privateMetadata` are
1040///   `invalidProperties` without `urn:ietf:params:jmap:metadata` in
1041///   `using` (pass [`jmap_server::CallContext::using`]; -05 §3), as is
1042///   `null` for either in a create (-05 §3.2). An update applies them as
1043///   RFC 8620 §5.3 [`PatchObject`] paths through
1044///   [`ChatStore::update_object`](crate::ChatStore::update_object), before the structural keys; the
1045///   backend validates the rest.
1046///
1047/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1048///
1049/// A `removeMembers` element, or the `id` of an `addMembers` or
1050/// `updateMembers` entry, that is a `#creationId` reference names a
1051/// `ChatContact` created earlier in the request and resolves against
1052/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
1053/// §5.3); an unknown reference is `invalidProperties` naming the patch key.
1054/// The channel ids in `removeChannels`, `updateChannels` and category
1055/// `channelIds` are not resolved: a channel Chat is created only by
1056/// `addChannels`, which has no creation id.
1057///
1058/// # Errors
1059///
1060/// Returns a method-level [`JmapError`]:
1061///
1062/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
1063///   an element of `destroy` is not a string;
1064/// - `accountNotFound` when the backend does not know `accountId`;
1065/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
1066///   more than `maxObjectsInSet` objects;
1067/// - `stateMismatch` when `ifInState` is not the current state;
1068/// - `serverFail` when the backend fails.
1069///
1070/// A create, update or destroy that fails on its own is a [`SetError`] in
1071/// the response, not an `Err`.
1072pub async fn handle_space_set<B: ChatBackend>(
1073    backend: &B,
1074    caller: &B::CallerCtx,
1075    created_ids: &BTreeMap<Id, Id>,
1076    mut args: Value,
1077    using: &[String],
1078) -> Result<HandlerOutput, JmapError> {
1079    // A `#creationId` blob reference names a blob created earlier in the
1080    // request (RFC 8620 §5.3; draft-ietf-jmap-blobext-03 §8); an unknown one
1081    // is left for the Id checks below.
1082    jmap_server::resolve_blob_refs(&mut args, &["iconBlobId"], created_ids);
1083    let (account_id, mut args) = extract_account_id(args)?;
1084
1085    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
1086    if !backend
1087        .account_exists(caller, &account_id)
1088        .await
1089        .map_err(|e| server_fail_from_backend(&e))?
1090    {
1091        return Err(JmapError::account_not_found());
1092    }
1093
1094    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
1095    // unbounded /set batches before touching the storage layer.
1096    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
1097
1098    let old_state = backend
1099        .get_state::<Space>(caller, &account_id)
1100        .await
1101        .map_err(|e| server_fail_from_backend(&e))?;
1102
1103    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
1104        && if_in_state != old_state.as_ref()
1105    {
1106        return Err(JmapError::state_mismatch());
1107    }
1108
1109    // `ChatSpaces::space_extension_properties`: "A listed key that is
1110    // already a core Space property or a structural patch key keeps its
1111    // core meaning", so such a key is dropped here and never reaches
1112    // `extra` on create or `apply_space_metadata_patch` on update.
1113    let extension_props: Vec<&str> = backend
1114        .space_extension_properties(caller, &account_id)
1115        .iter()
1116        .copied()
1117        .filter(|&key| {
1118            !(Space::SERVER_SET.contains(&key)
1119                || Space::CLIENT_SETTABLE.contains(&key)
1120                || StructuralKey::from_wire(key).is_some())
1121        })
1122        .collect();
1123
1124    let ctx = SetCtx {
1125        backend,
1126        caller,
1127        account_id: &account_id,
1128        created_ids,
1129        using,
1130        extension_props: &extension_props,
1131    };
1132    let mut acc = SetAccumulators::default();
1133    let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
1134
1135    // Query per-Space content limits once for the whole request. The
1136    // values are implementation-defined (bd:JMAP-g7wu.2.4.8 / workspace
1137    // AGENTS.md "Backend caps and limits") and the trait method is a
1138    // sync default that backends can override per-account. Querying
1139    // once per request (rather than once per target) is correct because
1140    // the limits are scoped to the account, not the Space.
1141    let space_limits = backend.limits(caller, &account_id);
1142
1143    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
1144    jmap_server::resolve_set_id_refs(&mut args, created_ids, &acc.created);
1145    mutated |= set_update(&ctx, &mut args, &mut acc, &space_limits).await?;
1146    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;
1147
1148    finalize_set_response::<B, Space>(backend, caller, &account_id, old_state, mutated, acc).await
1149}
1150
1151/// What every `Space/set` sub-function needs from the request
1152/// (docs/design/set-handler-split.md).
1153struct SetCtx<'a, B: ChatBackend> {
1154    backend: &'a B,
1155    caller: &'a B::CallerCtx,
1156    account_id: &'a Id,
1157    /// The request-wide `#creationId` map (RFC 8620 §5.3).
1158    created_ids: &'a BTreeMap<Id, Id>,
1159    /// The request's `using` capabilities.
1160    using: &'a [String],
1161    /// The backend's extension properties, less any core or structural
1162    /// key.
1163    extension_props: &'a [&'a str],
1164}
1165
1166/// The `create` part of `Space/set`. Returns whether the backend was
1167/// written.
1168async fn set_create<B: ChatBackend>(
1169    ctx: &SetCtx<'_, B>,
1170    args: &mut serde_json::Map<String, Value>,
1171    acc: &mut SetAccumulators,
1172) -> Result<bool, JmapError> {
1173    let mut mutated = false;
1174    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
1175        for (create_id, obj_val) in create_map {
1176            mutated |= create_one(ctx, create_id, obj_val, acc).await?;
1177        }
1178    }
1179    Ok(mutated)
1180}
1181
1182/// The client-supplied properties of a `Space/set` create, checked.
1183struct CreateFields {
1184    name: String,
1185    icon_blob_id: Option<Id>,
1186    metadata: Option<serde_json::Map<String, Value>>,
1187    private_metadata: Option<serde_json::Map<String, Value>>,
1188    is_public: bool,
1189    is_publicly_previewable: bool,
1190}
1191
1192/// Check one `Space/set` create object and return its properties, or the
1193/// [`SetError`] value for `notCreated`.
1194fn create_fields(
1195    obj_val: &Value,
1196    extension_props: &[&str],
1197    using: &[String],
1198) -> Result<CreateFields, Value> {
1199    if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Space>) {
1200        return Err(serde_json::Value::from(&err));
1201    }
1202    // RFC 8620 §5.3 invalidProperties: "It contains properties that
1203    // are invalid according to the type specification of this
1204    // record type." A key that is neither a client-settable Space
1205    // property nor a registered extension property is rejected, as
1206    // on update, rather than silently dropped.
1207    let unknown_keys: Vec<&str> = obj_val
1208        .as_object()
1209        .into_iter()
1210        .flat_map(|m| m.keys())
1211        .map(String::as_str)
1212        .filter(|key| !(Space::CLIENT_SETTABLE.contains(key) || extension_props.contains(key)))
1213        .collect();
1214    if !unknown_keys.is_empty() {
1215        return Err(json!({ "type": "invalidProperties", "properties": unknown_keys }));
1216    }
1217    if let Some(Err(err)) = obj_val
1218        .as_object()
1219        .map(|o| check_metadata_entry(o, true, using))
1220    {
1221        return Err(serde_json::Value::from(&*err));
1222    }
1223    // draft-ietf-jmap-metadata-05 §3.2: the create sets the
1224    // metadata properties; the backend validates them.
1225    let (metadata, private_metadata) = create_metadata(obj_val)?;
1226    // Optional properties: a wrongly-typed value is invalidProperties
1227    // (RFC 8620 §5.3), not a silent absence.
1228    if let Some(err) = mistyped_create_props(
1229        obj_val,
1230        &[
1231            ("description", PropType::Str),
1232            ("iconBlobId", PropType::Str),
1233            ("isPublic", PropType::Bool),
1234            ("isPubliclyPreviewable", PropType::Bool),
1235        ],
1236    ) {
1237        return Err(err);
1238    }
1239    // draft-atwood-jmap-chat-00 §Space/set "Creating a Space":
1240    // "Optional: `description` (String), `iconBlobId` (String)."
1241    // The value is a blob Id, so it must be a valid RFC 8620 §1.2
1242    // Id. Whether the blob exists is left to the backend.
1243    let icon_blob_id = match obj_val.get("iconBlobId").and_then(|v| v.as_str()) {
1244        None => None,
1245        Some(raw) => Some(
1246            jmap_server::parse_wire_id(raw, "iconBlobId")
1247                .map_err(|err| serde_json::Value::from(&*err))?,
1248        ),
1249    };
1250    let name = match obj_val.get("name").and_then(|v| v.as_str()) {
1251        Some(s) if !s.is_empty() => s.to_owned(),
1252        _ => return Err(json!({ "type": "invalidProperties", "properties": ["name"] })),
1253    };
1254    if name.len() > 256 {
1255        return Err(json!({ "type": "invalidProperties", "properties": ["name"] }));
1256    }
1257
1258    let is_public = obj_val
1259        .get("isPublic")
1260        .and_then(|v| v.as_bool())
1261        .unwrap_or(false);
1262    let is_publicly_previewable = obj_val
1263        .get("isPubliclyPreviewable")
1264        .and_then(|v| v.as_bool())
1265        .unwrap_or(false);
1266    Ok(CreateFields {
1267        name,
1268        icon_blob_id,
1269        metadata,
1270        private_metadata,
1271        is_public,
1272        is_publicly_previewable,
1273    })
1274}
1275
1276/// One `create` entry of `Space/set`. Returns whether the backend was
1277/// written.
1278async fn create_one<B: ChatBackend>(
1279    ctx: &SetCtx<'_, B>,
1280    create_id: &str,
1281    obj_val: &Value,
1282    acc: &mut SetAccumulators,
1283) -> Result<bool, JmapError> {
1284    let fields = match create_fields(obj_val, ctx.extension_props, ctx.using) {
1285        Ok(fields) => fields,
1286        Err(err) => {
1287            acc.not_created.insert(create_id.to_owned(), err);
1288            return Ok(false);
1289        }
1290    };
1291
1292    let now_str = now_utc_string();
1293    let now: UTCDate = UTCDate::from(now_str.as_ref());
1294
1295    // draft-atwood-jmap-chat-00 §Space/set "Creating a Space": the
1296    // server "adds the caller to `members` with at least one role
1297    // granting permissions sufficient to administer the Space". The
1298    // caller acts as the account owner, whose member entry is the
1299    // accountId (§SpaceMember `id`). Bootstrap configuration
1300    // (bd:JMAP-yt1w.34): one "Admin" role holding every spec
1301    // permission at the highest UnsignedInt position. Role ids are
1302    // scoped to their Space, so the fixed id cannot collide with a
1303    // role in another Space.
1304    // ponytail: one fixed bootstrap policy for every backend, though
1305    // the draft calls it server-defined. If a consumer needs another
1306    // policy, add a ChatBackend hook returning the bootstrap role,
1307    // defaulting to this one.
1308    let admin_role: SpaceRole = serde_json::from_value(json!({
1309        "id": BOOTSTRAP_ADMIN_ROLE_ID,
1310        "name": "Admin",
1311        "permissions": SPEC_PERMISSION_NAMES,
1312        "position": BOOTSTRAP_ADMIN_ROLE_POSITION,
1313    }))
1314    .expect("bootstrap role literal matches SpaceRole");
1315    let owner: SpaceMember = serde_json::from_value(json!({
1316        "id": ctx.account_id,
1317        "roleIds": [BOOTSTRAP_ADMIN_ROLE_ID],
1318        "joinedAt": now_str,
1319    }))
1320    .expect("bootstrap member literal matches SpaceMember");
1321
1322    let build = |id: &Id| {
1323        let mut space = Space::new(
1324            id.clone(),
1325            fields.name,
1326            vec![admin_role],
1327            vec![owner],
1328            vec![],
1329            vec![],
1330            now,
1331            fields.is_public,
1332            fields.is_publicly_previewable,
1333            1,
1334        );
1335        if let Some(desc) = obj_val.get("description").and_then(|v| v.as_str()) {
1336            space.description = Some(desc.to_owned());
1337        }
1338        space.icon_blob_id = fields.icon_blob_id;
1339        space.metadata = fields.metadata;
1340        space.private_metadata = fields.private_metadata;
1341        for &key in ctx.extension_props {
1342            match obj_val.get(key) {
1343                None | Some(Value::Null) => {}
1344                Some(v) => {
1345                    space.extra.insert(key.to_owned(), v.clone());
1346                }
1347            }
1348        }
1349        space
1350    };
1351
1352    match ctx
1353        .backend
1354        .create_object::<Space, _>(ctx.caller, ctx.account_id, create_id, build)
1355        .await
1356    {
1357        Ok((_server_id, created_obj)) => {
1358            acc.created.insert(
1359                create_id.to_owned(),
1360                jmap_server::serialize_value(&created_obj)?,
1361            );
1362            Ok(true)
1363        }
1364        Err(e) => {
1365            acc.not_created
1366                .insert(create_id.to_owned(), backend_set_error_value(e));
1367            Ok(false)
1368        }
1369    }
1370}
1371
1372/// The `update` part of `Space/set`. `space_limits` are the account's
1373/// per-Space count caps. Returns whether the backend was written.
1374async fn set_update<B: ChatBackend>(
1375    ctx: &SetCtx<'_, B>,
1376    args: &mut serde_json::Map<String, Value>,
1377    acc: &mut SetAccumulators,
1378    space_limits: &ChatLimits,
1379) -> Result<bool, JmapError> {
1380    let mut mutated = false;
1381    if let Some(Value::Object(update_map)) = args.remove("update") {
1382        for (id_str, patch_val) in update_map {
1383            mutated |= update_one(ctx, id_str, patch_val, acc, space_limits).await?;
1384        }
1385    }
1386    Ok(mutated)
1387}
1388
1389/// Resolve the `#creationId` references in one `Space/set` update patch,
1390/// or return the [`SetError`] value for `notUpdated`.
1391///
1392/// draft-atwood-jmap-chat-00 §Space/set "Updating a Space": these keys
1393/// name members by `ChatContact` id.
1394fn resolve_update_refs<B: ChatBackend>(
1395    ctx: &SetCtx<'_, B>,
1396    patch_val: &mut Value,
1397) -> Result<(), Value> {
1398    resolve_refs(patch_val, &["removeMembers"], ctx.created_ids)
1399        .and_then(|()| {
1400            resolve_entry_refs(
1401                patch_val,
1402                &[
1403                    ("addMembers", "id", "addMembers"),
1404                    ("updateMembers", "id", "updateMembers"),
1405                ],
1406                ctx.created_ids,
1407            )
1408        })
1409        .and_then(|()| resolve_override_targets(patch_val, ctx.created_ids))
1410        .map_err(|err| serde_json::Value::from(&*err))
1411}
1412
1413/// Whether the Space `id` is closed (`closedAt` set), or the `serverFail`
1414/// value for `notUpdated` when the backend read fails. A Space the read
1415/// does not find is not closed.
1416async fn space_is_closed<B: ChatBackend>(ctx: &SetCtx<'_, B>, id: &Id) -> Result<bool, Value> {
1417    ctx.backend
1418        .get_objects::<Space>(
1419            ctx.caller,
1420            ctx.account_id,
1421            Some(std::slice::from_ref(id)),
1422            None,
1423        )
1424        .await
1425        .map(|(spaces, _)| spaces.first().is_some_and(|s| s.closed_at.is_some()))
1426        .map_err(|e| server_fail_value_from_backend(&e))
1427}
1428
1429/// One `update` entry of `Space/set`. Returns whether the backend was
1430/// written; a target can land in `notUpdated` after an earlier write
1431/// for it succeeded.
1432async fn update_one<B: ChatBackend>(
1433    ctx: &SetCtx<'_, B>,
1434    id_str: String,
1435    mut patch_val: Value,
1436    acc: &mut SetAccumulators,
1437    space_limits: &ChatLimits,
1438) -> Result<bool, JmapError> {
1439    let id = match jmap_server::parse_wire_id(&id_str, "id") {
1440        Ok(id) => id,
1441        Err(err) => {
1442            acc.not_updated
1443                .insert(id_str, serde_json::Value::from(&*err));
1444            return Ok(false);
1445        }
1446    };
1447    if let Err(err) = resolve_update_refs(ctx, &mut patch_val) {
1448        acc.not_updated.insert(id_str, err);
1449        return Ok(false);
1450    }
1451
1452    // draft-atwood-jmap-chat-00 §Space `closedAt`: "The server
1453    // MUST also reject ... every `Space/set` update to the Space
1454    // with a `forbidden` SetError, except a member removing
1455    // themselves via `removeMembers`." Checked before the
1456    // read-only and no-op checks so that `{}` and server-set keys
1457    // are `forbidden` too. A patch that may be a self-removal is
1458    // checked again once parsed, below.
1459    let closed = match space_is_closed(ctx, &id).await {
1460        Ok(closed) => closed,
1461        Err(err) => {
1462            acc.not_updated.insert(id_str, err);
1463            return Ok(false);
1464        }
1465    };
1466    if closed && patch_val.get("removeMembers") != Some(&json!([ctx.account_id])) {
1467        acc.not_updated.insert(id_str, space_closed());
1468        return Ok(false);
1469    }
1470
1471    // Reject patches that change server-set Space properties,
1472    // including `roles`, `members`, `categories` and
1473    // `uncategorizedChannelIds`, which change only through the
1474    // structural keys; a stored value repeated unchanged is dropped
1475    // (RFC 8620 §5.3).
1476    match check_read_only_patch::<_, Space>(
1477        ctx.backend,
1478        ctx.caller,
1479        ctx.account_id,
1480        &id,
1481        &mut patch_val,
1482    )
1483    .await
1484    {
1485        Ok(false) => {}
1486        Ok(true) => {
1487            acc.updated.insert(id_str, Value::Null);
1488            return Ok(false);
1489        }
1490        Err(err) => {
1491            acc.not_updated.insert(id_str, err);
1492            return Ok(false);
1493        }
1494    }
1495
1496    let parts = match split_update_patch(patch_val, ctx.extension_props, ctx.using) {
1497        Ok(parts) => parts,
1498        Err(err) => {
1499            acc.not_updated.insert(id_str, err);
1500            return Ok(false);
1501        }
1502    };
1503    if let Some(err) = update_ops_error(ctx, &id, closed, &parts, space_limits).await? {
1504        acc.not_updated.insert(id_str, err);
1505        return Ok(false);
1506    }
1507    apply_update(ctx, id_str, &id, parts, acc).await
1508}
1509
1510/// A `Space/set` update patch, split by where each key goes.
1511struct UpdateParts {
1512    /// The structural keys, parsed.
1513    ops: Vec<SpacePatchOp>,
1514    /// Client-updatable Space properties and extension properties, for
1515    /// `apply_space_metadata_patch`.
1516    clean_patch: serde_json::Map<String, Value>,
1517    /// draft-ietf-jmap-metadata-05 `metadata` / `privateMetadata` paths,
1518    /// for `update_object`.
1519    object_metadata_patch: serde_json::Map<String, Value>,
1520}
1521
1522/// Split one `Space/set` update patch (after the read-only check) into
1523/// its [`UpdateParts`], or return the [`SetError`] value for `notUpdated`.
1524fn split_update_patch(
1525    patch_val: Value,
1526    extension_props: &[&str],
1527    using: &[String],
1528) -> Result<UpdateParts, Value> {
1529    // The patch must be a JSON object. Reject `null`, arrays, and
1530    // scalars up front so the rest of the handler can assume a map.
1531    let Value::Object(mut patch_map) = patch_val else {
1532        return Err(
1533            json!({ "type": "invalidPatch", "description": "patch must be a JSON object" }),
1534        );
1535    };
1536
1537    // Walk every key on the patch object and bucket it as:
1538    //   - structural (parsed into SpacePatchOp values via the
1539    //     StructuralKey enum, defined at module top),
1540    //   - draft-ietf-jmap-metadata-05 `metadata` / `privateMetadata`
1541    //     (the property or a path below it), forwarded to
1542    //     update_object,
1543    //   - metadata or a backend-registered extension property
1544    //     (`ChatSpaces::space_extension_properties`), forwarded
1545    //     to apply_space_metadata_patch,
1546    //   - unknown (rejected as invalidProperties).
1547    // Any parse error on a structural entry is fatal for this target.
1548    //
1549    // Note: per draft §Space/set the wire-level apply order across
1550    // keys is implementation-defined. The backend's apply_space_patch
1551    // (not this loop) is canonical for ordering semantics.
1552    let mut ops: Vec<SpacePatchOp> = Vec::new();
1553    let mut clean_patch = serde_json::Map::new();
1554    let mut object_metadata_patch = serde_json::Map::new();
1555    let mut unknown_keys: Vec<String> = Vec::new();
1556    let mut bad_structural_key: Option<(&'static str, String)> = None;
1557
1558    for (key, value) in std::mem::take(&mut patch_map) {
1559        if let Some(structural) = StructuralKey::from_wire(&key) {
1560            match parse_structural_entries(structural, value) {
1561                Ok(parsed) => ops.extend(parsed),
1562                Err(reason) => {
1563                    bad_structural_key = Some((structural.wire_name(), reason));
1564                    break;
1565                }
1566            }
1567        } else if is_metadata_key(&key) {
1568            object_metadata_patch.insert(key, value);
1569        } else if is_client_updatable::<Space>(&key) || extension_props.contains(&key.as_str()) {
1570            clean_patch.insert(key, value);
1571        } else {
1572            unknown_keys.push(key);
1573        }
1574    }
1575
1576    if let Some((canonical, reason)) = bad_structural_key {
1577        return Err(json!({
1578            "type": "invalidProperties",
1579            "properties": [canonical],
1580            "description": reason,
1581        }));
1582    }
1583
1584    if !unknown_keys.is_empty() {
1585        return Err(json!({ "type": "invalidProperties", "properties": unknown_keys }));
1586    }
1587
1588    if let Err(err) = check_metadata_entry(&object_metadata_patch, false, using) {
1589        return Err(serde_json::Value::from(&*err));
1590    }
1591
1592    if ops.is_empty() && clean_patch.is_empty() && object_metadata_patch.is_empty() {
1593        return Err(
1594            json!({ "type": "invalidPatch", "description": "patch contains no valid fields" }),
1595        );
1596    }
1597    Ok(UpdateParts {
1598        ops,
1599        clean_patch,
1600        object_metadata_patch,
1601    })
1602}
1603
1604/// The [`SetError`] value that refuses a split `Space/set` update before any
1605/// write: the closed-Space gate, a reserved role position, or a per-Space
1606/// count cap. `None` to go on.
1607async fn update_ops_error<B: ChatBackend>(
1608    ctx: &SetCtx<'_, B>,
1609    id: &Id,
1610    closed: bool,
1611    parts: &UpdateParts,
1612    space_limits: &ChatLimits,
1613) -> Result<Option<Value>, JmapError> {
1614    let ops = &parts.ops;
1615    // The closedAt gate above, for a patch that also names other
1616    // changes. The owner removes themselves by the accountId
1617    // (§Terminology).
1618    let self_removal = parts.clean_patch.is_empty()
1619        && parts.object_metadata_patch.is_empty()
1620        && matches!(ops.as_slice(), [SpacePatchOp::RemoveMember(m)] if m == ctx.account_id);
1621    if closed && !self_removal {
1622        return Ok(Some(space_closed()));
1623    }
1624
1625    // Reject SpaceRole.position == 0 per draft-atwood-jmap-chat-00
1626    // §SpaceRole commit `c3ea5d9` ("harden position 0 / @everyone
1627    // reservation"): position 0 is reserved for the implicit
1628    // @everyone role, which every member of a Space holds and
1629    // which serves as the permission floor. Defined SpaceRoles
1630    // MUST have position > 0. The reference permissions resolver
1631    // uses position: 0 internally for the synthetic @everyone
1632    // role, so accepting it on the wire would create real
1633    // conflicts.
1634    //
1635    // Per RFC 8620 §5.3 the rejection is per-target atomic, so a
1636    // single position-0 violation in any addRoles or updateRoles
1637    // entry rejects the whole update target. The wire shape is
1638    // `invalidProperties` with `properties: ["position"]` to
1639    // match the existing per-field-rejection convention in this
1640    // crate; the bead's "invalidArguments" text was an internal
1641    // slip (RFC 8620's `invalidArguments` SetError does not
1642    // carry a `properties` field).
1643    if ops.iter().any(|op| match op {
1644        SpacePatchOp::AddRole(role) => role.position == 0,
1645        SpacePatchOp::UpdateRole { patch, .. } => patch.position == Some(0),
1646        _ => false,
1647    }) {
1648        return Ok(Some(json!({
1649            "type": "invalidProperties",
1650            "properties": ["position"],
1651            "description":
1652                "SpaceRole.position 0 is reserved for the implicit @everyone role; defined roles MUST have position > 0 (draft-atwood-jmap-chat-00 §SpaceRole)",
1653        })));
1654    }
1655
1656    // Enforce per-Space count limits before dispatching structural
1657    // ops to the backend (bd:JMAP-g7wu.2.4.8). If any aggregate
1658    // would exceed its cap, reject the whole update target with
1659    // a single `overQuota` SetError per RFC 8620 §5.3 atomicity
1660    // at the target level. The cap values come from the
1661    // backend's `ChatSettings::limits` (queried once per request
1662    // above the loop); the current per-collection counts come
1663    // from a `get_objects::<Space>` read of the target Space.
1664    if !ops.is_empty()
1665        && let Some(err) = check_space_count_limits(
1666            ctx.backend,
1667            ctx.caller,
1668            ctx.account_id,
1669            id,
1670            ops,
1671            space_limits,
1672        )
1673        .await?
1674    {
1675        return Ok(Some(serde_json::Value::from(&err)));
1676    }
1677    Ok(None)
1678}
1679
1680/// Write one checked `Space/set` update: the metadata paths, then the
1681/// structural ops, then the top-level fields. Returns whether the backend
1682/// was written; a later failure leaves an earlier write in place.
1683async fn apply_update<B: ChatBackend>(
1684    ctx: &SetCtx<'_, B>,
1685    id_str: String,
1686    id: &Id,
1687    parts: UpdateParts,
1688    acc: &mut SetAccumulators,
1689) -> Result<bool, JmapError> {
1690    let UpdateParts {
1691        ops,
1692        clean_patch,
1693        object_metadata_patch,
1694    } = parts;
1695    let mut mutated = false;
1696
1697    // draft-ietf-jmap-metadata-05 §3.2: `metadata` and
1698    // `privateMetadata` take RFC 8620 §5.3 PatchObject paths
1699    // (`metadata/<namespace>/...`), which the RFC 7396 merge patch
1700    // of `apply_space_metadata_patch` cannot express, so they go
1701    // through `update_object`, whose backend runs the -05 §3.2
1702    // checks. Applied before the structural ops, so a rejected
1703    // metadata write leaves the Space unchanged.
1704    // ponytail: like the structural ops and the top-level fields
1705    // below, this is its own backend call, so a later failure
1706    // leaves the metadata written; a backend needing strictness
1707    // applies all three in one transaction.
1708    if !object_metadata_patch.is_empty() {
1709        let patch: PatchObject = match serde_json::from_value(Value::Object(object_metadata_patch))
1710        {
1711            Ok(p) => p,
1712            Err(e) => {
1713                acc.not_updated.insert(
1714                    id_str,
1715                    json!({ "type": "invalidPatch", "description": e.to_string() }),
1716                );
1717                return Ok(mutated);
1718            }
1719        };
1720        if let Err(e) = ctx
1721            .backend
1722            .update_object::<Space>(ctx.caller, ctx.account_id, id, patch)
1723            .await
1724        {
1725            acc.not_updated.insert(id_str, backend_set_error_value(e));
1726            return Ok(mutated);
1727        }
1728        mutated = true;
1729    }
1730
1731    // Then the structural ops. If any op fails, surface the first
1732    // failure as a `notUpdated` entry and skip the top-level field
1733    // write —
1734    // RFC 8620 §5.3 requires each update target to land in exactly
1735    // one of `updated` / `notUpdated`, and a partial half-applied
1736    // outcome would be misleading.
1737    if !ops.is_empty()
1738        && let Err(err) = apply_structural_ops(ctx, id, ops).await
1739    {
1740        acc.not_updated.insert(id_str, err);
1741        return Ok(mutated);
1742    }
1743
1744    // Apply metadata (if any) via the dedicated chat-server
1745    // entry point. Routing through
1746    // `ChatSpaces::apply_space_metadata_patch` (rather than
1747    // the generic `update_object::<Space>`) gives the backend
1748    // the type and identity context it needs to apply the
1749    // `manage_space` permission gate atomically with the
1750    // mutation. The gate is backend-canonical per workspace
1751    // AGENTS.md "Caller identity (foundation seam)" — handler
1752    // does no permission check here. See bd:JMAP-g7wu.2.4.13.
1753    //
1754    // If there were no metadata fields, structural ops alone
1755    // count as a successful update — emit a null sentinel
1756    // into `updated`.
1757    if clean_patch.is_empty() {
1758        acc.updated.insert(id_str, Value::Null);
1759        return Ok(true);
1760    }
1761    apply_metadata_patch(ctx, id_str, id, clean_patch, acc)
1762        .await
1763        .map(|written| mutated || written)
1764}
1765
1766/// Apply the structural ops of one `Space/set` update and report each
1767/// removed channel to `ChatEvents::on_chat_destroyed`. Returns the
1768/// [`SetError`] value of the first failed op.
1769async fn apply_structural_ops<B: ChatBackend>(
1770    ctx: &SetCtx<'_, B>,
1771    id: &Id,
1772    ops: Vec<SpacePatchOp>,
1773) -> Result<(), Value> {
1774    let removed_channels: Vec<Id> = ops
1775        .iter()
1776        .filter_map(|op| match op {
1777            SpacePatchOp::RemoveChannel(chat_id) => Some(chat_id.clone()),
1778            _ => None,
1779        })
1780        .collect();
1781    match ctx
1782        .backend
1783        .apply_space_patch(ctx.caller, ctx.account_id, id, ops)
1784        .await
1785    {
1786        Ok(op_results) => {
1787            if let Some(first_err) = op_results.iter().find_map(|r| r.outcome.as_ref().err()) {
1788                return Err(serde_json::Value::from(first_err));
1789            }
1790            for chat_id in &removed_channels {
1791                ctx.backend
1792                    .on_chat_destroyed(ctx.caller, ctx.account_id, chat_id)
1793                    .await;
1794            }
1795            Ok(())
1796        }
1797        Err(e) => Err(backend_set_error_value(e)),
1798    }
1799}
1800
1801/// Apply the top-level fields of one `Space/set` update through
1802/// `ChatSpaces::apply_space_metadata_patch`. Returns whether the backend
1803/// was written.
1804async fn apply_metadata_patch<B: ChatBackend>(
1805    ctx: &SetCtx<'_, B>,
1806    id_str: String,
1807    id: &Id,
1808    clean_patch: serde_json::Map<String, Value>,
1809    acc: &mut SetAccumulators,
1810) -> Result<bool, JmapError> {
1811    // Decode the wire patch's metadata-key subset into the typed
1812    // SpaceMetadataPatch shape (bd:JMAP-x2gd.39). The handler has
1813    // already filtered to METADATA_FIELDS plus the backend's
1814    // extension properties (which land in `extra`), so unknown-key
1815    // rejection is impossible here; the remaining failure mode is
1816    // a wire `null` on a non-nullable field (`isPublic` /
1817    // `isPubliclyPreviewable`) which surfaces as
1818    // `invalidProperties` naming the offending key. The error
1819    // message names the field that failed to deserialize, which
1820    // is sufficient for a client to act on.
1821    let typed_patch: jmap_chat_types::SpaceMetadataPatch =
1822        match serde_json::from_value(Value::Object(clean_patch)) {
1823            Ok(p) => p,
1824            Err(e) => {
1825                acc.not_updated.insert(
1826                    id_str,
1827                    json!({
1828                        "type": "invalidProperties",
1829                        "description": format!("metadata patch failed to deserialize: {e}"),
1830                    }),
1831                );
1832                return Ok(false);
1833            }
1834        };
1835
1836    match ctx
1837        .backend
1838        .apply_space_metadata_patch(ctx.caller, ctx.account_id, id, typed_patch)
1839        .await
1840    {
1841        Ok(Some(obj)) => {
1842            acc.updated
1843                .insert(id_str, jmap_server::serialize_value(&obj)?);
1844            Ok(true)
1845        }
1846        Ok(None) => {
1847            acc.updated.insert(id_str, Value::Null);
1848            Ok(true)
1849        }
1850        Err(e) => {
1851            acc.not_updated.insert(id_str, backend_set_error_value(e));
1852            Ok(false)
1853        }
1854    }
1855}
1856
1857/// The `destroy` part of `Space/set`. Returns whether the backend was
1858/// written.
1859async fn set_destroy<B: ChatBackend>(
1860    ctx: &SetCtx<'_, B>,
1861    args: &mut serde_json::Map<String, Value>,
1862    acc: &mut SetAccumulators,
1863) -> Result<bool, JmapError> {
1864    let mut mutated = false;
1865    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
1866        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
1867        // Reject the whole request if any element is non-string rather than
1868        // silently skipping it, which would produce a misleading response.
1869        let id_strs: Vec<&str> = destroy_arr
1870            .iter()
1871            .map(|v| {
1872                v.as_str().ok_or_else(|| {
1873                    JmapError::invalid_arguments(format!(
1874                        "destroy: every element must be a string Id; got {}",
1875                        jmap_server::json_type_name(v)
1876                    ))
1877                })
1878            })
1879            .collect::<Result<_, _>>()?;
1880        for id_str in id_strs {
1881            let id = match jmap_server::parse_wire_id(id_str, "id") {
1882                Ok(id) => id,
1883                Err(err) => {
1884                    acc.not_destroyed
1885                        .insert(id_str.to_owned(), serde_json::Value::from(&*err));
1886                    continue;
1887                }
1888            };
1889
1890            // The backend cascades the destroy to the Space's channel
1891            // Chats (§Destroying a Space), so read their ids first for
1892            // `ChatEvents::on_chat_destroyed`.
1893            // ponytail: a channel added by a concurrent request between
1894            // this read and the destroy gets no callback. The upgrade
1895            // path is a destroy method that returns the cascaded ids.
1896            let channel_ids =
1897                match space_channel_ids(ctx.backend, ctx.caller, ctx.account_id, &id).await {
1898                    Ok(ids) => ids,
1899                    Err(e) => {
1900                        acc.not_destroyed
1901                            .insert(id_str.to_owned(), server_fail_value_from_backend(&e));
1902                        continue;
1903                    }
1904                };
1905
1906            match ctx
1907                .backend
1908                .destroy_object::<Space>(ctx.caller, ctx.account_id, &id)
1909                .await
1910            {
1911                Ok(()) => {
1912                    mutated = true;
1913                    acc.destroyed.push(Value::String(id_str.to_owned()));
1914                    for chat_id in &channel_ids {
1915                        ctx.backend
1916                            .on_chat_destroyed(ctx.caller, ctx.account_id, chat_id)
1917                            .await;
1918                    }
1919                    ctx.backend
1920                        .on_space_destroyed(ctx.caller, ctx.account_id, &id)
1921                        .await;
1922                }
1923                Err(e) => {
1924                    acc.not_destroyed
1925                        .insert(id_str.to_owned(), backend_set_error_value(e));
1926                }
1927            }
1928        }
1929    }
1930    Ok(mutated)
1931}
1932
1933// ---------------------------------------------------------------------------
1934// Space/join
1935// ---------------------------------------------------------------------------
1936
1937/// Handle a `Space/join` method call (draft-atwood-jmap-chat-00 §Space).
1938///
1939/// `args` is the draft §Space `Space/join` request shape (`accountId`,
1940/// exactly one of `inviteCode` or `spaceId`); the returned `Value` is
1941/// the §Space response shape (`accountId`, `spaceId`).
1942///
1943/// Accepts exactly one of `inviteCode` or `spaceId`. Validates the invite or
1944/// space, adds the caller as a member, and returns `{ "accountId": ..., "spaceId": ... }`.
1945///
1946/// `inviteCode` resolves only within the request's `accountId`, which
1947/// names the account hosting the Space; invite links therefore carry
1948/// both `accountId` and the code. A code created in another account is
1949/// reported as `invalidArguments` "invite code not found", exactly like
1950/// an unknown code.
1951///
1952/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1953///
1954/// # Errors
1955///
1956/// Returns a method-level [`JmapError`]:
1957///
1958/// - `invalidArguments` when `accountId` is missing or not a valid Id, not
1959///   exactly one of `inviteCode` and `spaceId` is given, `spaceId` is not a
1960///   valid Id, the invite code is unknown, expired or used up, or the caller
1961///   is already a member;
1962/// - `accountNotFound` when the backend does not know `accountId`;
1963/// - `notPermitted` when `spaceId` names no public Space;
1964/// - `forbidden` when a `SpaceBan` in force bans the caller from the Space,
1965///   or the Space is closed;
1966/// - `serverFail` when the backend fails.
1967pub async fn handle_space_join<B: ChatBackend>(
1968    backend: &B,
1969    caller: &B::CallerCtx,
1970    args: Value,
1971) -> Result<HandlerOutput, JmapError> {
1972    let (account_id, args) = extract_account_id(args)?;
1973
1974    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
1975    if !backend
1976        .account_exists(caller, &account_id)
1977        .await
1978        .map_err(|e| server_fail_from_backend(&e))?
1979    {
1980        return Err(JmapError::account_not_found());
1981    }
1982
1983    // The joining participant is the owner, referenced by the accountId:
1984    // draft-atwood-jmap-chat-00 §SpaceMember.id is "The participant's
1985    // ChatContact.id, or the accountId for the owner", and the owner's
1986    // SpaceBan carries the accountId as its `userId` (§Terminology).
1987
1988    let invite_code = args
1989        .get("inviteCode")
1990        .and_then(|v| v.as_str())
1991        .map(|s| s.to_owned());
1992    let space_id_str = args
1993        .get("spaceId")
1994        .and_then(|v| v.as_str())
1995        .map(|s| s.to_owned());
1996
1997    // Validate the invite or space and collect the space_id, current members
1998    // (public path only; the invite path's membership write is the backend's
1999    // atomic redemption), the invite to redeem, and whether the Space is closed.
2000    let JoinTarget {
2001        space_id,
2002        current_members,
2003        invite_id,
2004        closed,
2005    } = match (invite_code, space_id_str) {
2006        (Some(_), Some(_)) | (None, None) => {
2007            return Err(JmapError::invalid_arguments(
2008                "exactly one of inviteCode or spaceId must be provided",
2009            ));
2010        }
2011        (Some(code), None) => invite_join_target(backend, caller, &account_id, &code).await?,
2012        (None, Some(sid)) => public_join_target(backend, caller, &account_id, &sid).await?,
2013    };
2014
2015    check_join_ban(backend, caller, &account_id, &space_id).await?;
2016
2017    // draft-atwood-jmap-chat-00 §Space/join: "If the target Space has
2018    // `closedAt` set ({{space}}), the server MUST reject the request with
2019    // a `forbidden` method error, whether the caller supplied
2020    // `inviteCode` or `spaceId`." Evaluated with the ban check, after
2021    // Space resolution.
2022    if closed {
2023        return Err(JmapError::forbidden());
2024    }
2025
2026    match invite_id {
2027        Some(invite_id) => {
2028            join_with_invite(backend, caller, &account_id, &invite_id).await?;
2029        }
2030        None => join_public_space(backend, caller, &account_id, &space_id, current_members).await?,
2031    }
2032    create_channel_read_positions(backend, caller, &account_id, &space_id).await;
2033    Ok(HandlerOutput::new(
2034        json!({ "accountId": account_id.as_ref(), "spaceId": space_id.as_ref() }),
2035    ))
2036}
2037
2038/// The Space a `Space/join` joins, as [`invite_join_target`] or
2039/// [`public_join_target`] resolved it.
2040struct JoinTarget {
2041    /// The Space.
2042    space_id: Id,
2043    /// Its members, serialized: on the public path only. The invite path's
2044    /// membership write is the backend's atomic redemption.
2045    current_members: Vec<Value>,
2046    /// The invite to redeem, on the invite path.
2047    invite_id: Option<Id>,
2048    /// Whether the Space is closed (`closedAt` set).
2049    closed: bool,
2050}
2051
2052/// Resolve the `inviteCode` of a `Space/join` to the Space it joins.
2053///
2054/// # Errors
2055///
2056/// `invalidArguments` when the code is unknown in `account_id`, expired or
2057/// used up; `serverFail` when the backend fails.
2058async fn invite_join_target<B: ChatBackend>(
2059    backend: &B,
2060    caller: &B::CallerCtx,
2061    account_id: &Id,
2062    code: &str,
2063) -> Result<JoinTarget, JmapError> {
2064    // Invite code path: scan the request account's invites for a
2065    // matching code. Resolution is scoped to `accountId` by design
2066    // (see the function docs); there is no server-wide index.
2067    let (invites, _) = backend
2068        .get_objects::<SpaceInvite>(caller, account_id, None, None)
2069        .await
2070        .map_err(|e| server_fail_from_backend(&e))?;
2071
2072    // Constant-time invite-code compare (bd:JMAP-sc1b.89).
2073    //
2074    // `SpaceInvite.code` is an unguessable CSPRNG-derived credential
2075    // (see `ChatSpaces::generate_invite_code` in `backend.rs`). A
2076    // plain `String == String` short-circuits at the first mismatched
2077    // byte, exposing a byte-by-byte timing oracle to any caller that
2078    // can issue `Space/join` requests. `ConstantTimeEq::ct_eq`
2079    // compares whole equal-length byte slices in constant time.
2080    //
2081    // Length-discrimination note: `ct_eq` returns `Choice(0)` cheaply
2082    // when lengths differ, so an attacker can learn whether their
2083    // supplied code matches the stored length. The canonical
2084    // generator emits fixed-length (32 hex chars) codes, so the
2085    // length is effectively public — only the content needs
2086    // constant-time protection.
2087    let invite = invites
2088        .into_iter()
2089        .find(|inv| inv.code.as_bytes().ct_eq(code.as_bytes()).into())
2090        .ok_or_else(|| JmapError::invalid_arguments("invite code not found"))?;
2091
2092    // Check expiry using second-precision prefix (see iso8601_before).
2093    // Pure lexicographic comparison on the full string is incorrect for
2094    // fractional-second timestamps ('.' < 'Z' in ASCII).
2095    if let Some(expires_at) = &invite.expires_at {
2096        let now = now_utc_string();
2097        if !iso8601_before(&now, expires_at) {
2098            return Err(JmapError::invalid_arguments("invite has expired"));
2099        }
2100    }
2101
2102    // Check maxUses: if set, uses must be strictly less. Kept here for
2103    // the draft's check order; `join_space_with_invite` re-checks it
2104    // atomically with the increment.
2105    if let Some(max) = invite.max_uses
2106        && invite.uses >= max
2107    {
2108        return Err(JmapError::invalid_arguments(
2109            "invite has reached its maximum number of uses",
2110        ));
2111    }
2112
2113    let space_id = invite.space_id.clone();
2114
2115    // Fetch the space for its `closedAt`.
2116    let (spaces, _) = backend
2117        .get_objects::<Space>(
2118            caller,
2119            account_id,
2120            Some(std::slice::from_ref(&space_id)),
2121            None,
2122        )
2123        .await
2124        .map_err(|e| server_fail_from_backend(&e))?;
2125    let closed = spaces.first().is_some_and(|s| s.closed_at.is_some());
2126
2127    Ok(JoinTarget {
2128        space_id,
2129        current_members: Vec::new(),
2130        invite_id: Some(invite.id),
2131        closed,
2132    })
2133}
2134
2135/// Resolve the `spaceId` of a `Space/join` to the public Space it joins.
2136///
2137/// draft-atwood-jmap-chat-00 §Space/join: "If the Space does not exist or
2138/// has `isPublic: false`, the server MUST return a `notPermitted` method
2139/// error."
2140///
2141/// # Errors
2142///
2143/// `invalidArguments` when `sid` is not a valid Id; `notPermitted` when it
2144/// names no public Space; `serverFail` when the backend fails.
2145async fn public_join_target<B: ChatBackend>(
2146    backend: &B,
2147    caller: &B::CallerCtx,
2148    account_id: &Id,
2149    sid: &str,
2150) -> Result<JoinTarget, JmapError> {
2151    // Public space path: fetch the space by id and verify is_public.
2152    let space_id_typed = Id::new_validated(sid)
2153        .map_err(|e| JmapError::invalid_arguments(format!("spaceId: {e}")))?;
2154    let (spaces, _) = backend
2155        .get_objects::<Space>(caller, account_id, Some(&[space_id_typed]), None)
2156        .await
2157        .map_err(|e| server_fail_from_backend(&e))?;
2158
2159    let space = spaces
2160        .into_iter()
2161        .next()
2162        .filter(|s| s.is_public)
2163        .ok_or_else(|| JmapError::custom("notPermitted"))?;
2164
2165    let space_id = space.id.clone();
2166    let closed = space.closed_at.is_some();
2167    let members: Vec<Value> = space
2168        .members
2169        .into_iter()
2170        .map(serde_json::to_value)
2171        .collect::<Result<Vec<_>, _>>()
2172        .map_err(|e| server_fail_from_backend(&e))?;
2173
2174    Ok(JoinTarget {
2175        space_id,
2176        current_members: members,
2177        invite_id: None,
2178        closed,
2179    })
2180}
2181
2182/// Refuse a `Space/join` of `space_id` by the owner of `account_id` while a
2183/// `SpaceBan` is in force for it.
2184///
2185/// draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474 L1420):
2186/// "The server SHOULD verify that no active `SpaceBan` exists for the
2187/// requesting account's owner in the target Space. If a ban exists, the
2188/// server SHOULD reject the request with a `forbidden` method error."
2189/// This crate performs the recommended check by choice. Evaluated after the
2190/// argument and Space-resolution checks, per the draft's check order. A ban
2191/// whose `expiresAt` has passed is not active.
2192///
2193/// # Errors
2194///
2195/// `forbidden` when a ban is in force; `serverFail` when the backend fails.
2196async fn check_join_ban<B: ChatBackend>(
2197    backend: &B,
2198    caller: &B::CallerCtx,
2199    account_id: &Id,
2200    space_id: &Id,
2201) -> Result<(), JmapError> {
2202    let (bans, _) = backend
2203        .get_objects::<SpaceBan>(caller, account_id, None, None)
2204        .await
2205        .map_err(|e| server_fail_from_backend(&e))?;
2206    let now = now_utc_string();
2207    if bans.iter().any(|b| {
2208        b.space_id == *space_id
2209            && b.user_id == *account_id
2210            && b.expires_at
2211                .as_ref()
2212                .is_none_or(|e| iso8601_before(&now, e))
2213    }) {
2214        return Err(JmapError::forbidden());
2215    }
2216    Ok(())
2217}
2218
2219/// Redeem the invite `invite_id` for the owner of `account_id`.
2220///
2221/// draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474 L1416):
2222/// "The `uses` increment and membership insertion SHOULD be performed
2223/// within a single atomic operation so that concurrent redemptions cannot
2224/// exceed `maxUses`." This crate requires it by choice.
2225///
2226/// # Errors
2227///
2228/// `invalidArguments` when the backend refuses the redemption;
2229/// `serverFail` when the backend fails.
2230async fn join_with_invite<B: ChatBackend>(
2231    backend: &B,
2232    caller: &B::CallerCtx,
2233    account_id: &Id,
2234    invite_id: &Id,
2235) -> Result<(), JmapError> {
2236    let joined_at = UTCDate::from(now_utc_string().as_ref());
2237    match backend
2238        .join_space_with_invite(caller, account_id, invite_id, &joined_at)
2239        .await
2240        .map_err(|e| server_fail_from_backend(&e))?
2241    {
2242        Ok(()) => Ok(()),
2243        Err(InviteJoinRefusal::NotFound) => {
2244            Err(JmapError::invalid_arguments("invite code not found"))
2245        }
2246        Err(InviteJoinRefusal::Exhausted) => Err(JmapError::invalid_arguments(
2247            "invite has reached its maximum number of uses",
2248        )),
2249        Err(InviteJoinRefusal::AlreadyMember) => Err(JmapError::invalid_arguments(
2250            "caller is already a member of this space",
2251        )),
2252    }
2253}
2254
2255/// Add the owner of `account_id` to the public Space `space_id`, whose
2256/// members are `current_members`.
2257///
2258/// # Errors
2259///
2260/// `invalidArguments` when the caller is already a member; `serverFail`
2261/// when the backend fails.
2262async fn join_public_space<B: ChatBackend>(
2263    backend: &B,
2264    caller: &B::CallerCtx,
2265    account_id: &Id,
2266    space_id: &Id,
2267    current_members: Vec<Value>,
2268) -> Result<(), JmapError> {
2269    // Add the calling user as a Space member.
2270    // This bypasses the read-only check in handle_space_set — Space/join calling
2271    // update_object directly is correct: it is an atomic server operation, not a client patch.
2272    let now_str = now_utc_string();
2273    let mut new_members = current_members;
2274
2275    // Pre-check: reject if already a member. This check is NOT atomic with the
2276    // write below — two concurrent requests can both pass and create duplicate
2277    // member entries. The post-write duplicate detection below catches this in
2278    // the common case. Storage-layer unique constraints are the authoritative guard.
2279    //
2280    // Identity: compare against the owner's accountId (see top of
2281    // function). Writer and reader must agree on which value identifies the
2282    // member, or two distinct join paths can both succeed and the
2283    // duplicate-detection logic below will misclassify.
2284    let already_member = new_members
2285        .iter()
2286        .any(|m| m.get("id").and_then(|v| v.as_str()) == Some(account_id.as_ref()));
2287    if already_member {
2288        return Err(JmapError::invalid_arguments(
2289            "caller is already a member of this space",
2290        ));
2291    }
2292
2293    new_members.push(json!({
2294        "id": account_id.as_ref(),
2295        "roleIds": [],
2296        "joinedAt": now_str,
2297    }));
2298    // Concurrency note: this is a read-modify-write on the members array.
2299    // Two concurrent Space/join calls for different accounts can both read
2300    // the same stale members list and overwrite each other. Production backends
2301    // MUST implement this as an atomic array-append (e.g. via a transaction or
2302    // compare-and-swap) to prevent membership loss.
2303    let mut members_patch = serde_json::Map::new();
2304    members_patch.insert("members".to_owned(), json!(new_members));
2305    backend
2306        .update_object::<Space>(
2307            caller,
2308            account_id,
2309            space_id,
2310            PatchObject::from_map(members_patch),
2311        )
2312        .await
2313        // bd:JMAP-ic0j.70 — route through server_fail_from_backend so the
2314        // wire description is the static SERVER_FAIL_INTERNAL_DESC rather
2315        // than the backend BackendSetError Display output.
2316        .map_err(|e: jmap_server::BackendSetError<_>| server_fail_from_backend(&e))?;
2317
2318    dedup_joined_member(backend, caller, account_id, space_id).await
2319}
2320
2321/// After [`join_public_space`] wrote the caller's member entry, re-read the
2322/// Space's members and collapse duplicate entries for the caller to one.
2323///
2324/// TOCTOU guard: re-read members after write and detect duplicate entries.
2325/// Two concurrent join requests can both pass the pre-check and both
2326/// succeed at the write layer. If that happened, exactly one racer must
2327/// undo its write. We detect the duplicate here; the storage layer SHOULD
2328/// enforce a unique constraint on (`space_id`, `user_id`) as the authoritative
2329/// guard — this code is best-effort self-healing.
2330///
2331/// # Errors
2332///
2333/// `serverFail` when the backend fails.
2334async fn dedup_joined_member<B: ChatBackend>(
2335    backend: &B,
2336    caller: &B::CallerCtx,
2337    account_id: &Id,
2338    space_id: &Id,
2339) -> Result<(), JmapError> {
2340    let (post_spaces, _) = backend
2341        .get_objects::<Space>(
2342            caller,
2343            account_id,
2344            Some(std::slice::from_ref(space_id)),
2345            None,
2346        )
2347        .await
2348        .map_err(|e| server_fail_from_backend(&e))?;
2349    let post_members: Vec<Value> = post_spaces
2350        .into_iter()
2351        .next()
2352        .map(|s| {
2353            s.members
2354                .into_iter()
2355                .map(serde_json::to_value)
2356                .collect::<Result<Vec<_>, _>>()
2357        })
2358        .transpose()
2359        .map_err(|e| server_fail_from_backend(&e))?
2360        .unwrap_or_default();
2361    let duplicate_count = post_members
2362        .iter()
2363        .filter(|m| m.get("id").and_then(|v| v.as_str()) == Some(account_id.as_ref()))
2364        .count();
2365    if duplicate_count > 1 {
2366        // Same-caller TOCTOU: two concurrent Space/join requests from this
2367        // caller both passed the pre-check in join_public_space and both
2368        // wrote a member entry. The filter keys on account_id, so
2369        // duplicate_count > 1 strictly implies same-caller —
2370        // different-account races can never hit this branch.
2371        //
2372        // Both winning and losing writes inserted bit-identical entries
2373        // (same id, same roleIds, possibly-millisecond-coincident joinedAt).
2374        // The previous recovery filter matched on (id, joinedAt) and dropped
2375        // serverFail in the caller's face — but if the joinedAt strings
2376        // collided at millisecond resolution, the filter could match either
2377        // entry, and either way the user IS a member after dedup. The
2378        // serverFail return forced the caller into a confusing retry path
2379        // where the pre-check then rejected as already-a-member.
2380        //
2381        // Idempotent join: dedup the extras down to a single entry and
2382        // succeed. Per RFC 8620 §1.6's forward-compat posture, repeated
2383        // identical writes that converge on the same state are not failures.
2384        // The unique-key constraint at the storage layer remains the
2385        // authoritative guard (see the write comment in join_public_space);
2386        // this code is best-effort self-healing.
2387        let deduped = dedup_caller_members(post_members, account_id.as_ref());
2388        let mut deduped_patch = serde_json::Map::new();
2389        deduped_patch.insert("members".to_owned(), json!(deduped));
2390        backend
2391            .update_object::<Space>(
2392                caller,
2393                account_id,
2394                space_id,
2395                PatchObject::from_map(deduped_patch),
2396            )
2397            .await
2398            .map_err(|e: jmap_server::BackendSetError<_>| server_fail_from_backend(&e))?;
2399        // Fall through to the success return — the caller is a member of
2400        // the Space, which is the join's contract.
2401    }
2402    Ok(())
2403}
2404
2405/// The `forbidden` [`SetError`] for a `Space/set` update to a closed Space
2406/// (draft-atwood-jmap-chat-00 §Space `closedAt`).
2407fn space_closed() -> Value {
2408    json!({ "type": "forbidden", "description": "the Space is closed" })
2409}
2410
2411/// Create the owner's `ReadPosition` for every channel Chat of `space_id`.
2412///
2413/// draft-atwood-jmap-chat-00 §`ReadPosition`: "For channel Chats, a
2414/// `ReadPosition` is created when the owner joins the containing Space."
2415/// Best effort, like [`crate::message::ensure_read_positions`]: the join
2416/// is already stored, so a failure here is not a method-level error; a
2417/// missed record is created by the next delivery to that channel.
2418async fn create_channel_read_positions<B: ChatBackend>(
2419    backend: &B,
2420    caller: &B::CallerCtx,
2421    account_id: &Id,
2422    space_id: &Id,
2423) {
2424    let Ok(channel_ids) = space_channel_ids(backend, caller, account_id, space_id).await else {
2425        return;
2426    };
2427    crate::message::ensure_read_positions(backend, caller, account_id, channel_ids).await;
2428}
2429
2430/// Ids of every channel Chat whose `spaceId` is `space_id`.
2431async fn space_channel_ids<B: ChatBackend>(
2432    backend: &B,
2433    caller: &B::CallerCtx,
2434    account_id: &Id,
2435    space_id: &Id,
2436) -> Result<Vec<Id>, B::Error> {
2437    let (chats, _) = backend
2438        .get_objects::<Chat>(caller, account_id, None, None)
2439        .await?;
2440    Ok(chats
2441        .into_iter()
2442        .filter(|c| c.kind == ChatKind::Channel && c.space_id.as_ref() == Some(space_id))
2443        .map(|c| c.id)
2444        .collect())
2445}
2446
2447#[cfg(test)]
2448mod tests {
2449    use super::*;
2450    use serde_json::json;
2451
2452    // Oracles in this module are hand-built per workspace test-integrity
2453    // policy: the assertion uses a wire shape independent of the dedup
2454    // helper under test. Each case asserts both the resulting Vec length
2455    // and the resulting member ids in order, matching a JMAP wire view
2456    // a real backend would produce.
2457
2458    /// A single-entry list with the caller's id is untouched.
2459    #[test]
2460    fn dedup_caller_members_keeps_single_entry() {
2461        let input = vec![json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.000Z"})];
2462        let out = dedup_caller_members(input, "a1");
2463        assert_eq!(out.len(), 1);
2464        assert_eq!(out[0]["id"], "a1");
2465    }
2466
2467    /// Two entries with the caller's id collapse to one; the first is kept.
2468    /// This is the bug fix surface for bd:JMAP-x2gd.11.
2469    #[test]
2470    fn dedup_caller_members_collapses_duplicates() {
2471        let input = vec![
2472            json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.000Z"}),
2473            json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.001Z"}),
2474        ];
2475        let out = dedup_caller_members(input, "a1");
2476        assert_eq!(out.len(), 1);
2477        assert_eq!(out[0]["id"], "a1");
2478        // First entry wins; the second's joinedAt is dropped.
2479        assert_eq!(out[0]["joinedAt"], "2026-01-01T00:00:00.000Z");
2480    }
2481
2482    /// Three duplicates collapse to one — the kit's recovery is unbounded
2483    /// in the count of duplicates a backend may report.
2484    #[test]
2485    fn dedup_caller_members_collapses_three_duplicates() {
2486        let input = vec![
2487            json!({"id": "a1"}),
2488            json!({"id": "a1"}),
2489            json!({"id": "a1"}),
2490        ];
2491        let out = dedup_caller_members(input, "a1");
2492        assert_eq!(out.len(), 1);
2493        assert_eq!(out[0]["id"], "a1");
2494    }
2495
2496    /// Other members are preserved verbatim, in order. Only the caller's
2497    /// duplicates are deduplicated; bystander members are untouched.
2498    #[test]
2499    fn dedup_caller_members_preserves_other_members() {
2500        let input = vec![
2501            json!({"id": "u2"}),
2502            json!({"id": "a1"}),
2503            json!({"id": "u3"}),
2504            json!({"id": "a1"}),
2505            json!({"id": "u4"}),
2506        ];
2507        let out = dedup_caller_members(input, "a1");
2508        assert_eq!(out.len(), 4);
2509        let ids: Vec<&str> = out
2510            .iter()
2511            .filter_map(|m| m.get("id").and_then(|v| v.as_str()))
2512            .collect();
2513        assert_eq!(ids, vec!["u2", "a1", "u3", "u4"]);
2514    }
2515
2516    /// An empty members list is returned unchanged.
2517    #[test]
2518    fn dedup_caller_members_empty() {
2519        let out = dedup_caller_members(vec![], "a1");
2520        assert!(out.is_empty());
2521    }
2522
2523    /// Members whose id field is missing or non-string don't match — they
2524    /// pass through to the result. This protects against malformed data
2525    /// in storage (which the kit should not produce but a misbehaving
2526    /// backend might).
2527    #[test]
2528    fn dedup_caller_members_skips_malformed_entries() {
2529        let input = vec![
2530            json!({"joinedAt": "2026-01-01T00:00:00.000Z"}), // no id field
2531            json!({"id": 42}),                               // non-string id
2532            json!({"id": "a1"}),
2533        ];
2534        let out = dedup_caller_members(input, "a1");
2535        assert_eq!(out.len(), 3);
2536    }
2537}