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    /// The bits `me` may set in an overwrite on `target` (CORD-04 §3): every bit from its Roles
393    /// strictly above the target, while Manage Roles is among them. The owner may set any on
394    /// anyone but themselves. `None`: nothing at all. An edit must keep every bit it carries,
395    /// and every bit it changes, inside this.
396    pub fn overwrite_support(&self, me: &str, owner_hex: &str, target: &OverwriteTarget) -> Option<u64> {
397        let reach = match target {
398            OverwriteTarget::Member(m) if m == owner_hex => return None,
399            _ if me == owner_hex => return Some(u64::MAX),
400            OverwriteTarget::Everyone => u32::MAX,
401            OverwriteTarget::Role(id) => self.role(id)?.position,
402            OverwriteTarget::Member(m) => self.highest_position(m).unwrap_or(u32::MAX),
403        };
404        let held = self.permissions_above(me, reach);
405        held.contains(Permissions::MANAGE_ROLES).then_some(held.0)
406    }
407
408    /// True iff the member's effective permissions include every bit in `bits`.
409    pub fn has_permission(&self, member_hex: &str, bits: u64) -> bool {
410        self.effective_permissions(member_hex).contains(bits)
411    }
412
413    /// Highest authority (lowest position index) among the member's roles; `None` if
414    /// they hold no role. The owner (implicit position 0) is handled by the caller.
415    pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
416        self.roles_of(member_hex).map(|r| r.position).min()
417    }
418
419    /// True iff the member holds at least one role (i.e. is privileged below the owner).
420    pub fn is_privileged(&self, member_hex: &str) -> bool {
421        self.roles_of(member_hex).next().is_some()
422    }
423
424    /// True iff the member holds a role with management permissions — an "admin" (vs. a member who
425    /// holds only a non-management/social role). Drives the member-list crown.
426    pub fn is_admin(&self, member_hex: &str) -> bool {
427        self.roles_of(member_hex).any(|r| r.permissions.is_management())
428    }
429
430    /// Whether a member is STAFF (CORD-04 §3): the owner, or any holder of a
431    /// Control-writing bit ([`Permissions::STAFF_MASK`]) — the set entitled to
432    /// the `control_root` (CORD-02 §2).
433    pub fn is_staff(&self, member_hex: &str, owner_hex: Option<&str>) -> bool {
434        if owner_hex == Some(member_hex) {
435            return true;
436        }
437        self.effective_permissions(member_hex).0 & Permissions::STAFF_MASK != 0
438    }
439
440    /// Whether a grant's role set leaves its member staff, judged against this
441    /// roster's role definitions — the granter-side trigger for delivering the
442    /// `control_root` inside the Grant itself (CORD-04 §3). An id with no known
443    /// definition contributes nothing (never a reason to hand out the secret).
444    pub fn roles_make_staff(&self, role_ids: &[String]) -> bool {
445        role_ids
446            .iter()
447            .filter_map(|rid| self.role(rid))
448            .any(|r| r.permissions.0 & Permissions::STAFF_MASK != 0)
449    }
450
451    /// Is `actor_hex` authorized for an action requiring `permission`? The **owner** (the
452    /// proven owner npub, if known) is supreme and always authorized; otherwise the actor must hold
453    /// a role granting `permission`. This is the grant-set check the inner-author-proof gates on: a
454    /// demoted member is no longer in the grant set, so their actions stop being honored.
455    pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
456        if owner_hex == Some(actor_hex) {
457            return true;
458        }
459        self.has_permission(actor_hex, permission)
460    }
461
462    /// Every grantee [`is_authorized`](Self::is_authorized) for `permission`, found in one pass
463    /// over the grants rather than one scan of them per member.
464    pub fn authorized_grantees(&self, owner_hex: Option<&str>, permission: u64) -> std::collections::HashSet<&str> {
465        let mut bits: crate::fasthash::FastMap<&str, Permissions> = Default::default();
466        for r in &self.roles {
467            // `role` finds the first of a repeated id.
468            bits.entry(r.role_id.as_str()).or_insert(r.permissions);
469        }
470        let mut held: crate::fasthash::FastMap<&str, Permissions> = Default::default();
471        for g in &self.grants {
472            let member = held.entry(g.member.as_str()).or_insert(self.everyone.unwrap_or_default());
473            for rid in &g.role_ids {
474                if let Some(b) = bits.get(rid.as_str()) {
475                    *member = member.union(*b);
476                }
477            }
478        }
479        held.into_iter().filter(|(m, p)| owner_hex == Some(*m) || p.contains(permission)).map(|(m, _)| m).collect()
480    }
481
482    /// escalation defense — may `actor_hex` manage something sitting at `target_position`
483    /// (grant/revoke/edit/reorder a role)? The actor must **strictly outrank** it (their highest
484    /// authority is a *lower* position number) AND hold `MANAGE_ROLES`. The owner is supreme
485    /// (implicit position 0, above every role) and always may. Equal cannot act on equal: an admin
486    /// can never grant/revoke a peer admin at the same position — only someone strictly above can.
487    /// This is what stops an admin granting the Admin role (`pos == pos`, refused) while still
488    /// letting them manage any role beneath them.
489    pub fn can_manage_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
490        self.can_act_on_position(actor_hex, owner_hex, target_position, Permissions::MANAGE_ROLES)
491    }
492
493    /// May `actor_hex` act on MEMBER `target_hex` for a role change (add/remove a role)? Resolves the
494    /// target's highest authority and applies the `MANAGE_ROLES` position rule. The **owner is never a
495    /// valid target** (supreme, unremovable — the sole hardcoded exception).
496    pub fn can_manage_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
497        self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_ROLES)
498    }
499
500    /// The pure position test (no permission bit): does `actor_hex` **strictly outrank**
501    /// `target_position`? The owner (implicit position 0) outranks everything; a roleless actor
502    /// outranks nothing. This is the position half of every authority check — callers AND it with the
503    /// specific permission the action needs (`BAN`, `MANAGE_MESSAGES`, `MANAGE_ROLES`, ...).
504    pub fn outranks(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32) -> bool {
505        if owner_hex == Some(actor_hex) {
506            return true;
507        }
508        match self.highest_position(actor_hex) {
509            Some(p) => p < target_position,
510            None => false,
511        }
512    }
513
514    /// Generalized authority test: may `actor_hex` perform an action requiring `permission` against a
515    /// target at `target_position`? Owner is supreme; otherwise the actor must hold `permission` AND
516    /// strictly outrank the target. (`can_manage_position` is this with `MANAGE_ROLES`; bans pass
517    /// `BAN`, moderation-hides pass `MANAGE_MESSAGES`.)
518    pub fn can_act_on_position(&self, actor_hex: &str, owner_hex: Option<&str>, target_position: u32, permission: u64) -> bool {
519        if owner_hex == Some(actor_hex) {
520            return true;
521        }
522        self.has_permission(actor_hex, permission) && self.outranks(actor_hex, owner_hex, target_position)
523    }
524
525    /// Generalized member-targeting authority test (ban / kick / hide / role-change). The **owner is
526    /// never a valid target**; a roleless member sits below everyone. The actor needs `permission`
527    /// plus a strict outrank of the target's highest role.
528    pub fn can_act_on_member(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str, permission: u64) -> bool {
529        if owner_hex == Some(target_hex) {
530            return false;
531        }
532        let target_position = self.highest_position(target_hex).unwrap_or(u32::MAX);
533        self.can_act_on_position(actor_hex, owner_hex, target_position, permission)
534    }
535
536    /// May `actor_hex` set `target_hex`'s Nickname (CORD-04 §10)? Their own takes `CHANGE_NICKNAME`,
537    /// `@everyone`'s included, and a legacy Roster restricts nobody's; anyone else's takes
538    /// `MANAGE_NICKNAMES` and a strict outrank.
539    pub fn may_name(&self, actor_hex: &str, owner_hex: Option<&str>, target_hex: &str) -> bool {
540        if actor_hex != target_hex {
541            return self.can_act_on_member(actor_hex, owner_hex, target_hex, Permissions::MANAGE_NICKNAMES);
542        }
543        owner_hex == Some(actor_hex) || self.everyone.is_none() || self.has_permission(actor_hex, Permissions::CHANGE_NICKNAME)
544    }
545
546    // ── Private-Channel entitlement (CORD-03/04/06) ──────────────────────────
547    //
548    // CORD-03 defines a Private Channel as "readable only by granted
549    // role-holders", its key "delivered on grant and rekeyed on removal"; the
550    // binding that names those role-holders is CORD-04 §2's
551    // `scope: {"kind":"channel","channel_id":...}`. So **the roles scoped to a
552    // channel are its access list**.
553    //
554    // Read access is enforced by key possession alone — nothing here grants it.
555    // This is the routing that decides who a key is delivered TO on grant, and
556    // who a rekey keeps on revoke.
557
558    /// The roles conferring read access to `channel_hex`, in display order
559    /// (highest authority first).
560    ///
561    /// A Private Channel with none is readable by nobody but the owner and
562    /// whoever already holds the key — degenerate rather than "open", so
563    /// clients shouldn't create it, but one arriving that way from elsewhere
564    /// still reads correctly and its key holders keep reading it.
565    pub fn channel_roles(&self, channel_hex: &str) -> Vec<&Role> {
566        let wanted = channel_hex.to_ascii_lowercase();
567        let mut out: Vec<&Role> = self
568            .roles
569            .iter()
570            .filter(|r| matches!(&r.scope, RoleScope::Channel(c) if c.eq_ignore_ascii_case(&wanted)))
571            .collect();
572        out.sort_by_key(|r| r.position);
573        out
574    }
575
576    /// [`channel_roles`](Self::channel_roles), by id.
577    pub fn channel_role_ids(&self, channel_hex: &str) -> Vec<String> {
578        self.channel_roles(channel_hex).into_iter().map(|r| r.role_id.clone()).collect()
579    }
580
581    /// Is `member_hex` entitled to `channel_hex`'s key? The owner always is
582    /// (position 0, supreme and unremovable).
583    ///
584    /// `with`/`without` overlay a Grant that was JUST published, so a caller can
585    /// settle key custody against the change it just made rather than against a
586    /// fold that lags its own publish.
587    pub fn is_entitled(
588        &self,
589        owner_hex: Option<&str>,
590        member_hex: &str,
591        channel_hex: &str,
592        with: &[String],
593        without: &[String],
594    ) -> bool {
595        if owner_hex == Some(member_hex) {
596            return true;
597        }
598        let held = self.held_with(member_hex, with, without);
599        // On Roles v2 the key follows View Channel as the Channel resolves it (CORD-03 §5).
600        if self.everyone.is_some() {
601            return self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &held, true).contains(Permissions::VIEW_CHANNEL);
602        }
603        self.channel_role_ids(channel_hex).iter().any(|id| held.contains(id))
604    }
605
606    /// Whether `member_hex` may read `channel_hex`'s history from before their access began,
607    /// under the same overlay as [`Self::is_entitled`]. Legacy rosters have no such bit.
608    pub fn reads_history(&self, owner_hex: Option<&str>, member_hex: &str, channel_hex: &str, with: &[String], without: &[String]) -> bool {
609        self.everyone.is_none()
610            || self.channel_permissions_holding(owner_hex, member_hex, channel_hex, &self.held_with(member_hex, with, without), true).contains(Permissions::READ_MESSAGE_HISTORY)
611    }
612
613    fn held_with(&self, member_hex: &str, with: &[String], without: &[String]) -> Vec<String> {
614        let mut held: Vec<String> = self.roles_of(member_hex).map(|r| r.role_id.clone()).filter(|id| !without.contains(id)).collect();
615        for id in with.iter().filter(|id| !without.contains(id)) {
616            if !held.contains(id) {
617                held.push(id.clone());
618            }
619        }
620        held
621    }
622
623    /// Effective permissions for an action TARGETING one channel: server-scope
624    /// roles plus roles scoped to that channel.
625    ///
626    /// ⚠️ **Offer-side only.** The fold stays scope-agnostic in every
627    /// implementation (CORD-04 §3, and [`effective_permissions`](Self::effective_permissions) is what judges
628    /// inbound authority) — this narrows only what THIS client offers its own
629    /// user, never what it honors from others. Tightening the honor path would
630    /// retroactively invalidate actions shipped clients already folded.
631    pub fn effective_permissions_in(&self, member_hex: &str, channel_hex: &str) -> Permissions {
632        let wanted = channel_hex.to_ascii_lowercase();
633        self.roles_of(member_hex)
634            .filter(|r| match &r.scope {
635                RoleScope::Server => true,
636                RoleScope::Channel(c) => c.eq_ignore_ascii_case(&wanted),
637            })
638            .fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
639    }
640
641    /// [`is_authorized`](Self::is_authorized), judged against one channel per
642    /// [`effective_permissions_in`](Self::effective_permissions_in). Offer-side only.
643    pub fn is_authorized_in(&self, actor_hex: &str, owner_hex: Option<&str>, channel_hex: &str, permission: u64) -> bool {
644        if owner_hex == Some(actor_hex) {
645            return true;
646        }
647        self.effective_permissions_in(actor_hex, channel_hex).contains(permission)
648    }
649}
650
651/// One roster's per-member questions answered from each member's Roles gathered once: what
652/// [`CommunityRoles`] answers by scanning every grant per question. A fold asks for each
653/// candidate it judges, so over a large roster the scans dominate.
654pub struct RoleIndex<'a> {
655    everyone: Permissions,
656    by_id: crate::fasthash::FastMap<&'a str, &'a Role>,
657    held: crate::fasthash::FastMap<&'a str, Vec<&'a Role>>,
658}
659
660impl<'a> RoleIndex<'a> {
661    pub fn of(roster: &'a CommunityRoles) -> Self {
662        let mut by_id: crate::fasthash::FastMap<&'a str, &'a Role> = Default::default();
663        for r in &roster.roles {
664            // `role` finds the first of a repeated id.
665            by_id.entry(r.role_id.as_str()).or_insert(r);
666        }
667        let mut held: crate::fasthash::FastMap<&str, Vec<&Role>> = Default::default();
668        for g in &roster.grants {
669            let roles = held.entry(g.member.as_str()).or_default();
670            roles.extend(g.role_ids.iter().filter_map(|rid| by_id.get(rid.as_str()).copied()));
671        }
672        RoleIndex { everyone: roster.everyone.unwrap_or_default(), by_id, held }
673    }
674
675    /// [`CommunityRoles::role`].
676    pub fn role(&self, role_id: &str) -> Option<&'a Role> {
677        self.by_id.get(role_id).copied()
678    }
679
680    fn roles_of(&self, member_hex: &str) -> &[&'a Role] {
681        self.held.get(member_hex).map_or(&[], Vec::as_slice)
682    }
683
684    /// [`CommunityRoles::permissions_above`].
685    pub fn permissions_above(&self, member_hex: &str, bound: u32) -> Permissions {
686        self.roles_of(member_hex).iter().filter(|r| r.position < bound).fold(Permissions::empty(), |acc, r| acc.union(r.permissions))
687    }
688
689    /// [`CommunityRoles::is_authorized`].
690    pub fn is_authorized(&self, actor_hex: &str, owner_hex: Option<&str>, permission: u64) -> bool {
691        owner_hex == Some(actor_hex) || self.roles_of(actor_hex).iter().fold(self.everyone, |acc, r| acc.union(r.permissions)).contains(permission)
692    }
693
694    /// [`CommunityRoles::highest_position`].
695    pub fn highest_position(&self, member_hex: &str) -> Option<u32> {
696        self.roles_of(member_hex).iter().map(|r| r.position).min()
697    }
698
699    /// The highest of the member's Role positions strictly above `bound`.
700    pub fn highest_position_above(&self, member_hex: &str, bound: u32) -> Option<u32> {
701        self.roles_of(member_hex).iter().map(|r| r.position).filter(|p| *p < bound).min()
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    #[test]
710    fn authorized_grantees_agrees_with_asking_each_member() {
711        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
712        let mut next = move |n: u64| {
713            seed ^= seed << 13;
714            seed ^= seed >> 7;
715            seed ^= seed << 17;
716            seed % n
717        };
718        for round in 0..200 {
719            let ids: Vec<String> = (0..6).map(|i| format!("{i:064x}")).collect();
720            let members: Vec<String> = (0..8).map(|i| format!("{:064x}", 100 + i)).collect();
721            // Repeated role ids and members, roles granted that don't exist, @everyone or not.
722            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();
723            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();
724            let r = CommunityRoles { roles, grants, everyone: (next(2) == 0).then(|| Permissions(next(16))), ..Default::default() };
725            let owner = (round % 3 == 0).then(|| members[0].as_str());
726            let index = RoleIndex::of(&r);
727            for bits in 1..16u64 {
728                let fast = r.authorized_grantees(owner, bits);
729                for g in &r.grants {
730                    assert_eq!(fast.contains(g.member.as_str()), r.is_authorized(&g.member, owner, bits), "round {round} bits {bits}");
731                }
732                for m in members.iter().map(String::as_str).chain(["nobody"]) {
733                    assert_eq!(index.is_authorized(m, owner, bits), r.is_authorized(m, owner, bits), "round {round}");
734                }
735            }
736            for m in members.iter().map(String::as_str).chain(["nobody"]) {
737                assert_eq!(index.highest_position(m), r.highest_position(m), "round {round}");
738                for bound in 0..8 {
739                    assert_eq!(index.permissions_above(m, bound), r.permissions_above(m, bound), "round {round} bound {bound}");
740                    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}");
741                }
742            }
743        }
744    }
745
746    #[test]
747    fn a_channel_resolves_everyone_then_roles_then_the_member() {
748        let (r1, r2) = ("1".repeat(64), "2".repeat(64));
749        let (m, n) = ("a".repeat(64), "b".repeat(64));
750        let role = |id: &str, bits: u64| Role { role_id: id.into(), position: 1, permissions: Permissions(bits), ..Role::admin(id.into()) };
751        let ch = "c".repeat(64);
752        let ow = |target, allow: u64, deny: u64| Overwrite { scope: ch.clone(), target, allow: Permissions(allow), deny: Permissions(deny) };
753        let (view, send) = (Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES);
754        let mut r = CommunityRoles {
755            roles: vec![role(&r1, 0), role(&r2, 0)],
756            grants: vec![MemberGrant { member: m.clone(), role_ids: vec![r1.clone(), r2.clone()] }],
757            everyone: Some(Permissions(view | send)),
758            overwrites: vec![ow(OverwriteTarget::Everyone, 0, view | send), ow(OverwriteTarget::Role(r1.clone()), view, 0), ow(OverwriteTarget::Role(r2.clone()), 0, view)],
759            syncs: Default::default(), legacy_channels: None, creators: Default::default(),
760        };
761        let at = |r: &CommunityRoles, who: &str| r.channel_permissions(Some("o"), who, &ch, false).0;
762        assert_eq!(at(&r, &m), view, "one role's allow beats another's deny; @everyone's deny of Send stands");
763        assert_eq!(at(&r, &n), 0, "without View a member holds nothing there");
764        assert_eq!(at(&r, "o"), u64::MAX, "the owner holds everything");
765        r.overwrites.push(ow(OverwriteTarget::Member(m.clone()), send, view));
766        assert_eq!(at(&r, &m), 0, "the member's own overwrite has the last word");
767        assert!(!r.is_entitled(Some("o"), &m, &ch, &[], &[]), "and the key follows View");
768        r.overwrites.pop();
769        assert!(r.is_entitled(Some("o"), &m, &ch, &[], &[]));
770        assert!(!r.is_entitled(Some("o"), &m, &ch, &[], std::slice::from_ref(&r1)), "losing the allowing role loses the key");
771        let cat = "d".repeat(64);
772        r.overwrites.push(Overwrite { scope: cat.clone(), target: OverwriteTarget::Role(r2.clone()), allow: Permissions(0), deny: Permissions(send) });
773        r.syncs.insert(ch.clone(), cat);
774        assert_eq!(at(&r, &n), view | send, "a synced channel takes its Category's overwrites, not its own");
775        assert_eq!(at(&r, &m), view, "including the Category's denies");
776    }
777
778    fn admin_roster(member: &str) -> CommunityRoles {
779        let role = Role::admin("a".repeat(64));
780        CommunityRoles {
781            grants: vec![MemberGrant {
782                member: member.to_string(),
783                role_ids: vec![role.role_id.clone()],
784            }],
785            roles: vec![role],
786            everyone: None,
787            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
788        }
789    }
790
791    #[test]
792    fn admin_role_holds_every_management_bit() {
793        let p = Permissions::admin();
794        for bit in [
795            Permissions::MANAGE_ROLES,
796            Permissions::MANAGE_CHANNELS,
797            Permissions::MANAGE_METADATA,
798            Permissions::KICK,
799            Permissions::BAN,
800            Permissions::MANAGE_MESSAGES,
801            Permissions::CREATE_INVITE,
802            Permissions::VIEW_AUDIT_LOG,
803            Permissions::MENTION_EVERYONE,
804        ] {
805            assert!(p.contains(bit), "admin must hold bit {bit}");
806        }
807    }
808
809    #[test]
810    fn social_only_role_is_not_management_nor_admin() {
811        // A role holding ONLY a social bit (MENTION_EVERYONE) is not "management" and its holder is
812        // NOT an admin — so it gets no crown and no management-secret delivery. Guards the
813        // MANAGEMENT_MASK invariant against a future fat-finger that folds a social bit in.
814        let social = Permissions(Permissions::MENTION_EVERYONE);
815        assert!(!social.is_management(), "a purely-social permission is not management");
816        let role = Role {
817            role_id: "c".repeat(64),
818            name: "Hype".into(),
819            position: 5,
820            permissions: social,
821            scope: RoleScope::Server,
822            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
823        };
824        let alice = "aa".repeat(32);
825        let r = CommunityRoles {
826            grants: vec![MemberGrant { member: alice.clone(), role_ids: vec![role.role_id.clone()] }],
827            roles: vec![role],
828            everyone: None,
829            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
830        };
831        assert!(!r.is_admin(&alice), "a social-only role holder is not an admin");
832        assert!(r.is_privileged(&alice), "though they do hold a role");
833    }
834
835    #[test]
836    fn overwrite_support_comes_only_from_roles_above_the_target() {
837        let (owner, me, peer, plain) = ("00".repeat(32), "aa".repeat(32), "bb".repeat(32), "cc".repeat(32));
838        let role = |id: &str, position: u32, bits: u64| Role {
839            role_id: id.repeat(64), name: id.into(), position, permissions: Permissions(bits), scope: RoleScope::Server,
840            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
841        };
842        let lead = Permissions::MANAGE_ROLES | Permissions::SEND_MESSAGES;
843        let r = CommunityRoles {
844            roles: vec![role("1", 1, Permissions::ATTACH_FILES), role("2", 2, lead), role("3", 3, Permissions::VIEW_CHANNEL), role("4", 4, Permissions::ADD_REACTIONS)],
845            grants: vec![
846                MemberGrant { member: me.clone(), role_ids: vec!["2".repeat(64), "4".repeat(64)] },
847                MemberGrant { member: peer.clone(), role_ids: vec!["2".repeat(64)] },
848            ],
849            everyone: Some(Permissions(Permissions::READ_MESSAGE_HISTORY)),
850            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
851        };
852        use OverwriteTarget as T;
853        // Beneath both of my roles: both count, @everyone's own bits never do.
854        assert_eq!(r.overwrite_support(&me, &owner, &T::Everyone), Some(lead | Permissions::ADD_REACTIONS));
855        assert_eq!(r.overwrite_support(&me, &owner, &T::Member(plain.clone())), Some(lead | Permissions::ADD_REACTIONS));
856        // Between them: only the role above counts.
857        assert_eq!(r.overwrite_support(&me, &owner, &T::Role("3".repeat(64))), Some(lead));
858        // My own top role, a peer at it, and anything above: nothing.
859        assert_eq!(r.overwrite_support(&me, &owner, &T::Role("2".repeat(64))), None);
860        assert_eq!(r.overwrite_support(&me, &owner, &T::Member(peer.clone())), None);
861        assert_eq!(r.overwrite_support(&me, &owner, &T::Role("1".repeat(64))), None);
862        assert_eq!(r.overwrite_support(&me, &owner, &T::Role("f".repeat(64))), None, "a role that's gone");
863        // Without Manage Roles above it, a role beneath is out of reach too.
864        assert_eq!(r.overwrite_support(&plain, &owner, &T::Everyone), None);
865        // The owner sets anything on anyone but themselves.
866        assert_eq!(r.overwrite_support(&owner, &owner, &T::Role("1".repeat(64))), Some(u64::MAX));
867        assert_eq!(r.overwrite_support(&owner, &owner, &T::Member(owner.clone())), None);
868    }
869
870    #[test]
871    fn hierarchy_only_strictly_higher_can_manage() {
872        // owner (implicit pos 0) > admin (pos 1) > mod (pos 2); a plain member holds no role.
873        let owner = "00".repeat(32);
874        let admin = "aa".repeat(32);
875        let moderator = "bb".repeat(32);
876        let member = "cc".repeat(32);
877        let admin_role = Role::admin("a".repeat(64));
878        let mod_role = Role {
879            role_id: "b".repeat(64),
880            name: "Mod".into(),
881            position: 2,
882            permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::KICK),
883            scope: RoleScope::Server,
884            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
885        };
886        let admin_pos = admin_role.position; // 1
887        let mod_pos = mod_role.position; // 2
888        let r = CommunityRoles {
889            grants: vec![
890                MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
891                MemberGrant { member: moderator.clone(), role_ids: vec![mod_role.role_id.clone()] },
892            ],
893            roles: vec![admin_role, mod_role],
894            everyone: None,
895            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
896        };
897        let owner_ref = Some(owner.as_str());
898
899        // Owner is supreme — outranks every position and every member, can't be targeted.
900        assert!(r.can_manage_position(&owner, owner_ref, admin_pos));
901        assert!(r.can_manage_member(&owner, owner_ref, &admin));
902        assert!(!r.can_manage_member(&admin, owner_ref, &owner), "owner is never a valid target");
903
904        // Equal cannot act on equal: an admin can NOT manage the Admin position (closes self/peer
905        // escalation — granting the Admin role), but CAN manage everything strictly below.
906        assert!(!r.can_manage_position(&admin, owner_ref, admin_pos), "admin can't grant a peer-rank role");
907        assert!(r.can_manage_position(&admin, owner_ref, mod_pos), "admin outranks Mod");
908        assert!(r.can_manage_member(&admin, owner_ref, &moderator), "admin outranks the mod member");
909        assert!(r.can_manage_member(&admin, owner_ref, &member), "admin outranks a roleless member");
910        assert!(!r.can_manage_member(&admin, owner_ref, &admin), "admin can't manage a peer admin");
911
912        // A mod can't reach up to the Admin position, and a roleless member can manage nothing.
913        assert!(!r.can_manage_position(&moderator, owner_ref, admin_pos));
914        assert!(!r.can_manage_position(&member, owner_ref, mod_pos), "no role, no MANAGE_ROLES → nothing");
915    }
916
917    #[test]
918    fn can_act_on_member_gates_on_permission_and_rank() {
919        // owner (pos 0), a BAN-capable admin (pos 1), a Mod with KICK-only (pos 2, NO ban), a plain
920        // member (no role). Verifies the generalized gate requires BOTH the right permission AND a
921        // strict outrank — the rule ban/hide use, distinct from MANAGE_ROLES.
922        let owner = "00".repeat(32);
923        let admin = "aa".repeat(32);
924        let kicker = "bb".repeat(32);
925        let member = "cc".repeat(32);
926        let admin_role = Role::admin("a".repeat(64)); // pos 1, ADMIN_ALL (incl. BAN + MANAGE_MESSAGES)
927        let kick_role = Role {
928            role_id: "b".repeat(64),
929            name: "Mod".into(),
930            position: 2,
931            permissions: Permissions(Permissions::KICK), // KICK only — NO ban, NO manage-messages
932            scope: RoleScope::Server,
933            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
934        };
935        let r = CommunityRoles {
936            grants: vec![
937                MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] },
938                MemberGrant { member: kicker.clone(), role_ids: vec![kick_role.role_id.clone()] },
939            ],
940            roles: vec![admin_role, kick_role],
941            everyone: None,
942            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
943        };
944        let o = Some(owner.as_str());
945        use Permissions as P;
946
947        // The BAN-capable admin: bans the Mod and a plain member, but NOT a peer admin, NOT the owner.
948        assert!(r.can_act_on_member(&admin, o, &kicker, P::BAN));
949        assert!(r.can_act_on_member(&admin, o, &member, P::BAN));
950        assert!(!r.can_act_on_member(&admin, o, &admin, P::BAN), "no banning a peer admin (equal rank)");
951        assert!(!r.can_act_on_member(&admin, o, &owner, P::BAN), "the owner is never a valid target");
952        assert!(r.can_act_on_member(&admin, o, &member, P::MANAGE_MESSAGES), "admin can hide a member's msg");
953
954        // The Mod has KICK but NOT BAN/MANAGE_MESSAGES → the permission gate refuses even a target it outranks.
955        assert!(!r.can_act_on_member(&kicker, o, &member, P::BAN), "no BAN permission → can't ban");
956        assert!(!r.can_act_on_member(&kicker, o, &member, P::MANAGE_MESSAGES), "no MANAGE_MESSAGES → can't hide");
957        assert!(r.can_act_on_member(&kicker, o, &member, P::KICK), "but it CAN kick a plain member");
958
959        // The owner is supreme for any permission, against anyone.
960        assert!(r.can_act_on_member(&owner, o, &admin, P::BAN));
961        // A plain member can do nothing.
962        assert!(!r.can_act_on_member(&member, o, &kicker, P::BAN));
963    }
964
965    #[test]
966    fn effective_permissions_union_and_position() {
967        let alice = "aa".repeat(32);
968        let r = admin_roster(&alice);
969        assert!(r.has_permission(&alice, Permissions::BAN));
970        assert!(r.has_permission(&alice, Permissions::MANAGE_ROLES));
971        assert_eq!(r.highest_position(&alice), Some(1));
972        assert!(r.is_privileged(&alice));
973
974        // A member with no grant has no permissions and no position.
975        let bob = "bb".repeat(32);
976        assert!(!r.has_permission(&bob, Permissions::BAN));
977        assert_eq!(r.highest_position(&bob), None);
978        assert!(!r.is_privileged(&bob));
979    }
980
981    #[test]
982    fn multiple_roles_union_perms_and_take_highest_position() {
983        let alice = "aa".repeat(32);
984        let mod_role = Role {
985            role_id: "b".repeat(64),
986            name: "Mod".into(),
987            position: 2,
988            permissions: Permissions(Permissions::MANAGE_MESSAGES | Permissions::KICK),
989            scope: RoleScope::Server,
990            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
991        };
992        let admin = Role::admin("a".repeat(64));
993        let r = CommunityRoles {
994            grants: vec![MemberGrant {
995                member: alice.clone(),
996                role_ids: vec![admin.role_id.clone(), mod_role.role_id.clone()],
997            }],
998            roles: vec![admin, mod_role],
999            everyone: None,
1000            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
1001        };
1002        // Union of both roles' bits, and the *highest* (lowest index) position wins.
1003        assert!(r.has_permission(&alice, Permissions::BAN)); // from Admin
1004        assert!(r.has_permission(&alice, Permissions::MANAGE_MESSAGES)); // from both
1005        assert_eq!(r.highest_position(&alice), Some(1));
1006    }
1007
1008    #[test]
1009    fn round_trips_json() {
1010        let alice = "aa".repeat(32);
1011        let r = admin_roster(&alice);
1012        let json = serde_json::to_string(&r).unwrap();
1013        let back: CommunityRoles = serde_json::from_str(&json).unwrap();
1014        assert_eq!(r, back);
1015        assert!(json.contains("\"kind\":\"server\""));
1016    }
1017
1018    #[test]
1019    fn is_authorized_owner_supreme_admin_by_permission_demoted_rejected() {
1020        let owner = "00".repeat(32);
1021        let alice = "aa".repeat(32);
1022        let r = admin_roster(&alice); // alice granted Admin (has BAN)
1023        // Owner is always authorized, even without a role.
1024        assert!(r.is_authorized(&owner, Some(&owner), Permissions::BAN));
1025        // Admin Alice is authorized for BAN via her role.
1026        assert!(r.is_authorized(&alice, Some(&owner), Permissions::BAN));
1027        // A member with no role (Bob) is not — and neither is Alice once demoted (no grant).
1028        let bob = "bb".repeat(32);
1029        assert!(!r.is_authorized(&bob, Some(&owner), Permissions::BAN));
1030        let demoted = CommunityRoles { roles: r.roles.clone(), grants: vec![], everyone: None, overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default() };
1031        assert!(!demoted.is_authorized(&alice, Some(&owner), Permissions::BAN));
1032        // ...but the owner stays authorized even with an empty grant set.
1033        assert!(demoted.is_authorized(&owner, Some(&owner), Permissions::BAN));
1034    }
1035
1036    #[test]
1037    fn channel_scope_round_trips() {
1038        let scope = RoleScope::Channel("cc".repeat(32));
1039        let json = serde_json::to_string(&scope).unwrap();
1040        let back: RoleScope = serde_json::from_str(&json).unwrap();
1041        assert_eq!(scope, back);
1042    }
1043
1044    // ── Private-Channel entitlement ──────────────────────────────────────────
1045
1046    /// A roster with one channel-scoped role (`pos` 5) over `chan`, granted to
1047    /// `member`, plus a server-scope Admin held by `admin`.
1048    fn scoped_roster(chan: &str, member: &str, admin: &str) -> CommunityRoles {
1049        let scoped = Role {
1050            role_id: "11".repeat(32),
1051            name: "Testers".into(),
1052            position: 5,
1053            permissions: Permissions(Permissions::MANAGE_MESSAGES),
1054            scope: RoleScope::Channel(chan.to_string()),
1055            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
1056        };
1057        let server = Role::admin("22".repeat(32));
1058        CommunityRoles {
1059            grants: vec![
1060                MemberGrant { member: member.to_string(), role_ids: vec![scoped.role_id.clone()] },
1061                MemberGrant { member: admin.to_string(), role_ids: vec![server.role_id.clone()] },
1062            ],
1063            roles: vec![scoped, server],
1064            everyone: None,
1065            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
1066        }
1067    }
1068
1069    #[test]
1070    fn a_channels_scoped_roles_are_its_access_list() {
1071        let chan = "cc".repeat(32);
1072        let other = "dd".repeat(32);
1073        let owner = "00".repeat(32);
1074        let member = "aa".repeat(32);
1075        let admin = "bb".repeat(32);
1076        let r = scoped_roster(&chan, &member, &admin);
1077
1078        assert_eq!(r.channel_roles(&chan).len(), 1, "the scoped role is the access list");
1079        assert!(r.channel_roles(&other).is_empty(), "another channel gets none of it");
1080
1081        assert!(r.is_entitled(Some(&owner), &member, &chan, &[], &[]), "the granted holder is entitled");
1082        assert!(r.is_entitled(Some(&owner), &owner, &chan, &[], &[]), "the owner is always entitled");
1083        // A SERVER-scope Admin is not automatically entitled: entitlement is the
1084        // channel's scoped roles, never rank (CORD-03 — key possession, not authority).
1085        assert!(!r.is_entitled(Some(&owner), &admin, &chan, &[], &[]), "rank alone is not entitlement");
1086        assert!(!r.is_entitled(Some(&owner), &member, &other, &[], &[]), "entitlement does not spill to another channel");
1087    }
1088
1089    #[test]
1090    fn the_grant_overlay_settles_against_a_publish_the_fold_has_not_caught() {
1091        let chan = "cc".repeat(32);
1092        let owner = "00".repeat(32);
1093        let member = "aa".repeat(32);
1094        let stranger = "ee".repeat(32);
1095        let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1096        let scoped_id = r.channel_role_ids(&chan)[0].clone();
1097
1098        assert!(
1099            r.is_entitled(Some(&owner), &stranger, &chan, std::slice::from_ref(&scoped_id), &[]),
1100            "a just-published grant settles as entitled before the fold catches up"
1101        );
1102        assert!(
1103            !r.is_entitled(Some(&owner), &member, &chan, &[], std::slice::from_ref(&scoped_id)),
1104            "a just-published revoke settles as unentitled before the fold catches up"
1105        );
1106    }
1107
1108    #[test]
1109    fn channel_narrowing_is_offer_side_only() {
1110        let chan = "cc".repeat(32);
1111        let other = "dd".repeat(32);
1112        let owner = "00".repeat(32);
1113        let member = "aa".repeat(32);
1114        let r = scoped_roster(&chan, &member, &"bb".repeat(32));
1115
1116        // Narrowed: the scoped role's bits apply in ITS channel and nowhere else.
1117        assert!(r.is_authorized_in(&member, Some(&owner), &chan, Permissions::MANAGE_MESSAGES));
1118        assert!(!r.is_authorized_in(&member, Some(&owner), &other, Permissions::MANAGE_MESSAGES));
1119
1120        // The HONOR path stays scope-agnostic — every implementation folds the
1121        // same union (CORD-04 §3). Tightening this would retroactively invalidate
1122        // actions shipped clients already folded.
1123        assert!(
1124            r.is_authorized(&member, Some(&owner), Permissions::MANAGE_MESSAGES),
1125            "the scope-blind honor path is unchanged"
1126        );
1127    }
1128
1129    /// The founding mask is the admin-FINDER's floor and is frozen forever: a
1130    /// role minted under the ORIGINAL nine bits must always satisfy it, or
1131    /// every published Admin role orphans and the finder mints duplicates.
1132    #[test]
1133    fn founding_mask_is_frozen_at_the_original_nine_bits() {
1134        const ORIGINAL_NINE: u64 = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)
1135            | (1 << 5) | (1 << 6) | (1 << 8) | (1 << 9);
1136        assert_eq!(Permissions::ADMIN_FOUNDING_MASK, ORIGINAL_NINE);
1137        // A legacy admin role (pre-PIN_MESSAGES) still passes the finder's test...
1138        assert!(Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_FOUNDING_MASK));
1139        // ...and a newly minted one does too (ADMIN_ALL may widen, and has).
1140        assert!(Permissions::admin().contains(Permissions::ADMIN_FOUNDING_MASK));
1141        assert!(Permissions::admin().contains(Permissions::PIN_MESSAGES));
1142        // But a legacy role does NOT contain the widened ADMIN_ALL — the exact
1143        // reason nothing may identify admins with it.
1144        assert!(!Permissions(ORIGINAL_NINE).contains(Permissions::ADMIN_ALL));
1145    }
1146}