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