rust_rbac/storage/
memory.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::{Arc, RwLock};
3use async_trait::async_trait;
4
5use crate::error::RbacError;
6use crate::models::{Permission, Role};
7use crate::storage::traits::RbacStorage;
8
9/// In-memory implementation of RbacStorage
10pub struct MemoryStorage {
11    permissions: Arc<RwLock<HashMap<String, Permission>>>,
12    roles: Arc<RwLock<HashMap<String, Role>>>,
13    role_permissions: Arc<RwLock<HashMap<String, HashSet<String>>>>,
14    subject_roles: Arc<RwLock<HashMap<String, HashSet<String>>>>,
15    subject_permissions: Arc<RwLock<HashMap<String, HashSet<String>>>>,
16}
17
18impl MemoryStorage {
19    pub fn new() -> Self {
20        Self {
21            permissions: Arc::new(RwLock::new(HashMap::new())),
22            roles: Arc::new(RwLock::new(HashMap::new())),
23            role_permissions: Arc::new(RwLock::new(HashMap::new())),
24            subject_roles: Arc::new(RwLock::new(HashMap::new())),
25            subject_permissions: Arc::new(RwLock::new(HashMap::new())),
26        }
27    }
28}
29
30impl Default for MemoryStorage {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36#[async_trait]
37impl RbacStorage for MemoryStorage {
38    async fn create_permission(&self, permission: &Permission) -> Result<(), RbacError> {
39        let mut permissions = self.permissions.write().map_err(|_| {
40            RbacError::StorageError("Failed to acquire write lock on permissions".to_string())
41        })?;
42        
43        if permissions.contains_key(&permission.name) {
44            return Err(RbacError::PermissionAlreadyExists(permission.name.clone()));
45        }
46        
47        permissions.insert(permission.name.clone(), permission.clone());
48        Ok(())
49    }
50    
51    async fn get_permission(&self, name: &str) -> Result<Option<Permission>, RbacError> {
52        let permissions = self.permissions.read().map_err(|_| {
53            RbacError::StorageError("Failed to acquire read lock on permissions".to_string())
54        })?;
55        
56        Ok(permissions.get(name).cloned())
57    }
58    
59    async fn delete_permission(&self, name: &str) -> Result<(), RbacError> {
60        let mut permissions = self.permissions.write().map_err(|_| {
61            RbacError::StorageError("Failed to acquire write lock on permissions".to_string())
62        })?;
63        
64        if permissions.remove(name).is_none() {
65            return Err(RbacError::PermissionNotFound(name.to_string()));
66        }
67        
68        // Remove this permission from all roles
69        let mut role_permissions = self.role_permissions.write().map_err(|_| {
70            RbacError::StorageError("Failed to acquire write lock on role_permissions".to_string())
71        })?;
72        
73        for permissions in role_permissions.values_mut() {
74            permissions.remove(name);
75        }
76        
77        // Remove this permission from all subjects
78        let mut subject_permissions = self.subject_permissions.write().map_err(|_| {
79            RbacError::StorageError("Failed to acquire write lock on subject_permissions".to_string())
80        })?;
81        
82        for permissions in subject_permissions.values_mut() {
83            permissions.remove(name);
84        }
85        
86        Ok(())
87    }
88    
89    async fn create_role(&self, role: &Role) -> Result<(), RbacError> {
90        let mut roles = self.roles.write().map_err(|_| {
91            RbacError::StorageError("Failed to acquire write lock on roles".to_string())
92        })?;
93        
94        if roles.contains_key(&role.name) {
95            return Err(RbacError::RoleAlreadyExists(role.name.clone()));
96        }
97        
98        roles.insert(role.name.clone(), role.clone());
99        
100        // Initialize empty permission set for this role
101        let mut role_permissions = self.role_permissions.write().map_err(|_| {
102            RbacError::StorageError("Failed to acquire write lock on role_permissions".to_string())
103        })?;
104        
105        role_permissions.insert(role.name.clone(), HashSet::new());
106        
107        Ok(())
108    }
109    
110    async fn get_role(&self, name: &str) -> Result<Option<Role>, RbacError> {
111        let roles = self.roles.read().map_err(|_| {
112            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
113        })?;
114        
115        Ok(roles.get(name).cloned())
116    }
117    
118    async fn delete_role(&self, name: &str) -> Result<(), RbacError> {
119        let mut roles = self.roles.write().map_err(|_| {
120            RbacError::StorageError("Failed to acquire write lock on roles".to_string())
121        })?;
122        
123        if roles.remove(name).is_none() {
124            return Err(RbacError::RoleNotFound(name.to_string()));
125        }
126        
127        // Remove this role's permissions
128        let mut role_permissions = self.role_permissions.write().map_err(|_| {
129            RbacError::StorageError("Failed to acquire write lock on role_permissions".to_string())
130        })?;
131        
132        role_permissions.remove(name);
133        
134        // Remove this role from all subjects
135        let mut subject_roles = self.subject_roles.write().map_err(|_| {
136            RbacError::StorageError("Failed to acquire write lock on subject_roles".to_string())
137        })?;
138        
139        for roles in subject_roles.values_mut() {
140            roles.remove(name);
141        }
142        
143        Ok(())
144    }
145    
146    async fn assign_permission_to_role(&self, permission_name: &str, role_name: &str) -> Result<(), RbacError> {
147        // Check if permission exists
148        let permissions = self.permissions.read().map_err(|_| {
149            RbacError::StorageError("Failed to acquire read lock on permissions".to_string())
150        })?;
151        
152        if !permissions.contains_key(permission_name) {
153            return Err(RbacError::PermissionNotFound(permission_name.to_string()));
154        }
155        
156        // Check if role exists
157        let roles = self.roles.read().map_err(|_| {
158            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
159        })?;
160        
161        if !roles.contains_key(role_name) {
162            return Err(RbacError::RoleNotFound(role_name.to_string()));
163        }
164        
165        // Assign permission to role
166        let mut role_permissions = self.role_permissions.write().map_err(|_| {
167            RbacError::StorageError("Failed to acquire write lock on role_permissions".to_string())
168        })?;
169        
170        role_permissions
171            .entry(role_name.to_string())
172            .or_insert_with(HashSet::new)
173            .insert(permission_name.to_string());
174        
175        Ok(())
176    }
177    
178    async fn remove_permission_from_role(&self, permission_name: &str, role_name: &str) -> Result<(), RbacError> {
179        // Check if role exists
180        let roles = self.roles.read().map_err(|_| {
181            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
182        })?;
183        
184        if !roles.contains_key(role_name) {
185            return Err(RbacError::RoleNotFound(role_name.to_string()));
186        }
187        
188        // Remove permission from role
189        let mut role_permissions = self.role_permissions.write().map_err(|_| {
190            RbacError::StorageError("Failed to acquire write lock on role_permissions".to_string())
191        })?;
192        
193        if let Some(permissions) = role_permissions.get_mut(role_name) {
194            permissions.remove(permission_name);
195        }
196        
197        Ok(())
198    }
199    
200    async fn get_permissions_for_role(&self, role_name: &str) -> Result<Vec<Permission>, RbacError> {
201        // Check if role exists
202        let roles = self.roles.read().map_err(|_| {
203            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
204        })?;
205        
206        if !roles.contains_key(role_name) {
207            return Err(RbacError::RoleNotFound(role_name.to_string()));
208        }
209        
210        // Get permissions for role
211        let role_permissions = self.role_permissions.read().map_err(|_| {
212            RbacError::StorageError("Failed to acquire read lock on role_permissions".to_string())
213        })?;
214        
215        let permissions_read = self.permissions.read().map_err(|_| {
216            RbacError::StorageError("Failed to acquire read lock on permissions".to_string())
217        })?;
218        
219        let permission_names = role_permissions.get(role_name).map_or_else(
220            || Vec::new(),
221            |names| names.iter().cloned().collect::<Vec<_>>()
222        );
223        
224        let mut result = Vec::new();
225        for name in permission_names {
226            if let Some(permission) = permissions_read.get(&name) {
227                result.push(permission.clone());
228            }
229        }
230        
231        Ok(result)
232    }
233    
234    async fn assign_role_to_subject(&self, role_name: &str, subject_id: &str) -> Result<(), RbacError> {
235        // Check if role exists
236        let roles = self.roles.read().map_err(|_| {
237            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
238        })?;
239        
240        if !roles.contains_key(role_name) {
241            return Err(RbacError::RoleNotFound(role_name.to_string()));
242        }
243        
244        // Assign role to subject
245        let mut subject_roles = self.subject_roles.write().map_err(|_| {
246            RbacError::StorageError("Failed to acquire write lock on subject_roles".to_string())
247        })?;
248        
249        subject_roles
250            .entry(subject_id.to_string())
251            .or_insert_with(HashSet::new)
252            .insert(role_name.to_string());
253        
254        Ok(())
255    }
256    
257    async fn remove_role_from_subject(&self, role_name: &str, subject_id: &str) -> Result<(), RbacError> {
258        // Remove role from subject
259        let mut subject_roles = self.subject_roles.write().map_err(|_| {
260            RbacError::StorageError("Failed to acquire write lock on subject_roles".to_string())
261        })?;
262        
263        if let Some(roles) = subject_roles.get_mut(subject_id) {
264            roles.remove(role_name);
265        }
266        
267        Ok(())
268    }
269    
270    async fn get_roles_for_subject(&self, subject_id: &str) -> Result<Vec<Role>, RbacError> {
271        // Get roles for subject
272        let subject_roles = self.subject_roles.read().map_err(|_| {
273            RbacError::StorageError("Failed to acquire read lock on subject_roles".to_string())
274        })?;
275        
276        let roles_read = self.roles.read().map_err(|_| {
277            RbacError::StorageError("Failed to acquire read lock on roles".to_string())
278        })?;
279        
280        let role_names = subject_roles.get(subject_id).map_or_else(
281            || Vec::new(),
282            |names| names.iter().cloned().collect::<Vec<_>>()
283        );
284        
285        let mut result = Vec::new();
286        for name in role_names {
287            if let Some(role) = roles_read.get(&name) {
288                result.push(role.clone());
289            }
290        }
291        
292        Ok(result)
293    }
294    
295    async fn assign_permission_to_subject(&self, permission_name: &str, subject_id: &str) -> Result<(), RbacError> {
296        // Check if permission exists
297        let permissions = self.permissions.read().map_err(|_| {
298            RbacError::StorageError("Failed to acquire read lock on permissions".to_string())
299        })?;
300        
301        if !permissions.contains_key(permission_name) {
302            return Err(RbacError::PermissionNotFound(permission_name.to_string()));
303        }
304        
305        // Assign permission to subject
306        let mut subject_permissions = self.subject_permissions.write().map_err(|_| {
307            RbacError::StorageError("Failed to acquire write lock on subject_permissions".to_string())
308        })?;
309        
310        subject_permissions
311            .entry(subject_id.to_string())
312            .or_insert_with(HashSet::new)
313            .insert(permission_name.to_string());
314        
315        Ok(())
316    }
317    
318    async fn remove_permission_from_subject(&self, permission_name: &str, subject_id: &str) -> Result<(), RbacError> {
319        // Remove permission from subject
320        let mut subject_permissions = self.subject_permissions.write().map_err(|_| {
321            RbacError::StorageError("Failed to acquire write lock on subject_permissions".to_string())
322        })?;
323        
324        if let Some(permissions) = subject_permissions.get_mut(subject_id) {
325            permissions.remove(permission_name);
326        }
327        
328        Ok(())
329    }
330    
331    async fn get_direct_permissions_for_subject(&self, subject_id: &str) -> Result<Vec<Permission>, RbacError> {
332        // Get direct permissions for subject
333        let subject_permissions = self.subject_permissions.read().map_err(|_| {
334            RbacError::StorageError("Failed to acquire read lock on subject_permissions".to_string())
335        })?;
336        
337        let permissions_read = self.permissions.read().map_err(|_| {
338            RbacError::StorageError("Failed to acquire read lock on permissions".to_string())
339        })?;
340        
341        let permission_names = subject_permissions.get(subject_id).map_or_else(
342            || Vec::new(),
343            |names| names.iter().cloned().collect::<Vec<_>>()
344        );
345        
346        let mut result = Vec::new();
347        for name in permission_names {
348            if let Some(permission) = permissions_read.get(&name) {
349                result.push(permission.clone());
350            }
351        }
352        
353        Ok(result)
354    }
355    
356    async fn subject_has_permission(&self, subject_id: &str, permission_name: &str) -> Result<bool, RbacError> {
357        // Check direct permissions
358        let subject_permissions = self.subject_permissions.read().map_err(|_| {
359            RbacError::StorageError("Failed to acquire read lock on subject_permissions".to_string())
360        })?;
361        
362        if let Some(permissions) = subject_permissions.get(subject_id) {
363            if permissions.contains(permission_name) {
364                return Ok(true);
365            }
366        }
367        
368        // Check permissions via roles
369        let subject_roles = self.subject_roles.read().map_err(|_| {
370            RbacError::StorageError("Failed to acquire read lock on subject_roles".to_string())
371        })?;
372        
373        let role_permissions = self.role_permissions.read().map_err(|_| {
374            RbacError::StorageError("Failed to acquire read lock on role_permissions".to_string())
375        })?;
376        
377        if let Some(roles) = subject_roles.get(subject_id) {
378            for role_name in roles {
379                if let Some(permissions) = role_permissions.get(role_name) {
380                    if permissions.contains(permission_name) {
381                        return Ok(true);
382                    }
383                }
384            }
385        }
386        
387        Ok(false)
388    }
389}