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, Refusal, 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 plexus_client::FromClientError for AuthEvent {
306 fn from_client_error(error: plexus_client::ClientError) -> Self {
307 Self::error(error.to_string())
308 }
309}
310
311impl From<Session> for AuthEvent {
312 fn from(s: Session) -> Self {
313 Self::Session {
314 token: s.token,
315 principal: s.principal,
316 agent: s.agent,
317 name: s.name,
318 expires_at: s.expires_at,
319 ceiling: s.ceiling,
320 }
321 }
322}
323
324impl From<Waiting> for AuthEvent {
325 fn from(w: Waiting) -> Self {
326 Self::Waiting { principal: w.principal, name: w.name, provider: w.provider, since: w.since }
327 }
328}
329
330#[async_trait]
338pub trait AuthBackend: Send + Sync + 'static {
339 fn providers(&self) -> Vec<Provider>;
341
342 async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
349
350 async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
355
356 async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
359
360 fn waiting(&self) -> Vec<Waiting>;
363
364 async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
367
368 fn alive(&self, caller: &AuthContext) -> Result<(), String>;
375}
376
377struct BackendLiveness(Arc<dyn AuthBackend>);
379
380impl Liveness for BackendLiveness {
381 fn alive(&self, caller: &AuthContext) -> Result<(), String> {
382 self.0.alive(caller)
383 }
384}
385
386#[async_trait]
389pub trait RoleStore: Roles + 'static {
390 async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
392}
393
394#[async_trait]
396pub trait MembershipStore: Memberships + 'static {
397 async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
399
400 async fn revoke(
403 &self,
404 principal: &Principal,
405 role: Option<&RoleName>,
406 scope: &ScopeRef,
407 ) -> Result<Vec<RoleName>, StoreError>;
408}
409
410#[derive(Clone)]
412pub struct AuthSetup {
413 pub backend: Arc<dyn AuthBackend>,
414 pub roles: Arc<dyn RoleStore>,
415 pub memberships: Arc<dyn MembershipStore>,
416 pub resolve: Arc<dyn Resolve>,
417 pub generation: Option<GrantsGeneration>,
422}
423
424impl AuthSetup {
425 pub fn new(
426 backend: Arc<dyn AuthBackend>,
427 roles: Arc<dyn RoleStore>,
428 memberships: Arc<dyn MembershipStore>,
429 resolve: Arc<dyn Resolve>,
430 ) -> Self {
431 Self { backend, roles, memberships, resolve, generation: None }
432 }
433
434 pub fn with_generation(mut self, generation: GrantsGeneration) -> Self {
437 self.generation = Some(generation);
438 self
439 }
440}
441
442#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct Requirement {
449 pub grant: String,
450 pub target: Option<String>,
451 pub public: bool,
452}
453
454#[derive(Clone, Default)]
456pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>);
457
458impl Catalog {
459 pub(crate) fn add(&self, schema: &PluginSchema) {
462 let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
463 for m in &schema.methods {
464 if m.is_auto_schema() || !matches!(m.role, MethodRole::Rpc) {
465 continue;
466 }
467 let grant = m.grant_or(&schema.namespace);
468 map.insert(grant.clone(), Requirement { grant, target: m.target.clone(), public: m.public });
469 }
470 }
471
472 pub fn get(&self, method: &str) -> Option<Requirement> {
474 self.0.read().unwrap_or_else(|p| p.into_inner()).get(method).cloned()
475 }
476
477 pub fn knows(&self, grant: &str) -> bool {
479 self.0.read().unwrap_or_else(|p| p.into_inner()).contains_key(grant)
480 }
481}
482
483#[derive(Clone)]
491pub struct AuthActivation {
492 inner: Arc<AuthInner>,
493}
494
495struct AuthInner {
496 backend: Arc<dyn AuthBackend>,
497 roles: Arc<dyn RoleStore>,
498 memberships: Arc<dyn MembershipStore>,
499 gate: Gate,
500 catalog: Catalog,
501}
502
503struct WithEverywhere(Arc<dyn Resolve>);
506
507impl Resolve for WithEverywhere {
508 fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
509 if target.trim() == "*" {
510 return Some(vec![ScopeRef::Everywhere]);
511 }
512 self.0.chain(target)
513 }
514}
515
516impl AuthActivation {
517 pub(crate) fn mount(setup: AuthSetup, catalog: Catalog) -> (Self, Gate) {
519 let memberships: Arc<dyn Memberships> = setup.memberships.clone();
520 let roles: Arc<dyn Roles> = setup.roles.clone();
521 let mut gate = Gate::new(memberships, roles, Arc::new(WithEverywhere(setup.resolve)))
522 .with_liveness(Arc::new(BackendLiveness(setup.backend.clone())));
523 if let Some(generation) = setup.generation {
524 gate = gate.with_generation(generation);
525 }
526 let auth = Self {
527 inner: Arc::new(AuthInner {
528 backend: setup.backend,
529 roles: setup.roles,
530 memberships: setup.memberships,
531 gate: gate.clone(),
532 catalog,
533 }),
534 };
535 (auth, gate)
536 }
537}
538
539fn principal_of(ctx: &AuthContext) -> Option<Principal> {
540 ctx.principal()
541}
542
543fn meta(ctx: &AuthContext, key: &str) -> Option<String> {
544 ctx.get_metadata_string(key).filter(|s| !s.is_empty())
545}
546
547fn needs_everywhere(gate: &Gate, grant: &str, reach: &Reach) -> AuthEvent {
549 let g = Grant::new(grant);
550 AuthEvent::Error {
551 message: format!("needs {grant} on *"),
552 error_kind: Some("forbidden".into()),
553 grant: Some(grant.into()),
554 scope: Some("*".into()),
555 roles: Some(gate.roles_listing(&g).iter().map(|r| r.as_str().to_string()).collect()),
556 held_on: Some(reach.held_on().iter().map(|s| s.as_str().to_string()).collect()),
557 }
558}
559
560fn holds_where_written(gate: &Gate, caller: &AuthContext, reach: &Reach, grant: &str, scopes: &[&str]) -> Result<(), Box<AuthEvent>> {
566 let g = Grant::new(grant);
567 if reach.grant() != Some(&g) {
568 return Err(Box::new(needs_on(gate, grant, "*", reach.held_on())));
569 }
570 for scope in scopes {
571 match gate.check(Some(caller), &g, Some(scope)) {
572 Ok(_) => {}
573 Err(Refusal::MissingGrant { scope, held_on, .. }) => return Err(Box::new(needs_on(gate, grant, scope.as_str(), &held_on))),
574 Err(Refusal::Ended { reason }) => return Err(Box::new(AuthEvent::error(reason))),
575 Err(Refusal::Unauthenticated) => return Err(Box::new(AuthEvent::error("sign in first"))),
576 }
577 }
578 Ok(())
579}
580
581fn needs_on(gate: &Gate, grant: &str, scope: &str, held_on: &[ScopeRef]) -> AuthEvent {
583 AuthEvent::Error {
584 message: format!("needs {grant} on {scope}"),
585 error_kind: Some("forbidden".into()),
586 grant: Some(grant.into()),
587 scope: Some(scope.into()),
588 roles: Some(gate.roles_listing(&Grant::new(grant)).iter().map(|r| r.as_str().to_string()).collect()),
589 held_on: Some(held_on.iter().map(|s| s.as_str().to_string()).collect()),
590 }
591}
592
593fn role_event(role: &RoleName, grants: Option<GrantSet>) -> AuthEvent {
594 match grants {
595 Some(GrantSet::All) => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: true },
596 Some(GrantSet::Listed(set)) => AuthEvent::Role {
597 role: role.as_str().into(),
598 grants: set.iter().map(|g| g.as_str().to_string()).collect(),
599 all: false,
600 },
601 None => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: false },
602 }
603}
604
605#[plexus_macros::activation(
606 version = "1.0.0",
607 description = "Sign in, who am I, what does this need",
608 roles(member = ["whoami", "logout", "requires"]),
609 typed_params,
612)]
613impl AuthActivation {
614 #[plexus_macros::method(public, group = "sign in", description = "The ways in this server offers")]
616 async fn providers(&self) -> impl Stream<Item = AuthEvent> + Send + 'static {
617 let providers = self.inner.backend.providers();
618 stream! {
619 for p in providers {
620 yield AuthEvent::Provider { name: p.name, kind: p.kind, label: p.label };
621 }
622 }
623 }
624
625 #[plexus_macros::method(
629 public,
630 group = "sign in",
631 description = "Sign in — a person through the browser, an agent with its key",
632 params(flow = "browser {redirect} | code {code, state} | password {username, password} | session {ttl_secs?, ceiling?}")
633 )]
634 async fn login(&self, auth: Option<&AuthContext>, flow: LoginFlow) -> impl Stream<Item = AuthEvent> + Send + 'static {
635 let inner = self.inner.clone();
636 let caller = auth.cloned();
637 stream! {
638 if let LoginFlow::Session { ceiling: Some(entries), .. } = &flow {
639 if let Err(e) = Ceiling::parse(entries) {
640 yield AuthEvent::error(format!("ceiling: {e}"));
641 return;
642 }
643 }
644 if matches!(flow, LoginFlow::Session { .. }) && caller.as_ref().and_then(principal_of).is_none() {
645 yield AuthEvent::error("a session needs a connection that is someone: a key proof at the upgrade, or a session");
646 return;
647 }
648 match inner.backend.login(caller.as_ref(), flow).await {
649 Ok(LoginAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
650 Ok(LoginAnswer::Session(s)) => yield s.into(),
651 Err(e) => yield AuthEvent::error(e.0),
652 }
653 }
654 }
655
656 #[plexus_macros::method(
660 public,
661 group = "sign in",
662 description = "Create an account, or ask for access",
663 params(via = "The provider to sign up through, where the server offers several")
664 )]
665 async fn signup(&self, auth: Option<&AuthContext>, via: Option<param::ProviderName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
666 let inner = self.inner.clone();
667 let caller = auth.cloned();
668 let via = via.map(param::ProviderName::into_string);
669 stream! {
670 let holds_none = caller
671 .as_ref()
672 .and_then(principal_of)
673 .map(|p| inner.memberships.own_held(&p).is_empty());
674 let answer = match (holds_none, caller.as_ref()) {
675 (Some(true), Some(ctx)) => inner.backend.ask_access(ctx, via).await.map(SignupAnswer::Waiting),
676 _ => inner.backend.signup(caller.as_ref(), via).await,
677 };
678 match answer {
679 Ok(SignupAnswer::Waiting(w)) => yield w.into(),
680 Ok(SignupAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
681 Ok(SignupAnswer::Session(s)) => yield s.into(),
682 Err(e) => yield AuthEvent::error(e.0),
683 }
684 }
685 }
686
687 #[plexus_macros::method(group = "you", description = "Who you are: principal, roles held where, ceiling")]
690 async fn whoami(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
691 let inner = self.inner.clone();
692 let ctx = auth.clone();
693 stream! {
694 let Some(p) = principal_of(&ctx) else {
695 yield AuthEvent::error("sign in first");
696 return;
697 };
698 let memberships = inner
699 .memberships
700 .held(&p)
701 .into_iter()
702 .map(|m| MembershipEntry { role: m.role.as_str().into(), scope: m.scope.as_str().into() })
703 .collect();
704 let ceiling = Ceiling::layers_of(&ctx)
705 .map(|layers| layers.iter().flat_map(|l| l.text()).collect())
706 .unwrap_or_default();
707 yield AuthEvent::Whoami {
708 principal: p.to_string(),
709 name: meta(&ctx, "name"),
710 agent: meta(&ctx, "agent"),
711 memberships,
712 ceiling,
713 };
714 }
715 }
716
717 #[plexus_macros::method(group = "you", description = "Sign out: end this session")]
719 async fn logout(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
720 let inner = self.inner.clone();
721 let ctx = auth.clone();
722 stream! {
723 let principal = principal_of(&ctx).map(|p| p.to_string()).unwrap_or_default();
724 match inner.backend.logout(&ctx).await {
725 Ok(()) => {
726 inner.gate.moved(GrantsMove::SignOut);
728 yield AuthEvent::LoggedOut { principal }
729 }
730 Err(e) => yield AuthEvent::error(e.0),
731 }
732 }
733 }
734
735 #[plexus_macros::method(
738 group = "you",
739 description = "What a method needs: its grant, target, and the roles that list it",
740 params(method = "The method, as <activation>.<method>: tickets.set_status"),
741 example(note = "what changing a ticket's status needs", params = r#"{"method": "tickets.set_status"}"#)
742 )]
743 async fn requires(&self, auth: &AuthContext, method: param::MethodPath) -> impl Stream<Item = AuthEvent> + Send + 'static {
744 let _ = auth;
745 let inner = self.inner.clone();
746 stream! {
747 match inner.catalog.get(method.as_str()) {
748 None => yield AuthEvent::error(format!("no method {method} here")),
749 Some(req) => {
750 let roles = inner.gate.roles_listing(&Grant::new(req.grant.clone()));
751 yield AuthEvent::Requires {
752 method: method.into_string(),
753 grant: req.grant,
754 target: req.target,
755 roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
756 public: req.public,
757 };
758 }
759 }
760 }
761 }
762
763 #[plexus_macros::method(group = "admin", description = "Every role and the grants it lists")]
765 async fn roles(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
766 let _ = auth;
767 let inner = self.inner.clone();
768 stream! {
769 let admin = RoleName::new(ADMIN);
770 yield role_event(&admin, Some(GrantSet::All));
771 let names: BTreeSet<RoleName> = inner.roles.names().into_iter().filter(|r| r.as_str() != ADMIN).collect();
772 for r in names {
773 let grants = inner.roles.grants(&r);
774 yield role_event(&r, grants);
775 }
776 }
777 }
778
779 #[plexus_macros::method(
782 group = "admin",
783 description = "Set a role's grants (admin on *)",
784 params(role = "The role (not admin)", grants = "Grants (tickets.get) or roles to include")
785 )]
786 async fn role_set(&self, auth: &AuthContext, reach: Reach, role: param::RoleName, grants: Vec<param::GrantName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
787 let _ = auth;
788 let inner = self.inner.clone();
789 stream! {
790 if !reach.is_everywhere() || reach.grant() != Some(&Grant::new("auth.role_set")) {
791 yield needs_everywhere(&inner.gate, "auth.role_set", &reach);
792 return;
793 }
794 if role.as_str() == ADMIN {
797 yield AuthEvent::error("admin holds every grant; it is not edited");
798 return;
799 }
800 let mut set: BTreeSet<Grant> = BTreeSet::new();
801 for entry in grants.iter() {
802 let entry = entry.as_str();
803 if entry.contains('.') {
804 if !inner.catalog.knows(entry) {
805 yield AuthEvent::error(format!("no method {entry} here"));
806 return;
807 }
808 set.insert(Grant::new(entry));
809 } else {
810 match inner.roles.grants(&RoleName::new(entry)) {
811 Some(GrantSet::Listed(included)) => set.extend(included),
812 Some(GrantSet::All) => {
813 yield AuthEvent::error(format!("{entry} holds every grant; a role cannot include it"));
814 return;
815 }
816 None => {
817 yield AuthEvent::error(format!("no role {entry} to include"));
818 return;
819 }
820 }
821 }
822 }
823 let name = role.role();
824 if let Err(e) = inner.roles.set(&name, GrantSet::Listed(set)).await {
825 yield AuthEvent::error(e.0);
826 return;
827 }
828 inner.gate.moved(GrantsMove::RoleEdit);
829 let now = inner.roles.grants(&name);
830 yield role_event(&name, now);
831 }
832 }
833
834 #[plexus_macros::method(
837 target = "scope",
838 group = "admin",
839 description = "Give a principal a role on a scope",
840 params(principal = "key:…, oidc:…/…, idp:…", role = "The role", scope = "Where: a scope name, or *"),
841 example(note = "make a person an editor on MENGER", params = r#"{"principal": "oidc:workos/user_01M4", "role": "editor", "scope": "MENGER"}"#),
842 example(note = "make an agent's key an admin everywhere", params = r#"{"principal": "key:ac79e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "role": "admin", "scope": "*"}"#)
843 )]
844 async fn grant(&self, auth: &AuthContext, reach: Reach, principal: param::Principal, role: param::RoleName, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
845 let inner = self.inner.clone();
846 let caller = auth.clone();
847 stream! {
848 let who: Principal = principal.principal();
849 let role_name = role.role();
850 if role_name.as_str() != ADMIN && inner.roles.grants(&role_name).is_none() {
851 yield AuthEvent::error(format!("no role {role} here"));
852 return;
853 }
854 let scope_ref = scope.scope();
855 if let Err(refused) = holds_where_written(&inner.gate, &caller, &reach, "auth.grant", &[scope.as_str(), scope_ref.as_str()]) {
856 yield *refused;
857 return;
858 }
859 let m = Membership { principal: who.clone(), role: role_name.clone(), scope: scope_ref.clone() };
860 match inner.memberships.grant(m).await {
861 Ok(()) => {
862 inner.gate.moved(GrantsMove::Grant);
863 yield AuthEvent::Granted {
864 principal: who.to_string(),
865 role: role_name.as_str().into(),
866 scope: scope_ref.as_str().into(),
867 }
868 }
869 Err(e) => yield AuthEvent::error(e.0),
870 }
871 }
872 }
873
874 #[plexus_macros::method(
876 target = "scope",
877 group = "admin",
878 description = "Take a principal's role on a scope away",
879 params(principal = "key:…, oidc:…/…, idp:…", role = "The role; absent: every role there", scope = "Where: a scope name, or *")
880 )]
881 async fn revoke(&self, auth: &AuthContext, reach: Reach, principal: param::Principal, role: Option<param::RoleName>, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
882 let inner = self.inner.clone();
883 let caller = auth.clone();
884 stream! {
885 let who: Principal = principal.principal();
886 let scope_ref = scope.scope();
887 if let Err(refused) = holds_where_written(&inner.gate, &caller, &reach, "auth.revoke", &[scope.as_str(), scope_ref.as_str()]) {
888 yield *refused;
889 return;
890 }
891 let role_name = role.as_ref().map(param::RoleName::role);
892 match inner.memberships.revoke(&who, role_name.as_ref(), &scope_ref).await {
893 Ok(removed) => {
894 if !removed.is_empty() {
895 inner.gate.moved(GrantsMove::Revoke);
896 }
897 yield AuthEvent::Revoked {
898 principal: who.to_string(),
899 scope: scope_ref.as_str().into(),
900 roles: removed.iter().map(|r| r.as_str().to_string()).collect(),
901 }
902 }
903 Err(e) => yield AuthEvent::error(e.0),
904 }
905 }
906 }
907
908 #[plexus_macros::method(group = "admin", description = "Who asked for access and holds nothing yet (admin on *)")]
911 async fn waiting(&self, auth: &AuthContext, reach: Reach) -> impl Stream<Item = AuthEvent> + Send + 'static {
912 let _ = auth;
913 let inner = self.inner.clone();
914 stream! {
915 if !reach.is_everywhere() || reach.grant() != Some(&Grant::new("auth.waiting")) {
916 yield needs_everywhere(&inner.gate, "auth.waiting", &reach);
917 return;
918 }
919 for w in inner.backend.waiting() {
920 let still = w
921 .principal
922 .parse::<Principal>()
923 .map(|p| inner.memberships.own_held(&p).is_empty())
924 .unwrap_or(true);
925 if still {
926 yield w.into();
927 }
928 }
929 }
930 }
931}