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"`) | `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, 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::schema::{MethodRole, PluginSchema};
57
58/// The grants every signed-in caller reaches, whatever its roles or its
59/// session's ceiling: asking who it is, signing out, and asking what a
60/// method needs. Never anonymously.
61pub const SIGNED_IN_GRANTS: [&str; 3] = ["auth.whoami", "auth.logout", "auth.requires"];
62
63// ===========================================================================
64// Wire types
65// ===========================================================================
66
67/// How a provider signs someone in.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
69#[serde(rename_all = "snake_case")]
70pub enum ProviderKind {
71    /// A person, through the browser (OIDC, WorkOS, …): `login {flow:
72    /// {browser}}` then `{code}`.
73    Browser,
74    /// A username and password (`login {flow: {password}}`).
75    Password,
76    /// An agent's key: a proof at the upgrade, then `login {flow: {session}}`.
77    Key,
78}
79
80/// One way in this server offers.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
82pub struct Provider {
83    /// Its name (`workos`, `plexus-idp`, `key`).
84    pub name: String,
85    pub kind: ProviderKind,
86    /// A human label, when it has one.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub label: Option<String>,
89}
90
91/// How a caller signs in (`auth.login {flow: …}`). On the wire, externally
92/// tagged: `{"browser": {"redirect": …}}`, `{"code": {"code", "state"}}`,
93/// `{"password": {"username", "password"}}`, `{"session": {"ttl_secs",
94/// "ceiling"}}`.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
96#[serde(rename_all = "snake_case")]
97pub enum LoginFlow {
98    /// A person, from a client with a browser: answered with the URL to
99    /// open (`login_url {url, state}`); the browser comes back to
100    /// `redirect` (a loopback address the client listens on) with a
101    /// one-time code.
102    Browser { redirect: String },
103    /// The browser came back: trade the code for a session. Single-use,
104    /// bound to the state.
105    Code { code: String, state: String },
106    /// Where a provider takes a password.
107    Password { username: String, password: String },
108    /// A session on a connection that is already someone — a key proof at
109    /// the upgrade (IDENTITY-40), or a session — bounded by `ceiling`
110    /// (`role@SCOPE` / `grant@SCOPE` entries) and lasting `ttl_secs`.
111    Session {
112        #[serde(default)]
113        ttl_secs: Option<u64>,
114        #[serde(default)]
115        ceiling: Option<Vec<String>>,
116    },
117}
118
119/// A session a backend minted.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
121pub struct Session {
122    /// The bearer token (`Authorization: Bearer …`, or the service's cookie).
123    pub token: String,
124    /// Who it is: `key:…`, `oidc:workos/user_…`, `idp:…`.
125    pub principal: String,
126    /// The agent id, for an agent's session.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub agent: Option<String>,
129    /// A display name, when the provider gives one.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub name: Option<String>,
132    /// Unix seconds.
133    pub expires_at: i64,
134    /// The session's ceiling, `role@SCOPE` / `grant@SCOPE`; empty: none.
135    #[serde(default)]
136    pub ceiling: Vec<String>,
137}
138
139/// Someone asking for access.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
141pub struct Waiting {
142    pub principal: String,
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub name: Option<String>,
145    /// The way they came in (`key`, `workos`, …).
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub provider: Option<String>,
148    /// Unix seconds: when they first asked.
149    pub since: i64,
150}
151
152/// What `login` answers.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum LoginAnswer {
155    /// Open this URL; the browser comes back with a code for this state.
156    LoginUrl { url: String, state: String },
157    Session(Session),
158}
159
160/// What `signup` answers when the backend decides it.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum SignupAnswer {
163    Waiting(Waiting),
164    LoginUrl { url: String, state: String },
165    Session(Session),
166}
167
168/// Why a backend would not: said to the caller as an in-band error.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct AuthFailure(pub String);
171
172impl AuthFailure {
173    pub fn new(message: impl Into<String>) -> Self {
174        Self(message.into())
175    }
176}
177
178impl fmt::Display for AuthFailure {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.write_str(&self.0)
181    }
182}
183
184impl std::error::Error for AuthFailure {}
185
186/// Why a store would not write.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct StoreError(pub String);
189
190impl StoreError {
191    pub fn new(message: impl Into<String>) -> Self {
192        Self(message.into())
193    }
194}
195
196impl fmt::Display for StoreError {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.write_str(&self.0)
199    }
200}
201
202impl std::error::Error for StoreError {}
203
204/// A membership as `whoami` says it.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206pub struct MembershipEntry {
207    pub role: String,
208    pub scope: String,
209}
210
211/// Every event the `auth` activation sends (`{"type": …}`).
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213#[serde(tag = "type", rename_all = "snake_case")]
214pub enum AuthEvent {
215    /// `providers`: one way in.
216    Provider {
217        name: String,
218        kind: ProviderKind,
219        #[serde(default, skip_serializing_if = "Option::is_none")]
220        label: Option<String>,
221    },
222    /// `login {browser}` / `signup`: open this URL.
223    LoginUrl { url: String, state: String },
224    /// `login`: signed in.
225    Session {
226        token: String,
227        principal: String,
228        #[serde(default, skip_serializing_if = "Option::is_none")]
229        agent: Option<String>,
230        #[serde(default, skip_serializing_if = "Option::is_none")]
231        name: Option<String>,
232        expires_at: i64,
233        #[serde(default)]
234        ceiling: Vec<String>,
235    },
236    /// `signup` (asking for access) / `waiting` (an admin's list).
237    Waiting {
238        principal: String,
239        #[serde(default, skip_serializing_if = "Option::is_none")]
240        name: Option<String>,
241        #[serde(default, skip_serializing_if = "Option::is_none")]
242        provider: Option<String>,
243        since: i64,
244    },
245    /// `whoami`.
246    Whoami {
247        principal: String,
248        #[serde(default, skip_serializing_if = "Option::is_none")]
249        name: Option<String>,
250        #[serde(default, skip_serializing_if = "Option::is_none")]
251        agent: Option<String>,
252        memberships: Vec<MembershipEntry>,
253        ceiling: Vec<String>,
254    },
255    /// `logout`.
256    LoggedOut { principal: String },
257    /// `requires {method}`: its grant, its target, the roles that list it.
258    Requires {
259        method: String,
260        grant: String,
261        #[serde(default, skip_serializing_if = "Option::is_none")]
262        target: Option<String>,
263        roles: Vec<String>,
264        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
265        public: bool,
266    },
267    /// `roles` / `role_set`: a role and its grants (`all`: every grant —
268    /// admin).
269    Role {
270        role: String,
271        grants: Vec<String>,
272        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
273        all: bool,
274    },
275    /// `grant`.
276    Granted { principal: String, role: String, scope: String },
277    /// `revoke`: the roles it removed there.
278    Revoked { principal: String, scope: String, roles: Vec<String> },
279    /// Anything refused or failed. A refusal (`error_kind: "forbidden"`)
280    /// carries AUTH-2's fields.
281    Error {
282        message: String,
283        #[serde(default, skip_serializing_if = "Option::is_none")]
284        error_kind: Option<String>,
285        #[serde(default, skip_serializing_if = "Option::is_none")]
286        grant: Option<String>,
287        #[serde(default, skip_serializing_if = "Option::is_none")]
288        scope: Option<String>,
289        #[serde(default, skip_serializing_if = "Option::is_none")]
290        roles: Option<Vec<String>>,
291        #[serde(default, skip_serializing_if = "Option::is_none")]
292        held_on: Option<Vec<String>>,
293    },
294}
295
296impl AuthEvent {
297    fn error(message: impl Into<String>) -> Self {
298        Self::Error { message: message.into(), error_kind: None, grant: None, scope: None, roles: None, held_on: None }
299    }
300}
301
302impl From<Session> for AuthEvent {
303    fn from(s: Session) -> Self {
304        Self::Session {
305            token: s.token,
306            principal: s.principal,
307            agent: s.agent,
308            name: s.name,
309            expires_at: s.expires_at,
310            ceiling: s.ceiling,
311        }
312    }
313}
314
315impl From<Waiting> for AuthEvent {
316    fn from(w: Waiting) -> Self {
317        Self::Waiting { principal: w.principal, name: w.name, provider: w.provider, since: w.since }
318    }
319}
320
321// ===========================================================================
322// What a service supplies
323// ===========================================================================
324
325/// What only the service knows about signing in. Async: a backend may talk
326/// to its identity provider. (The gate's own questions — [`Memberships`],
327/// [`Roles`], [`Resolve`] — stay synchronous and from memory.)
328#[async_trait]
329pub trait AuthBackend: Send + Sync + 'static {
330    /// The ways in this server offers (`auth.providers`).
331    fn providers(&self) -> Vec<Provider>;
332
333    /// Sign in by `flow` (`auth.login`). `caller` is the connection's
334    /// identity, if any: a [`LoginFlow::Session`] needs one (a key proof at
335    /// the upgrade, or a session) and must not widen it — the new
336    /// session's ceiling lies within the caller's (layer it). The browser
337    /// flow's start and finish, the code's single use and expiry, and the
338    /// session's minting are the backend's.
339    async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
340
341    /// `auth.signup` where the activation's own rule does not decide it:
342    /// an anonymous caller (create an account — or refuse: sign in first),
343    /// or one who already holds a membership. (A signed-in caller holding
344    /// none is put on the waiting list by [`AuthBackend::ask_access`].)
345    async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
346
347    /// Put a signed-in caller who holds no membership on the waiting list
348    /// (asking again keeps the first `since`).
349    async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
350
351    /// Everyone who has asked for access. The activation shows an admin
352    /// only those still holding no membership.
353    fn waiting(&self) -> Vec<Waiting>;
354
355    /// End the caller's session (`auth.logout`). A connection with no
356    /// session to end (a bare key proof) is not an error.
357    async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
358
359    /// AUTH-11: whether a signed-in caller's sign-in still stands — its
360    /// session not signed out, revoked or expired. The gate asks it before
361    /// every call it decides (`auth.*` included), so a sign-in that ended
362    /// holds nothing from its next call on. `Err`: why not, in words for
363    /// the caller. Memory only: it is asked on every call. (The gate
364    /// refuses a caller past its `expires_at` stamp before asking.)
365    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
366}
367
368/// AUTH-11: the backend as the gate's [`Liveness`].
369struct BackendLiveness(Arc<dyn AuthBackend>);
370
371impl Liveness for BackendLiveness {
372    fn alive(&self, caller: &AuthContext) -> Result<(), String> {
373        self.0.alive(caller)
374    }
375}
376
377/// [`Roles`] an admin can edit (`auth.role_set`). The gate reads the same
378/// store, so an edit reaches the next call and the next view.
379#[async_trait]
380pub trait RoleStore: Roles + 'static {
381    /// Replace `role`'s grants. Never called for [`ADMIN`].
382    async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
383}
384
385/// [`Memberships`] an admin can edit (`auth.grant`, `auth.revoke`).
386#[async_trait]
387pub trait MembershipStore: Memberships + 'static {
388    /// Add a membership (holding it already is not an error).
389    async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
390
391    /// Remove `principal`'s memberships on `scope` — the one role named, or
392    /// every role there. Answers the roles removed.
393    async fn revoke(
394        &self,
395        principal: &Principal,
396        role: Option<&RoleName>,
397        scope: &ScopeRef,
398    ) -> Result<Vec<RoleName>, StoreError>;
399}
400
401/// What [`DynamicHub::with_auth`](super::DynamicHub::with_auth) takes.
402#[derive(Clone)]
403pub struct AuthSetup {
404    pub backend: Arc<dyn AuthBackend>,
405    pub roles: Arc<dyn RoleStore>,
406    pub memberships: Arc<dyn MembershipStore>,
407    pub resolve: Arc<dyn Resolve>,
408}
409
410impl AuthSetup {
411    pub fn new(
412        backend: Arc<dyn AuthBackend>,
413        roles: Arc<dyn RoleStore>,
414        memberships: Arc<dyn MembershipStore>,
415        resolve: Arc<dyn Resolve>,
416    ) -> Self {
417        Self { backend, roles, memberships, resolve }
418    }
419}
420
421// ===========================================================================
422// The catalog: what each method requires
423// ===========================================================================
424
425/// What one method requires, as `auth.requires` says it.
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct Requirement {
428    pub grant: String,
429    pub target: Option<String>,
430    pub public: bool,
431}
432
433/// Every method of the hub by grant — fed as activations register.
434#[derive(Clone, Default)]
435pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>);
436
437impl Catalog {
438    /// Add an activation's methods (not its auto-generated `schema`, which
439    /// is introspection, nor its child routes).
440    pub(crate) fn add(&self, schema: &PluginSchema) {
441        let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
442        for m in &schema.methods {
443            if (m.name == "schema" && m.hash == "auto_schema") || !matches!(m.role, MethodRole::Rpc) {
444                continue;
445            }
446            let grant = m.grant_or(&schema.namespace);
447            map.insert(grant.clone(), Requirement { grant, target: m.target.clone(), public: m.public });
448        }
449    }
450
451    /// The requirement of `method` (`tickets.set_status`).
452    pub fn get(&self, method: &str) -> Option<Requirement> {
453        self.0.read().unwrap_or_else(|p| p.into_inner()).get(method).cloned()
454    }
455
456    /// Whether `grant` names a method of this hub.
457    pub fn knows(&self, grant: &str) -> bool {
458        self.0.read().unwrap_or_else(|p| p.into_inner()).contains_key(grant)
459    }
460}
461
462// ===========================================================================
463// The activation
464// ===========================================================================
465
466/// The `auth` activation. Mounted by
467/// [`DynamicHub::with_auth`](super::DynamicHub::with_auth); see the module
468/// docs.
469#[derive(Clone)]
470pub struct Auth {
471    inner: Arc<AuthInner>,
472}
473
474struct AuthInner {
475    backend: Arc<dyn AuthBackend>,
476    roles: Arc<dyn RoleStore>,
477    memberships: Arc<dyn MembershipStore>,
478    gate: Gate,
479    catalog: Catalog,
480}
481
482/// The service's resolver, and `*` → `[*]` (a membership on everywhere is
483/// granted and revoked like any other scope).
484struct WithEverywhere(Arc<dyn Resolve>);
485
486impl Resolve for WithEverywhere {
487    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
488        if target.trim() == "*" {
489            return Some(vec![ScopeRef::Everywhere]);
490        }
491        self.0.chain(target)
492    }
493}
494
495impl Auth {
496    /// The activation and the gate over the same stores.
497    pub(crate) fn mount(setup: AuthSetup, catalog: Catalog) -> (Self, Gate) {
498        let memberships: Arc<dyn Memberships> = setup.memberships.clone();
499        let roles: Arc<dyn Roles> = setup.roles.clone();
500        let gate = Gate::new(memberships, roles, Arc::new(WithEverywhere(setup.resolve)))
501            .with_liveness(Arc::new(BackendLiveness(setup.backend.clone())));
502        let auth = Self {
503            inner: Arc::new(AuthInner {
504                backend: setup.backend,
505                roles: setup.roles,
506                memberships: setup.memberships,
507                gate: gate.clone(),
508                catalog,
509            }),
510        };
511        (auth, gate)
512    }
513}
514
515fn principal_of(ctx: &AuthContext) -> Option<Principal> {
516    ctx.principal()
517}
518
519fn meta(ctx: &AuthContext, key: &str) -> Option<String> {
520    ctx.get_metadata_string(key).filter(|s| !s.is_empty())
521}
522
523/// An in-band refusal: `grant` is needed on `*`.
524fn needs_everywhere(gate: &Gate, grant: &str, reach: &Reach) -> AuthEvent {
525    let g = Grant::new(grant);
526    AuthEvent::Error {
527        message: format!("needs {grant} on *"),
528        error_kind: Some("forbidden".into()),
529        grant: Some(grant.into()),
530        scope: Some("*".into()),
531        roles: Some(gate.roles_listing(&g).iter().map(|r| r.as_str().to_string()).collect()),
532        held_on: Some(reach.held_on().iter().map(|s| s.as_str().to_string()).collect()),
533    }
534}
535
536fn role_event(role: &RoleName, grants: Option<GrantSet>) -> AuthEvent {
537    match grants {
538        Some(GrantSet::All) => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: true },
539        Some(GrantSet::Listed(set)) => AuthEvent::Role {
540            role: role.as_str().into(),
541            grants: set.iter().map(|g| g.as_str().to_string()).collect(),
542            all: false,
543        },
544        None => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: false },
545    }
546}
547
548#[plexus_macros::activation(
549    namespace = "auth",
550    version = "1.0.0",
551    description = "Sign in, who am I, what does this need",
552    roles(member = ["whoami", "logout", "requires"]),
553)]
554#[allow(deprecated)]
555impl Auth {
556    /// The ways in this server offers.
557    #[plexus_macros::method(public, group = "sign in", description = "The ways in this server offers")]
558    async fn providers(&self) -> impl Stream<Item = AuthEvent> + Send + 'static {
559        let providers = self.inner.backend.providers();
560        stream! {
561            for p in providers {
562                yield AuthEvent::Provider { name: p.name, kind: p.kind, label: p.label };
563            }
564        }
565    }
566
567    /// Sign in — a person through the browser (`{browser: {redirect}}`,
568    /// then `{code: {code, state}}`), a password, or an agent's session on
569    /// a key-proved connection (`{session: {ttl_secs, ceiling}}`).
570    #[plexus_macros::method(
571        public,
572        group = "sign in",
573        description = "Sign in — a person through the browser, an agent with its key",
574        params(flow = "browser {redirect} | code {code, state} | password {username, password} | session {ttl_secs?, ceiling?}")
575    )]
576    async fn login(&self, auth: Option<&AuthContext>, flow: LoginFlow) -> impl Stream<Item = AuthEvent> + Send + 'static {
577        let inner = self.inner.clone();
578        let caller = auth.cloned();
579        stream! {
580            if let LoginFlow::Session { ceiling: Some(entries), .. } = &flow {
581                if let Err(e) = Ceiling::parse(entries) {
582                    yield AuthEvent::error(format!("ceiling: {e}"));
583                    return;
584                }
585            }
586            if matches!(flow, LoginFlow::Session { .. }) && caller.as_ref().and_then(principal_of).is_none() {
587                yield AuthEvent::error("a session needs a connection that is someone: a key proof at the upgrade, or a session");
588                return;
589            }
590            match inner.backend.login(caller.as_ref(), flow).await {
591                Ok(LoginAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
592                Ok(LoginAnswer::Session(s)) => yield s.into(),
593                Err(e) => yield AuthEvent::error(e.0),
594            }
595        }
596    }
597
598    /// Create an account, or ask for access: a signed-in caller holding no
599    /// membership joins the waiting list for an admin.
600    #[plexus_macros::method(
601        public,
602        group = "sign in",
603        description = "Create an account, or ask for access",
604        params(via = "The provider to sign up through, where the server offers several")
605    )]
606    async fn signup(&self, auth: Option<&AuthContext>, via: Option<String>) -> impl Stream<Item = AuthEvent> + Send + 'static {
607        let inner = self.inner.clone();
608        let caller = auth.cloned();
609        stream! {
610            let holds_none = caller
611                .as_ref()
612                .and_then(principal_of)
613                .map(|p| inner.memberships.held(&p).is_empty());
614            let answer = match (holds_none, caller.as_ref()) {
615                (Some(true), Some(ctx)) => inner.backend.ask_access(ctx, via).await.map(SignupAnswer::Waiting),
616                _ => inner.backend.signup(caller.as_ref(), via).await,
617            };
618            match answer {
619                Ok(SignupAnswer::Waiting(w)) => yield w.into(),
620                Ok(SignupAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
621                Ok(SignupAnswer::Session(s)) => yield s.into(),
622                Err(e) => yield AuthEvent::error(e.0),
623            }
624        }
625    }
626
627    /// Who this connection is: principal, name, the roles it holds where,
628    /// and its session's ceiling.
629    #[plexus_macros::method(group = "you", description = "Who you are: principal, roles held where, ceiling")]
630    async fn whoami(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
631        let inner = self.inner.clone();
632        let ctx = auth.clone();
633        stream! {
634            let Some(p) = principal_of(&ctx) else {
635                yield AuthEvent::error("sign in first");
636                return;
637            };
638            let memberships = inner
639                .memberships
640                .held(&p)
641                .into_iter()
642                .map(|m| MembershipEntry { role: m.role.as_str().into(), scope: m.scope.as_str().into() })
643                .collect();
644            let ceiling = Ceiling::layers_of(&ctx)
645                .map(|layers| layers.iter().flat_map(|l| l.text()).collect())
646                .unwrap_or_default();
647            yield AuthEvent::Whoami {
648                principal: p.to_string(),
649                name: meta(&ctx, "name"),
650                agent: meta(&ctx, "agent"),
651                memberships,
652                ceiling,
653            };
654        }
655    }
656
657    /// End this session.
658    #[plexus_macros::method(group = "you", description = "Sign out: end this session")]
659    async fn logout(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
660        let inner = self.inner.clone();
661        let ctx = auth.clone();
662        stream! {
663            let principal = principal_of(&ctx).map(|p| p.to_string()).unwrap_or_default();
664            match inner.backend.logout(&ctx).await {
665                Ok(()) => yield AuthEvent::LoggedOut { principal },
666                Err(e) => yield AuthEvent::error(e.0),
667            }
668        }
669    }
670
671    /// What a method needs: its grant, its target and the roles that list
672    /// it.
673    #[plexus_macros::method(
674        group = "you",
675        description = "What a method needs: its grant, target, and the roles that list it",
676        params(method = "The method, as <activation>.<method>: tickets.set_status"),
677        example(note = "what changing a ticket's status needs", params = r#"{"method": "tickets.set_status"}"#)
678    )]
679    async fn requires(&self, auth: &AuthContext, method: String) -> impl Stream<Item = AuthEvent> + Send + 'static {
680        let _ = auth;
681        let inner = self.inner.clone();
682        stream! {
683            match inner.catalog.get(method.trim()) {
684                None => yield AuthEvent::error(format!("no method {method} here")),
685                Some(req) => {
686                    let roles = inner.gate.roles_listing(&Grant::new(req.grant.clone()));
687                    yield AuthEvent::Requires {
688                        method: method.trim().to_string(),
689                        grant: req.grant,
690                        target: req.target,
691                        roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
692                        public: req.public,
693                    };
694                }
695            }
696        }
697    }
698
699    /// Every role and the grants it lists (admin: every grant).
700    #[plexus_macros::method(group = "admin", description = "Every role and the grants it lists")]
701    async fn roles(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
702        let _ = auth;
703        let inner = self.inner.clone();
704        stream! {
705            let admin = RoleName::new(ADMIN);
706            yield role_event(&admin, Some(GrantSet::All));
707            let names: BTreeSet<RoleName> = inner.roles.names().into_iter().filter(|r| r.as_str() != ADMIN).collect();
708            for r in names {
709                let grants = inner.roles.grants(&r);
710                yield role_event(&r, grants);
711            }
712        }
713    }
714
715    /// Set a role's grants (admin on `*`). Each entry a grant
716    /// (`tickets.get`) or an existing role whose grants it includes.
717    #[plexus_macros::method(
718        group = "admin",
719        description = "Set a role's grants (admin on *)",
720        params(role = "The role (not admin)", grants = "Grants (tickets.get) or roles to include")
721    )]
722    async fn role_set(&self, auth: &AuthContext, reach: Reach, role: String, grants: Vec<String>) -> impl Stream<Item = AuthEvent> + Send + 'static {
723        let _ = auth;
724        let inner = self.inner.clone();
725        stream! {
726            if !reach.is_everywhere() {
727                yield needs_everywhere(&inner.gate, "auth.role_set", &reach);
728                return;
729            }
730            let role = role.trim().to_string();
731            if role.is_empty() || role.contains('.') || role.contains('@') {
732                yield AuthEvent::error(format!("`{role}` is not a role name"));
733                return;
734            }
735            if role == ADMIN {
736                yield AuthEvent::error("admin holds every grant; it is not edited");
737                return;
738            }
739            let mut set: BTreeSet<Grant> = BTreeSet::new();
740            for entry in grants.iter().map(|g| g.trim()).filter(|g| !g.is_empty()) {
741                if entry.contains('.') {
742                    if !inner.catalog.knows(entry) {
743                        yield AuthEvent::error(format!("no method {entry} here"));
744                        return;
745                    }
746                    set.insert(Grant::new(entry));
747                } else {
748                    match inner.roles.grants(&RoleName::new(entry)) {
749                        Some(GrantSet::Listed(included)) => set.extend(included),
750                        Some(GrantSet::All) => {
751                            yield AuthEvent::error(format!("{entry} holds every grant; a role cannot include it"));
752                            return;
753                        }
754                        None => {
755                            yield AuthEvent::error(format!("no role {entry} to include"));
756                            return;
757                        }
758                    }
759                }
760            }
761            let name = RoleName::new(role.clone());
762            if let Err(e) = inner.roles.set(&name, GrantSet::Listed(set)).await {
763                yield AuthEvent::error(e.0);
764                return;
765            }
766            let now = inner.roles.grants(&name);
767            yield role_event(&name, now);
768        }
769    }
770
771    /// Give `principal` `role` on `scope` (whoever holds `auth.grant` on
772    /// the scope: admin there).
773    #[plexus_macros::method(
774        target = "scope",
775        group = "admin",
776        description = "Give a principal a role on a scope",
777        params(principal = "key:…, oidc:…/…, idp:…", role = "The role", scope = "Where: a scope name, or *"),
778        example(note = "make a person an editor on MENGER", params = r#"{"principal": "oidc:workos/user_01M4", "role": "editor", "scope": "MENGER"}"#),
779        example(note = "make an agent's key an admin everywhere", params = r#"{"principal": "key:ac79e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "role": "admin", "scope": "*"}"#)
780    )]
781    async fn grant(&self, auth: &AuthContext, principal: String, role: String, scope: String) -> impl Stream<Item = AuthEvent> + Send + 'static {
782        let _ = auth;
783        let inner = self.inner.clone();
784        stream! {
785            let who: Principal = match principal.trim().parse() {
786                Ok(p) => p,
787                Err(e) => {
788                    yield AuthEvent::error(format!("`{principal}` is not a principal: {e}"));
789                    return;
790                }
791            };
792            let role_name = RoleName::new(role.trim());
793            if role_name.as_str() != ADMIN && inner.roles.grants(&role_name).is_none() {
794                yield AuthEvent::error(format!("no role {role} here"));
795                return;
796            }
797            let scope_ref = ScopeRef::parse(&scope);
798            let m = Membership { principal: who.clone(), role: role_name.clone(), scope: scope_ref.clone() };
799            match inner.memberships.grant(m).await {
800                Ok(()) => yield AuthEvent::Granted {
801                    principal: who.to_string(),
802                    role: role_name.as_str().into(),
803                    scope: scope_ref.as_str().into(),
804                },
805                Err(e) => yield AuthEvent::error(e.0),
806            }
807        }
808    }
809
810    /// Take `principal`'s role (or every role) on `scope` away.
811    #[plexus_macros::method(
812        target = "scope",
813        group = "admin",
814        description = "Take a principal's role on a scope away",
815        params(principal = "key:…, oidc:…/…, idp:…", role = "The role; absent: every role there", scope = "Where: a scope name, or *")
816    )]
817    async fn revoke(&self, auth: &AuthContext, principal: String, role: Option<String>, scope: String) -> impl Stream<Item = AuthEvent> + Send + 'static {
818        let _ = auth;
819        let inner = self.inner.clone();
820        stream! {
821            let who: Principal = match principal.trim().parse() {
822                Ok(p) => p,
823                Err(e) => {
824                    yield AuthEvent::error(format!("`{principal}` is not a principal: {e}"));
825                    return;
826                }
827            };
828            let scope_ref = ScopeRef::parse(&scope);
829            let role_name = role.as_deref().map(|r| RoleName::new(r.trim()));
830            match inner.memberships.revoke(&who, role_name.as_ref(), &scope_ref).await {
831                Ok(removed) => yield AuthEvent::Revoked {
832                    principal: who.to_string(),
833                    scope: scope_ref.as_str().into(),
834                    roles: removed.iter().map(|r| r.as_str().to_string()).collect(),
835                },
836                Err(e) => yield AuthEvent::error(e.0),
837            }
838        }
839    }
840
841    /// Who signed up or asked for access and holds nothing yet (admin on
842    /// `*`).
843    #[plexus_macros::method(group = "admin", description = "Who asked for access and holds nothing yet (admin on *)")]
844    async fn waiting(&self, auth: &AuthContext, reach: Reach) -> impl Stream<Item = AuthEvent> + Send + 'static {
845        let _ = auth;
846        let inner = self.inner.clone();
847        stream! {
848            if !reach.is_everywhere() {
849                yield needs_everywhere(&inner.gate, "auth.waiting", &reach);
850                return;
851            }
852            for w in inner.backend.waiting() {
853                let still = w
854                    .principal
855                    .parse::<Principal>()
856                    .map(|p| inner.memberships.held(&p).is_empty())
857                    .unwrap_or(true);
858                if still {
859                    yield w.into();
860                }
861            }
862        }
863    }
864}