Skip to main content

plexus_auth_core/
grants.rs

1//! AUTH-2: **grants, roles, memberships, ceilings — and the gate** that asks
2//! them on every call.
3//!
4//! The model (AUTH-1, owner 2026-10-10: "every method should be its own grant
5//! inherently and require a role to have it explicitly listed if not admin
6//! role"):
7//!
8//! - A [`Grant`] is the right to call one method: `<activation>.<method>`
9//!   (`tickets.set_status`). Inherent — every method has exactly one and
10//!   nothing declares it.
11//! - A role is a named, explicit list of grants ([`GrantSet::Listed`]); the
12//!   built-in [`ADMIN`] role alone holds every grant ([`GrantSet::All`]).
13//!   [`RoleTable`] is an in-memory [`Roles`] in which a role may list
14//!   another role (inclusion), flattened as it is defined.
15//! - A [`Membership`] says a principal holds a role on a scope
16//!   ([`ScopeRef::Named`]) or everywhere ([`ScopeRef::Everywhere`], `*`).
17//! - A *target* is the param that locates the resource a call acts on; the
18//!   service's [`Resolve`] maps its value to the scopes it lives in,
19//!   innermost first (`MENGER-12` → `[MENGER, *]`).
20//! - A [`Ceiling`] is a session's upper bound (IDENTITY-40): `role@SCOPE` or
21//!   `grant@SCOPE` entries. A session may carry several layers; every layer
22//!   must allow a check, as the memberships must.
23//!
24//! [`Gate::check`] answers one call: allowed — with the [`Reach`] the method
25//! answers from — or a [`Refusal`] that names what was needed. Everything is
26//! answered from memory: the three service traits are synchronous and must
27//! not do I/O.
28//!
29//! # Relation to R-5's [`ScopeRegistry`](crate::ScopeRegistry)
30//!
31//! R-5's registry maps *token-claimed roles* to dotted capability scopes and
32//! knows nothing of where a role is held. The grant model keeps its words —
33//! a grant is exactly R-5's implicit `<activation>.<method>` scope, and
34//! [`RoleName`] is the same type — and adds the *where*: memberships on
35//! scopes, targets resolved through a chain, ceilings. Both gates can be
36//! configured on one hub; a hub with neither dispatches as before.
37
38use std::collections::{BTreeMap, BTreeSet};
39use std::fmt;
40use std::sync::Arc;
41
42use serde::{Deserialize, Deserializer, Serialize, Serializer};
43
44use crate::audit::RoleName;
45use crate::auth::AuthContext;
46use crate::identity::Principal;
47
48/// The built-in role that holds every grant. No other role holds anything it
49/// does not list.
50pub const ADMIN: &str = "admin";
51
52/// The metadata key a session's ceiling rides under (IDENTITY-42's
53/// `menger_session` sessions write it): either a list of `role@SCOPE` /
54/// `grant@SCOPE` strings (one layer) or a list of such lists (layers, every
55/// one of which must allow a check).
56pub const CEILING_KEY: &str = "ceiling";
57
58// ---------------------------------------------------------------------------
59// Grant
60// ---------------------------------------------------------------------------
61
62/// The right to call one method: `<activation>.<method>`, e.g.
63/// `tickets.set_status`. Every method has exactly one; nothing declares it.
64#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct Grant(String);
67
68impl Grant {
69    /// Wrap a dotted method path as a grant. Unvalidated, as wire-decoded
70    /// values are.
71    pub fn new(path: impl Into<String>) -> Self {
72        Self(path.into())
73    }
74
75    /// The grant of `method` on `activation`: `<activation>.<method>`.
76    pub fn of(activation: &str, method: &str) -> Self {
77        Self(format!("{activation}.{method}"))
78    }
79
80    /// The dotted path.
81    pub fn as_str(&self) -> &str {
82        &self.0
83    }
84}
85
86impl fmt::Display for Grant {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.write_str(&self.0)
89    }
90}
91
92// ---------------------------------------------------------------------------
93// ScopeRef
94// ---------------------------------------------------------------------------
95
96/// Where a role is held: everywhere (`*`) or one named scope (`MENGER`).
97/// What a name means — a shortcode, a tenant, a project — is the service's;
98/// the gate only compares names and asks [`Resolve::chain`] how they nest.
99///
100/// On the wire, a plain string: `"*"` or the name.
101#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub enum ScopeRef {
103    /// `*`: every scope.
104    Everywhere,
105    /// One named scope, and whatever the service nests under it.
106    Named(String),
107}
108
109impl ScopeRef {
110    /// `"*"` → [`ScopeRef::Everywhere`]; anything else (trimmed) → named.
111    pub fn parse(text: &str) -> Self {
112        match text.trim() {
113            "*" => Self::Everywhere,
114            other => Self::Named(other.to_string()),
115        }
116    }
117
118    /// A named scope.
119    pub fn named(name: impl Into<String>) -> Self {
120        Self::Named(name.into())
121    }
122
123    /// `"*"` or the name.
124    pub fn as_str(&self) -> &str {
125        match self {
126            Self::Everywhere => "*",
127            Self::Named(n) => n,
128        }
129    }
130
131    /// Whether this is `*`.
132    pub fn is_everywhere(&self) -> bool {
133        matches!(self, Self::Everywhere)
134    }
135}
136
137impl fmt::Display for ScopeRef {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.write_str(self.as_str())
140    }
141}
142
143impl Serialize for ScopeRef {
144    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
145        s.serialize_str(self.as_str())
146    }
147}
148
149impl<'de> Deserialize<'de> for ScopeRef {
150    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
151        let s = String::deserialize(d)?;
152        Ok(Self::parse(&s))
153    }
154}
155
156// ---------------------------------------------------------------------------
157// GrantSet, RoleOrGrant, Membership, Ceiling
158// ---------------------------------------------------------------------------
159
160/// What a role holds: every grant ([`ADMIN`]) or exactly those it lists.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum GrantSet {
163    /// Every grant — the admin role, and only it by default.
164    All,
165    /// Exactly these grants.
166    Listed(BTreeSet<Grant>),
167}
168
169impl GrantSet {
170    /// Whether the set holds `grant`.
171    pub fn contains(&self, grant: &Grant) -> bool {
172        match self {
173            Self::All => true,
174            Self::Listed(set) => set.contains(grant),
175        }
176    }
177
178    /// A listed set from anything that names grants.
179    pub fn listed<I, G>(grants: I) -> Self
180    where
181        I: IntoIterator<Item = G>,
182        G: Into<String>,
183    {
184        Self::Listed(grants.into_iter().map(|g| Grant::new(g)).collect())
185    }
186}
187
188/// One ceiling entry's left side: a role (`editor`) or a single grant
189/// (`tickets.get`). A dotted name is a grant; a bare one is a role.
190#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
191pub enum RoleOrGrant {
192    Role(RoleName),
193    Grant(Grant),
194}
195
196impl RoleOrGrant {
197    /// A dotted name is a grant, a bare one a role.
198    pub fn parse(text: &str) -> Self {
199        let t = text.trim();
200        if t.contains('.') {
201            Self::Grant(Grant::new(t))
202        } else {
203            Self::Role(RoleName::new(t))
204        }
205    }
206}
207
208impl fmt::Display for RoleOrGrant {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        match self {
211            Self::Role(r) => write!(f, "{r}"),
212            Self::Grant(g) => write!(f, "{g}"),
213        }
214    }
215}
216
217/// A principal holds a role on a scope: `key:ac79… is editor on MENGER`.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct Membership {
220    pub principal: Principal,
221    pub role: RoleName,
222    pub scope: ScopeRef,
223}
224
225/// A session's upper bound (IDENTITY-40): `(role or grant, scope)` entries,
226/// spelled `editor@MENGER-12`, `tickets.get@*`. A check passes a ceiling
227/// when some entry's scope is in the target's chain and the entry allows the
228/// grant (the grant itself, or a role listing it).
229#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
230pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);
231
232/// Why a ceiling could not be read.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct CeilingError(pub String);
235
236impl fmt::Display for CeilingError {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        f.write_str(&self.0)
239    }
240}
241
242impl std::error::Error for CeilingError {}
243
244impl Ceiling {
245    /// One `role@SCOPE` or `grant@SCOPE` entry.
246    pub fn entry(text: &str) -> Result<(RoleOrGrant, ScopeRef), CeilingError> {
247        let (left, scope) = text
248            .trim()
249            .split_once('@')
250            .ok_or_else(|| CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())))?;
251        if left.trim().is_empty() || scope.trim().is_empty() {
252            return Err(CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())));
253        }
254        Ok((RoleOrGrant::parse(left), ScopeRef::parse(scope)))
255    }
256
257    /// A ceiling from its entries' text.
258    pub fn parse<I, S>(entries: I) -> Result<Self, CeilingError>
259    where
260        I: IntoIterator<Item = S>,
261        S: AsRef<str>,
262    {
263        entries
264            .into_iter()
265            .map(|e| Self::entry(e.as_ref()))
266            .collect::<Result<Vec<_>, _>>()
267            .map(Ceiling)
268    }
269
270    /// The entries as the wire says them: `role@SCOPE` each.
271    pub fn text(&self) -> Vec<String> {
272        self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
273    }
274
275    /// The ceilings an identity's metadata carries under [`CEILING_KEY`]:
276    /// none → `[]`; a list of strings → one layer; a list of lists → one
277    /// layer each. Anything else is an error, and a caller whose ceiling
278    /// cannot be read must be refused, never widened.
279    pub fn layers_of(ctx: &AuthContext) -> Result<Vec<Ceiling>, CeilingError> {
280        let Some(v) = ctx.metadata.get(CEILING_KEY) else {
281            return Ok(Vec::new());
282        };
283        let unreadable = || CeilingError("this session's ceiling cannot be read: sign in again".into());
284        let items = v.as_array().ok_or_else(unreadable)?;
285        if items.iter().all(|i| i.is_string()) {
286            let texts: Vec<&str> = items.iter().filter_map(|i| i.as_str()).collect();
287            return Ok(vec![Self::parse(texts).map_err(|_| unreadable())?]);
288        }
289        items
290            .iter()
291            .map(|layer| {
292                let entries = layer.as_array().ok_or_else(unreadable)?;
293                let texts = entries
294                    .iter()
295                    .map(|e| e.as_str().ok_or_else(unreadable))
296                    .collect::<Result<Vec<_>, _>>()?;
297                Self::parse(texts).map_err(|_| unreadable())
298            })
299            .collect()
300    }
301}
302
303/// PERF-15: everything [`Gate::held_on`] reads of one signed-in caller,
304/// besides the grants generation — what its principal holds (each
305/// membership's role and scope, as a set) and its session's ceiling layers.
306/// Two callers with equal fingerprints hold the same grants on the same
307/// scopes, whoever they are: at one generation the gate answers them alike.
308/// So a service keeps what a caller may see (its view, AUTH-4) by it —
309/// one entry shared by every caller holding the same, dropped when the
310/// generation moves. Compared whole, never by a digest: two fingerprints are
311/// one key only when they are equal. [`Gate::fingerprint`] takes one,
312/// [`Gate::held_on_by`] answers from it.
313#[derive(Debug, Clone, PartialEq, Eq, Hash)]
314pub struct Fingerprint {
315    /// (role, scope) of each membership, sorted, each once.
316    held: Vec<(RoleName, ScopeRef)>,
317    /// The session's ceiling, as [`Ceiling::layers_of`] reads it (an
318    /// unreadable one is one empty layer, as the gate reads it).
319    layers: Vec<Ceiling>,
320}
321
322// ---------------------------------------------------------------------------
323// What a service supplies
324// ---------------------------------------------------------------------------
325
326/// Who holds which role where (menger: its members table, cached). Answered
327/// from memory: no I/O on a call.
328pub trait Memberships: Send + Sync {
329    fn held(&self, who: &Principal) -> Vec<Membership>;
330
331    /// What `who` holds of its own — without a membership the service
332    /// gives every signed-in principal (menger's `everyone` grant). It
333    /// decides whether `who` is still waiting for an admin (`auth.waiting`,
334    /// `auth.signup`); the gate reads [`Memberships::held`]. The default is
335    /// `held`: a service with no such grant has nothing to leave out.
336    fn own_held(&self, who: &Principal) -> Vec<Membership> {
337        self.held(who)
338    }
339}
340
341/// Role → grants (defaults declared in code, edits as data). Answered from
342/// memory. [`ADMIN`] holds every grant whatever this answers.
343pub trait Roles: Send + Sync {
344    /// What `role` holds; `None` for a role this service does not know
345    /// (it holds nothing).
346    fn grants(&self, role: &RoleName) -> Option<GrantSet>;
347
348    /// Every role this service knows, so a refusal can name the roles that
349    /// list a grant. The default knows none (a refusal then names only
350    /// [`ADMIN`]).
351    fn names(&self) -> Vec<RoleName> {
352        Vec::new()
353    }
354}
355
356/// Where a target lives. Answered from memory.
357pub trait Resolve: Send + Sync {
358    /// The scopes a target lives in, innermost first, ending in
359    /// [`ScopeRef::Everywhere`]: `"MENGER-12"` → `[MENGER-12, MENGER, *]`
360    /// (or, for a service whose memberships are per shortcode,
361    /// `[MENGER, *]`). `None`: the value locates nothing — the call is
362    /// refused.
363    ///
364    /// The gate also asks it about **scope names** (a membership's or a
365    /// ceiling's): `chain("MENGER")` → `[MENGER, PLEXUS, *]`, to tell which
366    /// of two scopes lies within the other when it narrows a reach by a
367    /// ceiling. A service that cannot answer for a name returns `None`, and
368    /// two different names are then taken as disjoint.
369    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
370}
371
372// ---------------------------------------------------------------------------
373// RoleTable — an in-memory Roles with inclusion
374// ---------------------------------------------------------------------------
375
376/// Why [`RoleTable::define`] refused a role.
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum RoleTableError {
379    /// An entry named a role that is not (yet) defined. A role may only
380    /// include roles defined before it, which is what keeps inclusion
381    /// acyclic.
382    UnknownRole { role: String, includes: String },
383}
384
385impl fmt::Display for RoleTableError {
386    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387        match self {
388            Self::UnknownRole { role, includes } => write!(
389                f,
390                "role {role} includes {includes}, which is not defined before it"
391            ),
392        }
393    }
394}
395
396impl std::error::Error for RoleTableError {}
397
398/// An in-memory [`Roles`]: each role an explicit list of grants, where an
399/// entry may also name an earlier role (inclusion, flattened when defined).
400/// [`ADMIN`] is built in.
401///
402/// ```
403/// use plexus_auth_core::grants::{Grant, RoleTable, Roles};
404/// use plexus_auth_core::RoleName;
405///
406/// let roles = RoleTable::new()
407///     .define("viewer", ["tickets.get", "tickets.list"]).unwrap()
408///     .define("editor", ["viewer", "tickets.set_status"]).unwrap();
409/// let editor = roles.grants(&RoleName::new("editor")).unwrap();
410/// assert!(editor.contains(&Grant::new("tickets.get")));
411/// ```
412#[derive(Debug, Clone, Default)]
413pub struct RoleTable {
414    roles: BTreeMap<RoleName, GrantSet>,
415}
416
417impl RoleTable {
418    /// The table with only the built-in [`ADMIN`].
419    pub fn new() -> Self {
420        Self::default()
421    }
422
423    /// Define (or extend) `role`: each entry a grant (dotted) or an earlier
424    /// role (bare), whose grants are included. Defining a role again adds to
425    /// it, which is how several activations' defaults for one role name
426    /// merge.
427    pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
428    where
429        I: IntoIterator<Item = S>,
430        S: AsRef<str>,
431    {
432        let name = RoleName::new(role);
433        let mut set = match self.roles.remove(&name) {
434            Some(GrantSet::Listed(s)) => s,
435            Some(GrantSet::All) => {
436                self.roles.insert(name, GrantSet::All);
437                return Ok(self);
438            }
439            None => BTreeSet::new(),
440        };
441        let mut all = name.as_str() == ADMIN;
442        for entry in entries {
443            let e = entry.as_ref().trim();
444            if e.contains('.') {
445                set.insert(Grant::new(e));
446                continue;
447            }
448            if e == ADMIN {
449                all = true;
450                continue;
451            }
452            match self.roles.get(&RoleName::new(e)) {
453                Some(GrantSet::All) => all = true,
454                Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
455                None => {
456                    return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
457                }
458            }
459        }
460        self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
461        Ok(self)
462    }
463
464    /// Replace `role`'s grants outright (an admin's edit: the store wins).
465    pub fn set(&mut self, role: &str, grants: GrantSet) {
466        self.roles.insert(RoleName::new(role), grants);
467    }
468
469    /// A table from already-flat lists (`role → [grant, …]`), as a schema's
470    /// `roles` carries them; lists for one role name merge.
471    pub fn from_lists<'a, I, G>(lists: I) -> Self
472    where
473        I: IntoIterator<Item = (&'a str, G)>,
474        G: IntoIterator,
475        G::Item: AsRef<str>,
476    {
477        let mut table = Self::new();
478        for (role, grants) in lists {
479            let name = RoleName::new(role);
480            let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
481            match table.roles.entry(name) {
482                std::collections::btree_map::Entry::Occupied(mut o) => {
483                    if let GrantSet::Listed(s) = o.get_mut() {
484                        s.extend(grants);
485                    }
486                }
487                std::collections::btree_map::Entry::Vacant(v) => {
488                    v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
489                }
490            }
491        }
492        table
493    }
494}
495
496impl Roles for RoleTable {
497    fn grants(&self, role: &RoleName) -> Option<GrantSet> {
498        if role.as_str() == ADMIN {
499            return Some(GrantSet::All);
500        }
501        self.roles.get(role).cloned()
502    }
503
504    fn names(&self) -> Vec<RoleName> {
505        self.roles.keys().cloned().collect()
506    }
507}
508
509// ---------------------------------------------------------------------------
510// Refusal
511// ---------------------------------------------------------------------------
512
513/// Why the gate refused a call.
514#[derive(Debug, Clone, PartialEq, Eq)]
515pub enum Refusal {
516    /// No principal: only `public` methods are reachable anonymously.
517    Unauthenticated,
518    /// The caller does not hold `grant` on `scope` (within its ceiling).
519    MissingGrant {
520        /// The grant the call needed.
521        grant: Grant,
522        /// Where it was needed: the target's innermost scope, or `*` for a
523        /// method without a target (held anywhere would have done).
524        scope: ScopeRef,
525        /// The roles that list the grant ([`ADMIN`] last).
526        roles: Vec<RoleName>,
527        /// Where the caller does hold it (within its ceiling).
528        held_on: Vec<ScopeRef>,
529    },
530    /// AUTH-11: the caller signed in, but that sign-in no longer stands
531    /// (signed out, expired, revoked) — it proves no one.
532    Ended {
533        /// Why, in words for the caller ("you have signed out: sign in
534        /// again").
535        reason: String,
536    },
537}
538
539impl fmt::Display for Refusal {
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        match self {
542            Self::Unauthenticated => f.write_str("sign in first"),
543            Self::Ended { reason } => f.write_str(reason),
544            Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
545        }
546    }
547}
548
549impl std::error::Error for Refusal {}
550
551// ---------------------------------------------------------------------------
552// Reach
553// ---------------------------------------------------------------------------
554
555/// Where a call may act: the scopes the caller holds the method's grant on
556/// (within its ceiling), handed to the method beside `auth`. A read without a
557/// target (`list`, `watch`) answers only from these.
558///
559/// A reach is **live** when it came from a gate: [`Reach::allows`] and
560/// [`Reach::current`] ask the gate again, as memberships, roles and the
561/// ceiling stand *now* — so a stream checks each event (IDENTITY-37: a role
562/// revoked reaches an open stream at its next event). A hub without a gate
563/// hands every method [`Reach::everywhere`], which allows everything.
564#[derive(Clone)]
565pub struct Reach {
566    held_on: Vec<ScopeRef>,
567    live: Option<Live>,
568}
569
570#[derive(Clone)]
571struct Live {
572    gate: Gate,
573    caller: Option<AuthContext>,
574    grant: Grant,
575    /// KEEL-31: the reach of a method that acts on the whole service — asked
576    /// again by [`Gate::check_everywhere`], so it lasts only while the grant
577    /// is held on `*`.
578    everywhere: bool,
579}
580
581impl Live {
582    /// The gate's answer now, by the rule this reach was given by.
583    fn now(&self) -> Result<Reach, Refusal> {
584        match self.everywhere {
585            true => self.gate.check_everywhere(self.caller.as_ref(), &self.grant),
586            false => self.gate.check(self.caller.as_ref(), &self.grant, None),
587        }
588    }
589}
590
591impl fmt::Debug for Reach {
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        f.debug_struct("Reach")
594            .field("held_on", &self.held_on)
595            .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
596            .finish()
597    }
598}
599
600impl PartialEq for Reach {
601    /// Two reaches are equal when they hold the same scopes for the same
602    /// grant (the gate behind them is not compared).
603    fn eq(&self, other: &Self) -> bool {
604        self.held_on == other.held_on && self.grant() == other.grant()
605    }
606}
607
608impl Reach {
609    /// Everything — what a method receives on a hub without a gate (login
610    /// off), as today.
611    pub fn everywhere() -> Self {
612        Self { held_on: vec![ScopeRef::Everywhere], live: None }
613    }
614
615    /// RETURNS-47: nothing — the reach of a call made for no one (a child
616    /// under the `anonymous` forward policy, or one whose caller cannot be
617    /// read). Covers and allows nothing, and names no grant.
618    pub fn nowhere() -> Self {
619        Self { held_on: Vec::new(), live: None }
620    }
621
622    /// Whether the grant is held on `*`.
623    pub fn is_everywhere(&self) -> bool {
624        self.held_on.iter().any(ScopeRef::is_everywhere)
625    }
626
627    /// Whether the grant is held nowhere (a `public` method called by a
628    /// caller who holds no role listing it).
629    pub fn is_empty(&self) -> bool {
630        self.held_on.is_empty()
631    }
632
633    /// The scopes the grant is held on; `[*]` when everywhere.
634    pub fn held_on(&self) -> &[ScopeRef] {
635        &self.held_on
636    }
637
638    /// The grant this reach is for; `None` on a service without a gate.
639    pub fn grant(&self) -> Option<&Grant> {
640        self.live.as_ref().map(|l| &l.grant)
641    }
642
643    /// POLYGLOT-5: the grants generation of the gate this reach came from
644    /// (BIDIR-8) — a call held open elsewhere (a child service's stream)
645    /// asks [`Reach::current`] again only when it moved. `None` without a
646    /// gate.
647    pub fn generation(&self) -> Option<&GrantsGeneration> {
648        self.live.as_ref().map(|l| l.gate.generation())
649    }
650
651    /// Whether the call may act on `target` — asked of the gate as it
652    /// stands now. Without a gate: always. KEEL-31: a whole-service
653    /// method's reach allows a target only while the grant is held on `*`.
654    pub fn allows(&self, target: &str) -> bool {
655        match &self.live {
656            None => self.is_everywhere(),
657            Some(l) if l.everywhere => l.now().is_ok(),
658            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
659        }
660    }
661
662    /// The reach as it stands now: `None` once the grant is held nowhere (a
663    /// stream should end). Without a gate: unchanged.
664    pub fn current(&self) -> Option<Reach> {
665        match &self.live {
666            None => Some(self.clone()),
667            Some(l) => l.now().ok(),
668        }
669    }
670
671    /// FRAME-5: [`Reach::current`] with the gate's refusal kept — `Err`
672    /// says why the grant is held nowhere now: [`Refusal::Ended`] when the
673    /// sign-in no longer stands (signed out, expired, revoked session),
674    /// [`Refusal::MissingGrant`] when the grants moved away,
675    /// [`Refusal::Unauthenticated`] when the caller proves no one. A held
676    /// open call that must say *why* it ends (a watch's typed reason) asks
677    /// this; one that only needs to know whether asks `current`. Without a
678    /// gate: unchanged.
679    pub fn recheck(&self) -> Result<Reach, Refusal> {
680        match &self.live {
681            None => Ok(self.clone()),
682            Some(l) => l.now(),
683        }
684    }
685
686    /// Whether the reach covers a target whose chain is `chain` (as
687    /// [`Resolve::chain`] gives it), by this snapshot — no new question to
688    /// the gate. Prefer [`Reach::allows`] where the answer must be current.
689    pub fn covers(&self, chain: &[ScopeRef]) -> bool {
690        self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
691    }
692}
693
694// ---------------------------------------------------------------------------
695// Gate
696// ---------------------------------------------------------------------------
697
698/// AUTH-11: whether a signed-in caller's sign-in still stands — the
699/// service's session table, asked by [`Gate::check`] on every call (and so
700/// on every [`Reach::allows`] / [`Reach::current`] a stream makes). A
701/// signed-out or revoked session proves no one, whatever its principal
702/// holds. Memory only, like the other service traits.
703pub trait Liveness: Send + Sync {
704    /// `Err`: why the sign-in no longer stands, in words for the caller.
705    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
706}
707
708struct GateInner {
709    memberships: Arc<dyn Memberships>,
710    roles: Arc<dyn Roles>,
711    resolve: Arc<dyn Resolve>,
712    liveness: Option<Arc<dyn Liveness>>,
713    generation: GrantsGeneration,
714}
715
716/// BIDIR-8: what moved the grants generation ([`Gate::moved`]) — every
717/// write that could change an answer the gate gave.
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
719pub enum GrantsMove {
720    /// A membership added.
721    Grant,
722    /// A membership removed.
723    Revoke,
724    /// A role's grants edited.
725    RoleEdit,
726    /// A principal added to a team (it holds the team's grants).
727    TeamAdd,
728    /// A principal removed from a team.
729    TeamRemove,
730    /// A sign-in ended: signed out, or its session revoked.
731    SignOut,
732}
733
734/// BIDIR-8 (BIDIR-5's finding): the **grants generation** — a count every
735/// write that could change one of the gate's answers moves
736/// ([`GrantsMove`]). It is the gate's: whoever holds an answer across time
737/// (a duplex call's caller, a watch) records the generation it was decided
738/// at and asks the gate again only when it has moved — once per move, never
739/// per item. Cheap to clone (two `Arc`s, one count); a read is one atomic
740/// load; a move wakes every [`subscribe`](GrantsGeneration::subscribe)r.
741///
742/// A service shares one across its gates with [`Gate::with_generation`]
743/// (menger: the gate in front of its calls, the access layer's and the store's count are
744/// one).
745#[derive(Clone)]
746pub struct GrantsGeneration {
747    now: Arc<std::sync::atomic::AtomicU64>,
748    tx: Arc<tokio::sync::watch::Sender<u64>>,
749}
750
751impl fmt::Debug for GrantsGeneration {
752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753        f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
754    }
755}
756
757impl Default for GrantsGeneration {
758    fn default() -> Self {
759        Self::new()
760    }
761}
762
763impl GrantsGeneration {
764    /// A count at 0.
765    pub fn new() -> Self {
766        Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
767    }
768
769    /// Something that could change an answer moved: +1, and every
770    /// subscriber woken. Answers the generation now.
771    pub fn bump(&self) -> u64 {
772        let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
773        self.tx.send_replace(n);
774        n
775    }
776
777    /// [`bump`](Self::bump), naming what moved (for the reader; the count
778    /// is one either way).
779    pub fn moved(&self, why: GrantsMove) -> u64 {
780        let _ = why;
781        self.bump()
782    }
783
784    /// The generation now (one atomic load).
785    pub fn current(&self) -> u64 {
786        self.now.load(std::sync::atomic::Ordering::Acquire)
787    }
788
789    /// At least `n` — a service that counted before it shared this handle
790    /// carries its count over. Never back: a smaller `n` changes nothing.
791    pub fn raise_to(&self, n: u64) {
792        let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
793        if n > was {
794            self.tx.send_replace(self.current());
795        }
796    }
797
798    /// What wakes a holder when the generation moves.
799    pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
800        self.tx.subscribe()
801    }
802}
803
804/// The one rule in front of every call: the method's grant, held through a
805/// role on the target's scope, within the session's ceiling. Default deny.
806/// Cheap to clone (one `Arc`); cheap to ask (memory only), so a stream may
807/// ask per event.
808#[derive(Clone)]
809pub struct Gate {
810    inner: Arc<GateInner>,
811}
812
813impl fmt::Debug for Gate {
814    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815        f.write_str("Gate")
816    }
817}
818
819impl Gate {
820    /// A gate over a service's memberships, roles and resolver.
821    pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
822        Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
823    }
824
825    /// BIDIR-8: this gate, counting its moves in `generation` — the
826    /// service's one ([`GrantsGeneration`]), shared by every gate it builds.
827    /// Without it a gate counts alone, from 0.
828    pub fn with_generation(self, generation: GrantsGeneration) -> Self {
829        let i = &self.inner;
830        Self {
831            inner: Arc::new(GateInner {
832                memberships: i.memberships.clone(),
833                roles: i.roles.clone(),
834                resolve: i.resolve.clone(),
835                liveness: i.liveness.clone(),
836                generation,
837            }),
838        }
839    }
840
841    /// BIDIR-8: the grants generation this gate's answers are decided at.
842    pub fn generation(&self) -> &GrantsGeneration {
843        &self.inner.generation
844    }
845
846    /// BIDIR-8: a write that could change this gate's answers happened
847    /// (the service wrote it — the gate keeps no memberships of its own):
848    /// the generation moves once. Answers the generation now.
849    pub fn moved(&self, why: GrantsMove) -> u64 {
850        self.inner.generation.moved(why)
851    }
852
853    /// AUTH-11: this gate, asking `liveness` whether a caller's sign-in
854    /// still stands before every check. Without it the gate still refuses
855    /// a caller past its `expires_at` stamp ([`AuthContext::expired`]).
856    pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
857        let i = &self.inner;
858        Self {
859            inner: Arc::new(GateInner {
860                memberships: i.memberships.clone(),
861                roles: i.roles.clone(),
862                resolve: i.resolve.clone(),
863                liveness: Some(liveness),
864                generation: i.generation.clone(),
865            }),
866        }
867    }
868
869    /// AUTH-11: whether `caller`'s sign-in still stands: not past its
870    /// `expires_at`, and live by the service's [`Liveness`]. An anonymous
871    /// context has no sign-in to end: `Ok`.
872    pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
873        if caller.principal().is_none() {
874            return Ok(());
875        }
876        if caller.expired() {
877            return Err("your sign-in has expired: sign in again".into());
878        }
879        match &self.inner.liveness {
880            Some(l) => l.alive(caller),
881            None => Ok(()),
882        }
883    }
884
885    /// Whether `role` lists `grant` ([`ADMIN`] lists every grant).
886    pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
887        role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
888    }
889
890    /// The roles that list `grant`, [`ADMIN`] last.
891    pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
892        let mut out: Vec<RoleName> = self
893            .inner
894            .roles
895            .names()
896            .into_iter()
897            .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
898            .collect();
899        out.push(RoleName::new(ADMIN));
900        out
901    }
902
903    /// Whether a ceiling entry allows `grant`.
904    fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
905        match entry {
906            RoleOrGrant::Grant(g) => g == grant,
907            RoleOrGrant::Role(r) => self.lists(r, grant),
908        }
909    }
910
911    /// The caller's principal and ceiling layers; `None` when anonymous. An
912    /// unreadable ceiling becomes one empty layer — it allows nothing.
913    fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
914        let ctx = caller?;
915        let principal = ctx.principal()?;
916        let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
917        Some((principal, layers))
918    }
919
920    /// Whether `inner` lies within `outer` (or is it).
921    fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
922        if outer.is_everywhere() || inner == outer {
923            return true;
924        }
925        match inner {
926            ScopeRef::Everywhere => false,
927            ScopeRef::Named(name) => self.inner.resolve.chain(name).is_some_and(|c| c.contains(outer)),
928        }
929    }
930
931    /// The scopes both `a` and `b` reach: where one lies within the other,
932    /// the inner one.
933    fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
934        if a.iter().any(ScopeRef::is_everywhere) {
935            return b;
936        }
937        if b.iter().any(ScopeRef::is_everywhere) {
938            return a;
939        }
940        let mut out = BTreeSet::new();
941        for x in &a {
942            for y in &b {
943                if self.within(x, y) {
944                    out.insert(x.clone());
945                } else if self.within(y, x) {
946                    out.insert(y.clone());
947                }
948            }
949        }
950        out.into_iter().collect()
951    }
952
953    /// Collapse to `[*]` when `*` is among them; dedupe, ordered.
954    fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
955        let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
956        if set.contains(&ScopeRef::Everywhere) {
957            vec![ScopeRef::Everywhere]
958        } else {
959            set.into_iter().collect()
960        }
961    }
962
963    fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
964        let held = self.inner.memberships.held(principal);
965        self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
966    }
967
968    /// Where `held` (role, scope pairs) holds `grant` within `layers`: what
969    /// [`Gate::held_on`] answers from the memberships and
970    /// [`Gate::held_on_by`] from a [`Fingerprint`] — one rule.
971    fn held_on_in<'a>(
972        &self,
973        held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
974        layers: &[Ceiling],
975        grant: &Grant,
976    ) -> Vec<ScopeRef> {
977        let mut acc = Self::normal(held.filter(|(role, _)| self.lists(role, grant)).map(|(_, scope)| scope.clone()));
978        for layer in layers {
979            if acc.is_empty() {
980                break;
981            }
982            let allowed = Self::normal(
983                layer.0.iter().filter(|(rg, _)| self.entry_allows(rg, grant)).map(|(_, s)| s.clone()),
984            );
985            acc = self.meet(acc, allowed);
986        }
987        acc
988    }
989
990    /// Where the caller holds `grant`, within its ceiling: `[*]` when
991    /// everywhere, `[]` when nowhere (and for an anonymous caller). What a
992    /// method without a target answers from.
993    pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
994        match Self::caller_of(Some(caller)) {
995            Some((p, layers)) => self.held_on_for(&p, &layers, grant),
996            None => Vec::new(),
997        }
998    }
999
1000    /// PERF-15: what this gate's answers about `caller` read, besides the
1001    /// grants generation — its principal's memberships and its session's
1002    /// ceiling ([`Fingerprint`]); `None` when it is anonymous. The
1003    /// memberships are read now, from memory.
1004    pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
1005        let (principal, layers) = Self::caller_of(Some(caller))?;
1006        let mut held: Vec<(RoleName, ScopeRef)> =
1007            self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
1008        held.sort();
1009        held.dedup();
1010        Some(Fingerprint { held, layers })
1011    }
1012
1013    /// PERF-15: [`Gate::held_on`] for whoever has `who` — read from the
1014    /// fingerprint instead of the memberships, by the same rule, so a view
1015    /// built from it is exactly the one built from any caller it was taken
1016    /// of.
1017    pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
1018        self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
1019    }
1020
1021    /// Allowed when the grant is listed by a role held on a scope in the
1022    /// target's chain — or anywhere, for a call with no target — and every
1023    /// ceiling layer allows it the same way. The [`Reach`] is live (it asks
1024    /// this gate again on [`Reach::allows`] / [`Reach::current`]).
1025    ///
1026    /// AUTH-11: first, the caller's sign-in must still stand
1027    /// ([`Gate::alive`]) — a signed-out session holds nothing, so a socket
1028    /// that signed out cannot go on to call `auth.grant`.
1029    pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
1030        let Some((principal, layers)) = Self::caller_of(caller) else {
1031            return Err(Refusal::Unauthenticated);
1032        };
1033        if let Some(ctx) = caller {
1034            self.alive(ctx).map_err(|reason| Refusal::Ended { reason })?;
1035        }
1036        let held_on = self.held_on_for(&principal, &layers, grant);
1037        let (allowed, scope) = match target {
1038            None => (!held_on.is_empty(), ScopeRef::Everywhere),
1039            Some(t) => match self.inner.resolve.chain(t) {
1040                None => (false, ScopeRef::named(t)),
1041                Some(chain) => {
1042                    let in_chain = |s: &ScopeRef| s.is_everywhere() || chain.contains(s);
1043                    let by_membership = self
1044                        .inner
1045                        .memberships
1046                        .held(&principal)
1047                        .iter()
1048                        .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
1049                    let by_ceiling = layers
1050                        .iter()
1051                        .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
1052                    let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
1053                    (by_membership && by_ceiling, scope)
1054                }
1055            },
1056        };
1057        if allowed {
1058            Ok(Reach {
1059                held_on,
1060                live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere: false }),
1061            })
1062        } else {
1063            Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
1064        }
1065    }
1066
1067    /// KEEL-31: the check for a method that acts on the whole service (it
1068    /// names no target because its target is everything: a key rotated, a
1069    /// process spawned, a peer connected). Allowed only where the grant is
1070    /// held on `*` — by a role held on `*` that lists it, and every ceiling
1071    /// layer allowing it on `*` — never because it is held on some scope. A
1072    /// scoped `admin`, or a session minted `admin@X`, is refused, naming `*`.
1073    /// The reach is `[*]` and stays live by this same rule.
1074    pub fn check_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
1075        let reach = match self.check(caller, grant, None) {
1076            Ok(reach) => reach,
1077            Err(Refusal::MissingGrant { grant, roles, held_on, .. }) => {
1078                return Err(Refusal::MissingGrant { grant, scope: ScopeRef::Everywhere, roles, held_on })
1079            }
1080            Err(other) => return Err(other),
1081        };
1082        if !reach.is_everywhere() {
1083            return Err(Refusal::MissingGrant {
1084                grant: grant.clone(),
1085                scope: ScopeRef::Everywhere,
1086                roles: self.roles_listing(grant),
1087                held_on: reach.held_on,
1088            });
1089        }
1090        Ok(Reach {
1091            held_on: reach.held_on,
1092            live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere: true }),
1093        })
1094    }
1095
1096    /// The reach of a `public` method: what [`Gate::check`] would allow
1097    /// without a target, or an empty (still live) reach when the caller holds
1098    /// the grant nowhere or is anonymous. A public method is never refused.
1099    pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
1100        self.check(caller, grant, None).unwrap_or_else(|_| Reach {
1101            held_on: Vec::new(),
1102            live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere: false }),
1103        })
1104    }
1105}
1106
1107// ---------------------------------------------------------------------------
1108// Tests — the gate's decision table
1109// ---------------------------------------------------------------------------
1110
1111#[cfg(test)]
1112mod tests {
1113    use super::*;
1114    use std::sync::Mutex;
1115
1116    const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1117    const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
1118
1119    /// Memberships as a mutable table, so a test can revoke one.
1120    #[derive(Default)]
1121    struct Members(Mutex<Vec<Membership>>);
1122    impl Members {
1123        fn grant(&self, who: &str, role: &str, scope: &str) {
1124            self.0.lock().unwrap().push(Membership {
1125                principal: who.parse().unwrap(),
1126                role: RoleName::new(role),
1127                scope: ScopeRef::parse(scope),
1128            });
1129        }
1130        fn revoke_all(&self) {
1131            self.0.lock().unwrap().clear();
1132        }
1133    }
1134    impl Memberships for Members {
1135        fn held(&self, who: &Principal) -> Vec<Membership> {
1136            self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
1137        }
1138    }
1139
1140    /// menger-shaped: a ticket `CODE-n` lives in itself, then `CODE`;
1141    /// MENGER and IDENTITY are disjoint, both hosted under PLEXUS.
1142    struct Shortcodes;
1143    impl Resolve for Shortcodes {
1144        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
1145            let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
1146            let mut chain = Vec::new();
1147            if target.contains('-') {
1148                chain.push(ScopeRef::named(target));
1149            }
1150            match code {
1151                "MENGER" | "IDENTITY" => {
1152                    chain.push(ScopeRef::named(code));
1153                    chain.push(ScopeRef::named("PLEXUS"));
1154                }
1155                "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
1156                _ => return None,
1157            }
1158            chain.push(ScopeRef::Everywhere);
1159            Some(chain)
1160        }
1161    }
1162
1163    fn roles() -> RoleTable {
1164        RoleTable::new()
1165            .define("viewer", ["tickets.get", "tickets.list"])
1166            .unwrap()
1167            .define("editor", ["viewer", "tickets.set_status"])
1168            .unwrap()
1169    }
1170
1171    fn gate(members: &Arc<Members>) -> Gate {
1172        Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
1173    }
1174
1175    fn who(p: &str) -> AuthContext {
1176        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
1177    }
1178
1179    fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
1180        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
1181    }
1182
1183    fn g(s: &str) -> Grant {
1184        Grant::new(s)
1185    }
1186
1187    #[test]
1188    fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
1189        let m = Arc::new(Members::default());
1190        m.grant(ADA, "editor", "*");
1191        m.grant(BOB, "admin", "MENGER");
1192        let gate = gate(&m);
1193        let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
1194        assert_eq!(
1195            err,
1196            Refusal::MissingGrant {
1197                grant: g("members.grant"),
1198                scope: ScopeRef::named("MENGER-1"),
1199                roles: vec![RoleName::new("admin")],
1200                held_on: vec![],
1201            }
1202        );
1203        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
1204        // admin on MENGER is not admin on IDENTITY.
1205        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
1206    }
1207
1208    #[test]
1209    fn held_on_a_scope_allows_targets_in_its_chain_only() {
1210        let m = Arc::new(Members::default());
1211        m.grant(ADA, "editor", "MENGER");
1212        let gate = gate(&m);
1213        let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
1214        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
1215        let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
1216        assert_eq!(
1217            err,
1218            Refusal::MissingGrant {
1219                grant: g("tickets.set_status"),
1220                scope: ScopeRef::named("IDENTITY-1"),
1221                roles: vec![RoleName::new("editor"), RoleName::new("admin")],
1222                held_on: vec![ScopeRef::named("MENGER")],
1223            }
1224        );
1225        assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
1226        // A target nothing resolves is refused.
1227        assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
1228    }
1229
1230    #[test]
1231    fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
1232        let m = Arc::new(Members::default());
1233        m.grant(ADA, "viewer", "*");
1234        m.grant(ADA, "viewer", "MENGER");
1235        let gate = gate(&m);
1236        let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
1237        assert!(reach.is_everywhere());
1238        assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
1239        assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
1240        // viewer does not list set_status, wherever it is held.
1241        assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
1242    }
1243
1244    #[test]
1245    fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
1246        let m = Arc::new(Members::default());
1247        m.grant(ADA, "viewer", "MENGER");
1248        m.grant(ADA, "viewer", "IDENTITY");
1249        let gate = gate(&m);
1250        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1251        assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
1252        assert!(reach.allows("MENGER-4"));
1253        assert!(!reach.allows("PLEXUS-1"));
1254        let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
1255        assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
1256    }
1257
1258    #[test]
1259    fn a_ceiling_narrows_the_membership() {
1260        let m = Arc::new(Members::default());
1261        m.grant(ADA, "editor", "MENGER");
1262        let gate = gate(&m);
1263        let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1264        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
1265        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
1266        // The reach of a target-less read is the meet: MENGER-12, inside MENGER.
1267        let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
1268        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
1269        // A grant-entry ceiling: only tickets.get, anywhere the membership allows.
1270        let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
1271        assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
1272        let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
1273        assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
1274        // Two layers: both must allow.
1275        let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
1276        assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
1277        assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
1278        // A ceiling never widens: editor@IDENTITY grants nothing there.
1279        let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
1280        assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
1281        // An unreadable ceiling allows nothing.
1282        let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
1283        assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
1284    }
1285
1286    #[test]
1287    fn role_inclusion_flattens_and_must_name_an_earlier_role() {
1288        let r = roles();
1289        let editor = r.grants(&RoleName::new("editor")).unwrap();
1290        assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
1291        let viewer = r.grants(&RoleName::new("viewer")).unwrap();
1292        assert!(!viewer.contains(&g("tickets.set_status")));
1293        assert_eq!(
1294            RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
1295            RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
1296        );
1297        // admin is built in: holds every grant, whatever the table says.
1298        assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
1299        // from_lists merges one role's lists from several activations.
1300        let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
1301        let e = merged.grants(&RoleName::new("editor")).unwrap();
1302        assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
1303    }
1304
1305    #[test]
1306    fn anonymous_is_unauthenticated() {
1307        let m = Arc::new(Members::default());
1308        let gate = gate(&m);
1309        assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
1310        assert_eq!(
1311            gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
1312            Refusal::Unauthenticated
1313        );
1314        // A public method's reach for an anonymous caller: empty, never refused.
1315        assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
1316    }
1317
1318    #[test]
1319    fn a_live_reach_follows_grants_as_they_stand() {
1320        let m = Arc::new(Members::default());
1321        m.grant(ADA, "viewer", "MENGER");
1322        let gate = gate(&m);
1323        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1324        assert!(reach.allows("MENGER-1"));
1325        assert!(reach.current().is_some());
1326        m.revoke_all();
1327        assert!(!reach.allows("MENGER-1"));
1328        assert!(reach.current().is_none());
1329        // Without a gate, everything.
1330        assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
1331    }
1332
1333    #[test]
1334    fn scope_refs_and_ceilings_round_trip() {
1335        assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
1336        assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
1337        let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
1338        assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
1339        assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
1340        assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
1341        assert!(Ceiling::parse(["editor"]).is_err());
1342    }
1343
1344    /// A session table with one switch: signed out or not.
1345    #[derive(Default)]
1346    struct Switch(std::sync::atomic::AtomicBool);
1347    impl Liveness for Switch {
1348        fn alive(&self, _: &AuthContext) -> Result<(), String> {
1349            if self.0.load(std::sync::atomic::Ordering::SeqCst) {
1350                Err("you have signed out: sign in again".into())
1351            } else {
1352                Ok(())
1353            }
1354        }
1355    }
1356
1357    /// AUTH-11: a signed-out session holds nothing — not even admin on `*`
1358    /// — and a live reach taken before the sign-out ends with it.
1359    #[test]
1360    fn a_session_that_ended_holds_nothing() {
1361        let m = Arc::new(Members::default());
1362        m.grant(ADA, "admin", "*");
1363        let out = Arc::new(Switch::default());
1364        let gate = gate(&m).with_liveness(out.clone());
1365        let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
1366        assert!(reach.allows("MENGER-1"));
1367        out.0.store(true, std::sync::atomic::Ordering::SeqCst);
1368        let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
1369        assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
1370        assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
1371        assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
1372        assert!(reach.current().is_none());
1373        assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
1374        // Anonymous is not "ended": still plain Unauthenticated.
1375        assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
1376    }
1377
1378    /// AUTH-11: past its `expires_at` stamp, a sign-in is over even with
1379    /// no liveness hook.
1380    #[test]
1381    fn an_expired_sign_in_holds_nothing() {
1382        let m = Arc::new(Members::default());
1383        m.grant(ADA, "admin", "*");
1384        let gate = gate(&m);
1385        let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
1386        assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
1387        let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
1388        assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
1389    }
1390
1391    /// PERF-15: a fingerprint is what the gate's answers read of a caller —
1392    /// equal for two principals holding the same, different when a
1393    /// membership or the ceiling differs, `None` when anonymous — and
1394    /// `held_on_by` answers from it exactly what `held_on` answers.
1395    #[test]
1396    fn a_fingerprint_is_what_the_answers_read() {
1397        let m = Arc::new(Members::default());
1398        m.grant(ADA, "viewer", "IDENTITY");
1399        m.grant(ADA, "editor", "MENGER");
1400        m.grant(BOB, "editor", "MENGER");
1401        m.grant(BOB, "viewer", "IDENTITY");
1402        m.grant(BOB, "editor", "MENGER");
1403        let gate = gate(&m);
1404        let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
1405        assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
1406        assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
1407        let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1408        let narrowed = gate.fingerprint(&narrow).unwrap();
1409        assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
1410        let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
1411        assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
1412        for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
1413            for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
1414                assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
1415            }
1416        }
1417        assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
1418        m.revoke_all();
1419        assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
1420    }
1421
1422    /// KEEL-31 (the review's probe, KEEL-28): `admin` held on one ticket is
1423    /// admitted to a method with no target by [`Gate::check`] — held
1424    /// somewhere — and refused by [`Gate::check_everywhere`], naming `*`; so
1425    /// is a session minted narrower than `*`. Held on `*`, it is allowed,
1426    /// and its reach stays live by the same rule.
1427    #[test]
1428    fn a_whole_service_method_needs_its_grant_on_everywhere() {
1429        let m = Arc::new(Members::default());
1430        m.grant(ADA, "admin", "MENGER-5");
1431        m.grant(BOB, "admin", "*");
1432        let gate = gate(&m);
1433        let grow = g("dyn.grow");
1434        assert_eq!(gate.check(Some(&who(ADA)), &grow, None).unwrap().held_on(), [ScopeRef::named("MENGER-5")]);
1435        match gate.check_everywhere(Some(&who(ADA)), &grow) {
1436            Err(Refusal::MissingGrant { scope, held_on, .. }) => {
1437                assert_eq!(scope, ScopeRef::Everywhere);
1438                assert_eq!(held_on, [ScopeRef::named("MENGER-5")]);
1439            }
1440            other => panic!("a scoped admin: {other:?}"),
1441        }
1442        let reach = gate.check_everywhere(Some(&who(BOB)), &grow).unwrap();
1443        assert!(reach.is_everywhere());
1444        for ceiling in [serde_json::json!(["admin@MENGER-5"]), serde_json::json!(["viewer@*"]), serde_json::json!("admin@*")] {
1445            let capped = with_ceiling(BOB, ceiling.clone());
1446            assert!(gate.check_everywhere(Some(&capped), &grow).is_err(), "ceiling {ceiling}");
1447        }
1448        assert!(gate.check_everywhere(Some(&with_ceiling(BOB, serde_json::json!(["dyn.grow@*"]))), &grow).is_ok());
1449        assert!(gate.check_everywhere(Some(&with_ceiling(ADA, serde_json::json!(["admin@*"]))), &grow).is_err(), "a ceiling never widens");
1450        assert_eq!(gate.check_everywhere(None, &grow).err(), Some(Refusal::Unauthenticated));
1451        // Live: narrowed to a scope while it runs, the reach is gone.
1452        m.revoke_all();
1453        m.grant(BOB, "admin", "MENGER");
1454        assert!(reach.current().is_none());
1455        assert!(reach.recheck().is_err());
1456        assert!(!reach.allows("MENGER-1"));
1457    }
1458}