Skip to main content

vector_core/community/
roles.rs

1//! Concord role graph (GROUP_PROTOCOL.md).
2//!
3//! The MVP exposes a single auto-generated "Admin" role, but this is the FULL graph:
4//! roles are data (not a hardcoded `is_admin` flag), enforcement is capability-based
5//! (effective-permission bits + position), and the engine reads an arbitrary set of
6//! roles + grants. Mod roles, per-channel mods, and custom roles later are just more
7//! `Role` records flowing through the same code — additive, no enforcement changes.
8//!
9//! WIRE MODEL (per-entity): roles and grants do NOT live in the GroupRoot, and they
10//! are NOT one consolidated blob. Each role is its own addressable RoleMetadata event
11//! (vsk=1, d-tag = role_id) and each member's grants are their own Grant event
12//! (vsk=3, d-tag = an opaque per-member locator). So two managers editing *different*
13//! roles or *different* members never clobber each other — only same-coordinate edits
14//! converge (authority-first). `CommunityRoles` here is the in-memory AGGREGATION a
15//! client builds from those fetched per-entity events, not an on-wire document.
16
17use serde::{Deserialize, Serialize};
18
19/// Management/moderation permission bits. Access (read/post a channel) is NOT
20/// here — that is key possession (the two-mechanism split). Bit positions are part of
21/// the wire format and are FROZEN: append a reserved bit, never renumber or reuse one.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct Permissions(pub u64);
25
26/// The bit constants are plain `u64`s, so `Permissions::KICK | Permissions::BAN` converts.
27impl 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    /// Curate a Channel's Pin List (CORD-04 §7) — editorial power: a pin makes
51    /// its message permanently attributable to every future member.
52    pub const PIN_MESSAGES: u64 = 1 << 11;
53    // Channel permissions (CORD-04 §3): what a member may do in a Channel, adjusted per
54    // Channel by its overwrites.
55    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    /// Timeouts (CORD-04 §6).
69    pub const MODERATE_MEMBERS: u64 = 1 << 26;
70    /// Name members beneath them (CORD-04 §10).
71    pub const MANAGE_NICKNAMES: u64 = 1 << 28;
72    /// Name themselves (CORD-04 §10).
73    pub const CHANGE_NICKNAME: u64 = 1 << 29;
74    // 1 << 27, 1 << 30 and 1 << 31 reserved: BYPASS_SLOWMODE, CREATE_PRIVATE_THREADS, MANAGE_THREADS.
75    // Reserved / retired (claim the bit so it's never reassigned):
76    // `1 << 7` was MANAGE_INVITES — RETIRED (per-creator ownership: no one can manage another's
77    // links, so there is nothing to grant; `CREATE_INVITE` mints your own, `BAN` owns the revoking rekey).
78    // MANAGE_EMOJI = 1 << 10, MANAGE_EVENTS = 1 << 12.
79
80    /// The founding nine bits — the mask every Admin role published before
81    /// PIN_MESSAGES existed carries. FROZEN FOREVER: this is the floor the
82    /// admin-role finder tests with, so it must never gain a bit. Widening it
83    /// would orphan every published Admin role and mint duplicates.
84    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    /// Every management bit currently defined — what a newly minted "Admin"
95    /// role holds. MAY widen as bits land; anything that *identifies* an
96    /// existing admin role must test [`Self::ADMIN_FOUNDING_MASK`] instead.
97    pub const ADMIN_ALL: u64 = Self::ADMIN_FOUNDING_MASK | Self::PIN_MESSAGES;
98
99    /// Control-plane bits: exercising any of these signs a control/metadata edition (keyless model —
100    /// the actor's own npub signature IS the authority, re-verified against the roster). Every
101    /// management bit EXCEPT purely-social ones (`MENTION_EVERYONE` acts at the message layer, not the
102    /// control plane). A role with any of these is a "management role" — its holder shows the admin crown.
103    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    /// The STAFF bits (CORD-04 §3): the permissions whose authorized actions
114    /// land as Control Plane editions. A member holding ANY of them — plus
115    /// always the owner — is staff: the set that holds the `control_root`
116    /// write key (CORD-02 §2). `KICK` writes to the Guestbook and
117    /// `MANAGE_MESSAGES` to Chat planes; neither needs it. The list is
118    /// normative — a future permission whose actions are Control editions
119    /// joins it by explicit spec amendment, never by local judgment.
120    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    /// True iff this role carries any management permission (vs. a purely-social role) — i.e. its
134    /// holder counts as an admin.
135    pub fn is_management(self) -> bool {
136        self.0 & Self::MANAGEMENT_MASK != 0
137    }
138    /// True iff every bit in `bits` is set.
139    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/// Discord's "any channel" vs "this channel". Server-scope acts everywhere;
148/// channel-scope is rejected against any other channel.
149#[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 id, lowercase hex.
154    Channel(String),
155}
156
157/// A role: its own addressable RoleMetadata event (vsk=1). Fully general; the MVP
158/// auto-creates exactly one (`Role::admin`).
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct Role {
161    /// Random opaque 32-byte hex id, stable across renames; also the event's d-tag.
162    pub role_id: String,
163    pub name: String,
164    /// Lower = higher authority. Owner is the implicit top (position 0, never a Role).
165    /// Authoritative ordering will move to a single RoleOrder entity when
166    /// drag-reorder ships; until then this declared value is the position (no reordering
167    /// to race in the owner-only MVP).
168    pub position: u32,
169    pub permissions: Permissions,
170    pub scope: RoleScope,
171    /// UI badge color (e.g. the Admin crown); 0 = theme default. Cosmetic.
172    #[serde(default)]
173    pub color: u32,
174    /// The Roles v2 rank key (CORD-04 §3), from which `position` is assigned at fold time.
175    /// `None` for a legacy Role, whose `position` is its own.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub rank: Option<String>,
178    /// Holders list under this Role's own heading.
179    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
180    pub display: bool,
181    /// Any member may @mention it (CORD-03 §3).
182    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
183    pub mentionable: bool,
184    /// Fields another client wrote that this one doesn't model. An edition replaces the
185    /// whole entity, so they ride every republish untouched (CORD-02 §6): dropping them
186    /// would erase another client's data for every member.
187    #[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    /// The MVP's auto-created server-scope Admin role: all management bits, position 1
193    /// (just below the owner). `role_id` is a fresh random opaque id minted at creation.
194    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/// One member's role grants (vsk=3) — its own addressable event so granting Alice
207/// never clobbers Bob's grants. `member` is the grantee's pubkey, lowercase hex (same form
208/// as the banlist), and `role_ids` are the roles they hold (a member can have several).
209#[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/// The role graph a client AGGREGATES from the fetched per-entity events (RoleMetadata +
217/// per-member Grant). Not an on-wire document — the enforcement engine queries this.
218#[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    /// What every member holds before any Role (CORD-04 §2), once Roles v2 is active.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub everyone: Option<Permissions>,
227    /// Channel permission overwrites (CORD-04 §8), on Roles v2.
228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
229    pub overwrites: Vec<Overwrite>,
230    /// Channels that take their Category's overwrites instead of their own: channel → category.
231    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
232    pub syncs: std::collections::BTreeMap<String, String>,
233    /// The Channels that stood before Roles v2 (CORD-04 §2), as the activating `@everyone`
234    /// listed them: the only ones an unmarked Channel edition may still describe.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub legacy_channels: Option<std::collections::BTreeSet<String>>,
237    /// Private Channels' creators, as each Channel's sealed metadata names them: channel → member.
238    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
239    pub creators: std::collections::BTreeMap<String, String>,
240}
241
242/// The bits an overwrite may touch (CORD-04 §8): the channel permissions and
243/// `MANAGE_MESSAGES`. Everything else, staff bits above all, means the same in every Channel.
244pub 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/// Who an overwrite applies to.
261#[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/// One overwrite in one Channel or Category: bits allowed and bits denied on top of what
270/// the target holds server-wide (CORD-04 §8).
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272pub struct Overwrite {
273    /// The Channel or Category id, lowercase hex.
274    pub scope: String,
275    pub target: OverwriteTarget,
276    pub allow: Permissions,
277    pub deny: Permissions,
278}
279
280impl CommunityRoles {
281    /// Look up a role definition by id.
282    pub fn role(&self, role_id: &str) -> Option<&Role> {
283        self.roles.iter().find(|r| r.role_id == role_id)
284    }
285
286    /// The roles granted to `member_hex` (resolved through the grant list).
287    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    /// A member's permissions in one Channel (CORD-04 §8), holding `role_ids` (their Grant,
296    /// or one about to replace it): server permissions, then the Channel's `@everyone`
297    /// overwrite, its Roles' denies then allows, and their own overwrite last. Without
298    /// VIEW_CHANNEL they hold nothing there. The owner holds everything. A private Channel
299    /// is closed to `@everyone` whatever its overwrites say: only a Role's or a member's
300    /// allow opens it, so no overwrite a manager can clear is all that keeps it private.
301    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        // A Private Channel's creator is let in while they manage channels: nobody's own overwrite
309        // can admit them, since none outranks itself (CORD-04 §8).
310        let created = p & Permissions::MANAGE_CHANNELS != 0 && self.creators.get(&channel).is_some_and(|c| c == member_hex);
311        // A synced Channel resolves against its Category's overwrites, ignoring its own.
312        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    /// Whether `@everyone`, resolved up to the View Channel step, may post in a Channel: one
343    /// where it can't is restricted (CORD-03 §1). A legacy Roster restricts nothing.
344    pub fn everyone_sends(&self, channel_hex: &str) -> bool {
345        self.everyone_in(channel_hex).is_none_or(|p| p & Permissions::SEND_MESSAGES != 0)
346    }
347
348    /// Whether `@everyone`, resolved the same way, may write nothing in a Channel: no post, no
349    /// reaction, no call. Such a Channel is Locked: every write takes its writer key. A legacy
350    /// Roster locks nothing.
351    pub fn everyone_writes_nothing(&self, channel_hex: &str) -> bool {
352        self.everyone_in(channel_hex).is_some_and(|p| p & (Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT) == 0)
353    }
354
355    /// Whether `@everyone`, resolved the same way, reads a Channel's history: its earlier planes are
356    /// then every member's (CORD-03 §2). A legacy Roster holds no such bit, and reads it.
357    pub fn everyone_reads_history(&self, channel_hex: &str) -> bool {
358        self.everyone_in(channel_hex).is_none_or(|p| p & Permissions::READ_MESSAGE_HISTORY != 0)
359    }
360
361    /// `@everyone`'s bits in a Channel with only its own overwrite applied (its Category's when
362    /// synced), `None` on a legacy Roster.
363    fn everyone_in(&self, channel_hex: &str) -> Option<u64> {
364        let everyone = self.everyone?;
365        let channel = channel_hex.to_ascii_lowercase();
366        let scope = self.syncs.get(&channel).cloned().unwrap_or(channel);
367        let row = self.overwrites.iter().find(|o| o.scope == scope && o.target == OverwriteTarget::Everyone);
368        Some(row.map_or(everyone.0, |o| (everyone.0 & !o.deny.0) | o.allow.0))
369    }
370
371    /// [`Self::channel_permissions_holding`] for the Roles the member holds now.
372    pub fn channel_permissions(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, private: bool) -> Permissions {
373        let held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).collect();
374        self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, private)
375    }
376
377    /// Effective permissions for a member: `@everyone` and every granted Role's bits.
378    pub fn effective_permissions(&self, member_hex: &str) -> Permissions {
379        self.roles_of(member_hex)
380            .fold(self.everyone.unwrap_or_default(), |acc, r| acc.union(r.permissions))
381    }
382
383    /// The permissions a member holds through Roles positioned strictly above `bound`: the only
384    /// standing an action on something at `bound` may draw on (CORD-04 §3). Authority then flows
385    /// strictly downward, so no Role can prop up the authority that admits it.
386    pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
387        self.roles_of(member_hex)
388            .filter(|r| r.position < bound)
389            .fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
390    }
391
392    /// True iff the member's effective permissions include every bit in `bits`.
393    pub fn has_permission(&self, member_hex: &str, bits: u64) -> bool {
394        self.effective_permissions(member_hex).contains(bits)
395    }
396
397    /// Highest authority (lowest position index) among the member's roles; `None` if
398    /// they hold no role. The owner (implicit position 0) is handled by the caller.
399    pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
400        self.roles_of(member_hex).map(|r| r.position).min()
401    }
402
403    /// True iff the member holds at least one role (i.e. is privileged below the owner).
404    pub fn is_privileged(&self, member_hex: &str) -> bool {
405        self.roles_of(member_hex).next().is_some()
406    }
407
408    /// True iff the member holds a role with management permissions — an "admin" (vs. a member who
409    /// holds only a non-management/social role). Drives the member-list crown.
410    pub fn is_admin(&self, member_hex: &str) -> bool {
411        self.roles_of(member_hex).any(|r| r.permissions.is_management())
412    }
413
414    /// Whether a member is STAFF (CORD-04 §3): the owner, or any holder of a
415    /// Control-writing bit ([`Permissions::STAFF_MASK`]) — the set entitled to
416    /// the `control_root` (CORD-02 §2).
417    pub fn is_staff(&self, member_hex: &str, owner_hex: Option<&str>) -> bool {
418        if owner_hex == Some(member_hex) {
419            return true;
420        }
421        self.effective_permissions(member_hex).0 & Permissions::STAFF_MASK != 0
422    }
423
424    /// Whether a grant's role set leaves its member staff, judged against this
425    /// roster's role definitions — the granter-side trigger for delivering the
426    /// `control_root` inside the Grant itself (CORD-04 §3). An id with no known
427    /// definition contributes nothing (never a reason to hand out the secret).
428    pub fn roles_make_staff(&self, role_ids: &[String]) -> bool {
429        role_ids
430            .iter()
431            .filter_map(|rid| self.role(rid))
432            .any(|r| r.permissions.0 & Permissions::STAFF_MASK != 0)
433    }
434
435    /// Is `actor_hex` authorized for an action requiring `permission`? The **owner** (the
436    /// proven owner npub, if known) is supreme and always authorized; otherwise the actor must hold
437    /// a role granting `permission`. This is the grant-set check the inner-author-proof gates on: a
438    /// demoted member is no longer in the grant set, so their actions stop being honored.
439    pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
440        if owner_hex == Some(actor_hex) {
441            return true;
442        }
443        self.has_permission(actor_hex, permission)
444    }
445
446    /// Every grantee [`is_authorized`](Self::is_authorized) for `permission`, found in one pass
447    /// over the grants rather than one scan of them per member.
448    pub fn authorized_grantees(&self, owner_hex: Option<&str>, permission: u64) -> std::collections::HashSet<&str> {
449        let mut bits: crate::fasthash::FastMap<&str, Permissions> = Default::default();
450        for r in &self.roles {
451            // `role` finds the first of a repeated id.
452            bits.entry(r.role_id.as_str()).or_insert(r.permissions);
453        }
454        let mut held: crate::fasthash::FastMap<&str, Permissions> = Default::default();
455        for g in &self.grants {
456            let member = held.entry(g.member.as_str()).or_insert(self.everyone.unwrap_or_default());
457            for rid in &g.role_ids {
458                if let Some(b) = bits.get(rid.as_str()) {
459                    *member = member.union(*b);
460                }
461            }
462        }
463        held.into_iter().filter(|(m, p)| owner_hex == Some(*m) || p.contains(permission)).map(|(m, _)| m).collect()
464    }
465
466    /// escalation defense — may `actor_hex` manage something sitting at `target_position`
467    /// (grant/revoke/edit/reorder a role)? The actor must **strictly outrank** it (their highest
468    /// authority is a *lower* position number) AND hold `MANAGE_ROLES`. The owner is supreme
469    /// (implicit position 0, above every role) and always may. Equal cannot act on equal: an admin
470    /// can never grant/revoke a peer admin at the same position — only someone strictly above can.
471    /// This is what stops an admin granting the Admin role (`pos == pos`, refused) while still
472    /// letting them manage any role beneath them.
473    pub fn can_manage_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
474        self.can_act_on_position(actor_hex, owner_hex, target_position, Permissions::MANAGE_ROLES)
475    }
476
477    /// May `actor_hex` act on MEMBER `target_hex` for a role change (add/remove a role)? Resolves the
478    /// target's highest authority and applies the `MANAGE_ROLES` position rule. The **owner is never a
479    /// valid target** (supreme, unremovable — the sole hardcoded exception).
480    pub fn can_manage_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
481        self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_ROLES)
482    }
483
484    /// The pure position test (no permission bit): does `actor_hex` **strictly outrank**
485    /// `target_position`? The owner (implicit position 0) outranks everything; a roleless actor
486    /// outranks nothing. This is the position half of every authority check — callers AND it with the
487    /// specific permission the action needs (`BAN`, `MANAGE_MESSAGES`, `MANAGE_ROLES`, ...).
488    pub fn outranks(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
489        if owner_hex == Some(actor_hex) {
490            return true;
491        }
492        match self.highest_position(actor_hex) {
493            Some(p) => p < target_position,
494            None => false,
495        }
496    }
497
498    /// Generalized authority test: may `actor_hex` perform an action requiring `permission` against a
499    /// target at `target_position`? Owner is supreme; otherwise the actor must hold `permission` AND
500    /// strictly outrank the target. (`can_manage_position` is this with `MANAGE_ROLES`; bans pass
501    /// `BAN`, moderation-hides pass `MANAGE_MESSAGES`.)
502    pub fn can_act_on_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32, permission: u64) -> bool {
503        if owner_hex == Some(actor_hex) {
504            return true;
505        }
506        self.has_permission(actor_hex, permission) && self.outranks(actor_hex, owner_hex, target_position)
507    }
508
509    /// Generalized member-targeting authority test (ban / kick / hide / role-change). The **owner is
510    /// never a valid target**; a roleless member sits below everyone. The actor needs `permission`
511    /// plus a strict outrank of the target's highest role.
512    pub fn can_act_on_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str, permission: u64) -> bool {
513        if owner_hex == Some(target_hex) {
514            return false;
515        }
516        let target_position = self.highest_position(target_hex).unwrap_or(u32::MAX);
517        self.can_act_on_position(actor_hex, owner_hex, target_position, permission)
518    }
519
520    /// May `actor_hex` set `target_hex`'s Nickname (CORD-04 §10)? Their own takes `CHANGE_NICKNAME`,
521    /// `@everyone`'s included, and a legacy Roster restricts nobody's; anyone else's takes
522    /// `MANAGE_NICKNAMES` and a strict outrank.
523    pub fn may_name(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
524        if actor_hex != target_hex {
525            return self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_NICKNAMES);
526        }
527        owner_hex == Some(actor_hex) || self.everyone.is_none() || self.has_permission(actor_hex, Permissions::CHANGE_NICKNAME)
528    }
529
530    // ── Private-Channel entitlement (CORD-03/04/06) ──────────────────────────
531    //
532    // CORD-03 defines a Private Channel as "readable only by granted
533    // role-holders", its key "delivered on grant and rekeyed on removal"; the
534    // binding that names those role-holders is CORD-04 §2's
535    // `scope: {"kind":"channel","channel_id":...}`. So **the roles scoped to a
536    // channel are its access list**.
537    //
538    // Read access is enforced by key possession alone — nothing here grants it.
539    // This is the routing that decides who a key is delivered TO on grant, and
540    // who a rekey keeps on revoke.
541
542    /// The roles conferring read access to `channel_hex`, in display order
543    /// (highest authority first).
544    ///
545    /// A Private Channel with none is readable by nobody but the owner and
546    /// whoever already holds the key — degenerate rather than "open", so
547    /// clients shouldn't create it, but one arriving that way from elsewhere
548    /// still reads correctly and its key holders keep reading it.
549    pub fn channel_roles(&self, channel_hex: &str) -> Vec<&Role> {
550        let wanted = channel_hex.to_ascii_lowercase();
551        let mut out: Vec<&Role> = self
552            .roles
553            .iter()
554            .filter(|r| matches!(&r.scope, RoleScope::Channel(c) if c.eq_ignore_ascii_case(&wanted)))
555            .collect();
556        out.sort_by_key(|r| r.position);
557        out
558    }
559
560    /// [`channel_roles`](Self::channel_roles), by id.
561    pub fn channel_role_ids(&self, channel_hex: &str) -> Vec<String> {
562        self.channel_roles(channel_hex).into_iter().map(|r| r.role_id.clone()).collect()
563    }
564
565    /// Is `member_hex` entitled to `channel_hex`'s key? The owner always is
566    /// (position 0, supreme and unremovable).
567    ///
568    /// `with`/`without` overlay a Grant that was JUST published, so a caller can
569    /// settle key custody against the change it just made rather than against a
570    /// fold that lags its own publish.
571    pub fn is_entitled(
572        &self,
573        owner_hex: Option<&str>,
574        member_hex: &str,
575        channel_hex: &str,
576        with: &[String],
577        without: &[String],
578    ) -> bool {
579        if owner_hex == Some(member_hex) {
580            return true;
581        }
582        let held = self.held_with(member_hex, with, without);
583        // On Roles v2 the key follows View Channel as the Channel resolves it (CORD-03 §5).
584        if self.everyone.is_some() {
585            return self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, true).contains(Permissions::VIEW_CHANNEL);
586        }
587        self.channel_role_ids(channel_hex).iter().any(|id| held.contains(id))
588    }
589
590    /// Whether `member_hex` may read `channel_hex`'s history from before their access began,
591    /// under the same overlay as [`Self::is_entitled`]. Legacy rosters have no such bit.
592    pub fn reads_history(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, with: &[String], without: &[String]) -> bool {
593        self.everyone.is_none()
594            || self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &self.held_with(member_hex, with, without), true).contains(Permissions::READ_MESSAGE_HISTORY)
595    }
596
597    fn held_with(&self, member_hex: &str, with: &[String], without: &[String]) -> Vec<String> {
598        let mut held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).filter(|id| !without.contains(id)).collect();
599        for id in with.iter().filter(|id| !without.contains(id)) {
600            if !held.contains(id) {
601                held.push(id.clone());
602            }
603        }
604        held
605    }
606
607    /// Effective permissions for an action TARGETING one channel: server-scope
608    /// roles plus roles scoped to that channel.
609    ///
610    /// ⚠️ **Offer-side only.** The fold stays scope-agnostic in every
611    /// implementation (CORD-04 §3, and [`effective_permissions`](Self::effective_permissions) is what judges
612    /// inbound authority) — this narrows only what THIS client offers its own
613    /// user, never what it honors from others. Tightening the honor path would
614    /// retroactively invalidate actions shipped clients already folded.
615    pub fn effective_permissions_in(&self, member_hex: &str, channel_hex: &str) -> Permissions {
616        let wanted = channel_hex.to_ascii_lowercase();
617        self.roles_of(member_hex)
618            .filter(|r| match &r.scope {
619                RoleScope::Server => true,
620                RoleScope::Channel(c) => c.eq_ignore_ascii_case(&wanted),
621            })
622            .fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
623    }
624
625    /// [`is_authorized`](Self::is_authorized), judged against one channel per
626    /// [`effective_permissions_in`](Self::effective_permissions_in). Offer-side only.
627    pub fn is_authorized_in(&self, actor_hex: &str, owner_hex: Option<&str>, channel_hex: &str, permission: u64) -> bool {
628        if owner_hex == Some(actor_hex) {
629            return true;
630        }
631        self.effective_permissions_in(actor_hex, channel_hex).contains(permission)
632    }
633}
634
635/// One roster's per-member questions answered from each member's Roles gathered once: what
636/// [`CommunityRoles`] answers by scanning every grant per question. A fold asks for each
637/// candidate it judges, so over a large roster the scans dominate.
638pub struct RoleIndex<'a> {
639    everyone: Permissions,
640    by_id: crate::fasthash::FastMap<&'a str, &'a Role>,
641    held: crate::fasthash::FastMap<&'a str, Vec<&'a Role>>,
642}
643
644impl<'a> RoleIndex<'a> {
645    pub fn of(roster: &'a CommunityRoles) -> Self {
646        let mut by_id: crate::fasthash::FastMap<&'a str, &'a Role> = Default::default();
647        for r in &roster.roles {
648            // `role` finds the first of a repeated id.
649            by_id.entry(r.role_id.as_str()).or_insert(r);
650        }
651        let mut held: crate::fasthash::FastMap<&str, Vec<&Role>> = Default::default();
652        for g in &roster.grants {
653            let roles = held.entry(g.member.as_str()).or_default();
654            roles.extend(g.role_ids.iter().filter_map(|rid| by_id.get(rid.as_str()).copied()));
655        }
656        RoleIndex { everyone: roster.everyone.unwrap_or_default(), by_id, held }
657    }
658
659    /// [`CommunityRoles::role`].
660    pub fn role(&self, role_id: &str) -> Option<&'a Role> {
661        self.by_id.get(role_id).copied()
662    }
663
664    fn roles_of(&self, member_hex: &str) -> &[&'a Role] {
665        self.held.get(member_hex).map_or(&[], Vec::as_slice)
666    }
667
668    /// [`CommunityRoles::permissions_above`].
669    pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
670        self.roles_of(member_hex).iter().filter(|r| r.position < bound).fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
671    }
672
673    /// [`CommunityRoles::is_authorized`].
674    pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
675        owner_hex == Some(actor_hex) || self.roles_of(actor_hex).iter().fold(self.everyone, |acc, r| acc.union(r.permissions)).contains(permission)
676    }
677
678    /// [`CommunityRoles::highest_position`].
679    pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
680        self.roles_of(member_hex).iter().map(|r| r.position).min()
681    }
682
683    /// The highest of the member's Role positions strictly above `bound`.
684    pub fn highest_position_above(&self, member_hex: &str, bound: u32) -> Option<u32> {
685        self.roles_of(member_hex).iter().map(|r| r.position).filter(|p| *p < bound).min()
686    }
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    #[test]
694    fn authorized_grantees_agrees_with_asking_each_member() {
695        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
696        let mut next = move |n: u64| {
697            seed ^= seed << 13;
698            seed ^= seed >> 7;
699            seed ^= seed << 17;
700            seed % n
701        };
702        for round in 0..200 {
703            let ids: Vec<String> = (0..6).map(|i| format!("{i:064x}")).collect();
704            let members: Vec<String> = (0..8).map(|i| format!("{:064x}", 100 + i)).collect();
705            // Repeated role ids and members, roles granted that don't exist, @everyone or not.
706            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();
707            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();
708            let r = CommunityRoles { roles, grants, everyone: (next(2) == 0).then(|| Permissions(next(16))), ..Default::default() };
709            let owner = (round % 3 == 0).then(|| members[0].as_str());
710            let index = RoleIndex::of(&r);
711            for bits in 1..16u64 {
712                let fast = r.authorized_grantees(owner, bits);
713                for g in &r.grants {
714                    assert_eq!(fast.contains(g.member.as_str()), r.is_authorized(&g.member, owner, bits), "round {round} bits {bits}");
715                }
716                for m in members.iter().map(String::as_str).chain(["nobody"]) {
717                    assert_eq!(index.is_authorized(m, owner, bits), r.is_authorized(m, owner, bits), "round {round}");
718                }
719            }
720            for m in members.iter().map(String::as_str).chain(["nobody"]) {
721                assert_eq!(index.highest_position(m), r.highest_position(m), "round {round}");
722                for bound in 0..8 {
723                    assert_eq!(index.permissions_above(m, bound), r.permissions_above(m, bound), "round {round} bound {bound}");
724                    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}");
725                }
726            }
727        }
728    }
729
730    #[test]
731    fn a_channel_resolves_everyone_then_roles_then_the_member() {
732        let (r1, r2) = ("1".repeat(64), "2".repeat(64));
733        let (m, n) = ("a".repeat(64), "b".repeat(64));
734        let role = |id: &str, bits: u64| Role { role_id: id.into(), position: 1, permissions: Permissions(bits), ..Role::admin(id.into()) };
735        let ch = "c".repeat(64);
736        let ow = |target, allow: u64, deny: u64| Overwrite { scope: ch.clone(), target, allow: Permissions(allow), deny: Permissions(deny) };
737        let (view, send) = (Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES);
738        let mut r = CommunityRoles {
739            roles: vec![role(&r1, 0), role(&r2, 0)],
740            grants: vec![MemberGrant { member: m.clone(), role_ids: vec![r1.clone(), r2.clone()] }],
741            everyone: Some(Permissions(view | send)),
742            overwrites: vec![ow(OverwriteTarget::Everyone, 0, view | send), ow(OverwriteTarget::Role(r1.clone()), view, 0), ow(OverwriteTarget::Role(r2.clone()), 0, view)],
743            syncs: Default::default(), legacy_channels: None, creators: Default::default(),
744        };
745        let at = |r: &CommunityRoles, who: &str| r.channel_permissions(Some("o"), who, &ch, false).0;
746        assert_eq!(at(&r, &m), view, "one role's allow beats another's deny; @everyone's deny of Send stands");
747        assert_eq!(at(&r, &n), 0, "without View a member holds nothing there");
748        assert_eq!(at(&r, "o"), u64::MAX, "the owner holds everything");
749        r.overwrites.push(ow(OverwriteTarget::Member(m.clone()), send, view));
750        assert_eq!(at(&r, &m), 0, "the member's own overwrite has the last word");
751        assert!(!r.is_entitled(Some("o"), &m, &ch, &[], &[]), "and the key follows View");
752        r.overwrites.pop();
753        assert!(r.is_entitled(Some("o"), &m, &ch, &[], &[]));
754        assert!(!r.is_entitled(Some("o"), &m, &ch, &[], std::slice::from_ref(&r1)), "losing the allowing role loses the key");
755        let cat = "d".repeat(64);
756        r.overwrites.push(Overwrite { scope: cat.clone(), target: OverwriteTarget::Role(r2.clone()), allow: Permissions(0), deny: Permissions(send) });
757        r.syncs.insert(ch.clone(), cat);
758        assert_eq!(at(&r, &n), view | send, "a synced channel takes its Category's overwrites, not its own");
759        assert_eq!(at(&r, &m), view, "including the Category's denies");
760    }
761
762    fn admin_roster(member: &str) -> CommunityRoles {
763        let role = Role::admin("a".repeat(64));
764        CommunityRoles {
765            grants: vec![MemberGrant {
766                member: member.to_string(),
767                role_ids: vec![role.role_id.clone()],
768            }],
769            roles: vec![role],
770            everyone: None,
771            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
772        }
773    }
774
775    #[test]
776    fn admin_role_holds_every_management_bit() {
777        let p = Permissions::admin();
778        for bit in [
779            Permissions::MANAGE_ROLES,
780            Permissions::MANAGE_CHANNELS,
781            Permissions::MANAGE_METADATA,
782            Permissions::KICK,
783            Permissions::BAN,
784            Permissions::MANAGE_MESSAGES,
785            Permissions::CREATE_INVITE,
786            Permissions::VIEW_AUDIT_LOG,
787            Permissions::MENTION_EVERYONE,
788        ] {
789            assert!(p.contains(bit), "admin must hold bit {bit}");
790        }
791    }
792
793    #[test]
794    fn social_only_role_is_not_management_nor_admin() {
795        // A role holding ONLY a social bit (MENTION_EVERYONE) is not "management" and its holder is
796        // NOT an admin — so it gets no crown and no management-secret delivery. Guards the
797        // MANAGEMENT_MASK invariant against a future fat-finger that folds a social bit in.
798        let social = Permissions(Permissions::MENTION_EVERYONE);
799        assert!(!social.is_management(), "a purely-social permission is not management");
800        let role = Role {
801            role_id: "c".repeat(64),
802            name: "Hype".into(),
803            position: 5,
804            permissions: social,
805            scope: RoleScope::Server,
806            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
807        };
808        let alice = "aa".repeat(32);
809        let r = CommunityRoles {
810            grants: vec![MemberGrant { member: alice.clone(), role_ids: vec![role.role_id.clone()] }],
811            roles: vec![role],
812            everyone: None,
813            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
814        };
815        assert!(!r.is_admin(&alice), "a social-only role holder is not an admin");
816        assert!(r.is_privileged(&alice), "though they do hold a role");
817    }
818
819    #[test]
820    fn hierarchy_only_strictly_higher_can_manage() {
821        // owner (implicit pos 0) > admin (pos 1) > mod (pos 2); a plain member holds no role.
822        let owner = "00".repeat(32);
823        let admin = "aa".repeat(32);
824        let moderator = "bb".repeat(32);
825        let member = "cc".repeat(32);
826        let admin_role = Role::admin("a".repeat(64));
827        let mod_role = Role {
828            role_id: "b".repeat(64),
829            name: "Mod".into(),
830            position: 2,
831            permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::KICK),
832            scope: RoleScope::Server,
833            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
834        };
835        let admin_pos = admin_role.position; // 1
836        let mod_pos = mod_role.position; // 2
837        let r = CommunityRoles {
838            grants: vec![
839                MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
840                MemberGrant { member: moderator.clone(), role_ids: vec![mod_role.role_id.clone()] },
841            ],
842            roles: vec![admin_role, mod_role],
843            everyone: None,
844            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
845        };
846        let owner_ref = Some(owner.as_str());
847
848        // Owner is supreme — outranks every position and every member, can't be targeted.
849        assert!(r.can_manage_position(&owner, owner_ref, admin_pos));
850        assert!(r.can_manage_member(&owner, owner_ref, &admin));
851        assert!(!r.can_manage_member(&admin, owner_ref, &owner), "owner is never a valid target");
852
853        // Equal cannot act on equal: an admin can NOT manage the Admin position (closes self/peer
854        // escalation — granting the Admin role), but CAN manage everything strictly below.
855        assert!(!r.can_manage_position(&admin, owner_ref, admin_pos), "admin can't grant a peer-rank role");
856        assert!(r.can_manage_position(&admin, owner_ref, mod_pos), "admin outranks Mod");
857        assert!(r.can_manage_member(&admin, owner_ref, &moderator), "admin outranks the mod member");
858        assert!(r.can_manage_member(&admin, owner_ref, &member), "admin outranks a roleless member");
859        assert!(!r.can_manage_member(&admin, owner_ref, &admin), "admin can't manage a peer admin");
860
861        // A mod can't reach up to the Admin position, and a roleless member can manage nothing.
862        assert!(!r.can_manage_position(&moderator, owner_ref, admin_pos));
863        assert!(!r.can_manage_position(&member, owner_ref, mod_pos), "no role, no MANAGE_ROLES → nothing");
864    }
865
866    #[test]
867    fn can_act_on_member_gates_on_permission_and_rank() {
868        // owner (pos 0), a BAN-capable admin (pos 1), a Mod with KICK-only (pos 2, NO ban), a plain
869        // member (no role). Verifies the generalized gate requires BOTH the right permission AND a
870        // strict outrank — the rule ban/hide use, distinct from MANAGE_ROLES.
871        let owner = "00".repeat(32);
872        let admin = "aa".repeat(32);
873        let kicker = "bb".repeat(32);
874        let member = "cc".repeat(32);
875        let admin_role = Role::admin("a".repeat(64)); // pos 1, ADMIN_ALL (incl. BAN + MANAGE_MESSAGES)
876        let kick_role = Role {
877            role_id: "b".repeat(64),
878            name: "Mod".into(),
879            position: 2,
880            permissions: Permissions(Permissions::KICK), // KICK only — NO ban, NO manage-messages
881            scope: RoleScope::Server,
882            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
883        };
884        let r = CommunityRoles {
885            grants: vec![
886                MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
887                MemberGrant { member: kicker.clone(), role_ids: vec![kick_role.role_id.clone()] },
888            ],
889            roles: vec![admin_role, kick_role],
890            everyone: None,
891            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
892        };
893        let o = Some(owner.as_str());
894        use Permissions as P;
895
896        // The BAN-capable admin: bans the Mod and a plain member, but NOT a peer admin, NOT the owner.
897        assert!(r.can_act_on_member(&admin, o, &kicker, P::BAN));
898        assert!(r.can_act_on_member(&admin, o, &member, P::BAN));
899        assert!(!r.can_act_on_member(&admin, o, &admin, P::BAN), "no banning a peer admin (equal rank)");
900        assert!(!r.can_act_on_member(&admin, o, &owner, P::BAN), "the owner is never a valid target");
901        assert!(r.can_act_on_member(&admin, o, &member, P::MANAGE_MESSAGES), "admin can hide a member's msg");
902
903        // The Mod has KICK but NOT BAN/MANAGE_MESSAGES → the permission gate refuses even a target it outranks.
904        assert!(!r.can_act_on_member(&kicker, o, &member, P::BAN), "no BAN permission → can't ban");
905        assert!(!r.can_act_on_member(&kicker, o, &member, P::MANAGE_MESSAGES), "no MANAGE_MESSAGES → can't hide");
906        assert!(r.can_act_on_member(&kicker, o, &member, P::KICK), "but it CAN kick a plain member");
907
908        // The owner is supreme for any permission, against anyone.
909        assert!(r.can_act_on_member(&owner, o, &admin, P::BAN));
910        // A plain member can do nothing.
911        assert!(!r.can_act_on_member(&member, o, &kicker, P::BAN));
912    }
913
914    #[test]
915    fn effective_permissions_union_and_position() {
916        let alice = "aa".repeat(32);
917        let r = admin_roster(&alice);
918        assert!(r.has_permission(&alice, Permissions::BAN));
919        assert!(r.has_permission(&alice, Permissions::MANAGE_ROLES));
920        assert_eq!(r.highest_position(&alice), Some(1));
921        assert!(r.is_privileged(&alice));
922
923        // A member with no grant has no permissions and no position.
924        let bob = "bb".repeat(32);
925        assert!(!r.has_permission(&bob, Permissions::BAN));
926        assert_eq!(r.highest_position(&bob), None);
927        assert!(!r.is_privileged(&bob));
928    }
929
930    #[test]
931    fn multiple_roles_union_perms_and_take_highest_position() {
932        let alice = "aa".repeat(32);
933        let mod_role = Role {
934            role_id: "b".repeat(64),
935            name: "Mod".into(),
936            position: 2,
937            permissions: Permissions(Permissions::MANAGE_MESSAGES | Permissions::KICK),
938            scope: RoleScope::Server,
939            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
940        };
941        let admin = Role::admin("a".repeat(64));
942        let r = CommunityRoles {
943            grants: vec![MemberGrant {
944                member: alice.clone(),
945                role_ids: vec![admin.role_id.clone(), mod_role.role_id.clone()],
946            }],
947            roles: vec![admin, mod_role],
948            everyone: None,
949            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
950        };
951        // Union of both roles' bits, and the *highest* (lowest index) position wins.
952        assert!(r.has_permission(&alice, Permissions::BAN)); // from Admin
953        assert!(r.has_permission(&alice, Permissions::MANAGE_MESSAGES)); // from both
954        assert_eq!(r.highest_position(&alice), Some(1));
955    }
956
957    #[test]
958    fn round_trips_json() {
959        let alice = "aa".repeat(32);
960        let r = admin_roster(&alice);
961        let json = serde_json::to_string(&r).unwrap();
962        let back: CommunityRoles = serde_json::from_str(&json).unwrap();
963        assert_eq!(r, back);
964        assert!(json.contains("\"kind\":\"server\""));
965    }
966
967    #[test]
968    fn is_authorized_owner_supreme_admin_by_permission_demoted_rejected() {
969        let owner = "00".repeat(32);
970        let alice = "aa".repeat(32);
971        let r = admin_roster(&alice); // alice granted Admin (has BAN)
972        // Owner is always authorized, even without a role.
973        assert!(r.is_authorized(&owner, Some(&owner), Permissions::BAN));
974        // Admin Alice is authorized for BAN via her role.
975        assert!(r.is_authorized(&alice, Some(&owner), Permissions::BAN));
976        // A member with no role (Bob) is not — and neither is Alice once demoted (no grant).
977        let bob = "bb".repeat(32);
978        assert!(!r.is_authorized(&bob, Some(&owner), Permissions::BAN));
979        let demoted = CommunityRoles { roles: r.roles.clone(), grants: vec![], everyone: None, overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default() };
980        assert!(!demoted.is_authorized(&alice, Some(&owner), Permissions::BAN));
981        // ...but the owner stays authorized even with an empty grant set.
982        assert!(demoted.is_authorized(&owner, Some(&owner), Permissions::BAN));
983    }
984
985    #[test]
986    fn channel_scope_round_trips() {
987        let scope = RoleScope::Channel("cc".repeat(32));
988        let json = serde_json::to_string(&scope).unwrap();
989        let back: RoleScope = serde_json::from_str(&json).unwrap();
990        assert_eq!(scope, back);
991    }
992
993    // ── Private-Channel entitlement ──────────────────────────────────────────
994
995    /// A roster with one channel-scoped role (`pos` 5) over `chan`, granted to
996    /// `member`, plus a server-scope Admin held by `admin`.
997    fn scoped_roster(chan: &str, member: &str, admin: &str) -> CommunityRoles {
998        let scoped = Role {
999            role_id: "11".repeat(32),
1000            name: "Testers".into(),
1001            position: 5,
1002            permissions: Permissions(Permissions::MANAGE_MESSAGES),
1003            scope: RoleScope::Channel(chan.to_string()),
1004            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
1005        };
1006        let server = Role::admin("22".repeat(32));
1007        CommunityRoles {
1008            grants: vec![
1009                MemberGrant { member: member.to_string(), role_ids: vec![scoped.role_id.clone()] },
1010                MemberGrant { member: admin.to_string(), role_ids: vec![server.role_id.clone()] },
1011            ],
1012            roles: vec![scoped, server],
1013            everyone: None,
1014            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
1015        }
1016    }
1017
1018    #[test]
1019    fn a_channels_scoped_roles_are_its_access_list() {
1020        let chan = "cc".repeat(32);
1021        let other = "dd".repeat(32);
1022        let owner = "00".repeat(32);
1023        let member = "aa".repeat(32);
1024        let admin = "bb".repeat(32);
1025        let r = scoped_roster(&chan, &member, &admin);
1026
1027        assert_eq!(r.channel_roles(&chan).len(), 1, "the scoped role is the access list");
1028        assert!(r.channel_roles(&other).is_empty(), "another channel gets none of it");
1029
1030        assert!(r.is_entitled(Some(&owner), &member, &chan, &[], &[]), "the granted holder is entitled");
1031        assert!(r.is_entitled(Some(&owner), &owner, &chan, &[], &[]), "the owner is always entitled");
1032        // A SERVER-scope Admin is not automatically entitled: entitlement is the
1033        // channel's scoped roles, never rank (CORD-03 — key possession, not authority).
1034        assert!(!r.is_entitled(Some(&owner), &admin, &chan, &[], &[]), "rank alone is not entitlement");
1035        assert!(!r.is_entitled(Some(&owner), &member, &other, &[], &[]), "entitlement does not spill to another channel");
1036    }
1037
1038    #[test]
1039    fn the_grant_overlay_settles_against_a_publish_the_fold_has_not_caught() {
1040        let chan = "cc".repeat(32);
1041        let owner = "00".repeat(32);
1042        let member = "aa".repeat(32);
1043        let stranger = "ee".repeat(32);
1044        let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1045        let scoped_id = r.channel_role_ids(&chan)[0].clone();
1046
1047        assert!(
1048            r.is_entitled(Some(&owner), &stranger, &chan, std::slice::from_ref(&scoped_id), &[]),
1049            "a just-published grant settles as entitled before the fold catches up"
1050        );
1051        assert!(
1052            !r.is_entitled(Some(&owner), &member, &chan, &[], std::slice::from_ref(&scoped_id)),
1053            "a just-published revoke settles as unentitled before the fold catches up"
1054        );
1055    }
1056
1057    #[test]
1058    fn channel_narrowing_is_offer_side_only() {
1059        let chan = "cc".repeat(32);
1060        let other = "dd".repeat(32);
1061        let owner = "00".repeat(32);
1062        let member = "aa".repeat(32);
1063        let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1064
1065        // Narrowed: the scoped role's bits apply in ITS channel and nowhere else.
1066        assert!(r.is_authorized_in(&member, Some(&owner), &chan, Permissions::MANAGE_MESSAGES));
1067        assert!(!r.is_authorized_in(&member, Some(&owner), &other, Permissions::MANAGE_MESSAGES));
1068
1069        // The HONOR path stays scope-agnostic — every implementation folds the
1070        // same union (CORD-04 §3). Tightening this would retroactively invalidate
1071        // actions shipped clients already folded.
1072        assert!(
1073            r.is_authorized(&member, Some(&owner), Permissions::MANAGE_MESSAGES),
1074            "the scope-blind honor path is unchanged"
1075        );
1076    }
1077
1078    /// The founding mask is the admin-FINDER's floor and is frozen forever: a
1079    /// role minted under the ORIGINAL nine bits must always satisfy it, or
1080    /// every published Admin role orphans and the finder mints duplicates.
1081    #[test]
1082    fn founding_mask_is_frozen_at_the_original_nine_bits() {
1083        const ORIGINAL_NINE: u64 = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)
1084            | (1 << 5) | (1 << 6) | (1 << 8) | (1 << 9);
1085        assert_eq!(Permissions::ADMIN_FOUNDING_MASK, ORIGINAL_NINE);
1086        // A legacy admin role (pre-PIN_MESSAGES) still passes the finder's test...
1087        assert!(Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_FOUNDING_MASK));
1088        // ...and a newly minted one does too (ADMIN_ALL may widen, and has).
1089        assert!(Permissions::admin().contains(Permissions::ADMIN_FOUNDING_MASK));
1090        assert!(Permissions::admin().contains(Permissions::PIN_MESSAGES));
1091        // But a legacy role does NOT contain the widened ADMIN_ALL — the exact
1092        // reason nothing may identify admins with it.
1093        assert!(!Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_ALL));
1094    }
1095}