Skip to main content

fastauth_plugin_admin/
access.rs

1//! Statement-based access control, the same design as Better Auth's admin plugin: a role is
2//! a set of actions per resource, and a request is allowed when one of the user's roles
3//! grants every action it asks for.
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use fastauth_core::plugin_prelude::*;
8
9/// Every resource and action the admin endpoints check, as Better Auth defines them.
10pub const STATEMENTS: &[(&str, &[&str])] = &[
11    (
12        "user",
13        &[
14            "create",
15            "list",
16            "set-role",
17            "ban",
18            "impersonate",
19            "impersonate-admins",
20            "delete",
21            "set-password",
22            "set-email",
23            "get",
24            "update",
25        ],
26    ),
27    ("session", &["list", "revoke", "delete"]),
28];
29
30/// Actions per resource: `{ "user": ["list", "ban"] }`. A role's grants, or the actions a
31/// permission check asks for.
32///
33/// ```
34/// use fastauth_plugin_admin::Permissions;
35///
36/// let support = Permissions::new().allow("user", ["list", "get"]).allow("session", ["list"]);
37/// assert!(support.authorize(&Permissions::new().allow("user", ["list"])));
38/// assert!(!support.authorize(&Permissions::new().allow("user", ["ban"])));
39/// ```
40#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(transparent)]
42pub struct Permissions(BTreeMap<String, BTreeSet<String>>);
43
44impl Permissions {
45    /// No actions at all: the built-in `user` role.
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Adds `actions` on `resource`.
51    pub fn allow(
52        mut self,
53        resource: impl Into<String>,
54        actions: impl IntoIterator<Item = impl Into<String>>,
55    ) -> Self {
56        self.0
57            .entry(resource.into())
58            .or_default()
59            .extend(actions.into_iter().map(Into::into));
60        self
61    }
62
63    /// The built-in `admin` role: every action in [`STATEMENTS`] except
64    /// `user:impersonate-admins`.
65    pub fn admin() -> Self {
66        STATEMENTS
67            .iter()
68            .fold(Self::new(), |permissions, (resource, actions)| {
69                permissions.allow(
70                    *resource,
71                    actions
72                        .iter()
73                        .copied()
74                        .filter(|action| *action != "impersonate-admins"),
75                )
76            })
77    }
78
79    /// Whether these grants cover every action of every resource in `request`. An empty
80    /// request, or a resource with no actions, is never allowed.
81    pub fn authorize(&self, request: &Permissions) -> bool {
82        !request.0.is_empty()
83            && request.0.iter().all(|(resource, actions)| {
84                !actions.is_empty()
85                    && self
86                        .0
87                        .get(resource)
88                        .is_some_and(|granted| actions.is_subset(granted))
89            })
90    }
91}