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