Skip to main content

role_system/
core.rs

1//! Core role system implementation.
2//!
3//! This module contains the main implementation of the role-based access control system.
4//! It provides the central `RoleSystem` struct which manages roles, permissions, subjects,
5//! and resources, along with all access control operations.
6//!
7//! # Architecture
8//!
9//! The role system is built around these key components:
10//!
11//! - **Roles**: Named entities with assigned permissions
12//! - **Permissions**: Grant access to perform actions on resource types
13//! - **Subjects**: Users, services, or other entities that are assigned roles
14//! - **Resources**: Objects that are protected by permissions
15//! - **Storage**: Backend for persisting roles and other entities
16//!
17//! # Thread Safety
18//!
19//! The implementation uses `DashMap` for concurrent access to internal data structures,
20//! making it thread-safe for use in multi-threaded applications.
21//!
22//! # Caching
23//!
24//! Permission checks are cached to improve performance for repeated access checks,
25//! with configurable cache TTL and invalidation on role changes.
26
27#[cfg(feature = "audit")]
28use log::{info, warn};
29
30use crate::{
31    app_type::ApplicationType,
32    error::{Error, Result},
33    metrics::{MetricsProvider, RoleSystemMetrics},
34    permission::Permission,
35    resource::Resource,
36    role::{Role, RoleElevation},
37    storage::{MemoryStorage, Storage},
38    subject::Subject,
39};
40use chrono::{DateTime, Utc};
41use dashmap::DashMap;
42use std::collections::{HashMap, HashSet};
43use std::sync::Arc;
44use std::time::{Duration, Instant};
45
46/// The result of an access check.
47#[derive(Debug, Clone, PartialEq)]
48pub enum AccessResult {
49    /// Access is granted.
50    Granted,
51    /// Access is denied with a reason.
52    Denied(String),
53}
54
55impl AccessResult {
56    /// Returns true if access was granted.
57    pub fn is_granted(&self) -> bool {
58        matches!(self, AccessResult::Granted)
59    }
60
61    /// Returns true if access was denied.
62    pub fn is_denied(&self) -> bool {
63        !self.is_granted()
64    }
65
66    /// Returns the denial reason if access was denied.
67    pub fn denial_reason(&self) -> Option<&str> {
68        match self {
69            AccessResult::Denied(reason) => Some(reason),
70            AccessResult::Granted => None,
71        }
72    }
73}
74
75impl From<bool> for AccessResult {
76    fn from(granted: bool) -> Self {
77        if granted {
78            AccessResult::Granted
79        } else {
80            AccessResult::Denied("Access denied".to_string())
81        }
82    }
83}
84
85/// Configuration for the role system.
86#[derive(Debug, Clone)]
87pub struct RoleSystemConfig {
88    /// Maximum depth for role hierarchy traversal.
89    pub max_hierarchy_depth: usize,
90    /// Whether to enable permission caching.
91    pub enable_caching: bool,
92    /// Cache TTL in seconds.
93    pub cache_ttl_seconds: u64,
94    /// Whether to enable audit logging.
95    pub enable_audit: bool,
96}
97
98impl Default for RoleSystemConfig {
99    fn default() -> Self {
100        Self {
101            max_hierarchy_depth: 10,
102            enable_caching: true,
103            cache_ttl_seconds: 300, // 5 minutes
104            enable_audit: true,
105        }
106    }
107}
108
109/// Cached permissions for a user with last updated timestamp.
110#[derive(Debug, Clone)]
111pub struct UserPermissions {
112    /// The computed permission results
113    pub computed_permissions: HashMap<String, AccessResult>,
114    /// When the permissions were last updated
115    pub last_updated: DateTime<Utc>,
116}
117
118impl UserPermissions {
119    /// Create new user permissions cache
120    pub fn new(permissions: HashMap<String, AccessResult>) -> Self {
121        Self {
122            computed_permissions: permissions,
123            last_updated: Utc::now(),
124        }
125    }
126
127    /// Check if the cache entry is expired based on TTL
128    pub fn is_expired(&self, ttl_seconds: u64) -> bool {
129        let now = Utc::now();
130        let ttl = chrono::Duration::seconds(ttl_seconds as i64);
131        now.signed_duration_since(self.last_updated) > ttl
132    }
133}
134
135/// The main role-based access control system.
136pub struct RoleSystem<S = MemoryStorage>
137where
138    S: Storage,
139{
140    storage: S,
141    config: RoleSystemConfig,
142    // Role hierarchy: child -> parents
143    role_hierarchy: DashMap<String, HashSet<String>>,
144    // Subject role assignments
145    subject_roles: DashMap<String, HashSet<String>>,
146    // Temporary role elevations
147    role_elevations: DashMap<String, Vec<RoleElevation>>,
148    // Permission cache: (subject_id, permission_key) -> (UserPermissions)
149    permission_cache: DashMap<(String, String), UserPermissions>,
150    // Metrics collection
151    metrics: Arc<RoleSystemMetrics>,
152}
153
154impl RoleSystem<MemoryStorage> {
155    /// Create a new role system with default configuration and memory storage.
156    pub fn new() -> Self {
157        Self::with_config(RoleSystemConfig::default())
158    }
159
160    /// Create a new role system with custom configuration and memory storage.
161    pub fn with_config(config: RoleSystemConfig) -> Self {
162        Self {
163            storage: MemoryStorage::new(),
164            config,
165            role_hierarchy: DashMap::new(),
166            subject_roles: DashMap::new(),
167            role_elevations: DashMap::new(),
168            permission_cache: DashMap::new(),
169            metrics: Arc::new(RoleSystemMetrics::new()),
170        }
171    }
172}
173
174impl<S> MetricsProvider for RoleSystem<S>
175where
176    S: Storage,
177{
178    fn metrics(&self) -> &RoleSystemMetrics {
179        &self.metrics
180    }
181}
182
183impl<S> RoleSystem<S>
184where
185    S: Storage,
186{
187    /// Create a new role system with custom storage.
188    pub fn with_storage(storage: S, config: RoleSystemConfig) -> Self {
189        Self {
190            storage,
191            config,
192            role_hierarchy: DashMap::new(),
193            subject_roles: DashMap::new(),
194            role_elevations: DashMap::new(),
195            permission_cache: DashMap::new(),
196            metrics: Arc::new(RoleSystemMetrics::new()),
197        }
198    }
199
200    /// Register a new role in the system.
201    pub fn register_role(&mut self, role: Role) -> Result<()> {
202        let role_name = role.name().to_string();
203
204        if self.storage.role_exists(&role_name)? {
205            return Err(Error::RoleAlreadyExists(role_name));
206        }
207
208        self.storage.store_role(role)?;
209
210        #[cfg(feature = "audit")]
211        info!("Role '{role_name}' registered");
212
213        Ok(())
214    }
215
216    /// Get a role by name.
217    pub fn get_role(&self, name: &str) -> Result<Option<Role>> {
218        self.storage.get_role(name)
219    }
220
221    /// Update an existing role.
222    pub fn update_role(&mut self, role: Role) -> Result<()> {
223        let role_name = role.name().to_string();
224
225        if !self.storage.role_exists(&role_name)? {
226            return Err(Error::RoleNotFound(role_name));
227        }
228
229        self.storage.update_role(role)?;
230
231        // Clear permission cache for all subjects with this role
232        self.clear_role_cache(&role_name);
233
234        #[cfg(feature = "audit")]
235        info!("Role '{role_name}' updated");
236
237        Ok(())
238    }
239
240    /// Add role inheritance (child inherits from parent).
241    pub fn add_role_inheritance(&mut self, child: &str, parent: &str) -> Result<()> {
242        // Check that both roles exist
243        if !self.storage.role_exists(child)? {
244            return Err(Error::RoleNotFound(child.to_string()));
245        }
246        if !self.storage.role_exists(parent)? {
247            return Err(Error::RoleNotFound(parent.to_string()));
248        }
249
250        // Check for circular dependencies
251        if self.would_create_cycle(child, parent)? {
252            return Err(Error::CircularDependency(child.to_string()));
253        }
254
255        // Check if adding this inheritance would exceed the maximum depth
256        if self.would_exceed_max_depth(child, parent)? {
257            return Err(Error::MaxDepthExceeded(self.config.max_hierarchy_depth));
258        }
259
260        self.role_hierarchy
261            .entry(child.to_string())
262            .or_default()
263            .insert(parent.to_string());
264
265        #[cfg(feature = "audit")]
266        info!("Role inheritance added: '{child}' inherits from '{parent}'");
267
268        Ok(())
269    }
270
271    /// Remove role inheritance.
272    pub fn remove_role_inheritance(&mut self, child: &str, parent: &str) -> Result<()> {
273        if let Some(mut parents) = self.role_hierarchy.get_mut(child) {
274            parents.remove(parent);
275            if parents.is_empty() {
276                drop(parents);
277                self.role_hierarchy.remove(child);
278            }
279        }
280
281        #[cfg(feature = "audit")]
282        info!("Role inheritance removed: '{child}' no longer inherits from '{parent}'");
283
284        Ok(())
285    }
286
287    /// Assign a role to a subject.
288    pub fn assign_role(&mut self, subject: &Subject, role_name: &str) -> Result<()> {
289        if !self.storage.role_exists(role_name)? {
290            self.metrics.record_error("RoleNotFound");
291            return Err(Error::RoleNotFound(role_name.to_string()));
292        }
293
294        self.subject_roles
295            .entry(subject.id().to_string())
296            .or_default()
297            .insert(role_name.to_string());
298
299        // Clear permission cache for this subject
300        self.clear_subject_cache(subject.id());
301
302        // Record metrics
303        self.metrics.record_role_assignment(subject.id());
304
305        #[cfg(feature = "audit")]
306        info!(
307            "Role '{}' assigned to subject '{}'",
308            role_name,
309            subject.id()
310        );
311
312        Ok(())
313    }
314
315    /// Remove a role from a subject.
316    pub fn remove_role(&mut self, subject: &Subject, role_name: &str) -> Result<()> {
317        if let Some(mut roles) = self.subject_roles.get_mut(subject.id()) {
318            roles.remove(role_name);
319            if roles.is_empty() {
320                drop(roles);
321                self.subject_roles.remove(subject.id());
322            }
323        }
324
325        // Clear permission cache for this subject
326        self.clear_subject_cache(subject.id());
327
328        // Record metrics
329        self.metrics.record_role_removal(subject.id());
330
331        #[cfg(feature = "audit")]
332        info!(
333            "Role '{}' removed from subject '{}'",
334            role_name,
335            subject.id()
336        );
337
338        Ok(())
339    }
340
341    /// Temporarily elevate a subject's role.
342    pub fn elevate_role(
343        &mut self,
344        subject: &Subject,
345        role_name: &str,
346        duration: Option<Duration>,
347    ) -> Result<()> {
348        if !self.storage.role_exists(role_name)? {
349            self.metrics.record_error("RoleNotFound");
350            return Err(Error::RoleNotFound(role_name.to_string()));
351        }
352
353        let elevation = RoleElevation::new(role_name.to_string(), duration);
354
355        self.role_elevations
356            .entry(subject.id().to_string())
357            .or_default()
358            .push(elevation);
359
360        // Clear permission cache for this subject
361        self.clear_subject_cache(subject.id());
362
363        // Record metrics
364        self.metrics.record_role_elevation(subject.id());
365
366        #[cfg(feature = "audit")]
367        info!(
368            "Role '{}' elevated for subject '{}' with duration {:?}",
369            role_name,
370            subject.id(),
371            duration
372        );
373
374        Ok(())
375    }
376
377    /// Check if a subject has a specific permission on a resource.
378    pub fn check_permission(
379        &self,
380        subject: &Subject,
381        action: &str,
382        resource: &Resource,
383    ) -> Result<bool> {
384        self.check_permission_with_context(subject, action, resource, &HashMap::new())
385    }
386
387    /// Check permission with additional context.
388    pub fn check_permission_with_context(
389        &self,
390        subject: &Subject,
391        action: &str,
392        resource: &Resource,
393        context: &HashMap<String, String>,
394    ) -> Result<bool> {
395        let _timer = self.start_timer("permission_check");
396
397        // Create cache key that includes context hash for conditional permissions
398        let context_hash = if context.is_empty() {
399            String::new()
400        } else {
401            // Create a simple hash of the context for caching
402            let mut sorted_context: Vec<_> = context.iter().collect();
403            sorted_context.sort_by_key(|(k, _)| *k);
404            format!("{sorted_context:?}")
405        };
406
407        // The key must identify the whole question: action, resource type, resource id
408        // and context. `{:?}` escapes each field, so field boundaries cannot be forged.
409        let permission_key = format!(
410            "{:?}|{:?}|{:?}|{}",
411            action,
412            resource.resource_type(),
413            resource.id(),
414            context_hash
415        );
416        let cache_key = (subject.id().to_string(), permission_key);
417
418        // Check cache first
419        if self.config.enable_caching {
420            if let Some(entry) = self.permission_cache.get(&cache_key) {
421                let permissions = entry.value();
422
423                // Check if cache entry is still valid based on TTL
424                let cache_still_valid = !permissions.is_expired(self.config.cache_ttl_seconds);
425
426                // Additionally check if any role elevations have been applied since cache entry was created
427                // For simplicity, we assume all elevations are valid and don't check timestamps
428                let elevations_still_valid = true;
429
430                if cache_still_valid && elevations_still_valid {
431                    // Return the cached result for the specific permission
432                    if let Some(result) = permissions.computed_permissions.get(action) {
433                        self.metrics.record_cache_hit();
434                        return Ok(result.is_granted());
435                    }
436                }
437            }
438            self.metrics.record_cache_miss();
439        }
440
441        let result = self.check_permission_internal(subject, action, resource, context)?;
442
443        // Cache the result
444        if self.config.enable_caching {
445            // Get existing permissions or create new
446            let mut user_permissions = if let Some(existing) = self.permission_cache.get(&cache_key)
447            {
448                existing.value().clone()
449            } else {
450                UserPermissions::new(HashMap::new())
451            };
452
453            // Update the permission
454            user_permissions
455                .computed_permissions
456                .insert(action.to_string(), result.into());
457            user_permissions.last_updated = Utc::now();
458
459            // Insert back into cache
460            self.permission_cache.insert(cache_key, user_permissions);
461        }
462
463        #[cfg(feature = "audit")]
464        {
465            let granted = result;
466            if granted {
467                info!(
468                    "Permission GRANTED for subject '{}', action '{}', resource '{}'",
469                    subject.id(),
470                    action,
471                    resource.id()
472                );
473            } else {
474                warn!(
475                    "Permission DENIED for subject '{}', action '{}', resource '{}'",
476                    subject.id(),
477                    action,
478                    resource.id()
479                );
480            }
481        }
482
483        Ok(result)
484    }
485    /// Get all roles assigned to a subject (including inherited roles).
486    pub fn get_subject_roles(&self, subject: &Subject) -> Result<HashSet<String>> {
487        let mut all_roles = HashSet::new();
488
489        // Get directly assigned roles
490        if let Some(direct_roles) = self.subject_roles.get(subject.id()) {
491            for role in direct_roles.iter() {
492                all_roles.insert(role.clone());
493                // Get inherited roles
494                self.collect_inherited_roles(role, &mut all_roles, 0)?;
495            }
496        }
497
498        // Get elevated roles
499        if let Some(elevations) = self.role_elevations.get(subject.id()) {
500            let now = Instant::now();
501            for elevation in elevations.iter() {
502                if !elevation.is_expired(now) {
503                    all_roles.insert(elevation.role_name().to_string());
504                    self.collect_inherited_roles(elevation.role_name(), &mut all_roles, 0)?;
505                }
506            }
507        }
508
509        Ok(all_roles)
510    }
511
512    /// Creates standard roles commonly used in applications.
513    ///
514    /// This method creates the following roles:
515    /// - admin: Full system access
516    /// - editor: Create and edit content
517    /// - viewer: Read-only access
518    /// - guest: Limited read access
519    pub fn create_standard_roles(&mut self) -> Result<()> {
520        #[cfg(feature = "audit")]
521        info!("Creating standard roles: admin, editor, viewer, guest");
522
523        // Admin role with full access
524        let admin_role = Role::new("admin")
525            .with_description("Full system access")
526            .add_permission(Permission::super_admin());
527
528        // Editor role with edit permissions
529        let editor_role = Role::new("editor")
530            .with_description("Create and edit content")
531            .add_permission(Permission::new("create", "*"))
532            .add_permission(Permission::new("read", "*"))
533            .add_permission(Permission::new("update", "*"))
534            .add_permission(Permission::new("delete", "*"));
535
536        // Viewer role with read-only permissions
537        let viewer_role = Role::new("viewer")
538            .with_description("Read-only access")
539            .add_permission(Permission::new("read", "*"));
540
541        // Guest role with limited read permissions
542        let guest_role = Role::new("guest")
543            .with_description("Limited read access")
544            .add_permission(Permission::new("read", "public"));
545
546        // Register the roles
547        self.register_role(admin_role)?;
548        self.register_role(editor_role)?;
549        self.register_role(viewer_role)?;
550        self.register_role(guest_role)?;
551
552        Ok(())
553    }
554    // ApplicationType enum is defined at the module level
555
556    /// Creates roles appropriate for specific application types.
557    pub fn create_application_roles(&mut self, app_type: ApplicationType) -> Result<()> {
558        match app_type {
559            ApplicationType::WebApp => self.create_web_app_roles()?,
560            ApplicationType::ApiService => self.create_api_service_roles()?,
561            ApplicationType::Cms => self.create_cms_roles()?,
562            ApplicationType::Ecommerce => self.create_ecommerce_roles()?,
563            ApplicationType::AdminDashboard => self.create_admin_dashboard_roles()?,
564        }
565
566        Ok(())
567    }
568
569    // Private helper methods for specific application types
570    fn create_web_app_roles(&mut self) -> Result<()> {
571        #[cfg(feature = "audit")]
572        info!("Creating web application roles");
573
574        // User role
575        let user_role = Role::new("user")
576            .with_description("Standard authenticated user")
577            .add_permission(Permission::new("read", "content"))
578            .add_permission(Permission::new("read", "profile"))
579            .add_permission(Permission::new("update", "profile:self"));
580
581        // Premium user role
582        let premium_role = Role::new("premium_user")
583            .with_description("Premium tier user with extra access")
584            .add_permission(Permission::new("read", "content"))
585            .add_permission(Permission::new("read", "profile"))
586            .add_permission(Permission::new("update", "profile:self"))
587            .add_permission(Permission::new("read", "premium_content"));
588
589        // Moderator role
590        let moderator_role = Role::new("moderator")
591            .with_description("Content moderation capabilities")
592            .add_permission(Permission::new("read", "*"))
593            .add_permission(Permission::new("update", "content"))
594            .add_permission(Permission::new("delete", "content"));
595
596        self.register_role(user_role)?;
597        self.register_role(premium_role)?;
598        self.register_role(moderator_role)?;
599
600        // Also create standard roles
601        self.create_standard_roles()?;
602
603        Ok(())
604    }
605
606    fn create_api_service_roles(&mut self) -> Result<()> {
607        #[cfg(feature = "audit")]
608        info!("Creating API service roles");
609
610        // Service role
611        let service_role = Role::new("service")
612            .with_description("Service-to-service API access")
613            .add_permission(Permission::new("read", "api"))
614            .add_permission(Permission::new("create", "api"));
615
616        // Consumer role
617        let consumer_role = Role::new("consumer")
618            .with_description("API consumer with read access")
619            .add_permission(Permission::new("read", "api"));
620
621        // System role
622        let system_role = Role::new("system")
623            .with_description("Internal system operations")
624            .add_permission(Permission::new("*", "system"));
625
626        self.register_role(service_role)?;
627        self.register_role(consumer_role)?;
628        self.register_role(system_role)?;
629
630        // Also create standard roles
631        self.create_standard_roles()?;
632
633        Ok(())
634    }
635
636    fn create_cms_roles(&mut self) -> Result<()> {
637        #[cfg(feature = "audit")]
638        info!("Creating CMS roles");
639
640        // Author role
641        let author_role = Role::new("author")
642            .with_description("Content creator")
643            .add_permission(Permission::new("create", "content"))
644            .add_permission(Permission::new("read", "content"))
645            .add_permission(Permission::new("update", "content:own"))
646            .add_permission(Permission::new("delete", "content:own"));
647
648        // Publisher role
649        let publisher_role = Role::new("publisher")
650            .with_description("Content publisher")
651            .add_permission(Permission::new("read", "content"))
652            .add_permission(Permission::new("update", "content"))
653            .add_permission(Permission::new("publish", "content"));
654
655        self.register_role(author_role)?;
656        self.register_role(publisher_role)?;
657
658        // Also create standard roles
659        self.create_standard_roles()?;
660
661        Ok(())
662    }
663
664    fn create_ecommerce_roles(&mut self) -> Result<()> {
665        #[cfg(feature = "audit")]
666        info!("Creating e-commerce roles");
667
668        // Customer role
669        let customer_role = Role::new("customer")
670            .with_description("Shopping customer")
671            .add_permission(Permission::new("read", "product"))
672            .add_permission(Permission::new("create", "order"))
673            .add_permission(Permission::new("read", "order:own"));
674
675        // Vendor role
676        let vendor_role = Role::new("vendor")
677            .with_description("Product vendor")
678            .add_permission(Permission::new("create", "product"))
679            .add_permission(Permission::new("read", "product:own"))
680            .add_permission(Permission::new("update", "product:own"))
681            .add_permission(Permission::new("delete", "product:own"))
682            .add_permission(Permission::new("read", "order:for_products"));
683
684        self.register_role(customer_role)?;
685        self.register_role(vendor_role)?;
686
687        // Also create standard roles
688        self.create_standard_roles()?;
689
690        Ok(())
691    }
692
693    fn create_admin_dashboard_roles(&mut self) -> Result<()> {
694        #[cfg(feature = "audit")]
695        info!("Creating admin dashboard roles");
696
697        // Support role
698        let support_role = Role::new("support")
699            .with_description("Customer support staff")
700            .add_permission(Permission::new("read", "*"))
701            .add_permission(Permission::new("update", "user:status"));
702
703        // Analytics role
704        let analytics_role = Role::new("analytics")
705            .with_description("Data analysis")
706            .add_permission(Permission::new("read", "*"))
707            .add_permission(Permission::new("export", "data"));
708
709        self.register_role(support_role)?;
710        self.register_role(analytics_role)?;
711
712        // Also create standard roles
713        self.create_standard_roles()?;
714
715        Ok(())
716    }
717
718    // Internal implementation
719
720    fn check_permission_internal(
721        &self,
722        subject: &Subject,
723        action: &str,
724        resource: &Resource,
725        context: &HashMap<String, String>,
726    ) -> Result<bool> {
727        let subject_roles = self.get_subject_roles(subject)?;
728        // An empty resource id means "no specific instance".
729        let instance = Some(resource.id()).filter(|id| !id.is_empty());
730
731        // A deny in any held role wins over a grant in any other.
732        let mut roles = Vec::new();
733        for role_name in subject_roles {
734            if let Some(role) = self.storage.get_role(&role_name)? {
735                if role.denies_with_instance(action, resource.resource_type(), instance, context) {
736                    return Ok(false);
737                }
738                roles.push(role);
739            }
740        }
741
742        for role in roles {
743            if role.has_permission_with_instance(
744                action,
745                resource.resource_type(),
746                instance,
747                context,
748            ) {
749                return Ok(true);
750            }
751        }
752
753        Ok(false)
754    }
755
756    fn collect_inherited_roles(
757        &self,
758        role_name: &str,
759        collected: &mut HashSet<String>,
760        depth: usize,
761    ) -> Result<()> {
762        if depth >= self.config.max_hierarchy_depth {
763            return Err(Error::MaxDepthExceeded(self.config.max_hierarchy_depth));
764        }
765
766        if let Some(parents) = self.role_hierarchy.get(role_name) {
767            for parent in parents.iter() {
768                if collected.insert(parent.clone()) {
769                    self.collect_inherited_roles(parent, collected, depth + 1)?;
770                }
771            }
772        }
773
774        Ok(())
775    }
776
777    fn would_create_cycle(&self, child: &str, parent: &str) -> Result<bool> {
778        let mut visited = HashSet::new();
779        self.has_path(parent, child, &mut visited, 0)
780    }
781
782    fn would_exceed_max_depth(&self, child: &str, parent: &str) -> Result<bool> {
783        // Calculate the depth from the child downwards (how many levels inherit from child)
784        let child_downward_depth = self.calculate_downward_depth(child)?;
785        // Calculate the depth from the parent upwards (how many levels parent inherits from)
786        let parent_upward_depth = self.calculate_upward_depth(parent)?;
787
788        // If child inherits from parent, the total depth would be:
789        // parent_upward_depth + 1 (for the new link) + child_downward_depth
790        let total_depth = parent_upward_depth + 1 + child_downward_depth;
791
792        Ok(total_depth > self.config.max_hierarchy_depth)
793    }
794
795    fn calculate_downward_depth(&self, role_name: &str) -> Result<usize> {
796        let mut max_depth = 0;
797        let mut visited = HashSet::new();
798        self.calculate_downward_depth_recursive(role_name, &mut visited, 0, &mut max_depth)?;
799        Ok(max_depth)
800    }
801
802    fn calculate_downward_depth_recursive(
803        &self,
804        role_name: &str,
805        visited: &mut HashSet<String>,
806        current_depth: usize,
807        max_depth: &mut usize,
808    ) -> Result<()> {
809        if current_depth > self.config.max_hierarchy_depth {
810            return Err(Error::MaxDepthExceeded(self.config.max_hierarchy_depth));
811        }
812
813        if !visited.insert(role_name.to_string()) {
814            return Ok(()); // Already visited
815        }
816
817        *max_depth = std::cmp::max(*max_depth, current_depth);
818
819        // Find all roles that inherit from this role
820        for entry in self.role_hierarchy.iter() {
821            let (child, parents) = (entry.key(), entry.value());
822            if parents.contains(role_name) {
823                self.calculate_downward_depth_recursive(
824                    child,
825                    visited,
826                    current_depth + 1,
827                    max_depth,
828                )?;
829            }
830        }
831
832        Ok(())
833    }
834
835    fn calculate_upward_depth(&self, role_name: &str) -> Result<usize> {
836        let mut max_depth = 0;
837        let mut visited = HashSet::new();
838        self.calculate_upward_depth_recursive(role_name, &mut visited, 0, &mut max_depth)?;
839        Ok(max_depth)
840    }
841
842    fn calculate_upward_depth_recursive(
843        &self,
844        role_name: &str,
845        visited: &mut HashSet<String>,
846        current_depth: usize,
847        max_depth: &mut usize,
848    ) -> Result<()> {
849        if current_depth > self.config.max_hierarchy_depth {
850            return Err(Error::MaxDepthExceeded(self.config.max_hierarchy_depth));
851        }
852
853        if !visited.insert(role_name.to_string()) {
854            return Ok(()); // Already visited
855        }
856
857        *max_depth = std::cmp::max(*max_depth, current_depth);
858
859        if let Some(parents) = self.role_hierarchy.get(role_name) {
860            for parent in parents.iter() {
861                self.calculate_upward_depth_recursive(
862                    parent,
863                    visited,
864                    current_depth + 1,
865                    max_depth,
866                )?;
867            }
868        }
869
870        Ok(())
871    }
872
873    fn has_path(
874        &self,
875        from: &str,
876        to: &str,
877        visited: &mut HashSet<String>,
878        depth: usize,
879    ) -> Result<bool> {
880        if depth >= self.config.max_hierarchy_depth {
881            return Err(Error::MaxDepthExceeded(self.config.max_hierarchy_depth));
882        }
883
884        if from == to {
885            return Ok(true);
886        }
887
888        if !visited.insert(from.to_string()) {
889            return Ok(false); // Already visited
890        }
891
892        if let Some(parents) = self.role_hierarchy.get(from) {
893            for parent in parents.iter() {
894                if self.has_path(parent, to, visited, depth + 1)? {
895                    return Ok(true);
896                }
897            }
898        }
899
900        Ok(false)
901    }
902
903    fn clear_subject_cache(&self, subject_id: &str) {
904        if !self.config.enable_caching {
905            return;
906        }
907
908        let keys_to_remove: Vec<_> = self
909            .permission_cache
910            .iter()
911            .filter(|entry| entry.key().0 == subject_id)
912            .map(|entry| entry.key().clone())
913            .collect();
914
915        for key in keys_to_remove {
916            self.permission_cache.remove(&key);
917        }
918    }
919
920    fn clear_role_cache(&self, _role_name: &str) {
921        if !self.config.enable_caching {
922            return;
923        }
924
925        // We need to clear cache for all subjects that have this role
926        // This is a simplified approach - in a real implementation you might
927        // want to track role assignments more efficiently
928        self.permission_cache.clear();
929    }
930}
931
932impl<S: Storage> RoleSystem<S> {
933    /// Get access to the internal storage backend (for query operations).
934    pub fn storage(&self) -> &S {
935        &self.storage
936    }
937
938    /// Get access to the subject roles mapping (for query operations).
939    pub fn subject_roles(&self) -> &DashMap<String, HashSet<String>> {
940        &self.subject_roles
941    }
942
943    /// Get access to the role hierarchy mapping (for query operations).
944    pub fn role_hierarchy(&self) -> &DashMap<String, HashSet<String>> {
945        &self.role_hierarchy
946    }
947
948    /// Get access to the configuration (for query operations).
949    pub fn config(&self) -> &RoleSystemConfig {
950        &self.config
951    }
952}
953
954// Enhanced API Extensions
955impl<S: Storage> RoleSystem<S> {
956    /// Assign multiple roles to a subject in a single operation.
957    pub fn assign_roles<I>(&mut self, subject: &Subject, roles: I) -> Result<()>
958    where
959        I: IntoIterator,
960        I::Item: AsRef<str>,
961    {
962        for role in roles {
963            self.assign_role(subject, role.as_ref())?;
964        }
965        Ok(())
966    }
967
968    /// Remove multiple roles from a subject in a single operation.
969    pub fn remove_roles<I>(&mut self, subject: &Subject, roles: I) -> Result<()>
970    where
971        I: IntoIterator,
972        I::Item: AsRef<str>,
973    {
974        for role in roles {
975            self.remove_role(subject, role.as_ref())?;
976        }
977        Ok(())
978    }
979
980    /// Check multiple permissions for a subject in a single operation.
981    pub fn check_permissions_batch(
982        &self,
983        subject: &Subject,
984        permissions: &[(&str, &Resource)],
985    ) -> Result<Vec<(String, String, bool)>> {
986        permissions
987            .iter()
988            .map(|(action, resource)| {
989                let result = self.check_permission(subject, action, resource)?;
990                Ok((action.to_string(), resource.id().to_string(), result))
991            })
992            .collect()
993    }
994
995    /// Bulk role assignment with validation.
996    pub fn bulk_assign_roles(
997        &mut self,
998        assignments: &[(Subject, Vec<String>)],
999    ) -> Result<Vec<Result<()>>> {
1000        let mut results = Vec::new();
1001
1002        for (subject, roles) in assignments {
1003            let role_refs: Vec<&str> = roles.iter().map(|s| s.as_str()).collect();
1004            let result = self.assign_roles(subject, role_refs);
1005            results.push(result);
1006        }
1007
1008        Ok(results)
1009    }
1010
1011    /// Get detailed permission summary for a subject.
1012    pub fn get_permission_summary(&self, subject: &Subject) -> Result<PermissionSummary> {
1013        let roles = self.get_subject_roles(subject)?;
1014        let mut permissions = Vec::new();
1015
1016        for role_name in &roles {
1017            if let Some(role) = self.storage.get_role(role_name)? {
1018                for permission in role.permissions().permissions() {
1019                    permissions.push(permission.clone());
1020                }
1021            }
1022        }
1023
1024        let effective_permissions_count = permissions.len();
1025
1026        Ok(PermissionSummary {
1027            subject_id: subject.id().to_string(),
1028            roles: roles.into_iter().collect(),
1029            permissions,
1030            effective_permissions_count,
1031        })
1032    }
1033}
1034
1035/// Summary of a subject's permissions and roles.
1036#[derive(Debug, Clone)]
1037pub struct PermissionSummary {
1038    pub subject_id: String,
1039    pub roles: Vec<String>,
1040    pub permissions: Vec<Permission>,
1041    pub effective_permissions_count: usize,
1042}
1043
1044impl<S> Default for RoleSystem<S>
1045where
1046    S: Storage + Default,
1047{
1048    fn default() -> Self {
1049        Self::with_storage(S::default(), RoleSystemConfig::default())
1050    }
1051}