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//! - ONE-6: a membership may also be held on an **address** — `/dyn` (the
25//!   methods of the activation `dyn`, or with `/dyn.connect` one method) or
26//!   `/dyn.*` (`dyn` and everything mounted beneath it). `self` is `*`: the
27//!   service being called. A scope being written goes through
28//!   [`ScopeRef::parse_checked`].
29//!
30//! # Activation scopes and data scopes are separate (ONE-6)
31//!
32//! Owner, 2026-11-11: "activation and data scopes are separate. we can only
33//! generally handle activation scopes. data scopes must be handled by the
34//! application". An address scope answers one question — may this caller
35//! make this call at this address (the **door**) — and never stands for
36//! data: it is never among the scopes a [`Reach`] holds, never satisfies a
37//! data target, and never makes a read "held anywhere". The gate owns
38//! addresses: it is told the call as one [`DispatchedCall`] (its literal
39//! address and its grant) and never asks a [`Resolve`] about one.
40//!
41//! What an address scope does, by the three shapes the gate knows:
42//!
43//! | the method's shape | asked through | an address scope covering the call | a data scope | `*` |
44//! |---|---|---|---|---|
45//! | `everywhere` (acts on the whole activation: `dyn.connect`, `auth.role_set`) | [`Gate::check_everywhere_at`] | **admits** (the door) | never (KEEL-31) | admits |
46//! | a declared target (`tickets.get --id KILN-3`) | [`Gate::check`] with the target | **nothing** | admits when in the target's chain | admits |
47//! | no target (`tickets.list`, `dyn.peers`, `ui.versions`) | [`Gate::check`] with none | **nothing** | admits, reach = the data scopes | admits, reach `[*]` |
48//! | a call into an untyped peer slot (`dyn.peer.shop.items.list`) — no data chain on this service | [`Gate::check_everywhere_at`] (build 2) | **admits** (the door) | never | admits |
49//!
50//! **"No target" is ambiguous**: it is a read over data (`tickets.list`)
51//! or a method with no data at all (`dyn.peers`, `ui.versions`), and the
52//! gate cannot tell which. The safe default is the data reading: an address
53//! scope counts for nothing there, so a caller who holds a grant only on
54//! addresses is refused — not admitted with an empty reach, which a method
55//! that forgets to filter by its reach would read as "no restriction", and
56//! which would make "held on an address" a second meaning of "held
57//! nowhere". So `operator on /dyn` cannot call `dyn.peers` until it is
58//! declared activation-scoped. What builds 2–3 need instead of a new word
59//! here: (a) the dispatcher sends `everywhere` methods and untyped peer-slot
60//! calls through [`Gate::check_everywhere_at`]; (b) a schema-level way to
61//! say "this targetless method touches no data" — reusing `everywhere`
62//! (decided at the door alone; a data-scoped holder refused) is enough for
63//! `dyn.peers`-like methods, or a macro word if a targetless method must
64//! stay open to data holders *and* address holders; (c) the in-method
65//! backstops that ask [`Reach::is_everywhere`] on whole-service methods move
66//! to [`Reach::holds_activation`].
67//!
68//! A ceiling layer is read the same way: its entries on addresses count at
69//! the door, its entries on data scopes (and `*`) count for data. A layer
70//! with only address entries allows no data; a layer with only data entries
71//! opens no door.
72//!
73//! [`Gate::check`] answers one call: allowed — with the [`Reach`] the method
74//! answers from — or a [`Refusal`] that names what was needed. Everything is
75//! answered from memory: the three service traits are synchronous and must
76//! not do I/O.
77//!
78//! # Relation to R-5's [`ScopeRegistry`](crate::ScopeRegistry)
79//!
80//! R-5's registry maps *token-claimed roles* to dotted capability scopes and
81//! knows nothing of where a role is held. The grant model keeps its words —
82//! a grant is exactly R-5's implicit `<activation>.<method>` scope, and
83//! [`RoleName`] is the same type — and adds the *where*: memberships on
84//! scopes, targets resolved through a chain, ceilings. Both gates can be
85//! configured on one service; a service with neither dispatches as before.
86
87use std::collections::{BTreeMap, BTreeSet};
88use std::fmt;
89use std::sync::Arc;
90
91use serde::{Deserialize, Deserializer, Serialize, Serializer};
92
93use crate::audit::RoleName;
94use crate::auth::AuthContext;
95use crate::identity::Principal;
96
97/// The built-in role that holds every grant. No other role holds anything it
98/// does not list.
99pub const ADMIN: &str = "admin";
100
101/// The metadata key a session's ceiling rides under (IDENTITY-42's
102/// `menger_session` sessions write it): either a list of `role@SCOPE` /
103/// `grant@SCOPE` strings (one layer) or a list of such lists (layers, every
104/// one of which must allow a check).
105pub const CEILING_KEY: &str = "ceiling";
106
107// ---------------------------------------------------------------------------
108// Grant
109// ---------------------------------------------------------------------------
110
111/// The right to call one method: `<activation>.<method>`, e.g.
112/// `tickets.set_status`. Every method has exactly one; nothing declares it.
113#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
114#[serde(transparent)]
115pub struct Grant(String);
116
117impl Grant {
118    /// Wrap a dotted method path as a grant. Unvalidated, as wire-decoded
119    /// values are.
120    pub fn new(path: impl Into<String>) -> Self {
121        Self(path.into())
122    }
123
124    /// The grant of `method` on `activation`: `<activation>.<method>`.
125    pub fn of(activation: &str, method: &str) -> Self {
126        Self(format!("{activation}.{method}"))
127    }
128
129    /// The dotted path.
130    pub fn as_str(&self) -> &str {
131        &self.0
132    }
133}
134
135impl fmt::Display for Grant {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.write_str(&self.0)
138    }
139}
140
141// ---------------------------------------------------------------------------
142// ScopeRef
143// ---------------------------------------------------------------------------
144
145/// Where a role is held: everywhere (`*`) or one named scope (`MENGER`).
146/// What a name means — a shortcode, a tenant, a project — is the service's;
147/// the gate only compares names and asks [`Resolve::chain`] how they nest.
148///
149/// ONE-6: two kinds of name are not the service's.
150///
151/// - A name that begins with `/` is an address scope (`/dyn`, `/dyn.*`,
152///   [`ScopeRef::parse_checked`]), which the gate decides by the call's
153///   address alone ([`CallAddress`], [`DispatchedCall`]). It is never a data
154///   scope: a service whose own data scopes began with `/` loses them (as of
155///   0.3.4), and a [`Resolve`] chain that names one has it dropped.
156/// - The name `self` is reserved: written through
157///   [`ScopeRef::parse_checked`] it is `*`; held as a raw `Named("self")`
158///   (stored through the lenient [`ScopeRef::parse`] or serde) it holds
159///   nothing at all — never a data scope, never `*`. A [`Resolve`] chain that
160///   names it has it dropped too.
161///
162/// An address scope never stands for data: it opens the door of the calls
163/// it covers and holds nothing else (the module's "Activation scopes and
164/// data scopes are separate"; the rules are `Gate::as_data` and
165/// `Gate::opens`).
166///
167/// On the wire, a plain string: `"*"` or the name.
168#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
169pub enum ScopeRef {
170    /// `*`: every scope.
171    Everywhere,
172    /// One named scope, and whatever the service nests under it.
173    Named(String),
174}
175
176impl ScopeRef {
177    /// `"*"` → [`ScopeRef::Everywhere`]; anything else (trimmed) → named.
178    ///
179    /// Lenient, as the wire is: it refuses nothing and reads `self` as a
180    /// name, which the gate then holds on nothing. **A scope being written —
181    /// a membership granted (`auth.grant`, `members.grant`), a role or a
182    /// team's grant stored, a ceiling minted into a session — must go
183    /// through [`ScopeRef::parse_checked`]**, which reads `self` as `*` and
184    /// refuses a malformed address, so neither is stored to mean nothing.
185    pub fn parse(text: &str) -> Self {
186        match text.trim() {
187            "*" => Self::Everywhere,
188            other => Self::Named(other.to_string()),
189        }
190    }
191
192    /// A named scope.
193    pub fn named(name: impl Into<String>) -> Self {
194        Self::Named(name.into())
195    }
196
197    /// `"*"` or the name.
198    pub fn as_str(&self) -> &str {
199        match self {
200            Self::Everywhere => "*",
201            Self::Named(n) => n,
202        }
203    }
204
205    /// Whether this is `*`.
206    pub fn is_everywhere(&self) -> bool {
207        matches!(self, Self::Everywhere)
208    }
209
210    /// ONE-6: a scope as a grant writes it, checked — what a membership or
211    /// a ceiling may be held on:
212    ///
213    /// - `*` or `self` → [`ScopeRef::Everywhere`]: the root of the service
214    ///   being called (`self` never means the caller);
215    /// - `/a.b` or `/a.b.*` → an address scope, kept as written (see
216    ///   [`CallAddress`] for the forms and what each covers); refused unless
217    ///   every segment is one or more of `A–Z a–z 0–9 _ -`, so `/`, `//`,
218    ///   `/*`, `/a.`, `/.a`, `/a..b`, `/a.*.b`, and any `*`, `@`, space or
219    ///   non-ASCII character inside one are refused;
220    /// - anything else non-empty, with no space around it → a data scope,
221    ///   the service's own name.
222    ///
223    /// [`ScopeRef::parse`] stays as it was (lenient, the wire's): it never
224    /// reads `self` as `*`. A malformed address it lets through is held on
225    /// nothing — the gate reads every scope that begins with `/` as an
226    /// address scope or as nothing, never as a data scope.
227    pub fn parse_checked(text: &str) -> Result<Self, AddressError> {
228        match text {
229            "*" | "self" => Ok(Self::Everywhere),
230            t if t.starts_with('/') => match address_form(t) {
231                Some(_) => Ok(Self::Named(t.to_string())),
232                None => Err(AddressError(format!(
233                    "`{t}` is not an address scope: `/` then dotted segments of A-Z a-z 0-9 _ -, \
234                     optionally ending `.*`"
235                ))),
236            },
237            t if t.is_empty() || t.trim() != t => Err(AddressError(format!("`{t}` is not a scope"))),
238            t => Ok(Self::Named(t.to_string())),
239        }
240    }
241
242    /// ONE-6: whether this is an address scope — a name beginning with `/`.
243    /// Well formed or not: one that is not covers nothing.
244    pub fn is_address(&self) -> bool {
245        matches!(self, Self::Named(n) if n.starts_with('/'))
246    }
247
248    /// A service's own name: neither `*`, nor an address, nor the reserved
249    /// `self`.
250    fn is_data(&self) -> bool {
251        matches!(self, Self::Named(n) if !n.starts_with('/') && n != "self")
252    }
253
254    /// ONE-6: whether this scope covers the call at `at` *as an address*:
255    /// `*` covers every call; `/P` the methods of the activation `P` and
256    /// the method `P` itself; `/P.*` the address `P` and everything under
257    /// it. A data scope, or a malformed address, covers none.
258    pub fn covers_address(&self, at: &CallAddress) -> bool {
259        match self {
260            Self::Everywhere => true,
261            Self::Named(n) => match address_form(n) {
262                Some((p, true)) => at.path() == p || at.path().strip_prefix(p).is_some_and(|rest| rest.starts_with('.')),
263                Some((p, false)) => p == at.activation() || p == at.path(),
264                None => false,
265            },
266        }
267    }
268}
269
270// ---------------------------------------------------------------------------
271// Addresses (ONE-6)
272// ---------------------------------------------------------------------------
273
274/// ONE-6: why an address, or a scope written as one, was refused.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct AddressError(pub String);
277
278impl fmt::Display for AddressError {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.write_str(&self.0)
281    }
282}
283
284impl std::error::Error for AddressError {}
285
286/// One segment of an address: one or more of `A–Z a–z 0–9 _ -`. Compared
287/// byte for byte, so case matters (`/Dyn` is not `/dyn`).
288fn segment_ok(segment: &str) -> bool {
289    !segment.is_empty() && segment.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
290}
291
292/// One or more segments joined by single dots.
293fn path_ok(path: &str) -> bool {
294    path.split('.').all(segment_ok)
295}
296
297/// An address scope's path and whether it is the subtree form (`/P.*`);
298/// `None` when `scope` is not a well-formed address scope.
299fn address_form(scope: &str) -> Option<(&str, bool)> {
300    let body = scope.strip_prefix('/')?;
301    let (path, subtree) = match body.strip_suffix(".*") {
302        Some(p) => (p, true),
303        None => (body, false),
304    };
305    path_ok(path).then_some((path, subtree))
306}
307
308/// ONE-6: the literal address of one call — the activation it is
309/// dispatched to and the method, named apart. The gate is told it by
310/// whoever dispatches (plexus-core), from the path it routes, never from a
311/// parameter; a service's [`Resolve`] is never asked about an address.
312///
313/// **A method of X, or a child of X.** A dotted path alone does not say
314/// which of its dots separates the activation from the method, so the
315/// gate is told: the activation is one or more segments, the method is
316/// exactly one. `dyn.connect` is the method `connect` of the activation
317/// `dyn`; `dyn.peer.shop.items.list` is the method `list` of the activation
318/// `dyn.peer.shop.items` — mounted under `dyn`, not of it. Since a method
319/// may not hold a dot, a path has one way to be told and no other: a
320/// caller that split it anywhere but at its last dot is refused here.
321///
322/// **What an address scope covers** ([`ScopeRef::covers_address`]):
323///
324/// | held on | covers the call at `A.m` when |
325/// |---|---|
326/// | `*`, `self` | always |
327/// | `/P` | `P` is `A` (a method of that activation) or `P` is `A.m` (that one method) |
328/// | `/P.*` | `A.m` is `P` or begins with `P.` (`P` and all beneath it) |
329///
330/// So `operator on /dyn` reaches `dyn.connect` and not
331/// `dyn.peer.shop.items.list`; `operator on /dyn.*` reaches both;
332/// `operator on /dyn.peer.shop.*` reaches the peer `shop` alone.
333///
334/// **`/P` names a method and an activation alike.** `/dyn.connect` covers
335/// the method `dyn.connect` *and* every method of an activation mounted at
336/// `dyn.connect`, should one exist. An address cannot tell them apart; a
337/// service that mounts a child under a method's name gives both to whoever
338/// holds `/P`.
339///
340/// **The contract a dispatcher relies on.** What is refused here: an empty
341/// segment, a method holding a dot, and any byte outside `A–Z a–z 0–9 _ -`
342/// (so `*`, `@`, `{`, `/`, a space, non-ASCII). What cannot be refused
343/// here: a key that holds a dot, joined into the activation's path
344/// (`dyn.peer.github.repos.alice.app.v2.issues`) — it reads as two
345/// segments, and `/…alice.app.*` would cover the repository `app.v2`. A
346/// dispatcher builds the address from its routed segments with
347/// [`CallAddress::of_segments`], which refuses a segment holding a dot,
348/// and never joins or splits a key itself. An address that cannot be built
349/// is no address: the call is decided as told none, where an address scope
350/// holds nothing — never on a shorter address that would parse.
351#[derive(Debug, Clone, PartialEq, Eq, Hash)]
352pub struct CallAddress {
353    /// `activation.method`.
354    path: String,
355    /// Where the method begins, less the dot: `activation.len()`.
356    dot: usize,
357}
358
359impl CallAddress {
360    /// The call of `method` on the activation at `activation`
361    /// (`CallAddress::new("dyn.peer.shop.items", "list")`). Refused unless
362    /// `activation` is dotted segments and `method` is one segment, each of
363    /// `A–Z a–z 0–9 _ -`.
364    pub fn new(activation: &str, method: &str) -> Result<Self, AddressError> {
365        if !path_ok(activation) {
366            return Err(AddressError(format!("`{activation}` is not an activation's address")));
367        }
368        if !segment_ok(method) {
369            return Err(AddressError(format!("`{method}` is not a method's name (one segment, no dot)")));
370        }
371        Ok(Self { path: format!("{activation}.{method}"), dot: activation.len() })
372    }
373
374    /// The call of `method` on the activation whose path is `activation`,
375    /// segment by segment as routed (`["dyn", "peer", "shop", "items"]`,
376    /// `"list"`). Each is one segment: one holding a dot (a key `app.v2`)
377    /// is refused, never split.
378    pub fn of_segments(activation: &[&str], method: &str) -> Result<Self, AddressError> {
379        match activation.iter().find(|s| !segment_ok(s)) {
380            Some(bad) => Err(AddressError(format!("`{bad}` is not one segment of an address"))),
381            None if activation.is_empty() => Err(AddressError("an activation's address has a segment".into())),
382            None => Self::new(&activation.join("."), method),
383        }
384    }
385
386    /// The activation's address: `dyn`, `dyn.peer.shop.items`.
387    pub fn activation(&self) -> &str {
388        &self.path[..self.dot]
389    }
390
391    /// The method's name: `connect`.
392    pub fn method(&self) -> &str {
393        &self.path[self.dot + 1..]
394    }
395
396    /// The whole address, as dispatched: `dyn.connect`.
397    pub fn path(&self) -> &str {
398        &self.path
399    }
400}
401
402impl fmt::Display for CallAddress {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        f.write_str(&self.path)
405    }
406}
407
408/// ONE-6: one call as dispatched — its literal address and the grant that
409/// address dispatches to, as one value. The door
410/// ([`Gate::check_everywhere_at`]) takes this and nothing else, and decides
411/// its grant: an address scope covering the address admits that grant only.
412///
413/// The dispatcher builds it **once, at dispatch, from the routed entry**:
414/// the address from the path it routed, the grant from the same entry (the
415/// method's own, a schema-named one, or a slot's such as `dyn.{peer}`). The
416/// gate never compares the two as strings — a grant's name may differ from
417/// its path.
418///
419/// **A check inside a call** — a method's own `required(…)`, a seam asking
420/// the gate, a store's per-aspect check, any second grant — is asked with
421/// [`Gate::check`] / [`Gate::check_everywhere`], told no address: an address
422/// scope holds nothing there. Only the reach the door gave carries its
423/// address, and only for its own grant ([`Reach::current`] re-asks with
424/// both; [`Reach::allows`] answers data, which an address never holds).
425#[derive(Debug, Clone, PartialEq, Eq, Hash)]
426pub struct DispatchedCall {
427    at: CallAddress,
428    grant: Grant,
429}
430
431impl DispatchedCall {
432    /// The call at `at`, which dispatches to `grant`.
433    pub fn new(at: CallAddress, grant: Grant) -> Self {
434        Self { at, grant }
435    }
436
437    /// Its address.
438    pub fn at(&self) -> &CallAddress {
439        &self.at
440    }
441
442    /// The grant its address dispatches to.
443    pub fn grant(&self) -> &Grant {
444        &self.grant
445    }
446}
447
448impl fmt::Display for ScopeRef {
449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450        f.write_str(self.as_str())
451    }
452}
453
454impl Serialize for ScopeRef {
455    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
456        s.serialize_str(self.as_str())
457    }
458}
459
460impl<'de> Deserialize<'de> for ScopeRef {
461    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
462        let s = String::deserialize(d)?;
463        Ok(Self::parse(&s))
464    }
465}
466
467// ---------------------------------------------------------------------------
468// GrantSet, RoleOrGrant, Membership, Ceiling
469// ---------------------------------------------------------------------------
470
471/// What a role holds: every grant ([`ADMIN`]) or exactly those it lists.
472#[derive(Debug, Clone, PartialEq, Eq)]
473pub enum GrantSet {
474    /// Every grant — the admin role, and only it by default.
475    All,
476    /// Exactly these grants.
477    Listed(BTreeSet<Grant>),
478}
479
480impl GrantSet {
481    /// Whether the set holds `grant`.
482    pub fn contains(&self, grant: &Grant) -> bool {
483        match self {
484            Self::All => true,
485            Self::Listed(set) => set.contains(grant),
486        }
487    }
488
489    /// A listed set from anything that names grants.
490    pub fn listed<I, G>(grants: I) -> Self
491    where
492        I: IntoIterator<Item = G>,
493        G: Into<String>,
494    {
495        Self::Listed(grants.into_iter().map(|g| Grant::new(g)).collect())
496    }
497}
498
499/// One ceiling entry's left side: a role (`editor`) or a single grant
500/// (`tickets.get`). A dotted name is a grant; a bare one is a role.
501#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
502pub enum RoleOrGrant {
503    Role(RoleName),
504    Grant(Grant),
505}
506
507impl RoleOrGrant {
508    /// A dotted name is a grant, a bare one a role.
509    pub fn parse(text: &str) -> Self {
510        let t = text.trim();
511        if t.contains('.') {
512            Self::Grant(Grant::new(t))
513        } else {
514            Self::Role(RoleName::new(t))
515        }
516    }
517}
518
519impl fmt::Display for RoleOrGrant {
520    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521        match self {
522            Self::Role(r) => write!(f, "{r}"),
523            Self::Grant(g) => write!(f, "{g}"),
524        }
525    }
526}
527
528/// A principal holds a role on a scope: `key:ac79… is editor on MENGER`.
529#[derive(Debug, Clone, PartialEq, Eq)]
530pub struct Membership {
531    pub principal: Principal,
532    pub role: RoleName,
533    pub scope: ScopeRef,
534}
535
536/// A session's upper bound (IDENTITY-40): `(role or grant, scope)` entries,
537/// spelled `editor@MENGER-12`, `tickets.get@*`. A check passes a ceiling
538/// when some entry's scope is in the target's chain and the entry allows the
539/// grant (the grant itself, or a role listing it).
540#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
541pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);
542
543/// Why a ceiling could not be read.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct CeilingError(pub String);
546
547impl fmt::Display for CeilingError {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        f.write_str(&self.0)
550    }
551}
552
553impl std::error::Error for CeilingError {}
554
555impl Ceiling {
556    /// One `role@SCOPE` or `grant@SCOPE` entry.
557    pub fn entry(text: &str) -> Result<(RoleOrGrant, ScopeRef), CeilingError> {
558        let (left, scope) = text
559            .trim()
560            .split_once('@')
561            .ok_or_else(|| CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())))?;
562        if left.trim().is_empty() || scope.trim().is_empty() {
563            return Err(CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())));
564        }
565        Ok((RoleOrGrant::parse(left), ScopeRef::parse(scope)))
566    }
567
568    /// A ceiling from its entries' text.
569    pub fn parse<I, S>(entries: I) -> Result<Self, CeilingError>
570    where
571        I: IntoIterator<Item = S>,
572        S: AsRef<str>,
573    {
574        entries
575            .into_iter()
576            .map(|e| Self::entry(e.as_ref()))
577            .collect::<Result<Vec<_>, _>>()
578            .map(Ceiling)
579    }
580
581    /// The entries as the wire says them: `role@SCOPE` each.
582    pub fn text(&self) -> Vec<String> {
583        self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
584    }
585
586    /// The ceilings an identity's metadata carries under [`CEILING_KEY`]:
587    /// none → `[]`; a list of strings → one layer; a list of lists → one
588    /// layer each. Anything else is an error, and a caller whose ceiling
589    /// cannot be read must be refused, never widened.
590    pub fn layers_of(ctx: &AuthContext) -> Result<Vec<Ceiling>, CeilingError> {
591        let Some(v) = ctx.metadata.get(CEILING_KEY) else {
592            return Ok(Vec::new());
593        };
594        let unreadable = || CeilingError("this session's ceiling cannot be read: sign in again".into());
595        let items = v.as_array().ok_or_else(unreadable)?;
596        if items.iter().all(|i| i.is_string()) {
597            let texts: Vec<&str> = items.iter().filter_map(|i| i.as_str()).collect();
598            return Ok(vec![Self::parse(texts).map_err(|_| unreadable())?]);
599        }
600        items
601            .iter()
602            .map(|layer| {
603                let entries = layer.as_array().ok_or_else(unreadable)?;
604                let texts = entries
605                    .iter()
606                    .map(|e| e.as_str().ok_or_else(unreadable))
607                    .collect::<Result<Vec<_>, _>>()?;
608                Self::parse(texts).map_err(|_| unreadable())
609            })
610            .collect()
611    }
612}
613
614/// PERF-15: everything [`Gate::held_on`] reads of one signed-in caller,
615/// besides the grants generation — what its principal holds (each
616/// membership's role and scope, as a set) and its session's ceiling layers.
617/// Two callers with equal fingerprints hold the same grants on the same
618/// scopes, whoever they are: at one generation the gate answers them alike.
619/// So a service keeps what a caller may see (its view, AUTH-4) by it —
620/// one entry shared by every caller holding the same, dropped when the
621/// generation moves. Compared whole, never by a digest: two fingerprints are
622/// one key only when they are equal. [`Gate::fingerprint`] takes one,
623/// [`Gate::held_on_by`] answers from it.
624#[derive(Debug, Clone, PartialEq, Eq, Hash)]
625pub struct Fingerprint {
626    /// (role, scope) of each membership, sorted, each once.
627    held: Vec<(RoleName, ScopeRef)>,
628    /// The session's ceiling, as [`Ceiling::layers_of`] reads it (an
629    /// unreadable one is one empty layer, as the gate reads it).
630    layers: Vec<Ceiling>,
631}
632
633// ---------------------------------------------------------------------------
634// What a service supplies
635// ---------------------------------------------------------------------------
636
637/// Who holds which role where (menger: its members table, cached). Answered
638/// from memory: no I/O on a call.
639pub trait Memberships: Send + Sync {
640    fn held(&self, who: &Principal) -> Vec<Membership>;
641
642    /// What `who` holds of its own — without a membership the service
643    /// gives every signed-in principal (menger's `everyone` grant). It
644    /// decides whether `who` is still waiting for an admin (`auth.waiting`,
645    /// `auth.signup`); the gate reads [`Memberships::held`]. The default is
646    /// `held`: a service with no such grant has nothing to leave out.
647    fn own_held(&self, who: &Principal) -> Vec<Membership> {
648        self.held(who)
649    }
650}
651
652/// Role → grants (defaults declared in code, edits as data). Answered from
653/// memory. [`ADMIN`] holds every grant whatever this answers.
654pub trait Roles: Send + Sync {
655    /// What `role` holds; `None` for a role this service does not know
656    /// (it holds nothing).
657    fn grants(&self, role: &RoleName) -> Option<GrantSet>;
658
659    /// Every role this service knows, so a refusal can name the roles that
660    /// list a grant. The default knows none (a refusal then names only
661    /// [`ADMIN`]).
662    fn names(&self) -> Vec<RoleName> {
663        Vec::new()
664    }
665}
666
667/// Where a target lives. Answered from memory.
668pub trait Resolve: Send + Sync {
669    /// The scopes a target lives in, innermost first, ending in
670    /// [`ScopeRef::Everywhere`]: `"MENGER-12"` → `[MENGER-12, MENGER, *]`
671    /// (or, for a service whose memberships are per shortcode,
672    /// `[MENGER, *]`). `None`: the value locates nothing — the call is
673    /// refused.
674    ///
675    /// The gate also asks it about **scope names** (a membership's or a
676    /// ceiling's): `chain("MENGER")` → `[MENGER, PLEXUS, *]`, to tell which
677    /// of two scopes lies within the other when it narrows a reach by a
678    /// ceiling. A service that cannot answer for a name returns `None`, and
679    /// two different names are then taken as disjoint.
680    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
681}
682
683// ---------------------------------------------------------------------------
684// RoleTable — an in-memory Roles with inclusion
685// ---------------------------------------------------------------------------
686
687/// Why [`RoleTable::define`] refused a role.
688#[derive(Debug, Clone, PartialEq, Eq)]
689pub enum RoleTableError {
690    /// An entry named a role that is not (yet) defined. A role may only
691    /// include roles defined before it, which is what keeps inclusion
692    /// acyclic.
693    UnknownRole { role: String, includes: String },
694}
695
696impl fmt::Display for RoleTableError {
697    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698        match self {
699            Self::UnknownRole { role, includes } => write!(
700                f,
701                "role {role} includes {includes}, which is not defined before it"
702            ),
703        }
704    }
705}
706
707impl std::error::Error for RoleTableError {}
708
709/// An in-memory [`Roles`]: each role an explicit list of grants, where an
710/// entry may also name an earlier role (inclusion, flattened when defined).
711/// [`ADMIN`] is built in.
712///
713/// ```
714/// use plexus_auth_core::grants::{Grant, RoleTable, Roles};
715/// use plexus_auth_core::RoleName;
716///
717/// let roles = RoleTable::new()
718///     .define("viewer", ["tickets.get", "tickets.list"]).unwrap()
719///     .define("editor", ["viewer", "tickets.set_status"]).unwrap();
720/// let editor = roles.grants(&RoleName::new("editor")).unwrap();
721/// assert!(editor.contains(&Grant::new("tickets.get")));
722/// ```
723#[derive(Debug, Clone, Default)]
724pub struct RoleTable {
725    roles: BTreeMap<RoleName, GrantSet>,
726}
727
728impl RoleTable {
729    /// The table with only the built-in [`ADMIN`].
730    pub fn new() -> Self {
731        Self::default()
732    }
733
734    /// Define (or extend) `role`: each entry a grant (dotted) or an earlier
735    /// role (bare), whose grants are included. Defining a role again adds to
736    /// it, which is how several activations' defaults for one role name
737    /// merge.
738    pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
739    where
740        I: IntoIterator<Item = S>,
741        S: AsRef<str>,
742    {
743        let name = RoleName::new(role);
744        let mut set = match self.roles.remove(&name) {
745            Some(GrantSet::Listed(s)) => s,
746            Some(GrantSet::All) => {
747                self.roles.insert(name, GrantSet::All);
748                return Ok(self);
749            }
750            None => BTreeSet::new(),
751        };
752        let mut all = name.as_str() == ADMIN;
753        for entry in entries {
754            let e = entry.as_ref().trim();
755            if e.contains('.') {
756                set.insert(Grant::new(e));
757                continue;
758            }
759            if e == ADMIN {
760                all = true;
761                continue;
762            }
763            match self.roles.get(&RoleName::new(e)) {
764                Some(GrantSet::All) => all = true,
765                Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
766                None => {
767                    return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
768                }
769            }
770        }
771        self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
772        Ok(self)
773    }
774
775    /// Replace `role`'s grants outright (an admin's edit: the store wins).
776    pub fn set(&mut self, role: &str, grants: GrantSet) {
777        self.roles.insert(RoleName::new(role), grants);
778    }
779
780    /// A table from already-flat lists (`role → [grant, …]`), as a schema's
781    /// `roles` carries them; lists for one role name merge.
782    pub fn from_lists<'a, I, G>(lists: I) -> Self
783    where
784        I: IntoIterator<Item = (&'a str, G)>,
785        G: IntoIterator,
786        G::Item: AsRef<str>,
787    {
788        let mut table = Self::new();
789        for (role, grants) in lists {
790            let name = RoleName::new(role);
791            let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
792            match table.roles.entry(name) {
793                std::collections::btree_map::Entry::Occupied(mut o) => {
794                    if let GrantSet::Listed(s) = o.get_mut() {
795                        s.extend(grants);
796                    }
797                }
798                std::collections::btree_map::Entry::Vacant(v) => {
799                    v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
800                }
801            }
802        }
803        table
804    }
805}
806
807impl Roles for RoleTable {
808    fn grants(&self, role: &RoleName) -> Option<GrantSet> {
809        if role.as_str() == ADMIN {
810            return Some(GrantSet::All);
811        }
812        self.roles.get(role).cloned()
813    }
814
815    fn names(&self) -> Vec<RoleName> {
816        self.roles.keys().cloned().collect()
817    }
818}
819
820// ---------------------------------------------------------------------------
821// Refusal
822// ---------------------------------------------------------------------------
823
824/// Why the gate refused a call.
825#[derive(Debug, Clone, PartialEq, Eq)]
826pub enum Refusal {
827    /// No principal: only `public` methods are reachable anonymously.
828    Unauthenticated,
829    /// The caller does not hold `grant` on `scope` (within its ceiling).
830    MissingGrant {
831        /// The grant the call needed.
832        grant: Grant,
833        /// Where it was needed: the target's innermost scope, or `*` for a
834        /// method without a target (held anywhere would have done).
835        scope: ScopeRef,
836        /// The roles that list the grant ([`ADMIN`] last).
837        roles: Vec<RoleName>,
838        /// Where the caller does hold it (within its ceiling).
839        held_on: Vec<ScopeRef>,
840    },
841    /// AUTH-11: the caller signed in, but that sign-in no longer stands
842    /// (signed out, expired, revoked) — it proves no one.
843    Ended {
844        /// Why, in words for the caller ("you have signed out: sign in
845        /// again").
846        reason: String,
847    },
848}
849
850impl fmt::Display for Refusal {
851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
852        match self {
853            Self::Unauthenticated => f.write_str("sign in first"),
854            Self::Ended { reason } => f.write_str(reason),
855            Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
856        }
857    }
858}
859
860impl std::error::Error for Refusal {}
861
862// ---------------------------------------------------------------------------
863// Reach
864// ---------------------------------------------------------------------------
865
866/// Where a call may act: the scopes the caller holds the method's grant on
867/// (within its ceiling), handed to the method beside `auth`. A read without a
868/// target (`list`, `watch`) answers only from these.
869///
870/// A reach is **live** when it came from a gate: [`Reach::allows`] and
871/// [`Reach::current`] ask the gate again, as memberships, roles and the
872/// ceiling stand *now* — so a stream checks each event (IDENTITY-37: a role
873/// revoked reaches an open stream at its next event). A service without a gate
874/// hands every method [`Reach::everywhere`], which allows everything.
875#[derive(Clone)]
876pub struct Reach {
877    /// PERF.115-49: borrowed for the two constant answers (everywhere,
878    /// nowhere), so a service without a gate allocates nothing for them.
879    held_on: std::borrow::Cow<'static, [ScopeRef]>,
880    live: Option<Live>,
881}
882
883#[derive(Clone)]
884struct Live {
885    gate: Gate,
886    caller: Option<AuthContext>,
887    grant: Grant,
888    /// KEEL-31: the reach of a method that acts on the whole service — asked
889    /// again by [`Gate::check_everywhere`], so it lasts only while the grant
890    /// is held on `*`.
891    everywhere: bool,
892    /// ONE-6: the dispatched call whose door admitted it — set only on a
893    /// whole-service reach [`Gate::check_everywhere_at`] gave, and asked
894    /// again at the same door.
895    call: Option<DispatchedCall>,
896}
897
898impl Live {
899    /// The gate's answer now, by the rule this reach was given by.
900    fn now(&self) -> Result<Reach, Refusal> {
901        self.now_on(None)
902    }
903
904    /// The gate's answer now, for `target` (a whole-service reach ignores
905    /// it, as it always has).
906    fn now_on(&self, target: Option<&str>) -> Result<Reach, Refusal> {
907        match self.everywhere {
908            true => self.gate.everywhere_in(self.caller.as_ref(), &self.grant, self.call.as_ref()),
909            false => self.gate.check_in(self.caller.as_ref(), &self.grant, target),
910        }
911    }
912}
913
914impl fmt::Debug for Reach {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        f.debug_struct("Reach")
917            .field("held_on", &self.held_on)
918            .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
919            .finish()
920    }
921}
922
923impl PartialEq for Reach {
924    /// Two reaches are equal when they hold the same scopes for the same
925    /// grant (the gate behind them is not compared).
926    fn eq(&self, other: &Self) -> bool {
927        self.held_on == other.held_on && self.grant() == other.grant()
928    }
929}
930
931impl Reach {
932    /// Everything — what a method receives on a service without a gate (login
933    /// off), as today.
934    pub fn everywhere() -> Self {
935        static EVERYWHERE: [ScopeRef; 1] = [ScopeRef::Everywhere];
936        Self { held_on: std::borrow::Cow::Borrowed(&EVERYWHERE), live: None }
937    }
938
939    /// RETURNS-47: nothing — the reach of a call made for no one (a child
940    /// under the `anonymous` forward policy, or one whose caller cannot be
941    /// read). Covers and allows nothing, and names no grant.
942    pub fn nowhere() -> Self {
943        Self { held_on: std::borrow::Cow::Borrowed(&[]), live: None }
944    }
945
946    /// Whether the grant is held on `*`. ONE-6: only a real `*` (or
947    /// `self`) — never an address scope, which holds no data.
948    pub fn is_everywhere(&self) -> bool {
949        self.held_on.iter().any(ScopeRef::is_everywhere)
950    }
951
952    /// ONE-6: whether the grant is held for the whole of this call's
953    /// activation — the door: on `*`, or, for a reach
954    /// [`Gate::check_everywhere_at`] gave, on an address scope covering the
955    /// call. Never because of a data scope. An in-method backstop on a
956    /// whole-service method asks this (an `operator on /dyn` holds
957    /// `dyn.connect`'s activation); one that means "holds every data scope"
958    /// asks [`Reach::is_everywhere`], which this never widens. Without a
959    /// gate: true, as `is_everywhere` is.
960    pub fn holds_activation(&self) -> bool {
961        self.is_everywhere() || self.live.as_ref().is_some_and(|l| l.everywhere && l.call.is_some())
962    }
963
964    /// Whether the grant is held nowhere (a `public` method called by a
965    /// caller who holds no role listing it).
966    pub fn is_empty(&self) -> bool {
967        self.held_on.is_empty()
968    }
969
970    /// The scopes the grant is held on; `[*]` when everywhere.
971    pub fn held_on(&self) -> &[ScopeRef] {
972        &self.held_on
973    }
974
975    /// PERF.115-49: the caller this reach was decided for — the context the
976    /// gate was asked about, which it keeps to ask again; `None` for an
977    /// anonymous caller and for a reach no gate made ([`Reach::everywhere`],
978    /// [`Reach::nowhere`]). Lets a holder of the reach read that caller
979    /// rather than keep a second copy of it.
980    pub fn caller(&self) -> Option<&AuthContext> {
981        self.live.as_ref().and_then(|l| l.caller.as_ref())
982    }
983
984    /// The grant this reach is for; `None` on a service without a gate.
985    pub fn grant(&self) -> Option<&Grant> {
986        self.live.as_ref().map(|l| &l.grant)
987    }
988
989    /// POLYGLOT-5: the grants generation of the gate this reach came from
990    /// (BIDIR-8) — a call held open elsewhere (a child service's stream)
991    /// asks [`Reach::current`] again only when it moved. `None` without a
992    /// gate.
993    pub fn generation(&self) -> Option<&GrantsGeneration> {
994        self.live.as_ref().map(|l| l.gate.generation())
995    }
996
997    /// Whether the call may act on `target` — asked of the gate as it
998    /// stands now. Without a gate: always. KEEL-31: a whole-service
999    /// method's reach allows a target only while the grant is held on `*`.
1000    /// ONE-6: a whole-service reach admitted at a door
1001    /// ([`Gate::check_everywhere_at`]) allows a target only while the door
1002    /// still admits *and* the target's data chain does (`*` or a data scope
1003    /// holding the grant) — an address scope never allows data.
1004    pub fn allows(&self, target: &str) -> bool {
1005        match &self.live {
1006            None => self.is_everywhere(),
1007            Some(l) if l.everywhere && l.call.is_none() => l.now().is_ok(),
1008            Some(l) if l.everywhere => match l.now() {
1009                Ok(now) => now.is_everywhere() || l.gate.check_in(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
1010                Err(_) => false,
1011            },
1012            Some(l) => l.now_on(Some(target)).is_ok(),
1013        }
1014    }
1015
1016    /// The reach as it stands now: `None` once the grant is held nowhere (a
1017    /// stream should end). Without a gate: unchanged.
1018    pub fn current(&self) -> Option<Reach> {
1019        match &self.live {
1020            None => Some(self.clone()),
1021            Some(l) => l.now().ok(),
1022        }
1023    }
1024
1025    /// FRAME-5: [`Reach::current`] with the gate's refusal kept — `Err`
1026    /// says why the grant is held nowhere now: [`Refusal::Ended`] when the
1027    /// sign-in no longer stands (signed out, expired, revoked session),
1028    /// [`Refusal::MissingGrant`] when the grants moved away,
1029    /// [`Refusal::Unauthenticated`] when the caller proves no one. A held
1030    /// open call that must say *why* it ends (a watch's typed reason) asks
1031    /// this; one that only needs to know whether asks `current`. Without a
1032    /// gate: unchanged.
1033    pub fn recheck(&self) -> Result<Reach, Refusal> {
1034        match &self.live {
1035            None => Ok(self.clone()),
1036            Some(l) => l.now(),
1037        }
1038    }
1039
1040    /// Whether the reach covers a target whose chain is `chain` (as
1041    /// [`Resolve::chain`] gives it), by this snapshot — no new question to
1042    /// the gate. Prefer [`Reach::allows`] where the answer must be current.
1043    pub fn covers(&self, chain: &[ScopeRef]) -> bool {
1044        self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
1045    }
1046}
1047
1048// ---------------------------------------------------------------------------
1049// Gate
1050// ---------------------------------------------------------------------------
1051
1052/// AUTH-11: whether a signed-in caller's sign-in still stands — the
1053/// service's session table, asked by [`Gate::check`] on every call (and so
1054/// on every [`Reach::allows`] / [`Reach::current`] a stream makes). A
1055/// signed-out or revoked session proves no one, whatever its principal
1056/// holds. Memory only, like the other service traits.
1057pub trait Liveness: Send + Sync {
1058    /// `Err`: why the sign-in no longer stands, in words for the caller.
1059    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
1060}
1061
1062struct GateInner {
1063    memberships: Arc<dyn Memberships>,
1064    roles: Arc<dyn Roles>,
1065    resolve: Arc<dyn Resolve>,
1066    liveness: Option<Arc<dyn Liveness>>,
1067    generation: GrantsGeneration,
1068}
1069
1070/// BIDIR-8: what moved the grants generation ([`Gate::moved`]) — every
1071/// write that could change an answer the gate gave.
1072#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1073pub enum GrantsMove {
1074    /// A membership added.
1075    Grant,
1076    /// A membership removed.
1077    Revoke,
1078    /// A role's grants edited.
1079    RoleEdit,
1080    /// A principal added to a team (it holds the team's grants).
1081    TeamAdd,
1082    /// A principal removed from a team.
1083    TeamRemove,
1084    /// A sign-in ended: signed out, or its session revoked.
1085    SignOut,
1086}
1087
1088/// BIDIR-8 (BIDIR-5's finding): the **grants generation** — a count every
1089/// write that could change one of the gate's answers moves
1090/// ([`GrantsMove`]). It is the gate's: whoever holds an answer across time
1091/// (a duplex call's caller, a watch) records the generation it was decided
1092/// at and asks the gate again only when it has moved — once per move, never
1093/// per item. Cheap to clone (two `Arc`s, one count); a read is one atomic
1094/// load; a move wakes every [`subscribe`](GrantsGeneration::subscribe)r.
1095///
1096/// A service shares one across its gates with [`Gate::with_generation`]
1097/// (menger: the gate in front of its calls, the access layer's and the store's count are
1098/// one).
1099#[derive(Clone)]
1100pub struct GrantsGeneration {
1101    now: Arc<std::sync::atomic::AtomicU64>,
1102    tx: Arc<tokio::sync::watch::Sender<u64>>,
1103}
1104
1105impl fmt::Debug for GrantsGeneration {
1106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107        f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
1108    }
1109}
1110
1111impl Default for GrantsGeneration {
1112    fn default() -> Self {
1113        Self::new()
1114    }
1115}
1116
1117/// KEEL-59 (N2): see [`GrantsGeneration::on_move`].
1118static ON_MOVE: std::sync::OnceLock<fn(u64)> = std::sync::OnceLock::new();
1119
1120impl GrantsGeneration {
1121    /// A count at 0.
1122    pub fn new() -> Self {
1123        Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
1124    }
1125
1126    /// Something that could change an answer moved: +1, and every
1127    /// subscriber woken. Answers the generation now.
1128    pub fn bump(&self) -> u64 {
1129        let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
1130        // KEEL-59 (N2): told before any subscriber wakes, in the task that
1131        // moved it, so the call that made the move knows it was its own.
1132        if let Some(told) = ON_MOVE.get() {
1133            told(n);
1134        }
1135        self.tx.send_replace(n);
1136        n
1137    }
1138
1139    /// KEEL-59 (N2): `told(generation)` is called, in the moving task, with
1140    /// every generation a [`bump`](Self::bump) makes — before anything
1141    /// subscribed to it wakes. Set once per process (plexus-core sets it,
1142    /// so the call whose own write moved the grants is not ended by that
1143    /// move); a later call is ignored.
1144    pub fn on_move(told: fn(u64)) {
1145        let _ = ON_MOVE.set(told);
1146    }
1147
1148    /// [`bump`](Self::bump), naming what moved (for the reader; the count
1149    /// is one either way).
1150    pub fn moved(&self, why: GrantsMove) -> u64 {
1151        let _ = why;
1152        self.bump()
1153    }
1154
1155    /// The generation now (one atomic load).
1156    pub fn current(&self) -> u64 {
1157        self.now.load(std::sync::atomic::Ordering::Acquire)
1158    }
1159
1160    /// At least `n` — a service that counted before it shared this handle
1161    /// carries its count over. Never back: a smaller `n` changes nothing.
1162    pub fn raise_to(&self, n: u64) {
1163        let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
1164        if n > was {
1165            self.tx.send_replace(self.current());
1166        }
1167    }
1168
1169    /// What wakes a holder when the generation moves.
1170    pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
1171        self.tx.subscribe()
1172    }
1173}
1174
1175/// The one rule in front of every call: the method's grant, held through a
1176/// role on the target's scope, within the session's ceiling. Default deny.
1177/// Cheap to clone (one `Arc`); cheap to ask (memory only), so a stream may
1178/// ask per event.
1179#[derive(Clone)]
1180pub struct Gate {
1181    inner: Arc<GateInner>,
1182}
1183
1184impl fmt::Debug for Gate {
1185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186        f.write_str("Gate")
1187    }
1188}
1189
1190impl Gate {
1191    /// A gate over a service's memberships, roles and resolver.
1192    pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
1193        Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
1194    }
1195
1196    /// BIDIR-8: this gate, counting its moves in `generation` — the
1197    /// service's one ([`GrantsGeneration`]), shared by every gate it builds.
1198    /// Without it a gate counts alone, from 0.
1199    pub fn with_generation(self, generation: GrantsGeneration) -> Self {
1200        let i = &self.inner;
1201        Self {
1202            inner: Arc::new(GateInner {
1203                memberships: i.memberships.clone(),
1204                roles: i.roles.clone(),
1205                resolve: i.resolve.clone(),
1206                liveness: i.liveness.clone(),
1207                generation,
1208            }),
1209        }
1210    }
1211
1212    /// BIDIR-8: the grants generation this gate's answers are decided at.
1213    pub fn generation(&self) -> &GrantsGeneration {
1214        &self.inner.generation
1215    }
1216
1217    /// BIDIR-8: a write that could change this gate's answers happened
1218    /// (the service wrote it — the gate keeps no memberships of its own):
1219    /// the generation moves once. Answers the generation now.
1220    pub fn moved(&self, why: GrantsMove) -> u64 {
1221        self.inner.generation.moved(why)
1222    }
1223
1224    /// AUTH-11: this gate, asking `liveness` whether a caller's sign-in
1225    /// still stands before every check. Without it the gate still refuses
1226    /// a caller past its `expires_at` stamp ([`AuthContext::expired`]).
1227    pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
1228        let i = &self.inner;
1229        Self {
1230            inner: Arc::new(GateInner {
1231                memberships: i.memberships.clone(),
1232                roles: i.roles.clone(),
1233                resolve: i.resolve.clone(),
1234                liveness: Some(liveness),
1235                generation: i.generation.clone(),
1236            }),
1237        }
1238    }
1239
1240    /// AUTH-11: whether `caller`'s sign-in still stands: not past its
1241    /// `expires_at`, and live by the service's [`Liveness`]. An anonymous
1242    /// context has no sign-in to end: `Ok`.
1243    pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
1244        if caller.principal().is_none() {
1245            return Ok(());
1246        }
1247        self.alive_named(caller)
1248    }
1249
1250    /// [`Gate::alive`] for a caller whose principal was just read (PERF.115-49:
1251    /// [`Gate::check`] has it from [`Gate::caller_of`], and does not parse it
1252    /// again).
1253    fn alive_named(&self, caller: &AuthContext) -> Result<(), String> {
1254        if caller.expired() {
1255            return Err("your sign-in has expired: sign in again".into());
1256        }
1257        match &self.inner.liveness {
1258            Some(l) => l.alive(caller),
1259            None => Ok(()),
1260        }
1261    }
1262
1263    /// Whether `role` lists `grant` ([`ADMIN`] lists every grant).
1264    pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
1265        role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
1266    }
1267
1268    /// The roles that list `grant`, [`ADMIN`] last.
1269    pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
1270        let mut out: Vec<RoleName> = self
1271            .inner
1272            .roles
1273            .names()
1274            .into_iter()
1275            .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
1276            .collect();
1277        out.push(RoleName::new(ADMIN));
1278        out
1279    }
1280
1281    /// Whether a ceiling entry allows `grant`.
1282    fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
1283        match entry {
1284            RoleOrGrant::Grant(g) => g == grant,
1285            RoleOrGrant::Role(r) => self.lists(r, grant),
1286        }
1287    }
1288
1289    /// The caller's principal and ceiling layers; `None` when anonymous. An
1290    /// unreadable ceiling becomes one empty layer — it allows nothing.
1291    fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
1292        let ctx = caller?;
1293        let principal = ctx.principal()?;
1294        let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
1295        Some((principal, layers))
1296    }
1297
1298    /// ONE-6: what the service's [`Resolve`] says of `name`, with every
1299    /// scope that is not the service's own dropped — an address, or the
1300    /// reserved `self`. The gate owns addresses: a resolver's answer can
1301    /// never put one in a chain. Dropping only narrows — the chain loses a
1302    /// scope and gains none — and a chain is otherwise read as before, so a
1303    /// caller holding `*` is answered as it always was even when the
1304    /// target's own value begins with `/` (a resolver that echoes its
1305    /// target, as plexus-login's does).
1306    fn chain_of(&self, name: &str) -> Option<Vec<ScopeRef>> {
1307        let mut chain = self.inner.resolve.chain(name)?;
1308        chain.retain(|s| s.is_everywhere() || s.is_data());
1309        Some(chain)
1310    }
1311
1312    /// ONE-6 (F1): the address of the door being asked about, in a check
1313    /// of `grant` — the dispatched call's, and only when `grant` is the
1314    /// grant that call dispatches to. Any other grant is asked as if no call
1315    /// were told. The pair is compared whole, as the dispatcher built it;
1316    /// never a grant's name against a path.
1317    fn address_for<'c>(call: Option<&'c DispatchedCall>, grant: &Grant) -> Option<&'c CallAddress> {
1318        call.filter(|c| c.grant() == grant).map(DispatchedCall::at)
1319    }
1320
1321    /// **ONE-6, the rule for data** (owner, 2026-11-11: "activation and
1322    /// data scopes are separate"): what a held scope (a membership's, a
1323    /// ceiling entry's) stands for among the data scopes a call is decided
1324    /// on and a reach holds. `*` is `*`; a data scope is itself; an address
1325    /// scope — and the reserved `self` held raw — is nothing. An address
1326    /// scope never stands for data.
1327    fn as_data(scope: &ScopeRef) -> Option<&ScopeRef> {
1328        (scope.is_everywhere() || scope.is_data()).then_some(scope)
1329    }
1330
1331    /// **ONE-6, the rule for the door**: whether a held scope opens the
1332    /// door of the call at `at` — `*`, or an address scope covering it. A
1333    /// data scope never does (KEEL-31).
1334    fn opens(scope: &ScopeRef, at: &CallAddress) -> bool {
1335        scope.is_everywhere() || (scope.is_address() && scope.covers_address(at))
1336    }
1337
1338    /// Whether `inner` lies within `outer` (or is it). Both are data
1339    /// scopes or `*` ([`Gate::as_data`]); anything else is within nothing.
1340    fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
1341        if outer.is_everywhere() {
1342            return true;
1343        }
1344        if !inner.is_data() || !outer.is_data() {
1345            return false;
1346        }
1347        if inner == outer {
1348            return true;
1349        }
1350        match inner {
1351            ScopeRef::Named(name) => self.chain_of(name).is_some_and(|c| c.contains(outer)),
1352            ScopeRef::Everywhere => false,
1353        }
1354    }
1355
1356    /// The scopes both `a` and `b` reach: where one lies within the other,
1357    /// the inner one.
1358    fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
1359        if a.iter().any(ScopeRef::is_everywhere) {
1360            return b;
1361        }
1362        if b.iter().any(ScopeRef::is_everywhere) {
1363            return a;
1364        }
1365        let mut out = BTreeSet::new();
1366        for x in &a {
1367            for y in &b {
1368                if self.within(x, y) {
1369                    out.insert(x.clone());
1370                } else if self.within(y, x) {
1371                    out.insert(y.clone());
1372                }
1373            }
1374        }
1375        out.into_iter().collect()
1376    }
1377
1378    /// Collapse to `[*]` when `*` is among them; dedupe, ordered.
1379    fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
1380        let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
1381        if set.contains(&ScopeRef::Everywhere) {
1382            vec![ScopeRef::Everywhere]
1383        } else {
1384            set.into_iter().collect()
1385        }
1386    }
1387
1388    fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
1389        let held = self.inner.memberships.held(principal);
1390        self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
1391    }
1392
1393    /// Where `held` (role, scope pairs) holds `grant` within `layers`,
1394    /// among data scopes ([`Gate::as_data`]): what [`Gate::held_on`]
1395    /// answers from the memberships and [`Gate::held_on_by`] from a
1396    /// [`Fingerprint`] — one rule.
1397    fn held_on_in<'a>(
1398        &self,
1399        held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
1400        layers: &[Ceiling],
1401        grant: &Grant,
1402    ) -> Vec<ScopeRef> {
1403        let mut acc = Self::normal(
1404            held.filter(|(role, _)| self.lists(role, grant)).filter_map(|(_, scope)| Self::as_data(scope).cloned()),
1405        );
1406        for layer in layers {
1407            if acc.is_empty() {
1408                break;
1409            }
1410            let allowed = Self::normal(
1411                layer
1412                    .0
1413                    .iter()
1414                    .filter(|(rg, _)| self.entry_allows(rg, grant))
1415                    .filter_map(|(_, s)| Self::as_data(s).cloned()),
1416            );
1417            acc = self.meet(acc, allowed);
1418        }
1419        acc
1420    }
1421
1422    /// Where the caller holds `grant`, within its ceiling: `[*]` when
1423    /// everywhere, `[]` when nowhere (and for an anonymous caller). What a
1424    /// method without a target answers from. ONE-6: data scopes only — an
1425    /// address scope is never among them.
1426    pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
1427        match Self::caller_of(Some(caller)) {
1428            Some((p, layers)) => self.held_on_for(&p, &layers, grant),
1429            None => Vec::new(),
1430        }
1431    }
1432
1433    /// PERF-15: what this gate's answers about `caller` read, besides the
1434    /// grants generation — its principal's memberships and its session's
1435    /// ceiling ([`Fingerprint`]); `None` when it is anonymous. The
1436    /// memberships are read now, from memory.
1437    pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
1438        let (principal, layers) = Self::caller_of(Some(caller))?;
1439        let mut held: Vec<(RoleName, ScopeRef)> =
1440            self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
1441        held.sort();
1442        held.dedup();
1443        Some(Fingerprint { held, layers })
1444    }
1445
1446    /// PERF-15: [`Gate::held_on`] for whoever has `who` — read from the
1447    /// fingerprint instead of the memberships, by the same rule, so a view
1448    /// built from it is exactly the one built from any caller it was taken
1449    /// of.
1450    pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
1451        self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
1452    }
1453
1454    /// Allowed when the grant is listed by a role held on a scope in the
1455    /// target's chain — or anywhere, for a call with no target — and every
1456    /// ceiling layer allows it the same way. The [`Reach`] is live (it asks
1457    /// this gate again on [`Reach::allows`] / [`Reach::current`]).
1458    ///
1459    /// AUTH-11: first, the caller's sign-in must still stand
1460    /// ([`Gate::alive`]) — a signed-out session holds nothing, so a socket
1461    /// that signed out cannot go on to call `auth.grant`.
1462    ///
1463    /// ONE-6: decided on data scopes and `*` alone. An address scope never
1464    /// counts here — not for a target, and not as "held anywhere" for a
1465    /// read with no target: it opens a door ([`Gate::check_everywhere_at`])
1466    /// and holds no data. A caller holding a grant only on addresses is
1467    /// refused here, as one holding it nowhere is.
1468    pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
1469        self.check_in(caller, grant, target)
1470    }
1471
1472    /// The data check.
1473    fn check_in(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
1474        let Some((principal, layers)) = Self::caller_of(caller) else {
1475            return Err(Refusal::Unauthenticated);
1476        };
1477        if let Some(ctx) = caller {
1478            self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
1479        }
1480        let held_on = self.held_on_for(&principal, &layers, grant);
1481        let (allowed, scope) = match target {
1482            None => (!held_on.is_empty(), ScopeRef::Everywhere),
1483            Some(t) => match self.chain_of(t) {
1484                None => (false, ScopeRef::named(t)),
1485                Some(chain) => {
1486                    let in_chain =
1487                        |s: &ScopeRef| Self::as_data(s).is_some_and(|d| d.is_everywhere() || chain.contains(d));
1488                    let by_membership = self
1489                        .inner
1490                        .memberships
1491                        .held(&principal)
1492                        .iter()
1493                        .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
1494                    let by_ceiling = layers
1495                        .iter()
1496                        .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
1497                    let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
1498                    (by_membership && by_ceiling, scope)
1499                }
1500            },
1501        };
1502        if allowed {
1503            Ok(Reach { held_on: held_on.into(), live: Some(self.live(caller, grant, None, false)) })
1504        } else {
1505            Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
1506        }
1507    }
1508
1509    /// The live part of a reach: this gate, the caller, the grant, the rule
1510    /// it is asked again by, and the door's call (if a door admitted it).
1511    fn live(&self, caller: Option<&AuthContext>, grant: &Grant, call: Option<&DispatchedCall>, everywhere: bool) -> Live {
1512        Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere, call: call.cloned() }
1513    }
1514
1515    /// KEEL-31: the check for a method that acts on the whole service (it
1516    /// names no target because its target is everything: a key rotated, a
1517    /// process spawned, a peer connected). Allowed only where the grant is
1518    /// held on `*` — by a role held on `*` that lists it, and every ceiling
1519    /// layer allowing it on `*` — never because it is held on some scope. A
1520    /// scoped `admin`, or a session minted `admin@X`, is refused, naming `*`.
1521    /// The reach is `[*]` and stays live by this same rule.
1522    pub fn check_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
1523        self.everywhere_in(caller, grant, None)
1524    }
1525
1526    /// ONE-6: **the door** — [`Gate::check_everywhere`] of the dispatched
1527    /// `call`, for its own grant: may this caller make this call at this
1528    /// address. Admitted where a role listing the grant is held on a scope
1529    /// that opens the call's door — `*` (`self`), the activation's address
1530    /// (`/dyn` for `dyn.connect`), the method's own (`/dyn.connect`), or a
1531    /// subtree above it (`/dyn.*`) — and every ceiling layer has an entry
1532    /// allowing the grant on such a scope. A data scope never opens a door
1533    /// (KEEL-31), nor an address that does not cover the call (`/ui`,
1534    /// `/dyn.peer.shop.*`). A refusal names the activation's address.
1535    ///
1536    /// The reach says what was admitted apart from what data is held:
1537    /// [`Reach::holds_activation`] is true; [`Reach::held_on`] is the
1538    /// caller's data scopes for the grant, as [`Gate::check`] reads them —
1539    /// `[*]` for a holder of `*`, `[]` for one who holds only addresses — so
1540    /// [`Reach::is_everywhere`] is true only for a real `*`. It stays live
1541    /// by this same rule, at the same door.
1542    pub fn check_everywhere_at(&self, caller: Option<&AuthContext>, call: &DispatchedCall) -> Result<Reach, Refusal> {
1543        self.everywhere_in(caller, call.grant(), Some(call))
1544    }
1545
1546    /// The whole-service check of `grant`: on `*` alone (no call), or at
1547    /// the dispatched call's door.
1548    fn everywhere_in(
1549        &self,
1550        caller: Option<&AuthContext>,
1551        grant: &Grant,
1552        call: Option<&DispatchedCall>,
1553    ) -> Result<Reach, Refusal> {
1554        match Self::address_for(call, grant) {
1555            None => self.on_everywhere(caller, grant),
1556            Some(at) => self.at_door(caller, grant, call, at),
1557        }
1558    }
1559
1560    /// KEEL-31's rule, as it was: the grant held on `*`.
1561    fn on_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
1562        let reach = match self.check_in(caller, grant, None) {
1563            Ok(reach) => reach,
1564            Err(Refusal::MissingGrant { grant, roles, held_on, .. }) => {
1565                return Err(Refusal::MissingGrant { grant, scope: ScopeRef::Everywhere, roles, held_on })
1566            }
1567            Err(other) => return Err(other),
1568        };
1569        if !reach.is_everywhere() {
1570            return Err(Refusal::MissingGrant {
1571                grant: grant.clone(),
1572                scope: ScopeRef::Everywhere,
1573                roles: self.roles_listing(grant),
1574                held_on: reach.held_on.into_owned(),
1575            });
1576        }
1577        // PERF.115-49: the check's own live part (this gate, this caller,
1578        // this grant), kept by the rule of `*` — not a second copy of each.
1579        let live = reach.live.map(|live| Live { everywhere: true, ..live });
1580        Ok(Reach { held_on: reach.held_on, live })
1581    }
1582
1583    /// The door of the call at `at`: a membership opening it lists the
1584    /// grant, and every ceiling layer has an entry opening it that allows
1585    /// the grant ([`Gate::opens`]).
1586    fn at_door(
1587        &self,
1588        caller: Option<&AuthContext>,
1589        grant: &Grant,
1590        call: Option<&DispatchedCall>,
1591        at: &CallAddress,
1592    ) -> Result<Reach, Refusal> {
1593        let Some((principal, layers)) = Self::caller_of(caller) else {
1594            return Err(Refusal::Unauthenticated);
1595        };
1596        if let Some(ctx) = caller {
1597            self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
1598        }
1599        let held = self.inner.memberships.held(&principal);
1600        let by_membership = held.iter().any(|m| Self::opens(&m.scope, at) && self.lists(&m.role, grant));
1601        let by_ceiling =
1602            layers.iter().all(|layer| layer.0.iter().any(|(rg, s)| Self::opens(s, at) && self.entry_allows(rg, grant)));
1603        let held_on = self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), &layers, grant);
1604        if by_membership && by_ceiling {
1605            Ok(Reach { held_on: held_on.into(), live: Some(self.live(caller, grant, call, true)) })
1606        } else {
1607            Err(Refusal::MissingGrant {
1608                grant: grant.clone(),
1609                scope: ScopeRef::named(format!("/{}", at.activation())),
1610                roles: self.roles_listing(grant),
1611                held_on,
1612            })
1613        }
1614    }
1615
1616    /// The reach of a `public` method: what [`Gate::check`] would allow
1617    /// without a target, or an empty (still live) reach when the caller holds
1618    /// the grant nowhere or is anonymous. A public method is never refused.
1619    pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
1620        self.check_in(caller, grant, None).unwrap_or_else(|_| Reach {
1621            held_on: std::borrow::Cow::Borrowed(&[]),
1622            live: Some(self.live(caller, grant, None, false)),
1623        })
1624    }
1625}
1626
1627// ---------------------------------------------------------------------------
1628// Tests — the gate's decision table
1629// ---------------------------------------------------------------------------
1630
1631#[cfg(test)]
1632mod tests {
1633    use super::*;
1634    use std::sync::Mutex;
1635
1636    const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1637    const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
1638
1639    /// Memberships as a mutable table, so a test can revoke one.
1640    #[derive(Default)]
1641    struct Members(Mutex<Vec<Membership>>);
1642    impl Members {
1643        fn grant(&self, who: &str, role: &str, scope: &str) {
1644            self.0.lock().unwrap().push(Membership {
1645                principal: who.parse().unwrap(),
1646                role: RoleName::new(role),
1647                scope: ScopeRef::parse(scope),
1648            });
1649        }
1650        fn revoke_all(&self) {
1651            self.0.lock().unwrap().clear();
1652        }
1653    }
1654    impl Memberships for Members {
1655        fn held(&self, who: &Principal) -> Vec<Membership> {
1656            self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
1657        }
1658    }
1659
1660    /// menger-shaped: a ticket `CODE-n` lives in itself, then `CODE`;
1661    /// MENGER and IDENTITY are disjoint, both hosted under PLEXUS.
1662    struct Shortcodes;
1663    impl Resolve for Shortcodes {
1664        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
1665            let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
1666            let mut chain = Vec::new();
1667            if target.contains('-') {
1668                chain.push(ScopeRef::named(target));
1669            }
1670            match code {
1671                "MENGER" | "IDENTITY" => {
1672                    chain.push(ScopeRef::named(code));
1673                    chain.push(ScopeRef::named("PLEXUS"));
1674                }
1675                "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
1676                _ => return None,
1677            }
1678            chain.push(ScopeRef::Everywhere);
1679            Some(chain)
1680        }
1681    }
1682
1683    fn roles() -> RoleTable {
1684        RoleTable::new()
1685            .define("viewer", ["tickets.get", "tickets.list"])
1686            .unwrap()
1687            .define("editor", ["viewer", "tickets.set_status"])
1688            .unwrap()
1689    }
1690
1691    fn gate(members: &Arc<Members>) -> Gate {
1692        Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
1693    }
1694
1695    fn who(p: &str) -> AuthContext {
1696        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
1697    }
1698
1699    fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
1700        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
1701    }
1702
1703    fn g(s: &str) -> Grant {
1704        Grant::new(s)
1705    }
1706
1707    #[test]
1708    fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
1709        let m = Arc::new(Members::default());
1710        m.grant(ADA, "editor", "*");
1711        m.grant(BOB, "admin", "MENGER");
1712        let gate = gate(&m);
1713        let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
1714        assert_eq!(
1715            err,
1716            Refusal::MissingGrant {
1717                grant: g("members.grant"),
1718                scope: ScopeRef::named("MENGER-1"),
1719                roles: vec![RoleName::new("admin")],
1720                held_on: vec![],
1721            }
1722        );
1723        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
1724        // admin on MENGER is not admin on IDENTITY.
1725        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
1726    }
1727
1728    #[test]
1729    fn held_on_a_scope_allows_targets_in_its_chain_only() {
1730        let m = Arc::new(Members::default());
1731        m.grant(ADA, "editor", "MENGER");
1732        let gate = gate(&m);
1733        let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
1734        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
1735        let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
1736        assert_eq!(
1737            err,
1738            Refusal::MissingGrant {
1739                grant: g("tickets.set_status"),
1740                scope: ScopeRef::named("IDENTITY-1"),
1741                roles: vec![RoleName::new("editor"), RoleName::new("admin")],
1742                held_on: vec![ScopeRef::named("MENGER")],
1743            }
1744        );
1745        assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
1746        // A target nothing resolves is refused.
1747        assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
1748    }
1749
1750    #[test]
1751    fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
1752        let m = Arc::new(Members::default());
1753        m.grant(ADA, "viewer", "*");
1754        m.grant(ADA, "viewer", "MENGER");
1755        let gate = gate(&m);
1756        let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
1757        assert!(reach.is_everywhere());
1758        assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
1759        assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
1760        // viewer does not list set_status, wherever it is held.
1761        assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
1762    }
1763
1764    #[test]
1765    fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
1766        let m = Arc::new(Members::default());
1767        m.grant(ADA, "viewer", "MENGER");
1768        m.grant(ADA, "viewer", "IDENTITY");
1769        let gate = gate(&m);
1770        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1771        assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
1772        assert!(reach.allows("MENGER-4"));
1773        assert!(!reach.allows("PLEXUS-1"));
1774        let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
1775        assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
1776    }
1777
1778    #[test]
1779    fn a_ceiling_narrows_the_membership() {
1780        let m = Arc::new(Members::default());
1781        m.grant(ADA, "editor", "MENGER");
1782        let gate = gate(&m);
1783        let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1784        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
1785        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
1786        // The reach of a target-less read is the meet: MENGER-12, inside MENGER.
1787        let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
1788        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
1789        // A grant-entry ceiling: only tickets.get, anywhere the membership allows.
1790        let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
1791        assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
1792        let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
1793        assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
1794        // Two layers: both must allow.
1795        let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
1796        assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
1797        assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
1798        // A ceiling never widens: editor@IDENTITY grants nothing there.
1799        let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
1800        assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
1801        // An unreadable ceiling allows nothing.
1802        let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
1803        assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
1804    }
1805
1806    #[test]
1807    fn role_inclusion_flattens_and_must_name_an_earlier_role() {
1808        let r = roles();
1809        let editor = r.grants(&RoleName::new("editor")).unwrap();
1810        assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
1811        let viewer = r.grants(&RoleName::new("viewer")).unwrap();
1812        assert!(!viewer.contains(&g("tickets.set_status")));
1813        assert_eq!(
1814            RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
1815            RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
1816        );
1817        // admin is built in: holds every grant, whatever the table says.
1818        assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
1819        // from_lists merges one role's lists from several activations.
1820        let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
1821        let e = merged.grants(&RoleName::new("editor")).unwrap();
1822        assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
1823    }
1824
1825    #[test]
1826    fn anonymous_is_unauthenticated() {
1827        let m = Arc::new(Members::default());
1828        let gate = gate(&m);
1829        assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
1830        assert_eq!(
1831            gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
1832            Refusal::Unauthenticated
1833        );
1834        // A public method's reach for an anonymous caller: empty, never refused.
1835        assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
1836    }
1837
1838    #[test]
1839    fn a_live_reach_follows_grants_as_they_stand() {
1840        let m = Arc::new(Members::default());
1841        m.grant(ADA, "viewer", "MENGER");
1842        let gate = gate(&m);
1843        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1844        assert!(reach.allows("MENGER-1"));
1845        assert!(reach.current().is_some());
1846        m.revoke_all();
1847        assert!(!reach.allows("MENGER-1"));
1848        assert!(reach.current().is_none());
1849        // Without a gate, everything.
1850        assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
1851    }
1852
1853    #[test]
1854    fn scope_refs_and_ceilings_round_trip() {
1855        assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
1856        assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
1857        let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
1858        assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
1859        assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
1860        assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
1861        assert!(Ceiling::parse(["editor"]).is_err());
1862    }
1863
1864    /// A session table with one switch: signed out or not.
1865    #[derive(Default)]
1866    struct Switch(std::sync::atomic::AtomicBool);
1867    impl Liveness for Switch {
1868        fn alive(&self, _: &AuthContext) -> Result<(), String> {
1869            if self.0.load(std::sync::atomic::Ordering::SeqCst) {
1870                Err("you have signed out: sign in again".into())
1871            } else {
1872                Ok(())
1873            }
1874        }
1875    }
1876
1877    /// AUTH-11: a signed-out session holds nothing — not even admin on `*`
1878    /// — and a live reach taken before the sign-out ends with it.
1879    #[test]
1880    fn a_session_that_ended_holds_nothing() {
1881        let m = Arc::new(Members::default());
1882        m.grant(ADA, "admin", "*");
1883        let out = Arc::new(Switch::default());
1884        let gate = gate(&m).with_liveness(out.clone());
1885        let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
1886        assert!(reach.allows("MENGER-1"));
1887        out.0.store(true, std::sync::atomic::Ordering::SeqCst);
1888        let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
1889        assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
1890        assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
1891        assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
1892        assert!(reach.current().is_none());
1893        assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
1894        // Anonymous is not "ended": still plain Unauthenticated.
1895        assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
1896    }
1897
1898    /// AUTH-11: past its `expires_at` stamp, a sign-in is over even with
1899    /// no liveness hook.
1900    #[test]
1901    fn an_expired_sign_in_holds_nothing() {
1902        let m = Arc::new(Members::default());
1903        m.grant(ADA, "admin", "*");
1904        let gate = gate(&m);
1905        let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
1906        assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
1907        let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
1908        assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
1909    }
1910
1911    /// PERF-15: a fingerprint is what the gate's answers read of a caller —
1912    /// equal for two principals holding the same, different when a
1913    /// membership or the ceiling differs, `None` when anonymous — and
1914    /// `held_on_by` answers from it exactly what `held_on` answers.
1915    #[test]
1916    fn a_fingerprint_is_what_the_answers_read() {
1917        let m = Arc::new(Members::default());
1918        m.grant(ADA, "viewer", "IDENTITY");
1919        m.grant(ADA, "editor", "MENGER");
1920        m.grant(BOB, "editor", "MENGER");
1921        m.grant(BOB, "viewer", "IDENTITY");
1922        m.grant(BOB, "editor", "MENGER");
1923        let gate = gate(&m);
1924        let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
1925        assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
1926        assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
1927        let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1928        let narrowed = gate.fingerprint(&narrow).unwrap();
1929        assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
1930        let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
1931        assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
1932        for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
1933            for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
1934                assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
1935            }
1936        }
1937        assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
1938        m.revoke_all();
1939        assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
1940    }
1941
1942    /// KEEL-31 (the review's probe, KEEL-28): `admin` held on one ticket is
1943    /// admitted to a method with no target by [`Gate::check`] — held
1944    /// somewhere — and refused by [`Gate::check_everywhere`], naming `*`; so
1945    /// is a session minted narrower than `*`. Held on `*`, it is allowed,
1946    /// and its reach stays live by the same rule.
1947    #[test]
1948    fn a_whole_service_method_needs_its_grant_on_everywhere() {
1949        let m = Arc::new(Members::default());
1950        m.grant(ADA, "admin", "MENGER-5");
1951        m.grant(BOB, "admin", "*");
1952        let gate = gate(&m);
1953        let grow = g("dyn.grow");
1954        assert_eq!(gate.check(Some(&who(ADA)), &grow, None).unwrap().held_on(), [ScopeRef::named("MENGER-5")]);
1955        match gate.check_everywhere(Some(&who(ADA)), &grow) {
1956            Err(Refusal::MissingGrant { scope, held_on, .. }) => {
1957                assert_eq!(scope, ScopeRef::Everywhere);
1958                assert_eq!(held_on, [ScopeRef::named("MENGER-5")]);
1959            }
1960            other => panic!("a scoped admin: {other:?}"),
1961        }
1962        let reach = gate.check_everywhere(Some(&who(BOB)), &grow).unwrap();
1963        assert!(reach.is_everywhere());
1964        for ceiling in [serde_json::json!(["admin@MENGER-5"]), serde_json::json!(["viewer@*"]), serde_json::json!("admin@*")] {
1965            let capped = with_ceiling(BOB, ceiling.clone());
1966            assert!(gate.check_everywhere(Some(&capped), &grow).is_err(), "ceiling {ceiling}");
1967        }
1968        assert!(gate.check_everywhere(Some(&with_ceiling(BOB, serde_json::json!(["dyn.grow@*"]))), &grow).is_ok());
1969        assert!(gate.check_everywhere(Some(&with_ceiling(ADA, serde_json::json!(["admin@*"]))), &grow).is_err(), "a ceiling never widens");
1970        assert_eq!(gate.check_everywhere(None, &grow).err(), Some(Refusal::Unauthenticated));
1971        // Live: narrowed to a scope while it runs, the reach is gone.
1972        m.revoke_all();
1973        m.grant(BOB, "admin", "MENGER");
1974        assert!(reach.current().is_none());
1975        assert!(reach.recheck().is_err());
1976        assert!(!reach.allows("MENGER-1"));
1977    }
1978
1979    /// ONE-6 (review F1): inside the gate too, a dispatched call opens its
1980    /// door only for the grant it dispatches to — any other grant asked
1981    /// "at" it is decided as told no call (on `*` alone).
1982    #[test]
1983    fn a_dispatched_call_opens_its_door_for_its_own_grant_only() {
1984        let m = Arc::new(Members::default());
1985        m.grant(ADA, "admin", "/dyn.connect");
1986        let gate = gate(&m);
1987        let connect = DispatchedCall::new(CallAddress::new("dyn", "connect").unwrap(), g("dyn.connect"));
1988        assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.connect"), Some(&connect)).is_ok());
1989        assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.disconnect"), Some(&connect)).is_err());
1990        assert!(gate.everywhere_in(Some(&who(ADA)), &g("auth.grant"), Some(&connect)).is_err());
1991    }
1992}