jmap_chat_server/backend.rs
1//! ChatBackend trait and supporting types for JMAP Chat method handlers.
2//!
3//! Consumers implement [`ChatBackend`] for their storage system. The method
4//! handlers in sibling modules call into the backend through this trait.
5//!
6//! The read-side operations (`get_objects`, `get_state`, `get_changes`,
7//! `query_objects`, `query_changes`) are defined on the [`jmap_server::JmapBackend`]
8//! supertrait. Only write operations are here.
9//!
10//! Marker traits and property selector enums live in `jmap-types` and
11//! `jmap-chat-types` respectively; the crate root re-exports the ones an
12//! impl needs.
13
14use jmap_chat_types::SpacePatchOp;
15use jmap_server::{BackendSetError, JmapBackend, JmapObject, SetError, SetErrorType, SetObject};
16
17// ---------------------------------------------------------------------------
18// Space/set structural-mutation result
19// ---------------------------------------------------------------------------
20
21/// The outcome of a single [`SpacePatchOp`](crate::SpacePatchOp) applied by
22/// [`ChatSpaces::apply_space_patch`].
23///
24/// `op_index` is the zero-based index of the op within the input `Vec`, used
25/// by handlers to construct a descriptive error message identifying which
26/// per-key entry failed (e.g. `addRoles[2] failed: ...`).
27///
28/// `outcome` is:
29/// - `Ok(Some(id))` — the op produced a new server-assigned id (e.g.
30/// [`SpacePatchOp::AddRole`], [`SpacePatchOp::AddChannel`],
31/// [`SpacePatchOp::AddCategory`]). The handler reports this id back to
32/// the client via the `/set` response.
33/// - `Ok(None)` — the op completed but produced no id (every `Remove*` and
34/// `Update*` variant).
35/// - `Err(SetError)` — the op was rejected (e.g. permission denied, target
36/// id not found, role hierarchy violation, count limit exceeded).
37///
38/// Per RFC 8620 §5.3 `/set`, an update target is per-target atomic on the
39/// wire: it appears in exactly one of `updated` or `notUpdated`. If **any**
40/// `OpResult` in the returned `Vec` has an `Err`, the handler reports the
41/// containing update target in `notUpdated`. The handler is free to choose
42/// which `Err` to surface; the reference handler surfaces the first.
43///
44/// This type lives in `jmap-chat-server` (not `jmap-chat-types`) because
45/// [`SetError`] is defined in `jmap-server` and `jmap-chat-types` cannot
46/// depend on it (per the workspace dependency rule: types crates depend
47/// only on `jmap-types`, `serde`, `serde_json`).
48///
49/// `#[non_exhaustive]` preserves the ability to add fields without a
50/// SemVer break (e.g. an audit-log handle, commit ordering hint,
51/// permission-diagnostic annotation). External consumers MUST construct
52/// instances via [`OpResult::ok`] or [`OpResult::err`] rather than
53/// field-init syntax.
54///
55/// # Field-addition policy
56///
57/// Future fields added to `OpResult` are an **additive non-breaking
58/// change**: the new field MUST have a `Default` value (typical for
59/// `Option` / `Vec` / `HashMap`) and the new field is exposed via a
60/// `with_*`-style builder setter rather than being appended as a third
61/// positional argument to [`OpResult::ok`] or [`OpResult::err`]. The
62/// `ok(op_index, id)` and `err(op_index, error)` constructors therefore
63/// stay stable across the crate's pre-1.0 lifetime, matching the
64/// [`ChatLimits`]-style canonical workspace pattern for
65/// `#[non_exhaustive]` types with builder setters.
66#[non_exhaustive]
67#[derive(Debug)]
68pub struct OpResult {
69 /// Zero-based index of the originating op in the input `Vec<SpacePatchOp>`.
70 pub op_index: usize,
71 /// The outcome of applying that op.
72 pub outcome: Result<Option<jmap_types::Id>, SetError>,
73}
74
75impl OpResult {
76 /// Construct an `Ok` result for a successfully applied op.
77 ///
78 /// The contained `Id` is the server-assigned id when the op was a
79 /// create (the kit's response includes it under `created[create_id].id`);
80 /// pass `None` for updates and destroys, which have no id to surface.
81 #[must_use]
82 pub const fn ok(op_index: usize, id: Option<jmap_types::Id>) -> Self {
83 Self {
84 op_index,
85 outcome: Ok(id),
86 }
87 }
88
89 /// Construct an `Err` result for a rejected op.
90 ///
91 /// The kit's `handle_space_set` surfaces this error to the JMAP
92 /// `notUpdated` map for the containing update target.
93 #[must_use]
94 pub const fn err(op_index: usize, error: SetError) -> Self {
95 Self {
96 op_index,
97 outcome: Err(error),
98 }
99 }
100
101 /// Builder-style setter for [`Self::op_index`].
102 ///
103 /// Lets callers update the originating op index after construction.
104 /// Useful when re-indexing a result produced for one op into the
105 /// position of another (e.g. when filtering a batch).
106 #[must_use]
107 pub const fn with_op_index(mut self, op_index: usize) -> Self {
108 self.op_index = op_index;
109 self
110 }
111
112 /// Builder-style setter for [`Self::outcome`].
113 ///
114 /// Lets callers replace the outcome after construction. Useful for
115 /// retry / fallback flows that re-classify a transient error into a
116 /// success or vice versa before surfacing the result to the
117 /// handler.
118 #[must_use]
119 pub fn with_outcome(mut self, outcome: Result<Option<jmap_types::Id>, SetError>) -> Self {
120 self.outcome = outcome;
121 self
122 }
123}
124
125// ---------------------------------------------------------------------------
126// Per-Space content limits
127// ---------------------------------------------------------------------------
128
129/// Implementation-defined per-Space content limits enforced by
130/// `Space/set` handlers.
131///
132/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
133/// 2026-05-11), each `add*` op on a Space MUST return an `overQuota`
134/// SetError (RFC 8620 §5.3) when the resulting count would exceed a
135/// server-defined limit. The spec does not name or normatively define
136/// the cap values; they are implementation-defined and may vary per
137/// account or per tenant.
138///
139/// Backends override [`ChatSettings::limits`] to supply their own values.
140/// The default impl returns conservative reference-impl-grade values
141/// suitable for tests and single-tenant dev servers; production
142/// deployments are expected to override.
143///
144/// Client visibility of these caps (when desired) is via JMAP Quotas
145/// (`urn:ietf:params:jmap:quotas`, RFC 9425), not via this struct.
146/// The `urn:ietf:params:jmap:chat` session capability does NOT advertise
147/// the count caps (the previous cap-advertising fields `maxRolesPerSpace`,
148/// `maxSpaceMembers`, `maxChannelsPerSpace`, `maxCategoriesPerSpace`
149/// were removed from the draft in spec commit `80d5e11`).
150///
151/// See the workspace `AGENTS.md` "Backend caps and limits" section for
152/// the cross-extension pattern this struct establishes for JMAP Chat.
153#[non_exhaustive]
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct ChatLimits {
156 /// Maximum number of roles per Space. Enforced against the
157 /// resulting count after applying every `addRoles` entry in a
158 /// `Space/set` update patch.
159 pub max_roles_per_space: u32,
160 /// Maximum number of members per Space. Enforced against the
161 /// resulting count after applying every `addMembers` entry in a
162 /// `Space/set` update patch.
163 pub max_space_members: u32,
164 /// Maximum number of channels per Space. Enforced against the
165 /// resulting count after applying every `addChannels` entry in a
166 /// `Space/set` update patch. The current channel count is the sum
167 /// of `space.uncategorizedChannelIds.len()` and every
168 /// `space.categories[].channelIds.len()`.
169 pub max_channels_per_space: u32,
170 /// Maximum number of categories per Space. Enforced against the
171 /// resulting count after applying every `addCategories` entry in
172 /// a `Space/set` update patch.
173 pub max_categories_per_space: u32,
174 /// Maximum number of members per group Chat. Enforced against the
175 /// resulting count after applying every `addMembers` entry in a
176 /// `Chat/set` update patch.
177 pub max_group_chat_members: u32,
178 /// `bodyType` values the account advertises as `supportedBodyTypes`
179 /// and `Message/set` accepts (draft-atwood-jmap-chat-00
180 /// §Account-Level Capability Object). Defaults to
181 /// [`crate::message::SUPPORTED_BODY_TYPES`]. The list "MUST include
182 /// `"text/plain"` unless the server accepts only end-to-end encrypted
183 /// body types"; `Message/set` rejects a `bodyType` not listed here,
184 /// including the implied `"text/plain"` of an omitted `bodyType`.
185 pub supported_body_types: &'static [&'static str],
186 /// Listed types that a companion specification reserves for
187 /// server-created Messages (e.g. `"application/mimi-fanout"`,
188 /// draft-atwood-jmap-chat-mimi-00). `Message/set` create rejects
189 /// them with an `invalidProperties` SetError naming `bodyType`;
190 /// update does not. Defaults to empty.
191 pub server_reserved_body_types: &'static [&'static str],
192 /// `bodyType` values that indicate an end-to-end encrypted body.
193 /// Defaults to [`crate::message::ENCRYPTED_BODY_TYPES`]. For these
194 /// types `Message/set` create and update reject a non-empty
195 /// `mentions`, `broadcastMentions`, `attachments`, `actions`,
196 /// `replyTo`, `threadRootId`, `topicId` or `subject`
197 /// (draft-atwood-jmap-chat-00 §Fields Inside the Ciphertext). A MIMI
198 /// deployment adds `"application/mimi-fanout"`, which "is an
199 /// encrypted body type for the purposes of" that draft
200 /// (draft-atwood-jmap-chat-mimi-00 §MLS Messages).
201 pub encrypted_body_types: &'static [&'static str],
202 /// The account's `supportsThreads` capability value
203 /// (draft-atwood-jmap-chat-00 §Thread Model). When `true`,
204 /// `Message/get` computes `replyCount` and `unreadReplyCount`, and
205 /// `Message/query` accepts the `threadRootId` filter, which the
206 /// backend's `query_objects` must then implement. Defaults to `false`.
207 pub supports_threads: bool,
208 /// The account's `maxBodyBytes` capability value
209 /// (draft-atwood-jmap-chat-00 §Account-Level Capability Object):
210 /// "Maximum UTF-8 byte length of a Message `body`." `Message/set`
211 /// create rejects a longer `body` with a `tooLarge` SetError.
212 /// Defaults to 100,000.
213 pub max_body_bytes: u64,
214 /// The account's `maxAttachmentBytes` capability value: "Maximum size
215 /// in bytes of a single attachment blob." `Message/set` create
216 /// rejects an Attachment whose `size` exceeds it with a `tooLarge`
217 /// SetError, before consulting [`ChatResolvers::attachment_blob`].
218 /// Defaults to 50,000,000.
219 pub max_attachment_bytes: u64,
220 /// The account's `maxAttachmentsPerMessage` capability value:
221 /// "Maximum number of attachments per message." `Message/set` create
222 /// rejects more with a `tooLarge` SetError. Defaults to 16.
223 pub max_attachments_per_message: u64,
224 /// Maximum number of CustomEmoji in one Space; `None` is no limit.
225 /// jmap-chat-implementer-guide §2.2: "The server MUST reject
226 /// `CustomEmoji/set` with `overQuota` (per RFC 8620 §5.3) when the
227 /// count or size limit is exceeded." A create that would make the
228 /// Space hold more is rejected. Server-global emoji (no `spaceId`)
229 /// are not counted. Defaults to the guide's starting point, 100.
230 pub max_custom_emoji_per_space: Option<u32>,
231 /// Maximum size in bytes of a CustomEmoji image blob; `None` is no
232 /// limit. `CustomEmoji/set` rejects a create or a `blobId` update
233 /// naming a larger blob with `overQuota` (guide §2.2, as above). The
234 /// size comes from [`ChatResolvers::attachment_blob`]; a blob it does
235 /// not report is not checked. Defaults to the guide's starting point,
236 /// 256 KB (262,144 bytes).
237 pub max_custom_emoji_bytes: Option<u64>,
238}
239
240impl Default for ChatLimits {
241 fn default() -> Self {
242 Self::new(50, 10_000, 500, 100)
243 }
244}
245
246impl ChatLimits {
247 /// Construct a [`ChatLimits`] with the four Space cap fields
248 /// specified in declaration order: roles, members, channels,
249 /// categories. [`Self::max_group_chat_members`] defaults to 1000;
250 /// override it with [`Self::with_max_group_chat_members`].
251 ///
252 /// The struct is `#[non_exhaustive]` so external callers (tests
253 /// using `MemoryBackend::set_limits_for_test`, production backends
254 /// overriding [`ChatSettings::limits`]) need a constructor to build
255 /// one. Future cap-field additions to [`ChatLimits`] are an
256 /// additive non-breaking change because the constructor stays
257 /// stable; callers wanting to override the new field combine
258 /// `ChatLimits::new(..)` with [`Self::with_max_roles_per_space`]
259 /// / [`Self::with_max_space_members`] /
260 /// [`Self::with_max_channels_per_space`] /
261 /// [`Self::with_max_categories_per_space`] and a future analogous
262 /// setter.
263 pub const fn new(
264 max_roles_per_space: u32,
265 max_space_members: u32,
266 max_channels_per_space: u32,
267 max_categories_per_space: u32,
268 ) -> Self {
269 Self {
270 max_roles_per_space,
271 max_space_members,
272 max_channels_per_space,
273 max_categories_per_space,
274 max_group_chat_members: 1_000,
275 supported_body_types: crate::message::SUPPORTED_BODY_TYPES,
276 server_reserved_body_types: &[],
277 encrypted_body_types: crate::message::ENCRYPTED_BODY_TYPES,
278 supports_threads: false,
279 max_body_bytes: 100_000,
280 max_attachment_bytes: 50_000_000,
281 max_attachments_per_message: 16,
282 max_custom_emoji_per_space: Some(100),
283 max_custom_emoji_bytes: Some(262_144),
284 }
285 }
286
287 /// Builder-style setter for [`Self::max_roles_per_space`].
288 #[must_use]
289 pub const fn with_max_roles_per_space(mut self, max: u32) -> Self {
290 self.max_roles_per_space = max;
291 self
292 }
293
294 /// Builder-style setter for [`Self::max_space_members`].
295 #[must_use]
296 pub const fn with_max_space_members(mut self, max: u32) -> Self {
297 self.max_space_members = max;
298 self
299 }
300
301 /// Builder-style setter for [`Self::max_channels_per_space`].
302 #[must_use]
303 pub const fn with_max_channels_per_space(mut self, max: u32) -> Self {
304 self.max_channels_per_space = max;
305 self
306 }
307
308 /// Builder-style setter for [`Self::max_categories_per_space`].
309 #[must_use]
310 pub const fn with_max_categories_per_space(mut self, max: u32) -> Self {
311 self.max_categories_per_space = max;
312 self
313 }
314
315 /// Builder-style setter for [`Self::max_group_chat_members`].
316 #[must_use]
317 pub const fn with_max_group_chat_members(mut self, max: u32) -> Self {
318 self.max_group_chat_members = max;
319 self
320 }
321
322 /// Builder-style setter for [`Self::supported_body_types`].
323 #[must_use]
324 pub const fn with_supported_body_types(mut self, types: &'static [&'static str]) -> Self {
325 self.supported_body_types = types;
326 self
327 }
328
329 /// Builder-style setter for [`Self::server_reserved_body_types`].
330 #[must_use]
331 pub const fn with_server_reserved_body_types(mut self, types: &'static [&'static str]) -> Self {
332 self.server_reserved_body_types = types;
333 self
334 }
335
336 /// Builder-style setter for [`Self::encrypted_body_types`].
337 #[must_use]
338 pub const fn with_encrypted_body_types(mut self, types: &'static [&'static str]) -> Self {
339 self.encrypted_body_types = types;
340 self
341 }
342
343 /// Builder-style setter for [`Self::supports_threads`].
344 #[must_use]
345 pub const fn with_supports_threads(mut self, supports: bool) -> Self {
346 self.supports_threads = supports;
347 self
348 }
349
350 /// Builder-style setter for [`Self::max_body_bytes`].
351 #[must_use]
352 pub const fn with_max_body_bytes(mut self, max: u64) -> Self {
353 self.max_body_bytes = max;
354 self
355 }
356
357 /// Builder-style setter for [`Self::max_attachment_bytes`].
358 #[must_use]
359 pub const fn with_max_attachment_bytes(mut self, max: u64) -> Self {
360 self.max_attachment_bytes = max;
361 self
362 }
363
364 /// Builder-style setter for [`Self::max_attachments_per_message`].
365 #[must_use]
366 pub const fn with_max_attachments_per_message(mut self, max: u64) -> Self {
367 self.max_attachments_per_message = max;
368 self
369 }
370
371 /// Builder-style setter for [`Self::max_custom_emoji_per_space`].
372 #[must_use]
373 pub const fn with_max_custom_emoji_per_space(mut self, max: Option<u32>) -> Self {
374 self.max_custom_emoji_per_space = max;
375 self
376 }
377
378 /// Builder-style setter for [`Self::max_custom_emoji_bytes`].
379 #[must_use]
380 pub const fn with_max_custom_emoji_bytes(mut self, max: Option<u64>) -> Self {
381 self.max_custom_emoji_bytes = max;
382 self
383 }
384}
385
386// ---------------------------------------------------------------------------
387// Attachment blob verification
388// ---------------------------------------------------------------------------
389
390/// The stored blob behind an Attachment `blobId`, as reported by
391/// [`ChatResolvers::attachment_blob`].
392///
393/// `handle_message_set` compares these against the Attachment's `size`
394/// and `sha256` (draft-atwood-jmap-chat-00 §Attachment at jmap-chat-spec
395/// 77c3474, `size` L374: "Servers SHOULD verify against actual content";
396/// `sha256` L377: "Servers SHOULD verify"). This crate performs both
397/// recommended checks by choice.
398#[non_exhaustive]
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub struct AttachmentBlob {
401 /// Byte count of the stored blob.
402 pub size: u64,
403 /// SHA-256 digest of the stored blob's bytes.
404 pub sha256: [u8; 32],
405}
406
407impl AttachmentBlob {
408 /// Construct an [`AttachmentBlob`] from the stored blob's byte count
409 /// and SHA-256 digest.
410 #[must_use]
411 pub const fn new(size: u64, sha256: [u8; 32]) -> Self {
412 Self { size, sha256 }
413 }
414}
415
416// ---------------------------------------------------------------------------
417// Custom emoji authorization gate
418// ---------------------------------------------------------------------------
419
420/// Identifies the kind of `CustomEmoji/set` operation being authorized by
421/// [`SpacePolicy::may_set_custom_emoji`].
422///
423/// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11, "refactor:
424/// implementation-defined emoji authorization"), authorization for
425/// `CustomEmoji/set` is fully implementation-defined for both server-global
426/// and Space-scoped emoji. The kit forwards the op kind so the backend can
427/// apply different policies per op (e.g. allow create+update but require
428/// elevated rights for destroy).
429#[non_exhaustive]
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431pub enum EmojiSetOp {
432 /// `CustomEmoji/set` `create` — a new emoji is being added.
433 Create,
434 /// `CustomEmoji/set` `update` — an existing emoji's mutable fields
435 /// (currently `name` and `blobId`) are being patched.
436 Update,
437 /// `CustomEmoji/set` `destroy` — an existing emoji is being removed.
438 Destroy,
439}
440
441/// Why [`ChatSpaces::join_space_with_invite`] refused a redemption.
442#[non_exhaustive]
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum InviteJoinRefusal {
445 /// The invite, or the Space it names, no longer exists.
446 NotFound,
447 /// The invite's `uses` has reached `maxUses`.
448 Exhausted,
449 /// The owner is already a member of the Space.
450 AlreadyMember,
451}
452
453// ---------------------------------------------------------------------------
454// Slow-mode rate-limit gate
455// ---------------------------------------------------------------------------
456
457/// Outcome of a [`ChatAccessPolicy::slow_mode_check`] rejection.
458///
459/// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec commit
460/// `de60acb` (2026-05-11) which softened the manage-channels exemption to
461/// SHOULD: a non-exempt member who sends faster than the configured rate
462/// MUST be rejected with a `rateLimit` SetError (RFC 8620 §5.3) carrying a
463/// `serverRetryAfter` UTCDate that tells the client when it may retry.
464///
465/// `retry_after` is a fully-formed [`jmap_types::UTCDate`] — the backend
466/// has already done the arithmetic (typically "now + remaining slow-mode
467/// window"). The handler serialises it verbatim onto the wire as the
468/// `serverRetryAfter` SetError extra field.
469///
470/// `#[non_exhaustive]` preserves the ability to add fields without a
471/// SemVer break (e.g. an error code, sender-facing retry hint string,
472/// "this is your N-th throttle in M minutes" diagnostic counter).
473/// External consumers MUST construct instances via [`SlowModeError::new`]
474/// rather than field-init syntax.
475#[non_exhaustive]
476#[derive(Debug, Clone)]
477pub struct SlowModeError {
478 /// When the rate-limited sender may retry.
479 pub retry_after: jmap_types::UTCDate,
480}
481
482impl SlowModeError {
483 /// Construct a [`SlowModeError`] from a precomputed retry-after
484 /// [`UTCDate`].
485 ///
486 /// [`UTCDate`]: jmap_types::UTCDate
487 #[must_use]
488 pub const fn new(retry_after: jmap_types::UTCDate) -> Self {
489 Self { retry_after }
490 }
491}
492
493impl std::fmt::Display for SlowModeError {
494 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495 write!(
496 f,
497 "slow-mode rate limit; retry after {}",
498 self.retry_after.as_ref()
499 )
500 }
501}
502
503impl std::error::Error for SlowModeError {}
504
505// ---------------------------------------------------------------------------
506// ChatBackend trait
507// ---------------------------------------------------------------------------
508
509mod delegate;
510pub use delegate::*;
511
512/// Storage backend for JMAP Chat method handlers.
513///
514/// Implementors provide the actual data access; the method handler modules
515/// in this crate translate between JMAP wire protocol and backend calls.
516///
517/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
518/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
519/// supertrait. Only write operations and type introspection are here.
520///
521/// This trait is not object-safe by design (generic methods). Use
522/// `Arc<impl ChatBackend>` when sharing across tasks.
523///
524/// # Async vs sync method convention
525///
526/// `ChatBackend` carves its methods into two groups:
527///
528/// 1. **Mutation / hot-path hooks are async.** [`ChatStore::create_object`],
529/// [`ChatStore::update_object`], [`ChatStore::destroy_object`],
530/// [`ChatSpaces::apply_space_patch`],
531/// [`ChatSpaces::apply_space_metadata_patch`],
532/// [`ChatMessageLifecycle::expire_message`],
533/// [`ChatMessageLifecycle::read_and_burn_message`],
534/// [`ChatAccessPolicy::slow_mode_check`],
535/// [`ChatSpaces::generate_invite_code`],
536/// [`ChatAccessPolicy::is_contact_blocked`], and
537/// [`SpacePolicy::may_set_custom_emoji`] all return
538/// `impl Future + Send`. These methods consult per-account state,
539/// may issue I/O, and run on the JMAP request hot path; the async
540/// signature lets production backends `.await` storage / cache /
541/// policy lookups without runtime-pinning hazards.
542///
543/// 2. **Policy / capability hooks are sync.** [`ChatStore::supports_type`],
544/// [`ChatSettings::limits`], [`ChatSpaces::protect_last_admin`], and
545/// [`ChatSettings::retains_edit_history`] are synchronous methods.
546/// These hooks answer deployment-policy or capability questions
547/// whose answer SHOULD be derivable from in-process state (a
548/// startup-loaded config snapshot, a cached per-account record).
549/// The sync shape keeps the trait surface easy to implement for
550/// single-process and reference backends, which are the dominant
551/// use case for a kit crate. `generate_invite_code` is async and
552/// fallible instead, because an HSM or KMS entropy source needs I/O
553/// and can fail.
554///
555/// The carve-up is intentional and is NOT a "we forgot to async these"
556/// regression. Production backends that need to consult an async
557/// source for any of the four sync hooks have two options: (a)
558/// pre-cache the answer at startup or on a background refresh; or (b)
559/// file a follow-up bead proposing the conversion for that specific
560/// method, with the production constraint documented. Per-method
561/// rustdoc notes ("`# Why sync, not async`" / "`# Fallibility and
562/// async — known limitations`") spell out the workaround on each
563/// affected method. Flipping any of the sync hooks to async is a
564/// major-version breaking change for downstream implementors;
565/// converting them all preemptively for hypothetical multi-tenant
566/// SaaS deployments would over-engineer the kit-vs-product posture
567/// described in workspace `AGENTS.md`.
568pub trait ChatBackend:
569 ChatStore
570 + ChatSpaces
571 + SpacePolicy
572 + ChatAccessPolicy
573 + ChatRestrictions
574 + ChatModeration
575 + ChatMessageLifecycle
576 + ChatEvents
577 + ChatSettings
578 + ChatResolvers
579{
580}
581
582impl<T> ChatBackend for T where
583 T: ChatStore
584 + ChatSpaces
585 + SpacePolicy
586 + ChatAccessPolicy
587 + ChatRestrictions
588 + ChatModeration
589 + ChatMessageLifecycle
590 + ChatEvents
591 + ChatSettings
592 + ChatResolvers
593{
594}
595
596/// Object writes and type support: the `/set` storage half of a chat backend.
597///
598/// Its defaults report outbound events through [`ChatEvents`].
599///
600/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
601pub trait ChatStore: ChatEvents {
602 /// Create a new object.
603 ///
604 /// Returns `(assigned_id, created_object)` on success. `create_id` is the
605 /// client-side creation id used in the `/set` request.
606 ///
607 /// # Authorisation contract
608 ///
609 /// This method is the canonical enforcement point for caller authorisation
610 /// per workspace AGENTS.md "Caller identity (foundation seam)" and per-crate
611 /// AGENTS.md "Permission enforcement: backend canonical". The caller of a
612 /// chat account is its owner, whose Space member entry is the accountId
613 /// (draft-atwood-jmap-chat §Terminology). Implementors MUST verify that
614 /// `caller` may act as the owner of `account_id` before performing the
615 /// mutation, and MUST return [`BackendSetError::SetError`] carrying
616 /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. Handlers in this crate do no
617 /// account-access checking, so a backend that trusts the handler lets any
618 /// caller write any account. Space permission and role-hierarchy gates
619 /// resolve against the owner's member entry through the `may_*` hooks (for
620 /// example [`ChatAccessPolicy::may_send_message`]), [`ChatSpaces::apply_space_patch`] and
621 /// [`ChatSpaces::apply_space_metadata_patch`].
622 ///
623 /// # Id assignment
624 ///
625 /// The backend mints the new object's id, calls `build(&id)` exactly
626 /// once to obtain the complete object, and stores that object under
627 /// `id` in the same atomic write. `build` sets the object's `id` field
628 /// to the id it is given; the backend stores the built object as is.
629 /// RFC 8620 §5.3 lists `id` among the "server-set properties".
630 ///
631 /// `Message/set` builds an owner-composed Message with `senderMsgId`
632 /// equal to that id (draft-atwood-jmap-chat-00 §Message `senderMsgId`:
633 /// "Equals `id` for messages composed by the owner."). A
634 /// server-originated Message ([`crate::message::store_server_message`]) carries
635 /// the `senderMsgId` its originator chose. In both cases the backend
636 /// stores `senderMsgId` unchanged.
637 ///
638 /// # Per-type uniqueness contracts
639 ///
640 /// For most types the (id) primary key is the only uniqueness
641 /// invariant the backend must enforce, and the backend's normal
642 /// server-assigned-id discipline closes that. A few types carry
643 /// additional uniqueness invariants on non-id fields that the
644 /// backend MUST enforce atomically with the create — the handler
645 /// pre-checks defensively but cannot close the
646 /// two-concurrent-requests race window.
647 ///
648 /// - **`ReadPosition`** — at most one record per
649 /// `(account_id, chat_id)`. Clients cannot create one
650 /// (`ReadPosition/set` create is `forbidden`); the server creates
651 /// it on first message delivery in
652 /// [`crate::message::handle_message_set`] and on
653 /// [`crate::space::handle_space_join`], which pre-check via a
654 /// sequential scan, but two concurrent requests for
655 /// the same `chatId` can both pass the pre-check and then both
656 /// reach `create_object`. The
657 /// backend MUST enforce a unique constraint on
658 /// `(account_id, chat_id)` at the storage layer (typically a
659 /// composite unique index in a database backend) and surface a
660 /// duplicate as `BackendSetError::SetError(SetError::new(
661 /// SetErrorType::AlreadyExists).with_existing_id(canonical))`.
662 /// See draft-atwood-jmap-chat-00 §ReadPosition.
663 /// - **`ChatContact`** — at most one record per
664 /// `(account_id, identity)`, compared octet for octet.
665 /// [`crate::contact::handle_contact_set`] does not pre-check: the
666 /// backend MUST reject a duplicate atomically with the create as
667 /// `BackendSetError::SetError(SetError::new(
668 /// SetErrorType::AlreadyExists).with_existing_id(existing))`, where
669 /// `existing` is the id of the ChatContact that holds the
670 /// `identity`. See draft-atwood-jmap-chat-00 §ChatContact/set.
671 /// - **`CustomEmoji`** — at most one emoji per `(account_id,
672 /// spaceId, name)`, an absent `spaceId` being the server-global
673 /// scope. [`crate::emoji::handle_emoji_set`] does not pre-check:
674 /// the backend MUST reject a duplicate create as
675 /// `BackendSetError::SetError(SetError::new(
676 /// SetErrorType::AlreadyExists).with_existing_id(existing))` and,
677 /// in `update_object`, a rename onto a held name as an
678 /// `invalidProperties` SetError naming `name`. See
679 /// draft-atwood-jmap-chat-00 §CustomEmoji `name`.
680 /// The same holds for the [`ChatLimits`] emoji caps: the backend
681 /// MUST reject, atomically with the write, a create that would put
682 /// more than `max_custom_emoji_per_space` emoji in its Space, and a
683 /// create or `blobId` update naming a blob larger than
684 /// `max_custom_emoji_bytes`, as `BackendSetError::SetError` with an
685 /// `overQuota` SetError (jmap-chat-implementer-guide §2.2: "The
686 /// server MUST reject `CustomEmoji/set` with `overQuota` ... when
687 /// the count or size limit is exceeded"). The handler pre-checks
688 /// both, but the pre-check cannot close the race.
689 /// - **`Chat`** with `kind == Direct` — at most one direct chat
690 /// per `(account_id, contact_id)`. The handler at
691 /// [`crate::chat::handle_chat_set`] uses optimistic
692 /// create-then-validate with rollback; backends MAY enforce a
693 /// storage-level unique constraint to eliminate the rollback
694 /// path entirely, but it is not required because the
695 /// handler's rollback closes the race correctly. See
696 /// draft-atwood-jmap-chat-00 §Chat.
697 ///
698 /// The reference `MemoryBackend` does NOT
699 /// enforce the `ReadPosition` `(account, chatId)` uniqueness
700 /// constraint at the storage layer — it is single-Mutex
701 /// per-call so concurrent racing cannot occur in practice, but a
702 /// production backend that holds different locks per record (or
703 /// no lock at all between read and write) MUST.
704 ///
705 /// # Errors
706 ///
707 /// Reject a create that RFC 8620 §5.3 defines an error for with
708 /// [`BackendSetError::SetError`] carrying the matching
709 /// [`SetErrorType`]; the handler places it verbatim in `notCreated`.
710 /// For create these are `forbidden`, `overQuota`, `tooLarge`,
711 /// `rateLimit` and `invalidProperties`. An `invalidProperties` error
712 /// SHOULD name in `properties` "*all* the properties that were
713 /// invalid", for example `chatId` when a Message names a Chat that does
714 /// not exist.
715 ///
716 /// Return [`BackendSetError::Other`] only for unexpected storage
717 /// failures. The handler reports it as `serverFail` without the
718 /// error's `Display` text, which tells the client to retry; a
719 /// deterministic rejection returned as `Other` invites retries that
720 /// cannot succeed.
721 ///
722 /// # State and change log
723 ///
724 /// RFC 8620 §5.1 defines the state string over "*all* the data of
725 /// this type in the account": "If the data changes, this string MUST
726 /// change." Every successful `create_object`,
727 /// [`update_object`](Self::update_object) and
728 /// [`destroy_object`](Self::destroy_object) MUST advance
729 /// [`get_state`](jmap_server::JmapReads::get_state) for `O` in `account_id` and
730 /// record the id as created, updated or destroyed so
731 /// [`get_changes`](jmap_server::JmapReads::get_changes) reports it.
732 ///
733 /// When [`ChatLimits::supports_threads`] is `true`, `Message/get`
734 /// returns the server-computed `replyCount` and `unreadReplyCount`
735 /// (draft-atwood-jmap-chat-00 §Message), so a write that changes them
736 /// changes those Messages. The backend MUST then also record as
737 /// updated in `Message` state:
738 ///
739 /// - on a Message create or destroy (including
740 /// [`expire_message`](ChatMessageLifecycle::expire_message) and
741 /// [`read_and_burn_message`](ChatMessageLifecycle::read_and_burn_message)), the
742 /// still-stored Message its `replyTo` names, whose `replyCount`
743 /// changed;
744 /// - on a ReadPosition update that changes `lastReadMessageId`, each
745 /// thread root (no `threadRootId`) in that Chat with a direct reply
746 /// not sent by the owner (`senderId` is not the accountId) whose id
747 /// moved across `lastReadMessageId`, whose `unreadReplyCount`
748 /// changed.
749 ///
750 /// The write, the state advance and the change record MUST be atomic
751 /// with respect to other callers: the reference `MemoryBackend` does
752 /// all three under one mutex acquisition, and a database backend uses
753 /// one transaction. A call that returns `Err` MUST leave the stored
754 /// data, the state and the change log unchanged.
755 fn create_object<O, F>(
756 &self,
757 caller: &Self::CallerCtx,
758 account_id: &jmap_types::Id,
759 create_id: &str,
760 build: F,
761 ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
762 + Send
763 where
764 O: SetObject + Send + Sync,
765 F: FnOnce(&jmap_types::Id) -> O + Send;
766
767 /// Store an owner-composed Message and report its
768 /// [`OutboundEvent::NewMessage`](crate::OutboundEvent::NewMessage) as
769 /// one unit.
770 ///
771 /// [`crate::message::handle_message_set`] calls this for every
772 /// `Message/set` create that passes its checks. draft-atwood-jmap-chat-00
773 /// §Message/set: "The server sets `id`, `senderMsgId`, `senderId`,
774 /// `receivedAt`, `deliveryState`, and delivery timestamp fields, then
775 /// enqueues the message for outbound delivery."
776 ///
777 /// `build` and every contract of [`Self::create_object`] (authorisation,
778 /// id assignment, errors, state and change log) apply unchanged. On
779 /// `Ok` the Message is stored and its `NewMessage` event, naming the
780 /// Message's `chatId`, `id` and `senderMsgId`, is enqueued. On `Err`
781 /// nothing is stored and nothing is enqueued.
782 ///
783 /// An overriding backend may fail the whole create when it cannot
784 /// enqueue the event; the handler reports the error in `notCreated`
785 /// like any [`Self::create_object`] error, so a
786 /// [`BackendSetError::Other`] becomes `serverFail`. A backend that
787 /// wants the store and the delivery fan-out in one transaction (for
788 /// example a SQLite backend committing a group send once) overrides
789 /// this.
790 ///
791 /// # Default implementation
792 ///
793 /// Calls [`Self::create_object`] for `Message`, then, on success,
794 /// [`ChatEvents::on_outbound_event`] with the `NewMessage` event. The store
795 /// and the enqueue are then two steps, and the enqueue cannot fail
796 /// the create.
797 fn create_message<F>(
798 &self,
799 caller: &Self::CallerCtx,
800 account_id: &jmap_types::Id,
801 create_id: &str,
802 build: F,
803 ) -> impl std::future::Future<
804 Output = Result<(jmap_types::Id, jmap_chat_types::Message), BackendSetError<Self::Error>>,
805 > + Send
806 where
807 F: FnOnce(&jmap_types::Id) -> jmap_chat_types::Message + Send,
808 {
809 async move {
810 let (id, message) = self
811 .create_object::<jmap_chat_types::Message, _>(caller, account_id, create_id, build)
812 .await?;
813 let event = crate::OutboundEvent::NewMessage {
814 chat_id: message.chat_id.clone(),
815 message_id: message.id.clone(),
816 sender_msg_id: message.sender_msg_id.clone(),
817 };
818 self.on_outbound_event(caller, account_id, &event).await;
819 Ok((id, message))
820 }
821 }
822
823 /// Apply a partial update (patch) to an existing object.
824 ///
825 /// Returns `Some(updated_object)` if the backend modified any properties
826 /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
827 /// or `None` if the patch was applied verbatim.
828 ///
829 /// # Authorisation contract
830 ///
831 /// Implementors MUST verify that `caller` may act as the owner of
832 /// `account_id` before applying the patch and MUST return [`BackendSetError::SetError`]
833 /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
834 /// for the workspace-canonical rationale; the same rule applies here.
835 ///
836 /// # Patch format
837 ///
838 /// `patch` is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
839 /// Merge Patch: "The keys are a path in JSON Pointer format
840 /// \[RFC6901\], with an implicit leading "/"". So `{"a/b": null}`
841 /// removes member `b` of property `a`; it does not touch a top-level
842 /// property literally named `a/b`. A `null` value sets the
843 /// property's default if it has one, otherwise removes it. A pointer
844 /// into an array, a pointer whose parent does not exist, or two keys
845 /// where one pointer is a prefix of the other "MUST be rejected with
846 /// an "invalidPatch" error".
847 ///
848 /// Implementors SHOULD apply `patch` with
849 /// [`jmap_server::apply_patch_object`], which enforces these rules
850 /// all-or-nothing, and map any [`jmap_server::PatchPathError`] to
851 /// [`jmap_server::SetErrorType::InvalidPatch`], as the reference
852 /// `MemoryBackend` does.
853 ///
854 /// # Errors
855 ///
856 /// As for [`create_object`](Self::create_object), plus these RFC 8620
857 /// §5.3 rules for update:
858 ///
859 /// - "If an id given cannot be found, the update or destroy MUST be
860 /// rejected with a "notFound" set error."
861 /// - A patch that breaks the rules under "Patch format" is
862 /// `invalidPatch`.
863 /// - A patched record that is invalid is `invalidProperties`. That
864 /// includes changing a server-set property, though "it is not an
865 /// error to include a server-set property in an update as long as
866 /// the value is identical to the current value on the server."
867 ///
868 /// # Atomicity
869 ///
870 /// RFC 8620 §5.3: the server "MUST NOT only commit part of an update
871 /// to a single record". Apply the whole patch and validate the result
872 /// before writing it, so that on any error the stored record is
873 /// unchanged. State and change log follow
874 /// [`create_object`](Self::create_object) ("State and change log"); an
875 /// `Ok(None)` return still advances the state.
876 fn update_object<O: SetObject + Send + Sync>(
877 &self,
878 caller: &Self::CallerCtx,
879 account_id: &jmap_types::Id,
880 id: &jmap_types::Id,
881 patch: O::Patch,
882 ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
883
884 /// Destroy an existing object by id.
885 ///
886 /// # Authorisation contract
887 ///
888 /// Implementors MUST verify that `caller` may act as the owner of
889 /// `account_id` before destroying it and MUST return [`BackendSetError::SetError`]
890 /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
891 /// for the workspace-canonical rationale; the same rule applies here.
892 ///
893 /// # Errors
894 ///
895 /// As for [`create_object`](Self::create_object), plus these RFC 8620
896 /// §5.3 rules for destroy: an unknown id, including one already
897 /// destroyed, is `notFound`, and a destroy that "would violate an ACL
898 /// or other permissions policy" is `forbidden`.
899 ///
900 /// `destroy_object::<Space>` MUST return `forbidden` unless the caller
901 /// holds `manage_space` in that Space, checked atomically with the
902 /// destroy (draft-atwood-jmap-chat-00 §Destroying a Space, jmap-chat-spec
903 /// 77c3474 L1391: "The caller SHOULD hold `"manage_space"`"; "Servers
904 /// SHOULD return a `forbidden` SetError when the caller does not satisfy
905 /// the deployment's destroy-authorization rules"). This crate performs
906 /// the recommended check by choice. The handler does no check of its
907 /// own.
908 ///
909 /// # Cascades
910 ///
911 /// `destroy_object::<Message>` MUST also remove the id from its
912 /// Chat's `pinnedMessageIds` (draft-atwood-jmap-chat-00 §Chat:
913 /// "When a pinned Message is hard-deleted, the server MUST remove
914 /// its id from this list."), as
915 /// [`expire_message`](ChatMessageLifecycle::expire_message) does. That change is
916 /// a Chat update.
917 ///
918 /// `destroy_object::<Space>` MUST also destroy every channel Chat
919 /// whose `spaceId` is the Space and every Message in those Chats
920 /// (draft-atwood-jmap-chat-00 §Destroying a Space: "Cascades to all
921 /// channel Chats and their Messages. Hard-deletes all records; no
922 /// tombstones are retained."). Those are Chat and Message destroys.
923 ///
924 /// Every Chat destroy, including those cascades, MUST also destroy
925 /// the Chat's ReadPosition (draft-atwood-jmap-chat-00 §ReadPosition:
926 /// the server "destroys it when the Chat is destroyed"). That is a
927 /// ReadPosition destroy.
928 ///
929 /// If the backend itself changes another record because of the
930 /// destroy, it MUST advance that record type's state and record the
931 /// change in the same atomic step, so `/changes` on that type sees it.
932 /// State and change log for `O` follow
933 /// [`create_object`](Self::create_object) ("State and change log").
934 fn destroy_object<O: SetObject + Send + Sync>(
935 &self,
936 caller: &Self::CallerCtx,
937 account_id: &jmap_types::Id,
938 id: &jmap_types::Id,
939 ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
940
941 /// Returns `true` if this backend supports JMAP object type `O` for
942 /// `account_id`, as seen by `caller`.
943 ///
944 /// # Types in scope
945 ///
946 /// Implementors should answer for the object types this trait
947 /// covers (draft-atwood-jmap-chat-00): `Chat`, `Message`, `Space`,
948 /// `SpaceInvite`, `SpaceBan`, `ChatBan`, `ChatContact`, `CustomEmoji`,
949 /// `ReadPosition`, and `PresenceStatus`. Backends MAY answer for
950 /// object types from sibling extensions if they also implement those
951 /// traits. A backend that does not recognise `O` SHOULD return
952 /// `false`.
953 ///
954 /// # Callers
955 ///
956 /// The handler library in this crate does not call this method. The
957 /// server consumer calls it when building the JMAP session capability
958 /// response.
959 ///
960 /// # Per-account semantics
961 ///
962 /// Capabilities are per account (RFC 8620 §1.6.2, §2
963 /// `accountCapabilities`), so the answer may vary with `caller` and
964 /// `account_id`. Backends that support every type in this trait for
965 /// every account can ignore both arguments and return `true`.
966 ///
967 /// # Why sync, not async
968 ///
969 /// Type-support is a deployment capability question answered from
970 /// in-process state. A backend whose supported types come from
971 /// configuration or a per-account record SHOULD load it ahead of the
972 /// request and answer from the in-memory snapshot. See the
973 /// trait-level "Async vs sync method convention" section above for
974 /// the workspace rationale.
975 fn supports_type<O: JmapObject>(
976 &self,
977 caller: &Self::CallerCtx,
978 account_id: &jmap_types::Id,
979 ) -> bool;
980}
981
982/// Space structure: invites, joins, member and role patches, and Space-wide settings.
983///
984/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
985pub trait ChatSpaces: JmapBackend {
986 /// Generate a cryptographically random invite code.
987 ///
988 /// Implementations MUST use a CSPRNG seeded from OS entropy. The
989 /// recommended choices are [`rand::rngs::OsRng`] or the [`getrandom`]
990 /// crate directly. Do NOT use `rand::thread_rng()` for security-relevant
991 /// output: although current `rand` versions document `ThreadRng` as
992 /// cryptographically secure, its underlying algorithm is
993 /// implementation-defined and has changed across releases, and the
994 /// `rand` book explicitly routes security-sensitive callers to `OsRng`.
995 ///
996 /// The returned string must be unguessable — do NOT use timestamps,
997 /// sequential counters, or non-CSPRNG sources.
998 ///
999 /// # Output shape contract
1000 ///
1001 /// Implementations MUST satisfy ALL of the following for the kit's
1002 /// constant-time-compare guarantee (see below) to hold:
1003 ///
1004 /// 1. **Fixed length across calls.** Every invocation of
1005 /// `generate_invite_code` on a single backend MUST return a
1006 /// string of the same byte length. A backend that returns
1007 /// variable-length codes leaks a length oracle through the
1008 /// constant-time-compare timing channel: `ct_eq` returns
1009 /// `Choice(0)` cheaply on length mismatch, so an attacker can
1010 /// learn whether their candidate code matches the stored
1011 /// length even when the content compare is constant-time.
1012 /// 2. **Minimum 128 bits of CSPRNG entropy.** The reference
1013 /// `MemoryBackend` impl in this crate (in `memory.rs`) emits
1014 /// 32 lowercase-hex characters (16 bytes = 128 bits) which is
1015 /// the workspace floor. Production backends MAY use more; less
1016 /// is forbidden. The trait method itself is abstract — no
1017 /// default impl — so backends MUST provide one.
1018 /// 3. **ASCII-safe encoding.** The returned bytes MUST be 7-bit
1019 /// ASCII printable, byte-length-equal-to-char-length, and
1020 /// safe to use as-is in JMAP wire format and HTTP-style
1021 /// URL paths (no `/`, `+`, `=`, or whitespace). Recommended
1022 /// encodings: lowercase hex (the default), base32 unpadded,
1023 /// base64url unpadded. Plain base64 with `/` is forbidden
1024 /// because downstream URL-encoded redemption flows misroute
1025 /// the slash. Non-ASCII output is forbidden because
1026 /// helpers that take byte-prefix slices (e.g. the
1027 /// `iso8601_before` partial-comparison family) panic on
1028 /// multi-byte UTF-8 boundaries.
1029 /// 4. **Sufficient lifespan.** Codes MUST remain
1030 /// discriminable from each other across the backend's
1031 /// retention window. With 128 bits of entropy and
1032 /// well-mixed CSPRNG output, collision probability is
1033 /// cryptographically negligible up to 2^64 active codes.
1034 ///
1035 /// A backend that cannot meet any of points 1–3 MUST NOT
1036 /// expose `Space/join`'s invite-code redemption path, or MUST
1037 /// build its own redemption with a different constant-time
1038 /// argument. The kit's `handle_space_join` assumes the contract
1039 /// without re-validating each code's shape.
1040 ///
1041 /// # Constant-time comparison contract
1042 ///
1043 /// Consumers of the returned code (notably `Space/join` invite-code
1044 /// lookup) MUST compare it against attacker-supplied values in
1045 /// constant time using `subtle::ConstantTimeEq::ct_eq` or equivalent.
1046 /// The reference handler in `space::handle_space_join` already does
1047 /// this; backends that build their own invite-redemption paths must
1048 /// preserve the invariant. A plain `String == String` short-circuits
1049 /// at the first mismatched byte and exposes a byte-by-byte timing
1050 /// oracle for credential recovery.
1051 ///
1052 /// # Errors
1053 ///
1054 /// A backend that cannot mint a code (entropy starvation, an
1055 /// unreachable HSM or KMS) returns `Err`; `SpaceInvite/set` reports
1056 /// that create as `serverFail`. Never fall back to a predictable code.
1057 ///
1058 /// `caller` and `account_id` identify the SpaceInvite create the code
1059 /// is for, so a backend can scope its entropy source per account.
1060 ///
1061 /// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
1062 /// [`getrandom`]: https://docs.rs/getrandom
1063 fn generate_invite_code(
1064 &self,
1065 caller: &Self::CallerCtx,
1066 account_id: &jmap_types::Id,
1067 ) -> impl std::future::Future<Output = Result<String, Self::Error>> + Send;
1068
1069 /// Redeem the SpaceInvite `invite_id` for `Space/join`: add the owner
1070 /// (member entry `account_id`, no roles, `joinedAt` = `joined_at`) to
1071 /// the invite's Space and increment the invite's `uses`.
1072 ///
1073 /// Per draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474
1074 /// L1416): "The `uses` increment and membership insertion SHOULD be
1075 /// performed within a single atomic operation so that concurrent
1076 /// redemptions cannot exceed `maxUses`." This crate requires the
1077 /// recommended atomicity by choice.
1078 ///
1079 /// # Atomicity contract
1080 ///
1081 /// The `uses < maxUses` check, the already-member check, the member
1082 /// append and the `uses` increment MUST all take effect or none, and
1083 /// MUST be serialized against concurrent redemptions of the invite
1084 /// and concurrent membership writes to the Space (a transaction or
1085 /// compare-and-swap). Composing this from `update_object` calls loses
1086 /// that guarantee: a failed second write leaves a member admitted
1087 /// without a use counted, and concurrent joins both pass `maxUses`.
1088 ///
1089 /// # Account scope
1090 ///
1091 /// `account_id` is the request's `accountId`, which names the
1092 /// account hosting the Space; the handler resolves the invite code
1093 /// only within that account, and `invite_id` and its Space live
1094 /// there. Implementations need no server-wide invite-code index.
1095 ///
1096 /// # When the handler calls this
1097 ///
1098 /// Once, after the invite resolved by code and is unexpired, and
1099 /// after the ban and `closedAt` checks. The handler maps each
1100 /// [`InviteJoinRefusal`] to the draft's `invalidArguments` method
1101 /// error. There is no default: a non-atomic default would reinstate
1102 /// the race.
1103 fn join_space_with_invite(
1104 &self,
1105 caller: &Self::CallerCtx,
1106 account_id: &jmap_types::Id,
1107 invite_id: &jmap_types::Id,
1108 joined_at: &jmap_types::UTCDate,
1109 ) -> impl std::future::Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send;
1110
1111 /// Apply a sequence of structural mutations to a Space
1112 /// (draft-atwood-jmap-chat-00 §Space/set).
1113 ///
1114 /// `Space/set` `update` operations use semantic mutation keys
1115 /// (`addRoles`, `removeRoles`, `addMembers`, …) rather than RFC 8620
1116 /// JSON Pointer patches. The handler in `space::handle_space_set`
1117 /// parses the wire object, unfolds each array entry into a
1118 /// [`SpacePatchOp`](crate::SpacePatchOp) value, then calls this method with the resulting
1119 /// ordered `Vec`.
1120 ///
1121 /// # Authorisation contract
1122 ///
1123 /// Implementors MUST verify that `caller` may act as the owner of
1124 /// `account_id` before applying any op, and MUST return
1125 /// [`BackendSetError::SetError`] with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden)
1126 /// for the whole call otherwise; the handler reports it in `notUpdated`.
1127 /// The per-op permission and role-hierarchy gates under "Per-op error
1128 /// semantics" are also enforced here, atomically with the mutation. See
1129 /// [`ChatStore::create_object`] for the workspace-canonical rationale.
1130 ///
1131 /// # Ordering and atomicity
1132 ///
1133 /// Implementations SHOULD apply ops in input order and SHOULD provide
1134 /// best-effort transactional semantics so that a partial failure does
1135 /// not leave the Space in a half-updated state. The reference
1136 /// in-memory implementation locks the entire backend for the duration
1137 /// of the call. A database-backed implementation should wrap the
1138 /// sequence in a single transaction.
1139 ///
1140 /// # Permission and limit checks
1141 ///
1142 /// Permission gates (`manage_space`, `manage_roles`,
1143 /// `manage_members`, `manage_channels`) are backend-canonical per
1144 /// workspace AGENTS.md "Caller identity (foundation seam)": the
1145 /// reference handler does NOT apply gates before calling this
1146 /// method, and the backend is responsible for rejecting any op the
1147 /// caller is not authorized to perform.
1148 ///
1149 /// Per-aggregate count limits on roles, members, channels, and
1150 /// categories per Space are **backend-canonical** as of
1151 /// bd:JMAP-x2gd.44: the backend MUST query its own
1152 /// [`ChatSettings::limits`], project the post-patch counts for the
1153 /// target Space, and reject the whole patch with an `overQuota`
1154 /// SetError (RFC 8620 §5.3) if any aggregate would exceed its
1155 /// cap. The cap enforcement MUST be atomic with the mutation
1156 /// itself — typically inside the same database transaction or
1157 /// the same mutex critical section. Per
1158 /// draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
1159 /// 2026-05-11), this behavior is normative.
1160 ///
1161 /// The handler at [`crate::space::handle_space_set`] additionally
1162 /// runs a defense-in-depth pre-flight cap check before this
1163 /// method, but the pre-flight is non-load-bearing: a backend
1164 /// caller that bypasses the JMAP wire layer (admin tool,
1165 /// federation receiver, internal batch importer) and calls
1166 /// `apply_space_patch` directly MUST still see caps enforced.
1167 /// The pre-flight exists only to surface `overQuota` to the
1168 /// client as a single SetError without consuming a backend
1169 /// round-trip; backends MAY rely on the handler having pre-checked
1170 /// for performance, but MUST NOT rely on it for correctness.
1171 ///
1172 /// The role-position hierarchy check (members may only add or modify
1173 /// roles whose `position` is strictly less than their own
1174 /// highest-position role — draft §Space/set L1260, L1266) MUST
1175 /// be enforced by the backend because it is atomic with the
1176 /// mutation and depends on the current Space state.
1177 ///
1178 /// # Cross-type cascade contract
1179 ///
1180 /// Several `SpacePatchOp` variants have side effects on other JMAP
1181 /// types in the chat extension (`Chat`, `Message`). The wire-format
1182 /// `Space/set` response describes only the Space-side change, but
1183 /// `/changes` subscribers on the cascaded types depend on the
1184 /// backend bumping the relevant type state tokens. A backend that
1185 /// performs the cross-type mutations but forgets the state bumps
1186 /// silently desynchronises every multi-client subscriber — the
1187 /// failure is invisible to single-tenant smoke tests.
1188 ///
1189 /// The required cascades are:
1190 ///
1191 /// * `RemoveChannel` — MUST destroy the channel-kind `Chat` record
1192 /// and every `Message` whose `chatId` matches the removed
1193 /// channel (draft §Space/set L1283: "Cascades to all
1194 /// Messages in those channels."), and the channel's
1195 /// `ReadPosition` (draft §ReadPosition: the server "destroys it
1196 /// when the Chat is destroyed"). The `Chat`, `Message` and
1197 /// `ReadPosition` type state tokens MUST bump so their `/changes`
1198 /// subscribers see the destruction.
1199 ///
1200 /// * `RemoveCategory` — MUST clear `Chat.categoryId` on every
1201 /// channel-kind `Chat` whose `categoryId` named the removed
1202 /// category (the channels fall back to uncategorized). The
1203 /// `Chat` type state token MUST bump and the affected channel
1204 /// ids MUST appear in the next `Chat/changes` entry's `updated`
1205 /// list.
1206 ///
1207 /// * `AddCategory` / `UpdateCategory` with a non-empty `channelIds`
1208 /// array — MUST set `Chat.categoryId` on each named channel
1209 /// (relocating it from its previous category or from
1210 /// uncategorized). The `Chat` type state token MUST bump and
1211 /// the relocated channel ids MUST appear in `Chat/changes`
1212 /// `updated`. This pins a regression class where channel
1213 /// relocations silently bypass the `Chat/changes` log; a
1214 /// backend that mutates `Chat.categoryId` without bumping the
1215 /// `Chat` state token desynchronises every multi-client
1216 /// subscriber.
1217 ///
1218 /// * `RemoveRole` — MUST strip the removed role id from
1219 /// `roleIds` on every `SpaceMember` of this Space (draft
1220 /// §Space/set L1263). Members embed directly in `Space`,
1221 /// so the cascade is captured by the existing `Space` state
1222 /// bump; no separate `Member/changes` rotation is required.
1223 ///
1224 /// * `RemoveMember` — MUST remove the member entry and keep
1225 /// `Space.memberCount` consistent with `members.len()`. The
1226 /// spec does not mandate cascade to the member's `ReadPosition`
1227 /// records; the reference impl leaves them in place and treats
1228 /// ReadPosition cleanup as implementation-defined. A backend
1229 /// that destroys orphaned ReadPositions MUST bump the
1230 /// `ReadPosition` type state token; a backend that retains
1231 /// them MUST NOT.
1232 ///
1233 /// State-token bumps SHOULD be batched per call: one bump per
1234 /// affected type per `apply_space_patch` invocation, not one bump
1235 /// per op. The reference impl combines every channel created,
1236 /// updated, and destroyed by a patch into a single `Chat/changes`
1237 /// entry; doing the same in production keeps `/changes`
1238 /// rotation rates proportional to client-visible mutations rather
1239 /// than to internal op count.
1240 ///
1241 /// # Server-set field invariants
1242 ///
1243 /// Server-set fields on the target Space (`memberCount`,
1244 /// `updatedAt`, and any future analogous cached aggregates) MUST
1245 /// be kept consistent with the post-mutation state. Specifically,
1246 /// after any combination of `AddMember` and `RemoveMember` ops,
1247 /// `Space.memberCount` MUST equal `Space.members.len()` as
1248 /// observed by the next `Space/get`. Backends MAY store these as
1249 /// cached values that they recompute on every mutation, or MAY
1250 /// compute them lazily at read time; either is acceptable as
1251 /// long as `Space/get` returns values consistent with the
1252 /// returned `members` array. The natural-minimal "persist
1253 /// memberCount once and trust it" implementation is **not**
1254 /// correct: subsequent mutations to `members` would let
1255 /// `memberCount` drift silently.
1256 ///
1257 /// `Space.closedAt` is server-set the same way: when the caller
1258 /// removes themselves as the last member holding `manage_space`
1259 /// and other members remain, the backend MUST set `closedAt` in
1260 /// the same mutation (draft §Space/set `removeMembers`). The
1261 /// handler rejects every other update to a closed Space.
1262 ///
1263 /// # Per-op error semantics
1264 ///
1265 /// Backend rejections that originate from a single op carry both
1266 /// a typed [`SetErrorType`] and a human-readable `description`
1267 /// string. The kit's integration tests pin specific
1268 /// (`SetErrorType`, `description`-substring) pairs for the
1269 /// common failure modes; a backend that returns a different
1270 /// variant or an empty description will fail those tests when
1271 /// plugged in.
1272 ///
1273 /// The following table records the contract for the
1274 /// failure modes the kit exercises today:
1275 ///
1276 /// | Op + failure mode | `SetErrorType` | `description` MUST contain |
1277 /// |---|---|---|
1278 /// | Any op, caller lacks the spec-mandated permission | `Forbidden` | the permission identifier as a substring (`"manage_space"`, `"manage_channels"`, `"manage_members"`, `"manage_roles"`, or a deployment-specific permission name) |
1279 /// | `AddRole` / `UpdateRole` naming a role (or new `position`) at or above caller's highest role `position`; `AddMember` assigning, or `UpdateMember` adding or removing, such a role (draft §Space/set: "servers SHOULD enforce this"; a backend that enforces it uses this row) | `Forbidden` | `"hierarchy"` or `"position"` |
1280 /// | Any op or combination of ops that takes the Space from at least one member holding `manage_members` or `manage_space` to none (when [`Self::protect_last_admin`] returns `true`), other than self-removal | `InvalidProperties` (`properties`: the patch key(s) concerned, among `removeRoles`, `updateRoles`, `removeMembers`, `updateMembers`) | `"last-admin"` or `"manage_members"` |
1281 /// | `AddMember` with `userId` already a member | `InvalidProperties` (`properties: ["userId"]`) | implementation-defined; the reference impl names the duplicate userId |
1282 /// | `AddMember` with a `roleId` that does not name a role on this Space | `InvalidProperties` (`properties: ["roleIds"]`) | implementation-defined; the reference impl names the unknown roleId |
1283 /// | `RemoveRole` / `RemoveChannel` / `RemoveCategory` with an id that does not exist on this Space | `NotFound` | implementation-defined; the reference impl names the missing id |
1284 ///
1285 /// The "MUST contain ... as a substring" rule on permission-denied
1286 /// failures lets downstream UI / CLI consumers route
1287 /// permission-request flows by parsing the description, and lets
1288 /// users see "Permission denied: missing manage_space" rather
1289 /// than a bare "Permission denied". Deployments that need a
1290 /// programmatic alternative SHOULD additionally surface the
1291 /// missing permission via [`SetError::with_extra`] under a
1292 /// deployment-specific key — substring matching is the floor,
1293 /// not the ceiling.
1294 ///
1295 /// Note on routing: per-op rejections normally surface inside the
1296 /// returned [`OpResult`] vector, NOT as a top-level
1297 /// [`BackendSetError`] return. The handler at
1298 /// [`crate::space::handle_space_set`] applies the kit's per-
1299 /// update-target atomicity: any failing op in the patch fails the
1300 /// whole `update` target, so the test fixtures see the first-failing
1301 /// op's `(SetErrorType, description)` surface on
1302 /// `notUpdated[<spaceId>]`. The table above describes the
1303 /// per-op outcome content; the handler does not synthesise new
1304 /// variants or rewrite descriptions.
1305 ///
1306 /// # Return value
1307 ///
1308 /// On success, returns a `Vec<OpResult>` of the same length as `ops`,
1309 /// in input order. Each entry reports the outcome of one op (id
1310 /// assignment for `Add*` variants, error for rejections). The
1311 /// handler maps per-op errors back into the `/set` response shape
1312 /// per [`OpResult`]'s documentation.
1313 ///
1314 /// Returns [`BackendSetError::Other`] only for backend-level failures
1315 /// (the storage layer is unreachable, the account does not exist,
1316 /// `space_id` is unknown, etc.) — i.e. failures that prevent any op
1317 /// from being attempted. Per-op rejections (permission denied,
1318 /// invalid id, role hierarchy violation, etc.) go in the `outcome`
1319 /// field of the returned [`OpResult`] vector, not in an error return.
1320 fn apply_space_patch(
1321 &self,
1322 caller: &Self::CallerCtx,
1323 account_id: &jmap_types::Id,
1324 space_id: &jmap_types::Id,
1325 ops: Vec<SpacePatchOp>,
1326 ) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
1327
1328 /// Apply a JSON Merge Patch to a Space's top-level metadata fields
1329 /// (draft-atwood-jmap-chat-00 §Space/set, `name`, `description`,
1330 /// `iconBlobId`, `isPublic`, `isPubliclyPreviewable`).
1331 ///
1332 /// `Space/set` `update` operations carrying *only* top-level
1333 /// metadata fields (and not the semantic-mutation keys
1334 /// `addRoles` / `addMembers` / `addChannels` / `addCategories`
1335 /// etc.) route through this method instead of the generic
1336 /// [`ChatStore::update_object`]. Mixed patches carrying both top-level
1337 /// metadata AND semantic-mutation keys call
1338 /// [`Self::apply_space_patch`] first (for the structural ops) and
1339 /// this method second (for the metadata). The handler at
1340 /// `space::handle_space_set` is responsible for the split and for
1341 /// stripping non-metadata keys before calling this method.
1342 ///
1343 /// # Authorisation contract
1344 ///
1345 /// Implementors MUST verify that `caller` may act as the owner of
1346 /// `account_id` before applying the patch and MUST return [`BackendSetError::SetError`]
1347 /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`ChatStore::create_object`]
1348 /// for the workspace-canonical rationale; the same rule applies here.
1349 ///
1350 /// # Permission and atomicity
1351 ///
1352 /// Per draft-atwood-jmap-chat-00, every top-level metadata field
1353 /// carries the marker "Mutable by members with `manage_space`
1354 /// permission". Implementations MUST gate the mutation on the
1355 /// caller's effective permissions in the target Space: verify the
1356 /// caller holds `manage_space` (resolved through the Space's role
1357 /// hierarchy) and reject the patch with
1358 /// [`SetErrorType::Forbidden`] if not. The caller is the owner, whose
1359 /// `members` entry is the `account_id` (draft §Terminology), so look
1360 /// the caller up by `account_id`, not by the principal, whether or
1361 /// not [`JmapAccounts::principal_id`](jmap_server::JmapAccounts::principal_id) returns `Some`; the same holds
1362 /// for every caller-membership or permission check in this trait.
1363 ///
1364 /// The check fires inside this method atomically with the
1365 /// mutation: snapshot the Space's role/member state, evaluate
1366 /// the permission gate, and apply the merge patch in one
1367 /// critical section. Backend canonical per workspace AGENTS.md.
1368 ///
1369 /// # `patch` shape
1370 ///
1371 /// The handler decodes the wire patch's metadata-key subset
1372 /// (`name`, `description`, `iconBlobId`, `isPublic`,
1373 /// `isPubliclyPreviewable`) into a [`SpaceMetadataPatch`](crate::SpaceMetadataPatch),
1374 /// stripping structural mutation keys (`addRoles` etc.) before
1375 /// building it. Each field is `Option<_>`; nullable target fields
1376 /// use `Option<Clearable<T>>` so the backend can distinguish
1377 /// "wire null" (clear) from "absent" (unchanged). Backends MAY
1378 /// validate the values further (e.g. reject an `icon_blob_id`
1379 /// referencing a non-existent blob) and surface those as
1380 /// [`SetError`] returns. The expected `SetErrorType` for
1381 /// value-level validation failures is
1382 /// [`SetErrorType::InvalidProperties`] with the offending field
1383 /// name in `properties` — see the "Diagnostic content
1384 /// convention" section below for the blob-not-found shape
1385 /// specifically. (RFC 8620 §5.3 defines `blobNotFound` only as
1386 /// a method-level error; at the SetError level it surfaces as
1387 /// `InvalidProperties` naming the offending blob-id field.)
1388 ///
1389 /// # Return value
1390 ///
1391 /// The discriminator between `Ok(Some(space))` and `Ok(None)` is
1392 /// the **wire-visible Space shape**:
1393 ///
1394 /// - Return `Ok(None)` if the wire-visible `Space` (the shape
1395 /// `Space/get` would serialise after applying this patch) is
1396 /// identical to the result of mechanically applying the patch
1397 /// keys to the prior state with no additional server-side
1398 /// modification. The handler can then build the `/set` `updated`
1399 /// entry from the input patch alone with no extra fetch.
1400 /// - Return `Ok(Some(space))` if the backend modified any
1401 /// wire-visible property beyond what the client requested
1402 /// (RFC 8620 §5.3 server-set field echo, e.g. a normalised
1403 /// `name`, a derived `iconBlobId`, a server-bumped
1404 /// `memberCount`, or any spec-defined server-set field that
1405 /// `Space/get` would return). The handler echoes the returned
1406 /// `Space` to the client.
1407 ///
1408 /// Server-internal bookkeeping that is NOT part of the
1409 /// wire-visible `Space` shape (e.g. private last-touched
1410 /// timestamps used only for `/changes` cache-keying, internal
1411 /// sequence numbers) MUST NOT itself drive the `Some` path —
1412 /// the discriminator is "would `Space/get` return a different
1413 /// shape?", not "did the backend touch anything internally?".
1414 /// A backend that bumps an internal timestamp on every metadata
1415 /// patch correctly returns `Ok(None)` when the wire shape is
1416 /// otherwise unchanged.
1417 ///
1418 /// `Err(BackendSetError::SetError(e))` with `e.kind ==
1419 /// SetErrorType::Forbidden` when the caller fails the
1420 /// `manage_space` gate.
1421 ///
1422 /// # Diagnostic content convention
1423 ///
1424 /// The `SetError.description` on a `manage_space`-gate rejection
1425 /// MUST contain `"manage_space"` as a substring. The kit's
1426 /// integration tests assert this (e.g.
1427 /// `tests/space_metadata_apply.rs`); a backend that returns a
1428 /// bare `SetError::new(SetErrorType::Forbidden)` with no
1429 /// `description` will fail those tests. Build the error via
1430 /// `SetError::new(SetErrorType::Forbidden).with_description(
1431 /// "manage_space permission required")` (or any other string
1432 /// that contains the literal `"manage_space"`).
1433 ///
1434 /// Future blob-validation rejections (e.g. `iconBlobId`
1435 /// referencing a non-existent blob, see the `patch` shape
1436 /// section above) SHOULD surface as
1437 /// `SetErrorType::InvalidProperties` with
1438 /// `properties: ["iconBlobId"]` and a description that names
1439 /// the offending blob id. The reference impl does not validate
1440 /// blobs today; production backends with a blob store SHOULD.
1441 ///
1442 /// Rationale for the separate metadata patch method: routing
1443 /// top-level metadata through the generic `update_object::<Space>`
1444 /// would bypass the permission gate, since the generic path is
1445 /// not permission-aware. This method exists so that top-level
1446 /// `Space/set` `update` requests carrying only metadata fields
1447 /// (`name` / `description` / `iconBlobId` / `isPublic` /
1448 /// `isPubliclyPreviewable`) route through a `manage_space`-gated
1449 /// path instead.
1450 fn apply_space_metadata_patch(
1451 &self,
1452 caller: &Self::CallerCtx,
1453 account_id: &jmap_types::Id,
1454 space_id: &jmap_types::Id,
1455 patch: jmap_chat_types::SpaceMetadataPatch,
1456 ) -> impl std::future::Future<
1457 Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
1458 > + Send;
1459
1460 /// Extra top-level Space properties owned by a Space extension, such
1461 /// as `calendarId` (draft-atwood-jmap-chat-calendars-00 §calendarId)
1462 /// or `taskListId` (draft-atwood-jmap-chat-tasks-00 §taskListId).
1463 ///
1464 /// `Space/set` accepts a listed key instead of rejecting it as
1465 /// `invalidProperties`. On `create`, a non-null value is stored in
1466 /// [`jmap_chat_types::Space::extra`] through `create_object`. In an
1467 /// `update` patch, the key travels in
1468 /// [`SpaceMetadataPatch::extra`](crate::SpaceMetadataPatch::extra) through
1469 /// [`Self::apply_space_metadata_patch`], so it is subject to that
1470 /// method's `manage_space` gate; a `null` value removes the property
1471 /// (RFC 7396). `Space/get` returns stored values like any other
1472 /// property. The non-member restricted view omits them.
1473 ///
1474 /// The handler does not validate values. A backend that must check
1475 /// one (for example, that `taskListId` names an existing TaskList on
1476 /// the same account) rejects it in `create_object` or
1477 /// `apply_space_metadata_patch` with an `invalidProperties` SetError
1478 /// naming the key. A listed key that is already a core Space property
1479 /// or a structural patch key keeps its core meaning.
1480 ///
1481 /// # Default implementation
1482 ///
1483 /// Returns an empty list, so no extension property is accepted.
1484 /// Backends that implement a Space extension override it.
1485 fn space_extension_properties(
1486 &self,
1487 caller: &Self::CallerCtx,
1488 account_id: &jmap_types::Id,
1489 ) -> &'static [&'static str] {
1490 let _ = (caller, account_id);
1491 &[]
1492 }
1493
1494 /// Whether the backend should reject any [`Self::apply_space_patch`]
1495 /// that would leave the target Space with zero members holding
1496 /// either `manage_members` or `manage_space` permission.
1497 ///
1498 /// # Invariant (by outcome, not by op type)
1499 ///
1500 /// The protection is invariant on the *post-patch* state of the
1501 /// (member, role, permission) graph, not on any single op variant.
1502 /// A backend that returns `true` from this method MUST reject every
1503 /// patch that takes the Space from at least one member holding
1504 /// `manage_members` or `manage_space` to none, including (non-exhaustively)
1505 /// the cases below. Self-removal (a `removeMembers` holding only the
1506 /// accountId, which references the owner per draft §Terminology) is
1507 /// exempt: draft §Space/set says
1508 /// "Last-administrator protection does not apply to self-removal."
1509 ///
1510 ///
1511 /// - `RemoveMember` that removes the last admin member.
1512 /// - `UpdateMember` that strips a role granting `manage_members` or
1513 /// `manage_space` from a member who holds no other such role.
1514 /// - `UpdateRole` that removes `manage_members` or `manage_space`
1515 /// permission from a role currently held by the last admin.
1516 /// - `RemoveRole` that drops a permission-granting role from the
1517 /// graph when no other role grants the same permission to a
1518 /// remaining member.
1519 /// - Any combination of the above within a single `ops` vector
1520 /// whose cumulative effect is zero admins.
1521 ///
1522 /// Production backends should project the post-patch graph and
1523 /// reject when the admin count would reach zero, regardless of
1524 /// which op caused the transition.
1525 ///
1526 /// # Why this exists
1527 ///
1528 /// The 2026-05-12 design reversal dropped the `Space.ownerId` field:
1529 /// "who controls a Space" is now fully implementation-defined /
1530 /// out-of-band per draft-atwood-jmap-chat-00.
1531 /// Without a normative owner identity, the kit cannot enforce the
1532 /// previous "owner cannot be removed" rule. Instead the kit exposes
1533 /// this purely permission-graph-based knob: production backends that
1534 /// want to prevent the "no admin left" failure mode return `true`
1535 /// (the trait default); deployments with their own designated
1536 /// controller principal or external admin-tracking system can opt
1537 /// out by returning `false`.
1538 ///
1539 /// # Default implementation
1540 ///
1541 /// Returns `true` — production-safe by default. A third-party
1542 /// backend that does not override this method gets last-admin
1543 /// protection automatically.
1544 ///
1545 /// # Why the reference `MemoryBackend` overrides this to `false`
1546 ///
1547 /// The reference impl flips the default to keep existing
1548 /// integration tests (which do not seed admin memberships) passing
1549 /// unchanged. Tests that exercise the protection path opt in via
1550 /// `MemoryBackend::set_protect_last_admin_for_test(true)`.
1551 ///
1552 /// # Atomicity
1553 ///
1554 /// The check fires inside [`Self::apply_space_patch`] atomically
1555 /// with the candidate mutation: the backend snapshots the Space's
1556 /// member/role state, projects the post-patch admin count across
1557 /// all ops in the patch (member adds/removes, role-id changes,
1558 /// permission edits), and rejects the whole update target with an
1559 /// `invalidProperties` SetError naming the patch key(s) concerned
1560 /// if zero admins would remain (draft §Space/set `removeMembers`:
1561 /// "a refusal names the patch key concerned").
1562 ///
1563 /// # Why sync, not async
1564 ///
1565 /// This predicate is a deployment-policy flag: a backend either
1566 /// enforces the last-admin invariant or it does not. Backends
1567 /// that consult an external admin-tracking service to derive the
1568 /// answer SHOULD cache the per-account boolean and answer from
1569 /// the cache. See the trait-level "Async vs sync method
1570 /// convention" section above for the workspace rationale.
1571 fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
1572 let _ = (caller, account_id);
1573 true
1574 }
1575
1576 /// The permissions of the implicit `@everyone` role in `space`, the
1577 /// account `account_id`'s Space.
1578 ///
1579 /// Every member holds that role, "which serves as the permission
1580 /// floor" (draft-atwood-jmap-chat-00 §SpaceRole, jmap-chat-spec
1581 /// 29e9a41 L812), and §Space Permission Resolution step 1 (L1705)
1582 /// unions its permissions with the member's SpaceRoles. The draft puts
1583 /// them on no wire object, so the backend decides where each Space's
1584 /// set is stored. The chat bindings (`jmap-chat-filenode-server`,
1585 /// `jmap-chat-vtc-server`) and the `Peer/deliver` handler of
1586 /// `jmap-chat-federation-server` read it here.
1587 ///
1588 /// No default: a permission floor has no neutral value.
1589 fn everyone_permissions(
1590 &self,
1591 caller: &Self::CallerCtx,
1592 account_id: &jmap_types::Id,
1593 space: &jmap_chat_types::Space,
1594 ) -> impl std::future::Future<
1595 Output = Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, Self::Error>,
1596 > + Send;
1597}
1598
1599/// Space-scoped authorization gates: custom emoji, SpaceBan and SpaceInvite writes and reads.
1600///
1601/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
1602pub trait SpacePolicy: JmapBackend {
1603 /// Authorization gate consulted by `handle_emoji_set` before every
1604 /// `CustomEmoji/set` create, update, or destroy.
1605 ///
1606 /// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11,
1607 /// "refactor: implementation-defined emoji authorization"):
1608 /// authorization for `CustomEmoji/set` is fully
1609 /// implementation-defined, for both server-global and Space-scoped
1610 /// emoji. When the caller is not authorized, the handler emits a
1611 /// `forbidden` SetError (RFC 8620 §5.3).
1612 ///
1613 /// # `target_space_id` semantics
1614 ///
1615 /// `target_space_id` is the **actual scope of the emoji this op
1616 /// targets**:
1617 ///
1618 /// - `None` — the emoji is server-global (its `spaceId` field is
1619 /// absent / null).
1620 /// - `Some(id)` — the emoji is scoped to that Space (its `spaceId`
1621 /// field equals `id`).
1622 ///
1623 /// For `Create`, the handler reads the scope from the create
1624 /// payload. For `Update` and `Destroy`, the handler pre-fetches
1625 /// the existing emoji via `get_objects` and passes its current
1626 /// `spaceId`. If the pre-fetch reports the id as not found, the
1627 /// handler skips this gate entirely and lets `update_object` /
1628 /// `destroy_object` surface a `notFound` SetError naturally — a
1629 /// non-existent target consumes no authorization decision.
1630 ///
1631 /// # When the handler calls this
1632 ///
1633 /// Exactly once per create/update/destroy entry in the request,
1634 /// AFTER wire-format validation has succeeded and BEFORE the
1635 /// corresponding `create_object` / `update_object` /
1636 /// `destroy_object` call. The handler skips the underlying mutation
1637 /// when the outer `Result` is `Ok(Err(_))` or when the outer is
1638 /// `Err(_)`. The wire mapping is:
1639 ///
1640 /// - `Ok(Ok(()))` — permit; the handler proceeds to the underlying
1641 /// `create_object` / `update_object` / `destroy_object`.
1642 /// - `Ok(Err(set_err))` — deny with reason; the handler serialises
1643 /// `set_err` into the appropriate `notCreated` / `notUpdated` /
1644 /// `notDestroyed` map verbatim. Backends construct the SetError
1645 /// with the type, description, and any `with_extra` fields the
1646 /// deployment wants the client to see.
1647 /// - `Err(e)` — backend infrastructure failure; the handler maps
1648 /// to a `serverFail` SetError.
1649 ///
1650 /// # Default implementation
1651 ///
1652 /// The default returns `Ok(Ok(()))` — every op is permitted. This
1653 /// matches the workspace's "kit defines the hook; consumer
1654 /// enforces the policy" posture (see the parallel design of
1655 /// [`ChatAccessPolicy::slow_mode_check`]). Production backends SHOULD override
1656 /// this method to apply the deployment's permission model — e.g.
1657 /// "only members of `target_space_id` may modify a Space-scoped
1658 /// emoji" or "only `manage_emoji` permission-holders may modify
1659 /// server-global emoji."
1660 ///
1661 /// # SetError shape recommendation
1662 ///
1663 /// Production backends SHOULD return
1664 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1665 /// .with_description("…")))` for authorization denials, mirroring
1666 /// the workspace convention for /set responses. The description
1667 /// should explain the deployment's denial reason without leaking
1668 /// internal policy details — e.g. "Space-scoped emoji on this
1669 /// Space requires `manage_channels` permission" rather than
1670 /// "principal abc123 is not in role admin on Space xyz789".
1671 ///
1672 /// # Foundation seam
1673 ///
1674 /// Backends that wish to identify the caller call
1675 /// [`jmap_server::JmapAccounts::principal_id`] on `caller` to learn
1676 /// whether identity is wired, and compare `account_id` (the owner's
1677 /// member entry, draft §Terminology) against the Space's `members`
1678 /// list, or consult ACLs or whatever permission model the
1679 /// deployment uses. Backends whose
1680 /// `principal_id` returns `None` (the workspace default, see the
1681 /// "Caller identity (foundation seam)" section of the workspace
1682 /// `AGENTS.md`) cannot meaningfully implement identity-scoped
1683 /// authorization — they should either override `principal_id`
1684 /// first or return `Ok(Ok(()))` to match the reference posture.
1685 fn may_set_custom_emoji(
1686 &self,
1687 _caller: &Self::CallerCtx,
1688 _account_id: &jmap_types::Id,
1689 _target_space_id: Option<&jmap_types::Id>,
1690 _op: EmojiSetOp,
1691 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1692 async { Ok(Ok(())) }
1693 }
1694
1695 /// Authorization gate consulted by `handle_ban_set` before each
1696 /// SpaceBan create, update or destroy.
1697 ///
1698 /// Per draft-atwood-jmap-chat-00 §SpaceBan/set: create, update and
1699 /// destroy each "Requires `"ban"` permission in the Space."
1700 ///
1701 /// # When the handler calls this
1702 ///
1703 /// Once per entry, AFTER wire-format validation and BEFORE
1704 /// `create_object` / `update_object` / `destroy_object`. `space_id`
1705 /// is the create body's `spaceId`, or the stored ban's `spaceId` for
1706 /// update and destroy; an update or destroy whose ban does not
1707 /// resolve skips the gate so the backend surfaces `notFound`. The
1708 /// return mapping is the same as [`Self::may_set_custom_emoji`].
1709 ///
1710 /// # Default implementation
1711 ///
1712 /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1713 /// parallel hooks above. Production backends SHOULD override this
1714 /// method and deny with
1715 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1716 fn may_set_space_ban(
1717 &self,
1718 _caller: &Self::CallerCtx,
1719 _account_id: &jmap_types::Id,
1720 _space_id: &jmap_types::Id,
1721 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1722 async { Ok(Ok(())) }
1723 }
1724
1725 /// Authorization gate consulted by `handle_invite_set` before each
1726 /// SpaceInvite create or destroy.
1727 ///
1728 /// Per draft-atwood-jmap-chat-00 §SpaceInvite/set: create "Requires
1729 /// `"manage_members"` permission"; destroy "Requires
1730 /// `"manage_members"` permission or ownership of the invite."
1731 ///
1732 /// # When the handler calls this
1733 ///
1734 /// Once per entry, AFTER wire-format validation and BEFORE
1735 /// `create_object` / `destroy_object`. `space_id` is the create body's
1736 /// `spaceId`, or the stored invite's `spaceId` for destroy.
1737 /// `created_by` is `None` on create and the stored invite's
1738 /// `createdBy` on destroy. A destroy whose invite does not resolve
1739 /// skips the gate so the backend surfaces `notFound`. The return
1740 /// mapping is the same as [`Self::may_set_custom_emoji`].
1741 ///
1742 /// # Default implementation
1743 ///
1744 /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1745 /// parallel hooks above. Production backends SHOULD override this
1746 /// method and deny with
1747 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1748 fn may_set_space_invite(
1749 &self,
1750 _caller: &Self::CallerCtx,
1751 _account_id: &jmap_types::Id,
1752 _space_id: &jmap_types::Id,
1753 _created_by: Option<&jmap_types::Id>,
1754 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1755 async { Ok(Ok(())) }
1756 }
1757
1758 /// Visibility gate consulted by `handle_invite_get` and
1759 /// `handle_invite_changes` for each stored SpaceInvite.
1760 ///
1761 /// Per draft-atwood-jmap-chat-00 §SpaceInvite/get: "Only members of
1762 /// the Space may retrieve its invites. Members with
1763 /// `"manage_members"` permission see all invites; other members see
1764 /// only invites they created." §SpaceInvite/changes: "The same
1765 /// visibility rules as `SpaceInvite/get` apply".
1766 ///
1767 /// # When the handler calls this
1768 ///
1769 /// Once per invite returned by `get_objects`. `Ok(false)` hides the
1770 /// invite: `/get` reports a requested id as `notFound`, and
1771 /// `/changes` omits it from `created` and `updated`.
1772 ///
1773 /// # Default implementation
1774 ///
1775 /// Returns `Ok(true)`, so every invite is visible, matching the
1776 /// parallel hooks above. Production backends SHOULD override this
1777 /// method; invite codes are join credentials.
1778 fn may_get_space_invite(
1779 &self,
1780 _caller: &Self::CallerCtx,
1781 _account_id: &jmap_types::Id,
1782 _invite: &jmap_chat_types::SpaceInvite,
1783 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1784 async { Ok(true) }
1785 }
1786
1787 /// Visibility gate consulted by `handle_ban_get` for each stored
1788 /// SpaceBan.
1789 ///
1790 /// Per draft-atwood-jmap-chat-00 §SpaceBan/get: "Members with
1791 /// `"ban"` permission in the Space see all SpaceBan records for that
1792 /// Space. A banned user fetching their own account sees only SpaceBan
1793 /// records where `userId` is the accountId."
1794 ///
1795 /// # When the handler calls this
1796 ///
1797 /// Once per ban returned by `get_objects`. `Ok(false)` hides the ban,
1798 /// and a requested id is reported as `notFound`. `SpaceBan/changes`
1799 /// does not consult this hook, because the spec defines it as plain
1800 /// "Standard JMAP `/changes`".
1801 ///
1802 /// # Default implementation
1803 ///
1804 /// Returns `Ok(true)`, so every ban is visible, matching the parallel
1805 /// hooks above. Production backends SHOULD override this method.
1806 fn may_get_space_ban(
1807 &self,
1808 _caller: &Self::CallerCtx,
1809 _account_id: &jmap_types::Id,
1810 _ban: &jmap_chat_types::SpaceBan,
1811 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1812 async { Ok(true) }
1813 }
1814}
1815
1816/// Chat and Message access gates: send, view, pins, broadcast mentions, slow mode, blocked contacts.
1817///
1818/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
1819pub trait ChatAccessPolicy: JmapBackend {
1820 /// Whether the [`ChatContact`] `contact_id` has `blocked: true` on the
1821 /// contact list of `account_id`.
1822 ///
1823 /// Delivery paths call this per recipient: `account_id` is the
1824 /// recipient (the owner of the contact list) and `contact_id` is the
1825 /// sender's or referenced ChatContact id *in that account*.
1826 /// draft-atwood-jmap-chat-00 §Blocked Contacts: "Typing and presence
1827 /// push events whose sending or referenced ChatContact has
1828 /// `blocked: true` on the receiving owner's contact list are
1829 /// similarly dropped server-side before delivery to any of the
1830 /// owner's clients". §ChatContact `id` "identifies the ChatContact only
1831 /// on this server", so `contact_id` is always resolved within
1832 /// `account_id`'s list; it is never looked up in the sender's account.
1833 ///
1834 /// [`ChatContact`]: jmap_chat_types::ChatContact
1835 ///
1836 /// # Callers
1837 ///
1838 /// [`crate::should_push`] calls it with the push owner's account and
1839 /// `Message.senderId`. [`crate::should_deliver_typing`] calls it with
1840 /// the typing event's recipient and `senderId`.
1841 /// [`crate::project_presence`] calls it with the presence event's
1842 /// recipient and `contactId`.
1843 /// [`crate::handle_chat_typing`] does not call it: the request carries
1844 /// the sender's `accountId`, and the recipient's account is known only
1845 /// to the transport that fans the event out, which calls
1846 /// [`crate::should_deliver_typing`] per recipient.
1847 ///
1848 /// # Default implementation
1849 ///
1850 /// Fetches `contact_id` from `account_id` with
1851 /// [`JmapReads::get_objects`](jmap_server::JmapReads::get_objects) and returns its `blocked` field, or
1852 /// `Ok(false)` when `account_id` holds no such ChatContact. The
1853 /// callers pass the recipient's `caller`, the same one they use to
1854 /// read the recipient's Chat. Override this only when ChatContacts are
1855 /// not stored behind `get_objects` or a cheaper lookup exists.
1856 fn is_contact_blocked(
1857 &self,
1858 caller: &Self::CallerCtx,
1859 account_id: &jmap_types::Id,
1860 contact_id: &jmap_types::Id,
1861 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1862 async move {
1863 let (contacts, _) = self
1864 .get_objects::<jmap_chat_types::ChatContact>(
1865 caller,
1866 account_id,
1867 Some(std::slice::from_ref(contact_id)),
1868 None,
1869 )
1870 .await?;
1871 Ok(contacts.iter().any(|c| c.id == *contact_id && c.blocked))
1872 }
1873 }
1874
1875 /// Authorization gate consulted by `handle_message_set` before a
1876 /// create or update with a non-empty `broadcastMentions` array is
1877 /// applied.
1878 ///
1879 /// Per draft-atwood-jmap-chat-00 §BroadcastMention (jmap-chat-spec
1880 /// 77c3474 L462): sending a `Message` with a non-empty
1881 /// `broadcastMentions` array requires the `"mention_broadcast"` Space
1882 /// permission, and "Servers SHOULD reject `Message/set` create or update
1883 /// requests that would write a broadcast mention from a sender lacking
1884 /// this permission with `forbidden`." This crate performs the
1885 /// recommended rejection by choice.
1886 ///
1887 /// For group/direct chats NOT part of any Space (`spaceId` is
1888 /// `None`), broadcast mentions are unrestricted per spec; the
1889 /// handler skips calling this method entirely in that case.
1890 ///
1891 /// # `space_id` semantics
1892 ///
1893 /// `space_id` is the Space that contains the target Chat (channel).
1894 /// The handler resolves it by pre-fetching the Chat and reading
1895 /// its `space_id` field. This method is only called when
1896 /// `space_id` is `Some` — the handler skips the call for
1897 /// group/direct chats with no Space.
1898 ///
1899 /// # `chat_id` semantics
1900 ///
1901 /// `chat_id` is the target channel Chat, whose `permissionOverrides`
1902 /// apply: per draft-atwood-jmap-chat-00 §Space Permission Resolution,
1903 /// "When determining whether a member may perform an action in a
1904 /// channel Chat, servers MUST evaluate permissions in this order",
1905 /// so an override may deny or allow `mention_broadcast` in one
1906 /// channel only.
1907 ///
1908 /// # When the handler calls this
1909 ///
1910 /// `handle_message_set` invokes `may_broadcast_mention` once per
1911 /// create entry or edit whose post-patch `broadcastMentions` is
1912 /// non-empty AND whose target Chat has a `spaceId`; rich-body
1913 /// `"broadcast"` spans are display-only and never trigger it
1914 /// (draft-atwood-jmap-chat-00 §Rich Body Format). The call
1915 /// fires AFTER structural validation (`validate_broadcast_mentions`)
1916 /// has succeeded and BEFORE `create_object` / `update_object`, so
1917 /// malformed payloads do not consume an authorization decision and
1918 /// an unauthorized message never touches storage.
1919 ///
1920 /// # Default implementation
1921 ///
1922 /// Returns `Ok(Ok(()))` — every op is permitted. This matches the
1923 /// workspace's "kit defines the hook; consumer enforces the policy"
1924 /// posture (see the parallel design of [`SpacePolicy::may_set_custom_emoji`]).
1925 /// Production backends SHOULD override this method to check the
1926 /// caller's `mention_broadcast` permission in the target channel,
1927 /// resolved per §Space Permission Resolution (see
1928 /// [`resolve_channel_permissions`](crate::permissions::resolve_channel_permissions)).
1929 ///
1930 /// # SetError shape recommendation
1931 ///
1932 /// Production backends SHOULD return
1933 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1934 /// .with_description("sender lacks mention_broadcast permission in this channel")))`.
1935 fn may_broadcast_mention(
1936 &self,
1937 _caller: &Self::CallerCtx,
1938 _account_id: &jmap_types::Id,
1939 _space_id: &jmap_types::Id,
1940 _chat_id: &jmap_types::Id,
1941 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1942 async { Ok(Ok(())) }
1943 }
1944
1945 /// Authorization gate consulted by `handle_chat_set` before an update
1946 /// whose patch touches `pinnedMessageIds` is applied.
1947 ///
1948 /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "For group
1949 /// chats, only admins may modify this list. For direct chats, the
1950 /// owner may modify it freely. For channel chats, only members with
1951 /// the `"pin"` Space permission may modify this list." For a channel
1952 /// the `"pin"` permission is resolved per §Space Permission
1953 /// Resolution, so the channel's `permissionOverrides` apply.
1954 ///
1955 /// # When the handler calls this
1956 ///
1957 /// Once per update entry whose patch sets `pinnedMessageIds` (or a
1958 /// pointer path beneath it), AFTER wire-format validation and BEFORE
1959 /// `update_object`. A `chat_id` that does not resolve SHOULD yield
1960 /// `Ok(Ok(()))` so `update_object` surfaces `notFound`. The return
1961 /// mapping is the same as [`SpacePolicy::may_set_custom_emoji`].
1962 ///
1963 /// # Default implementation
1964 ///
1965 /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1966 /// parallel hooks above. Production backends SHOULD override this
1967 /// method and deny with
1968 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1969 fn may_set_pinned_messages(
1970 &self,
1971 _caller: &Self::CallerCtx,
1972 _account_id: &jmap_types::Id,
1973 _chat_id: &jmap_types::Id,
1974 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1975 async { Ok(Ok(())) }
1976 }
1977
1978 /// Authorization gate consulted by `handle_message_set` before each
1979 /// Message create.
1980 ///
1981 /// Per draft-atwood-jmap-chat-00 §Message/set (jmap-chat-spec 77c3474
1982 /// L1218): "The server SHOULD verify the sender is a current member of
1983 /// the target Chat. For group chats, this means a ChatMember record
1984 /// exists; for channel chats, the sender must be a member of the
1985 /// containing Space. Non-members SHOULD receive a SetError of type
1986 /// `forbidden`." and (L1220) "For channel Chats, the server SHOULD
1987 /// verify the sender holds the `"send"` permission (resolved per
1988 /// {{space-permissions}}) before accepting the message; if absent, the
1989 /// server SHOULD return a SetError of type `forbidden`." The handler
1990 /// performs these recommended checks by choice.
1991 /// [`resolve_channel_permissions`](crate::permissions::resolve_channel_permissions)
1992 /// implements that resolution.
1993 ///
1994 /// # When the handler calls this
1995 ///
1996 /// Once per create entry, AFTER wire-format validation and the
1997 /// closed-Chat and closed-Space checks, and BEFORE `create_object`.
1998 /// A `chat_id` that does not resolve SHOULD yield `Ok(Ok(()))` so
1999 /// `create_object` surfaces the normal error. The return mapping is
2000 /// the same as [`SpacePolicy::may_set_custom_emoji`].
2001 ///
2002 /// # Default implementation
2003 ///
2004 /// Returns `Ok(Ok(()))` — every create is permitted, matching the
2005 /// parallel hooks above. Production backends SHOULD override this
2006 /// method and deny with
2007 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
2008 fn may_send_message(
2009 &self,
2010 _caller: &Self::CallerCtx,
2011 _account_id: &jmap_types::Id,
2012 _chat_id: &jmap_types::Id,
2013 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2014 async { Ok(Ok(())) }
2015 }
2016
2017 /// Visibility gate consulted by `handle_message_get` and
2018 /// `handle_message_query`.
2019 ///
2020 /// Per draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474
2021 /// L1301): "For channel Chats, the server SHOULD verify the caller holds
2022 /// the `"view"` permission before returning messages in `Message/get` or
2023 /// `Message/query` responses; messages in channels the caller cannot
2024 /// view SHOULD be omitted." The handlers perform this recommended check
2025 /// by choice. The permission is resolved per §Space Permission
2026 /// Resolution, as in [`Self::may_send_message`].
2027 ///
2028 /// # When the handler calls this
2029 ///
2030 /// `Message/get` calls it once per distinct `chatId` among the
2031 /// returned messages; `Ok(false)` hides those messages, and a
2032 /// requested id is reported as `notFound`. `Message/query` calls it
2033 /// for the filter's top-level `chatId` and returns no ids when it
2034 /// yields `Ok(false)`. A query without `chatId` spans Chats, so the
2035 /// backend's `query_objects` MUST itself omit messages the caller
2036 /// cannot view; the handler cannot filter a page it did not cut.
2037 /// `Message/changes` does not consult this hook, because the spec
2038 /// defines it as plain "Standard JMAP `/changes`".
2039 ///
2040 /// # Default implementation
2041 ///
2042 /// Returns `Ok(true)`, so every Chat is viewable, matching the
2043 /// parallel hooks above. Production backends SHOULD override this
2044 /// method.
2045 fn may_view_chat(
2046 &self,
2047 _caller: &Self::CallerCtx,
2048 _account_id: &jmap_types::Id,
2049 _chat_id: &jmap_types::Id,
2050 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
2051 async { Ok(true) }
2052 }
2053
2054 /// Referential check consulted by `handle_chat_set` before an update
2055 /// that adds ids to `pinnedMessageIds` is applied.
2056 ///
2057 /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "Each id
2058 /// MUST be the id of a Message in this Chat; the server MUST reject a
2059 /// `Chat/set` update that would add any other id with
2060 /// `invalidProperties`."
2061 ///
2062 /// # When the handler calls this
2063 ///
2064 /// After [`Self::may_set_pinned_messages`] permits the update and
2065 /// BEFORE `update_object`, with `added` holding only the ids in the
2066 /// new list that are not already in the stored list. Ids already
2067 /// pinned are not re-checked: the requirement covers adding, and a
2068 /// stale id left behind by a backend that missed a hard delete must
2069 /// not make the list impossible to edit. Not called when `added` is
2070 /// empty or `chat_id` does not resolve.
2071 ///
2072 /// Return `Ok(Err(SetError))` with type `invalidProperties` and
2073 /// properties `["pinnedMessageIds"]` when any id in `added` is not a
2074 /// Message whose `chatId` is `chat_id`.
2075 ///
2076 /// # Default implementation
2077 ///
2078 /// Fetches `added` with [`JmapReads::get_objects`](jmap_server::JmapReads::get_objects) and accepts only
2079 /// when every id comes back as a Message whose `chatId` is `chat_id`.
2080 /// Override this only when Messages are not stored behind
2081 /// `get_objects` or a cheaper lookup exists.
2082 fn validate_pinned_message_ids(
2083 &self,
2084 caller: &Self::CallerCtx,
2085 account_id: &jmap_types::Id,
2086 chat_id: &jmap_types::Id,
2087 added: &[jmap_types::Id],
2088 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2089 async move {
2090 let (messages, _) = self
2091 .get_objects::<jmap_chat_types::Message>(caller, account_id, Some(added), None)
2092 .await?;
2093 let in_chat = |id: &jmap_types::Id| {
2094 messages
2095 .iter()
2096 .any(|m| m.id == *id && m.chat_id == *chat_id)
2097 };
2098 if added.iter().all(in_chat) {
2099 return Ok(Ok(()));
2100 }
2101 Ok(Err(SetError::new(SetErrorType::InvalidProperties)
2102 .with_properties(["pinnedMessageIds"])
2103 .with_description(
2104 "pinned id is not a Message in this Chat",
2105 )))
2106 }
2107 }
2108
2109 /// Throttle gate consulted before a `Message/set` create lands on
2110 /// the rate-limited path.
2111 ///
2112 /// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec
2113 /// commit `de60acb` (2026-05-11, "soften slow-mode exemption to
2114 /// SHOULD with rationale"): a `Chat` with `slowModeSeconds > 0`
2115 /// throttles the rate at which a member may post messages. The
2116 /// spec SHOULD-exempts members holding the `manage_channels`
2117 /// permission, and servers MAY define additional exempt
2118 /// principals. The kit does not opine on the exemption set — the
2119 /// backend implements the policy.
2120 ///
2121 /// When the caller is throttled, the backend returns
2122 /// `Err(`[`SlowModeError`]`)` with `retry_after` set to a UTCDate
2123 /// the rate-limited sender may use to schedule a retry. The
2124 /// `Message/set` create handler maps the error onto a
2125 /// `rateLimit` SetError (RFC 8620 §5.3 `SetError.type`) whose
2126 /// `serverRetryAfter` extra field carries the UTCDate verbatim.
2127 ///
2128 /// # When the handler calls this
2129 ///
2130 /// `handle_message_set` invokes `slow_mode_check` once per create
2131 /// entry, after wire-format validation has succeeded and before
2132 /// `create_object`. A throttle rejection short-circuits to
2133 /// `notCreated[create_id] = { type: "rateLimit",
2134 /// serverRetryAfter: <UTCDate> }` and the create_object call is
2135 /// never made.
2136 ///
2137 /// # Default implementation
2138 ///
2139 /// The default returns `Ok(())` — no throttle. This is appropriate
2140 /// for backends that have not yet implemented rate-tracking and
2141 /// for single-tenant dev servers where no abuse path exists.
2142 /// Production backends SHOULD override this method with their own
2143 /// per-(account, chat, caller) rate tracker.
2144 ///
2145 /// # No state on the kit
2146 ///
2147 /// The kit deliberately does not provide a reference rate-tracker
2148 /// — that is deployment territory. The reference `MemoryBackend`
2149 /// keeps the default no-op behaviour for the same reason.
2150 fn slow_mode_check(
2151 &self,
2152 _caller: &Self::CallerCtx,
2153 _account_id: &jmap_types::Id,
2154 _chat_id: &jmap_types::Id,
2155 ) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
2156 async { Ok(()) }
2157 }
2158}
2159
2160/// Per-Chat restriction gates on Message create and update and on Chat update, which a backend bound to an external room (such as a MIMI room) overrides.
2161///
2162/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2163pub trait ChatRestrictions: JmapBackend {
2164 /// Per-Chat restriction gate consulted by `handle_message_set` before
2165 /// each Message create, with the stored target Chat.
2166 ///
2167 /// For extensions that bind a Chat to something outside JMAP Chat and
2168 /// so restrict it, e.g. draft-atwood-jmap-chat-mimi-00 §message/mls:
2169 /// "The server MUST reject a `Message/set` create in a Chat with a
2170 /// `roomId` with a `forbidden` SetError." Extension properties of the
2171 /// Chat are in [`Chat::extra`](jmap_chat_types::Chat::extra).
2172 /// [`ChatAccessPolicy::may_send_message`] is the sender's membership and
2173 /// permission gate; this one sees the Chat itself.
2174 ///
2175 /// # When the handler calls this
2176 ///
2177 /// Once per create entry whose `chatId` resolves, AFTER wire-format
2178 /// validation and BEFORE the closed-Chat check and
2179 /// [`ChatAccessPolicy::may_send_message`]. The return mapping is the same as
2180 /// [`SpacePolicy::may_set_custom_emoji`].
2181 ///
2182 /// # Default implementation
2183 ///
2184 /// Returns `Ok(Ok(()))`: every create is permitted (fail-open, like
2185 /// the hooks above).
2186 fn may_create_message(
2187 &self,
2188 _caller: &Self::CallerCtx,
2189 _account_id: &jmap_types::Id,
2190 _chat: &jmap_chat_types::Chat,
2191 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2192 async { Ok(Ok(())) }
2193 }
2194
2195 /// Per-Chat restriction gate consulted by `handle_message_set` before
2196 /// each Message update, with the stored Message, its stored Chat and
2197 /// the client's patch keys.
2198 ///
2199 /// For extension-bound Chats, e.g. draft-atwood-jmap-chat-mimi-00
2200 /// §message/mls: "The server MUST reject a `Message/set` update that
2201 /// changes `body`, `bodyType`, or `reactions` of a Message in a Chat
2202 /// with a `roomId` with an `invalidProperties` SetError naming the
2203 /// changed properties."
2204 ///
2205 /// # When the handler calls this
2206 ///
2207 /// Once per update entry whose Message and Chat resolve, AFTER the
2208 /// patch keys and `bodyType` are validated and BEFORE the sender,
2209 /// edit-limit and reaction checks and `update_object`, even for an
2210 /// empty patch. `patch_keys` are the keys as the client sent them,
2211 /// less server-set and immutable keys that repeat the stored value
2212 /// (RFC 8620 §5.3), so a reaction change appears as
2213 /// `reactions/<senderReactionId>`. The return mapping is
2214 /// the same as [`SpacePolicy::may_set_custom_emoji`].
2215 ///
2216 /// # Default implementation
2217 ///
2218 /// Returns `Ok(Ok(()))`: every update is permitted (fail-open, like
2219 /// the hooks above).
2220 fn may_update_message(
2221 &self,
2222 _caller: &Self::CallerCtx,
2223 _account_id: &jmap_types::Id,
2224 _chat: &jmap_chat_types::Chat,
2225 _message: &jmap_chat_types::Message,
2226 _patch_keys: &[&str],
2227 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2228 async { Ok(Ok(())) }
2229 }
2230
2231 /// Per-Chat restriction gate consulted by `handle_chat_set` before
2232 /// each Chat update, with the stored Chat and the client's patch keys.
2233 ///
2234 /// For extension-bound Chats, e.g. draft-atwood-jmap-chat-mimi-00
2235 /// §Chat.roomId: "The server MUST reject, with `forbidden`, a
2236 /// `Chat/set` update on such a Chat that sets `name`, `description`,
2237 /// or `avatarBlobId` or that uses the `addMembers`, `removeMembers`,
2238 /// or `updateMemberRoles` patch key".
2239 ///
2240 /// # When the handler calls this
2241 ///
2242 /// Once per update entry whose Chat resolves, AFTER the patch keys
2243 /// are validated and BEFORE the closed-group, admin, member-patch and
2244 /// `pinnedMessageIds` checks and `update_object`, even for an empty
2245 /// patch. `patch_keys` are the keys as the client sent them, less
2246 /// server-set and immutable keys that repeat the stored value (RFC
2247 /// 8620 §5.3). The return mapping is
2248 /// the same as [`SpacePolicy::may_set_custom_emoji`].
2249 ///
2250 /// # Default implementation
2251 ///
2252 /// Returns `Ok(Ok(()))`: every update is permitted (fail-open, like
2253 /// the hooks above).
2254 fn may_update_chat(
2255 &self,
2256 _caller: &Self::CallerCtx,
2257 _account_id: &jmap_types::Id,
2258 _chat: &jmap_chat_types::Chat,
2259 _patch_keys: &[&str],
2260 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2261 async { Ok(Ok(())) }
2262 }
2263}
2264
2265/// Group Chat moderation: ChatBan create, update and destroy, and the `kickMembers` patch key.
2266///
2267/// Its defaults write through [`ChatStore`].
2268///
2269/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2270pub trait ChatModeration: ChatStore {
2271 /// Store a ChatBan and remove the banned user from the Chat's
2272 /// `members` as one unit.
2273 ///
2274 /// [`crate::handle_chat_ban_set`] calls this for every `ChatBan/set`
2275 /// create that passes its checks: the Chat named by `chatId` is a
2276 /// group Chat, the caller holds its `"admin"` role and `userId` is not
2277 /// the accountId. draft-atwood-jmap-chat-00 §ChatBan/set: "Creating a
2278 /// ban removes the user from `members` if present, as `removeMembers`
2279 /// would".
2280 ///
2281 /// `build` and every contract of [`ChatStore::create_object`]
2282 /// (authorisation, id assignment, errors, state and change log) apply
2283 /// unchanged. On `Ok` the ban is stored and the user is no longer in
2284 /// the Chat's `members`. On `Err` neither happens. A backend that binds
2285 /// Chats to another group model (for example a MIMI room, where
2286 /// draft-atwood-jmap-chat-mimi-00 §Moderation makes the ban one commit
2287 /// that gives the user the "banned" role and removes the user's
2288 /// clients) overrides this, and may reject the ban with a
2289 /// [`BackendSetError::SetError`] such as `forbidden`.
2290 ///
2291 /// # Default implementation
2292 ///
2293 /// Calls [`ChatStore::create_object`] for `ChatBan`. If the user is in the
2294 /// Chat's `members`, it then calls [`ChatStore::update_object`] on the Chat
2295 /// with the user removed, and on success [`ChatEvents::on_outbound_event`]
2296 /// with the [`GroupUpdateAction::RemoveMembers`](crate::GroupUpdateAction::RemoveMembers)
2297 /// event that a `removeMembers` update reports. If that update fails,
2298 /// the ban is destroyed again and the update's error is returned.
2299 /// The steps are not one transaction; a backend that needs them in one
2300 /// overrides this.
2301 fn create_chat_ban<F>(
2302 &self,
2303 caller: &Self::CallerCtx,
2304 account_id: &jmap_types::Id,
2305 create_id: &str,
2306 build: F,
2307 ) -> impl std::future::Future<
2308 Output = Result<(jmap_types::Id, jmap_chat_types::ChatBan), BackendSetError<Self::Error>>,
2309 > + Send
2310 where
2311 F: FnOnce(&jmap_types::Id) -> jmap_chat_types::ChatBan + Send,
2312 {
2313 async move {
2314 let (id, ban) = self
2315 .create_object::<jmap_chat_types::ChatBan, _>(caller, account_id, create_id, build)
2316 .await?;
2317 let chat = match self
2318 .get_objects::<jmap_chat_types::Chat>(
2319 caller,
2320 account_id,
2321 Some(std::slice::from_ref(&ban.chat_id)),
2322 None,
2323 )
2324 .await
2325 {
2326 Ok((chats, _)) => chats.into_iter().next(),
2327 Err(e) => {
2328 // Best effort: the ban must not outlive a failed removal.
2329 let _ = self
2330 .destroy_object::<jmap_chat_types::ChatBan>(caller, account_id, &id)
2331 .await;
2332 return Err(BackendSetError::Other(e));
2333 }
2334 };
2335 let Some(chat) = chat else {
2336 return Ok((id, ban));
2337 };
2338 let before = chat.members.unwrap_or_default();
2339 if before.iter().all(|m| m.id != ban.user_id) {
2340 return Ok((id, ban));
2341 }
2342 let after: Vec<_> = before.into_iter().filter(|m| m.id != ban.user_id).collect();
2343 let mut map = serde_json::Map::new();
2344 map.insert(
2345 "members".to_owned(),
2346 serde_json::to_value(&after).expect("ChatMember serializes"),
2347 );
2348 if let Err(e) = self
2349 .update_object::<jmap_chat_types::Chat>(
2350 caller,
2351 account_id,
2352 &chat.id,
2353 jmap_types::PatchObject::from_map(map),
2354 )
2355 .await
2356 {
2357 // Best effort: the ban must not outlive a failed removal.
2358 let _ = self
2359 .destroy_object::<jmap_chat_types::ChatBan>(caller, account_id, &id)
2360 .await;
2361 return Err(e);
2362 }
2363 let mut recipients: Vec<jmap_types::Id> = after
2364 .iter()
2365 .filter(|m| m.id != *account_id)
2366 .map(|m| m.id.clone())
2367 .collect();
2368 recipients.push(ban.user_id.clone());
2369 let event = crate::OutboundEvent::GroupUpdate {
2370 chat_id: chat.id.clone(),
2371 action: crate::GroupUpdateAction::RemoveMembers {
2372 removed_ids: vec![ban.user_id.clone()],
2373 },
2374 recipients,
2375 };
2376 self.on_outbound_event(caller, account_id, &event).await;
2377 Ok((id, ban))
2378 }
2379 }
2380
2381 /// Apply a `ChatBan/set` update to the stored ban `id`.
2382 ///
2383 /// [`crate::handle_chat_ban_set`] calls this for every update that
2384 /// passes its checks: the caller holds the `"admin"` role in the ban's
2385 /// Chat, and `patch` names only `reason` and `expiresAt`
2386 /// (draft-atwood-jmap-chat-00 §ChatBan/set: "`update` supports:
2387 /// `reason`, `expiresAt`"). Every contract of [`ChatStore::update_object`]
2388 /// applies unchanged. A backend that mirrors bans into another group
2389 /// model (for example a MIMI room) overrides this.
2390 ///
2391 /// # Default implementation
2392 ///
2393 /// Calls [`ChatStore::update_object`] for `ChatBan`.
2394 fn update_chat_ban(
2395 &self,
2396 caller: &Self::CallerCtx,
2397 account_id: &jmap_types::Id,
2398 id: &jmap_types::Id,
2399 patch: jmap_types::PatchObject,
2400 ) -> impl std::future::Future<
2401 Output = Result<Option<jmap_chat_types::ChatBan>, BackendSetError<Self::Error>>,
2402 > + Send {
2403 self.update_object::<jmap_chat_types::ChatBan>(caller, account_id, id, patch)
2404 }
2405
2406 /// Lift the ChatBan `id`.
2407 ///
2408 /// [`crate::handle_chat_ban_set`] calls this for every destroy that
2409 /// passes its checks (the caller holds the `"admin"` role in the ban's
2410 /// Chat), and [`crate::sweep_expired`] for every ban whose `expiresAt`
2411 /// has passed. draft-atwood-jmap-chat-00 §ChatBan/set: "`destroy`
2412 /// lifts the ban ... Lifting a ban does not add the user back to the
2413 /// Chat." Every contract of [`ChatStore::destroy_object`] applies unchanged.
2414 /// A backend that binds Chats to a MIMI room overrides this to give
2415 /// the user the member role again without adding any client
2416 /// (draft-atwood-jmap-chat-mimi-00 §Moderation).
2417 ///
2418 /// # Default implementation
2419 ///
2420 /// Calls [`ChatStore::destroy_object`] for `ChatBan`; `members` is not
2421 /// touched.
2422 fn destroy_chat_ban(
2423 &self,
2424 caller: &Self::CallerCtx,
2425 account_id: &jmap_types::Id,
2426 id: &jmap_types::Id,
2427 ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send {
2428 self.destroy_object::<jmap_chat_types::ChatBan>(caller, account_id, id)
2429 }
2430
2431 /// Apply the `kickMembers` key of a `Chat/set` update.
2432 ///
2433 /// draft-atwood-jmap-chat-mimi-00 §Moderation: "The `kickMembers`
2434 /// patch key of `Chat/set` (String\[], ChatContact ids), which this
2435 /// document adds for Chats bound to a room, removes the listed users'
2436 /// clients from the group but keeps them in the participant list, so
2437 /// that they can rejoin (`canKick`)." A backend that binds Chats to
2438 /// MIMI rooms overrides this: it checks that `chat` is bound to a room
2439 /// and that the owner may kick, then commits the client removals.
2440 /// `members` is not changed; the Chat record stays as it is.
2441 ///
2442 /// # When the handler calls this
2443 ///
2444 /// Once per `Chat/set` update whose patch carries a non-empty
2445 /// `kickMembers`, after the handler has checked it is an array of
2446 /// valid ids (else `invalidProperties`), after
2447 /// [`ChatRestrictions::may_update_chat`] and the other patch checks, and before
2448 /// [`ChatStore::update_object`] writes the rest of the patch (if any).
2449 /// `chat` is the stored Chat and `user_ids` the listed ChatContact ids
2450 /// with `#creationId` references resolved. `Ok(Err(set_error))`
2451 /// rejects the update with that SetError and nothing is written; `Err`
2452 /// is `serverFail`.
2453 ///
2454 /// # Default implementation
2455 ///
2456 /// Rejects every kick with `invalidProperties` naming `kickMembers`.
2457 /// A backend with no room model has no Chat that the key applies to,
2458 /// so for it `kickMembers` is a key outside draft-atwood-jmap-chat-00
2459 /// §Chat/set "Updating a Chat", which the handler rejects the same
2460 /// way. Answering success instead would claim clients were removed
2461 /// when none were.
2462 fn kick_chat_members(
2463 &self,
2464 _caller: &Self::CallerCtx,
2465 _account_id: &jmap_types::Id,
2466 _chat: &jmap_chat_types::Chat,
2467 _user_ids: &[jmap_types::Id],
2468 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2469 async {
2470 Ok(Err(SetError::new(
2471 jmap_server::SetErrorType::InvalidProperties,
2472 )
2473 .with_properties(["kickMembers"])
2474 .with_description(
2475 "kickMembers applies only to a Chat bound to a MIMI room \
2476 (draft-atwood-jmap-chat-mimi-00); this backend binds none",
2477 )))
2478 }
2479 }
2480}
2481
2482/// Message expiry and read-and-burn.
2483///
2484/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2485pub trait ChatMessageLifecycle: JmapBackend {
2486 /// Apply a `readAt`-setting `patch` to the `burnOnRead` Message
2487 /// `message_id` and hard-delete it, as one atomic operation.
2488 ///
2489 /// Per draft-atwood-jmap-chat-00 §Message `burnOnRead` (jmap-chat-spec
2490 /// 77c3474 L750): "the receiving server SHOULD permanently hard-delete
2491 /// this message (row removal, not tombstone) immediately after setting
2492 /// `readAt`." This crate performs the recommended deletion by choice.
2493 ///
2494 /// # Authorisation contract
2495 ///
2496 /// Implementors MUST verify that `caller` may act as the owner of
2497 /// `account_id` before setting `readAt` and deleting the Message and MUST return [`BackendSetError::SetError`]
2498 /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`ChatStore::create_object`]
2499 /// for the workspace-canonical rationale; the same rule applies here.
2500 ///
2501 /// # Atomicity contract
2502 ///
2503 /// Validate `patch` against the stored Message exactly as
2504 /// [`ChatStore::update_object`] would, then remove the row, record the id
2505 /// in the `destroyed` set of the `Message` change log (bumping the
2506 /// `Message` state once), and unpin it from its Chat (§Chat
2507 /// `pinnedMessageIds`). All of it takes effect or none: on any error
2508 /// nothing is committed, so a retried `readAt` patch burns again.
2509 /// Composing this from `update_object` and [`Self::expire_message`]
2510 /// loses that guarantee: a failed delete leaves `readAt` stored, and
2511 /// a retry finds nothing left to set.
2512 ///
2513 /// # When the handler calls this
2514 ///
2515 /// `Message/set` update calls this instead of `update_object` when
2516 /// the patch sets a non-null `readAt` and the stored Message has
2517 /// `burnOnRead: true`. Return `SetError` `notFound` if the Message
2518 /// does not exist and the `update_object` `SetError` for an invalid
2519 /// patch. There is no default: a non-atomic default would reinstate
2520 /// the gap.
2521 fn read_and_burn_message(
2522 &self,
2523 caller: &Self::CallerCtx,
2524 account_id: &jmap_types::Id,
2525 message_id: &jmap_types::Id,
2526 patch: jmap_types::PatchObject,
2527 ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
2528
2529 /// Hard-delete a message ("expire" it) due to a per-message expiry
2530 /// event.
2531 ///
2532 /// Called by [`crate::expiry::sweep_expired`] for each message whose
2533 /// `senderExpiresAt`, Chat `messageExpirySeconds` or
2534 /// `expiresAfterReadSeconds` deadline has passed
2535 /// (draft-atwood-jmap-chat-00 §Message, §Chat). The kit does NOT run a
2536 /// scheduler; consumers call the sweep, or this method directly, when
2537 /// a timer fires.
2538 ///
2539 /// # Contract
2540 ///
2541 /// Per draft-atwood-jmap-chat-00 §Message (jmap-chat-spec 77c3474 L747,
2542 /// L753), the `senderExpiresAt` and `expiresAfterReadSeconds` deletions
2543 /// are SHOULD; this crate performs them by choice. The deletion removes
2544 /// the row (not a tombstone), and the message appears in the
2545 /// `destroyed` set of subsequent `Message/changes` results.
2546 /// Implementations therefore SHOULD:
2547 ///
2548 /// - Remove the underlying record so a subsequent `Message/get`
2549 /// does not find it.
2550 /// - Bump the per-account `Message` state token and record the id
2551 /// in the change log so `Message/changes` sees it as destroyed.
2552 /// - Remove the id from its Chat's `pinnedMessageIds` (§Chat
2553 /// `pinnedMessageIds`: "When a pinned Message is hard-deleted, the
2554 /// server MUST remove its id from this list."). The same applies to
2555 /// `destroy_object::<Message>`.
2556 ///
2557 /// # Idempotency
2558 ///
2559 /// If the message no longer exists — because a previous
2560 /// `expire_message` call or [`Self::read_and_burn_message`] has
2561 /// already deleted it — this method MUST
2562 /// return `Ok(())`, AND MUST NOT bump the per-account `Message`
2563 /// state token in that case. The no-op case must be
2564 /// observationally indistinguishable from "the scheduler never
2565 /// fired" for `Message/changes` subscribers; a state bump on the
2566 /// retry path would surface a spurious empty change set on every
2567 /// re-fire and induce a poll storm. Expiry events are
2568 /// inherently retry-friendly (a scheduler may re-fire if it
2569 /// crashed mid-batch). The
2570 /// return type is `Result<(), Self::Error>` (not
2571 /// `BackendSetError`) precisely to prevent a `NotFound`
2572 /// SetError construction on this path: expiry is an internal
2573 /// scheduler hook, not a `/set`-shaped call, and there is no
2574 /// JMAP wire surface for per-message expiry rejection.
2575 ///
2576 /// A `Message/set` read of a `burnOnRead` Message does not use this
2577 /// hook; it calls [`Self::read_and_burn_message`] so the `readAt`
2578 /// write and the hard-delete are atomic. The expiry sweep
2579 /// ([`crate::sweep_expired`]) does call it for a read
2580 /// `burnOnRead` Message that reached the store another way.
2581 ///
2582 /// # Default implementation
2583 ///
2584 /// The default returns `Ok(())` without doing anything, so expired
2585 /// messages stay in the store and remain visible to `Message/get`.
2586 /// It is correct only for a backend on which no message ever
2587 /// expires. Backends whose messages can carry `senderExpiresAt`,
2588 /// `expiresAfterReadSeconds` or a Chat `messageExpirySeconds` MUST
2589 /// override this method: for `senderExpiresAt`,
2590 /// draft-atwood-jmap-chat-00 §Message (jmap-chat-spec 77c3474 L747)
2591 /// says "servers SHOULD permanently delete this message — removing the
2592 /// row entirely, not leaving a tombstone — at or before this time",
2593 /// which this crate performs by choice.
2594 fn expire_message(
2595 &self,
2596 _caller: &Self::CallerCtx,
2597 _account_id: &jmap_types::Id,
2598 _message_id: &jmap_types::Id,
2599 ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
2600 async { Ok(()) }
2601 }
2602}
2603
2604/// Notifications from the handlers after a change: lifecycle callbacks and outbound events.
2605///
2606/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2607pub trait ChatEvents: JmapBackend {
2608 /// Called after a Chat is destroyed, so a companion extension can
2609 /// update the records that reference it. Examples:
2610 /// draft-atwood-jmap-chat-tasks-00 §Lifecycle ("the affected Tasks'
2611 /// `chatId` fields MUST be cleared") and draft-atwood-jmap-vtc-00
2612 /// §VTCCall ("the server MUST clear the corresponding field to
2613 /// `null` on all VTCCalls that reference it").
2614 ///
2615 /// # When the handler calls this
2616 ///
2617 /// Once for each Chat that a request destroys, after the destroy
2618 /// succeeds:
2619 ///
2620 /// - a `Chat/set` destroy;
2621 /// - each channel in a successful `Space/set` `removeChannels` patch;
2622 /// - each channel Chat whose `spaceId` is a Space that `Space/set`
2623 /// destroys (draft-atwood-jmap-chat-00 §Destroying a Space:
2624 /// "Cascades to all channel Chats"). These calls come before
2625 /// [`Self::on_space_destroyed`] for that Space.
2626 ///
2627 /// It is not called when the handler deletes a duplicate direct Chat
2628 /// it created in the same request, because no response ever named
2629 /// that id.
2630 ///
2631 /// The destroy is already committed, so the hook cannot fail the
2632 /// request. A backend handles its own errors here. A change it makes
2633 /// to another record type MUST advance that type's state, as in
2634 /// [`ChatStore::destroy_object`] ("Cascades").
2635 ///
2636 /// # Default implementation
2637 ///
2638 /// Does nothing. A backend that implements an extension which
2639 /// references Chats overrides it.
2640 fn on_chat_destroyed(
2641 &self,
2642 caller: &Self::CallerCtx,
2643 account_id: &jmap_types::Id,
2644 chat_id: &jmap_types::Id,
2645 ) -> impl std::future::Future<Output = ()> + Send {
2646 let _ = (caller, account_id, chat_id);
2647 async {}
2648 }
2649
2650 /// Called after a `Space/set` destroy succeeds, so a companion
2651 /// extension can update the records that reference the Space.
2652 /// Examples: draft-atwood-jmap-vtc-00 §VTCCall (clear `spaceId` on
2653 /// VTCCalls) and draft-atwood-jmap-chat-filenode-00 §Space Deletion
2654 /// ("the server SHOULD also destroy the associated file tree").
2655 ///
2656 /// The handler calls it once per destroyed Space, after
2657 /// [`Self::on_chat_destroyed`] for each of its channel Chats. The
2658 /// error and state rules of [`Self::on_chat_destroyed`] apply.
2659 ///
2660 /// # Default implementation
2661 ///
2662 /// Does nothing. A backend that implements an extension which
2663 /// references Spaces overrides it.
2664 fn on_space_destroyed(
2665 &self,
2666 caller: &Self::CallerCtx,
2667 account_id: &jmap_types::Id,
2668 space_id: &jmap_types::Id,
2669 ) -> impl std::future::Future<Output = ()> + Send {
2670 let _ = (caller, account_id, space_id);
2671 async {}
2672 }
2673
2674 /// Called after a `SpaceBan/set` create succeeds, with the stored
2675 /// ban, so a companion extension can apply the ban to its own
2676 /// records. Example: draft-atwood-jmap-vtc-00 §Access Control "Space
2677 /// ban enforcement" (the server "MUST set `leftAt` on that
2678 /// VTCParticipant record"; "The ban takes effect immediately on
2679 /// active calls").
2680 ///
2681 /// The handler calls it once per created ban. The error and state
2682 /// rules of [`Self::on_chat_destroyed`] apply.
2683 ///
2684 /// # Default implementation
2685 ///
2686 /// Does nothing. A backend that implements an extension which must
2687 /// enforce Space bans overrides it.
2688 fn on_space_ban_created(
2689 &self,
2690 caller: &Self::CallerCtx,
2691 account_id: &jmap_types::Id,
2692 ban: &jmap_chat_types::SpaceBan,
2693 ) -> impl std::future::Future<Output = ()> + Send {
2694 let _ = (caller, account_id, ban);
2695 async {}
2696 }
2697
2698 /// Called when the owner's action must be sent to other participants'
2699 /// servers: a new Message, a retraction (`deletedForAll`), an edit, a
2700 /// reaction added or removed, a group Chat change, a read receipt, a
2701 /// typing signal or a presence change. A backend that implements
2702 /// draft-atwood-jmap-chat-federation-00 turns the
2703 /// [`OutboundEvent`](crate::OutboundEvent) into `Peer/deliver`
2704 /// (`message`, `edit` or `reactionUpdate`), `Peer/retract`,
2705 /// `Peer/groupUpdate`, `Peer/receipt`, `Peer/typing` or `Peer/presence`
2706 /// calls, typically by enqueueing the durable ones (§Persistent Queue).
2707 /// [`OutboundEvent::Typing`](crate::OutboundEvent::Typing) also drives
2708 /// the local `typing` push to the Chat's other local participants.
2709 ///
2710 /// # When the handler calls this
2711 ///
2712 /// - `Message/set` create:
2713 /// [`OutboundEvent::NewMessage`](crate::OutboundEvent::NewMessage), after the Message is written
2714 /// (draft-atwood-jmap-chat-00 §Message/set: "enqueues the message for
2715 /// outbound delivery").
2716 /// - `Message/set` update setting `deletedForAll: true`:
2717 /// [`OutboundEvent::Retract`](crate::OutboundEvent::Retract), after the update is written
2718 /// (§Peer/retract "Sender Behavior": "the server MUST send
2719 /// `Peer/retract` to the server of every other participant in the
2720 /// Chat"). If the write fails, nothing is reported.
2721 /// - `Message/set` update editing `body`, `bodyType`, `mentions` or
2722 /// `broadcastMentions` and not deleting the Message:
2723 /// [`OutboundEvent::Edit`](crate::OutboundEvent::Edit), after the update is written.
2724 /// - `Chat/set` create of a group Chat, or update that changes a group
2725 /// Chat's members, roles, `name`, `description` or `avatarBlobId`:
2726 /// one [`OutboundEvent::GroupUpdate`](crate::OutboundEvent::GroupUpdate) per action, after the write
2727 /// (draft-atwood-jmap-chat-00 §Chat/set).
2728 ///
2729 /// - `Message/set` update patching `reactions/<senderReactionId>` and
2730 /// not deleting the Message:
2731 /// one [`OutboundEvent::ReactionUpdate`](crate::OutboundEvent::ReactionUpdate) per key that adds a
2732 /// reaction or removes a stored one, after the update is written
2733 /// (draft-atwood-jmap-chat-00 §Adding and Removing Reactions).
2734 /// - `Message/set` update setting a non-null `readAt` on a Message whose
2735 /// `senderId` is not the accountId:
2736 /// [`OutboundEvent::Receipt`](crate::OutboundEvent::Receipt), after
2737 /// the update (or the `burnOnRead` hard-delete) is written, unless
2738 /// the effective `receiptSharing` (`Chat.receiptSharing`, else
2739 /// `PresenceStatus.receiptSharing`) is `false`
2740 /// (draft-atwood-jmap-chat-federation-00 §Peer/receipt "Sender
2741 /// Behavior").
2742 /// - `Chat/typing`: [`OutboundEvent::Typing`](crate::OutboundEvent::Typing),
2743 /// after the request is validated (draft-atwood-jmap-chat-00
2744 /// §Chat/typing).
2745 /// - `PresenceStatus/set` update naming `presence`, `statusText` or
2746 /// `statusEmoji`: [`OutboundEvent::Presence`](crate::OutboundEvent::Presence),
2747 /// after the update is written
2748 /// (draft-atwood-jmap-chat-federation-00 §Peer/subscribePresence).
2749 ///
2750 /// The hook cannot fail the request. A backend handles its own errors
2751 /// here.
2752 ///
2753 /// # Default implementation
2754 ///
2755 /// Does nothing, for a server that does not federate.
2756 fn on_outbound_event(
2757 &self,
2758 caller: &Self::CallerCtx,
2759 account_id: &jmap_types::Id,
2760 event: &crate::OutboundEvent,
2761 ) -> impl std::future::Future<Output = ()> + Send {
2762 let _ = (caller, account_id, event);
2763 async {}
2764 }
2765}
2766
2767/// Deployment settings and identity: limits, edit history, unread counts, the owner's user id.
2768///
2769/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2770pub trait ChatSettings: JmapBackend {
2771 /// Implementation-defined per-Space content limits for this caller
2772 /// and account.
2773 ///
2774 /// Called by `handle_space_set` once per request, before
2775 /// dispatching to [`ChatSpaces::apply_space_patch`], to enforce
2776 /// per-aggregate caps on roles, members, channels, and categories
2777 /// per Space (draft-atwood-jmap-chat-00 §Space/set, spec commit
2778 /// `80d5e11`), and by `handle_message_set` once per request to
2779 /// validate `bodyType` against [`ChatLimits::supported_body_types`]
2780 /// and [`ChatLimits::server_reserved_body_types`].
2781 ///
2782 /// The default implementation returns [`ChatLimits::default`],
2783 /// which carries conservative reference-impl-grade values. The
2784 /// `caller` and `account_id` arguments are plumbed even though the
2785 /// default impl ignores them, so production backends can vary caps
2786 /// per-account (Free vs. Pro tier, multi-tenant SaaS, etc.)
2787 /// without a future API break. Implementations SHOULD return
2788 /// quickly (in-process struct construction, possibly off a cached
2789 /// per-account record) — this method is called on the hot
2790 /// `Space/set` path.
2791 ///
2792 /// # Why sync, not async
2793 ///
2794 /// `Space/set` calls this once per request before dispatching the
2795 /// mutation; an async `.await` here would add a roundtrip to the
2796 /// hot path of every Space mutation. Production backends with
2797 /// per-tenant caps SHOULD cache the resolved [`ChatLimits`] for
2798 /// each account on first use and serve from the cache thereafter.
2799 /// See the trait-level "Async vs sync method convention" section
2800 /// above for the workspace rationale.
2801 ///
2802 /// Workspace cross-extension pattern: see `AGENTS.md` "Backend
2803 /// caps and limits".
2804 fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
2805 ChatLimits::default()
2806 }
2807
2808 /// Whether the backend retains edit history for messages.
2809 ///
2810 /// Per draft-atwood-jmap-chat-00 commit `0783fc4` ("condition
2811 /// MessageRevision push on edit-history retention") +
2812 /// `§Message editHistory`: servers MAY limit retained
2813 /// MessageRevisions, and when the server does not retain edit
2814 /// history, the `editHistory` field MUST be omitted from
2815 /// `Message/get` and (in principle) `Message/changes` responses.
2816 /// `Message/changes` per RFC 8620 §5.2 returns only id arrays,
2817 /// not Message objects, so the spec's "omit from /changes" is
2818 /// a no-op at the wire level — the kit only enforces the
2819 /// `Message/get` projection.
2820 ///
2821 /// # When the handler calls this
2822 ///
2823 /// `handle_message_get` consults this predicate once per call.
2824 /// When `false`, every returned `Message` has its
2825 /// `edit_history` field set to `None` before serialization,
2826 /// which serde's `skip_serializing_if = "Option::is_none"`
2827 /// collapses to a wire-absent field per spec.
2828 ///
2829 /// # Why sync, not async
2830 ///
2831 /// This is a static deployment-policy flag, not a per-call
2832 /// decision — it does not consult per-account state, principal
2833 /// identity, or per-message bounds. Production backends that
2834 /// need to vary retention per-account would file a follow-up
2835 /// bead for a parallel `retains_edit_history_for_account` hook
2836 /// rather than reshaping this method.
2837 ///
2838 /// # Default implementation
2839 ///
2840 /// Returns `false` — no retention. This matches the workspace's
2841 /// "kit defines the hook; consumer enforces the policy" posture.
2842 /// Production backends that retain edit history MUST override
2843 /// this to `true`; the reference `MemoryBackend` exposes a
2844 /// test-only setter for tests that need the retain-on path.
2845 fn retains_edit_history(&self) -> bool {
2846 false
2847 }
2848
2849 /// Whether the backend keeps `Chat.unreadCount` itself instead of
2850 /// the kit recomputing it.
2851 ///
2852 /// draft-atwood-jmap-chat-00 §Chat `unreadCount` (jmap-chat-spec
2853 /// 33702a5 L629): "The value is advisory, for display such as
2854 /// badges. Servers SHOULD keep it accurate, but MAY update it some
2855 /// time after the change that affects it, MAY combine several such
2856 /// changes into one update, and MAY report a server-defined maximum
2857 /// in place of any larger count. Whenever the server changes the
2858 /// value, the Chat's state changes as for any other property
2859 /// ({{RFC8620}} Section 5.1)."
2860 ///
2861 /// # When the handlers call this
2862 ///
2863 /// When `false`, the kit keeps the count exact: `Chat/get` recomputes
2864 /// `unreadCount` from the account's Messages and ReadPositions, and
2865 /// every Message create or destroy, Message expiry, read-and-burn and
2866 /// ReadPosition update writes the recomputed count to each affected
2867 /// Chat through [`ChatStore::update_object`], which advances the
2868 /// `Chat` state.
2869 ///
2870 /// When `true`, the kit does neither: `Chat/get` returns the stored
2871 /// `unreadCount` and no Chat is rewritten. The backend sees every
2872 /// write that moves the count (the `create_object`, `update_object`
2873 /// and `destroy_object` calls for Message and ReadPosition,
2874 /// [`ChatMessageLifecycle::expire_message`] and
2875 /// [`ChatMessageLifecycle::read_and_burn_message`]), and may defer, coalesce or
2876 /// cap its update. It MUST still advance the `Chat` state, and log the
2877 /// Chat as updated for `Chat/changes`, whenever the stored value
2878 /// changes (RFC 8620 §5.1: "If the data changes, this string MUST
2879 /// change").
2880 ///
2881 /// # Default implementation
2882 ///
2883 /// Returns `false`, the exact upkeep the spec's SHOULD asks for. A
2884 /// backend for which the per-event rewrite costs too much (it scans
2885 /// every Message in the account) overrides this to `true`.
2886 fn maintains_unread_count(&self) -> bool {
2887 false
2888 }
2889
2890 /// The owner's identity for `account_id`: the value of the
2891 /// `ownerUserId` Session field (draft-atwood-jmap-chat-00 §Session
2892 /// Object Extensions).
2893 ///
2894 /// [`crate::contact::handle_contact_set`] rejects a `ChatContact/set`
2895 /// create whose `identity` equals this value, octet for octet, with
2896 /// an `invalidProperties` SetError naming `identity`
2897 /// (draft-atwood-jmap-chat-00 §ChatContact/set: "the owner has no
2898 /// ChatContact").
2899 ///
2900 /// # Default implementation
2901 ///
2902 /// Returns `Ok(None)`: the owner's identity is unknown and the check
2903 /// is skipped. Backends that serve `ownerUserId` MUST override this
2904 /// to return the same value. A backend used with federation (a
2905 /// `jmap_chat_federation_server::FederationBackend`) must return
2906 /// `Some` for every mailbox: "Servers implementing {{JMAP-CHAT-FED}}
2907 /// MUST include this field in the Session they serve an authenticated
2908 /// owner" (draft-atwood-jmap-chat-00 §Session Object Extensions,
2909 /// jmap-chat-spec b1cd625 L346), and the `Peer/*` handlers read it to
2910 /// recognize the owner's identity in a call.
2911 fn owner_user_id(
2912 &self,
2913 _caller: &Self::CallerCtx,
2914 _account_id: &jmap_types::Id,
2915 ) -> impl std::future::Future<Output = Result<Option<String>, Self::Error>> + Send {
2916 async { Ok(None) }
2917 }
2918
2919 /// The account-level `urn:ietf:params:jmap:search` capability object
2920 /// (crate-jmap docs/specs/jmap-search.md §Account-Level Capability
2921 /// Object) the consumer advertises for `account_id`, or `None` when it
2922 /// does not advertise the capability.
2923 ///
2924 /// With `None`, or without `"Message"` in its `dataTypes`, a
2925 /// `Message/query` or `Message/queryChanges` filter that sets `where`
2926 /// is `unsupportedFilter`, as it is when the request's `using` lacks
2927 /// `urn:ietf:params:jmap:search` (§Opting In a Data Type). With it, the
2928 /// handlers check `where` against it
2929 /// ([`jmap_search::check_where_filter`]), report `canCalculateChanges:
2930 /// false` from `Message/query` and answer `Message/queryChanges` with
2931 /// `cannotCalculateChanges` (§Query Changes). `query_objects` then
2932 /// evaluates `where` over the Messages the caller may fetch, each as
2933 /// the caller would receive it from `Message/get` (§Visibility,
2934 /// §Addressable Properties).
2935 ///
2936 /// # Default implementation
2937 ///
2938 /// Returns `Ok(None)`: no search.
2939 fn search_capability(
2940 &self,
2941 _caller: &Self::CallerCtx,
2942 _account_id: &jmap_types::Id,
2943 ) -> impl std::future::Future<
2944 Output = Result<Option<jmap_search::SearchCapability>, Self::Error>,
2945 > + Send {
2946 async { Ok(None) }
2947 }
2948}
2949
2950/// Lookups outside chat storage: attachment blobs and FileNode attachments.
2951///
2952/// Part of [`ChatBackend`] (docs/design/chat-backend-split.md).
2953pub trait ChatResolvers: JmapBackend {
2954 /// Blob lookup consulted by `handle_message_set` for each Attachment
2955 /// of a Message create.
2956 ///
2957 /// Per draft-atwood-jmap-chat-00 §Attachment at jmap-chat-spec 77c3474,
2958 /// `size` L374: "Servers SHOULD verify against actual content", and
2959 /// `sha256` L377: "Servers SHOULD verify". By choice, the handler
2960 /// compares the returned [`AttachmentBlob`]
2961 /// against the Attachment and rejects a mismatch with an
2962 /// `invalidProperties` SetError naming `attachments` (§Input
2963 /// Validation). The `sha256` comparison is constant-time
2964 /// (`subtle::ConstantTimeEq`), so implementations return the digest
2965 /// rather than comparing it themselves.
2966 ///
2967 /// # When the handler calls this
2968 ///
2969 /// Once per Attachment, AFTER the `maxAttachmentsPerMessage` and
2970 /// `maxAttachmentBytes` checks (§Denial of Service: "Enforce
2971 /// `maxBodyBytes` and `maxAttachmentBytes` at parse time, before any
2972 /// fetch or storage") and BEFORE `create_object`.
2973 ///
2974 /// # Return mapping
2975 ///
2976 /// - `Ok(Ok(Some(blob)))`: compare the Attachment against `blob`.
2977 /// - `Ok(Ok(None))`: the backend does not verify this blob; accept.
2978 /// - `Ok(Err(set_error))`: reject the create with `set_error`, e.g.
2979 /// `invalidProperties` naming `attachments` for an unknown `blobId`
2980 /// (RFC 8620 §5.3 defines `blobNotFound` only for upload paths).
2981 /// - `Err(e)`: `serverFail`.
2982 ///
2983 /// Required: the `size` check is a MUST, so a backend that cannot
2984 /// verify blobs says so explicitly by returning `Ok(Ok(None))`.
2985 ///
2986 /// # CustomEmoji images
2987 ///
2988 /// `handle_emoji_set` also calls this for the `blobId` of a create,
2989 /// and of an update that sets `blobId`, when
2990 /// [`ChatLimits::max_custom_emoji_bytes`] is a limit, to compare the
2991 /// blob's `size` with it (`overQuota` when larger). There `Ok(Ok(None))`
2992 /// skips the check, and `Ok(Err(_))` rejects the emoji with an
2993 /// `invalidProperties` SetError naming `blobId`.
2994 fn attachment_blob(
2995 &self,
2996 caller: &Self::CallerCtx,
2997 account_id: &jmap_types::Id,
2998 blob_id: &jmap_types::Id,
2999 ) -> impl std::future::Future<
3000 Output = Result<Result<Option<AttachmentBlob>, SetError>, Self::Error>,
3001 > + Send;
3002
3003 /// FileNode resolution consulted by `handle_message_set` for each
3004 /// create Attachment that carries `filenodeId`.
3005 ///
3006 /// Per draft-atwood-jmap-chat-filenode-00 §filenodeId: "When
3007 /// `filenodeId` is present on an Attachment, the fields `blobId`,
3008 /// `filename`, `contentType`, `size`, and `sha256` become OPTIONAL for
3009 /// that Attachment entry; the server MUST populate any absent fields
3010 /// from the referenced FileNode's properties before storage", and the
3011 /// server "MUST verify that the referenced FileNode exists and belongs
3012 /// to the same Space" and that "the sender has at least read access".
3013 /// `chat` is the message's target Chat. A deployment offering
3014 /// `urn:ietf:params:jmap:chat:filenode` implements this with
3015 /// `jmap_chat_filenode_server::resolve_filenode_attachment`.
3016 ///
3017 /// # When the handler calls this
3018 ///
3019 /// Once per such Attachment, AFTER the `maxAttachmentsPerMessage`
3020 /// check and the `may_send_message` gate, and BEFORE the
3021 /// draft-atwood-jmap-chat-00 §Input Validation checks, the
3022 /// `maxAttachmentBytes` check and [`Self::attachment_blob`], which all
3023 /// apply to the returned Attachment.
3024 ///
3025 /// # Return mapping
3026 ///
3027 /// - `Ok(Ok(Some(attachment)))`: store `attachment`, the entry with
3028 /// its absent fields filled.
3029 /// - `Ok(Ok(None))`: the extension is not active; the entry must carry
3030 /// all five fields, as an Attachment without `filenodeId` does.
3031 /// - `Ok(Err(set_error))`: reject the create with `set_error`.
3032 /// - `Err(e)`: `serverFail`.
3033 ///
3034 /// # Default implementation
3035 ///
3036 /// Returns `Ok(Ok(None))`: no FileNode store, matching the fail-open
3037 /// hooks above.
3038 fn filenode_attachment(
3039 &self,
3040 _caller: &Self::CallerCtx,
3041 _account_id: &jmap_types::Id,
3042 _chat: &jmap_chat_types::Chat,
3043 _attachment: &jmap_chat_types::AttachmentCreate,
3044 ) -> impl std::future::Future<
3045 Output = Result<Result<Option<jmap_chat_types::Attachment>, SetError>, Self::Error>,
3046 > + Send {
3047 async { Ok(Ok(None)) }
3048 }
3049}
3050
3051#[cfg(test)]
3052mod tests {
3053 use super::SlowModeError;
3054 use jmap_types::UTCDate;
3055
3056 #[test]
3057 fn slow_mode_error_display_contains_retry_after() {
3058 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
3059 let rendered = format!("{err}");
3060 assert!(
3061 rendered.contains("slow-mode rate limit"),
3062 "Display missing prefix: {rendered}"
3063 );
3064 assert!(
3065 rendered.contains("2026-05-16T12:34:56Z"),
3066 "Display missing retry_after timestamp: {rendered}"
3067 );
3068 }
3069
3070 #[test]
3071 fn slow_mode_error_is_std_error() {
3072 // Compile-time check that SlowModeError implements std::error::Error.
3073 // If this fails to compile, the trait impl regressed.
3074 fn assert_is_error<E: std::error::Error>(_: &E) {}
3075 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
3076 assert_is_error(&err);
3077 }
3078
3079 #[test]
3080 fn slow_mode_error_boxes_as_dyn_error() {
3081 // Independent oracle: the std error machinery itself. If
3082 // SlowModeError does not implement std::error::Error this
3083 // conversion does not compile.
3084 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
3085 let boxed: Box<dyn std::error::Error> = Box::new(err);
3086 assert!(boxed.to_string().contains("slow-mode rate limit"));
3087 }
3088
3089 use super::OpResult;
3090 use jmap_server::{SetError, SetErrorType};
3091
3092 #[test]
3093 fn op_result_ok_carries_op_index_and_optional_id() {
3094 let r = OpResult::ok(3, Some(jmap_types::Id::from("space-1")));
3095 assert_eq!(r.op_index, 3);
3096 assert_eq!(r.outcome, Ok(Some(jmap_types::Id::from("space-1"))));
3097 }
3098
3099 #[test]
3100 fn op_result_ok_with_none_id_for_update_or_destroy() {
3101 let r = OpResult::ok(0, None);
3102 assert_eq!(r.op_index, 0);
3103 assert_eq!(r.outcome, Ok(None));
3104 }
3105
3106 #[test]
3107 fn op_result_err_carries_op_index_and_set_error() {
3108 let r = OpResult::err(7, SetError::new(SetErrorType::Forbidden));
3109 assert_eq!(r.op_index, 7);
3110 match r.outcome {
3111 Err(e) => assert_eq!(e.error_type, SetErrorType::Forbidden),
3112 Ok(_) => panic!("expected Err outcome"),
3113 }
3114 }
3115
3116 #[test]
3117 fn op_result_with_op_index_replaces_field() {
3118 let r = OpResult::ok(0, None).with_op_index(42);
3119 assert_eq!(r.op_index, 42);
3120 assert_eq!(r.outcome, Ok(None));
3121 }
3122
3123 #[test]
3124 fn op_result_with_outcome_replaces_field() {
3125 let r =
3126 OpResult::ok(0, None).with_outcome(Err(SetError::new(SetErrorType::InvalidProperties)));
3127 assert_eq!(r.op_index, 0);
3128 match r.outcome {
3129 Err(e) => assert_eq!(e.error_type, SetErrorType::InvalidProperties),
3130 Ok(_) => panic!("expected Err outcome after with_outcome"),
3131 }
3132 }
3133
3134 // Const-context smoke tests — lock in the const fn markers so a
3135 // future refactor that accidentally drops `const` from any of
3136 // these constructors / builders is caught at compile time
3137 // (bd:JMAP-x2gd.79).
3138
3139 use super::ChatLimits;
3140
3141 /// `OpResult::ok` is callable in const context.
3142 #[test]
3143 fn op_result_ok_is_const_fn() {
3144 const _R: OpResult = OpResult::ok(0, None);
3145 }
3146
3147 /// `ChatLimits::new` plus all four `with_*` setters chain in const
3148 /// context — proves the entire builder pipeline stays const.
3149 #[test]
3150 fn chat_limits_builder_is_const_fn() {
3151 const _LIMITS: ChatLimits = ChatLimits::new(1, 2, 3, 4)
3152 .with_max_roles_per_space(10)
3153 .with_max_space_members(20)
3154 .with_max_channels_per_space(30)
3155 .with_max_categories_per_space(40);
3156 }
3157
3158 // Note: `SlowModeError::new` is `const fn` (clippy::nursery
3159 // `missing_const_for_fn` would re-fire if the marker were dropped),
3160 // but a const-context smoke test cannot be authored without a
3161 // const-constructible `UTCDate`. `UTCDate` wraps a `String`, and
3162 // `String` is not const-constructible from a non-empty literal in
3163 // stable Rust today. The clippy lint covers the regression case.
3164}