Skip to main content

utopia_database/
permission.rs

1//! [`Permission`]: an action granted to a [`Role`], written
2//! `action("role")` (`read("any")`, `update("team:123/owner")`).
3//!
4//! PHP: `Utopia\Database\Permission`.
5
6use std::fmt;
7
8use crate::error::{Error, Result};
9use crate::role::{Role, falsy};
10
11/// The action a permission grants.
12///
13/// PHP: the `$permission` string of `Permission`
14/// (`Database::PERMISSION_*`). PHP's constructor also stores other
15/// strings, which [`Permission::parse`] never produces; Rust cannot hold
16/// them (a recorded deviation).
17#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
18pub enum PermissionType {
19    /// `create`
20    Create,
21    /// `read`
22    Read,
23    /// `update`
24    Update,
25    /// `delete`
26    Delete,
27    /// `write`: an aggregate of create, update and delete.
28    Write,
29}
30
31impl AsRef<str> for PermissionType {
32    fn as_ref(&self) -> &str {
33        self.as_str()
34    }
35}
36
37impl PermissionType {
38    /// `Database::PERMISSIONS`: the individual actions, in PHP's order.
39    pub const ALL: [PermissionType; 4] =
40        [PermissionType::Create, PermissionType::Read, PermissionType::Update, PermissionType::Delete];
41
42    /// The action as PHP spells it.
43    pub fn as_str(self) -> &'static str {
44        match self {
45            PermissionType::Create => "create",
46            PermissionType::Read => "read",
47            PermissionType::Update => "update",
48            PermissionType::Delete => "delete",
49            PermissionType::Write => "write",
50        }
51    }
52
53    /// The action a name names, if any.
54    pub fn from_name(name: &str) -> Option<PermissionType> {
55        Some(match name {
56            "create" => PermissionType::Create,
57            "read" => PermissionType::Read,
58            "update" => PermissionType::Update,
59            "delete" => PermissionType::Delete,
60            "write" => PermissionType::Write,
61            _ => return None,
62        })
63    }
64
65    /// The individual actions an aggregate stands for (`write`: create,
66    /// update, delete); `None` for an individual action.
67    fn subtypes(self) -> Option<[PermissionType; 3]> {
68        match self {
69            PermissionType::Write => Some([PermissionType::Create, PermissionType::Update, PermissionType::Delete]),
70            _ => None,
71        }
72    }
73}
74
75/// A permission: an action and the role it is granted to.
76///
77/// ```
78/// use utopia_database::{Permission, PermissionType};
79/// use utopia_database::Role;
80///
81/// let p = Permission::parse("read(\"user:123\")").unwrap();
82/// assert_eq!(p.permission(), PermissionType::Read);
83/// assert_eq!(p.role().identifier(), "123");
84/// assert_eq!(Permission::read(&Role::any()), "read(\"any\")");
85/// assert_eq!(
86///     Permission::aggregate(&["write(\"any\")"], &PermissionType::ALL).unwrap(),
87///     ["create(\"any\")", "update(\"any\")", "delete(\"any\")"]
88/// );
89/// ```
90///
91/// PHP: `Utopia\Database\Permission`; `getRole()`,
92/// `getIdentifier()` and `getDimension()` are read through [`Permission::role`].
93#[derive(Clone, PartialEq, Eq, Hash, Debug)]
94pub struct Permission {
95    permission: PermissionType,
96    role: Role,
97}
98
99impl Permission {
100    /// `new Permission($permission, $role, $identifier, $dimension)`.
101    pub fn new(permission: PermissionType, role: Role) -> Self {
102        Self { permission, role }
103    }
104
105    /// The action (`getPermission()`).
106    pub fn permission(&self) -> PermissionType {
107        self.permission
108    }
109
110    /// The role (`getRole()`, `getIdentifier()`, `getDimension()`).
111    pub fn role(&self) -> &Role {
112        &self.role
113    }
114
115    /// `Permission::parse($permission)`.
116    ///
117    /// Fails ([`crate::Kind::Database`]) with `Invalid permission string
118    /// format: "..."`, `Invalid permission type: "..."`, `Only one dimension
119    /// can be provided` or `Dimension must not be empty`.
120    pub fn parse(permission: &str) -> Result<Self> {
121        let mut parts = permission.split("(\"");
122        let (Some(kind), Some(rest), None) = (parts.next(), parts.next(), parts.next()) else {
123            return Err(Error::database(format!("Invalid permission string format: \"{permission}\".")));
124        };
125        let Some(kind) = PermissionType::from_name(kind) else {
126            return Err(Error::database(format!("Invalid permission type: \"{kind}\".")));
127        };
128        let full_role = rest.replace("\")", "");
129        let role_parts: Vec<&str> = full_role.split(':').collect();
130        let name = role_parts[0];
131        let has_identifier = role_parts.len() > 1;
132        let has_dimension = full_role.contains('/');
133
134        let role = if !has_identifier && !has_dimension {
135            Role::named(name, "", "")
136        } else if has_identifier && !has_dimension {
137            Role::named(name, role_parts[1], "")
138        } else if !has_identifier {
139            let (name, dimension) = split_dimension(&full_role)?;
140            Role::named(name, "", dimension)
141        } else {
142            let (identifier, dimension) = split_dimension(role_parts[1])?;
143            Role::named(name, identifier, dimension)
144        };
145        Ok(Self::new(kind, role))
146    }
147
148    /// `Permission::aggregate($permissions, $allowed)`: each permission
149    /// string parsed and written back, aggregates (`write`) expanded into
150    /// the individual actions in `allowed`, without duplicates, in order.
151    ///
152    /// PHP: `null` permissions give `null`; a Rust caller without
153    /// permissions has nothing to call.
154    pub fn aggregate<S: AsRef<str>>(permissions: &[S], allowed: &[PermissionType]) -> Result<Vec<String>> {
155        let mut mutated: Vec<String> = Vec::new();
156        for permission in permissions {
157            let permission = Self::parse(permission.as_ref())?;
158            match permission.permission.subtypes() {
159                None => mutated.push(permission.to_string()),
160                Some(subtypes) => {
161                    for subtype in subtypes {
162                        if allowed.contains(&subtype) {
163                            mutated.push(Self::new(subtype, permission.role.clone()).to_string());
164                        }
165                    }
166                }
167            }
168        }
169        let mut unique: Vec<String> = Vec::with_capacity(mutated.len());
170        for p in mutated {
171            if !unique.contains(&p) {
172                unique.push(p);
173            }
174        }
175        Ok(unique)
176    }
177
178    /// `Permission::read($role)`.
179    pub fn read(role: &Role) -> String {
180        Self::new(PermissionType::Read, role.clone()).to_string()
181    }
182
183    /// `Permission::create($role)`.
184    pub fn create(role: &Role) -> String {
185        Self::new(PermissionType::Create, role.clone()).to_string()
186    }
187
188    /// `Permission::update($role)`.
189    pub fn update(role: &Role) -> String {
190        Self::new(PermissionType::Update, role.clone()).to_string()
191    }
192
193    /// `Permission::delete($role)`.
194    pub fn delete(role: &Role) -> String {
195        Self::new(PermissionType::Delete, role.clone()).to_string()
196    }
197
198    /// `Permission::write($role)`.
199    pub fn write(role: &Role) -> String {
200        Self::new(PermissionType::Write, role.clone()).to_string()
201    }
202}
203
204fn split_dimension(s: &str) -> Result<(&str, &str)> {
205    let mut parts = s.split('/');
206    let (Some(first), Some(second), None) = (parts.next(), parts.next(), parts.next()) else {
207        return Err(Error::database("Only one dimension can be provided"));
208    };
209    if falsy(second) {
210        return Err(Error::database("Dimension must not be empty"));
211    }
212    Ok((first, second))
213}
214
215impl fmt::Display for Permission {
216    /// `toString()`: `action("role")`.
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        write!(f, "{}(\"{}\")", self.permission.as_str(), self.role)
219    }
220}