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