1use serde::{Deserialize, Serialize};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct Permissions(pub u64);
25
26impl From<u64> for Permissions {
28 fn from(bits: u64) -> Self {
29 Permissions(bits)
30 }
31}
32
33impl std::ops::BitOr for Permissions {
34 type Output = Permissions;
35 fn bitor(self, rhs: Permissions) -> Permissions {
36 Permissions(self.0 | rhs.0)
37 }
38}
39
40impl Permissions {
41 pub const MANAGE_ROLES: u64 = 1 << 0;
42 pub const MANAGE_CHANNELS: u64 = 1 << 1;
43 pub const MANAGE_METADATA: u64 = 1 << 2;
44 pub const KICK: u64 = 1 << 3;
45 pub const BAN: u64 = 1 << 4;
46 pub const MANAGE_MESSAGES: u64 = 1 << 5;
47 pub const CREATE_INVITE: u64 = 1 << 6;
48 pub const VIEW_AUDIT_LOG: u64 = 1 << 8;
49 pub const MENTION_EVERYONE: u64 = 1 << 9;
50 pub const PIN_MESSAGES: u64 = 1 << 11;
53 pub const VIEW_CHANNEL: u64 = 1 << 13;
56 pub const SEND_MESSAGES: u64 = 1 << 14;
57 pub const SEND_IN_THREADS: u64 = 1 << 15;
58 pub const ATTACH_FILES: u64 = 1 << 16;
59 pub const ADD_REACTIONS: u64 = 1 << 17;
60 pub const READ_MESSAGE_HISTORY: u64 = 1 << 18;
61 pub const CONNECT: u64 = 1 << 19;
62 pub const SPEAK: u64 = 1 << 20;
63 pub const VIDEO: u64 = 1 << 21;
64 pub const PRIORITY_SPEAKER: u64 = 1 << 22;
65 pub const MUTE_MEMBERS: u64 = 1 << 23;
66 pub const DEAFEN_MEMBERS: u64 = 1 << 24;
67 pub const MOVE_MEMBERS: u64 = 1 << 25;
68 pub const MODERATE_MEMBERS: u64 = 1 << 26;
70 pub const MANAGE_NICKNAMES: u64 = 1 << 28;
72 pub const CHANGE_NICKNAME: u64 = 1 << 29;
74 pub const ADMIN_FOUNDING_MASK: u64 = Self::MANAGE_ROLES
85 | Self::MANAGE_CHANNELS
86 | Self::MANAGE_METADATA
87 | Self::KICK
88 | Self::BAN
89 | Self::MANAGE_MESSAGES
90 | Self::CREATE_INVITE
91 | Self::VIEW_AUDIT_LOG
92 | Self::MENTION_EVERYONE;
93
94 pub const ADMIN_ALL: u64 = Self::ADMIN_FOUNDING_MASK | Self::PIN_MESSAGES;
98
99 pub const MANAGEMENT_MASK: u64 = Self::MANAGE_ROLES
104 | Self::MANAGE_CHANNELS
105 | Self::MANAGE_METADATA
106 | Self::KICK
107 | Self::BAN
108 | Self::MANAGE_MESSAGES
109 | Self::CREATE_INVITE
110 | Self::VIEW_AUDIT_LOG
111 | Self::PIN_MESSAGES;
112
113 pub const STAFF_MASK: u64 = Self::MANAGE_ROLES
121 | Self::MANAGE_CHANNELS
122 | Self::MANAGE_METADATA
123 | Self::BAN
124 | Self::CREATE_INVITE
125 | Self::PIN_MESSAGES;
126
127 pub fn empty() -> Self {
128 Permissions(0)
129 }
130 pub fn admin() -> Self {
131 Permissions(Self::ADMIN_ALL)
132 }
133 pub fn is_management(self) -> bool {
136 self.0 & Self::MANAGEMENT_MASK != 0
137 }
138 pub fn contains(self, bits: u64) -> bool {
140 self.0 & bits == bits
141 }
142 pub fn union(self, other: Permissions) -> Permissions {
143 Permissions(self.0 | other.0)
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case", tag = "kind", content = "channel_id")]
151pub enum RoleScope {
152 Server,
153 Channel(String),
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct Role {
161 pub role_id: String,
163 pub name: String,
164 pub position: u32,
169 pub permissions: Permissions,
170 pub scope: RoleScope,
171 #[serde(default)]
173 pub color: u32,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub rank: Option<String>,
178 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
180 pub display: bool,
181 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
183 pub mentionable: bool,
184 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
188 pub extra: serde_json::Map<String, serde_json::Value>,
189}
190
191impl Role {
192 pub fn admin(role_id: String) -> Self {
195 Role {
196 role_id,
197 name: "Admin".to_string(),
198 position: 1,
199 permissions: Permissions::admin(),
200 scope: RoleScope::Server,
201 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210pub struct MemberGrant {
211 pub member: String,
212 #[serde(default)]
213 pub role_ids: Vec<String>,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
219pub struct CommunityRoles {
220 #[serde(default)]
221 pub roles: Vec<Role>,
222 #[serde(default)]
223 pub grants: Vec<MemberGrant>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub everyone: Option<Permissions>,
227 #[serde(default, skip_serializing_if = "Vec::is_empty")]
229 pub overwrites: Vec<Overwrite>,
230 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
232 pub syncs: std::collections::BTreeMap<String, String>,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub legacy_channels: Option<std::collections::BTreeSet<String>>,
237 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
239 pub creators: std::collections::BTreeMap<String, String>,
240}
241
242pub const OVERWRITABLE: u64 = Permissions::MANAGE_MESSAGES
245 | Permissions::VIEW_CHANNEL
246 | Permissions::SEND_MESSAGES
247 | Permissions::SEND_IN_THREADS
248 | Permissions::ATTACH_FILES
249 | Permissions::ADD_REACTIONS
250 | Permissions::READ_MESSAGE_HISTORY
251 | Permissions::CONNECT
252 | Permissions::SPEAK
253 | Permissions::VIDEO
254 | Permissions::PRIORITY_SPEAKER
255 | Permissions::MUTE_MEMBERS
256 | Permissions::DEAFEN_MEMBERS
257 | Permissions::MOVE_MEMBERS
258 | Permissions::MODERATE_MEMBERS;
259
260#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
262#[serde(tag = "kind", content = "id", rename_all = "lowercase")]
263pub enum OverwriteTarget {
264 Everyone,
265 Role(String),
266 Member(String),
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272pub struct Overwrite {
273 pub scope: String,
275 pub target: OverwriteTarget,
276 pub allow: Permissions,
277 pub deny: Permissions,
278}
279
280impl CommunityRoles {
281 pub fn role(&self, role_id: &str) -> Option<&Role> {
283 self.roles.iter().find(|r| r.role_id == role_id)
284 }
285
286 pub fn roles_of<'a>(&'a self, member_hex: &'a str) -> impl Iterator<Item = &'a Role> + 'a {
288 self.grants
289 .iter()
290 .filter(move |g| g.member == member_hex)
291 .flat_map(move |g| g.role_ids.iter())
292 .filter_map(move |rid| self.role(rid))
293 }
294
295 pub fn channel_permissions_holding(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, role_ids: &[String], private: bool) -> Permissions {
302 if owner_hex == Some(member_hex) {
303 return Permissions(u64::MAX);
304 }
305 let roles: Vec<&Role> = role_ids.iter().filter_map(|id| self.role(id)).collect();
306 let mut p = roles.iter().fold(self.everyone.unwrap_or_default(), |acc, r| acc.union(r.permissions)).0;
307 let channel = channel_hex.to_ascii_lowercase();
308 let created = p & Permissions::MANAGE_CHANNELS != 0 && self.creators.get(&channel).is_some_and(|c| c == member_hex);
311 let scope = self.syncs.get(&channel).cloned().unwrap_or(channel);
313 let here = || self.overwrites.iter().filter(|o| o.scope == scope);
314 if let Some(o) = here().find(|o| o.target == OverwriteTarget::Everyone) {
315 p = (p & !o.deny.0) | o.allow.0;
316 }
317 if private {
318 p &= !Permissions::VIEW_CHANNEL;
319 }
320 let (mut deny, mut allow) = (0u64, 0u64);
321 for o in here() {
322 if let OverwriteTarget::Role(id) = &o.target {
323 if roles.iter().any(|r| r.role_id == *id) {
324 deny |= o.deny.0;
325 allow |= o.allow.0;
326 }
327 }
328 }
329 p = (p & !deny) | allow;
330 if created {
331 p |= Permissions::VIEW_CHANNEL;
332 }
333 if let Some(o) = here().find(|o| matches!(&o.target, OverwriteTarget::Member(m) if m == member_hex)) {
334 p = (p & !o.deny.0) | o.allow.0;
335 }
336 if p & Permissions::VIEW_CHANNEL == 0 {
337 return Permissions::empty();
338 }
339 Permissions(p)
340 }
341
342 pub fn everyone_sends(&self, channel_hex: &str) -> bool {
345 let Some(everyone) = self.everyone else { return true };
346 let channel = channel_hex.to_ascii_lowercase();
347 let scope = self.syncs.get(&channel).cloned().unwrap_or(channel);
348 let row = self.overwrites.iter().find(|o| o.scope == scope && o.target == OverwriteTarget::Everyone);
349 let p = row.map_or(everyone.0, |o| (everyone.0 & !o.deny.0) | o.allow.0);
350 p & Permissions::SEND_MESSAGES != 0
351 }
352
353 pub fn channel_permissions(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, private: bool) -> Permissions {
355 let held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).collect();
356 self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, private)
357 }
358
359 pub fn effective_permissions(&self, member_hex: &str) -> Permissions {
361 self.roles_of(member_hex)
362 .fold(self.everyone.unwrap_or_default(), |acc, r| acc.union(r.permissions))
363 }
364
365 pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
369 self.roles_of(member_hex)
370 .filter(|r| r.position < bound)
371 .fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
372 }
373
374 pub fn has_permission(&self, member_hex: &str, bits: u64) -> bool {
376 self.effective_permissions(member_hex).contains(bits)
377 }
378
379 pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
382 self.roles_of(member_hex).map(|r| r.position).min()
383 }
384
385 pub fn is_privileged(&self, member_hex: &str) -> bool {
387 self.roles_of(member_hex).next().is_some()
388 }
389
390 pub fn is_admin(&self, member_hex: &str) -> bool {
393 self.roles_of(member_hex).any(|r| r.permissions.is_management())
394 }
395
396 pub fn is_staff(&self, member_hex: &str, owner_hex: Option<&str>) -> bool {
400 if owner_hex == Some(member_hex) {
401 return true;
402 }
403 self.effective_permissions(member_hex).0 & Permissions::STAFF_MASK != 0
404 }
405
406 pub fn roles_make_staff(&self, role_ids: &[String]) -> bool {
411 role_ids
412 .iter()
413 .filter_map(|rid| self.role(rid))
414 .any(|r| r.permissions.0 & Permissions::STAFF_MASK != 0)
415 }
416
417 pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
422 if owner_hex == Some(actor_hex) {
423 return true;
424 }
425 self.has_permission(actor_hex, permission)
426 }
427
428 pub fn authorized_grantees(&self, owner_hex: Option<&str>, permission: u64) -> std::collections::HashSet<&str> {
431 let mut bits: crate::fasthash::FastMap<&str, Permissions> = Default::default();
432 for r in &self.roles {
433 bits.entry(r.role_id.as_str()).or_insert(r.permissions);
435 }
436 let mut held: crate::fasthash::FastMap<&str, Permissions> = Default::default();
437 for g in &self.grants {
438 let member = held.entry(g.member.as_str()).or_insert(self.everyone.unwrap_or_default());
439 for rid in &g.role_ids {
440 if let Some(b) = bits.get(rid.as_str()) {
441 *member = member.union(*b);
442 }
443 }
444 }
445 held.into_iter().filter(|(m, p)| owner_hex == Some(*m) || p.contains(permission)).map(|(m, _)| m).collect()
446 }
447
448 pub fn can_manage_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
456 self.can_act_on_position(actor_hex, owner_hex, target_position, Permissions::MANAGE_ROLES)
457 }
458
459 pub fn can_manage_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
463 self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_ROLES)
464 }
465
466 pub fn outranks(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
471 if owner_hex == Some(actor_hex) {
472 return true;
473 }
474 match self.highest_position(actor_hex) {
475 Some(p) => p < target_position,
476 None => false,
477 }
478 }
479
480 pub fn can_act_on_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32, permission: u64) -> bool {
485 if owner_hex == Some(actor_hex) {
486 return true;
487 }
488 self.has_permission(actor_hex, permission) && self.outranks(actor_hex, owner_hex, target_position)
489 }
490
491 pub fn can_act_on_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str, permission: u64) -> bool {
495 if owner_hex == Some(target_hex) {
496 return false;
497 }
498 let target_position = self.highest_position(target_hex).unwrap_or(u32::MAX);
499 self.can_act_on_position(actor_hex, owner_hex, target_position, permission)
500 }
501
502 pub fn may_name(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
506 if actor_hex != target_hex {
507 return self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_NICKNAMES);
508 }
509 owner_hex == Some(actor_hex) || self.everyone.is_none() || self.has_permission(actor_hex, Permissions::CHANGE_NICKNAME)
510 }
511
512 pub fn channel_roles(&self, channel_hex: &str) -> Vec<&Role> {
532 let wanted = channel_hex.to_ascii_lowercase();
533 let mut out: Vec<&Role> = self
534 .roles
535 .iter()
536 .filter(|r| matches!(&r.scope, RoleScope::Channel(c) if c.eq_ignore_ascii_case(&wanted)))
537 .collect();
538 out.sort_by_key(|r| r.position);
539 out
540 }
541
542 pub fn channel_role_ids(&self, channel_hex: &str) -> Vec<String> {
544 self.channel_roles(channel_hex).into_iter().map(|r| r.role_id.clone()).collect()
545 }
546
547 pub fn is_entitled(
554 &self,
555 owner_hex: Option<&str>,
556 member_hex: &str,
557 channel_hex: &str,
558 with: &[String],
559 without: &[String],
560 ) -> bool {
561 if owner_hex == Some(member_hex) {
562 return true;
563 }
564 let held = self.held_with(member_hex, with, without);
565 if self.everyone.is_some() {
567 return self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, true).contains(Permissions::VIEW_CHANNEL);
568 }
569 self.channel_role_ids(channel_hex).iter().any(|id| held.contains(id))
570 }
571
572 pub fn reads_history(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, with: &[String], without: &[String]) -> bool {
575 self.everyone.is_none()
576 || self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &self.held_with(member_hex, with, without), true).contains(Permissions::READ_MESSAGE_HISTORY)
577 }
578
579 fn held_with(&self, member_hex: &str, with: &[String], without: &[String]) -> Vec<String> {
580 let mut held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).filter(|id| !without.contains(id)).collect();
581 for id in with.iter().filter(|id| !without.contains(id)) {
582 if !held.contains(id) {
583 held.push(id.clone());
584 }
585 }
586 held
587 }
588
589 pub fn effective_permissions_in(&self, member_hex: &str, channel_hex: &str) -> Permissions {
598 let wanted = channel_hex.to_ascii_lowercase();
599 self.roles_of(member_hex)
600 .filter(|r| match &r.scope {
601 RoleScope::Server => true,
602 RoleScope::Channel(c) => c.eq_ignore_ascii_case(&wanted),
603 })
604 .fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
605 }
606
607 pub fn is_authorized_in(&self, actor_hex: &str, owner_hex: Option<&str>, channel_hex: &str, permission: u64) -> bool {
610 if owner_hex == Some(actor_hex) {
611 return true;
612 }
613 self.effective_permissions_in(actor_hex, channel_hex).contains(permission)
614 }
615}
616
617pub struct RoleIndex<'a> {
621 everyone: Permissions,
622 by_id: crate::fasthash::FastMap<&'a str, &'a Role>,
623 held: crate::fasthash::FastMap<&'a str, Vec<&'a Role>>,
624}
625
626impl<'a> RoleIndex<'a> {
627 pub fn of(roster: &'a CommunityRoles) -> Self {
628 let mut by_id: crate::fasthash::FastMap<&'a str, &'a Role> = Default::default();
629 for r in &roster.roles {
630 by_id.entry(r.role_id.as_str()).or_insert(r);
632 }
633 let mut held: crate::fasthash::FastMap<&str, Vec<&Role>> = Default::default();
634 for g in &roster.grants {
635 let roles = held.entry(g.member.as_str()).or_default();
636 roles.extend(g.role_ids.iter().filter_map(|rid| by_id.get(rid.as_str()).copied()));
637 }
638 RoleIndex { everyone: roster.everyone.unwrap_or_default(), by_id, held }
639 }
640
641 pub fn role(&self, role_id: &str) -> Option<&'a Role> {
643 self.by_id.get(role_id).copied()
644 }
645
646 fn roles_of(&self, member_hex: &str) -> &[&'a Role] {
647 self.held.get(member_hex).map_or(&[], Vec::as_slice)
648 }
649
650 pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
652 self.roles_of(member_hex).iter().filter(|r| r.position < bound).fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
653 }
654
655 pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
657 owner_hex == Some(actor_hex) || self.roles_of(actor_hex).iter().fold(self.everyone, |acc, r| acc.union(r.permissions)).contains(permission)
658 }
659
660 pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
662 self.roles_of(member_hex).iter().map(|r| r.position).min()
663 }
664
665 pub fn highest_position_above(&self, member_hex: &str, bound: u32) -> Option<u32> {
667 self.roles_of(member_hex).iter().map(|r| r.position).filter(|p| *p < bound).min()
668 }
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674
675 #[test]
676 fn authorized_grantees_agrees_with_asking_each_member() {
677 let mut seed = 0x9e37_79b9_7f4a_7c15u64;
678 let mut next = move |n: u64| {
679 seed ^= seed << 13;
680 seed ^= seed >> 7;
681 seed ^= seed << 17;
682 seed % n
683 };
684 for round in 0..200 {
685 let ids: Vec<String> = (0..6).map(|i| format!("{i:064x}")).collect();
686 let members: Vec<String> = (0..8).map(|i| format!("{:064x}", 100 + i)).collect();
687 let roles = (0..next(7)).map(|_| Role { role_id: ids[next(6) as usize].clone(), position: 1 + next(5) as u32, permissions: Permissions(next(16)), ..Role::admin(String::new()) }).collect();
689 let grants = (0..next(12)).map(|_| MemberGrant { member: members[next(8) as usize].clone(), role_ids: (0..next(4)).map(|_| ids[next(6) as usize].clone()).collect() }).collect();
690 let r = CommunityRoles { roles, grants, everyone: (next(2) == 0).then(|| Permissions(next(16))), ..Default::default() };
691 let owner = (round % 3 == 0).then(|| members[0].as_str());
692 let index = RoleIndex::of(&r);
693 for bits in 1..16u64 {
694 let fast = r.authorized_grantees(owner, bits);
695 for g in &r.grants {
696 assert_eq!(fast.contains(g.member.as_str()), r.is_authorized(&g.member, owner, bits), "round {round} bits {bits}");
697 }
698 for m in members.iter().map(String::as_str).chain(["nobody"]) {
699 assert_eq!(index.is_authorized(m, owner, bits), r.is_authorized(m, owner, bits), "round {round}");
700 }
701 }
702 for m in members.iter().map(String::as_str).chain(["nobody"]) {
703 assert_eq!(index.highest_position(m), r.highest_position(m), "round {round}");
704 for bound in 0..8 {
705 assert_eq!(index.permissions_above(m, bound), r.permissions_above(m, bound), "round {round} bound {bound}");
706 assert_eq!(index.highest_position_above(m, bound), r.roles_of(m).map(|r| r.position).filter(|p| *p < bound).min(), "round {round} bound {bound}");
707 }
708 }
709 }
710 }
711
712 #[test]
713 fn a_channel_resolves_everyone_then_roles_then_the_member() {
714 let (r1, r2) = ("1".repeat(64), "2".repeat(64));
715 let (m, n) = ("a".repeat(64), "b".repeat(64));
716 let role = |id: &str, bits: u64| Role { role_id: id.into(), position: 1, permissions: Permissions(bits), ..Role::admin(id.into()) };
717 let ch = "c".repeat(64);
718 let ow = |target, allow: u64, deny: u64| Overwrite { scope: ch.clone(), target, allow: Permissions(allow), deny: Permissions(deny) };
719 let (view, send) = (Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES);
720 let mut r = CommunityRoles {
721 roles: vec![role(&r1, 0), role(&r2, 0)],
722 grants: vec![MemberGrant { member: m.clone(), role_ids: vec![r1.clone(), r2.clone()] }],
723 everyone: Some(Permissions(view | send)),
724 overwrites: vec![ow(OverwriteTarget::Everyone, 0, view | send), ow(OverwriteTarget::Role(r1.clone()), view, 0), ow(OverwriteTarget::Role(r2.clone()), 0, view)],
725 syncs: Default::default(), legacy_channels: None, creators: Default::default(),
726 };
727 let at = |r: &CommunityRoles, who: &str| r.channel_permissions(Some("o"), who, &ch, false).0;
728 assert_eq!(at(&r, &m), view, "one role's allow beats another's deny; @everyone's deny of Send stands");
729 assert_eq!(at(&r, &n), 0, "without View a member holds nothing there");
730 assert_eq!(at(&r, "o"), u64::MAX, "the owner holds everything");
731 r.overwrites.push(ow(OverwriteTarget::Member(m.clone()), send, view));
732 assert_eq!(at(&r, &m), 0, "the member's own overwrite has the last word");
733 assert!(!r.is_entitled(Some("o"), &m, &ch, &[], &[]), "and the key follows View");
734 r.overwrites.pop();
735 assert!(r.is_entitled(Some("o"), &m, &ch, &[], &[]));
736 assert!(!r.is_entitled(Some("o"), &m, &ch, &[], std::slice::from_ref(&r1)), "losing the allowing role loses the key");
737 let cat = "d".repeat(64);
738 r.overwrites.push(Overwrite { scope: cat.clone(), target: OverwriteTarget::Role(r2.clone()), allow: Permissions(0), deny: Permissions(send) });
739 r.syncs.insert(ch.clone(), cat);
740 assert_eq!(at(&r, &n), view | send, "a synced channel takes its Category's overwrites, not its own");
741 assert_eq!(at(&r, &m), view, "including the Category's denies");
742 }
743
744 fn admin_roster(member: &str) -> CommunityRoles {
745 let role = Role::admin("a".repeat(64));
746 CommunityRoles {
747 grants: vec![MemberGrant {
748 member: member.to_string(),
749 role_ids: vec![role.role_id.clone()],
750 }],
751 roles: vec![role],
752 everyone: None,
753 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
754 }
755 }
756
757 #[test]
758 fn admin_role_holds_every_management_bit() {
759 let p = Permissions::admin();
760 for bit in [
761 Permissions::MANAGE_ROLES,
762 Permissions::MANAGE_CHANNELS,
763 Permissions::MANAGE_METADATA,
764 Permissions::KICK,
765 Permissions::BAN,
766 Permissions::MANAGE_MESSAGES,
767 Permissions::CREATE_INVITE,
768 Permissions::VIEW_AUDIT_LOG,
769 Permissions::MENTION_EVERYONE,
770 ] {
771 assert!(p.contains(bit), "admin must hold bit {bit}");
772 }
773 }
774
775 #[test]
776 fn social_only_role_is_not_management_nor_admin() {
777 let social = Permissions(Permissions::MENTION_EVERYONE);
781 assert!(!social.is_management(), "a purely-social permission is not management");
782 let role = Role {
783 role_id: "c".repeat(64),
784 name: "Hype".into(),
785 position: 5,
786 permissions: social,
787 scope: RoleScope::Server,
788 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
789 };
790 let alice = "aa".repeat(32);
791 let r = CommunityRoles {
792 grants: vec![MemberGrant { member: alice.clone(), role_ids: vec![role.role_id.clone()] }],
793 roles: vec![role],
794 everyone: None,
795 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
796 };
797 assert!(!r.is_admin(&alice), "a social-only role holder is not an admin");
798 assert!(r.is_privileged(&alice), "though they do hold a role");
799 }
800
801 #[test]
802 fn hierarchy_only_strictly_higher_can_manage() {
803 let owner = "00".repeat(32);
805 let admin = "aa".repeat(32);
806 let moderator = "bb".repeat(32);
807 let member = "cc".repeat(32);
808 let admin_role = Role::admin("a".repeat(64));
809 let mod_role = Role {
810 role_id: "b".repeat(64),
811 name: "Mod".into(),
812 position: 2,
813 permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::KICK),
814 scope: RoleScope::Server,
815 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
816 };
817 let admin_pos = admin_role.position; let mod_pos = mod_role.position; let r = CommunityRoles {
820 grants: vec![
821 MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
822 MemberGrant { member: moderator.clone(), role_ids: vec![mod_role.role_id.clone()] },
823 ],
824 roles: vec![admin_role, mod_role],
825 everyone: None,
826 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
827 };
828 let owner_ref = Some(owner.as_str());
829
830 assert!(r.can_manage_position(&owner, owner_ref, admin_pos));
832 assert!(r.can_manage_member(&owner, owner_ref, &admin));
833 assert!(!r.can_manage_member(&admin, owner_ref, &owner), "owner is never a valid target");
834
835 assert!(!r.can_manage_position(&admin, owner_ref, admin_pos), "admin can't grant a peer-rank role");
838 assert!(r.can_manage_position(&admin, owner_ref, mod_pos), "admin outranks Mod");
839 assert!(r.can_manage_member(&admin, owner_ref, &moderator), "admin outranks the mod member");
840 assert!(r.can_manage_member(&admin, owner_ref, &member), "admin outranks a roleless member");
841 assert!(!r.can_manage_member(&admin, owner_ref, &admin), "admin can't manage a peer admin");
842
843 assert!(!r.can_manage_position(&moderator, owner_ref, admin_pos));
845 assert!(!r.can_manage_position(&member, owner_ref, mod_pos), "no role, no MANAGE_ROLES → nothing");
846 }
847
848 #[test]
849 fn can_act_on_member_gates_on_permission_and_rank() {
850 let owner = "00".repeat(32);
854 let admin = "aa".repeat(32);
855 let kicker = "bb".repeat(32);
856 let member = "cc".repeat(32);
857 let admin_role = Role::admin("a".repeat(64)); let kick_role = Role {
859 role_id: "b".repeat(64),
860 name: "Mod".into(),
861 position: 2,
862 permissions: Permissions(Permissions::KICK), scope: RoleScope::Server,
864 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
865 };
866 let r = CommunityRoles {
867 grants: vec![
868 MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
869 MemberGrant { member: kicker.clone(), role_ids: vec![kick_role.role_id.clone()] },
870 ],
871 roles: vec![admin_role, kick_role],
872 everyone: None,
873 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
874 };
875 let o = Some(owner.as_str());
876 use Permissions as P;
877
878 assert!(r.can_act_on_member(&admin, o, &kicker, P::BAN));
880 assert!(r.can_act_on_member(&admin, o, &member, P::BAN));
881 assert!(!r.can_act_on_member(&admin, o, &admin, P::BAN), "no banning a peer admin (equal rank)");
882 assert!(!r.can_act_on_member(&admin, o, &owner, P::BAN), "the owner is never a valid target");
883 assert!(r.can_act_on_member(&admin, o, &member, P::MANAGE_MESSAGES), "admin can hide a member's msg");
884
885 assert!(!r.can_act_on_member(&kicker, o, &member, P::BAN), "no BAN permission → can't ban");
887 assert!(!r.can_act_on_member(&kicker, o, &member, P::MANAGE_MESSAGES), "no MANAGE_MESSAGES → can't hide");
888 assert!(r.can_act_on_member(&kicker, o, &member, P::KICK), "but it CAN kick a plain member");
889
890 assert!(r.can_act_on_member(&owner, o, &admin, P::BAN));
892 assert!(!r.can_act_on_member(&member, o, &kicker, P::BAN));
894 }
895
896 #[test]
897 fn effective_permissions_union_and_position() {
898 let alice = "aa".repeat(32);
899 let r = admin_roster(&alice);
900 assert!(r.has_permission(&alice, Permissions::BAN));
901 assert!(r.has_permission(&alice, Permissions::MANAGE_ROLES));
902 assert_eq!(r.highest_position(&alice), Some(1));
903 assert!(r.is_privileged(&alice));
904
905 let bob = "bb".repeat(32);
907 assert!(!r.has_permission(&bob, Permissions::BAN));
908 assert_eq!(r.highest_position(&bob), None);
909 assert!(!r.is_privileged(&bob));
910 }
911
912 #[test]
913 fn multiple_roles_union_perms_and_take_highest_position() {
914 let alice = "aa".repeat(32);
915 let mod_role = Role {
916 role_id: "b".repeat(64),
917 name: "Mod".into(),
918 position: 2,
919 permissions: Permissions(Permissions::MANAGE_MESSAGES | Permissions::KICK),
920 scope: RoleScope::Server,
921 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
922 };
923 let admin = Role::admin("a".repeat(64));
924 let r = CommunityRoles {
925 grants: vec![MemberGrant {
926 member: alice.clone(),
927 role_ids: vec![admin.role_id.clone(), mod_role.role_id.clone()],
928 }],
929 roles: vec![admin, mod_role],
930 everyone: None,
931 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
932 };
933 assert!(r.has_permission(&alice, Permissions::BAN)); assert!(r.has_permission(&alice, Permissions::MANAGE_MESSAGES)); assert_eq!(r.highest_position(&alice), Some(1));
937 }
938
939 #[test]
940 fn round_trips_json() {
941 let alice = "aa".repeat(32);
942 let r = admin_roster(&alice);
943 let json = serde_json::to_string(&r).unwrap();
944 let back: CommunityRoles = serde_json::from_str(&json).unwrap();
945 assert_eq!(r, back);
946 assert!(json.contains("\"kind\":\"server\""));
947 }
948
949 #[test]
950 fn is_authorized_owner_supreme_admin_by_permission_demoted_rejected() {
951 let owner = "00".repeat(32);
952 let alice = "aa".repeat(32);
953 let r = admin_roster(&alice); assert!(r.is_authorized(&owner, Some(&owner), Permissions::BAN));
956 assert!(r.is_authorized(&alice, Some(&owner), Permissions::BAN));
958 let bob = "bb".repeat(32);
960 assert!(!r.is_authorized(&bob, Some(&owner), Permissions::BAN));
961 let demoted = CommunityRoles { roles: r.roles.clone(), grants: vec![], everyone: None, overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default() };
962 assert!(!demoted.is_authorized(&alice, Some(&owner), Permissions::BAN));
963 assert!(demoted.is_authorized(&owner, Some(&owner), Permissions::BAN));
965 }
966
967 #[test]
968 fn channel_scope_round_trips() {
969 let scope = RoleScope::Channel("cc".repeat(32));
970 let json = serde_json::to_string(&scope).unwrap();
971 let back: RoleScope = serde_json::from_str(&json).unwrap();
972 assert_eq!(scope, back);
973 }
974
975 fn scoped_roster(chan: &str, member: &str, admin: &str) -> CommunityRoles {
980 let scoped = Role {
981 role_id: "11".repeat(32),
982 name: "Testers".into(),
983 position: 5,
984 permissions: Permissions(Permissions::MANAGE_MESSAGES),
985 scope: RoleScope::Channel(chan.to_string()),
986 color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
987 };
988 let server = Role::admin("22".repeat(32));
989 CommunityRoles {
990 grants: vec![
991 MemberGrant { member: member.to_string(), role_ids: vec![scoped.role_id.clone()] },
992 MemberGrant { member: admin.to_string(), role_ids: vec![server.role_id.clone()] },
993 ],
994 roles: vec![scoped, server],
995 everyone: None,
996 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
997 }
998 }
999
1000 #[test]
1001 fn a_channels_scoped_roles_are_its_access_list() {
1002 let chan = "cc".repeat(32);
1003 let other = "dd".repeat(32);
1004 let owner = "00".repeat(32);
1005 let member = "aa".repeat(32);
1006 let admin = "bb".repeat(32);
1007 let r = scoped_roster(&chan, &member, &admin);
1008
1009 assert_eq!(r.channel_roles(&chan).len(), 1, "the scoped role is the access list");
1010 assert!(r.channel_roles(&other).is_empty(), "another channel gets none of it");
1011
1012 assert!(r.is_entitled(Some(&owner), &member, &chan, &[], &[]), "the granted holder is entitled");
1013 assert!(r.is_entitled(Some(&owner), &owner, &chan, &[], &[]), "the owner is always entitled");
1014 assert!(!r.is_entitled(Some(&owner), &admin, &chan, &[], &[]), "rank alone is not entitlement");
1017 assert!(!r.is_entitled(Some(&owner), &member, &other, &[], &[]), "entitlement does not spill to another channel");
1018 }
1019
1020 #[test]
1021 fn the_grant_overlay_settles_against_a_publish_the_fold_has_not_caught() {
1022 let chan = "cc".repeat(32);
1023 let owner = "00".repeat(32);
1024 let member = "aa".repeat(32);
1025 let stranger = "ee".repeat(32);
1026 let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1027 let scoped_id = r.channel_role_ids(&chan)[0].clone();
1028
1029 assert!(
1030 r.is_entitled(Some(&owner), &stranger, &chan, std::slice::from_ref(&scoped_id), &[]),
1031 "a just-published grant settles as entitled before the fold catches up"
1032 );
1033 assert!(
1034 !r.is_entitled(Some(&owner), &member, &chan, &[], std::slice::from_ref(&scoped_id)),
1035 "a just-published revoke settles as unentitled before the fold catches up"
1036 );
1037 }
1038
1039 #[test]
1040 fn channel_narrowing_is_offer_side_only() {
1041 let chan = "cc".repeat(32);
1042 let other = "dd".repeat(32);
1043 let owner = "00".repeat(32);
1044 let member = "aa".repeat(32);
1045 let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1046
1047 assert!(r.is_authorized_in(&member, Some(&owner), &chan, Permissions::MANAGE_MESSAGES));
1049 assert!(!r.is_authorized_in(&member, Some(&owner), &other, Permissions::MANAGE_MESSAGES));
1050
1051 assert!(
1055 r.is_authorized(&member, Some(&owner), Permissions::MANAGE_MESSAGES),
1056 "the scope-blind honor path is unchanged"
1057 );
1058 }
1059
1060 #[test]
1064 fn founding_mask_is_frozen_at_the_original_nine_bits() {
1065 const ORIGINAL_NINE: u64 = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)
1066 | (1 << 5) | (1 << 6) | (1 << 8) | (1 << 9);
1067 assert_eq!(Permissions::ADMIN_FOUNDING_MASK, ORIGINAL_NINE);
1068 assert!(Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_FOUNDING_MASK));
1070 assert!(Permissions::admin().contains(Permissions::ADMIN_FOUNDING_MASK));
1072 assert!(Permissions::admin().contains(Permissions::PIN_MESSAGES));
1073 assert!(!Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_ALL));
1076 }
1077}