use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Permissions(pub u64);
impl From<u64> for Permissions {
fn from(bits: u64) -> Self {
Permissions(bits)
}
}
impl std::ops::BitOr for Permissions {
type Output = Permissions;
fn bitor(self, rhs: Permissions) -> Permissions {
Permissions(self.0 | rhs.0)
}
}
impl Permissions {
pub const MANAGE_ROLES: u64 = 1 << 0;
pub const MANAGE_CHANNELS: u64 = 1 << 1;
pub const MANAGE_METADATA: u64 = 1 << 2;
pub const KICK: u64 = 1 << 3;
pub const BAN: u64 = 1 << 4;
pub const MANAGE_MESSAGES: u64 = 1 << 5;
pub const CREATE_INVITE: u64 = 1 << 6;
pub const VIEW_AUDIT_LOG: u64 = 1 << 8;
pub const MENTION_EVERYONE: u64 = 1 << 9;
pub const PIN_MESSAGES: u64 = 1 << 11;
pub const VIEW_CHANNEL: u64 = 1 << 13;
pub const SEND_MESSAGES: u64 = 1 << 14;
pub const SEND_IN_THREADS: u64 = 1 << 15;
pub const ATTACH_FILES: u64 = 1 << 16;
pub const ADD_REACTIONS: u64 = 1 << 17;
pub const READ_MESSAGE_HISTORY: u64 = 1 << 18;
pub const CONNECT: u64 = 1 << 19;
pub const SPEAK: u64 = 1 << 20;
pub const VIDEO: u64 = 1 << 21;
pub const PRIORITY_SPEAKER: u64 = 1 << 22;
pub const MUTE_MEMBERS: u64 = 1 << 23;
pub const DEAFEN_MEMBERS: u64 = 1 << 24;
pub const MOVE_MEMBERS: u64 = 1 << 25;
pub const MODERATE_MEMBERS: u64 = 1 << 26;
pub const MANAGE_NICKNAMES: u64 = 1 << 28;
pub const CHANGE_NICKNAME: u64 = 1 << 29;
pub const ADMIN_FOUNDING_MASK: u64 = Self::MANAGE_ROLES
| Self::MANAGE_CHANNELS
| Self::MANAGE_METADATA
| Self::KICK
| Self::BAN
| Self::MANAGE_MESSAGES
| Self::CREATE_INVITE
| Self::VIEW_AUDIT_LOG
| Self::MENTION_EVERYONE;
pub const ADMIN_ALL: u64 = Self::ADMIN_FOUNDING_MASK | Self::PIN_MESSAGES;
pub const MANAGEMENT_MASK: u64 = Self::MANAGE_ROLES
| Self::MANAGE_CHANNELS
| Self::MANAGE_METADATA
| Self::KICK
| Self::BAN
| Self::MANAGE_MESSAGES
| Self::CREATE_INVITE
| Self::VIEW_AUDIT_LOG
| Self::PIN_MESSAGES;
pub const STAFF_MASK: u64 = Self::MANAGE_ROLES
| Self::MANAGE_CHANNELS
| Self::MANAGE_METADATA
| Self::BAN
| Self::CREATE_INVITE
| Self::PIN_MESSAGES;
pub fn empty() -> Self {
Permissions(0)
}
pub fn admin() -> Self {
Permissions(Self::ADMIN_ALL)
}
pub fn is_management(self) -> bool {
self.0 & Self::MANAGEMENT_MASK != 0
}
pub fn contains(self, bits: u64) -> bool {
self.0 & bits == bits
}
pub fn union(self, other: Permissions) -> Permissions {
Permissions(self.0 | other.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "channel_id")]
pub enum RoleScope {
Server,
Channel(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Role {
pub role_id: String,
pub name: String,
pub position: u32,
pub permissions: Permissions,
pub scope: RoleScope,
#[serde(default)]
pub color: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rank: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub display: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mentionable: bool,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl Role {
pub fn admin(role_id: String) -> Self {
Role {
role_id,
name: "Admin".to_string(),
position: 1,
permissions: Permissions::admin(),
scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemberGrant {
pub member: String,
#[serde(default)]
pub role_ids: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CommunityRoles {
#[serde(default)]
pub roles: Vec<Role>,
#[serde(default)]
pub grants: Vec<MemberGrant>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub everyone: Option<Permissions>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub overwrites: Vec<Overwrite>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub syncs: std::collections::BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub legacy_channels: Option<std::collections::BTreeSet<String>>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub creators: std::collections::BTreeMap<String, String>,
}
pub const OVERWRITABLE: u64 = Permissions::MANAGE_MESSAGES
| Permissions::VIEW_CHANNEL
| Permissions::SEND_MESSAGES
| Permissions::SEND_IN_THREADS
| Permissions::ATTACH_FILES
| Permissions::ADD_REACTIONS
| Permissions::READ_MESSAGE_HISTORY
| Permissions::CONNECT
| Permissions::SPEAK
| Permissions::VIDEO
| Permissions::PRIORITY_SPEAKER
| Permissions::MUTE_MEMBERS
| Permissions::DEAFEN_MEMBERS
| Permissions::MOVE_MEMBERS
| Permissions::MODERATE_MEMBERS;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "lowercase")]
pub enum OverwriteTarget {
Everyone,
Role(String),
Member(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Overwrite {
pub scope: String,
pub target: OverwriteTarget,
pub allow: Permissions,
pub deny: Permissions,
}
impl CommunityRoles {
pub fn role(&self, role_id: &str) -> Option<&Role> {
self.roles.iter().find(|r| r.role_id == role_id)
}
pub fn roles_of<'a>(&'a self, member_hex: &'a str) -> impl Iterator<Item = &'a Role> + 'a {
self.grants
.iter()
.filter(move |g| g.member == member_hex)
.flat_map(move |g| g.role_ids.iter())
.filter_map(move |rid| self.role(rid))
}
pub fn channel_permissions_holding(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, role_ids: &[String], private: bool) -> Permissions {
if owner_hex == Some(member_hex) {
return Permissions(u64::MAX);
}
let roles: Vec<&Role> = role_ids.iter().filter_map(|id| self.role(id)).collect();
let mut p = roles.iter().fold(self.everyone.unwrap_or_default(), |acc, r| acc.union(r.permissions)).0;
let channel = channel_hex.to_ascii_lowercase();
let created = p & Permissions::MANAGE_CHANNELS != 0 && self.creators.get(&channel).is_some_and(|c| c == member_hex);
let scope = self.syncs.get(&channel).cloned().unwrap_or(channel);
let here = || self.overwrites.iter().filter(|o| o.scope == scope);
if let Some(o) = here().find(|o| o.target == OverwriteTarget::Everyone) {
p = (p & !o.deny.0) | o.allow.0;
}
if private {
p &= !Permissions::VIEW_CHANNEL;
}
let (mut deny, mut allow) = (0u64, 0u64);
for o in here() {
if let OverwriteTarget::Role(id) = &o.target {
if roles.iter().any(|r| r.role_id == *id) {
deny |= o.deny.0;
allow |= o.allow.0;
}
}
}
p = (p & !deny) | allow;
if created {
p |= Permissions::VIEW_CHANNEL;
}
if let Some(o) = here().find(|o| matches!(&o.target, OverwriteTarget::Member(m) if m == member_hex)) {
p = (p & !o.deny.0) | o.allow.0;
}
if p & Permissions::VIEW_CHANNEL == 0 {
return Permissions::empty();
}
Permissions(p)
}
pub fn everyone_sends(&self, channel_hex: &str) -> bool {
self.everyone_in(channel_hex).is_none_or(|p| p & Permissions::SEND_MESSAGES != 0)
}
pub fn everyone_writes_nothing(&self, channel_hex: &str) -> bool {
self.everyone_in(channel_hex).is_some_and(|p| p & (Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT) == 0)
}
pub fn everyone_reads_history(&self, channel_hex: &str) -> bool {
self.everyone_in(channel_hex).is_none_or(|p| p & Permissions::READ_MESSAGE_HISTORY != 0)
}
fn everyone_in(&self, channel_hex: &str) -> Option<u64> {
let everyone = self.everyone?;
let channel = channel_hex.to_ascii_lowercase();
let scope = self.syncs.get(&channel).cloned().unwrap_or(channel);
let row = self.overwrites.iter().find(|o| o.scope == scope && o.target == OverwriteTarget::Everyone);
Some(row.map_or(everyone.0, |o| (everyone.0 & !o.deny.0) | o.allow.0))
}
pub fn channel_permissions(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, private: bool) -> Permissions {
let held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).collect();
self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, private)
}
pub fn effective_permissions(&self, member_hex: &str) -> Permissions {
self.roles_of(member_hex)
.fold(self.everyone.unwrap_or_default(), |acc, r| acc.union(r.permissions))
}
pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
self.roles_of(member_hex)
.filter(|r| r.position < bound)
.fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
}
pub fn has_permission(&self, member_hex: &str, bits: u64) -> bool {
self.effective_permissions(member_hex).contains(bits)
}
pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
self.roles_of(member_hex).map(|r| r.position).min()
}
pub fn is_privileged(&self, member_hex: &str) -> bool {
self.roles_of(member_hex).next().is_some()
}
pub fn is_admin(&self, member_hex: &str) -> bool {
self.roles_of(member_hex).any(|r| r.permissions.is_management())
}
pub fn is_staff(&self, member_hex: &str, owner_hex: Option<&str>) -> bool {
if owner_hex == Some(member_hex) {
return true;
}
self.effective_permissions(member_hex).0 & Permissions::STAFF_MASK != 0
}
pub fn roles_make_staff(&self, role_ids: &[String]) -> bool {
role_ids
.iter()
.filter_map(|rid| self.role(rid))
.any(|r| r.permissions.0 & Permissions::STAFF_MASK != 0)
}
pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
if owner_hex == Some(actor_hex) {
return true;
}
self.has_permission(actor_hex, permission)
}
pub fn authorized_grantees(&self, owner_hex: Option<&str>, permission: u64) -> std::collections::HashSet<&str> {
let mut bits: crate::fasthash::FastMap<&str, Permissions> = Default::default();
for r in &self.roles {
bits.entry(r.role_id.as_str()).or_insert(r.permissions);
}
let mut held: crate::fasthash::FastMap<&str, Permissions> = Default::default();
for g in &self.grants {
let member = held.entry(g.member.as_str()).or_insert(self.everyone.unwrap_or_default());
for rid in &g.role_ids {
if let Some(b) = bits.get(rid.as_str()) {
*member = member.union(*b);
}
}
}
held.into_iter().filter(|(m, p)| owner_hex == Some(*m) || p.contains(permission)).map(|(m, _)| m).collect()
}
pub fn can_manage_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
self.can_act_on_position(actor_hex, owner_hex, target_position, Permissions::MANAGE_ROLES)
}
pub fn can_manage_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_ROLES)
}
pub fn outranks(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
if owner_hex == Some(actor_hex) {
return true;
}
match self.highest_position(actor_hex) {
Some(p) => p < target_position,
None => false,
}
}
pub fn can_act_on_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32, permission: u64) -> bool {
if owner_hex == Some(actor_hex) {
return true;
}
self.has_permission(actor_hex, permission) && self.outranks(actor_hex, owner_hex, target_position)
}
pub fn can_act_on_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str, permission: u64) -> bool {
if owner_hex == Some(target_hex) {
return false;
}
let target_position = self.highest_position(target_hex).unwrap_or(u32::MAX);
self.can_act_on_position(actor_hex, owner_hex, target_position, permission)
}
pub fn may_name(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
if actor_hex != target_hex {
return self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_NICKNAMES);
}
owner_hex == Some(actor_hex) || self.everyone.is_none() || self.has_permission(actor_hex, Permissions::CHANGE_NICKNAME)
}
pub fn channel_roles(&self, channel_hex: &str) -> Vec<&Role> {
let wanted = channel_hex.to_ascii_lowercase();
let mut out: Vec<&Role> = self
.roles
.iter()
.filter(|r| matches!(&r.scope, RoleScope::Channel(c) if c.eq_ignore_ascii_case(&wanted)))
.collect();
out.sort_by_key(|r| r.position);
out
}
pub fn channel_role_ids(&self, channel_hex: &str) -> Vec<String> {
self.channel_roles(channel_hex).into_iter().map(|r| r.role_id.clone()).collect()
}
pub fn is_entitled(
&self,
owner_hex: Option<&str>,
member_hex: &str,
channel_hex: &str,
with: &[String],
without: &[String],
) -> bool {
if owner_hex == Some(member_hex) {
return true;
}
let held = self.held_with(member_hex, with, without);
if self.everyone.is_some() {
return self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, true).contains(Permissions::VIEW_CHANNEL);
}
self.channel_role_ids(channel_hex).iter().any(|id| held.contains(id))
}
pub fn reads_history(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, with: &[String], without: &[String]) -> bool {
self.everyone.is_none()
|| self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &self.held_with(member_hex, with, without), true).contains(Permissions::READ_MESSAGE_HISTORY)
}
fn held_with(&self, member_hex: &str, with: &[String], without: &[String]) -> Vec<String> {
let mut held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).filter(|id| !without.contains(id)).collect();
for id in with.iter().filter(|id| !without.contains(id)) {
if !held.contains(id) {
held.push(id.clone());
}
}
held
}
pub fn effective_permissions_in(&self, member_hex: &str, channel_hex: &str) -> Permissions {
let wanted = channel_hex.to_ascii_lowercase();
self.roles_of(member_hex)
.filter(|r| match &r.scope {
RoleScope::Server => true,
RoleScope::Channel(c) => c.eq_ignore_ascii_case(&wanted),
})
.fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
}
pub fn is_authorized_in(&self, actor_hex: &str, owner_hex: Option<&str>, channel_hex: &str, permission: u64) -> bool {
if owner_hex == Some(actor_hex) {
return true;
}
self.effective_permissions_in(actor_hex, channel_hex).contains(permission)
}
}
pub struct RoleIndex<'a> {
everyone: Permissions,
by_id: crate::fasthash::FastMap<&'a str, &'a Role>,
held: crate::fasthash::FastMap<&'a str, Vec<&'a Role>>,
}
impl<'a> RoleIndex<'a> {
pub fn of(roster: &'a CommunityRoles) -> Self {
let mut by_id: crate::fasthash::FastMap<&'a str, &'a Role> = Default::default();
for r in &roster.roles {
by_id.entry(r.role_id.as_str()).or_insert(r);
}
let mut held: crate::fasthash::FastMap<&str, Vec<&Role>> = Default::default();
for g in &roster.grants {
let roles = held.entry(g.member.as_str()).or_default();
roles.extend(g.role_ids.iter().filter_map(|rid| by_id.get(rid.as_str()).copied()));
}
RoleIndex { everyone: roster.everyone.unwrap_or_default(), by_id, held }
}
pub fn role(&self, role_id: &str) -> Option<&'a Role> {
self.by_id.get(role_id).copied()
}
fn roles_of(&self, member_hex: &str) -> &[&'a Role] {
self.held.get(member_hex).map_or(&[], Vec::as_slice)
}
pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
self.roles_of(member_hex).iter().filter(|r| r.position < bound).fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
}
pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
owner_hex == Some(actor_hex) || self.roles_of(actor_hex).iter().fold(self.everyone, |acc, r| acc.union(r.permissions)).contains(permission)
}
pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
self.roles_of(member_hex).iter().map(|r| r.position).min()
}
pub fn highest_position_above(&self, member_hex: &str, bound: u32) -> Option<u32> {
self.roles_of(member_hex).iter().map(|r| r.position).filter(|p| *p < bound).min()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn authorized_grantees_agrees_with_asking_each_member() {
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
for round in 0..200 {
let ids: Vec<String> = (0..6).map(|i| format!("{i:064x}")).collect();
let members: Vec<String> = (0..8).map(|i| format!("{:064x}", 100 + i)).collect();
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();
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();
let r = CommunityRoles { roles, grants, everyone: (next(2) == 0).then(|| Permissions(next(16))), ..Default::default() };
let owner = (round % 3 == 0).then(|| members[0].as_str());
let index = RoleIndex::of(&r);
for bits in 1..16u64 {
let fast = r.authorized_grantees(owner, bits);
for g in &r.grants {
assert_eq!(fast.contains(g.member.as_str()), r.is_authorized(&g.member, owner, bits), "round {round} bits {bits}");
}
for m in members.iter().map(String::as_str).chain(["nobody"]) {
assert_eq!(index.is_authorized(m, owner, bits), r.is_authorized(m, owner, bits), "round {round}");
}
}
for m in members.iter().map(String::as_str).chain(["nobody"]) {
assert_eq!(index.highest_position(m), r.highest_position(m), "round {round}");
for bound in 0..8 {
assert_eq!(index.permissions_above(m, bound), r.permissions_above(m, bound), "round {round} bound {bound}");
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}");
}
}
}
}
#[test]
fn a_channel_resolves_everyone_then_roles_then_the_member() {
let (r1, r2) = ("1".repeat(64), "2".repeat(64));
let (m, n) = ("a".repeat(64), "b".repeat(64));
let role = |id: &str, bits: u64| Role { role_id: id.into(), position: 1, permissions: Permissions(bits), ..Role::admin(id.into()) };
let ch = "c".repeat(64);
let ow = |target, allow: u64, deny: u64| Overwrite { scope: ch.clone(), target, allow: Permissions(allow), deny: Permissions(deny) };
let (view, send) = (Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES);
let mut r = CommunityRoles {
roles: vec![role(&r1, 0), role(&r2, 0)],
grants: vec![MemberGrant { member: m.clone(), role_ids: vec![r1.clone(), r2.clone()] }],
everyone: Some(Permissions(view | send)),
overwrites: vec![ow(OverwriteTarget::Everyone, 0, view | send), ow(OverwriteTarget::Role(r1.clone()), view, 0), ow(OverwriteTarget::Role(r2.clone()), 0, view)],
syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let at = |r: &CommunityRoles, who: &str| r.channel_permissions(Some("o"), who, &ch, false).0;
assert_eq!(at(&r, &m), view, "one role's allow beats another's deny; @everyone's deny of Send stands");
assert_eq!(at(&r, &n), 0, "without View a member holds nothing there");
assert_eq!(at(&r, "o"), u64::MAX, "the owner holds everything");
r.overwrites.push(ow(OverwriteTarget::Member(m.clone()), send, view));
assert_eq!(at(&r, &m), 0, "the member's own overwrite has the last word");
assert!(!r.is_entitled(Some("o"), &m, &ch, &[], &[]), "and the key follows View");
r.overwrites.pop();
assert!(r.is_entitled(Some("o"), &m, &ch, &[], &[]));
assert!(!r.is_entitled(Some("o"), &m, &ch, &[], std::slice::from_ref(&r1)), "losing the allowing role loses the key");
let cat = "d".repeat(64);
r.overwrites.push(Overwrite { scope: cat.clone(), target: OverwriteTarget::Role(r2.clone()), allow: Permissions(0), deny: Permissions(send) });
r.syncs.insert(ch.clone(), cat);
assert_eq!(at(&r, &n), view | send, "a synced channel takes its Category's overwrites, not its own");
assert_eq!(at(&r, &m), view, "including the Category's denies");
}
fn admin_roster(member: &str) -> CommunityRoles {
let role = Role::admin("a".repeat(64));
CommunityRoles {
grants: vec![MemberGrant {
member: member.to_string(),
role_ids: vec![role.role_id.clone()],
}],
roles: vec![role],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
}
}
#[test]
fn admin_role_holds_every_management_bit() {
let p = Permissions::admin();
for bit in [
Permissions::MANAGE_ROLES,
Permissions::MANAGE_CHANNELS,
Permissions::MANAGE_METADATA,
Permissions::KICK,
Permissions::BAN,
Permissions::MANAGE_MESSAGES,
Permissions::CREATE_INVITE,
Permissions::VIEW_AUDIT_LOG,
Permissions::MENTION_EVERYONE,
] {
assert!(p.contains(bit), "admin must hold bit {bit}");
}
}
#[test]
fn social_only_role_is_not_management_nor_admin() {
let social = Permissions(Permissions::MENTION_EVERYONE);
assert!(!social.is_management(), "a purely-social permission is not management");
let role = Role {
role_id: "c".repeat(64),
name: "Hype".into(),
position: 5,
permissions: social,
scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let alice = "aa".repeat(32);
let r = CommunityRoles {
grants: vec![MemberGrant { member: alice.clone(), role_ids: vec![role.role_id.clone()] }],
roles: vec![role],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
assert!(!r.is_admin(&alice), "a social-only role holder is not an admin");
assert!(r.is_privileged(&alice), "though they do hold a role");
}
#[test]
fn hierarchy_only_strictly_higher_can_manage() {
let owner = "00".repeat(32);
let admin = "aa".repeat(32);
let moderator = "bb".repeat(32);
let member = "cc".repeat(32);
let admin_role = Role::admin("a".repeat(64));
let mod_role = Role {
role_id: "b".repeat(64),
name: "Mod".into(),
position: 2,
permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::KICK),
scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let admin_pos = admin_role.position; let mod_pos = mod_role.position; let r = CommunityRoles {
grants: vec![
MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
MemberGrant { member: moderator.clone(), role_ids: vec![mod_role.role_id.clone()] },
],
roles: vec![admin_role, mod_role],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let owner_ref = Some(owner.as_str());
assert!(r.can_manage_position(&owner, owner_ref, admin_pos));
assert!(r.can_manage_member(&owner, owner_ref, &admin));
assert!(!r.can_manage_member(&admin, owner_ref, &owner), "owner is never a valid target");
assert!(!r.can_manage_position(&admin, owner_ref, admin_pos), "admin can't grant a peer-rank role");
assert!(r.can_manage_position(&admin, owner_ref, mod_pos), "admin outranks Mod");
assert!(r.can_manage_member(&admin, owner_ref, &moderator), "admin outranks the mod member");
assert!(r.can_manage_member(&admin, owner_ref, &member), "admin outranks a roleless member");
assert!(!r.can_manage_member(&admin, owner_ref, &admin), "admin can't manage a peer admin");
assert!(!r.can_manage_position(&moderator, owner_ref, admin_pos));
assert!(!r.can_manage_position(&member, owner_ref, mod_pos), "no role, no MANAGE_ROLES → nothing");
}
#[test]
fn can_act_on_member_gates_on_permission_and_rank() {
let owner = "00".repeat(32);
let admin = "aa".repeat(32);
let kicker = "bb".repeat(32);
let member = "cc".repeat(32);
let admin_role = Role::admin("a".repeat(64)); let kick_role = Role {
role_id: "b".repeat(64),
name: "Mod".into(),
position: 2,
permissions: Permissions(Permissions::KICK), scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let r = CommunityRoles {
grants: vec![
MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
MemberGrant { member: kicker.clone(), role_ids: vec![kick_role.role_id.clone()] },
],
roles: vec![admin_role, kick_role],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let o = Some(owner.as_str());
use Permissions as P;
assert!(r.can_act_on_member(&admin, o, &kicker, P::BAN));
assert!(r.can_act_on_member(&admin, o, &member, P::BAN));
assert!(!r.can_act_on_member(&admin, o, &admin, P::BAN), "no banning a peer admin (equal rank)");
assert!(!r.can_act_on_member(&admin, o, &owner, P::BAN), "the owner is never a valid target");
assert!(r.can_act_on_member(&admin, o, &member, P::MANAGE_MESSAGES), "admin can hide a member's msg");
assert!(!r.can_act_on_member(&kicker, o, &member, P::BAN), "no BAN permission → can't ban");
assert!(!r.can_act_on_member(&kicker, o, &member, P::MANAGE_MESSAGES), "no MANAGE_MESSAGES → can't hide");
assert!(r.can_act_on_member(&kicker, o, &member, P::KICK), "but it CAN kick a plain member");
assert!(r.can_act_on_member(&owner, o, &admin, P::BAN));
assert!(!r.can_act_on_member(&member, o, &kicker, P::BAN));
}
#[test]
fn effective_permissions_union_and_position() {
let alice = "aa".repeat(32);
let r = admin_roster(&alice);
assert!(r.has_permission(&alice, Permissions::BAN));
assert!(r.has_permission(&alice, Permissions::MANAGE_ROLES));
assert_eq!(r.highest_position(&alice), Some(1));
assert!(r.is_privileged(&alice));
let bob = "bb".repeat(32);
assert!(!r.has_permission(&bob, Permissions::BAN));
assert_eq!(r.highest_position(&bob), None);
assert!(!r.is_privileged(&bob));
}
#[test]
fn multiple_roles_union_perms_and_take_highest_position() {
let alice = "aa".repeat(32);
let mod_role = Role {
role_id: "b".repeat(64),
name: "Mod".into(),
position: 2,
permissions: Permissions(Permissions::MANAGE_MESSAGES | Permissions::KICK),
scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let admin = Role::admin("a".repeat(64));
let r = CommunityRoles {
grants: vec![MemberGrant {
member: alice.clone(),
role_ids: vec![admin.role_id.clone(), mod_role.role_id.clone()],
}],
roles: vec![admin, mod_role],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
assert!(r.has_permission(&alice, Permissions::BAN)); assert!(r.has_permission(&alice, Permissions::MANAGE_MESSAGES)); assert_eq!(r.highest_position(&alice), Some(1));
}
#[test]
fn round_trips_json() {
let alice = "aa".repeat(32);
let r = admin_roster(&alice);
let json = serde_json::to_string(&r).unwrap();
let back: CommunityRoles = serde_json::from_str(&json).unwrap();
assert_eq!(r, back);
assert!(json.contains("\"kind\":\"server\""));
}
#[test]
fn is_authorized_owner_supreme_admin_by_permission_demoted_rejected() {
let owner = "00".repeat(32);
let alice = "aa".repeat(32);
let r = admin_roster(&alice); assert!(r.is_authorized(&owner, Some(&owner), Permissions::BAN));
assert!(r.is_authorized(&alice, Some(&owner), Permissions::BAN));
let bob = "bb".repeat(32);
assert!(!r.is_authorized(&bob, Some(&owner), Permissions::BAN));
let demoted = CommunityRoles { roles: r.roles.clone(), grants: vec![], everyone: None, overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default() };
assert!(!demoted.is_authorized(&alice, Some(&owner), Permissions::BAN));
assert!(demoted.is_authorized(&owner, Some(&owner), Permissions::BAN));
}
#[test]
fn channel_scope_round_trips() {
let scope = RoleScope::Channel("cc".repeat(32));
let json = serde_json::to_string(&scope).unwrap();
let back: RoleScope = serde_json::from_str(&json).unwrap();
assert_eq!(scope, back);
}
fn scoped_roster(chan: &str, member: &str, admin: &str) -> CommunityRoles {
let scoped = Role {
role_id: "11".repeat(32),
name: "Testers".into(),
position: 5,
permissions: Permissions(Permissions::MANAGE_MESSAGES),
scope: RoleScope::Channel(chan.to_string()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let server = Role::admin("22".repeat(32));
CommunityRoles {
grants: vec![
MemberGrant { member: member.to_string(), role_ids: vec![scoped.role_id.clone()] },
MemberGrant { member: admin.to_string(), role_ids: vec![server.role_id.clone()] },
],
roles: vec![scoped, server],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
}
}
#[test]
fn a_channels_scoped_roles_are_its_access_list() {
let chan = "cc".repeat(32);
let other = "dd".repeat(32);
let owner = "00".repeat(32);
let member = "aa".repeat(32);
let admin = "bb".repeat(32);
let r = scoped_roster(&chan, &member, &admin);
assert_eq!(r.channel_roles(&chan).len(), 1, "the scoped role is the access list");
assert!(r.channel_roles(&other).is_empty(), "another channel gets none of it");
assert!(r.is_entitled(Some(&owner), &member, &chan, &[], &[]), "the granted holder is entitled");
assert!(r.is_entitled(Some(&owner), &owner, &chan, &[], &[]), "the owner is always entitled");
assert!(!r.is_entitled(Some(&owner), &admin, &chan, &[], &[]), "rank alone is not entitlement");
assert!(!r.is_entitled(Some(&owner), &member, &other, &[], &[]), "entitlement does not spill to another channel");
}
#[test]
fn the_grant_overlay_settles_against_a_publish_the_fold_has_not_caught() {
let chan = "cc".repeat(32);
let owner = "00".repeat(32);
let member = "aa".repeat(32);
let stranger = "ee".repeat(32);
let r = scoped_roster(&chan, &member, &"bb".repeat(32));
let scoped_id = r.channel_role_ids(&chan)[0].clone();
assert!(
r.is_entitled(Some(&owner), &stranger, &chan, std::slice::from_ref(&scoped_id), &[]),
"a just-published grant settles as entitled before the fold catches up"
);
assert!(
!r.is_entitled(Some(&owner), &member, &chan, &[], std::slice::from_ref(&scoped_id)),
"a just-published revoke settles as unentitled before the fold catches up"
);
}
#[test]
fn channel_narrowing_is_offer_side_only() {
let chan = "cc".repeat(32);
let other = "dd".repeat(32);
let owner = "00".repeat(32);
let member = "aa".repeat(32);
let r = scoped_roster(&chan, &member, &"bb".repeat(32));
assert!(r.is_authorized_in(&member, Some(&owner), &chan, Permissions::MANAGE_MESSAGES));
assert!(!r.is_authorized_in(&member, Some(&owner), &other, Permissions::MANAGE_MESSAGES));
assert!(
r.is_authorized(&member, Some(&owner), Permissions::MANAGE_MESSAGES),
"the scope-blind honor path is unchanged"
);
}
#[test]
fn founding_mask_is_frozen_at_the_original_nine_bits() {
const ORIGINAL_NINE: u64 = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)
| (1 << 5) | (1 << 6) | (1 << 8) | (1 << 9);
assert_eq!(Permissions::ADMIN_FOUNDING_MASK, ORIGINAL_NINE);
assert!(Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_FOUNDING_MASK));
assert!(Permissions::admin().contains(Permissions::ADMIN_FOUNDING_MASK));
assert!(Permissions::admin().contains(Permissions::PIN_MESSAGES));
assert!(!Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_ALL));
}
}