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; they are re-exported here for convenience.
12
13pub use jmap_chat_types::backend::{
14 ChatContactProperty, ChatProperty, MessageProperty, ReadPositionProperty, SpaceProperty,
15};
16pub use jmap_chat_types::space_set::{SpaceMetadataPatch, SpacePatchOp};
17pub use jmap_server::{
18 AddedItem, BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend,
19 JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType, SetObject,
20};
21
22// ---------------------------------------------------------------------------
23// Space/set structural-mutation result
24// ---------------------------------------------------------------------------
25
26/// The outcome of a single [`SpacePatchOp`] applied by
27/// [`ChatBackend::apply_space_patch`].
28///
29/// `op_index` is the zero-based index of the op within the input `Vec`, used
30/// by handlers to construct a descriptive error message identifying which
31/// per-key entry failed (e.g. `addRoles[2] failed: ...`).
32///
33/// `outcome` is:
34/// - `Ok(Some(id))` — the op produced a new server-assigned id (e.g.
35/// [`SpacePatchOp::AddRole`], [`SpacePatchOp::AddChannel`],
36/// [`SpacePatchOp::AddCategory`]). The handler reports this id back to
37/// the client via the `/set` response.
38/// - `Ok(None)` — the op completed but produced no id (every `Remove*` and
39/// `Update*` variant).
40/// - `Err(SetError)` — the op was rejected (e.g. permission denied, target
41/// id not found, role hierarchy violation, count limit exceeded).
42///
43/// Per RFC 8620 §5.3 `/set`, an update target is per-target atomic on the
44/// wire: it appears in exactly one of `updated` or `notUpdated`. If **any**
45/// `OpResult` in the returned `Vec` has an `Err`, the handler reports the
46/// containing update target in `notUpdated`. The handler is free to choose
47/// which `Err` to surface; the reference handler surfaces the first.
48///
49/// This type lives in `jmap-chat-server` (not `jmap-chat-types`) because
50/// [`SetError`] is defined in `jmap-server` and `jmap-chat-types` cannot
51/// depend on it (per the workspace dependency rule: types crates depend
52/// only on `jmap-types`, `serde`, `serde_json`).
53///
54/// `#[non_exhaustive]` preserves the ability to add fields without a
55/// SemVer break (e.g. an audit-log handle, commit ordering hint,
56/// permission-diagnostic annotation). External consumers MUST construct
57/// instances via [`OpResult::ok`] or [`OpResult::err`] rather than
58/// field-init syntax.
59///
60/// # Field-addition policy
61///
62/// Future fields added to `OpResult` are an **additive non-breaking
63/// change**: the new field MUST have a `Default` value (typical for
64/// `Option` / `Vec` / `HashMap`) and the new field is exposed via a
65/// `with_*`-style builder setter rather than being appended as a third
66/// positional argument to [`OpResult::ok`] or [`OpResult::err`]. The
67/// `ok(op_index, id)` and `err(op_index, error)` constructors therefore
68/// stay stable across the crate's pre-1.0 lifetime, matching the
69/// [`ChatLimits`]-style canonical workspace pattern for
70/// `#[non_exhaustive]` types with builder setters.
71#[non_exhaustive]
72#[derive(Debug)]
73pub struct OpResult {
74 /// Zero-based index of the originating op in the input `Vec<SpacePatchOp>`.
75 pub op_index: usize,
76 /// The outcome of applying that op.
77 pub outcome: Result<Option<jmap_types::Id>, SetError>,
78}
79
80impl OpResult {
81 /// Construct an `Ok` result for a successfully applied op.
82 ///
83 /// The contained `Id` is the server-assigned id when the op was a
84 /// create (the kit's response includes it under `created[create_id].id`);
85 /// pass `None` for updates and destroys, which have no id to surface.
86 #[must_use]
87 pub const fn ok(op_index: usize, id: Option<jmap_types::Id>) -> Self {
88 Self {
89 op_index,
90 outcome: Ok(id),
91 }
92 }
93
94 /// Construct an `Err` result for a rejected op.
95 ///
96 /// The kit's `handle_space_set` surfaces this error to the JMAP
97 /// `notUpdated` map for the containing update target.
98 #[must_use]
99 pub const fn err(op_index: usize, error: SetError) -> Self {
100 Self {
101 op_index,
102 outcome: Err(error),
103 }
104 }
105
106 /// Builder-style setter for [`Self::op_index`].
107 ///
108 /// Lets callers update the originating op index after construction.
109 /// Useful when re-indexing a result produced for one op into the
110 /// position of another (e.g. when filtering a batch).
111 #[must_use]
112 pub const fn with_op_index(mut self, op_index: usize) -> Self {
113 self.op_index = op_index;
114 self
115 }
116
117 /// Builder-style setter for [`Self::outcome`].
118 ///
119 /// Lets callers replace the outcome after construction. Useful for
120 /// retry / fallback flows that re-classify a transient error into a
121 /// success or vice versa before surfacing the result to the
122 /// handler.
123 #[must_use]
124 pub fn with_outcome(mut self, outcome: Result<Option<jmap_types::Id>, SetError>) -> Self {
125 self.outcome = outcome;
126 self
127 }
128}
129
130// ---------------------------------------------------------------------------
131// Per-Space content limits
132// ---------------------------------------------------------------------------
133
134/// Implementation-defined per-Space content limits enforced by
135/// `Space/set` handlers.
136///
137/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
138/// 2026-05-11), each `add*` op on a Space MUST return an `overQuota`
139/// SetError (RFC 8620 §5.3) when the resulting count would exceed a
140/// server-defined limit. The spec does not name or normatively define
141/// the cap values; they are implementation-defined and may vary per
142/// account or per tenant.
143///
144/// Backends override [`ChatBackend::limits`] to supply their own values.
145/// The default impl returns conservative reference-impl-grade values
146/// suitable for tests and single-tenant dev servers; production
147/// deployments are expected to override.
148///
149/// Client visibility of these caps (when desired) is via JMAP Quotas
150/// (`urn:ietf:params:jmap:quotas`, RFC 9425), not via this struct.
151/// The `urn:ietf:params:jmap:chat` session capability does NOT advertise
152/// these caps (the previous cap-advertising fields `maxRolesPerSpace`,
153/// `maxSpaceMembers`, `maxChannelsPerSpace`, `maxCategoriesPerSpace`
154/// were removed from the draft in spec commit `80d5e11`).
155///
156/// See the workspace `AGENTS.md` "Backend caps and limits" section for
157/// the cross-extension pattern this struct establishes for JMAP Chat.
158#[non_exhaustive]
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct ChatLimits {
161 /// Maximum number of roles per Space. Enforced against the
162 /// resulting count after applying every `addRoles` entry in a
163 /// `Space/set` update patch.
164 pub max_roles_per_space: u32,
165 /// Maximum number of members per Space. Enforced against the
166 /// resulting count after applying every `addMembers` entry in a
167 /// `Space/set` update patch.
168 pub max_space_members: u32,
169 /// Maximum number of channels per Space. Enforced against the
170 /// resulting count after applying every `addChannels` entry in a
171 /// `Space/set` update patch. The current channel count is the sum
172 /// of `space.uncategorizedChannelIds.len()` and every
173 /// `space.categories[].channelIds.len()`.
174 pub max_channels_per_space: u32,
175 /// Maximum number of categories per Space. Enforced against the
176 /// resulting count after applying every `addCategories` entry in
177 /// a `Space/set` update patch.
178 pub max_categories_per_space: u32,
179}
180
181impl Default for ChatLimits {
182 fn default() -> Self {
183 Self {
184 max_roles_per_space: 50,
185 max_space_members: 10_000,
186 max_channels_per_space: 500,
187 max_categories_per_space: 100,
188 }
189 }
190}
191
192impl ChatLimits {
193 /// Construct a [`ChatLimits`] with the four cap fields specified
194 /// in declaration order: roles, members, channels, categories.
195 ///
196 /// The struct is `#[non_exhaustive]` so external callers (tests
197 /// using `MemoryBackend::set_limits_for_test`, production backends
198 /// overriding [`ChatBackend::limits`]) need a constructor to build
199 /// one. Future cap-field additions to [`ChatLimits`] are an
200 /// additive non-breaking change because the constructor stays
201 /// stable; callers wanting to override the new field combine
202 /// `ChatLimits::new(..)` with [`Self::with_max_roles_per_space`]
203 /// / [`Self::with_max_space_members`] /
204 /// [`Self::with_max_channels_per_space`] /
205 /// [`Self::with_max_categories_per_space`] and a future analogous
206 /// setter.
207 pub const fn new(
208 max_roles_per_space: u32,
209 max_space_members: u32,
210 max_channels_per_space: u32,
211 max_categories_per_space: u32,
212 ) -> Self {
213 Self {
214 max_roles_per_space,
215 max_space_members,
216 max_channels_per_space,
217 max_categories_per_space,
218 }
219 }
220
221 /// Builder-style setter for [`Self::max_roles_per_space`].
222 #[must_use]
223 pub const fn with_max_roles_per_space(mut self, max: u32) -> Self {
224 self.max_roles_per_space = max;
225 self
226 }
227
228 /// Builder-style setter for [`Self::max_space_members`].
229 #[must_use]
230 pub const fn with_max_space_members(mut self, max: u32) -> Self {
231 self.max_space_members = max;
232 self
233 }
234
235 /// Builder-style setter for [`Self::max_channels_per_space`].
236 #[must_use]
237 pub const fn with_max_channels_per_space(mut self, max: u32) -> Self {
238 self.max_channels_per_space = max;
239 self
240 }
241
242 /// Builder-style setter for [`Self::max_categories_per_space`].
243 #[must_use]
244 pub const fn with_max_categories_per_space(mut self, max: u32) -> Self {
245 self.max_categories_per_space = max;
246 self
247 }
248}
249
250// ---------------------------------------------------------------------------
251// Custom emoji authorization gate
252// ---------------------------------------------------------------------------
253
254/// Identifies the kind of `CustomEmoji/set` operation being authorized by
255/// [`ChatBackend::may_set_custom_emoji`].
256///
257/// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11, "refactor:
258/// implementation-defined emoji authorization"), authorization for
259/// `CustomEmoji/set` is fully implementation-defined for both server-global
260/// and Space-scoped emoji. The kit forwards the op kind so the backend can
261/// apply different policies per op (e.g. allow create+update but require
262/// elevated rights for destroy).
263#[non_exhaustive]
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub enum EmojiSetOp {
266 /// `CustomEmoji/set` `create` — a new emoji is being added.
267 Create,
268 /// `CustomEmoji/set` `update` — an existing emoji's mutable fields
269 /// (currently `name` and `blobId`) are being patched.
270 Update,
271 /// `CustomEmoji/set` `destroy` — an existing emoji is being removed.
272 Destroy,
273}
274
275// ---------------------------------------------------------------------------
276// Slow-mode rate-limit gate
277// ---------------------------------------------------------------------------
278
279/// Outcome of a [`ChatBackend::slow_mode_check`] rejection.
280///
281/// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec commit
282/// `de60acb` (2026-05-11) which softened the manage-channels exemption to
283/// SHOULD: a non-exempt member who sends faster than the configured rate
284/// MUST be rejected with a `rateLimited` SetError carrying a
285/// `serverRetryAfter` UTCDate that tells the client when it may retry.
286///
287/// `retry_after` is a fully-formed [`jmap_types::UTCDate`] — the backend
288/// has already done the arithmetic (typically "now + remaining slow-mode
289/// window"). The handler serialises it verbatim onto the wire as the
290/// `serverRetryAfter` SetError extra field.
291///
292/// `#[non_exhaustive]` preserves the ability to add fields without a
293/// SemVer break (e.g. an error code, sender-facing retry hint string,
294/// "this is your N-th throttle in M minutes" diagnostic counter).
295/// External consumers MUST construct instances via [`SlowModeError::new`]
296/// rather than field-init syntax.
297#[non_exhaustive]
298#[derive(Debug, Clone)]
299pub struct SlowModeError {
300 /// When the rate-limited sender may retry.
301 pub retry_after: jmap_types::UTCDate,
302}
303
304impl SlowModeError {
305 /// Construct a [`SlowModeError`] from a precomputed retry-after
306 /// [`UTCDate`].
307 ///
308 /// [`UTCDate`]: jmap_types::UTCDate
309 #[must_use]
310 pub const fn new(retry_after: jmap_types::UTCDate) -> Self {
311 Self { retry_after }
312 }
313}
314
315impl std::fmt::Display for SlowModeError {
316 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317 write!(
318 f,
319 "slow-mode rate limit; retry after {}",
320 self.retry_after.as_ref()
321 )
322 }
323}
324
325impl std::error::Error for SlowModeError {}
326
327// ---------------------------------------------------------------------------
328// ChatBackend trait
329// ---------------------------------------------------------------------------
330
331/// Storage backend for JMAP Chat method handlers.
332///
333/// Implementors provide the actual data access; the method handler modules
334/// in this crate translate between JMAP wire protocol and backend calls.
335///
336/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
337/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
338/// supertrait. Only write operations and type introspection are here.
339///
340/// This trait is not object-safe by design (generic methods). Use
341/// `Arc<impl ChatBackend>` when sharing across tasks.
342///
343/// # Async vs sync method convention
344///
345/// `ChatBackend` carves its methods into two groups:
346///
347/// 1. **Mutation / hot-path hooks are async.** [`ChatBackend::create_object`],
348/// [`ChatBackend::update_object`], [`ChatBackend::destroy_object`],
349/// [`ChatBackend::apply_space_patch`],
350/// [`ChatBackend::apply_space_metadata_patch`],
351/// [`ChatBackend::expire_message`],
352/// [`ChatBackend::slow_mode_check`],
353/// [`ChatBackend::is_contact_blocked`], and
354/// [`ChatBackend::may_set_custom_emoji`] all return
355/// `impl Future + Send`. These methods consult per-account state,
356/// may issue I/O, and run on the JMAP request hot path; the async
357/// signature lets production backends `.await` storage / cache /
358/// policy lookups without runtime-pinning hazards.
359///
360/// 2. **Policy / capability hooks are sync.** [`ChatBackend::supports_type`],
361/// [`ChatBackend::generate_invite_code`], [`ChatBackend::limits`],
362/// [`ChatBackend::protect_last_admin`], and
363/// [`ChatBackend::retains_edit_history`] are synchronous methods.
364/// These hooks answer deployment-policy or capability questions
365/// whose answer SHOULD be derivable from in-process state (a
366/// startup-loaded config snapshot, a cached per-account record, a
367/// CSPRNG handle). The sync shape keeps the trait surface easy to
368/// implement for single-process and reference backends, which are
369/// the dominant use case for a kit crate.
370///
371/// The carve-up is intentional and is NOT a "we forgot to async these"
372/// regression. Production backends that need to consult an async
373/// source for any of the five sync hooks have two options: (a)
374/// pre-cache the answer at startup or on a background refresh; or (b)
375/// file a follow-up bead proposing the conversion for that specific
376/// method, with the production constraint documented. Per-method
377/// rustdoc notes ("`# Why sync, not async`" / "`# Fallibility and
378/// async — known limitations`") spell out the workaround on each
379/// affected method. Flipping any of the sync hooks to async is a
380/// major-version breaking change for downstream implementors;
381/// converting them all preemptively for hypothetical multi-tenant
382/// SaaS deployments would over-engineer the kit-vs-product posture
383/// described in workspace `AGENTS.md`.
384pub trait ChatBackend: JmapBackend {
385 /// Create a new object.
386 ///
387 /// Returns `(assigned_id, created_object)` on success. `create_id` is the
388 /// client-side creation id used in the `/set` request.
389 ///
390 /// # Sentinel fields the backend MUST replace
391 ///
392 /// The method handlers in this crate pass partially-constructed objects
393 /// with sentinel values that the backend MUST replace with real values
394 /// before storing:
395 ///
396 /// - **`id`**: The `id` field in the input object is always set to
397 /// `"placeholder"`. The backend MUST replace it with a real, unique,
398 /// account-scoped ID and return that ID as the first element of the
399 /// result tuple.
400 ///
401 /// Failing to replace this sentinel will cause the client to receive an
402 /// invalid wire value (`"placeholder"`) as the assigned id of every
403 /// created `Space`, `Chat`, `Message`, `SpaceInvite`, `SpaceBan`,
404 /// `CustomEmoji`, and `ReadPosition`.
405 ///
406 /// # Per-type uniqueness contracts
407 ///
408 /// For most types the (id) primary key is the only uniqueness
409 /// invariant the backend must enforce, and the backend's normal
410 /// server-assigned-id discipline closes that. A few types carry
411 /// additional uniqueness invariants on non-id fields that the
412 /// backend MUST enforce atomically with the create — the handler
413 /// pre-checks defensively but cannot close the
414 /// two-concurrent-requests race window.
415 ///
416 /// - **`ReadPosition`** — at most one record per
417 /// `(account_id, chat_id)`. The handler at
418 /// [`crate::position::handle_position_set`] pre-checks via a
419 /// sequential scan and rejects sequential / intra-batch
420 /// duplicates with `alreadyExists`, but two concurrent
421 /// `ReadPosition/set` requests for the same `chatId` can both
422 /// pass the pre-check and then both reach `create_object`. The
423 /// backend MUST enforce a unique constraint on
424 /// `(account_id, chat_id)` at the storage layer (typically a
425 /// composite unique index in a database backend) and surface a
426 /// duplicate as `BackendSetError::SetError(SetError::new(
427 /// SetErrorType::AlreadyExists).with_existing_id(canonical))`.
428 /// See draft-atwood-jmap-chat-00 §ReadPosition.
429 /// - **`Chat`** with `kind == Direct` — at most one direct chat
430 /// per `(account_id, contact_id)`. The handler at
431 /// [`crate::chat::handle_chat_set`] uses optimistic
432 /// create-then-validate with rollback; backends MAY enforce a
433 /// storage-level unique constraint to eliminate the rollback
434 /// path entirely, but it is not required because the
435 /// handler's rollback closes the race correctly. See
436 /// draft-atwood-jmap-chat-00 §Chat.
437 ///
438 /// The reference [`crate::memory::MemoryBackend`] does NOT
439 /// enforce the `ReadPosition` `(account, chatId)` uniqueness
440 /// constraint at the storage layer — it is single-Mutex
441 /// per-call so concurrent racing cannot occur in practice, but a
442 /// production backend that holds different locks per record (or
443 /// no lock at all between read and write) MUST.
444 fn create_object<O: SetObject + Send + Sync>(
445 &self,
446 caller: &Self::CallerCtx,
447 account_id: &jmap_types::Id,
448 create_id: &str,
449 obj: O,
450 ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
451 + Send;
452
453 /// Apply a partial update (patch) to an existing object.
454 ///
455 /// Returns `Some(updated_object)` if the backend modified any properties
456 /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
457 /// or `None` if the patch was applied verbatim.
458 fn update_object<O: SetObject + Send + Sync>(
459 &self,
460 caller: &Self::CallerCtx,
461 account_id: &jmap_types::Id,
462 id: &jmap_types::Id,
463 patch: O::Patch,
464 ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
465
466 /// Destroy an existing object by id.
467 fn destroy_object<O: SetObject + Send + Sync>(
468 &self,
469 caller: &Self::CallerCtx,
470 account_id: &jmap_types::Id,
471 id: &jmap_types::Id,
472 ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
473
474 /// Returns true if this account supports the given JMAP object type.
475 /// Called by the server consumer (e.g. the session capability builder) —
476 /// NOT called internally by the handler library. Backends that support all
477 /// types unconditionally can return `true` always.
478 ///
479 /// # Why sync, not async
480 ///
481 /// Type-support is a startup-time deployment capability question,
482 /// not a per-request decision. Backends that vary supported types
483 /// per-tenant (e.g. "Pro tier exposes `CustomEmoji`") SHOULD load
484 /// the tenant configuration once at startup and answer from the
485 /// in-memory snapshot. See the trait-level "Async vs sync method
486 /// convention" section above for the workspace rationale.
487 ///
488 /// # Known limitation: no args
489 ///
490 /// This method takes no `caller` / `account_id` arguments, so a
491 /// multi-tenant backend cannot vary the answer per tenant from
492 /// inside this method alone — it must funnel all per-tenant
493 /// capability variation through `&self` state. Adding the
494 /// arguments would be a non-breaking signature widening; that
495 /// proposal is tracked separately.
496 fn supports_type<O: JmapObject>(&self) -> bool;
497
498 /// Generate a cryptographically random invite code.
499 ///
500 /// Implementations MUST use a CSPRNG seeded from OS entropy. The
501 /// recommended choices are [`rand::rngs::OsRng`] or the [`getrandom`]
502 /// crate directly. Do NOT use `rand::thread_rng()` for security-relevant
503 /// output: although current `rand` versions document `ThreadRng` as
504 /// cryptographically secure, its underlying algorithm is
505 /// implementation-defined and has changed across releases, and the
506 /// `rand` book explicitly routes security-sensitive callers to `OsRng`.
507 ///
508 /// The returned string must be unguessable — do NOT use timestamps,
509 /// sequential counters, or non-CSPRNG sources.
510 ///
511 /// # Output shape contract
512 ///
513 /// Implementations MUST satisfy ALL of the following for the kit's
514 /// constant-time-compare guarantee (see below) to hold:
515 ///
516 /// 1. **Fixed length across calls.** Every invocation of
517 /// `generate_invite_code` on a single backend MUST return a
518 /// string of the same byte length. A backend that returns
519 /// variable-length codes leaks a length oracle through the
520 /// constant-time-compare timing channel: `ct_eq` returns
521 /// `Choice(0)` cheaply on length mismatch, so an attacker can
522 /// learn whether their candidate code matches the stored
523 /// length even when the content compare is constant-time.
524 /// 2. **Minimum 128 bits of CSPRNG entropy.** The reference
525 /// `MemoryBackend` impl in this crate (in `memory.rs`) emits
526 /// 32 lowercase-hex characters (16 bytes = 128 bits) which is
527 /// the workspace floor. Production backends MAY use more; less
528 /// is forbidden. The trait method itself is abstract — no
529 /// default impl — so backends MUST provide one.
530 /// 3. **ASCII-safe encoding.** The returned bytes MUST be 7-bit
531 /// ASCII printable, byte-length-equal-to-char-length, and
532 /// safe to use as-is in JMAP wire format and HTTP-style
533 /// URL paths (no `/`, `+`, `=`, or whitespace). Recommended
534 /// encodings: lowercase hex (the default), base32 unpadded,
535 /// base64url unpadded. Plain base64 with `/` is forbidden
536 /// because downstream URL-encoded redemption flows misroute
537 /// the slash. Non-ASCII output is forbidden because
538 /// helpers that take byte-prefix slices (e.g. the
539 /// `iso8601_before` partial-comparison family) panic on
540 /// multi-byte UTF-8 boundaries.
541 /// 4. **Sufficient lifespan.** Codes MUST remain
542 /// discriminable from each other across the backend's
543 /// retention window. With 128 bits of entropy and
544 /// well-mixed CSPRNG output, collision probability is
545 /// cryptographically negligible up to 2^64 active codes.
546 ///
547 /// A backend that cannot meet any of points 1–3 MUST NOT
548 /// expose `Space/join`'s invite-code redemption path, or MUST
549 /// build its own redemption with a different constant-time
550 /// argument. The kit's `handle_space_join` assumes the contract
551 /// without re-validating each code's shape.
552 ///
553 /// # Constant-time comparison contract
554 ///
555 /// Consumers of the returned code (notably `Space/join` invite-code
556 /// lookup) MUST compare it against attacker-supplied values in
557 /// constant time using `subtle::ConstantTimeEq::ct_eq` or equivalent.
558 /// The reference handler in `space::handle_space_join` already does
559 /// this; backends that build their own invite-redemption paths must
560 /// preserve the invariant. A plain `String == String` short-circuits
561 /// at the first mismatched byte and exposes a byte-by-byte timing
562 /// oracle for credential recovery.
563 ///
564 /// # Fallibility and async — known limitations
565 ///
566 /// This method is sync and infallible. Backends that mint codes
567 /// via a remote source (HSM, KMS, hardened sandbox where
568 /// `getrandom` is gated, etc.) cannot surface failure from this
569 /// signature and cannot `.await` a network call. Such backends
570 /// must pre-fetch a buffer of codes at startup and serve from it,
571 /// or panic on entropy starvation. A future revision MAY change
572 /// the signature to `async fn generate_invite_code(&self) ->
573 /// Result<String, Self::Error>` to support remote / fallible
574 /// entropy sources without forcing the pre-fetch workaround.
575 ///
576 /// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
577 /// [`getrandom`]: https://docs.rs/getrandom
578 fn generate_invite_code(&self) -> String;
579
580 /// Implementation-defined per-Space content limits for this caller
581 /// and account.
582 ///
583 /// Called by `handle_space_set` once per request, before
584 /// dispatching to [`Self::apply_space_patch`], to enforce
585 /// per-aggregate caps on roles, members, channels, and categories
586 /// per Space (draft-atwood-jmap-chat-00 §Space/set, spec commit
587 /// `80d5e11`).
588 ///
589 /// The default implementation returns [`ChatLimits::default`],
590 /// which carries conservative reference-impl-grade values. The
591 /// `caller` and `account_id` arguments are plumbed even though the
592 /// default impl ignores them, so production backends can vary caps
593 /// per-account (Free vs. Pro tier, multi-tenant SaaS, etc.)
594 /// without a future API break. Implementations SHOULD return
595 /// quickly (in-process struct construction, possibly off a cached
596 /// per-account record) — this method is called on the hot
597 /// `Space/set` path.
598 ///
599 /// # Why sync, not async
600 ///
601 /// `Space/set` calls this once per request before dispatching the
602 /// mutation; an async `.await` here would add a roundtrip to the
603 /// hot path of every Space mutation. Production backends with
604 /// per-tenant caps SHOULD cache the resolved [`ChatLimits`] for
605 /// each account on first use and serve from the cache thereafter.
606 /// See the trait-level "Async vs sync method convention" section
607 /// above for the workspace rationale.
608 ///
609 /// Workspace cross-extension pattern: see `AGENTS.md` "Backend
610 /// caps and limits".
611 fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
612 ChatLimits::default()
613 }
614
615 /// Apply a sequence of structural mutations to a Space
616 /// (draft-atwood-jmap-chat-00 §Space/set).
617 ///
618 /// `Space/set` `update` operations use semantic mutation keys
619 /// (`addRoles`, `removeRoles`, `addMembers`, …) rather than RFC 8620
620 /// JSON Pointer patches. The handler in `space::handle_space_set`
621 /// parses the wire object, unfolds each array entry into a
622 /// [`SpacePatchOp`] value, then calls this method with the resulting
623 /// ordered `Vec`.
624 ///
625 /// # Ordering and atomicity
626 ///
627 /// Implementations SHOULD apply ops in input order and SHOULD provide
628 /// best-effort transactional semantics so that a partial failure does
629 /// not leave the Space in a half-updated state. The reference
630 /// in-memory implementation locks the entire backend for the duration
631 /// of the call. A database-backed implementation should wrap the
632 /// sequence in a single transaction.
633 ///
634 /// # Permission and limit checks
635 ///
636 /// Permission gates (`manage_space`, `manage_roles`,
637 /// `manage_members`, `manage_channels`) are backend-canonical per
638 /// workspace AGENTS.md "Caller identity (foundation seam)": the
639 /// reference handler does NOT apply gates before calling this
640 /// method, and the backend is responsible for rejecting any op the
641 /// caller is not authorized to perform.
642 ///
643 /// Per-aggregate count limits on roles, members, channels, and
644 /// categories per Space are **backend-canonical** as of
645 /// bd:JMAP-x2gd.44: the backend MUST query its own
646 /// [`ChatBackend::limits`], project the post-patch counts for the
647 /// target Space, and reject the whole patch with an `overQuota`
648 /// SetError (RFC 8620 §5.3) if any aggregate would exceed its
649 /// cap. The cap enforcement MUST be atomic with the mutation
650 /// itself — typically inside the same database transaction or
651 /// the same mutex critical section. Per
652 /// draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
653 /// 2026-05-11), this behavior is normative.
654 ///
655 /// The handler at [`crate::space::handle_space_set`] additionally
656 /// runs a defense-in-depth pre-flight cap check before this
657 /// method, but the pre-flight is non-load-bearing: a backend
658 /// caller that bypasses the JMAP wire layer (admin tool,
659 /// federation receiver, internal batch importer) and calls
660 /// `apply_space_patch` directly MUST still see caps enforced.
661 /// The pre-flight exists only to surface `overQuota` to the
662 /// client as a single SetError without consuming a backend
663 /// round-trip; backends MAY rely on the handler having pre-checked
664 /// for performance, but MUST NOT rely on it for correctness.
665 ///
666 /// The role-position hierarchy check (members may only add or modify
667 /// roles whose `position` is strictly less than their own
668 /// highest-position role — draft §Space/set lines 1096, 1102) MUST
669 /// be enforced by the backend because it is atomic with the
670 /// mutation and depends on the current Space state.
671 ///
672 /// # Cross-type cascade contract
673 ///
674 /// Several `SpacePatchOp` variants have side effects on other JMAP
675 /// types in the chat extension (`Chat`, `Message`). The wire-format
676 /// `Space/set` response describes only the Space-side change, but
677 /// `/changes` subscribers on the cascaded types depend on the
678 /// backend bumping the relevant type state tokens. A backend that
679 /// performs the cross-type mutations but forgets the state bumps
680 /// silently desynchronises every multi-client subscriber — the
681 /// failure is invisible to single-tenant smoke tests.
682 ///
683 /// The required cascades are:
684 ///
685 /// * `RemoveChannel` — MUST destroy the channel-kind `Chat` record
686 /// and every `Message` whose `chatId` matches the removed
687 /// channel (draft §Space/set line 1117: "Cascades to all
688 /// Messages in those channels."). The `Chat` and `Message` type
689 /// state tokens MUST both bump so `Chat/changes` and
690 /// `Message/changes` subscribers see the destruction.
691 ///
692 /// * `RemoveCategory` — MUST clear `Chat.categoryId` on every
693 /// channel-kind `Chat` whose `categoryId` named the removed
694 /// category (the channels fall back to uncategorized). The
695 /// `Chat` type state token MUST bump and the affected channel
696 /// ids MUST appear in the next `Chat/changes` entry's `updated`
697 /// list.
698 ///
699 /// * `AddCategory` / `UpdateCategory` with a non-empty `channelIds`
700 /// array — MUST set `Chat.categoryId` on each named channel
701 /// (relocating it from its previous category or from
702 /// uncategorized). The `Chat` type state token MUST bump and
703 /// the relocated channel ids MUST appear in `Chat/changes`
704 /// `updated`. This pins a regression class where channel
705 /// relocations silently bypass the `Chat/changes` log; a
706 /// backend that mutates `Chat.categoryId` without bumping the
707 /// `Chat` state token desynchronises every multi-client
708 /// subscriber.
709 ///
710 /// * `RemoveRole` — MUST strip the removed role id from
711 /// `roleIds` on every `SpaceMember` of this Space (draft
712 /// §Space/set line 1099). Members embed directly in `Space`,
713 /// so the cascade is captured by the existing `Space` state
714 /// bump; no separate `Member/changes` rotation is required.
715 ///
716 /// * `RemoveMember` — MUST remove the member entry and keep
717 /// `Space.memberCount` consistent with `members.len()`. The
718 /// spec does not mandate cascade to the member's `ReadPosition`
719 /// records; the reference impl leaves them in place and treats
720 /// ReadPosition cleanup as implementation-defined. A backend
721 /// that destroys orphaned ReadPositions MUST bump the
722 /// `ReadPosition` type state token; a backend that retains
723 /// them MUST NOT.
724 ///
725 /// State-token bumps SHOULD be batched per call: one bump per
726 /// affected type per `apply_space_patch` invocation, not one bump
727 /// per op. The reference impl combines every channel created,
728 /// updated, and destroyed by a patch into a single `Chat/changes`
729 /// entry; doing the same in production keeps `/changes`
730 /// rotation rates proportional to client-visible mutations rather
731 /// than to internal op count.
732 ///
733 /// # Server-set field invariants
734 ///
735 /// Server-set fields on the target Space (`memberCount`,
736 /// `updatedAt`, and any future analogous cached aggregates) MUST
737 /// be kept consistent with the post-mutation state. Specifically,
738 /// after any combination of `AddMember` and `RemoveMember` ops,
739 /// `Space.memberCount` MUST equal `Space.members.len()` as
740 /// observed by the next `Space/get`. Backends MAY store these as
741 /// cached values that they recompute on every mutation, or MAY
742 /// compute them lazily at read time; either is acceptable as
743 /// long as `Space/get` returns values consistent with the
744 /// returned `members` array. The natural-minimal "persist
745 /// memberCount once and trust it" implementation is **not**
746 /// correct: subsequent mutations to `members` would let
747 /// `memberCount` drift silently.
748 ///
749 /// # Per-op error semantics
750 ///
751 /// Backend rejections that originate from a single op carry both
752 /// a typed [`SetErrorType`] and a human-readable `description`
753 /// string. The kit's integration tests pin specific
754 /// (`SetErrorType`, `description`-substring) pairs for the
755 /// common failure modes; a backend that returns a different
756 /// variant or an empty description will fail those tests when
757 /// plugged in.
758 ///
759 /// The following table records the contract for the
760 /// failure modes the kit exercises today:
761 ///
762 /// | Op + failure mode | `SetErrorType` | `description` MUST contain |
763 /// |---|---|---|
764 /// | 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) |
765 /// | `AddRole` / `UpdateRole` at or above caller's highest role `position` | `Forbidden` | `"hierarchy"` or `"position"` |
766 /// | Any op or combination of ops whose post-patch projection leaves the Space with zero `manage_members`-holding members (when [`Self::protect_last_admin`] returns `true`) | `Forbidden` | `"last-admin"` or `"manage_members"` |
767 /// | `AddMember` with `userId` already a member | `InvalidProperties` (`properties: ["userId"]`) | implementation-defined; the reference impl names the duplicate userId |
768 /// | `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 |
769 /// | `RemoveRole` / `RemoveChannel` / `RemoveCategory` with an id that does not exist on this Space | `NotFound` | implementation-defined; the reference impl names the missing id |
770 ///
771 /// The "MUST contain ... as a substring" rule on permission-denied
772 /// failures lets downstream UI / CLI consumers route
773 /// permission-request flows by parsing the description, and lets
774 /// users see "Permission denied: missing manage_space" rather
775 /// than a bare "Permission denied". Deployments that need a
776 /// programmatic alternative SHOULD additionally surface the
777 /// missing permission via [`SetError::with_extra`] under a
778 /// deployment-specific key — substring matching is the floor,
779 /// not the ceiling.
780 ///
781 /// Note on routing: per-op rejections normally surface inside the
782 /// returned [`OpResult`] vector, NOT as a top-level
783 /// [`BackendSetError`] return. The handler at
784 /// [`crate::space::handle_space_set`] applies the kit's per-
785 /// update-target atomicity: any failing op in the patch fails the
786 /// whole `update` target, so the test fixtures see the first-failing
787 /// op's `(SetErrorType, description)` surface on
788 /// `notUpdated[<spaceId>]`. The table above describes the
789 /// per-op outcome content; the handler does not synthesise new
790 /// variants or rewrite descriptions.
791 ///
792 /// # Return value
793 ///
794 /// On success, returns a `Vec<OpResult>` of the same length as `ops`,
795 /// in input order. Each entry reports the outcome of one op (id
796 /// assignment for `Add*` variants, error for rejections). The
797 /// handler maps per-op errors back into the `/set` response shape
798 /// per [`OpResult`]'s documentation.
799 ///
800 /// Returns [`BackendSetError::Other`] only for backend-level failures
801 /// (the storage layer is unreachable, the account does not exist,
802 /// `space_id` is unknown, etc.) — i.e. failures that prevent any op
803 /// from being attempted. Per-op rejections (permission denied,
804 /// invalid id, role hierarchy violation, etc.) go in the `outcome`
805 /// field of the returned [`OpResult`] vector, not in an error return.
806 fn apply_space_patch(
807 &self,
808 caller: &Self::CallerCtx,
809 account_id: &jmap_types::Id,
810 space_id: &jmap_types::Id,
811 ops: Vec<SpacePatchOp>,
812 ) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
813
814 /// Apply a JSON Merge Patch to a Space's top-level metadata fields
815 /// (draft-atwood-jmap-chat-00 §Space/set, `name`, `description`,
816 /// `iconBlobId`, `isPublic`, `isPubliclyPreviewable`).
817 ///
818 /// `Space/set` `update` operations carrying *only* top-level
819 /// metadata fields (and not the semantic-mutation keys
820 /// `addRoles` / `addMembers` / `addChannels` / `addCategories`
821 /// etc.) route through this method instead of the generic
822 /// [`Self::update_object`]. Mixed patches carrying both top-level
823 /// metadata AND semantic-mutation keys call
824 /// [`Self::apply_space_patch`] first (for the structural ops) and
825 /// this method second (for the metadata). The handler at
826 /// `space::handle_space_set` is responsible for the split and for
827 /// stripping non-metadata keys before calling this method.
828 ///
829 /// # Permission and atomicity
830 ///
831 /// Per draft-atwood-jmap-chat-00, every top-level metadata field
832 /// carries the marker "Mutable by members with `manage_space`
833 /// permission". Implementations MUST gate the mutation on the
834 /// caller's effective permissions in the target Space:
835 ///
836 /// - If [`JmapBackend::principal_id`] returns `Some(caller_id)`,
837 /// verify the caller holds `manage_space` (resolved through the
838 /// Space's role hierarchy). Reject the patch with
839 /// [`SetErrorType::Forbidden`] if not.
840 /// - If [`JmapBackend::principal_id`] returns `None` (single-user
841 /// mode — the backend has not wired identity), the gate is
842 /// skipped. This is consistent with the workspace AGENTS.md
843 /// "Caller identity (foundation seam)" section: a backend that
844 /// does not honor identity-dependent semantics opts out.
845 ///
846 /// The check fires inside this method atomically with the
847 /// mutation: snapshot the Space's role/member state, evaluate
848 /// the permission gate, and apply the merge patch in one
849 /// critical section. Backend canonical per workspace AGENTS.md.
850 ///
851 /// # `patch` shape
852 ///
853 /// The handler decodes the wire patch's metadata-key subset
854 /// (`name`, `description`, `iconBlobId`, `isPublic`,
855 /// `isPubliclyPreviewable`) into a [`SpaceMetadataPatch`],
856 /// stripping structural mutation keys (`addRoles` etc.) before
857 /// building it. Each field is `Option<_>`; nullable target fields
858 /// use `Option<Clearable<T>>` so the backend can distinguish
859 /// "wire null" (clear) from "absent" (unchanged). Backends MAY
860 /// validate the values further (e.g. reject an `icon_blob_id`
861 /// referencing a non-existent blob) and surface those as
862 /// [`SetError`] returns. The expected `SetErrorType` for
863 /// value-level validation failures is
864 /// [`SetErrorType::InvalidProperties`] with the offending field
865 /// name in `properties` — see the "Diagnostic content
866 /// convention" section below for the blob-not-found shape
867 /// specifically. (RFC 8620 §5.3 defines `blobNotFound` only as
868 /// a method-level error; at the SetError level it surfaces as
869 /// `InvalidProperties` naming the offending blob-id field.)
870 ///
871 /// # Return value
872 ///
873 /// The discriminator between `Ok(Some(space))` and `Ok(None)` is
874 /// the **wire-visible Space shape**:
875 ///
876 /// - Return `Ok(None)` if the wire-visible `Space` (the shape
877 /// `Space/get` would serialise after applying this patch) is
878 /// identical to the result of mechanically applying the patch
879 /// keys to the prior state with no additional server-side
880 /// modification. The handler can then build the `/set` `updated`
881 /// entry from the input patch alone with no extra fetch.
882 /// - Return `Ok(Some(space))` if the backend modified any
883 /// wire-visible property beyond what the client requested
884 /// (RFC 8620 §5.3 server-set field echo, e.g. a normalised
885 /// `name`, a derived `iconBlobId`, a server-bumped
886 /// `memberCount`, or any spec-defined server-set field that
887 /// `Space/get` would return). The handler echoes the returned
888 /// `Space` to the client.
889 ///
890 /// Server-internal bookkeeping that is NOT part of the
891 /// wire-visible `Space` shape (e.g. private last-touched
892 /// timestamps used only for `/changes` cache-keying, internal
893 /// sequence numbers) MUST NOT itself drive the `Some` path —
894 /// the discriminator is "would `Space/get` return a different
895 /// shape?", not "did the backend touch anything internally?".
896 /// A backend that bumps an internal timestamp on every metadata
897 /// patch correctly returns `Ok(None)` when the wire shape is
898 /// otherwise unchanged.
899 ///
900 /// `Err(BackendSetError::SetError(e))` with `e.kind ==
901 /// SetErrorType::Forbidden` when the caller fails the
902 /// `manage_space` gate.
903 ///
904 /// # Diagnostic content convention
905 ///
906 /// The `SetError.description` on a `manage_space`-gate rejection
907 /// MUST contain `"manage_space"` as a substring. The kit's
908 /// integration tests assert this (e.g.
909 /// `tests/space_metadata_apply.rs`); a backend that returns a
910 /// bare `SetError::new(SetErrorType::Forbidden)` with no
911 /// `description` will fail those tests. Build the error via
912 /// `SetError::new(SetErrorType::Forbidden).with_description(
913 /// "manage_space permission required")` (or any other string
914 /// that contains the literal `"manage_space"`).
915 ///
916 /// Future blob-validation rejections (e.g. `iconBlobId`
917 /// referencing a non-existent blob, see the `patch` shape
918 /// section above) SHOULD surface as
919 /// `SetErrorType::InvalidProperties` with
920 /// `properties: ["iconBlobId"]` and a description that names
921 /// the offending blob id. The reference impl does not validate
922 /// blobs today; production backends with a blob store SHOULD.
923 ///
924 /// Rationale for the separate metadata patch method: routing
925 /// top-level metadata through the generic `update_object::<Space>`
926 /// would bypass the permission gate, since the generic path is
927 /// not permission-aware. This method exists so that top-level
928 /// `Space/set` `update` requests carrying only metadata fields
929 /// (`name` / `description` / `iconBlobId` / `isPublic` /
930 /// `isPubliclyPreviewable`) route through a `manage_space`-gated
931 /// path instead.
932 fn apply_space_metadata_patch(
933 &self,
934 caller: &Self::CallerCtx,
935 account_id: &jmap_types::Id,
936 space_id: &jmap_types::Id,
937 patch: jmap_chat_types::SpaceMetadataPatch,
938 ) -> impl std::future::Future<
939 Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
940 > + Send;
941
942 /// Whether the backend should reject any [`Self::apply_space_patch`]
943 /// that would leave the target Space with zero members holding
944 /// either `manage_members` or `manage_space` permission.
945 ///
946 /// # Invariant (by outcome, not by op type)
947 ///
948 /// The protection is invariant on the *post-patch* state of the
949 /// (member, role, permission) graph, not on any single op variant.
950 /// A backend that returns `true` from this method MUST reject every
951 /// patch whose post-application projection has zero members holding
952 /// `manage_members` or `manage_space`, including (non-exhaustively):
953 ///
954 /// - `RemoveMember` that removes the last admin member.
955 /// - `UpdateMember` that strips a role granting `manage_members` or
956 /// `manage_space` from a member who holds no other such role.
957 /// - `UpdateRole` that removes `manage_members` or `manage_space`
958 /// permission from a role currently held by the last admin.
959 /// - `RemoveRole` that drops a permission-granting role from the
960 /// graph when no other role grants the same permission to a
961 /// remaining member.
962 /// - Any combination of the above within a single `ops` vector
963 /// whose cumulative effect is zero admins.
964 ///
965 /// Production backends should project the post-patch graph and
966 /// reject when the admin count would reach zero, regardless of
967 /// which op caused the transition.
968 ///
969 /// # Why this exists
970 ///
971 /// The 2026-05-12 design reversal dropped the `Space.ownerId` field:
972 /// "who controls a Space" is now fully implementation-defined /
973 /// out-of-band per draft-atwood-jmap-chat-00.
974 /// Without a normative owner identity, the kit cannot enforce the
975 /// previous "owner cannot be removed" rule. Instead the kit exposes
976 /// this purely permission-graph-based knob: production backends that
977 /// want to prevent the "no admin left" failure mode return `true`
978 /// (the trait default); deployments with their own designated
979 /// controller principal or external admin-tracking system can opt
980 /// out by returning `false`.
981 ///
982 /// # Default implementation
983 ///
984 /// Returns `true` — production-safe by default. A third-party
985 /// backend that does not override this method gets last-admin
986 /// protection automatically.
987 ///
988 /// # Why the reference `MemoryBackend` overrides this to `false`
989 ///
990 /// The reference impl flips the default to keep existing
991 /// integration tests (which do not seed admin memberships) passing
992 /// unchanged. Tests that exercise the protection path opt in via
993 /// `MemoryBackend::set_protect_last_admin_for_test(true)`.
994 ///
995 /// The reference impl's projection is intentionally narrow: it
996 /// covers `RemoveMember` only, and does NOT model `UpdateMember`
997 /// role-strip, `UpdateRole` permission-strip, or `RemoveRole`
998 /// paths to zero-admin state. Production backends with the full
999 /// invariant requirement MUST extend the projection.
1000 ///
1001 /// # Atomicity
1002 ///
1003 /// The check fires inside [`Self::apply_space_patch`] atomically
1004 /// with the candidate mutation: the backend snapshots the Space's
1005 /// member/role state, projects the post-patch admin count across
1006 /// all ops in the patch (member adds/removes, role-id changes,
1007 /// permission edits), and rejects the whole update target with a
1008 /// `Forbidden` SetError if zero admins would remain.
1009 ///
1010 /// # Why sync, not async
1011 ///
1012 /// This predicate is a deployment-policy flag: a backend either
1013 /// enforces the last-admin invariant or it does not. Backends
1014 /// that consult an external admin-tracking service to derive the
1015 /// answer SHOULD cache the per-account boolean and answer from
1016 /// the cache. See the trait-level "Async vs sync method
1017 /// convention" section above for the workspace rationale.
1018 fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
1019 let _ = (caller, account_id);
1020 true
1021 }
1022
1023 /// Whether the backend retains edit history for messages.
1024 ///
1025 /// Per draft-atwood-jmap-chat-00 commit `0783fc4` ("condition
1026 /// MessageRevision push on edit-history retention") +
1027 /// `§Message editHistory`: servers MAY limit retained
1028 /// MessageRevisions, and when the server does not retain edit
1029 /// history, the `editHistory` field MUST be omitted from
1030 /// `Message/get` and (in principle) `Message/changes` responses.
1031 /// `Message/changes` per RFC 8620 §5.2 returns only id arrays,
1032 /// not Message objects, so the spec's "omit from /changes" is
1033 /// a no-op at the wire level — the kit only enforces the
1034 /// `Message/get` projection.
1035 ///
1036 /// # When the handler calls this
1037 ///
1038 /// `handle_message_get` consults this predicate once per call.
1039 /// When `false`, every returned `Message` has its
1040 /// `edit_history` field set to `None` before serialization,
1041 /// which serde's `skip_serializing_if = "Option::is_none"`
1042 /// collapses to a wire-absent field per spec.
1043 ///
1044 /// # Why sync, not async
1045 ///
1046 /// This is a static deployment-policy flag, not a per-call
1047 /// decision — it does not consult per-account state, principal
1048 /// identity, or per-message bounds. Production backends that
1049 /// need to vary retention per-account would file a follow-up
1050 /// bead for a parallel `retains_edit_history_for_account` hook
1051 /// rather than reshaping this method.
1052 ///
1053 /// # Default implementation
1054 ///
1055 /// Returns `false` — no retention. This matches the workspace's
1056 /// "kit defines the hook; consumer enforces the policy" posture.
1057 /// Production backends that retain edit history MUST override
1058 /// this to `true`; the reference `MemoryBackend` exposes a
1059 /// test-only setter for tests that need the retain-on path.
1060 fn retains_edit_history(&self) -> bool {
1061 false
1062 }
1063
1064 /// Predicate consulted by typing/presence fan-out paths: is the
1065 /// caller (the sender of the ephemeral event) blocked by the
1066 /// recipient who owns `account_id`'s contact list?
1067 ///
1068 /// Per draft-atwood-jmap-chat-00 commit `d68b4e3` (2026-05-11,
1069 /// "close blocked-sender suppression gaps for typing/presence"):
1070 /// when the sender corresponds to a [`ChatContact`] whose
1071 /// `blocked` is `true` on the recipient's contact list, the
1072 /// server MUST silently suppress the ephemeral event for that
1073 /// recipient. The sender is NOT informed.
1074 ///
1075 /// [`ChatContact`]: jmap_chat_types::ChatContact
1076 ///
1077 /// # Argument semantics
1078 ///
1079 /// - `caller`: identity of the sender. Backends with identity
1080 /// wired resolve this via
1081 /// [`JmapBackend::principal_id`];
1082 /// the resolved principal is matched against the
1083 /// [`ChatContact`]'s implementation-defined principal binding
1084 /// to determine which `ChatContact` (if any) in the recipient's
1085 /// list represents the sender.
1086 /// - `account_id`: the **recipient's** account, i.e. the account
1087 /// that owns the [`ChatContact`] list to consult. NOT the
1088 /// sender's account.
1089 /// - `contact_id`: the candidate [`ChatContact`] id within the
1090 /// recipient's account. The backend checks whether THIS
1091 /// contact's `blocked` field is `true` AND whether THIS
1092 /// contact corresponds to the sender (via the principal
1093 /// binding resolved from `caller`).
1094 ///
1095 /// # Single-user mode (principal_id returns None)
1096 ///
1097 /// Backends that have not wired identity cannot match the sender
1098 /// against a `ChatContact` principal binding. Such backends
1099 /// SHOULD fail-safe by returning `Ok(false)` (the default impl
1100 /// does this), which preserves visibility — under-suppression in
1101 /// a single-user dev deployment is preferable to
1102 /// over-suppression that would mask a misconfigured backend.
1103 ///
1104 /// # When the handler calls this
1105 ///
1106 /// `handle_chat_typing` consults this predicate when the target
1107 /// `Chat` is direct (a single recipient identified by
1108 /// `Chat.contact_id`). The kit does not implement transport-layer
1109 /// fan-out (push events to subscribers) — that is the consumer's
1110 /// responsibility — so the consultation result does not change
1111 /// the handler's wire response. The call site is the documented
1112 /// integration point: production transport that fans typing
1113 /// events out to subscribers SHOULD consult this predicate
1114 /// before each per-recipient event.
1115 ///
1116 /// Group / channel chats are skipped on the kit side. The kit
1117 /// handler has no way to enumerate fan-out recipients; that work
1118 /// belongs to the consumer's transport layer, which must call
1119 /// this predicate per recipient with that recipient's
1120 /// `account_id`.
1121 ///
1122 /// # Default implementation
1123 ///
1124 /// Returns `Ok(false)` — no one is blocked. This is appropriate
1125 /// for backends that have not yet implemented contact lists, and
1126 /// it matches the workspace's "kit defines the hook; consumer
1127 /// enforces the policy" posture.
1128 fn is_contact_blocked(
1129 &self,
1130 _caller: &Self::CallerCtx,
1131 _account_id: &jmap_types::Id,
1132 _contact_id: &jmap_types::Id,
1133 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1134 async { Ok(false) }
1135 }
1136
1137 /// Authorization gate consulted by `handle_emoji_set` before every
1138 /// `CustomEmoji/set` create, update, or destroy.
1139 ///
1140 /// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11,
1141 /// "refactor: implementation-defined emoji authorization"):
1142 /// authorization for `CustomEmoji/set` is fully
1143 /// implementation-defined, for both server-global and Space-scoped
1144 /// emoji. When the caller is not authorized, the handler emits a
1145 /// `forbidden` SetError (RFC 8620 §5.3).
1146 ///
1147 /// # `target_space_id` semantics
1148 ///
1149 /// `target_space_id` is the **actual scope of the emoji this op
1150 /// targets**:
1151 ///
1152 /// - `None` — the emoji is server-global (its `spaceId` field is
1153 /// absent / null).
1154 /// - `Some(id)` — the emoji is scoped to that Space (its `spaceId`
1155 /// field equals `id`).
1156 ///
1157 /// For `Create`, the handler reads the scope from the create
1158 /// payload. For `Update` and `Destroy`, the handler pre-fetches
1159 /// the existing emoji via `get_objects` and passes its current
1160 /// `spaceId`. If the pre-fetch reports the id as not found, the
1161 /// handler skips this gate entirely and lets `update_object` /
1162 /// `destroy_object` surface a `notFound` SetError naturally — a
1163 /// non-existent target consumes no authorization decision.
1164 ///
1165 /// # When the handler calls this
1166 ///
1167 /// Exactly once per create/update/destroy entry in the request,
1168 /// AFTER wire-format validation has succeeded and BEFORE the
1169 /// corresponding `create_object` / `update_object` /
1170 /// `destroy_object` call. The handler skips the underlying mutation
1171 /// when the outer `Result` is `Ok(Err(_))` or when the outer is
1172 /// `Err(_)`. The wire mapping is:
1173 ///
1174 /// - `Ok(Ok(()))` — permit; the handler proceeds to the underlying
1175 /// `create_object` / `update_object` / `destroy_object`.
1176 /// - `Ok(Err(set_err))` — deny with reason; the handler serialises
1177 /// `set_err` into the appropriate `notCreated` / `notUpdated` /
1178 /// `notDestroyed` map verbatim. Backends construct the SetError
1179 /// with the type, description, and any `with_extra` fields the
1180 /// deployment wants the client to see.
1181 /// - `Err(e)` — backend infrastructure failure; the handler maps
1182 /// to a `serverFail` SetError.
1183 ///
1184 /// # Default implementation
1185 ///
1186 /// The default returns `Ok(Ok(()))` — every op is permitted. This
1187 /// matches the workspace's "kit defines the hook; consumer
1188 /// enforces the policy" posture (see the parallel design of
1189 /// [`Self::slow_mode_check`]). Production backends SHOULD override
1190 /// this method to apply the deployment's permission model — e.g.
1191 /// "only members of `target_space_id` may modify a Space-scoped
1192 /// emoji" or "only `manage_emoji` permission-holders may modify
1193 /// server-global emoji."
1194 ///
1195 /// # SetError shape recommendation
1196 ///
1197 /// Production backends SHOULD return
1198 /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1199 /// .with_description("…")))` for authorization denials, mirroring
1200 /// the workspace convention for /set responses. The description
1201 /// should explain the deployment's denial reason without leaking
1202 /// internal policy details — e.g. "Space-scoped emoji on this
1203 /// Space requires `manage_channels` permission" rather than
1204 /// "principal abc123 is not in role admin on Space xyz789".
1205 ///
1206 /// # Foundation seam
1207 ///
1208 /// Backends that wish to identify the caller call
1209 /// [`jmap_server::JmapBackend::principal_id`] on `caller` and
1210 /// compare against the Space's `members` list, ACLs, or whatever
1211 /// permission model the deployment uses. Backends whose
1212 /// `principal_id` returns `None` (the workspace default, see the
1213 /// "Caller identity (foundation seam)" section of the workspace
1214 /// `AGENTS.md`) cannot meaningfully implement identity-scoped
1215 /// authorization — they should either override `principal_id`
1216 /// first or return `Ok(Ok(()))` to match the reference posture.
1217 fn may_set_custom_emoji(
1218 &self,
1219 _caller: &Self::CallerCtx,
1220 _account_id: &jmap_types::Id,
1221 _target_space_id: Option<&jmap_types::Id>,
1222 _op: EmojiSetOp,
1223 ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1224 async { Ok(Ok(())) }
1225 }
1226
1227 /// Throttle gate consulted before a `Message/set` create lands on
1228 /// the rate-limited path.
1229 ///
1230 /// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec
1231 /// commit `de60acb` (2026-05-11, "soften slow-mode exemption to
1232 /// SHOULD with rationale"): a `Chat` with `slowModeSeconds > 0`
1233 /// throttles the rate at which a member may post messages. The
1234 /// spec SHOULD-exempts members holding the `manage_channels`
1235 /// permission, and servers MAY define additional exempt
1236 /// principals. The kit does not opine on the exemption set — the
1237 /// backend implements the policy.
1238 ///
1239 /// When the caller is throttled, the backend returns
1240 /// `Err(`[`SlowModeError`]`)` with `retry_after` set to a UTCDate
1241 /// the rate-limited sender may use to schedule a retry. The
1242 /// `Message/set` create handler maps the error onto a
1243 /// `rateLimited` SetError (RFC 8620 §5.3 `SetError.type`) whose
1244 /// `serverRetryAfter` extra field carries the UTCDate verbatim.
1245 ///
1246 /// # When the handler calls this
1247 ///
1248 /// `handle_message_set` invokes `slow_mode_check` once per create
1249 /// entry, after wire-format validation has succeeded and before
1250 /// `create_object`. A throttle rejection short-circuits to
1251 /// `notCreated[create_id] = { type: "rateLimited",
1252 /// serverRetryAfter: <UTCDate> }` and the create_object call is
1253 /// never made.
1254 ///
1255 /// # Default implementation
1256 ///
1257 /// The default returns `Ok(())` — no throttle. This is appropriate
1258 /// for backends that have not yet implemented rate-tracking and
1259 /// for single-tenant dev servers where no abuse path exists.
1260 /// Production backends SHOULD override this method with their own
1261 /// per-(account, chat, caller) rate tracker.
1262 ///
1263 /// # No state on the kit
1264 ///
1265 /// The kit deliberately does not provide a reference rate-tracker
1266 /// — that is deployment territory. The reference `MemoryBackend`
1267 /// keeps the default no-op behaviour for the same reason.
1268 fn slow_mode_check(
1269 &self,
1270 _caller: &Self::CallerCtx,
1271 _account_id: &jmap_types::Id,
1272 _chat_id: &jmap_types::Id,
1273 ) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
1274 async { Ok(()) }
1275 }
1276
1277 /// Hard-delete a message ("expire" it) due to a per-message expiry
1278 /// event.
1279 ///
1280 /// Called by the kit from two places:
1281 ///
1282 /// 1. The `Message/set` update handler when a patch sets `readAt` on
1283 /// a message whose pre-patch `burnOnRead` is `true`
1284 /// (draft-atwood-jmap-chat-00 §Message `burnOnRead`).
1285 /// 2. A deployment-provided scheduler when a message's
1286 /// `senderExpiresAt` fires (draft-atwood-jmap-chat-00 §Message
1287 /// `senderExpiresAt`). The kit does NOT run a scheduler;
1288 /// consumers wire one in and call this method directly when a
1289 /// timer fires.
1290 ///
1291 /// # Contract
1292 ///
1293 /// Per draft-atwood-jmap-chat-00, an expiry MUST hard-delete the
1294 /// row (not tombstone) and the message MUST appear in the
1295 /// `destroyed` set of subsequent `Message/changes` results.
1296 /// Implementations therefore SHOULD:
1297 ///
1298 /// - Remove the underlying record so a subsequent `Message/get`
1299 /// does not find it.
1300 /// - Bump the per-account `Message` state token and record the id
1301 /// in the change log so `Message/changes` sees it as destroyed.
1302 ///
1303 /// # Idempotency
1304 ///
1305 /// If the message no longer exists — because a previous
1306 /// `expire_message` call or an atomic `update_object`
1307 /// implementation has already deleted it — this method MUST
1308 /// return `Ok(())`, AND MUST NOT bump the per-account `Message`
1309 /// state token in that case. The no-op case must be
1310 /// observationally indistinguishable from "the scheduler never
1311 /// fired" for `Message/changes` subscribers; a state bump on the
1312 /// retry path would surface a spurious empty change set on every
1313 /// re-fire and induce a poll storm. Expiry events are
1314 /// inherently retry-friendly (a scheduler may re-fire if it
1315 /// crashed mid-batch) and the burn-on-read handler integration
1316 /// also treats a not-found backend response as a no-op. The
1317 /// return type is `Result<(), Self::Error>` (not
1318 /// `BackendSetError`) precisely to prevent a `NotFound`
1319 /// SetError construction on this path: expiry is an internal
1320 /// scheduler hook, not a `/set`-shaped call, and there is no
1321 /// JMAP wire surface for per-message expiry rejection.
1322 ///
1323 /// # Atomicity with `Message/set` update
1324 ///
1325 /// The reference burn-on-read handler integration calls
1326 /// `update_object` to apply the `readAt` patch and then calls
1327 /// `expire_message` as a separate step. A backend that wants
1328 /// strict atomicity between the `readAt` write and the hard-delete
1329 /// SHOULD override `update_object` to perform both inside a
1330 /// single transaction; in that case `expire_message` becomes
1331 /// idempotent for this code path (the message is already gone
1332 /// when the handler calls it).
1333 ///
1334 /// # Default implementation
1335 ///
1336 /// The default returns `Ok(())` without doing anything. This is
1337 /// appropriate for backends that have not yet implemented expiry
1338 /// or that handle the burn-on-read flow atomically inside their
1339 /// own `update_object`. Production backends that need expiry
1340 /// SHOULD override this method.
1341 fn expire_message(
1342 &self,
1343 _caller: &Self::CallerCtx,
1344 _account_id: &jmap_types::Id,
1345 _message_id: &jmap_types::Id,
1346 ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
1347 async { Ok(()) }
1348 }
1349}
1350
1351#[cfg(test)]
1352mod tests {
1353 use super::SlowModeError;
1354 use jmap_types::UTCDate;
1355
1356 #[test]
1357 fn slow_mode_error_display_contains_retry_after() {
1358 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1359 let rendered = format!("{err}");
1360 assert!(
1361 rendered.contains("slow-mode rate limit"),
1362 "Display missing prefix: {rendered}"
1363 );
1364 assert!(
1365 rendered.contains("2026-05-16T12:34:56Z"),
1366 "Display missing retry_after timestamp: {rendered}"
1367 );
1368 }
1369
1370 #[test]
1371 fn slow_mode_error_is_std_error() {
1372 // Compile-time check that SlowModeError implements std::error::Error.
1373 // If this fails to compile, the trait impl regressed.
1374 fn assert_is_error<E: std::error::Error>(_: &E) {}
1375 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1376 assert_is_error(&err);
1377 }
1378
1379 #[test]
1380 fn slow_mode_error_boxes_as_dyn_error() {
1381 // Independent oracle: the std error machinery itself. If
1382 // SlowModeError does not implement std::error::Error this
1383 // conversion does not compile.
1384 let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1385 let boxed: Box<dyn std::error::Error> = Box::new(err);
1386 assert!(boxed.to_string().contains("slow-mode rate limit"));
1387 }
1388
1389 use super::OpResult;
1390 use jmap_server::backend::{SetError, SetErrorType};
1391
1392 #[test]
1393 fn op_result_ok_carries_op_index_and_optional_id() {
1394 let r = OpResult::ok(3, Some(jmap_types::Id::from("space-1")));
1395 assert_eq!(r.op_index, 3);
1396 assert_eq!(r.outcome, Ok(Some(jmap_types::Id::from("space-1"))));
1397 }
1398
1399 #[test]
1400 fn op_result_ok_with_none_id_for_update_or_destroy() {
1401 let r = OpResult::ok(0, None);
1402 assert_eq!(r.op_index, 0);
1403 assert_eq!(r.outcome, Ok(None));
1404 }
1405
1406 #[test]
1407 fn op_result_err_carries_op_index_and_set_error() {
1408 let r = OpResult::err(7, SetError::new(SetErrorType::Forbidden));
1409 assert_eq!(r.op_index, 7);
1410 match r.outcome {
1411 Err(e) => assert_eq!(e.error_type, SetErrorType::Forbidden),
1412 Ok(_) => panic!("expected Err outcome"),
1413 }
1414 }
1415
1416 #[test]
1417 fn op_result_with_op_index_replaces_field() {
1418 let r = OpResult::ok(0, None).with_op_index(42);
1419 assert_eq!(r.op_index, 42);
1420 assert_eq!(r.outcome, Ok(None));
1421 }
1422
1423 #[test]
1424 fn op_result_with_outcome_replaces_field() {
1425 let r =
1426 OpResult::ok(0, None).with_outcome(Err(SetError::new(SetErrorType::InvalidProperties)));
1427 assert_eq!(r.op_index, 0);
1428 match r.outcome {
1429 Err(e) => assert_eq!(e.error_type, SetErrorType::InvalidProperties),
1430 Ok(_) => panic!("expected Err outcome after with_outcome"),
1431 }
1432 }
1433
1434 // Const-context smoke tests — lock in the const fn markers so a
1435 // future refactor that accidentally drops `const` from any of
1436 // these constructors / builders is caught at compile time
1437 // (bd:JMAP-x2gd.79).
1438
1439 use super::ChatLimits;
1440
1441 /// `OpResult::ok` is callable in const context.
1442 #[test]
1443 fn op_result_ok_is_const_fn() {
1444 const _R: OpResult = OpResult::ok(0, None);
1445 }
1446
1447 /// `ChatLimits::new` plus all four `with_*` setters chain in const
1448 /// context — proves the entire builder pipeline stays const.
1449 #[test]
1450 fn chat_limits_builder_is_const_fn() {
1451 const _LIMITS: ChatLimits = ChatLimits::new(1, 2, 3, 4)
1452 .with_max_roles_per_space(10)
1453 .with_max_space_members(20)
1454 .with_max_channels_per_space(30)
1455 .with_max_categories_per_space(40);
1456 }
1457
1458 // Note: `SlowModeError::new` is `const fn` (clippy::nursery
1459 // `missing_const_for_fn` would re-fire if the marker were dropped),
1460 // but a const-context smoke test cannot be authored without a
1461 // const-constructible `UTCDate`. `UTCDate` wraps a `String`, and
1462 // `String` is not const-constructible from a non-empty literal in
1463 // stable Rust today. The clippy lint covers the regression case.
1464}