1use 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
58pub const SIGNED_IN_GRANTS: [&str; 3] = ["auth.whoami", "auth.logout", "auth.requires"];
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
69#[serde(rename_all = "snake_case")]
70pub enum ProviderKind {
71 Browser,
74 Password,
76 Key,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
82pub struct Provider {
83 pub name: String,
85 pub kind: ProviderKind,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub label: Option<String>,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
96#[serde(rename_all = "snake_case")]
97pub enum LoginFlow {
98 Browser { redirect: String },
103 Code { code: String, state: String },
106 Password { username: String, password: String },
108 Session {
112 #[serde(default)]
113 ttl_secs: Option<u64>,
114 #[serde(default)]
115 ceiling: Option<Vec<String>>,
116 },
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
121pub struct Session {
122 pub token: String,
124 pub principal: String,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub agent: Option<String>,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub name: Option<String>,
132 pub expires_at: i64,
134 #[serde(default)]
136 pub ceiling: Vec<String>,
137}
138
139#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub provider: Option<String>,
148 pub since: i64,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum LoginAnswer {
155 LoginUrl { url: String, state: String },
157 Session(Session),
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum SignupAnswer {
163 Waiting(Waiting),
164 LoginUrl { url: String, state: String },
165 Session(Session),
166}
167
168#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206pub struct MembershipEntry {
207 pub role: String,
208 pub scope: String,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213#[serde(tag = "type", rename_all = "snake_case")]
214pub enum AuthEvent {
215 Provider {
217 name: String,
218 kind: ProviderKind,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 label: Option<String>,
221 },
222 LoginUrl { url: String, state: String },
224 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 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 {
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 LoggedOut { principal: String },
257 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 Role {
270 role: String,
271 grants: Vec<String>,
272 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
273 all: bool,
274 },
275 Granted { principal: String, role: String, scope: String },
277 Revoked { principal: String, scope: String, roles: Vec<String> },
279 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#[async_trait]
329pub trait AuthBackend: Send + Sync + 'static {
330 fn providers(&self) -> Vec<Provider>;
332
333 async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
340
341 async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
346
347 async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
350
351 fn waiting(&self) -> Vec<Waiting>;
354
355 async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
358
359 fn alive(&self, caller: &AuthContext) -> Result<(), String>;
366}
367
368struct 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#[async_trait]
380pub trait RoleStore: Roles + 'static {
381 async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
383}
384
385#[async_trait]
387pub trait MembershipStore: Memberships + 'static {
388 async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
390
391 async fn revoke(
394 &self,
395 principal: &Principal,
396 role: Option<&RoleName>,
397 scope: &ScopeRef,
398 ) -> Result<Vec<RoleName>, StoreError>;
399}
400
401#[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#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct Requirement {
428 pub grant: String,
429 pub target: Option<String>,
430 pub public: bool,
431}
432
433#[derive(Clone, Default)]
435pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>);
436
437impl Catalog {
438 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 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 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#[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
482struct 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 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
523fn 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}