Skip to main content

ChatAccessPolicy

Trait ChatAccessPolicy 

Source
pub trait ChatAccessPolicy: JmapBackend {
    // Provided methods
    fn is_contact_blocked(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        contact_id: &Id,
    ) -> impl Future<Output = Result<bool, Self::Error>> + Send { ... }
    fn may_broadcast_mention(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &Id,
        _space_id: &Id,
        _chat_id: &Id,
    ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send { ... }
    fn may_set_pinned_messages(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &Id,
        _chat_id: &Id,
    ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send { ... }
    fn may_send_message(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &Id,
        _chat_id: &Id,
    ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send { ... }
    fn may_view_chat(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &Id,
        _chat_id: &Id,
    ) -> impl Future<Output = Result<bool, Self::Error>> + Send { ... }
    fn validate_pinned_message_ids(
        &self,
        caller: &Self::CallerCtx,
        account_id: &Id,
        chat_id: &Id,
        added: &[Id],
    ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send { ... }
    fn slow_mode_check(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &Id,
        _chat_id: &Id,
    ) -> impl Future<Output = Result<(), SlowModeError>> + Send { ... }
}
Expand description

Chat and Message access gates: send, view, pins, broadcast mentions, slow mode, blocked contacts.

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

Provided Methods§

Source

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

Whether the ChatContact contact_id has blocked: true on the contact list of account_id.

Delivery paths call this per recipient: account_id is the recipient (the owner of the contact list) and contact_id is the sender’s or referenced ChatContact id in that account. draft-atwood-jmap-chat-00 §Blocked Contacts: “Typing and presence push events whose sending or referenced ChatContact has blocked: true on the receiving owner’s contact list are similarly dropped server-side before delivery to any of the owner’s clients”. §ChatContact id “identifies the ChatContact only on this server”, so contact_id is always resolved within account_id’s list; it is never looked up in the sender’s account.

§Callers

crate::should_push calls it with the push owner’s account and Message.senderId. crate::should_deliver_typing calls it with the typing event’s recipient and senderId. crate::project_presence calls it with the presence event’s recipient and contactId. crate::handle_chat_typing does not call it: the request carries the sender’s accountId, and the recipient’s account is known only to the transport that fans the event out, which calls crate::should_deliver_typing per recipient.

§Default implementation

Fetches contact_id from account_id with JmapReads::get_objects and returns its blocked field, or Ok(false) when account_id holds no such ChatContact. The callers pass the recipient’s caller, the same one they use to read the recipient’s Chat. Override this only when ChatContacts are not stored behind get_objects or a cheaper lookup exists.

Source

fn may_broadcast_mention( &self, _caller: &Self::CallerCtx, _account_id: &Id, _space_id: &Id, _chat_id: &Id, ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Authorization gate consulted by handle_message_set before a create or update with a non-empty broadcastMentions array is applied.

Per draft-atwood-jmap-chat-00 §BroadcastMention (jmap-chat-spec 77c3474 L462): sending a Message with a non-empty broadcastMentions array requires the "mention_broadcast" Space permission, and “Servers SHOULD reject Message/set create or update requests that would write a broadcast mention from a sender lacking this permission with forbidden.” This crate performs the recommended rejection by choice.

For group/direct chats NOT part of any Space (spaceId is None), broadcast mentions are unrestricted per spec; the handler skips calling this method entirely in that case.

§space_id semantics

space_id is the Space that contains the target Chat (channel). The handler resolves it by pre-fetching the Chat and reading its space_id field. This method is only called when space_id is Some — the handler skips the call for group/direct chats with no Space.

§chat_id semantics

chat_id is the target channel Chat, whose permissionOverrides apply: per draft-atwood-jmap-chat-00 §Space Permission Resolution, “When determining whether a member may perform an action in a channel Chat, servers MUST evaluate permissions in this order”, so an override may deny or allow mention_broadcast in one channel only.

§When the handler calls this

handle_message_set invokes may_broadcast_mention once per create entry or edit whose post-patch broadcastMentions is non-empty AND whose target Chat has a spaceId; rich-body "broadcast" spans are display-only and never trigger it (draft-atwood-jmap-chat-00 §Rich Body Format). The call fires AFTER structural validation (validate_broadcast_mentions) has succeeded and BEFORE create_object / update_object, so malformed payloads do not consume an authorization decision and an unauthorized message never touches storage.

§Default implementation

Returns Ok(Ok(())) — every op is permitted. This matches the workspace’s “kit defines the hook; consumer enforces the policy” posture (see the parallel design of SpacePolicy::may_set_custom_emoji). Production backends SHOULD override this method to check the caller’s mention_broadcast permission in the target channel, resolved per §Space Permission Resolution (see resolve_channel_permissions).

§SetError shape recommendation

Production backends SHOULD return Ok(Err(SetError::new(SetErrorType::Forbidden) .with_description("sender lacks mention_broadcast permission in this channel"))).

Source

fn may_set_pinned_messages( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat_id: &Id, ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Authorization gate consulted by handle_chat_set before an update whose patch touches pinnedMessageIds is applied.

Per draft-atwood-jmap-chat-00 §Chat pinnedMessageIds: “For group chats, only admins may modify this list. For direct chats, the owner may modify it freely. For channel chats, only members with the "pin" Space permission may modify this list.” For a channel the "pin" permission is resolved per §Space Permission Resolution, so the channel’s permissionOverrides apply.

§When the handler calls this

Once per update entry whose patch sets pinnedMessageIds (or a pointer path beneath it), AFTER wire-format validation and BEFORE update_object. A chat_id that does not resolve SHOULD yield Ok(Ok(())) so update_object surfaces notFound. The return mapping is the same as SpacePolicy::may_set_custom_emoji.

§Default implementation

Returns Ok(Ok(())) — every op is permitted, matching the parallel hooks above. Production backends SHOULD override this method and deny with Ok(Err(SetError::new(SetErrorType::Forbidden))).

Source

fn may_send_message( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat_id: &Id, ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Authorization gate consulted by handle_message_set before each Message create.

Per draft-atwood-jmap-chat-00 §Message/set (jmap-chat-spec 77c3474 L1218): “The server SHOULD verify the sender is a current member of the target Chat. For group chats, this means a ChatMember record exists; for channel chats, the sender must be a member of the containing Space. Non-members SHOULD receive a SetError of type forbidden.” and (L1220) “For channel Chats, the server SHOULD verify the sender holds the "send" permission (resolved per {{space-permissions}}) before accepting the message; if absent, the server SHOULD return a SetError of type forbidden.” The handler performs these recommended checks by choice. resolve_channel_permissions implements that resolution.

§When the handler calls this

Once per create entry, AFTER wire-format validation and the closed-Chat and closed-Space checks, and BEFORE create_object. A chat_id that does not resolve SHOULD yield Ok(Ok(())) so create_object surfaces the normal error. The return mapping is the same as SpacePolicy::may_set_custom_emoji.

§Default implementation

Returns Ok(Ok(())) — every create is permitted, matching the parallel hooks above. Production backends SHOULD override this method and deny with Ok(Err(SetError::new(SetErrorType::Forbidden))).

Source

fn may_view_chat( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat_id: &Id, ) -> impl Future<Output = Result<bool, Self::Error>> + Send

Visibility gate consulted by handle_message_get and handle_message_query.

Per draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474 L1301): “For channel Chats, the server SHOULD verify the caller holds the "view" permission before returning messages in Message/get or Message/query responses; messages in channels the caller cannot view SHOULD be omitted.” The handlers perform this recommended check by choice. The permission is resolved per §Space Permission Resolution, as in Self::may_send_message.

§When the handler calls this

Message/get calls it once per distinct chatId among the returned messages; Ok(false) hides those messages, and a requested id is reported as notFound. Message/query calls it for the filter’s top-level chatId and returns no ids when it yields Ok(false). A query without chatId spans Chats, so the backend’s query_objects MUST itself omit messages the caller cannot view; the handler cannot filter a page it did not cut. Message/changes does not consult this hook, because the spec defines it as plain “Standard JMAP /changes”.

§Default implementation

Returns Ok(true), so every Chat is viewable, matching the parallel hooks above. Production backends SHOULD override this method.

Source

fn validate_pinned_message_ids( &self, caller: &Self::CallerCtx, account_id: &Id, chat_id: &Id, added: &[Id], ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Referential check consulted by handle_chat_set before an update that adds ids to pinnedMessageIds is applied.

Per draft-atwood-jmap-chat-00 §Chat pinnedMessageIds: “Each id MUST be the id of a Message in this Chat; the server MUST reject a Chat/set update that would add any other id with invalidProperties.”

§When the handler calls this

After Self::may_set_pinned_messages permits the update and BEFORE update_object, with added holding only the ids in the new list that are not already in the stored list. Ids already pinned are not re-checked: the requirement covers adding, and a stale id left behind by a backend that missed a hard delete must not make the list impossible to edit. Not called when added is empty or chat_id does not resolve.

Return Ok(Err(SetError)) with type invalidProperties and properties ["pinnedMessageIds"] when any id in added is not a Message whose chatId is chat_id.

§Default implementation

Fetches added with JmapReads::get_objects and accepts only when every id comes back as a Message whose chatId is chat_id. Override this only when Messages are not stored behind get_objects or a cheaper lookup exists.

Source

fn slow_mode_check( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat_id: &Id, ) -> impl Future<Output = Result<(), SlowModeError>> + Send

Throttle gate consulted before a Message/set create lands on the rate-limited path.

Per draft-atwood-jmap-chat-00 §Chat slowModeSeconds plus spec commit de60acb (2026-05-11, “soften slow-mode exemption to SHOULD with rationale”): a Chat with slowModeSeconds > 0 throttles the rate at which a member may post messages. The spec SHOULD-exempts members holding the manage_channels permission, and servers MAY define additional exempt principals. The kit does not opine on the exemption set — the backend implements the policy.

When the caller is throttled, the backend returns Err(SlowModeError) with retry_after set to a UTCDate the rate-limited sender may use to schedule a retry. The Message/set create handler maps the error onto a rateLimit SetError (RFC 8620 §5.3 SetError.type) whose serverRetryAfter extra field carries the UTCDate verbatim.

§When the handler calls this

handle_message_set invokes slow_mode_check once per create entry, after wire-format validation has succeeded and before create_object. A throttle rejection short-circuits to notCreated[create_id] = { type: "rateLimit", serverRetryAfter: <UTCDate> } and the create_object call is never made.

§Default implementation

The default returns Ok(()) — no throttle. This is appropriate for backends that have not yet implemented rate-tracking and for single-tenant dev servers where no abuse path exists. Production backends SHOULD override this method with their own per-(account, chat, caller) rate tracker.

§No state on the kit

The kit deliberately does not provide a reference rate-tracker — that is deployment territory. The reference MemoryBackend keeps the default no-op behaviour for the same reason.

Dyn Compatibility§

This trait is not dyn compatible.

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

Implementors§

Source§

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

Available on crate feature memory only.
Source§

impl<T: DelegateChatAccessPolicy> ChatAccessPolicy for T