Skip to main content

jmap_chat_server/
permissions.rs

1//! Pure permission-vocabulary helpers for backend authorization gating.
2//!
3//! This module hosts pure (no I/O, no state) mappings from server-side
4//! mutation values onto the [`ChatPermission`] vocabulary defined by
5//! draft-atwood-jmap-chat-00 §SpaceRole `permissions` and gated per
6//! §Space/set. Backend implementations of
7//! [`ChatSpaces::apply_space_patch`](crate::ChatSpaces::apply_space_patch) consume these helpers to gate
8//! per-op authorization after resolving the caller's effective
9//! permission set in a Space.
10//!
11//! Per workspace AGENTS.md "backend canonical" policy, handlers MUST NOT
12//! call these helpers for permission gating — only backends do.
13//!
14//! [`ChatSpaces::apply_space_patch`](crate::ChatSpaces::apply_space_patch): crate::ChatSpaces::apply_space_patch
15
16use std::collections::HashSet;
17
18use crate::SpacePatchOp;
19use jmap_chat_types::{ChannelPermission, ChatPermission};
20
21/// Resolve a member's effective permissions in one channel Chat, per
22/// draft-atwood-jmap-chat-00 §Space Permission Resolution.
23///
24/// `space_permissions` is step 1, the union of `permissions` across every
25/// SpaceRole the member holds, including the implicit `@everyone` role.
26/// `space_id` is the id of the Space holding the channel, `role_ids` are
27/// the SpaceRole ids the member holds, `member_id` is its SpaceMember
28/// `id`, and `overrides` is the channel's `permissionOverrides`. Steps 2
29/// to 5 then apply, in order: `deny` of role-targeted records matching
30/// `role_ids` or `space_id`, their `allow`, `deny` of the record
31/// targeting `member_id`, and its `allow`.
32///
33/// Within one step every entry has the same effect (remove or add), so
34/// the draft's "ascending position order" for role-targeted records
35/// cannot change the result and is not consulted.
36///
37/// Records whose `targetType` is neither `"role"` nor `"member"` match
38/// nothing. Every member holds the implicit `@everyone` role, which has
39/// no SpaceRole id; a role-targeted record whose `targetId` is
40/// `space_id` addresses it (§ChannelPermission `targetId`: "A record
41/// with `targetType: "role"` whose `targetId` is the id of the Space
42/// itself addresses the implicit `@everyone` role"), so it matches every
43/// member.
44///
45/// A `deny` entry removes every permission with the same wire string
46/// ([`ChatPermission::as_str`]), so a forged
47/// [`ChatPermission::Other`] spelling of a known name still denies it;
48/// an `allow` entry adds the permission as given, so such a spelling
49/// never grants the known variant.
50pub fn resolve_channel_permissions(
51    space_permissions: HashSet<ChatPermission>,
52    space_id: &str,
53    member_id: &str,
54    role_ids: &HashSet<&str>,
55    overrides: &[ChannelPermission],
56) -> HashSet<ChatPermission> {
57    let role_records: Vec<&ChannelPermission> = overrides
58        .iter()
59        .filter(|o| {
60            let target = o.target_id.as_ref();
61            o.target_type.as_str() == "role" && (target == space_id || role_ids.contains(target))
62        })
63        .collect();
64    let member_records: Vec<&ChannelPermission> = overrides
65        .iter()
66        .filter(|o| o.target_type.as_str() == "member" && o.target_id.as_ref() == member_id)
67        .collect();
68    let mut perms = space_permissions;
69    for records in [role_records, member_records] {
70        for o in &records {
71            for p in &o.deny {
72                perms.retain(|q| q.as_str() != p.as_str());
73            }
74        }
75        for o in &records {
76            perms.extend(o.allow.iter().cloned());
77        }
78    }
79    perms
80}
81
82/// Result of [`required_permissions_for_op`] — typed alternative to
83/// a sentinel-string return value.
84///
85/// `SpacePatchOp` is `#[non_exhaustive]` upstream, so a future-added
86/// variant cannot be matched at compile time from this downstream
87/// crate. The [`UnknownOp`](Self::UnknownOp) arm signals that
88/// situation explicitly; backends MUST reject ops that produce
89/// `UnknownOp` rather than treating an empty permission set as
90/// "no permissions required".
91///
92/// The enum is `#[non_exhaustive]` so future variants (e.g. a
93/// `Conditional` arm carrying a runtime predicate) can be added
94/// without a SemVer break. Match arms in consumer code should
95/// include a `_ => { /* fail closed */ }` catch-all.
96#[non_exhaustive]
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum RequiredPermissions {
99    /// The op's permission requirement is known and enumerated by
100    /// the draft. The contained slice is the list of permissions
101    /// the caller MUST hold to apply this op. A caller's
102    /// effective-permission set must be a superset of this slice.
103    Known(&'static [ChatPermission]),
104    /// The op variant is not recognized by this version of
105    /// `required_permissions_for_op`. This happens when a
106    /// downstream-extended [`SpacePatchOp`] adds a new variant
107    /// that the kit predates. Backends MUST reject the op rather
108    /// than authorize it as zero-permissions-required.
109    UnknownOp,
110}
111
112/// Returns the set of permissions required to apply this
113/// [`SpacePatchOp`] variant, per draft-atwood-jmap-chat-00 §Space/set
114/// L1256-1295 (jmap-chat-spec 91672c9).
115///
116/// Permissions enumerated by the draft:
117///
118/// - `manage_space` — top-level metadata (`name`, `description`,
119///   `iconBlobId`, `isPublic`, `isPubliclyPreviewable`). Top-level
120///   metadata is patched via the standard JMAP [`PatchObject`] wire
121///   shape, not via [`SpacePatchOp`] values, so no variant here returns
122///   `manage_space`; backends must apply this gate themselves to the
123///   top-level wire-keys before unfolding the structural `add*` /
124///   `remove*` / `update*` arrays into ops.
125/// - `manage_roles` — `addRoles`, `removeRoles`, `updateRoles`, and
126///   `updateMembers` entries that modify `roleIds`.
127/// - `manage_members` — `addMembers`, `removeMembers`, and
128///   `updateMembers` entries that change `nick`.
129/// - `manage_channels` — `addChannels`, `removeChannels`,
130///   `updateChannels`, `addCategories`, `removeCategories`,
131///   `updateCategories`.
132///
133/// Return shape: [`RequiredPermissions::Known`] carries the spec-
134/// derived permission slice; [`RequiredPermissions::UnknownOp`]
135/// signals that the op variant is not recognized and the backend
136/// MUST reject the patch (fail closed). The typed return value
137/// replaced an earlier slice-only shape that used a magic sentinel
138/// string `"__unknown_space_patch_op__"` to signal the unknown case;
139/// that contract was load-bearing on a name no public API exposed.
140///
141/// This helper is pure and has no side effects. Backends consume it
142/// inside [`ChatSpaces::apply_space_patch`](crate::ChatSpaces::apply_space_patch) after resolving the
143/// caller's effective permissions. Handlers MUST NOT consume this
144/// helper for permission gating — gates are backend-canonical per
145/// workspace AGENTS.md.
146///
147/// [`PatchObject`]: jmap_types::PatchObject
148/// [`ChatSpaces::apply_space_patch`](crate::ChatSpaces::apply_space_patch): crate::ChatSpaces::apply_space_patch
149pub fn required_permissions_for_op(op: &SpacePatchOp) -> RequiredPermissions {
150    match op {
151        // Role family — draft §Space/set L1260, L1263, L1266.
152        SpacePatchOp::AddRole(_)
153        | SpacePatchOp::RemoveRole(_)
154        | SpacePatchOp::UpdateRole { .. } => {
155            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
156        }
157
158        // Member add/remove — draft §Space/set L1269, L1272.
159        SpacePatchOp::AddMember(_) | SpacePatchOp::RemoveMember(_) => {
160            RequiredPermissions::Known(&[ChatPermission::ManageMembers])
161        }
162
163        // Member update — draft-atwood-jmap-chat-00 L1277: "Role changes
164        // require `"manage_roles"`. Changing another member's `nick`
165        // requires `"manage_members"`." A `roleIds` change alone needs only
166        // `manage_roles`; the role-position hierarchy check in the backend
167        // bounds which roles it may grant or remove. The caller's own
168        // nick-only edit is exempt, but this helper has no caller identity,
169        // so the backend gate applies that exemption.
170        SpacePatchOp::UpdateMember { patch, .. } => match (&patch.role_ids, &patch.nick) {
171            (Some(_), Some(_)) => RequiredPermissions::Known(&[
172                ChatPermission::ManageMembers,
173                ChatPermission::ManageRoles,
174            ]),
175            (Some(_), None) => RequiredPermissions::Known(&[ChatPermission::ManageRoles]),
176            (None, _) => RequiredPermissions::Known(&[ChatPermission::ManageMembers]),
177        },
178
179        // Channel family — draft §Space/set L1280, L1283, L1286.
180        SpacePatchOp::AddChannel(_)
181        | SpacePatchOp::RemoveChannel(_)
182        | SpacePatchOp::UpdateChannel { .. } => {
183            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
184        }
185
186        // Category family — draft §Space/set L1289, L1292, L1295. Categories are a
187        // sub-property of the channel-set per the draft; the same permission
188        // gates both.
189        SpacePatchOp::AddCategory(_)
190        | SpacePatchOp::RemoveCategory(_)
191        | SpacePatchOp::UpdateCategory { .. } => {
192            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
193        }
194
195        // `SpacePatchOp` is `#[non_exhaustive]` upstream. A future-added
196        // variant cannot be matched at compile time from this downstream
197        // crate. Fail closed via the typed `UnknownOp` arm; backends MUST
198        // reject ops that produce this value.
199        _ => RequiredPermissions::UnknownOp,
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use jmap_chat_types::Clearable;
207    use jmap_chat_types::{
208        CategoryCreate, CategoryPatch, ChannelCreate, ChannelPatch, MemberPatch, RoleCreate,
209        RolePatch,
210    };
211    use jmap_types::Id;
212
213    // Oracle for the spec-line → permission mapping: draft-atwood-jmap-chat-00
214    // §Space/set L1256-1295 (jmap-chat-spec 91672c9). Each test constructs the SpacePatchOp variant from a
215    // hand-built payload (deserialized from spec-shaped JSON for types without
216    // `Default`, or built via `Default::default()` for the patch types) and
217    // asserts the slice returned by the helper matches the table in the
218    // rustdoc.
219    //
220    // `RoleCreate`, `CategoryCreate`, and `ChannelCreate` are `#[non_exhaustive]`
221    // without `Default`, so they are constructed via `serde_json::from_value`
222    // from hand-written JSON shaped after draft-atwood-jmap-chat-00 §4.12
223    // and §Space/set. This satisfies the workspace
224    // independent-oracle rule: the JSON is hand-typed from the spec, not
225    // derived from the code under test.
226
227    fn role_fixture() -> RoleCreate {
228        serde_json::from_value(serde_json::json!({
229            "name": "Moderator",
230            "permissions": ["chat:read"],
231            "position": 0
232        }))
233        .expect("role fixture must deserialize")
234    }
235
236    fn category_fixture() -> CategoryCreate {
237        serde_json::from_value(serde_json::json!({
238            "name": "Voice",
239            "position": 0,
240            "channelIds": []
241        }))
242        .expect("category fixture must deserialize")
243    }
244
245    fn channel_create_fixture() -> ChannelCreate {
246        serde_json::from_value(serde_json::json!({
247            "name": "general"
248        }))
249        .expect("channelCreate fixture must deserialize")
250    }
251
252    #[test]
253    fn add_role_requires_manage_roles() {
254        let op = SpacePatchOp::AddRole(role_fixture());
255        assert_eq!(
256            required_permissions_for_op(&op),
257            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
258        );
259    }
260
261    #[test]
262    fn remove_role_requires_manage_roles() {
263        let op = SpacePatchOp::RemoveRole(Id::from("r1"));
264        assert_eq!(
265            required_permissions_for_op(&op),
266            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
267        );
268    }
269
270    #[test]
271    fn update_role_requires_manage_roles() {
272        let mut patch = RolePatch::default();
273        patch.name = Some("Renamed".to_owned());
274        let op = SpacePatchOp::UpdateRole {
275            id: Id::from("r1"),
276            patch,
277        };
278        assert_eq!(
279            required_permissions_for_op(&op),
280            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
281        );
282    }
283
284    #[test]
285    fn add_member_requires_manage_members_only() {
286        let op = SpacePatchOp::AddMember(jmap_chat_types::MemberCreate::new(
287            Id::from("u1"),
288            vec![Id::from("r1"), Id::from("r2")],
289        ));
290        // Spec table: `addMembers` is `manage_members`. The role_ids field on
291        // AddMember does NOT additionally require `manage_roles` — only
292        // `updateMembers` with a roleIds change does.
293        assert_eq!(
294            required_permissions_for_op(&op),
295            RequiredPermissions::Known(&[ChatPermission::ManageMembers])
296        );
297    }
298
299    #[test]
300    fn remove_member_requires_manage_members() {
301        let op = SpacePatchOp::RemoveMember(Id::from("u1"));
302        assert_eq!(
303            required_permissions_for_op(&op),
304            RequiredPermissions::Known(&[ChatPermission::ManageMembers])
305        );
306    }
307
308    // Draft §Space/set `updateMembers`: "Changing another member's `nick`
309    // requires `"manage_members"`. A member MAY set their own `nick` by
310    // submitting `updateMembers` with a single entry whose `id` is their own
311    // and which contains only `nick`; the server MUST permit this regardless
312    // of the caller's permission set." This helper sees no caller, so it
313    // states the other-member requirement; the self-nick exemption lives in
314    // the backend gate (tests/space_update_members.rs).
315    #[test]
316    fn update_other_member_nick_only_requires_manage_members_only() {
317        let mut patch = MemberPatch::default();
318        patch.nick = Some(Clearable::Set("Captain".to_owned()));
319        let op = SpacePatchOp::UpdateMember {
320            user_id: Id::from("u1"),
321            patch,
322        };
323        assert_eq!(
324            required_permissions_for_op(&op),
325            RequiredPermissions::Known(&[ChatPermission::ManageMembers])
326        );
327    }
328
329    // Draft L1277: "Role changes require `"manage_roles"`." No other
330    // permission is named for a `roleIds`-only entry.
331    #[test]
332    fn update_member_role_ids_change_requires_manage_roles_only() {
333        let mut patch = MemberPatch::default();
334        patch.role_ids = Some(vec![Id::from("r1")]);
335        let op = SpacePatchOp::UpdateMember {
336            user_id: Id::from("u1"),
337            patch,
338        };
339        assert_eq!(
340            required_permissions_for_op(&op),
341            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
342        );
343    }
344
345    // Draft L1277: "Role changes require `"manage_roles"`. Changing another
346    // member's `nick` requires `"manage_members"`." An entry doing both needs
347    // both.
348    #[test]
349    fn update_member_role_ids_and_nick_requires_both() {
350        let mut patch = MemberPatch::default();
351        patch.role_ids = Some(vec![Id::from("r1")]);
352        patch.nick = Some(Clearable::Set("Captain".to_owned()));
353        let op = SpacePatchOp::UpdateMember {
354            user_id: Id::from("u1"),
355            patch,
356        };
357        assert_eq!(
358            required_permissions_for_op(&op),
359            RequiredPermissions::Known(&[
360                ChatPermission::ManageMembers,
361                ChatPermission::ManageRoles
362            ])
363        );
364    }
365
366    #[test]
367    fn update_member_role_ids_empty_still_counts_as_change() {
368        // An empty Vec is still `Some(_)` and represents an explicit
369        // "set roleIds to []" mutation, which requires manage_roles.
370        let mut patch = MemberPatch::default();
371        patch.role_ids = Some(vec![]);
372        let op = SpacePatchOp::UpdateMember {
373            user_id: Id::from("u1"),
374            patch,
375        };
376        assert_eq!(
377            required_permissions_for_op(&op),
378            RequiredPermissions::Known(&[ChatPermission::ManageRoles])
379        );
380    }
381
382    #[test]
383    fn add_channel_requires_manage_channels() {
384        let op = SpacePatchOp::AddChannel(channel_create_fixture());
385        assert_eq!(
386            required_permissions_for_op(&op),
387            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
388        );
389    }
390
391    #[test]
392    fn remove_channel_requires_manage_channels() {
393        let op = SpacePatchOp::RemoveChannel(Id::from("ch1"));
394        assert_eq!(
395            required_permissions_for_op(&op),
396            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
397        );
398    }
399
400    #[test]
401    fn update_channel_requires_manage_channels() {
402        let mut patch = ChannelPatch::default();
403        patch.name = Some("renamed".to_owned());
404        let op = SpacePatchOp::UpdateChannel {
405            id: Id::from("ch1"),
406            patch,
407        };
408        assert_eq!(
409            required_permissions_for_op(&op),
410            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
411        );
412    }
413
414    #[test]
415    fn add_category_requires_manage_channels() {
416        let op = SpacePatchOp::AddCategory(category_fixture());
417        assert_eq!(
418            required_permissions_for_op(&op),
419            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
420        );
421    }
422
423    #[test]
424    fn remove_category_requires_manage_channels() {
425        let op = SpacePatchOp::RemoveCategory(Id::from("cat1"));
426        assert_eq!(
427            required_permissions_for_op(&op),
428            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
429        );
430    }
431
432    #[test]
433    fn update_category_requires_manage_channels() {
434        let mut patch = CategoryPatch::default();
435        patch.name = Some("Voice".to_owned());
436        let op = SpacePatchOp::UpdateCategory {
437            id: Id::from("cat1"),
438            patch,
439        };
440        assert_eq!(
441            required_permissions_for_op(&op),
442            RequiredPermissions::Known(&[ChatPermission::ManageChannels])
443        );
444    }
445
446    // The required permissions serialize to the verbatim names of
447    // draft-atwood-jmap-chat-00 §SpaceRole `permissions` (jmap-chat-spec
448    // 33702a5, L798-807): `"manage_channels"`, `"manage_members"`,
449    // `"manage_roles"`. Pin the wire bytes so a rename is caught.
450    #[test]
451    fn required_permissions_serialize_to_spec_names() {
452        let mut both = MemberPatch::default();
453        both.role_ids = Some(vec![Id::from("r1")]);
454        both.nick = Some(Clearable::Set("Captain".to_owned()));
455        let cases = [
456            (
457                SpacePatchOp::UpdateMember {
458                    user_id: Id::from("u1"),
459                    patch: both,
460                },
461                serde_json::json!(["manage_members", "manage_roles"]),
462            ),
463            (
464                SpacePatchOp::RemoveChannel(Id::from("ch1")),
465                serde_json::json!(["manage_channels"]),
466            ),
467        ];
468        for (op, wire) in cases {
469            let RequiredPermissions::Known(slice) = required_permissions_for_op(&op) else {
470                panic!("op must have a known requirement");
471            };
472            assert_eq!(serde_json::to_value(slice).expect("serialize"), wire);
473        }
474    }
475
476    // Helper returns `RequiredPermissions` carrying `&'static [ChatPermission]`
477    // for the Known arm: no allocation. Pin the function pointer signature so
478    // a future return-type drift is caught at compile time.
479    #[test]
480    fn helper_returns_typed_known_or_unknown() {
481        fn assert_typed_return<F>(_f: F)
482        where
483            F: Fn(&SpacePatchOp) -> RequiredPermissions,
484        {
485        }
486        assert_typed_return(required_permissions_for_op);
487    }
488
489    // Round-trip the typed return shape: a Known arm must carry a non-empty,
490    // static slice; the UnknownOp arm must be constructible as a literal so
491    // consumers can write match arms that fail closed.
492    #[test]
493    fn unknown_op_variant_is_distinct_from_any_known_arm() {
494        // Two Known values with different content are unequal; a Known value
495        // is never equal to UnknownOp.
496        let a = RequiredPermissions::Known(&[ChatPermission::ManageRoles]);
497        let b = RequiredPermissions::Known(&[ChatPermission::ManageMembers]);
498        let u = RequiredPermissions::UnknownOp;
499        assert_ne!(a, b);
500        assert_ne!(a, u);
501        assert_ne!(b, u);
502        assert_eq!(u, RequiredPermissions::UnknownOp);
503    }
504
505    // Oracle for `resolve_channel_permissions`: draft-atwood-jmap-chat-00
506    // §Space Permission Resolution (jmap-chat-spec 33702a5, L1700-1709),
507    // quoted per test. Overrides are hand-written JSON shaped after
508    // §ChannelPermission: "`targetId` (String): A SpaceRole id or a
509    // SpaceMember `id`. `targetType` (String): `"role"` or `"member"`."
510
511    use serde_json::json;
512
513    fn overrides(v: serde_json::Value) -> Vec<ChannelPermission> {
514        serde_json::from_value(v).expect("hand-written ChannelPermission[]")
515    }
516
517    fn set(items: &[&str]) -> HashSet<ChatPermission> {
518        serde_json::from_value(json!(items)).expect("hand-written permission names")
519    }
520
521    fn resolve(base: &[&str], roles: &[&str], o: serde_json::Value) -> HashSet<ChatPermission> {
522        let role_ids: HashSet<&str> = roles.iter().copied().collect();
523        resolve_channel_permissions(set(base), "s1", "m1", &role_ids, &overrides(o))
524    }
525
526    // Step 1: "Compute the union of `permissions` across all SpaceRoles
527    // held by the member, including the implicit `@everyone` role." With
528    // no overrides the Space-level union is the result.
529    #[test]
530    fn step1_no_overrides_keeps_space_union() {
531        assert_eq!(
532            resolve(&["view", "send"], &["r1"], json!([])),
533            set(&["view", "send"])
534        );
535    }
536
537    // Step 2: "Apply `deny` entries from any ChannelPermission records
538    // matching the member's roles (`targetType: "role"`)". A record for a
539    // role the member does not hold does not apply.
540    #[test]
541    fn step2_role_deny_removes_permission() {
542        let o = json!([
543            { "targetId": "r1", "targetType": "role", "allow": [], "deny": ["send"] },
544            { "targetId": "r9", "targetType": "role", "allow": [], "deny": ["view"] }
545        ]);
546        assert_eq!(resolve(&["view", "send"], &["r1"], o), set(&["view"]));
547    }
548
549    // Step 3: "Apply `allow` entries from the same role-targeted records"
550    // — after step 2, so one role's allow beats another role's deny.
551    #[test]
552    fn step3_role_allow_overrides_role_deny() {
553        let o = json!([
554            { "targetId": "r1", "targetType": "role", "allow": [], "deny": ["send"] },
555            { "targetId": "r2", "targetType": "role", "allow": ["send"], "deny": [] }
556        ]);
557        assert_eq!(
558            resolve(&["view", "send"], &["r1", "r2"], o),
559            set(&["view", "send"])
560        );
561    }
562
563    // Step 4: "Apply `deny` entries from any ChannelPermission record
564    // matching the member directly (`targetType: "member"`)" — after step
565    // 3, so a member deny beats a role allow.
566    #[test]
567    fn step4_member_deny_overrides_role_allow() {
568        let o = json!([
569            { "targetId": "r1", "targetType": "role", "allow": ["send"], "deny": [] },
570            { "targetId": "m1", "targetType": "member", "allow": [], "deny": ["send"] }
571        ]);
572        assert_eq!(resolve(&["view"], &["r1"], o), set(&["view"]));
573    }
574
575    // Step 5: "Apply `allow` entries from the same member-targeted
576    // record." — last, so a member allow beats a role deny of the same
577    // permission, and a record for another member does not apply.
578    #[test]
579    fn step5_member_allow_overrides_role_deny() {
580        let o = json!([
581            { "targetId": "r1", "targetType": "role", "allow": [], "deny": ["send", "view"] },
582            { "targetId": "m1", "targetType": "member", "allow": ["send"], "deny": [] },
583            { "targetId": "m2", "targetType": "member", "allow": ["view"], "deny": [] }
584        ]);
585        assert_eq!(resolve(&["view", "send"], &["r1"], o), set(&["send"]));
586    }
587
588    // A role-targeted record never matches a member id and vice versa:
589    // §ChannelPermission `targetType` distinguishes "a SpaceRole id or a
590    // SpaceMember `id`".
591    #[test]
592    fn target_type_selects_the_id_space() {
593        let o = json!([
594            { "targetId": "m1", "targetType": "role", "allow": ["pin"], "deny": [] },
595            { "targetId": "r1", "targetType": "member", "allow": ["ban"], "deny": [] }
596        ]);
597        assert_eq!(resolve(&["view"], &["r1"], o), set(&["view"]));
598    }
599
600    // §ChannelPermission `targetId` (jmap-chat-spec 29e9a41, L853): "A
601    // record with `targetType: "role"` whose `targetId` is the id of the
602    // Space itself addresses the implicit `@everyone` role". Step 2 (L1706)
603    // applies "the record for `@everyone`, whose `targetId` is the Space
604    // id", so it matches a member that holds no SpaceRole.
605    #[test]
606    fn space_id_role_record_addresses_everyone() {
607        let o = json!([
608            { "targetId": "s1", "targetType": "role", "allow": ["pin"], "deny": ["send"] }
609        ]);
610        assert_eq!(resolve(&["view", "send"], &[], o), set(&["view", "pin"]));
611    }
612
613    // The `@everyone` record is role-targeted, so it is applied in steps
614    // 2 and 3, before the member-targeted steps 4 and 5: a member allow
615    // beats an `@everyone` deny.
616    #[test]
617    fn member_allow_overrides_everyone_deny() {
618        let o = json!([
619            { "targetId": "s1", "targetType": "role", "allow": [], "deny": ["send"] },
620            { "targetId": "m1", "targetType": "member", "allow": ["send"], "deny": [] }
621        ]);
622        assert_eq!(resolve(&["view", "send"], &[], o), set(&["view", "send"]));
623    }
624
625    // Only `targetType: "role"` with the Space id addresses `@everyone`;
626    // a member-targeted record naming the Space id matches no member.
627    #[test]
628    fn space_id_member_record_matches_nothing() {
629        let o = json!([
630            { "targetId": "s1", "targetType": "member", "allow": [], "deny": ["send"] }
631        ]);
632        assert_eq!(resolve(&["view", "send"], &[], o), set(&["view", "send"]));
633    }
634
635    // §SpaceRole (jmap-chat-spec 33702a5, L809): "Servers MUST ignore
636    // unrecognized permission names." A `ChatPermission::Other` spelling
637    // of a known name is matched on its wire string when denied, and is
638    // not the known permission when allowed: it can only fail closed.
639    #[test]
640    fn forged_other_spelling_denies_but_never_grants() {
641        let mut o = overrides(json!([
642            { "targetId": "m1", "targetType": "member", "allow": [], "deny": [] }
643        ]));
644        o[0].deny.push(ChatPermission::Other("send".to_owned()));
645        o[0].allow.push(ChatPermission::Other("pin".to_owned()));
646        let role_ids = HashSet::new();
647        let perms = resolve_channel_permissions(set(&["view", "send"]), "s1", "m1", &role_ids, &o);
648        assert!(!perms.contains(&ChatPermission::Send));
649        assert!(!perms.contains(&ChatPermission::Pin));
650        assert!(perms.contains(&ChatPermission::View));
651    }
652}