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, 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
59pub const SIGNED_IN_GRANTS: [&str; 3] = ["auth.whoami", "auth.logout", "auth.requires"];
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70#[serde(rename_all = "snake_case")]
71pub enum ProviderKind {
72 Browser,
75 Password,
77 Key,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
83pub struct Provider {
84 pub name: String,
86 pub kind: ProviderKind,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub label: Option<String>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "snake_case")]
98pub enum LoginFlow {
99 Browser { redirect: String },
104 Code { code: String, state: String },
107 Password { username: String, password: String },
109 Session {
113 #[serde(default)]
114 ttl_secs: Option<u64>,
115 #[serde(default)]
116 ceiling: Option<Vec<String>>,
117 },
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
122pub struct Session {
123 pub token: String,
125 pub principal: String,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub agent: Option<String>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub name: Option<String>,
133 pub expires_at: i64,
135 #[serde(default)]
137 pub ceiling: Vec<String>,
138}
139
140#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub provider: Option<String>,
149 pub since: i64,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum LoginAnswer {
156 LoginUrl { url: String, state: String },
158 Session(Session),
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum SignupAnswer {
164 Waiting(Waiting),
165 LoginUrl { url: String, state: String },
166 Session(Session),
167}
168
169#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
207pub struct MembershipEntry {
208 pub role: String,
209 pub scope: String,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
214#[serde(tag = "type", rename_all = "snake_case")]
215pub enum AuthEvent {
216 Provider {
218 name: String,
219 kind: ProviderKind,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 label: Option<String>,
222 },
223 LoginUrl { url: String, state: String },
225 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 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 {
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 LoggedOut { principal: String },
258 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 Role {
271 role: String,
272 grants: Vec<String>,
273 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
274 all: bool,
275 },
276 Granted { principal: String, role: String, scope: String },
278 Revoked { principal: String, scope: String, roles: Vec<String> },
280 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#[async_trait]
330pub trait AuthBackend: Send + Sync + 'static {
331 fn providers(&self) -> Vec<Provider>;
333
334 async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
341
342 async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
347
348 async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
351
352 fn waiting(&self) -> Vec<Waiting>;
355
356 async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
359
360 fn alive(&self, caller: &AuthContext) -> Result<(), String>;
367}
368
369struct 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#[async_trait]
381pub trait RoleStore: Roles + 'static {
382 async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
384}
385
386#[async_trait]
388pub trait MembershipStore: Memberships + 'static {
389 async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
391
392 async fn revoke(
395 &self,
396 principal: &Principal,
397 role: Option<&RoleName>,
398 scope: &ScopeRef,
399 ) -> Result<Vec<RoleName>, StoreError>;
400}
401
402#[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 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 pub fn with_generation(mut self, generation: GrantsGeneration) -> Self {
429 self.generation = Some(generation);
430 self
431 }
432}
433
434#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct Requirement {
441 pub grant: String,
442 pub target: Option<String>,
443 pub public: bool,
444}
445
446#[derive(Clone, Default)]
448pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>);
449
450impl Catalog {
451 pub(crate) fn add(&self, schema: &PluginSchema) {
454 let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
455 for m in &schema.methods {
456 if m.is_auto_schema() || !matches!(m.role, MethodRole::Rpc) {
457 continue;
458 }
459 let grant = m.grant_or(&schema.namespace);
460 map.insert(grant.clone(), Requirement { grant, target: m.target.clone(), public: m.public });
461 }
462 }
463
464 pub fn get(&self, method: &str) -> Option<Requirement> {
466 self.0.read().unwrap_or_else(|p| p.into_inner()).get(method).cloned()
467 }
468
469 pub fn knows(&self, grant: &str) -> bool {
471 self.0.read().unwrap_or_else(|p| p.into_inner()).contains_key(grant)
472 }
473}
474
475#[derive(Clone)]
483pub struct AuthActivation {
484 inner: Arc<AuthInner>,
485}
486
487struct AuthInner {
488 backend: Arc<dyn AuthBackend>,
489 roles: Arc<dyn RoleStore>,
490 memberships: Arc<dyn MembershipStore>,
491 gate: Gate,
492 catalog: Catalog,
493}
494
495struct WithEverywhere(Arc<dyn Resolve>);
498
499impl Resolve for WithEverywhere {
500 fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
501 if target.trim() == "*" {
502 return Some(vec![ScopeRef::Everywhere]);
503 }
504 self.0.chain(target)
505 }
506}
507
508impl AuthActivation {
509 pub(crate) fn mount(setup: AuthSetup, catalog: Catalog) -> (Self, Gate) {
511 let memberships: Arc<dyn Memberships> = setup.memberships.clone();
512 let roles: Arc<dyn Roles> = setup.roles.clone();
513 let mut gate = Gate::new(memberships, roles, Arc::new(WithEverywhere(setup.resolve)))
514 .with_liveness(Arc::new(BackendLiveness(setup.backend.clone())));
515 if let Some(generation) = setup.generation {
516 gate = gate.with_generation(generation);
517 }
518 let auth = Self {
519 inner: Arc::new(AuthInner {
520 backend: setup.backend,
521 roles: setup.roles,
522 memberships: setup.memberships,
523 gate: gate.clone(),
524 catalog,
525 }),
526 };
527 (auth, gate)
528 }
529}
530
531fn principal_of(ctx: &AuthContext) -> Option<Principal> {
532 ctx.principal()
533}
534
535fn meta(ctx: &AuthContext, key: &str) -> Option<String> {
536 ctx.get_metadata_string(key).filter(|s| !s.is_empty())
537}
538
539fn needs_everywhere(gate: &Gate, grant: &str, reach: &Reach) -> AuthEvent {
541 let g = Grant::new(grant);
542 AuthEvent::Error {
543 message: format!("needs {grant} on *"),
544 error_kind: Some("forbidden".into()),
545 grant: Some(grant.into()),
546 scope: Some("*".into()),
547 roles: Some(gate.roles_listing(&g).iter().map(|r| r.as_str().to_string()).collect()),
548 held_on: Some(reach.held_on().iter().map(|s| s.as_str().to_string()).collect()),
549 }
550}
551
552fn role_event(role: &RoleName, grants: Option<GrantSet>) -> AuthEvent {
553 match grants {
554 Some(GrantSet::All) => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: true },
555 Some(GrantSet::Listed(set)) => AuthEvent::Role {
556 role: role.as_str().into(),
557 grants: set.iter().map(|g| g.as_str().to_string()).collect(),
558 all: false,
559 },
560 None => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: false },
561 }
562}
563
564#[plexus_macros::activation(
565 version = "1.0.0",
566 description = "Sign in, who am I, what does this need",
567 roles(member = ["whoami", "logout", "requires"]),
568 typed_params,
571)]
572impl AuthActivation {
573 #[plexus_macros::method(public, group = "sign in", description = "The ways in this server offers")]
575 async fn providers(&self) -> impl Stream<Item = AuthEvent> + Send + 'static {
576 let providers = self.inner.backend.providers();
577 stream! {
578 for p in providers {
579 yield AuthEvent::Provider { name: p.name, kind: p.kind, label: p.label };
580 }
581 }
582 }
583
584 #[plexus_macros::method(
588 public,
589 group = "sign in",
590 description = "Sign in — a person through the browser, an agent with its key",
591 params(flow = "browser {redirect} | code {code, state} | password {username, password} | session {ttl_secs?, ceiling?}")
592 )]
593 async fn login(&self, auth: Option<&AuthContext>, flow: LoginFlow) -> impl Stream<Item = AuthEvent> + Send + 'static {
594 let inner = self.inner.clone();
595 let caller = auth.cloned();
596 stream! {
597 if let LoginFlow::Session { ceiling: Some(entries), .. } = &flow {
598 if let Err(e) = Ceiling::parse(entries) {
599 yield AuthEvent::error(format!("ceiling: {e}"));
600 return;
601 }
602 }
603 if matches!(flow, LoginFlow::Session { .. }) && caller.as_ref().and_then(principal_of).is_none() {
604 yield AuthEvent::error("a session needs a connection that is someone: a key proof at the upgrade, or a session");
605 return;
606 }
607 match inner.backend.login(caller.as_ref(), flow).await {
608 Ok(LoginAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
609 Ok(LoginAnswer::Session(s)) => yield s.into(),
610 Err(e) => yield AuthEvent::error(e.0),
611 }
612 }
613 }
614
615 #[plexus_macros::method(
619 public,
620 group = "sign in",
621 description = "Create an account, or ask for access",
622 params(via = "The provider to sign up through, where the server offers several")
623 )]
624 async fn signup(&self, auth: Option<&AuthContext>, via: Option<param::ProviderName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
625 let inner = self.inner.clone();
626 let caller = auth.cloned();
627 let via = via.map(param::ProviderName::into_string);
628 stream! {
629 let holds_none = caller
630 .as_ref()
631 .and_then(principal_of)
632 .map(|p| inner.memberships.own_held(&p).is_empty());
633 let answer = match (holds_none, caller.as_ref()) {
634 (Some(true), Some(ctx)) => inner.backend.ask_access(ctx, via).await.map(SignupAnswer::Waiting),
635 _ => inner.backend.signup(caller.as_ref(), via).await,
636 };
637 match answer {
638 Ok(SignupAnswer::Waiting(w)) => yield w.into(),
639 Ok(SignupAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
640 Ok(SignupAnswer::Session(s)) => yield s.into(),
641 Err(e) => yield AuthEvent::error(e.0),
642 }
643 }
644 }
645
646 #[plexus_macros::method(group = "you", description = "Who you are: principal, roles held where, ceiling")]
649 async fn whoami(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
650 let inner = self.inner.clone();
651 let ctx = auth.clone();
652 stream! {
653 let Some(p) = principal_of(&ctx) else {
654 yield AuthEvent::error("sign in first");
655 return;
656 };
657 let memberships = inner
658 .memberships
659 .held(&p)
660 .into_iter()
661 .map(|m| MembershipEntry { role: m.role.as_str().into(), scope: m.scope.as_str().into() })
662 .collect();
663 let ceiling = Ceiling::layers_of(&ctx)
664 .map(|layers| layers.iter().flat_map(|l| l.text()).collect())
665 .unwrap_or_default();
666 yield AuthEvent::Whoami {
667 principal: p.to_string(),
668 name: meta(&ctx, "name"),
669 agent: meta(&ctx, "agent"),
670 memberships,
671 ceiling,
672 };
673 }
674 }
675
676 #[plexus_macros::method(group = "you", description = "Sign out: end this session")]
678 async fn logout(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
679 let inner = self.inner.clone();
680 let ctx = auth.clone();
681 stream! {
682 let principal = principal_of(&ctx).map(|p| p.to_string()).unwrap_or_default();
683 match inner.backend.logout(&ctx).await {
684 Ok(()) => {
685 inner.gate.moved(GrantsMove::SignOut);
687 yield AuthEvent::LoggedOut { principal }
688 }
689 Err(e) => yield AuthEvent::error(e.0),
690 }
691 }
692 }
693
694 #[plexus_macros::method(
697 group = "you",
698 description = "What a method needs: its grant, target, and the roles that list it",
699 params(method = "The method, as <activation>.<method>: tickets.set_status"),
700 example(note = "what changing a ticket's status needs", params = r#"{"method": "tickets.set_status"}"#)
701 )]
702 async fn requires(&self, auth: &AuthContext, method: param::MethodPath) -> impl Stream<Item = AuthEvent> + Send + 'static {
703 let _ = auth;
704 let inner = self.inner.clone();
705 stream! {
706 match inner.catalog.get(method.as_str()) {
707 None => yield AuthEvent::error(format!("no method {method} here")),
708 Some(req) => {
709 let roles = inner.gate.roles_listing(&Grant::new(req.grant.clone()));
710 yield AuthEvent::Requires {
711 method: method.into_string(),
712 grant: req.grant,
713 target: req.target,
714 roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
715 public: req.public,
716 };
717 }
718 }
719 }
720 }
721
722 #[plexus_macros::method(group = "admin", description = "Every role and the grants it lists")]
724 async fn roles(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
725 let _ = auth;
726 let inner = self.inner.clone();
727 stream! {
728 let admin = RoleName::new(ADMIN);
729 yield role_event(&admin, Some(GrantSet::All));
730 let names: BTreeSet<RoleName> = inner.roles.names().into_iter().filter(|r| r.as_str() != ADMIN).collect();
731 for r in names {
732 let grants = inner.roles.grants(&r);
733 yield role_event(&r, grants);
734 }
735 }
736 }
737
738 #[plexus_macros::method(
741 group = "admin",
742 description = "Set a role's grants (admin on *)",
743 params(role = "The role (not admin)", grants = "Grants (tickets.get) or roles to include")
744 )]
745 async fn role_set(&self, auth: &AuthContext, reach: Reach, role: param::RoleName, grants: Vec<param::GrantName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
746 let _ = auth;
747 let inner = self.inner.clone();
748 stream! {
749 if !reach.is_everywhere() {
750 yield needs_everywhere(&inner.gate, "auth.role_set", &reach);
751 return;
752 }
753 if role.as_str() == ADMIN {
756 yield AuthEvent::error("admin holds every grant; it is not edited");
757 return;
758 }
759 let mut set: BTreeSet<Grant> = BTreeSet::new();
760 for entry in grants.iter() {
761 let entry = entry.as_str();
762 if entry.contains('.') {
763 if !inner.catalog.knows(entry) {
764 yield AuthEvent::error(format!("no method {entry} here"));
765 return;
766 }
767 set.insert(Grant::new(entry));
768 } else {
769 match inner.roles.grants(&RoleName::new(entry)) {
770 Some(GrantSet::Listed(included)) => set.extend(included),
771 Some(GrantSet::All) => {
772 yield AuthEvent::error(format!("{entry} holds every grant; a role cannot include it"));
773 return;
774 }
775 None => {
776 yield AuthEvent::error(format!("no role {entry} to include"));
777 return;
778 }
779 }
780 }
781 }
782 let name = role.role();
783 if let Err(e) = inner.roles.set(&name, GrantSet::Listed(set)).await {
784 yield AuthEvent::error(e.0);
785 return;
786 }
787 inner.gate.moved(GrantsMove::RoleEdit);
788 let now = inner.roles.grants(&name);
789 yield role_event(&name, now);
790 }
791 }
792
793 #[plexus_macros::method(
796 target = "scope",
797 group = "admin",
798 description = "Give a principal a role on a scope",
799 params(principal = "key:…, oidc:…/…, idp:…", role = "The role", scope = "Where: a scope name, or *"),
800 example(note = "make a person an editor on MENGER", params = r#"{"principal": "oidc:workos/user_01M4", "role": "editor", "scope": "MENGER"}"#),
801 example(note = "make an agent's key an admin everywhere", params = r#"{"principal": "key:ac79e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "role": "admin", "scope": "*"}"#)
802 )]
803 async fn grant(&self, auth: &AuthContext, principal: param::Principal, role: param::RoleName, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
804 let _ = auth;
805 let inner = self.inner.clone();
806 stream! {
807 let who: Principal = principal.principal();
808 let role_name = role.role();
809 if role_name.as_str() != ADMIN && inner.roles.grants(&role_name).is_none() {
810 yield AuthEvent::error(format!("no role {role} here"));
811 return;
812 }
813 let scope_ref = scope.scope();
814 let m = Membership { principal: who.clone(), role: role_name.clone(), scope: scope_ref.clone() };
815 match inner.memberships.grant(m).await {
816 Ok(()) => {
817 inner.gate.moved(GrantsMove::Grant);
818 yield AuthEvent::Granted {
819 principal: who.to_string(),
820 role: role_name.as_str().into(),
821 scope: scope_ref.as_str().into(),
822 }
823 }
824 Err(e) => yield AuthEvent::error(e.0),
825 }
826 }
827 }
828
829 #[plexus_macros::method(
831 target = "scope",
832 group = "admin",
833 description = "Take a principal's role on a scope away",
834 params(principal = "key:…, oidc:…/…, idp:…", role = "The role; absent: every role there", scope = "Where: a scope name, or *")
835 )]
836 async fn revoke(&self, auth: &AuthContext, principal: param::Principal, role: Option<param::RoleName>, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
837 let _ = auth;
838 let inner = self.inner.clone();
839 stream! {
840 let who: Principal = principal.principal();
841 let scope_ref = scope.scope();
842 let role_name = role.as_ref().map(param::RoleName::role);
843 match inner.memberships.revoke(&who, role_name.as_ref(), &scope_ref).await {
844 Ok(removed) => {
845 if !removed.is_empty() {
846 inner.gate.moved(GrantsMove::Revoke);
847 }
848 yield AuthEvent::Revoked {
849 principal: who.to_string(),
850 scope: scope_ref.as_str().into(),
851 roles: removed.iter().map(|r| r.as_str().to_string()).collect(),
852 }
853 }
854 Err(e) => yield AuthEvent::error(e.0),
855 }
856 }
857 }
858
859 #[plexus_macros::method(group = "admin", description = "Who asked for access and holds nothing yet (admin on *)")]
862 async fn waiting(&self, auth: &AuthContext, reach: Reach) -> impl Stream<Item = AuthEvent> + Send + 'static {
863 let _ = auth;
864 let inner = self.inner.clone();
865 stream! {
866 if !reach.is_everywhere() {
867 yield needs_everywhere(&inner.gate, "auth.waiting", &reach);
868 return;
869 }
870 for w in inner.backend.waiting() {
871 let still = w
872 .principal
873 .parse::<Principal>()
874 .map(|p| inner.memberships.own_held(&p).is_empty())
875 .unwrap_or(true);
876 if still {
877 yield w.into();
878 }
879 }
880 }
881 }
882}