Skip to main content

ChatSpaces

Trait ChatSpaces 

Source
pub trait ChatSpaces: JmapBackend {
    // Required methods
    fn generate_invite_code(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
    ) -> impl Future<Output = Result<String, Self::Error>> + Send;
    fn join_space_with_invite(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        invite_id: &Id,
        joined_at: &UTCDate,
    ) -> impl Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send;
    fn apply_space_patch(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        space_id: &Id,
        ops: Vec<SpacePatchOp>,
    ) -> impl Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
    fn apply_space_metadata_patch(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        space_id: &Id,
        patch: SpaceMetadataPatch,
    ) -> impl Future<Output = Result<Option<Space>, BackendSetError<Self::Error>>> + Send;
    fn everyone_permissions(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        space: &Space,
    ) -> impl Future<Output = Result<HashSet<ChatPermission>, Self::Error>> + Send;

    // Provided methods
    fn space_extension_properties(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
    ) -> &'static [&'static str] { ... }
    fn protect_last_admin(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
    ) -> bool { ... }
}
Expand description

Space structure: invites, joins, member and role patches, and Space-wide settings.

Part of ChatBackend (docs/design/chat-backend-split.md).

Required Methods§

Source

fn generate_invite_code( &self, caller: &Self::CallerCtx, account_id: &Id, ) -> impl Future<Output = Result<String, Self::Error>> + Send

Generate a cryptographically random invite code.

Implementations MUST use a CSPRNG seeded from OS entropy. The recommended choices are rand::rngs::OsRng or the getrandom crate directly. Do NOT use rand::thread_rng() for security-relevant output: although current rand versions document ThreadRng as cryptographically secure, its underlying algorithm is implementation-defined and has changed across releases, and the rand book explicitly routes security-sensitive callers to OsRng.

The returned string must be unguessable — do NOT use timestamps, sequential counters, or non-CSPRNG sources.

§Output shape contract

Implementations MUST satisfy ALL of the following for the kit’s constant-time-compare guarantee (see below) to hold:

  1. Fixed length across calls. Every invocation of generate_invite_code on a single backend MUST return a string of the same byte length. A backend that returns variable-length codes leaks a length oracle through the constant-time-compare timing channel: ct_eq returns Choice(0) cheaply on length mismatch, so an attacker can learn whether their candidate code matches the stored length even when the content compare is constant-time.
  2. Minimum 128 bits of CSPRNG entropy. The reference MemoryBackend impl in this crate (in memory.rs) emits 32 lowercase-hex characters (16 bytes = 128 bits) which is the workspace floor. Production backends MAY use more; less is forbidden. The trait method itself is abstract — no default impl — so backends MUST provide one.
  3. ASCII-safe encoding. The returned bytes MUST be 7-bit ASCII printable, byte-length-equal-to-char-length, and safe to use as-is in JMAP wire format and HTTP-style URL paths (no /, +, =, or whitespace). Recommended encodings: lowercase hex (the default), base32 unpadded, base64url unpadded. Plain base64 with / is forbidden because downstream URL-encoded redemption flows misroute the slash. Non-ASCII output is forbidden because helpers that take byte-prefix slices (e.g. the iso8601_before partial-comparison family) panic on multi-byte UTF-8 boundaries.
  4. Sufficient lifespan. Codes MUST remain discriminable from each other across the backend’s retention window. With 128 bits of entropy and well-mixed CSPRNG output, collision probability is cryptographically negligible up to 2^64 active codes.

A backend that cannot meet any of points 1–3 MUST NOT expose Space/join’s invite-code redemption path, or MUST build its own redemption with a different constant-time argument. The kit’s handle_space_join assumes the contract without re-validating each code’s shape.

§Constant-time comparison contract

Consumers of the returned code (notably Space/join invite-code lookup) MUST compare it against attacker-supplied values in constant time using subtle::ConstantTimeEq::ct_eq or equivalent. The reference handler in space::handle_space_join already does this; backends that build their own invite-redemption paths must preserve the invariant. A plain String == String short-circuits at the first mismatched byte and exposes a byte-by-byte timing oracle for credential recovery.

§Errors

A backend that cannot mint a code (entropy starvation, an unreachable HSM or KMS) returns Err; SpaceInvite/set reports that create as serverFail. Never fall back to a predictable code.

caller and account_id identify the SpaceInvite create the code is for, so a backend can scope its entropy source per account.

Source

fn join_space_with_invite( &self, caller: &Self::CallerCtx, account_id: &Id, invite_id: &Id, joined_at: &UTCDate, ) -> impl Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send

Redeem the SpaceInvite invite_id for Space/join: add the owner (member entry account_id, no roles, joinedAt = joined_at) to the invite’s Space and increment the invite’s uses.

Per draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474 L1416): “The uses increment and membership insertion SHOULD be performed within a single atomic operation so that concurrent redemptions cannot exceed maxUses.” This crate requires the recommended atomicity by choice.

§Atomicity contract

The uses < maxUses check, the already-member check, the member append and the uses increment MUST all take effect or none, and MUST be serialized against concurrent redemptions of the invite and concurrent membership writes to the Space (a transaction or compare-and-swap). Composing this from update_object calls loses that guarantee: a failed second write leaves a member admitted without a use counted, and concurrent joins both pass maxUses.

§Account scope

account_id is the request’s accountId, which names the account hosting the Space; the handler resolves the invite code only within that account, and invite_id and its Space live there. Implementations need no server-wide invite-code index.

§When the handler calls this

Once, after the invite resolved by code and is unexpired, and after the ban and closedAt checks. The handler maps each InviteJoinRefusal to the draft’s invalidArguments method error. There is no default: a non-atomic default would reinstate the race.

Source

fn apply_space_patch( &self, caller: &Self::CallerCtx, account_id: &Id, space_id: &Id, ops: Vec<SpacePatchOp>, ) -> impl Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send

Apply a sequence of structural mutations to a Space (draft-atwood-jmap-chat-00 §Space/set).

Space/set update operations use semantic mutation keys (addRoles, removeRoles, addMembers, …) rather than RFC 8620 JSON Pointer patches. The handler in space::handle_space_set parses the wire object, unfolds each array entry into a SpacePatchOp value, then calls this method with the resulting ordered Vec.

§Authorisation contract

Implementors MUST verify that caller may act as the owner of account_id before applying any op, and MUST return BackendSetError::SetError with SetErrorType::Forbidden for the whole call otherwise; the handler reports it in notUpdated. The per-op permission and role-hierarchy gates under “Per-op error semantics” are also enforced here, atomically with the mutation. See ChatStore::create_object for the workspace-canonical rationale.

§Ordering and atomicity

Implementations SHOULD apply ops in input order and SHOULD provide best-effort transactional semantics so that a partial failure does not leave the Space in a half-updated state. The reference in-memory implementation locks the entire backend for the duration of the call. A database-backed implementation should wrap the sequence in a single transaction.

§Permission and limit checks

Permission gates (manage_space, manage_roles, manage_members, manage_channels) are backend-canonical per workspace AGENTS.md “Caller identity (foundation seam)”: the reference handler does NOT apply gates before calling this method, and the backend is responsible for rejecting any op the caller is not authorized to perform.

Per-aggregate count limits on roles, members, channels, and categories per Space are backend-canonical as of bd:JMAP-x2gd.44: the backend MUST query its own ChatSettings::limits, project the post-patch counts for the target Space, and reject the whole patch with an overQuota SetError (RFC 8620 §5.3) if any aggregate would exceed its cap. The cap enforcement MUST be atomic with the mutation itself — typically inside the same database transaction or the same mutex critical section. Per draft-atwood-jmap-chat-00 §Space/set (spec commit 80d5e11, 2026-05-11), this behavior is normative.

The handler at crate::space::handle_space_set additionally runs a defense-in-depth pre-flight cap check before this method, but the pre-flight is non-load-bearing: a backend caller that bypasses the JMAP wire layer (admin tool, federation receiver, internal batch importer) and calls apply_space_patch directly MUST still see caps enforced. The pre-flight exists only to surface overQuota to the client as a single SetError without consuming a backend round-trip; backends MAY rely on the handler having pre-checked for performance, but MUST NOT rely on it for correctness.

The role-position hierarchy check (members may only add or modify roles whose position is strictly less than their own highest-position role — draft §Space/set L1260, L1266) MUST be enforced by the backend because it is atomic with the mutation and depends on the current Space state.

§Cross-type cascade contract

Several SpacePatchOp variants have side effects on other JMAP types in the chat extension (Chat, Message). The wire-format Space/set response describes only the Space-side change, but /changes subscribers on the cascaded types depend on the backend bumping the relevant type state tokens. A backend that performs the cross-type mutations but forgets the state bumps silently desynchronises every multi-client subscriber — the failure is invisible to single-tenant smoke tests.

The required cascades are:

  • RemoveChannel — MUST destroy the channel-kind Chat record and every Message whose chatId matches the removed channel (draft §Space/set L1283: “Cascades to all Messages in those channels.”), and the channel’s ReadPosition (draft §ReadPosition: the server “destroys it when the Chat is destroyed”). The Chat, Message and ReadPosition type state tokens MUST bump so their /changes subscribers see the destruction.

  • RemoveCategory — MUST clear Chat.categoryId on every channel-kind Chat whose categoryId named the removed category (the channels fall back to uncategorized). The Chat type state token MUST bump and the affected channel ids MUST appear in the next Chat/changes entry’s updated list.

  • AddCategory / UpdateCategory with a non-empty channelIds array — MUST set Chat.categoryId on each named channel (relocating it from its previous category or from uncategorized). The Chat type state token MUST bump and the relocated channel ids MUST appear in Chat/changes updated. This pins a regression class where channel relocations silently bypass the Chat/changes log; a backend that mutates Chat.categoryId without bumping the Chat state token desynchronises every multi-client subscriber.

  • RemoveRole — MUST strip the removed role id from roleIds on every SpaceMember of this Space (draft §Space/set L1263). Members embed directly in Space, so the cascade is captured by the existing Space state bump; no separate Member/changes rotation is required.

  • RemoveMember — MUST remove the member entry and keep Space.memberCount consistent with members.len(). The spec does not mandate cascade to the member’s ReadPosition records; the reference impl leaves them in place and treats ReadPosition cleanup as implementation-defined. A backend that destroys orphaned ReadPositions MUST bump the ReadPosition type state token; a backend that retains them MUST NOT.

State-token bumps SHOULD be batched per call: one bump per affected type per apply_space_patch invocation, not one bump per op. The reference impl combines every channel created, updated, and destroyed by a patch into a single Chat/changes entry; doing the same in production keeps /changes rotation rates proportional to client-visible mutations rather than to internal op count.

§Server-set field invariants

Server-set fields on the target Space (memberCount, updatedAt, and any future analogous cached aggregates) MUST be kept consistent with the post-mutation state. Specifically, after any combination of AddMember and RemoveMember ops, Space.memberCount MUST equal Space.members.len() as observed by the next Space/get. Backends MAY store these as cached values that they recompute on every mutation, or MAY compute them lazily at read time; either is acceptable as long as Space/get returns values consistent with the returned members array. The natural-minimal “persist memberCount once and trust it” implementation is not correct: subsequent mutations to members would let memberCount drift silently.

Space.closedAt is server-set the same way: when the caller removes themselves as the last member holding manage_space and other members remain, the backend MUST set closedAt in the same mutation (draft §Space/set removeMembers). The handler rejects every other update to a closed Space.

§Per-op error semantics

Backend rejections that originate from a single op carry both a typed SetErrorType and a human-readable description string. The kit’s integration tests pin specific (SetErrorType, description-substring) pairs for the common failure modes; a backend that returns a different variant or an empty description will fail those tests when plugged in.

The following table records the contract for the failure modes the kit exercises today:

Op + failure modeSetErrorTypedescription MUST contain
Any op, caller lacks the spec-mandated permissionForbiddenthe permission identifier as a substring ("manage_space", "manage_channels", "manage_members", "manage_roles", or a deployment-specific permission name)
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"
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-removalInvalidProperties (properties: the patch key(s) concerned, among removeRoles, updateRoles, removeMembers, updateMembers)"last-admin" or "manage_members"
AddMember with userId already a memberInvalidProperties (properties: ["userId"])implementation-defined; the reference impl names the duplicate userId
AddMember with a roleId that does not name a role on this SpaceInvalidProperties (properties: ["roleIds"])implementation-defined; the reference impl names the unknown roleId
RemoveRole / RemoveChannel / RemoveCategory with an id that does not exist on this SpaceNotFoundimplementation-defined; the reference impl names the missing id

The “MUST contain … as a substring” rule on permission-denied failures lets downstream UI / CLI consumers route permission-request flows by parsing the description, and lets users see “Permission denied: missing manage_space” rather than a bare “Permission denied”. Deployments that need a programmatic alternative SHOULD additionally surface the missing permission via SetError::with_extra under a deployment-specific key — substring matching is the floor, not the ceiling.

Note on routing: per-op rejections normally surface inside the returned OpResult vector, NOT as a top-level BackendSetError return. The handler at crate::space::handle_space_set applies the kit’s per- update-target atomicity: any failing op in the patch fails the whole update target, so the test fixtures see the first-failing op’s (SetErrorType, description) surface on notUpdated[<spaceId>]. The table above describes the per-op outcome content; the handler does not synthesise new variants or rewrite descriptions.

§Return value

On success, returns a Vec<OpResult> of the same length as ops, in input order. Each entry reports the outcome of one op (id assignment for Add* variants, error for rejections). The handler maps per-op errors back into the /set response shape per OpResult’s documentation.

Returns BackendSetError::Other only for backend-level failures (the storage layer is unreachable, the account does not exist, space_id is unknown, etc.) — i.e. failures that prevent any op from being attempted. Per-op rejections (permission denied, invalid id, role hierarchy violation, etc.) go in the outcome field of the returned OpResult vector, not in an error return.

Source

fn apply_space_metadata_patch( &self, caller: &Self::CallerCtx, account_id: &Id, space_id: &Id, patch: SpaceMetadataPatch, ) -> impl Future<Output = Result<Option<Space>, BackendSetError<Self::Error>>> + Send

Apply a JSON Merge Patch to a Space’s top-level metadata fields (draft-atwood-jmap-chat-00 §Space/set, name, description, iconBlobId, isPublic, isPubliclyPreviewable).

Space/set update operations carrying only top-level metadata fields (and not the semantic-mutation keys addRoles / addMembers / addChannels / addCategories etc.) route through this method instead of the generic ChatStore::update_object. Mixed patches carrying both top-level metadata AND semantic-mutation keys call Self::apply_space_patch first (for the structural ops) and this method second (for the metadata). The handler at space::handle_space_set is responsible for the split and for stripping non-metadata keys before calling this method.

§Authorisation contract

Implementors MUST verify that caller may act as the owner of account_id before applying the patch and MUST return BackendSetError::SetError with SetErrorType::Forbidden otherwise. See ChatStore::create_object for the workspace-canonical rationale; the same rule applies here.

§Permission and atomicity

Per draft-atwood-jmap-chat-00, every top-level metadata field carries the marker “Mutable by members with manage_space permission”. Implementations MUST gate the mutation on the caller’s effective permissions in the target Space: verify the caller holds manage_space (resolved through the Space’s role hierarchy) and reject the patch with SetErrorType::Forbidden if not. The caller is the owner, whose members entry is the account_id (draft §Terminology), so look the caller up by account_id, not by the principal, whether or not JmapAccounts::principal_id returns Some; the same holds for every caller-membership or permission check in this trait.

The check fires inside this method atomically with the mutation: snapshot the Space’s role/member state, evaluate the permission gate, and apply the merge patch in one critical section. Backend canonical per workspace AGENTS.md.

§patch shape

The handler decodes the wire patch’s metadata-key subset (name, description, iconBlobId, isPublic, isPubliclyPreviewable) into a SpaceMetadataPatch, stripping structural mutation keys (addRoles etc.) before building it. Each field is Option<_>; nullable target fields use Option<Clearable<T>> so the backend can distinguish “wire null” (clear) from “absent” (unchanged). Backends MAY validate the values further (e.g. reject an icon_blob_id referencing a non-existent blob) and surface those as SetError returns. The expected SetErrorType for value-level validation failures is SetErrorType::InvalidProperties with the offending field name in properties — see the “Diagnostic content convention” section below for the blob-not-found shape specifically. (RFC 8620 §5.3 defines blobNotFound only as a method-level error; at the SetError level it surfaces as InvalidProperties naming the offending blob-id field.)

§Return value

The discriminator between Ok(Some(space)) and Ok(None) is the wire-visible Space shape:

  • Return Ok(None) if the wire-visible Space (the shape Space/get would serialise after applying this patch) is identical to the result of mechanically applying the patch keys to the prior state with no additional server-side modification. The handler can then build the /set updated entry from the input patch alone with no extra fetch.
  • Return Ok(Some(space)) if the backend modified any wire-visible property beyond what the client requested (RFC 8620 §5.3 server-set field echo, e.g. a normalised name, a derived iconBlobId, a server-bumped memberCount, or any spec-defined server-set field that Space/get would return). The handler echoes the returned Space to the client.

Server-internal bookkeeping that is NOT part of the wire-visible Space shape (e.g. private last-touched timestamps used only for /changes cache-keying, internal sequence numbers) MUST NOT itself drive the Some path — the discriminator is “would Space/get return a different shape?”, not “did the backend touch anything internally?”. A backend that bumps an internal timestamp on every metadata patch correctly returns Ok(None) when the wire shape is otherwise unchanged.

Err(BackendSetError::SetError(e)) with e.kind == SetErrorType::Forbidden when the caller fails the manage_space gate.

§Diagnostic content convention

The SetError.description on a manage_space-gate rejection MUST contain "manage_space" as a substring. The kit’s integration tests assert this (e.g. tests/space_metadata_apply.rs); a backend that returns a bare SetError::new(SetErrorType::Forbidden) with no description will fail those tests. Build the error via SetError::new(SetErrorType::Forbidden).with_description( "manage_space permission required") (or any other string that contains the literal "manage_space").

Future blob-validation rejections (e.g. iconBlobId referencing a non-existent blob, see the patch shape section above) SHOULD surface as SetErrorType::InvalidProperties with properties: ["iconBlobId"] and a description that names the offending blob id. The reference impl does not validate blobs today; production backends with a blob store SHOULD.

Rationale for the separate metadata patch method: routing top-level metadata through the generic update_object::<Space> would bypass the permission gate, since the generic path is not permission-aware. This method exists so that top-level Space/set update requests carrying only metadata fields (name / description / iconBlobId / isPublic / isPubliclyPreviewable) route through a manage_space-gated path instead.

Source

fn everyone_permissions( &self, caller: &Self::CallerCtx, account_id: &Id, space: &Space, ) -> impl Future<Output = Result<HashSet<ChatPermission>, Self::Error>> + Send

The permissions of the implicit @everyone role in space, the account account_id’s Space.

Every member holds that role, “which serves as the permission floor” (draft-atwood-jmap-chat-00 §SpaceRole, jmap-chat-spec 29e9a41 L812), and §Space Permission Resolution step 1 (L1705) unions its permissions with the member’s SpaceRoles. The draft puts them on no wire object, so the backend decides where each Space’s set is stored. The chat bindings (jmap-chat-filenode-server, jmap-chat-vtc-server) and the Peer/deliver handler of jmap-chat-federation-server read it here.

No default: a permission floor has no neutral value.

Provided Methods§

Source

fn space_extension_properties( &self, caller: &Self::CallerCtx, account_id: &Id, ) -> &'static [&'static str]

Extra top-level Space properties owned by a Space extension, such as calendarId (draft-atwood-jmap-chat-calendars-00 §calendarId) or taskListId (draft-atwood-jmap-chat-tasks-00 §taskListId).

Space/set accepts a listed key instead of rejecting it as invalidProperties. On create, a non-null value is stored in jmap_chat_types::Space::extra through create_object. In an update patch, the key travels in SpaceMetadataPatch::extra through Self::apply_space_metadata_patch, so it is subject to that method’s manage_space gate; a null value removes the property (RFC 7396). Space/get returns stored values like any other property. The non-member restricted view omits them.

The handler does not validate values. A backend that must check one (for example, that taskListId names an existing TaskList on the same account) rejects it in create_object or apply_space_metadata_patch with an invalidProperties SetError naming the key. A listed key that is already a core Space property or a structural patch key keeps its core meaning.

§Default implementation

Returns an empty list, so no extension property is accepted. Backends that implement a Space extension override it.

Source

fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &Id) -> bool

Whether the backend should reject any Self::apply_space_patch that would leave the target Space with zero members holding either manage_members or manage_space permission.

§Invariant (by outcome, not by op type)

The protection is invariant on the post-patch state of the (member, role, permission) graph, not on any single op variant. A backend that returns true from this method MUST reject every patch that takes the Space from at least one member holding manage_members or manage_space to none, including (non-exhaustively) the cases below. Self-removal (a removeMembers holding only the accountId, which references the owner per draft §Terminology) is exempt: draft §Space/set says “Last-administrator protection does not apply to self-removal.”

  • RemoveMember that removes the last admin member.
  • UpdateMember that strips a role granting manage_members or manage_space from a member who holds no other such role.
  • UpdateRole that removes manage_members or manage_space permission from a role currently held by the last admin.
  • RemoveRole that drops a permission-granting role from the graph when no other role grants the same permission to a remaining member.
  • Any combination of the above within a single ops vector whose cumulative effect is zero admins.

Production backends should project the post-patch graph and reject when the admin count would reach zero, regardless of which op caused the transition.

§Why this exists

The 2026-05-12 design reversal dropped the Space.ownerId field: “who controls a Space” is now fully implementation-defined / out-of-band per draft-atwood-jmap-chat-00. Without a normative owner identity, the kit cannot enforce the previous “owner cannot be removed” rule. Instead the kit exposes this purely permission-graph-based knob: production backends that want to prevent the “no admin left” failure mode return true (the trait default); deployments with their own designated controller principal or external admin-tracking system can opt out by returning false.

§Default implementation

Returns true — production-safe by default. A third-party backend that does not override this method gets last-admin protection automatically.

§Why the reference MemoryBackend overrides this to false

The reference impl flips the default to keep existing integration tests (which do not seed admin memberships) passing unchanged. Tests that exercise the protection path opt in via MemoryBackend::set_protect_last_admin_for_test(true).

§Atomicity

The check fires inside Self::apply_space_patch atomically with the candidate mutation: the backend snapshots the Space’s member/role state, projects the post-patch admin count across all ops in the patch (member adds/removes, role-id changes, permission edits), and rejects the whole update target with an invalidProperties SetError naming the patch key(s) concerned if zero admins would remain (draft §Space/set removeMembers: “a refusal names the patch key concerned”).

§Why sync, not async

This predicate is a deployment-policy flag: a backend either enforces the last-admin invariant or it does not. Backends that consult an external admin-tracking service to derive the answer SHOULD cache the per-account boolean and answer from the cache. See the trait-level “Async vs sync method convention” section above for the workspace rationale.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<C: MemoryCaller> ChatSpaces for MemoryBackend<C>

Available on crate feature memory only.
Source§

impl<T: DelegateChatSpaces> ChatSpaces for T