fastauth_plugin_organization/access.rs
1//! Roles, the statements they grant, and the one permission check every endpoint and
2//! extractor goes through.
3//!
4//! A statement pairs a resource with the actions allowed on it: `("member", &["delete"])`.
5//! A role is a named set of statements. A member holds one role or several (stored
6//! comma-separated), and is allowed a request when any one of its roles grants every action
7//! on every resource the request names, the rule Better Auth's access control uses.
8
9use std::collections::{BTreeMap, BTreeSet};
10
11/// The role an organization's creator gets. The last member holding it can't leave or be
12/// demoted.
13pub const OWNER: &str = "owner";
14/// Manages members and invitations and updates the organization, but can't delete it.
15pub const ADMIN: &str = "admin";
16/// The default role: no organization, member or invitation actions.
17pub const MEMBER: &str = "member";
18
19/// The roles an organization knows, with what each may do. `Roles::new()` holds Better
20/// Auth's three defaults; add your own with [`role`](Roles::role) and give existing roles more
21/// with [`grant`](Roles::grant):
22///
23/// ```
24/// use fastauth_plugin_organization::{Organization, Roles};
25///
26/// let roles = Roles::new()
27/// .role("billing", [("invoice", &["read", "pay"]), ("organization", &["update"])])
28/// .grant("owner", [("invoice", &["read", "pay", "refund"])]);
29/// assert!(roles.allows("billing", &[("invoice", &["pay"])]));
30/// assert!(roles.allows("member,billing", &[("invoice", &["read"])]));
31/// assert!(!roles.allows("admin", &[("invoice", &["read"])]));
32/// let _plugin = Organization::default().roles(roles);
33/// ```
34///
35/// Resources and actions are plain strings because clients send them as JSON to
36/// `/organization/has-permission`; the [`Permission`] trait gives them a type for handlers.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Roles {
39 roles: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
40}
41
42impl Default for Roles {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48impl Roles {
49 /// Better Auth's default roles: `owner` (every action), `admin` (everything but deleting
50 /// the organization) and `member` (reading access control only).
51 pub fn new() -> Self {
52 let roles = Self {
53 roles: BTreeMap::new(),
54 };
55 roles
56 .role(
57 OWNER,
58 [
59 ("organization", &["update", "delete"]),
60 ("member", &["create", "update", "delete"]),
61 ("invitation", &["create", "cancel"]),
62 ("team", &["create", "update", "delete"]),
63 ("ac", &["create", "read", "update", "delete"]),
64 ],
65 )
66 .role(
67 ADMIN,
68 [
69 ("organization", &["update"]),
70 ("member", &["create", "update", "delete"]),
71 ("invitation", &["create", "cancel"]),
72 ("team", &["create", "update", "delete"]),
73 ("ac", &["create", "read", "update", "delete"]),
74 ],
75 )
76 .role(
77 MEMBER,
78 [
79 ("organization", &[]),
80 ("member", &[]),
81 ("invitation", &[]),
82 ("team", &[]),
83 ("ac", &["read"]),
84 ],
85 )
86 }
87
88 /// Defines `name` with exactly these statements, replacing a role of the same name.
89 pub fn role<const N: usize>(mut self, name: &str, statements: [(&str, &[&str]); N]) -> Self {
90 self.roles.insert(name.to_owned(), BTreeMap::new());
91 self.grant(name, statements)
92 }
93
94 /// Adds actions to `name`, defining it if it doesn't exist yet. Use it to let the
95 /// built-in roles act on your own resources.
96 pub fn grant<const N: usize>(mut self, name: &str, statements: [(&str, &[&str]); N]) -> Self {
97 let role = self.roles.entry(name.to_owned()).or_default();
98 for (resource, actions) in statements {
99 role.entry(resource.to_owned())
100 .or_default()
101 .extend(actions.iter().map(|a| (*a).to_owned()));
102 }
103 self
104 }
105
106 /// Whether a role of this name exists.
107 pub fn contains(&self, role: &str) -> bool {
108 self.roles.contains_key(role)
109 }
110
111 /// The permission check. `role` is one role or a comma-separated list; the answer is yes
112 /// when one of them grants every action on every resource in `permissions`. An empty
113 /// request, or a resource with no actions, is never allowed.
114 pub fn allows(&self, role: &str, permissions: &[(&str, &[&str])]) -> bool {
115 if permissions.is_empty() {
116 return false;
117 }
118 role_list(role).any(|name| {
119 self.roles.get(name).is_some_and(|statements| {
120 permissions.iter().all(|(resource, actions)| {
121 !actions.is_empty()
122 && statements
123 .get(*resource)
124 .is_some_and(|allowed| actions.iter().all(|a| allowed.contains(*a)))
125 })
126 })
127 })
128 }
129}
130
131/// Splits a stored role value into trimmed, non-empty role names.
132pub(crate) fn role_list(role: &str) -> impl Iterator<Item = &str> {
133 role.split(',').map(str::trim).filter(|r| !r.is_empty())
134}
135
136/// A permission as a type, so a handler's signature names what it requires:
137/// `RequirePermission<AppAuth, InvoicePay>` with the `axum` feature.
138///
139/// ```
140/// use fastauth_plugin_organization::Permission;
141///
142/// pub struct InvoicePay;
143///
144/// impl Permission for InvoicePay {
145/// const RESOURCE: &'static str = "invoice";
146/// const ACTIONS: &'static [&'static str] = &["pay"];
147/// }
148/// ```
149pub trait Permission: Send + Sync + 'static {
150 /// The resource, e.g. `"member"`.
151 const RESOURCE: &'static str;
152 /// The actions on it, all of which are required.
153 const ACTIONS: &'static [&'static str];
154}
155
156macro_rules! permissions {
157 ($($(#[$doc:meta])* $name:ident = $resource:literal: [$($action:literal),+];)*) => {
158 $(
159 $(#[$doc])*
160 #[derive(Clone, Copy, Debug, Default)]
161 pub struct $name;
162
163 impl Permission for $name {
164 const RESOURCE: &'static str = $resource;
165 const ACTIONS: &'static [&'static str] = &[$($action),+];
166 }
167 )*
168 };
169}
170
171permissions! {
172 /// `organization: [update]`: owners and admins.
173 OrganizationUpdate = "organization": ["update"];
174 /// `organization: [delete]`: owners.
175 OrganizationDelete = "organization": ["delete"];
176 /// `member: [create]`: owners and admins.
177 MemberCreate = "member": ["create"];
178 /// `member: [update]`: owners and admins.
179 MemberUpdate = "member": ["update"];
180 /// `member: [delete]`: owners and admins.
181 MemberDelete = "member": ["delete"];
182 /// `invitation: [create]`: owners and admins.
183 InvitationCreate = "invitation": ["create"];
184 /// `invitation: [cancel]`: owners and admins.
185 InvitationCancel = "invitation": ["cancel"];
186}