role-system 1.1.1

A flexible and powerful role-based access control (RBAC) library for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Storage abstractions for persisting role system data.

use crate::{error::Result, role::Role};
use dashmap::DashMap;
use std::sync::Arc;

/// Trait for storing and retrieving role system data.
pub trait Storage: Send + Sync {
    /// Store a role.
    fn store_role(&mut self, role: Role) -> Result<()>;

    /// Get a role by name.
    fn get_role(&self, name: &str) -> Result<Option<Role>>;

    /// Check if a role exists.
    fn role_exists(&self, name: &str) -> Result<bool>;

    /// Delete a role.
    fn delete_role(&mut self, name: &str) -> Result<bool>;

    /// List all role names.
    fn list_roles(&self) -> Result<Vec<String>>;

    /// Update an existing role.
    fn update_role(&mut self, role: Role) -> Result<()>;

    /// Get the number of stored roles.
    fn role_count(&self) -> usize {
        // Default implementation that tries to count via list_roles
        self.list_roles().map(|roles| roles.len()).unwrap_or(0)
    }
}

/// In-memory storage implementation using DashMap for thread safety.
#[derive(Debug, Default, Clone)]
pub struct MemoryStorage {
    roles: Arc<DashMap<String, Role>>,
}

impl MemoryStorage {
    /// Create a new memory storage instance.
    pub fn new() -> Self {
        Self {
            roles: Arc::new(DashMap::new()),
        }
    }

    /// Get the number of stored roles.
    pub fn role_count(&self) -> usize {
        self.roles.len()
    }

    /// Clear all stored data.
    pub fn clear(&mut self) {
        self.roles.clear();
    }
}

impl Storage for MemoryStorage {
    fn store_role(&mut self, role: Role) -> Result<()> {
        let name = role.name().to_string();
        self.roles.insert(name, role);
        Ok(())
    }

    fn get_role(&self, name: &str) -> Result<Option<Role>> {
        Ok(self.roles.get(name).map(|r| r.clone()))
    }

    fn role_exists(&self, name: &str) -> Result<bool> {
        Ok(self.roles.contains_key(name))
    }

    fn delete_role(&mut self, name: &str) -> Result<bool> {
        Ok(self.roles.remove(name).is_some())
    }

    fn list_roles(&self) -> Result<Vec<String>> {
        Ok(self.roles.iter().map(|entry| entry.key().clone()).collect())
    }

    fn update_role(&mut self, role: Role) -> Result<()> {
        let name = role.name().to_string();
        self.roles.insert(name, role);
        Ok(())
    }
}

/// File-based storage implementation (requires persistence feature).
#[cfg(feature = "persistence")]
pub mod file_storage {
    use super::*;
    use crate::error::Error;
    use std::{
        collections::HashMap,
        fs::{File, OpenOptions},
        io::{BufReader, BufWriter},
        path::{Path, PathBuf},
        sync::RwLock,
    };

    /// File-based storage that persists roles to JSON files.
    #[derive(Debug)]
    pub struct FileStorage {
        storage_path: PathBuf,
        roles: Arc<RwLock<HashMap<String, Role>>>,
    }

    impl FileStorage {
        /// Create a new file storage instance.
        pub fn new(storage_path: impl AsRef<Path>) -> Result<Self> {
            let storage_path = storage_path.as_ref().to_path_buf();

            // Create directory if it doesn't exist
            if let Some(parent) = storage_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    Error::Storage(format!("Failed to create storage directory: {}", e))
                })?;
            }

            let mut storage = Self {
                storage_path,
                roles: Arc::new(RwLock::new(HashMap::new())),
            };

            // Load existing data if the file exists
            storage.load_from_disk()?;

            Ok(storage)
        }

        /// Load roles from disk.
        fn load_from_disk(&mut self) -> Result<()> {
            if !self.storage_path.exists() {
                return Ok(());
            }

            let file = File::open(&self.storage_path)
                .map_err(|e| Error::Storage(format!("Failed to open storage file: {}", e)))?;

            let reader = BufReader::new(file);
            let roles: HashMap<String, Role> = serde_json::from_reader(reader)?;

            *self
                .roles
                .write()
                .map_err(|e| Error::Storage(format!("Failed to acquire write lock: {}", e)))? =
                roles;
            Ok(())
        }

        /// Save roles to disk.
        fn save_to_disk(&self) -> Result<()> {
            let file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&self.storage_path)
                .map_err(|e| Error::Storage(format!("Failed to create storage file: {}", e)))?;

            let writer = BufWriter::new(file);
            let roles = self
                .roles
                .read()
                .map_err(|e| Error::Storage(format!("Failed to acquire read lock: {}", e)))?;
            serde_json::to_writer_pretty(writer, &*roles)?;
            Ok(())
        }

        /// Get the storage file path.
        pub fn storage_path(&self) -> &Path {
            &self.storage_path
        }

        /// Get the number of stored roles.
        pub fn role_count(&self) -> usize {
            self.roles.read().map(|roles| roles.len()).unwrap_or(0)
        }
    }

    impl Storage for FileStorage {
        fn store_role(&mut self, role: Role) -> Result<()> {
            let name = role.name().to_string();
            self.roles
                .write()
                .map_err(|e| Error::Storage(format!("Failed to acquire write lock: {}", e)))?
                .insert(name, role);
            self.save_to_disk()
        }

        fn get_role(&self, name: &str) -> Result<Option<Role>> {
            let roles = self
                .roles
                .read()
                .map_err(|e| Error::Storage(format!("Failed to acquire read lock: {}", e)))?;
            Ok(roles.get(name).cloned())
        }

        fn role_exists(&self, name: &str) -> Result<bool> {
            let roles = self
                .roles
                .read()
                .map_err(|e| Error::Storage(format!("Failed to acquire read lock: {}", e)))?;
            Ok(roles.contains_key(name))
        }

        fn delete_role(&mut self, name: &str) -> Result<bool> {
            let removed = self
                .roles
                .write()
                .map_err(|e| Error::Storage(format!("Failed to acquire write lock: {}", e)))?
                .remove(name)
                .is_some();
            if removed {
                self.save_to_disk()?;
            }
            Ok(removed)
        }

        fn list_roles(&self) -> Result<Vec<String>> {
            let roles = self
                .roles
                .read()
                .map_err(|e| Error::Storage(format!("Failed to acquire read lock: {}", e)))?;
            Ok(roles.keys().cloned().collect())
        }

        fn update_role(&mut self, role: Role) -> Result<()> {
            let name = role.name().to_string();
            self.roles
                .write()
                .map_err(|e| Error::Storage(format!("Failed to acquire write lock: {}", e)))?
                .insert(name, role);
            self.save_to_disk()
        }
    }
}

#[cfg(feature = "persistence")]
pub use file_storage::FileStorage;

/// Composite storage that can combine multiple storage backends.
pub struct CompositeStorage {
    primary: Box<dyn Storage>,
    secondary: Option<Box<dyn Storage>>,
}

impl CompositeStorage {
    /// Create a new composite storage with primary storage.
    pub fn new(primary: Box<dyn Storage>) -> Self {
        Self {
            primary,
            secondary: None,
        }
    }

    /// Add a secondary storage backend.
    pub fn with_secondary(mut self, secondary: Box<dyn Storage>) -> Self {
        self.secondary = Some(secondary);
        self
    }
}

impl Storage for CompositeStorage {
    fn store_role(&mut self, role: Role) -> Result<()> {
        // Store in primary first
        self.primary.store_role(role.clone())?;

        // Then store in secondary if available
        if let Some(secondary) = &mut self.secondary {
            secondary.store_role(role)?;
        }

        Ok(())
    }

    fn get_role(&self, name: &str) -> Result<Option<Role>> {
        // Try primary first
        match self.primary.get_role(name)? {
            Some(role) => Ok(Some(role)),
            None => {
                // Fallback to secondary
                if let Some(secondary) = &self.secondary {
                    secondary.get_role(name)
                } else {
                    Ok(None)
                }
            }
        }
    }

    fn role_exists(&self, name: &str) -> Result<bool> {
        if self.primary.role_exists(name)? {
            Ok(true)
        } else if let Some(secondary) = &self.secondary {
            secondary.role_exists(name)
        } else {
            Ok(false)
        }
    }

    fn delete_role(&mut self, name: &str) -> Result<bool> {
        let mut deleted = false;

        if self.primary.delete_role(name)? {
            deleted = true;
        }

        if let Some(secondary) = &mut self.secondary
            && secondary.delete_role(name)?
        {
            deleted = true;
        }

        Ok(deleted)
    }

    fn list_roles(&self) -> Result<Vec<String>> {
        let mut roles = self.primary.list_roles()?;

        if let Some(secondary) = &self.secondary {
            let secondary_roles = secondary.list_roles()?;
            for role in secondary_roles {
                if !roles.contains(&role) {
                    roles.push(role);
                }
            }
        }

        roles.sort();
        Ok(roles)
    }

    fn update_role(&mut self, role: Role) -> Result<()> {
        self.primary.update_role(role.clone())?;

        if let Some(secondary) = &mut self.secondary {
            secondary.update_role(role)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{permission::Permission, role::Role};

    #[test]
    fn test_memory_storage() {
        let mut storage = MemoryStorage::new();

        let role = Role::new("test-role").add_permission(Permission::new("read", "documents"));

        // Store role
        storage
            .store_role(role.clone())
            .expect("Failed to store role");
        assert_eq!(storage.role_count(), 1);

        // Check existence
        assert!(
            storage
                .role_exists("test-role")
                .expect("Failed to check role existence")
        );
        assert!(
            !storage
                .role_exists("non-existent")
                .expect("Failed to check role existence")
        );

        // Get role
        let retrieved = storage
            .get_role("test-role")
            .expect("Failed to get role")
            .expect("Role should exist");
        assert_eq!(retrieved.name(), "test-role");

        // List roles
        let roles = storage.list_roles().expect("Failed to list roles");
        assert_eq!(roles.len(), 1);
        assert!(roles.contains(&"test-role".to_string()));

        // Delete role
        assert!(
            storage
                .delete_role("test-role")
                .expect("Failed to delete role")
        );
        assert!(
            !storage
                .role_exists("test-role")
                .expect("Failed to check role existence")
        );
        assert_eq!(storage.role_count(), 0);
    }

    #[cfg(feature = "persistence")]
    #[test]
    fn test_file_storage() {
        use std::env;

        let temp_dir = env::temp_dir();
        let storage_path = temp_dir.join("test_roles.json");

        // Clean up any existing file
        let _ = std::fs::remove_file(&storage_path);

        {
            let mut storage =
                FileStorage::new(&storage_path).expect("Failed to create file storage");

            let role =
                Role::new("file-test-role").add_permission(Permission::new("read", "documents"));

            // Store role
            storage
                .store_role(role.clone())
                .expect("Failed to store role");
            assert_eq!(storage.role_count(), 1);

            // Verify file was created
            assert!(storage_path.exists());
        }

        // Create new storage instance to test persistence
        {
            let storage = FileStorage::new(&storage_path).expect("Failed to create file storage");
            assert_eq!(storage.role_count(), 1);

            let retrieved = storage
                .get_role("file-test-role")
                .expect("Failed to get role")
                .expect("Role should exist");
            assert_eq!(retrieved.name(), "file-test-role");
        }

        // Clean up
        let _ = std::fs::remove_file(&storage_path);
    }

    #[test]
    fn test_composite_storage() {
        let primary = Box::new(MemoryStorage::new());
        let secondary = Box::new(MemoryStorage::new());

        let mut storage = CompositeStorage::new(primary).with_secondary(secondary);

        let role = Role::new("composite-test").add_permission(Permission::new("read", "documents"));

        // Store in both
        storage
            .store_role(role.clone())
            .expect("Failed to store role");

        // Should be able to retrieve
        let retrieved = storage
            .get_role("composite-test")
            .expect("Failed to get role")
            .expect("Role should exist");
        assert_eq!(retrieved.name(), "composite-test");

        // Should appear in list
        let roles = storage.list_roles().expect("Failed to list roles");
        assert!(roles.contains(&"composite-test".to_string()));
    }
}