Skip to main content

plexus_core/plexus/
auth_activation.rs

1//! AUTH-5 — **the `auth` activation**: one auth surface in every gated
2//! Plexus hub. Sign in, sign up, who am I, what does this need, and the
3//! admin's roles and memberships.
4//!
5//! A service turns login on with [`DynamicHub::with_auth`], handing it an
6//! [`AuthSetup`]: what only the service knows —
7//!
8//! - an [`AuthBackend`]: its providers, its login flows (the browser start
9//!   and finish, a password, a session minted on a key-proved or signed-in
10//!   connection), signup and the waiting list, logout;
11//! - an editable [`RoleStore`] (role → grants: defaults from the
12//!   activations' `roles(...)`, an admin's edits win) and
13//!   [`MembershipStore`] (who holds which role where);
14//! - its scope [`Resolve`]r.
15//!
16//! The hub builds the [`Gate`] from those same stores (so an edit reaches
17//! the next call and the next view), mounts this activation, and the rest
18//! the activation answers itself from the gate and the stores:
19//!
20//! | method | who | answers |
21//! |---|---|---|
22//! | `providers`, `login`, `signup` | anyone (`public`) | the door |
23//! | `whoami`, `logout`, `requires` | any signed-in caller (whatever its roles or ceiling) | `whoami`, `logged_out`, `requires` |
24//! | `roles` | whoever holds `auth.roles` (admin) | one `role` per role |
25//! | `role_set` | admin on `*` | the role as it now stands |
26//! | `grant`, `revoke` | whoever holds them on the scope (`target = "scope"`; KEEL-54: checked again in the method, on the scope written) | `granted` / `revoked` |
27//! | `waiting` | admin on `*` | one `waiting` per principal asking |
28//!
29//! A refusal the gate makes is AUTH-2's typed error item; one this
30//! activation makes (`role_set`, `waiting` short of `*`) is an in-band
31//! `{type: "error", error_kind: "forbidden", grant, scope, roles,
32//! held_on, message}` event — the same fields.
33//!
34//! [`super::auth_memory`] has a reference in-memory implementation of every
35//! trait here, for tests and as a starting point.
36//!
37//! [`DynamicHub::with_auth`]: super::DynamicHub::with_auth
38
39use std::collections::{BTreeMap, BTreeSet};
40use std::fmt;
41use std::sync::{Arc, RwLock};
42
43use async_stream::stream;
44use async_trait::async_trait;
45use futures::Stream;
46use schemars::JsonSchema;
47use serde::{Deserialize, Serialize};
48
49use plexus_auth_core::grants::{
50    Ceiling, Gate, Grant, GrantSet, GrantsGeneration, GrantsMove, Liveness, Membership, Memberships, Reach, Resolve, Roles, ScopeRef, ADMIN,
51};
52use plexus_auth_core::identity::Principal;
53use plexus_auth_core::RoleName;
54
55use super::auth::AuthContext;
56use super::auth_params as param;
57use super::schema::{MethodRole, PluginSchema};
58
59/// The grants every signed-in caller reaches, whatever its roles or its
60/// session's ceiling: asking who it is, signing out, and asking what a
61/// method needs. Never anonymously.
62pub const SIGNED_IN_GRANTS: [&str; 3] = ["auth.whoami", "auth.logout", "auth.requires"];
63
64// ===========================================================================
65// Wire types
66// ===========================================================================
67
68/// How a provider signs someone in.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70#[serde(rename_all = "snake_case")]
71pub enum ProviderKind {
72    /// A person, through the browser (OIDC, WorkOS, …): `login {flow:
73    /// {browser}}` then `{code}`.
74    Browser,
75    /// A username and password (`login {flow: {password}}`).
76    Password,
77    /// An agent's key: a proof at the upgrade, then `login {flow: {session}}`.
78    Key,
79}
80
81/// One way in this server offers.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
83pub struct Provider {
84    /// Its name (`workos`, `plexus-idp`, `key`).
85    pub name: String,
86    pub kind: ProviderKind,
87    /// A human label, when it has one.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub label: Option<String>,
90}
91
92/// How a caller signs in (`auth.login {flow: …}`). On the wire, externally
93/// tagged: `{"browser": {"redirect": …}}`, `{"code": {"code", "state"}}`,
94/// `{"password": {"username", "password"}}`, `{"session": {"ttl_secs",
95/// "ceiling"}}`.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "snake_case")]
98pub enum LoginFlow {
99    /// A person, from a client with a browser: answered with the URL to
100    /// open (`login_url {url, state}`); the browser comes back to
101    /// `redirect` (a loopback address the client listens on) with a
102    /// one-time code.
103    Browser { redirect: String },
104    /// The browser came back: trade the code for a session. Single-use,
105    /// bound to the state.
106    Code { code: String, state: String },
107    /// Where a provider takes a password.
108    Password { username: String, password: String },
109    /// A session on a connection that is already someone — a key proof at
110    /// the upgrade (IDENTITY-40), or a session — bounded by `ceiling`
111    /// (`role@SCOPE` / `grant@SCOPE` entries) and lasting `ttl_secs`.
112    Session {
113        #[serde(default)]
114        ttl_secs: Option<u64>,
115        #[serde(default)]
116        ceiling: Option<Vec<String>>,
117    },
118}
119
120/// A session a backend minted.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
122pub struct Session {
123    /// The bearer token (`Authorization: Bearer …`, or the service's cookie).
124    pub token: String,
125    /// Who it is: `key:…`, `oidc:workos/user_…`, `idp:…`.
126    pub principal: String,
127    /// The agent id, for an agent's session.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub agent: Option<String>,
130    /// A display name, when the provider gives one.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub name: Option<String>,
133    /// Unix seconds.
134    pub expires_at: i64,
135    /// The session's ceiling, `role@SCOPE` / `grant@SCOPE`; empty: none.
136    #[serde(default)]
137    pub ceiling: Vec<String>,
138}
139
140/// Someone asking for access.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142pub struct Waiting {
143    pub principal: String,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub name: Option<String>,
146    /// The way they came in (`key`, `workos`, …).
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub provider: Option<String>,
149    /// Unix seconds: when they first asked.
150    pub since: i64,
151}
152
153/// What `login` answers.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum LoginAnswer {
156    /// Open this URL; the browser comes back with a code for this state.
157    LoginUrl { url: String, state: String },
158    Session(Session),
159}
160
161/// What `signup` answers when the backend decides it.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum SignupAnswer {
164    Waiting(Waiting),
165    LoginUrl { url: String, state: String },
166    Session(Session),
167}
168
169/// Why a backend would not: said to the caller as an in-band error.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct AuthFailure(pub String);
172
173impl AuthFailure {
174    pub fn new(message: impl Into<String>) -> Self {
175        Self(message.into())
176    }
177}
178
179impl fmt::Display for AuthFailure {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        f.write_str(&self.0)
182    }
183}
184
185impl std::error::Error for AuthFailure {}
186
187/// Why a store would not write.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct StoreError(pub String);
190
191impl StoreError {
192    pub fn new(message: impl Into<String>) -> Self {
193        Self(message.into())
194    }
195}
196
197impl fmt::Display for StoreError {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.write_str(&self.0)
200    }
201}
202
203impl std::error::Error for StoreError {}
204
205/// A membership as `whoami` says it.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
207pub struct MembershipEntry {
208    pub role: String,
209    pub scope: String,
210}
211
212/// Every event the `auth` activation sends (`{"type": …}`).
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
214#[serde(tag = "type", rename_all = "snake_case")]
215pub enum AuthEvent {
216    /// `providers`: one way in.
217    Provider {
218        name: String,
219        kind: ProviderKind,
220        #[serde(default, skip_serializing_if = "Option::is_none")]
221        label: Option<String>,
222    },
223    /// `login {browser}` / `signup`: open this URL.
224    LoginUrl { url: String, state: String },
225    /// `login`: signed in.
226    Session {
227        token: String,
228        principal: String,
229        #[serde(default, skip_serializing_if = "Option::is_none")]
230        agent: Option<String>,
231        #[serde(default, skip_serializing_if = "Option::is_none")]
232        name: Option<String>,
233        expires_at: i64,
234        #[serde(default)]
235        ceiling: Vec<String>,
236    },
237    /// `signup` (asking for access) / `waiting` (an admin's list).
238    Waiting {
239        principal: String,
240        #[serde(default, skip_serializing_if = "Option::is_none")]
241        name: Option<String>,
242        #[serde(default, skip_serializing_if = "Option::is_none")]
243        provider: Option<String>,
244        since: i64,
245    },
246    /// `whoami`.
247    Whoami {
248        principal: String,
249        #[serde(default, skip_serializing_if = "Option::is_none")]
250        name: Option<String>,
251        #[serde(default, skip_serializing_if = "Option::is_none")]
252        agent: Option<String>,
253        memberships: Vec<MembershipEntry>,
254        ceiling: Vec<String>,
255    },
256    /// `logout`.
257    LoggedOut { principal: String },
258    /// `requires {method}`: its grant, its target, the roles that list it.
259    Requires {
260        method: String,
261        grant: String,
262        #[serde(default, skip_serializing_if = "Option::is_none")]
263        target: Option<String>,
264        roles: Vec<String>,
265        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
266        public: bool,
267    },
268    /// `roles` / `role_set`: a role and its grants (`all`: every grant —
269    /// admin).
270    Role {
271        role: String,
272        grants: Vec<String>,
273        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
274        all: bool,
275    },
276    /// `grant`.
277    Granted { principal: String, role: String, scope: String },
278    /// `revoke`: the roles it removed there.
279    Revoked { principal: String, scope: String, roles: Vec<String> },
280    /// Anything refused or failed. A refusal (`error_kind: "forbidden"`)
281    /// carries AUTH-2's fields.
282    Error {
283        message: String,
284        #[serde(default, skip_serializing_if = "Option::is_none")]
285        error_kind: Option<String>,
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        grant: Option<String>,
288        #[serde(default, skip_serializing_if = "Option::is_none")]
289        scope: Option<String>,
290        #[serde(default, skip_serializing_if = "Option::is_none")]
291        roles: Option<Vec<String>>,
292        #[serde(default, skip_serializing_if = "Option::is_none")]
293        held_on: Option<Vec<String>>,
294    },
295}
296
297impl AuthEvent {
298    fn error(message: impl Into<String>) -> Self {
299        Self::Error { message: message.into(), error_kind: None, grant: None, scope: None, roles: None, held_on: None }
300    }
301}
302
303impl From<Session> for AuthEvent {
304    fn from(s: Session) -> Self {
305        Self::Session {
306            token: s.token,
307            principal: s.principal,
308            agent: s.agent,
309            name: s.name,
310            expires_at: s.expires_at,
311            ceiling: s.ceiling,
312        }
313    }
314}
315
316impl From<Waiting> for AuthEvent {
317    fn from(w: Waiting) -> Self {
318        Self::Waiting { principal: w.principal, name: w.name, provider: w.provider, since: w.since }
319    }
320}
321
322// ===========================================================================
323// What a service supplies
324// ===========================================================================
325
326/// What only the service knows about signing in. Async: a backend may talk
327/// to its identity provider. (The gate's own questions — [`Memberships`],
328/// [`Roles`], [`Resolve`] — stay synchronous and from memory.)
329#[async_trait]
330pub trait AuthBackend: Send + Sync + 'static {
331    /// The ways in this server offers (`auth.providers`).
332    fn providers(&self) -> Vec<Provider>;
333
334    /// Sign in by `flow` (`auth.login`). `caller` is the connection's
335    /// identity, if any: a [`LoginFlow::Session`] needs one (a key proof at
336    /// the upgrade, or a session) and must not widen it — the new
337    /// session's ceiling lies within the caller's (layer it). The browser
338    /// flow's start and finish, the code's single use and expiry, and the
339    /// session's minting are the backend's.
340    async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
341
342    /// `auth.signup` where the activation's own rule does not decide it:
343    /// an anonymous caller (create an account — or refuse: sign in first),
344    /// or one who already holds a membership. (A signed-in caller holding
345    /// none is put on the waiting list by [`AuthBackend::ask_access`].)
346    async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
347
348    /// Put a signed-in caller who holds no membership on the waiting list
349    /// (asking again keeps the first `since`).
350    async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
351
352    /// Everyone who has asked for access. The activation shows an admin
353    /// only those still holding no membership.
354    fn waiting(&self) -> Vec<Waiting>;
355
356    /// End the caller's session (`auth.logout`). A connection with no
357    /// session to end (a bare key proof) is not an error.
358    async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
359
360    /// AUTH-11: whether a signed-in caller's sign-in still stands — its
361    /// session not signed out, revoked or expired. The gate asks it before
362    /// every call it decides (`auth.*` included), so a sign-in that ended
363    /// holds nothing from its next call on. `Err`: why not, in words for
364    /// the caller. Memory only: it is asked on every call. (The gate
365    /// refuses a caller past its `expires_at` stamp before asking.)
366    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
367}
368
369/// AUTH-11: the backend as the gate's [`Liveness`].
370struct BackendLiveness(Arc<dyn AuthBackend>);
371
372impl Liveness for BackendLiveness {
373    fn alive(&self, caller: &AuthContext) -> Result<(), String> {
374        self.0.alive(caller)
375    }
376}
377
378/// [`Roles`] an admin can edit (`auth.role_set`). The gate reads the same
379/// store, so an edit reaches the next call and the next view.
380#[async_trait]
381pub trait RoleStore: Roles + 'static {
382    /// Replace `role`'s grants. Never called for [`ADMIN`].
383    async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
384}
385
386/// [`Memberships`] an admin can edit (`auth.grant`, `auth.revoke`).
387#[async_trait]
388pub trait MembershipStore: Memberships + 'static {
389    /// Add a membership (holding it already is not an error).
390    async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
391
392    /// Remove `principal`'s memberships on `scope` — the one role named, or
393    /// every role there. Answers the roles removed.
394    async fn revoke(
395        &self,
396        principal: &Principal,
397        role: Option<&RoleName>,
398        scope: &ScopeRef,
399    ) -> Result<Vec<RoleName>, StoreError>;
400}
401
402/// What [`DynamicHub::with_auth`](super::DynamicHub::with_auth) takes.
403#[derive(Clone)]
404pub struct AuthSetup {
405    pub backend: Arc<dyn AuthBackend>,
406    pub roles: Arc<dyn RoleStore>,
407    pub memberships: Arc<dyn MembershipStore>,
408    pub resolve: Arc<dyn Resolve>,
409    /// BIDIR-8: the service's grants generation, when it shares one between
410    /// this service's call gate and gates of its own (menger's access
411    /// layer); else the call gate counts alone. `auth.grant`, `auth.revoke`,
412    /// `auth.role_set` and `auth.logout` move it.
413    pub generation: Option<GrantsGeneration>,
414}
415
416impl AuthSetup {
417    pub fn new(
418        backend: Arc<dyn AuthBackend>,
419        roles: Arc<dyn RoleStore>,
420        memberships: Arc<dyn MembershipStore>,
421        resolve: Arc<dyn Resolve>,
422    ) -> Self {
423        Self { backend, roles, memberships, resolve, generation: None }
424    }
425
426    /// BIDIR-8: the service's call gate counts its moves in `generation`, shared with
427    /// whatever else the service decides by it.
428    pub fn with_generation(mut self, generation: GrantsGeneration) -> Self {
429        self.generation = Some(generation);
430        self
431    }
432}
433
434// ===========================================================================
435// The catalog: what each method requires
436// ===========================================================================
437
438/// What one method requires, as `auth.requires` says it.
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct Requirement {
441    pub grant: String,
442    pub target: Option<String>,
443    pub public: bool,
444}
445
446/// Every method of the hub by grant — fed as activations register — and
447/// (NEST-5) the hub's slots, through which a literal path finds its slot's
448/// requirement.
449#[derive(Clone, Default)]
450pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>, Arc<RwLock<super::slots::Slots>>);
451
452impl Catalog {
453    /// Add an activation's methods (not its auto-generated `schema`, which
454    /// is introspection, nor its child routes).
455    pub(crate) fn add(&self, schema: &PluginSchema) {
456        self.1.write().unwrap_or_else(|p| p.into_inner()).add(schema);
457        let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
458        for m in &schema.methods {
459            if m.is_auto_schema() || !matches!(m.role, MethodRole::Rpc) {
460                continue;
461            }
462            let grant = m.grant_or(&schema.namespace);
463            map.insert(grant.clone(), Requirement { grant, target: m.target.clone(), public: m.public });
464        }
465    }
466
467    /// NEST-15: forget every method under the top-level name `ns` (a peer the
468    /// service no longer serves).
469    pub(crate) fn remove_under(&self, ns: &str) {
470        let prefix = format!("{ns}.");
471        self.0.write().unwrap_or_else(|p| p.into_inner()).retain(|k, _| !k.starts_with(&prefix));
472    }
473
474    /// NEST-5: an untyped slot (`solar.{planet}`), granted whole.
475    pub(crate) fn add_slots(&self, untyped: &[String]) {
476        let mut slots = self.1.write().unwrap_or_else(|p| p.into_inner());
477        let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
478        for path in untyped {
479            slots.add_untyped(path);
480            map.insert(path.clone(), Requirement { grant: path.clone(), target: None, public: false });
481        }
482    }
483
484    /// The requirement of `method` (`tickets.set_status`); NEST-5: through
485    /// a slot, the slot's (`solar.earth.info` → `solar.{planet}.info`).
486    pub fn get(&self, method: &str) -> Option<Requirement> {
487        let map = self.0.read().unwrap_or_else(|p| p.into_inner());
488        if let Some(r) = map.get(method) {
489            return Some(r.clone());
490        }
491        let key = self.1.read().unwrap_or_else(|p| p.into_inner()).resolve(method)?;
492        map.get(&key).cloned()
493    }
494
495    /// Whether `grant` names a method of this hub.
496    pub fn knows(&self, grant: &str) -> bool {
497        self.0.read().unwrap_or_else(|p| p.into_inner()).contains_key(grant)
498    }
499}
500
501// ===========================================================================
502// The activation
503// ===========================================================================
504
505/// The `auth` activation. Mounted by
506/// [`DynamicHub::with_auth`](super::DynamicHub::with_auth); see the module
507/// docs.
508#[derive(Clone)]
509pub struct AuthActivation {
510    inner: Arc<AuthInner>,
511}
512
513struct AuthInner {
514    backend: Arc<dyn AuthBackend>,
515    roles: Arc<dyn RoleStore>,
516    memberships: Arc<dyn MembershipStore>,
517    gate: Gate,
518    catalog: Catalog,
519}
520
521/// The service's resolver, and `*` → `[*]` (a membership on everywhere is
522/// granted and revoked like any other scope).
523struct WithEverywhere(Arc<dyn Resolve>);
524
525impl Resolve for WithEverywhere {
526    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
527        // ONE-7: `self` is `*`; an address scope (`/dyn`, `/dyn.peer.shop.*`)
528        // is the gate's, not the service's — granting or revoking one is
529        // decided on `*` alone (an address scope holds no data, so no data
530        // scope lies above it).
531        if matches!(target.trim(), "*" | "self") || target.trim().starts_with('/') {
532            return Some(vec![ScopeRef::Everywhere]);
533        }
534        self.0.chain(target)
535    }
536}
537
538/// ONE-7: a session's ceiling entries (`role@SCOPE`, `grant@SCOPE`), each
539/// scope written through [`ScopeRef::parse_checked`] — `self` is `*`, a
540/// malformed address refused, naming the rule.
541fn checked_ceiling(entries: &[String]) -> Result<Vec<String>, String> {
542    entries
543        .iter()
544        .map(|e| {
545            let (left, scope) = e.trim().split_once('@').ok_or_else(|| format!("`{e}` is not role@SCOPE or grant@SCOPE"))?;
546            let scope = ScopeRef::parse_checked(scope.trim()).map_err(|e| e.to_string())?;
547            Ok(format!("{}@{scope}", left.trim()))
548        })
549        .collect()
550}
551
552impl AuthActivation {
553    /// The activation and the gate over the same stores.
554    pub(crate) fn mount(setup: AuthSetup, catalog: Catalog) -> (Self, Gate) {
555        let memberships: Arc<dyn Memberships> = setup.memberships.clone();
556        let roles: Arc<dyn Roles> = setup.roles.clone();
557        let mut gate = Gate::new(memberships, roles, Arc::new(WithEverywhere(setup.resolve)))
558            .with_liveness(Arc::new(BackendLiveness(setup.backend.clone())));
559        if let Some(generation) = setup.generation {
560            gate = gate.with_generation(generation);
561        }
562        let auth = Self {
563            inner: Arc::new(AuthInner {
564                backend: setup.backend,
565                roles: setup.roles,
566                memberships: setup.memberships,
567                gate: gate.clone(),
568                catalog,
569            }),
570        };
571        (auth, gate)
572    }
573}
574
575fn principal_of(ctx: &AuthContext) -> Option<Principal> {
576    ctx.principal()
577}
578
579/// KEEL-31: the auth activation's methods that act on the whole service —
580/// marked `everywhere`, which [`super::DynamicHub::with_auth`] checks.
581pub const EVERYWHERE: &[&str] = &["role_set", "waiting"];
582
583fn meta(ctx: &AuthContext, key: &str) -> Option<String> {
584    ctx.get_metadata_string(key).filter(|s| !s.is_empty())
585}
586
587/// An in-band refusal: `grant` is needed on `*`.
588fn needs_everywhere(gate: &Gate, grant: &str, reach: &Reach) -> AuthEvent {
589    let g = Grant::new(grant);
590    AuthEvent::Error {
591        message: format!("needs {grant} on *"),
592        error_kind: Some("forbidden".into()),
593        grant: Some(grant.into()),
594        scope: Some("*".into()),
595        roles: Some(gate.roles_listing(&g).iter().map(|r| r.as_str().to_string()).collect()),
596        held_on: Some(reach.held_on().iter().map(|s| s.as_str().to_string()).collect()),
597    }
598}
599
600/// KEEL-54: `auth.grant` / `auth.revoke`'s own check, which no route
601/// replaces — the call's reach is for `grant` itself (the gate decided this
602/// method, not another spelling of it), and the caller holds `grant` on
603/// every scope the call writes (`scopes`: as said, and as kept), within its
604/// session's ceiling. Admin of `KILN` grants within `KILN`; on `*` only an
605/// admin on `*` does.
606fn holds_where_written(gate: &Gate, auth: &AuthContext, reach: &Reach, grant: &str, scopes: &[&str]) -> Result<(), Box<AuthEvent>> {
607    let g = Grant::new(grant);
608    if reach.grant() != Some(&g) {
609        return Err(Box::new(needs_on(gate, grant, "*", reach.held_on().iter().map(|s| s.as_str().to_string()).collect())));
610    }
611    for scope in scopes {
612        match gate.check(Some(auth), &g, Some(scope)) {
613            Ok(_) => {}
614            Err(plexus_auth_core::grants::Refusal::MissingGrant { scope, held_on, .. }) => {
615                return Err(Box::new(needs_on(gate, grant, scope.as_str(), held_on.iter().map(|s| s.as_str().to_string()).collect())));
616            }
617            Err(plexus_auth_core::grants::Refusal::Ended { reason }) => return Err(Box::new(AuthEvent::error(reason))),
618            Err(plexus_auth_core::grants::Refusal::Unauthenticated) => return Err(Box::new(AuthEvent::error("sign in first"))),
619        }
620    }
621    Ok(())
622}
623
624/// An in-band refusal: `grant` is needed on `scope`.
625fn needs_on(gate: &Gate, grant: &str, scope: &str, held_on: Vec<String>) -> AuthEvent {
626    AuthEvent::Error {
627        message: format!("needs {grant} on {scope}"),
628        error_kind: Some("forbidden".into()),
629        grant: Some(grant.into()),
630        scope: Some(scope.into()),
631        roles: Some(gate.roles_listing(&Grant::new(grant)).iter().map(|r| r.as_str().to_string()).collect()),
632        held_on: Some(held_on),
633    }
634}
635
636fn role_event(role: &RoleName, grants: Option<GrantSet>) -> AuthEvent {
637    match grants {
638        Some(GrantSet::All) => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: true },
639        Some(GrantSet::Listed(set)) => AuthEvent::Role {
640            role: role.as_str().into(),
641            grants: set.iter().map(|g| g.as_str().to_string()).collect(),
642            all: false,
643        },
644        None => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: false },
645    }
646}
647
648#[plexus_macros::activation(
649    version = "1.0.0",
650    description = "Sign in, who am I, what does this need",
651    roles(member = ["whoami", "logout", "requires"]),
652    // MACRO-12: every parameter is a type (`super::auth_params`); a bare
653    // string parameter does not compile here.
654    typed_params,
655)]
656impl AuthActivation {
657    /// The ways in this server offers.
658    #[plexus_macros::method(public, group = "sign in", description = "The ways in this server offers")]
659    async fn providers(&self) -> impl Stream<Item = AuthEvent> + Send + 'static {
660        let providers = self.inner.backend.providers();
661        stream! {
662            for p in providers {
663                yield AuthEvent::Provider { name: p.name, kind: p.kind, label: p.label };
664            }
665        }
666    }
667
668    /// Sign in — a person through the browser (`{browser: {redirect}}`,
669    /// then `{code: {code, state}}`), a password, or an agent's session on
670    /// a key-proved connection (`{session: {ttl_secs, ceiling}}`).
671    #[plexus_macros::method(
672        public,
673        group = "sign in",
674        description = "Sign in — a person through the browser, an agent with its key",
675        params(flow = "browser {redirect} | code {code, state} | password {username, password} | session {ttl_secs?, ceiling?}")
676    )]
677    async fn login(&self, auth: Option<&AuthContext>, flow: LoginFlow) -> impl Stream<Item = AuthEvent> + Send + 'static {
678        let inner = self.inner.clone();
679        let caller = auth.cloned();
680        let mut flow = flow;
681        stream! {
682            if let LoginFlow::Session { ceiling: Some(entries), .. } = &mut flow {
683                if let Err(e) = Ceiling::parse(entries.iter()) {
684                    yield AuthEvent::error(format!("ceiling: {e}"));
685                    return;
686                }
687                // ONE-7: a ceiling minted is written through `parse_checked`:
688                // `self` is `*`, a malformed address is refused.
689                match checked_ceiling(entries) {
690                    Ok(checked) => *entries = checked,
691                    Err(e) => {
692                        yield AuthEvent::error(format!("ceiling: {e}"));
693                        return;
694                    }
695                }
696            }
697            if matches!(flow, LoginFlow::Session { .. }) && caller.as_ref().and_then(principal_of).is_none() {
698                yield AuthEvent::error("a session needs a connection that is someone: a key proof at the upgrade, or a session");
699                return;
700            }
701            match inner.backend.login(caller.as_ref(), flow).await {
702                Ok(LoginAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
703                Ok(LoginAnswer::Session(s)) => yield s.into(),
704                Err(e) => yield AuthEvent::error(e.0),
705            }
706        }
707    }
708
709    /// Create an account, or ask for access: a signed-in caller holding no
710    /// membership of its own ([`Memberships::own_held`]) joins the waiting
711    /// list for an admin.
712    #[plexus_macros::method(
713        public,
714        group = "sign in",
715        description = "Create an account, or ask for access",
716        params(via = "The provider to sign up through, where the server offers several")
717    )]
718    async fn signup(&self, auth: Option<&AuthContext>, via: Option<param::ProviderName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
719        let inner = self.inner.clone();
720        let caller = auth.cloned();
721        let via = via.map(param::ProviderName::into_string);
722        stream! {
723            let holds_none = caller
724                .as_ref()
725                .and_then(principal_of)
726                .map(|p| inner.memberships.own_held(&p).is_empty());
727            let answer = match (holds_none, caller.as_ref()) {
728                (Some(true), Some(ctx)) => inner.backend.ask_access(ctx, via).await.map(SignupAnswer::Waiting),
729                _ => inner.backend.signup(caller.as_ref(), via).await,
730            };
731            match answer {
732                Ok(SignupAnswer::Waiting(w)) => yield w.into(),
733                Ok(SignupAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
734                Ok(SignupAnswer::Session(s)) => yield s.into(),
735                Err(e) => yield AuthEvent::error(e.0),
736            }
737        }
738    }
739
740    /// Who this connection is: principal, name, the roles it holds where,
741    /// and its session's ceiling.
742    #[plexus_macros::method(group = "you", description = "Who you are: principal, roles held where, ceiling")]
743    async fn whoami(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
744        let inner = self.inner.clone();
745        let ctx = auth.clone();
746        stream! {
747            let Some(p) = principal_of(&ctx) else {
748                yield AuthEvent::error("sign in first");
749                return;
750            };
751            let memberships = inner
752                .memberships
753                .held(&p)
754                .into_iter()
755                .map(|m| MembershipEntry { role: m.role.as_str().into(), scope: m.scope.as_str().into() })
756                .collect();
757            let ceiling = Ceiling::layers_of(&ctx)
758                .map(|layers| layers.iter().flat_map(|l| l.text()).collect())
759                .unwrap_or_default();
760            yield AuthEvent::Whoami {
761                principal: p.to_string(),
762                name: meta(&ctx, "name"),
763                agent: meta(&ctx, "agent"),
764                memberships,
765                ceiling,
766            };
767        }
768    }
769
770    /// End this session.
771    #[plexus_macros::method(group = "you", description = "Sign out: end this session")]
772    async fn logout(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
773        let inner = self.inner.clone();
774        let ctx = auth.clone();
775        stream! {
776            let principal = principal_of(&ctx).map(|p| p.to_string()).unwrap_or_default();
777            // BIDIR-8: a sign-in ended; whatever holds it verifies again.
778            let moving = MovesOnDrop::armed(&inner.gate, GrantsMove::SignOut);
779            let out = inner.backend.logout(&ctx).await;
780            moving.done(out.is_ok());
781            match out {
782                Ok(()) => {
783                    yield AuthEvent::LoggedOut { principal }
784                }
785                Err(e) => yield AuthEvent::error(e.0),
786            }
787        }
788    }
789
790    /// What a method needs: its grant, its target and the roles that list
791    /// it.
792    #[plexus_macros::method(
793        group = "you",
794        description = "What a method needs: its grant, target, and the roles that list it",
795        params(method = "The method, as <activation>.<method>: tickets.set_status"),
796        example(note = "what changing a ticket's status needs", params = r#"{"method": "tickets.set_status"}"#)
797    )]
798    async fn requires(&self, auth: &AuthContext, method: param::MethodPath) -> impl Stream<Item = AuthEvent> + Send + 'static {
799        let _ = auth;
800        let inner = self.inner.clone();
801        stream! {
802            match inner.catalog.get(method.as_str()) {
803                None => yield AuthEvent::error(format!("no method {method} here")),
804                Some(req) => {
805                    let roles = inner.gate.roles_listing(&Grant::new(req.grant.clone()));
806                    yield AuthEvent::Requires {
807                        method: method.into_string(),
808                        grant: req.grant,
809                        target: req.target,
810                        roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
811                        public: req.public,
812                    };
813                }
814            }
815        }
816    }
817
818    /// Every role and the grants it lists (admin: every grant).
819    #[plexus_macros::method(group = "admin", description = "Every role and the grants it lists")]
820    async fn roles(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
821        let _ = auth;
822        let inner = self.inner.clone();
823        stream! {
824            let admin = RoleName::new(ADMIN);
825            yield role_event(&admin, Some(GrantSet::All));
826            let names: BTreeSet<RoleName> = inner.roles.names().into_iter().filter(|r| r.as_str() != ADMIN).collect();
827            for r in names {
828                let grants = inner.roles.grants(&r);
829                yield role_event(&r, grants);
830            }
831        }
832    }
833
834    /// Set a role's grants (admin on `*`). Each entry a grant
835    /// (`tickets.get`) or an existing role whose grants it includes.
836    #[plexus_macros::method(
837        everywhere,
838        group = "admin",
839        description = "Set a role's grants (admin on *)",
840        params(role = "The role (not admin)", grants = "Grants (tickets.get) or roles to include")
841    )]
842    async fn role_set(&self, auth: &AuthContext, reach: Reach, role: param::RoleName, grants: Vec<param::GrantName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
843        let _ = auth;
844        let inner = self.inner.clone();
845        stream! {
846            // KEEL-31: the gate decides it on `*` (`everywhere`); kept as a
847            // backstop for a reach handed in by hand. ONE-7: or at its door
848            // (`admin on /auth`, whose role lists it — the owner's "a role
849            // which gives a grant for /auth is admin").
850            if !reach.holds_activation() || reach.grant().is_some_and(|g| g.as_str() != "auth.role_set") {
851                yield needs_everywhere(&inner.gate, "auth.role_set", &reach);
852                return;
853            }
854            // The name's shape (one word, no `.` or `@`) is `param::RoleName`'s,
855            // refused as InvalidParams before this runs.
856            if role.as_str() == ADMIN {
857                yield AuthEvent::error("admin holds every grant; it is not edited");
858                return;
859            }
860            let mut set: BTreeSet<Grant> = BTreeSet::new();
861            for entry in grants.iter() {
862                let entry = entry.as_str();
863                if entry.contains('.') {
864                    if !inner.catalog.knows(entry) {
865                        yield AuthEvent::error(format!("no method {entry} here"));
866                        return;
867                    }
868                    set.insert(Grant::new(entry));
869                } else {
870                    match inner.roles.grants(&RoleName::new(entry)) {
871                        Some(GrantSet::Listed(included)) => set.extend(included),
872                        Some(GrantSet::All) => {
873                            yield AuthEvent::error(format!("{entry} holds every grant; a role cannot include it"));
874                            return;
875                        }
876                        None => {
877                            yield AuthEvent::error(format!("no role {entry} to include"));
878                            return;
879                        }
880                    }
881                }
882            }
883            let name = role.role();
884            let moving = MovesOnDrop::armed(&inner.gate, GrantsMove::RoleEdit);
885            let set = inner.roles.set(&name, GrantSet::Listed(set)).await;
886            moving.done(set.is_ok());
887            if let Err(e) = set {
888                yield AuthEvent::error(e.0);
889                return;
890            }
891            let now = inner.roles.grants(&name);
892            yield role_event(&name, now);
893        }
894    }
895
896    /// Give `principal` `role` on `scope` (whoever holds `auth.grant` on
897    /// the scope: admin there).
898    #[plexus_macros::method(
899        target = "scope",
900        group = "admin",
901        description = "Give a principal a role on a scope",
902        params(principal = "key:…, oidc:…/…, idp:…", role = "The role", scope = "Where: a scope name, or *"),
903        example(note = "make a person an editor on MENGER", params = r#"{"principal": "oidc:workos/user_01M4", "role": "editor", "scope": "MENGER"}"#),
904        example(note = "make an agent's key an admin everywhere", params = r#"{"principal": "key:ac79e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "role": "admin", "scope": "*"}"#)
905    )]
906    async fn grant(&self, auth: &AuthContext, reach: Reach, principal: param::Principal, role: param::RoleName, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
907        let inner = self.inner.clone();
908        let caller = auth.clone();
909        stream! {
910            let who: Principal = principal.principal();
911            let role_name = role.role();
912            if role_name.as_str() != ADMIN && inner.roles.grants(&role_name).is_none() {
913                yield AuthEvent::error(format!("no role {role} here"));
914                return;
915            }
916            // ONE-7: a scope written goes through `parse_checked` — `self` is
917            // `*`; an address must be well formed, and is any activation's or
918            // peer's (`/dyn`, `/dyn.peer.shop.*`), served now or not: it holds
919            // nothing until a call it covers is dispatched.
920            let scope_ref = match ScopeRef::parse_checked(scope.as_str()) {
921                Ok(s) => s,
922                Err(e) => {
923                    yield AuthEvent::error(format!("scope: {e}"));
924                    return;
925                }
926            };
927            // KEEL-54: held where it is written, whatever routed the call.
928            if let Err(refused) = holds_where_written(&inner.gate, &caller, &reach, "auth.grant", &[scope.as_str(), scope_ref.as_str()]) {
929                yield *refused;
930                return;
931            }
932            let m = Membership { principal: who.clone(), role: role_name.clone(), scope: scope_ref.clone() };
933            match inner.memberships.grant(m).await {
934                Ok(()) => {
935                    inner.gate.moved(GrantsMove::Grant);
936                    yield AuthEvent::Granted {
937                        principal: who.to_string(),
938                        role: role_name.as_str().into(),
939                        scope: scope_ref.as_str().into(),
940                    }
941                }
942                Err(e) => yield AuthEvent::error(e.0),
943            }
944        }
945    }
946
947    /// Take `principal`'s role (or every role) on `scope` away.
948    #[plexus_macros::method(
949        target = "scope",
950        group = "admin",
951        description = "Take a principal's role on a scope away",
952        params(principal = "key:…, oidc:…/…, idp:…", role = "The role; absent: every role there", scope = "Where: a scope name, or *")
953    )]
954    async fn revoke(&self, auth: &AuthContext, reach: Reach, principal: param::Principal, role: Option<param::RoleName>, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
955        let inner = self.inner.clone();
956        let caller = auth.clone();
957        stream! {
958            let who: Principal = principal.principal();
959            // ONE-7: as it is granted (`self` is `*`); a malformed scope stored
960            // before — which holds nothing — is taken away by its text.
961            let scope_ref = ScopeRef::parse_checked(scope.as_str()).unwrap_or_else(|_| scope.scope());
962            // KEEL-54: held where it is taken away, whatever routed the call.
963            if let Err(refused) = holds_where_written(&inner.gate, &caller, &reach, "auth.revoke", &[scope.as_str(), scope_ref.as_str()]) {
964                yield *refused;
965                return;
966            }
967            let role_name = role.as_ref().map(param::RoleName::role);
968            let moving = MovesOnDrop::armed(&inner.gate, GrantsMove::Revoke);
969            let revoked = inner.memberships.revoke(&who, role_name.as_ref(), &scope_ref).await;
970            moving.done(revoked.as_ref().is_ok_and(|r| !r.is_empty()));
971            match revoked {
972                Ok(removed) => {
973                    yield AuthEvent::Revoked {
974                        principal: who.to_string(),
975                        scope: scope_ref.as_str().into(),
976                        roles: removed.iter().map(|r| r.as_str().to_string()).collect(),
977                    }
978                }
979                Err(e) => yield AuthEvent::error(e.0),
980            }
981        }
982    }
983
984    /// Who signed up or asked for access and holds nothing of its own yet
985    /// ([`Memberships::own_held`]; admin on `*`).
986    #[plexus_macros::method(everywhere, group = "admin", description = "Who asked for access and holds nothing yet (admin on *)")]
987    async fn waiting(&self, auth: &AuthContext, reach: Reach) -> impl Stream<Item = AuthEvent> + Send + 'static {
988        let _ = auth;
989        let inner = self.inner.clone();
990        stream! {
991            // KEEL-31: the gate decides it on `*`; kept as a backstop.
992            // ONE-7: or at its door.
993            if !reach.holds_activation() || reach.grant().is_some_and(|g| g.as_str() != "auth.waiting") {
994                yield needs_everywhere(&inner.gate, "auth.waiting", &reach);
995                return;
996            }
997            for w in inner.backend.waiting() {
998                let still = w
999                    .principal
1000                    .parse::<Principal>()
1001                    .map(|p| inner.memberships.own_held(&p).is_empty())
1002                    .unwrap_or(true);
1003                if still {
1004                    yield w.into();
1005                }
1006            }
1007        }
1008    }
1009}
1010
1011#[cfg(test)]
1012mod keel54_body_checks {
1013    //! KEEL-54, layer 4: `auth.grant` and `auth.revoke` check in their
1014    //! bodies — run here with a reach in hand, as whatever route reaches
1015    //! them would hand one, and no gate before them.
1016    use super::super::auth_memory::{MemoryAuthBackend, MemoryMemberships, MemoryRoles};
1017    use super::*;
1018    use crate::plexus::Activation;
1019    use futures::StreamExt;
1020    use plexus_auth_core::grants::{RoleTable, CEILING_KEY};
1021    use serde_json::{json, Value};
1022
1023    const KILN_ADMIN: &str = "key:4b494c4e4b494c4e4b494c4e4b494c4e4b494c4e4b494c4e4b494c4e4b494c4e";
1024    const ADMIN: &str = "key:adadadadadadadadadadadadadadadadadadadadadadadadadadadadadadadad";
1025    const TARGET: &str = "key:7474747474747474747474747474747474747474747474747474747474747474";
1026
1027    struct Kiln;
1028    impl Resolve for Kiln {
1029        fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
1030            Some(vec![ScopeRef::named(t.split('-').next().unwrap_or(t)), ScopeRef::Everywhere])
1031        }
1032    }
1033
1034    fn mounted() -> (AuthActivation, Gate, Arc<MemoryMemberships>) {
1035        let members = Arc::new(MemoryMemberships::new().with(KILN_ADMIN, "admin", "KILN").with(ADMIN, "admin", "*"));
1036        let roles = Arc::new(MemoryRoles::new(RoleTable::from_lists([("viewer", ["auth.whoami"])])));
1037        let setup = AuthSetup::new(Arc::new(MemoryAuthBackend::new("http://x/login")), roles, members.clone(), Arc::new(Kiln));
1038        let (auth, gate) = AuthActivation::mount(setup, Catalog::default());
1039        (auth, gate, members)
1040    }
1041
1042    fn who(p: &str, ceiling: Option<&[&str]>) -> AuthContext {
1043        let meta = ceiling.map_or(Value::Null, |c| json!({ CEILING_KEY: c }));
1044        AuthContext::for_principal(&p.parse().unwrap(), "s", vec![], meta)
1045    }
1046
1047    /// Run `method` as `ctx` under `reach`: the first event it says.
1048    async fn said(auth: &AuthActivation, ctx: &AuthContext, reach: Reach, method: &str, params: Value) -> Value {
1049        let run = async {
1050            let mut stream = Activation::call(auth, method, params, Some(ctx), None).await.expect("dispatched");
1051            stream.next().await.expect("an item")
1052        };
1053        let item = crate::call::scope(crate::call::CallContext::admitted(Some(ctx), reach), run).await;
1054        serde_json::to_value(item).unwrap()["content"].clone()
1055    }
1056
1057    fn everything() -> Value {
1058        json!({ "principal": TARGET, "role": "admin", "scope": "*" })
1059    }
1060
1061    fn raised(members: &MemoryMemberships) -> bool {
1062        members.all().iter().any(|m| m.principal.to_string() == TARGET && m.scope.is_everywhere())
1063    }
1064
1065    /// The probe's shape: the gate admitted the call on some grant held
1066    /// somewhere — the made-up one, or the method's own held on KILN — and
1067    /// the method was reached with that reach.
1068    #[tokio::test]
1069    async fn an_admin_of_one_scope_granting_everything_is_refused_by_the_method_itself() {
1070        let (auth, gate, members) = mounted();
1071        let ctx = who(KILN_ADMIN, None);
1072        for decided in ["vault.anything", "auth.grant"] {
1073            let reach = gate.check(Some(&ctx), &Grant::new(decided), None).unwrap();
1074            let refused = said(&auth, &ctx, reach, "grant", everything()).await;
1075            assert_eq!((refused["type"].as_str(), refused["error_kind"].as_str()), (Some("error"), Some("forbidden")), "{decided}: {refused}");
1076            assert!(!raised(&members), "{decided}");
1077        }
1078        let reach = gate.check(Some(&ctx), &Grant::new("auth.revoke"), Some("KILN")).unwrap();
1079        let refused = said(&auth, &ctx, reach, "revoke", json!({ "principal": ADMIN, "scope": "*" })).await;
1080        assert_eq!(refused["error_kind"], "forbidden", "{refused}");
1081        assert!(members.all().iter().any(|m| m.principal.to_string() == ADMIN), "nothing was taken");
1082        // Within KILN, it grants.
1083        let reach = gate.check(Some(&ctx), &Grant::new("auth.grant"), Some("KILN")).unwrap();
1084        let granted = said(&auth, &ctx, reach, "grant", json!({ "principal": TARGET, "role": "admin", "scope": "KILN" })).await;
1085        assert_eq!(granted["type"], "granted", "{granted}");
1086    }
1087
1088    #[tokio::test]
1089    async fn a_capped_session_is_held_to_its_cap_by_the_method_itself() {
1090        let (auth, gate, members) = mounted();
1091        let ctx = who(ADMIN, Some(&["admin@KILN"]));
1092        let reach = gate.check(Some(&ctx), &Grant::new("auth.grant"), Some("KILN")).unwrap();
1093        let refused = said(&auth, &ctx, reach.clone(), "grant", everything()).await;
1094        assert_eq!(refused["error_kind"], "forbidden", "{refused}");
1095        assert!(!raised(&members));
1096        let granted = said(&auth, &ctx, reach, "grant", json!({ "principal": TARGET, "role": "viewer", "scope": "KILN-3" })).await;
1097        assert_eq!(granted["type"], "granted", "{granted}");
1098    }
1099
1100    /// The admin of everything, with the reach for the method: as before.
1101    #[tokio::test]
1102    async fn the_admin_of_everything_grants_and_revokes_as_before() {
1103        let (auth, gate, members) = mounted();
1104        let ctx = who(ADMIN, None);
1105        let reach = gate.check(Some(&ctx), &Grant::new("auth.grant"), Some("*")).unwrap();
1106        assert_eq!(said(&auth, &ctx, reach, "grant", everything()).await["type"], "granted");
1107        assert!(raised(&members));
1108        let reach = gate.check(Some(&ctx), &Grant::new("auth.revoke"), Some("self")).unwrap();
1109        let revoked = said(&auth, &ctx, reach, "revoke", json!({ "principal": TARGET, "scope": "self" })).await;
1110        assert_eq!(revoked["type"], "revoked", "{revoked}");
1111        assert!(!raised(&members));
1112        // A reach for another grant, even the admin's: not this method's.
1113        let reach = gate.check(Some(&ctx), &Grant::new("auth.revoke"), Some("*")).unwrap();
1114        assert_eq!(said(&auth, &ctx, reach, "grant", everything()).await["error_kind"], "forbidden");
1115        assert!(!raised(&members));
1116    }
1117}
1118
1119/// KEEL-59: a write that narrows what the gate answers (a revoke, a role
1120/// edited, a sign-out) moves the grants generation even when its call is
1121/// ended mid-write — a call is now ended by the server too (its caller's own
1122/// grant revoked) — so a write that landed is never left without the move
1123/// that holds every open call to it. Disarmed when the write said it moved
1124/// nothing.
1125struct MovesOnDrop<'a> {
1126    gate: &'a plexus_auth_core::grants::Gate,
1127    why: Option<GrantsMove>,
1128}
1129
1130impl<'a> MovesOnDrop<'a> {
1131    fn armed(gate: &'a plexus_auth_core::grants::Gate, why: GrantsMove) -> Self {
1132        Self { gate, why: Some(why) }
1133    }
1134
1135    /// The write is over: move now if it changed something, never again.
1136    fn done(mut self, changed: bool) {
1137        if let Some(why) = self.why.take().filter(|_| changed) {
1138            self.gate.moved(why);
1139        }
1140    }
1141}
1142
1143impl Drop for MovesOnDrop<'_> {
1144    fn drop(&mut self) {
1145        if let Some(why) = self.why.take() {
1146            self.gate.moved(why);
1147        }
1148    }
1149}