Skip to main content

role_system/
role.rs

1//! Role definitions and management.
2
3use crate::{
4    error::{Error, Result},
5    permission::{Permission, PermissionSet},
6};
7use std::{
8    collections::HashMap,
9    time::{Duration, Instant},
10};
11use uuid::Uuid;
12
13/// A role hierarchy system for managing role inheritance.
14#[derive(Debug, Clone)]
15#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
16pub struct RoleHierarchy {
17    /// Map of child role ID to parent role ID
18    parent_map: HashMap<String, String>,
19    /// Map of parent role ID to set of child role IDs
20    children_map: HashMap<String, Vec<String>>,
21    /// All roles in the hierarchy
22    roles: HashMap<String, Role>,
23}
24
25impl RoleHierarchy {
26    /// Create a new empty role hierarchy.
27    pub fn new() -> Self {
28        Self {
29            parent_map: HashMap::new(),
30            children_map: HashMap::new(),
31            roles: HashMap::new(),
32        }
33    }
34
35    /// Add a role to the hierarchy.
36    pub fn add_role(&mut self, role: Role) -> Result<()> {
37        let role_id = role.id().to_string();
38        self.roles.insert(role_id, role);
39        Ok(())
40    }
41
42    /// Set a parent-child relationship between roles.
43    pub fn set_parent(&mut self, child_id: &str, parent_id: &str) -> Result<()> {
44        // Verify both roles exist
45        if !self.roles.contains_key(child_id) {
46            return Err(Error::RoleNotFound(child_id.to_string()));
47        }
48        if !self.roles.contains_key(parent_id) {
49            return Err(Error::RoleNotFound(parent_id.to_string()));
50        }
51
52        // Check for circular dependencies
53        if self.would_create_cycle(child_id, parent_id) {
54            return Err(Error::CircularDependency(format!(
55                "{} -> {}",
56                child_id, parent_id
57            )));
58        }
59
60        // Remove any existing parent relationship for this child
61        if let Some(old_parent) = self.parent_map.remove(child_id)
62            && let Some(siblings) = self.children_map.get_mut(&old_parent)
63        {
64            siblings.retain(|id| id != child_id);
65        }
66
67        // Set the new parent relationship
68        self.parent_map
69            .insert(child_id.to_string(), parent_id.to_string());
70        self.children_map
71            .entry(parent_id.to_string())
72            .or_default()
73            .push(child_id.to_string());
74
75        Ok(())
76    }
77
78    /// Get the parent role of a given role.
79    pub fn get_parent(&self, role_id: &str) -> Option<&Role> {
80        self.parent_map
81            .get(role_id)
82            .and_then(|parent_id| self.roles.get(parent_id))
83    }
84
85    /// Get all child roles of a given role.
86    pub fn get_children(&self, role_id: &str) -> Vec<&Role> {
87        self.children_map
88            .get(role_id)
89            .map(|child_ids| {
90                child_ids
91                    .iter()
92                    .filter_map(|id| self.roles.get(id))
93                    .collect()
94            })
95            .unwrap_or_default()
96    }
97
98    /// Get all ancestor roles (parents, grandparents, etc.) of a given role.
99    pub fn get_ancestors(&self, role_id: &str) -> Vec<&Role> {
100        let mut ancestors = Vec::new();
101        let mut current = role_id;
102
103        while let Some(parent_id) = self.parent_map.get(current) {
104            if let Some(parent_role) = self.roles.get(parent_id) {
105                ancestors.push(parent_role);
106                current = parent_id;
107            } else {
108                break;
109            }
110        }
111
112        ancestors
113    }
114
115    /// Get all permissions for a role, including inherited permissions.
116    pub fn get_effective_permissions(&self, role_id: &str) -> Result<PermissionSet> {
117        let role = self
118            .roles
119            .get(role_id)
120            .ok_or_else(|| Error::RoleNotFound(role_id.to_string()))?;
121
122        let mut permissions = role.permissions().clone();
123
124        // Add inherited permissions from ancestors
125        for ancestor in self.get_ancestors(role_id) {
126            for permission in ancestor.permissions().permissions() {
127                permissions.add(permission.clone());
128            }
129        }
130
131        Ok(permissions)
132    }
133
134    /// Check if a role has a specific permission, including inherited permissions.
135    pub fn has_permission(
136        &self,
137        role_id: &str,
138        action: &str,
139        resource: &str,
140        context: &HashMap<String, String>,
141    ) -> Result<bool> {
142        let effective_permissions = self.get_effective_permissions(role_id)?;
143        Ok(effective_permissions.grants(action, resource, context))
144    }
145
146    /// Get a role by ID.
147    pub fn get_role(&self, role_id: &str) -> Option<&Role> {
148        self.roles.get(role_id)
149    }
150
151    /// Get all roles in the hierarchy.
152    pub fn get_all_roles(&self) -> Vec<&Role> {
153        self.roles.values().collect()
154    }
155
156    /// Remove a role from the hierarchy.
157    pub fn remove_role(&mut self, role_id: &str) -> Result<()> {
158        // Remove the role itself
159        if self.roles.remove(role_id).is_none() {
160            return Err(Error::RoleNotFound(role_id.to_string()));
161        }
162
163        // Remove from parent mapping
164        if let Some(parent_id) = self.parent_map.remove(role_id)
165            && let Some(siblings) = self.children_map.get_mut(&parent_id)
166        {
167            siblings.retain(|id| id != role_id);
168        }
169
170        // Remove from children mapping and reparent children
171        if let Some(child_ids) = self.children_map.remove(role_id) {
172            for child_id in child_ids {
173                self.parent_map.remove(&child_id);
174            }
175        }
176
177        Ok(())
178    }
179
180    /// Check if setting a parent would create a circular dependency.
181    fn would_create_cycle(&self, child_id: &str, proposed_parent_id: &str) -> bool {
182        // If the proposed parent is the child itself, it's a cycle
183        if child_id == proposed_parent_id {
184            return true;
185        }
186
187        // Check if the proposed parent is already a descendant of the child
188        let mut current = proposed_parent_id;
189        while let Some(parent_id) = self.parent_map.get(current) {
190            if parent_id == child_id {
191                return true;
192            }
193            current = parent_id;
194        }
195
196        false
197    }
198}
199
200impl Default for RoleHierarchy {
201    fn default() -> Self {
202        Self::new()
203    }
204}
205
206/// A role represents a collection of permissions that can be assigned to subjects.
207#[derive(Debug, Clone)]
208#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
209pub struct Role {
210    /// Unique identifier for the role.
211    id: String,
212    /// Human-readable name of the role.
213    name: String,
214    /// Optional description of the role.
215    description: Option<String>,
216    /// Permissions granted by this role.
217    permissions: PermissionSet,
218    /// Metadata associated with the role.
219    metadata: HashMap<String, String>,
220    /// Whether this role is active.
221    active: bool,
222}
223
224impl Role {
225    /// Create a new role with the given name.
226    pub fn new(name: impl Into<String>) -> Self {
227        let name = name.into();
228        Self {
229            id: Uuid::new_v4().to_string(),
230            name,
231            description: None,
232            permissions: PermissionSet::new(),
233            metadata: HashMap::new(),
234            active: true,
235        }
236    }
237
238    /// Create a new role with a specific ID.
239    pub fn with_id(id: impl Into<String>, name: impl Into<String>) -> Self {
240        let mut role = Self::new(name);
241        role.id = id.into();
242        role
243    }
244
245    /// Get the role's unique identifier.
246    pub fn id(&self) -> &str {
247        &self.id
248    }
249
250    /// Get the role's name.
251    pub fn name(&self) -> &str {
252        &self.name
253    }
254
255    /// Set the role's description.
256    pub fn with_description(mut self, description: impl Into<String>) -> Self {
257        self.description = Some(description.into());
258        self
259    }
260
261    /// Get the role's description.
262    pub fn description(&self) -> Option<&str> {
263        self.description.as_deref()
264    }
265
266    /// Add a permission to this role.
267    pub fn add_permission(mut self, permission: Permission) -> Self {
268        self.permissions.add(permission);
269        self
270    }
271
272    /// Add multiple permissions to this role.
273    pub fn add_permissions(mut self, permissions: impl IntoIterator<Item = Permission>) -> Self {
274        for permission in permissions {
275            self.permissions.add(permission);
276        }
277        self
278    }
279
280    /// Remove a permission from this role.
281    pub fn remove_permission(&mut self, permission: &Permission) {
282        self.permissions.remove(permission);
283    }
284
285    /// Check if this role has a specific permission.
286    pub fn has_permission_exact(&self, permission: &Permission) -> bool {
287        self.permissions.contains(permission)
288    }
289
290    /// Check if this role grants permission for an action on a resource type.
291    pub fn has_permission(
292        &self,
293        action: &str,
294        resource_type: &str,
295        context: &HashMap<String, String>,
296    ) -> bool {
297        if !self.active {
298            return false;
299        }
300        self.permissions.grants(action, resource_type, context)
301    }
302
303    /// Check if this role grants permission for an action on a resource type, honouring
304    /// permission instances. A permission without an instance covers every instance; a
305    /// permission with an instance covers only that instance (or any, if it is `"*"`), and
306    /// never a request that names no instance.
307    pub fn has_permission_with_instance(
308        &self,
309        action: &str,
310        resource_type: &str,
311        instance: Option<&str>,
312        context: &HashMap<String, String>,
313    ) -> bool {
314        if !self.active {
315            return false;
316        }
317        self.permissions
318            .grants_with_instance(action, resource_type, instance, context)
319    }
320
321    /// Whether this role has a deny rule matching the request.
322    pub fn denies_with_instance(
323        &self,
324        action: &str,
325        resource_type: &str,
326        instance: Option<&str>,
327        context: &HashMap<String, String>,
328    ) -> bool {
329        self.active
330            && self
331                .permissions
332                .denies(action, resource_type, instance, context)
333    }
334
335    /// Get all permissions granted by this role.
336    pub fn permissions(&self) -> &PermissionSet {
337        &self.permissions
338    }
339
340    /// Set metadata for this role.
341    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
342        self.metadata.insert(key.into(), value.into());
343        self
344    }
345
346    /// Get metadata value for a key.
347    pub fn metadata(&self, key: &str) -> Option<&str> {
348        self.metadata.get(key).map(|s| s.as_str())
349    }
350
351    /// Get all metadata.
352    pub fn all_metadata(&self) -> &HashMap<String, String> {
353        &self.metadata
354    }
355
356    /// Set whether this role is active.
357    pub fn set_active(&mut self, active: bool) {
358        self.active = active;
359    }
360
361    /// Check if this role is active.
362    pub fn is_active(&self) -> bool {
363        self.active
364    }
365
366    /// Deactivate this role.
367    pub fn deactivate(mut self) -> Self {
368        self.active = false;
369        self
370    }
371
372    /// Merge permissions from another role into this one.
373    pub fn merge_permissions(&mut self, other: &Role) {
374        for permission in other.permissions() {
375            self.permissions.add(permission.clone());
376        }
377    }
378
379    // Optional hierarchy access methods (require hierarchy config to be enabled)
380
381    /// Get the parent role ID if this role has a parent in the hierarchy.
382    ///
383    /// This method provides access to the direct parent relationship, enabling
384    /// use cases like API responses, admin interfaces, and JWT token generation.
385    ///
386    /// Returns `None` if:
387    /// - This role has no parent (it's a root role)
388    /// - Hierarchy access is disabled in configuration
389    ///
390    /// # Example
391    /// ```rust
392    /// use role_system::Role;
393    ///
394    /// let role = Role::new("junior_dev");
395    /// if let Some(parent_id) = role.parent_role_id() {
396    ///     println!("Parent role: {}", parent_id);
397    /// }
398    /// ```
399    ///
400    /// # Note
401    /// This method returns `None` by default to maintain backward compatibility.
402    /// The actual parent relationship is managed by the `RoleHierarchy` system.
403    /// To use this feature, the role must be created through a system that
404    /// tracks hierarchy relationships and enables hierarchy access.
405    pub fn parent_role_id(&self) -> Option<&str> {
406        // By default, roles don't track their parents directly
407        // This is managed by RoleHierarchy and AsyncRoleSystem
408        // Individual Role instances return None for backward compatibility
409        None
410    }
411
412    /// Get the child role IDs if this role has children in the hierarchy.
413    ///
414    /// This method provides access to direct child relationships, useful for
415    /// building admin interfaces, API responses, and permission visualization.
416    ///
417    /// Returns empty vector if:
418    /// - This role has no children
419    /// - Hierarchy access is disabled in configuration
420    ///
421    /// # Example
422    /// ```rust
423    /// use role_system::Role;
424    ///
425    /// let role = Role::new("team_lead");
426    /// let children = role.child_role_ids();
427    /// for child_id in children {
428    ///     println!("Child role: {}", child_id);
429    /// }
430    /// ```
431    ///
432    /// # Note
433    /// This method returns an empty vector by default to maintain backward compatibility.
434    /// The actual child relationships are managed by the `RoleHierarchy` system.
435    /// To use this feature, the role must be created through a system that
436    /// tracks hierarchy relationships and enables hierarchy access.
437    pub fn child_role_ids(&self) -> Vec<&str> {
438        // By default, roles don't track their children directly
439        // This is managed by RoleHierarchy and AsyncRoleSystem
440        // Individual Role instances return empty vector for backward compatibility
441        Vec::new()
442    }
443
444    /// Check if this role is a root role (has no parent).
445    ///
446    /// A root role is one that sits at the top of a hierarchy branch
447    /// and doesn't inherit from any other role.
448    ///
449    /// # Example
450    /// ```rust
451    /// use role_system::Role;
452    ///
453    /// let admin_role = Role::new("admin");
454    /// if admin_role.is_root_role() {
455    ///     println!("This is a top-level role");
456    /// }
457    /// ```
458    ///
459    /// # Note
460    /// Returns `true` by default since individual Role instances don't
461    /// track hierarchy relationships. Use `RoleHierarchy` or `AsyncRoleSystem`
462    /// for actual hierarchy-aware operations.
463    pub fn is_root_role(&self) -> bool {
464        self.parent_role_id().is_none()
465    }
466
467    /// Check if this role is a leaf role (has no children).
468    ///
469    /// A leaf role is one that doesn't have any roles inheriting from it.
470    ///
471    /// # Example
472    /// ```rust
473    /// use role_system::Role;
474    ///
475    /// let intern_role = Role::new("intern");
476    /// if intern_role.is_leaf_role() {
477    ///     println!("This role has no children");
478    /// }
479    /// ```
480    ///
481    /// # Note
482    /// Returns `true` by default since individual Role instances don't
483    /// track hierarchy relationships. Use `RoleHierarchy` or `AsyncRoleSystem`
484    /// for actual hierarchy-aware operations.
485    pub fn is_leaf_role(&self) -> bool {
486        self.child_role_ids().is_empty()
487    }
488
489    /// Get the depth of this role in the hierarchy.
490    ///
491    /// Root roles have depth 0, their children have depth 1, etc.
492    /// This is useful for visualization and API responses.
493    ///
494    /// # Example
495    /// ```rust
496    /// use role_system::Role;
497    ///
498    /// let role = Role::new("senior_dev");
499    /// let depth = role.hierarchy_depth();
500    /// println!("Role depth: {}", depth);
501    /// ```
502    ///
503    /// # Note
504    /// Returns `0` by default since individual Role instances don't
505    /// track hierarchy relationships. Use `RoleHierarchy` or `AsyncRoleSystem`
506    /// for actual hierarchy-aware depth calculation.
507    pub fn hierarchy_depth(&self) -> usize {
508        0
509    }
510
511    /// Get metadata about this role's position in the hierarchy.
512    ///
513    /// Returns a HashMap containing hierarchy-related metadata such as:
514    /// - "parent_count": Number of ancestors
515    /// - "child_count": Number of direct children
516    /// - "descendant_count": Total number of descendants
517    /// - "depth": Depth in hierarchy
518    ///
519    /// # Example
520    /// ```rust
521    /// use role_system::Role;
522    ///
523    /// let role = Role::new("manager");
524    /// let hierarchy_meta = role.hierarchy_metadata();
525    /// if let Some(depth) = hierarchy_meta.get("depth") {
526    ///     println!("Hierarchy depth: {}", depth);
527    /// }
528    /// ```
529    ///
530    /// # Note
531    /// Returns minimal metadata by default. Use `RoleHierarchy` or `AsyncRoleSystem`
532    /// for complete hierarchy metadata.
533    pub fn hierarchy_metadata(&self) -> HashMap<String, String> {
534        let mut metadata = HashMap::new();
535        metadata.insert("depth".to_string(), "0".to_string());
536        metadata.insert("parent_count".to_string(), "0".to_string());
537        metadata.insert("child_count".to_string(), "0".to_string());
538        metadata.insert("descendant_count".to_string(), "0".to_string());
539        metadata.insert("is_root".to_string(), "true".to_string());
540        metadata.insert("is_leaf".to_string(), "true".to_string());
541        metadata
542    }
543}
544
545/// A temporary role elevation for a subject.
546#[derive(Debug, Clone)]
547#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
548pub struct RoleElevation {
549    /// The role being elevated to.
550    role_name: String,
551    /// When the elevation was created.
552    #[cfg_attr(feature = "persistence", serde(with = "instant_serde"))]
553    created_at: Instant,
554    /// How long the elevation lasts (None for permanent).
555    duration: Option<Duration>,
556    /// Reason for the elevation.
557    reason: Option<String>,
558}
559
560impl RoleElevation {
561    /// Create a new role elevation.
562    pub fn new(role_name: String, duration: Option<Duration>) -> Self {
563        Self {
564            role_name,
565            created_at: Instant::now(),
566            duration,
567            reason: None,
568        }
569    }
570
571    /// Create a role elevation with a reason.
572    pub fn with_reason(role_name: String, duration: Option<Duration>, reason: String) -> Self {
573        Self {
574            role_name,
575            created_at: Instant::now(),
576            duration,
577            reason: Some(reason),
578        }
579    }
580
581    /// Get the role name being elevated to.
582    pub fn role_name(&self) -> &str {
583        &self.role_name
584    }
585
586    /// Get when the elevation was created.
587    pub fn created_at(&self) -> Instant {
588        self.created_at
589    }
590
591    /// Get the duration of the elevation.
592    pub fn duration(&self) -> Option<Duration> {
593        self.duration
594    }
595
596    /// Get the reason for the elevation.
597    pub fn reason(&self) -> Option<&str> {
598        self.reason.as_deref()
599    }
600
601    /// Check if the elevation has expired.
602    pub fn is_expired(&self, now: Instant) -> bool {
603        if let Some(duration) = self.duration {
604            now.duration_since(self.created_at) > duration
605        } else {
606            false // Permanent elevation
607        }
608    }
609
610    /// Get the time remaining for this elevation.
611    pub fn time_remaining(&self, now: Instant) -> Option<Duration> {
612        if let Some(duration) = self.duration {
613            let elapsed = now.duration_since(self.created_at);
614            if elapsed < duration {
615                Some(duration - elapsed)
616            } else {
617                Some(Duration::ZERO)
618            }
619        } else {
620            None // Permanent elevation
621        }
622    }
623}
624
625/// Builder for creating roles with a fluent API.
626#[derive(Debug, Default)]
627pub struct RoleBuilder {
628    name: Option<String>,
629    description: Option<String>,
630    permissions: Vec<Permission>,
631    metadata: HashMap<String, String>,
632    active: bool,
633}
634
635impl RoleBuilder {
636    /// Create a new role builder.
637    pub fn new() -> Self {
638        Self {
639            active: true,
640            ..Default::default()
641        }
642    }
643
644    /// Set the role name.
645    pub fn name(mut self, name: impl Into<String>) -> Self {
646        self.name = Some(name.into());
647        self
648    }
649
650    /// Set the role description.
651    pub fn description(mut self, description: impl Into<String>) -> Self {
652        self.description = Some(description.into());
653        self
654    }
655
656    /// Add a permission to the role.
657    pub fn permission(mut self, permission: Permission) -> Self {
658        self.permissions.push(permission);
659        self
660    }
661
662    /// Add multiple permissions to the role.
663    pub fn permissions(mut self, permissions: impl IntoIterator<Item = Permission>) -> Self {
664        self.permissions.extend(permissions);
665        self
666    }
667
668    /// Add permissions with fluent allow syntax.
669    ///
670    /// # Example
671    /// ```rust
672    /// use role_system::role::RoleBuilder;
673    /// let role = RoleBuilder::new()
674    ///     .name("admin")
675    ///     .allow("users", ["create", "read", "update", "delete"])
676    ///     .allow("roles", ["read", "assign"])
677    ///     .build().unwrap();
678    /// ```
679    pub fn allow<I, S>(mut self, resource: impl Into<String>, actions: I) -> Self
680    where
681        I: IntoIterator<Item = S>,
682        S: Into<String>,
683    {
684        let resource = resource.into();
685        for action in actions {
686            self.permissions
687                .push(Permission::new(action.into(), resource.clone()));
688        }
689        self
690    }
691
692    /// Add deny rules. A deny overrides every grant of the same action and resource, including
693    /// grants in other roles the subject holds.
694    ///
695    /// # Example
696    /// ```rust
697    /// use role_system::role::RoleBuilder;
698    /// let role = RoleBuilder::new()
699    ///     .name("restricted_admin")
700    ///     .allow("users", ["read", "update"])
701    ///     .deny("system", ["shutdown"])
702    ///     .build().unwrap();
703    /// ```
704    pub fn deny<I, S>(mut self, resource: impl Into<String>, actions: I) -> Self
705    where
706        I: IntoIterator<Item = S>,
707        S: Into<String>,
708    {
709        let resource = resource.into();
710        for action in actions {
711            self.permissions
712                .push(Permission::deny(action.into(), resource.clone()));
713        }
714        self
715    }
716
717    /// Add permissions with conditional access.
718    ///
719    /// # Example
720    /// ```rust
721    /// use role_system::role::RoleBuilder;
722    /// let role = RoleBuilder::new()
723    ///     .name("user")
724    ///     .allow_when("profile", ["update"], |ctx|
725    ///         ctx.get("user_id") == ctx.get("target_id"))
726    ///     .build().unwrap();
727    /// ```
728    pub fn allow_when<I, S, F>(
729        mut self,
730        resource: impl Into<String>,
731        actions: I,
732        condition: F,
733    ) -> Self
734    where
735        I: IntoIterator<Item = S>,
736        S: Into<String>,
737        F: Fn(&std::collections::HashMap<String, String>) -> bool + Send + Sync + 'static + Clone,
738    {
739        let resource = resource.into();
740        for action in actions {
741            let conditional_permission =
742                Permission::with_condition(action.into(), resource.clone(), condition.clone());
743            self.permissions.push(conditional_permission);
744        }
745        self
746    }
747
748    /// Add metadata to the role.
749    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
750        self.metadata.insert(key.into(), value.into());
751        self
752    }
753
754    /// Set whether the role is active.
755    pub fn active(mut self, active: bool) -> Self {
756        self.active = active;
757        self
758    }
759
760    /// Build the role.
761    pub fn build(self) -> Result<Role> {
762        let name = self
763            .name
764            .ok_or_else(|| Error::InvalidConfiguration("Role name is required".to_string()))?;
765
766        let mut role = Role::new(name);
767
768        if let Some(description) = self.description {
769            role = role.with_description(description);
770        }
771
772        for permission in self.permissions {
773            role = role.add_permission(permission);
774        }
775
776        for (key, value) in self.metadata {
777            role = role.with_metadata(key, value);
778        }
779
780        role.set_active(self.active);
781
782        Ok(role)
783    }
784}
785
786// Helper module for serializing Instant with serde
787#[cfg(feature = "persistence")]
788mod instant_serde {
789    use serde::{Deserialize, Deserializer, Serialize, Serializer};
790    use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
791
792    /// The creation time is saved as wall-clock nanoseconds since the Unix epoch: now minus the
793    /// elevation's age.
794    pub fn serialize<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
795    where
796        S: Serializer,
797    {
798        let age = Instant::now().saturating_duration_since(*instant);
799        let now = SystemTime::now()
800            .duration_since(UNIX_EPOCH)
801            .map_err(serde::ser::Error::custom)?;
802        now.saturating_sub(age).as_nanos().serialize(serializer)
803    }
804
805    /// The saved wall-clock time is turned back into an age, so time that passed while the
806    /// process was not running counts against the elevation. A time in the future (a clock
807    /// that went backwards) is an age of zero. An age too large for the monotonic clock to
808    /// represent is clamped to the largest it can, which is still older than any elevation
809    /// that could have been made before it.
810    pub fn deserialize<'de, D>(deserializer: D) -> Result<Instant, D::Error>
811    where
812        D: Deserializer<'de>,
813    {
814        let nanos = u128::deserialize(deserializer)?;
815        let created = Duration::new(
816            u64::try_from(nanos / 1_000_000_000).map_err(serde::de::Error::custom)?,
817            (nanos % 1_000_000_000) as u32,
818        );
819        let now = SystemTime::now()
820            .duration_since(UNIX_EPOCH)
821            .map_err(serde::de::Error::custom)?;
822        let mut age = now.saturating_sub(created);
823        let instant_now = Instant::now();
824        loop {
825            if let Some(i) = instant_now.checked_sub(age) {
826                return Ok(i);
827            }
828            if age.is_zero() {
829                return Ok(instant_now);
830            }
831            age /= 2;
832        }
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839    use crate::permission::Permission;
840
841    #[test]
842    fn test_role_creation() {
843        let role = Role::new("admin")
844            .with_description("Administrator role")
845            .add_permission(Permission::new("read", "documents"))
846            .add_permission(Permission::new("write", "documents"));
847
848        assert_eq!(role.name(), "admin");
849        assert_eq!(role.description(), Some("Administrator role"));
850        assert_eq!(role.permissions().len(), 2);
851        assert!(role.is_active());
852    }
853
854    #[test]
855    fn test_role_permissions() {
856        let role = Role::new("reader").add_permission(Permission::new("read", "documents"));
857
858        let context = HashMap::new();
859        assert!(role.has_permission("read", "documents", &context));
860        assert!(!role.has_permission("write", "documents", &context));
861    }
862
863    #[test]
864    fn test_role_builder() {
865        let role = RoleBuilder::new()
866            .name("test-role")
867            .description("A test role")
868            .permission(Permission::new("read", "documents"))
869            .metadata("department", "IT")
870            .active(true)
871            .build()
872            .unwrap();
873
874        assert_eq!(role.name(), "test-role");
875        assert_eq!(role.description(), Some("A test role"));
876        assert_eq!(role.metadata("department"), Some("IT"));
877        assert!(role.is_active());
878    }
879
880    #[test]
881    fn test_role_elevation() {
882        let elevation = RoleElevation::new("admin".to_string(), Some(Duration::from_secs(3600)));
883
884        assert_eq!(elevation.role_name(), "admin");
885        assert_eq!(elevation.duration(), Some(Duration::from_secs(3600)));
886        assert!(!elevation.is_expired(Instant::now()));
887    }
888
889    #[test]
890    fn test_inactive_role_permissions() {
891        let mut role = Role::new("inactive").add_permission(Permission::new("read", "documents"));
892
893        role.set_active(false);
894
895        let context = HashMap::new();
896        assert!(!role.has_permission("read", "documents", &context));
897    }
898}