1use 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#[derive(Debug, Clone)]
15#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
16pub struct RoleHierarchy {
17 parent_map: HashMap<String, String>,
19 children_map: HashMap<String, Vec<String>>,
21 roles: HashMap<String, Role>,
23}
24
25impl RoleHierarchy {
26 pub fn new() -> Self {
28 Self {
29 parent_map: HashMap::new(),
30 children_map: HashMap::new(),
31 roles: HashMap::new(),
32 }
33 }
34
35 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 pub fn set_parent(&mut self, child_id: &str, parent_id: &str) -> Result<()> {
44 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 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 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 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 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 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 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 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 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 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 pub fn get_role(&self, role_id: &str) -> Option<&Role> {
148 self.roles.get(role_id)
149 }
150
151 pub fn get_all_roles(&self) -> Vec<&Role> {
153 self.roles.values().collect()
154 }
155
156 pub fn remove_role(&mut self, role_id: &str) -> Result<()> {
158 if self.roles.remove(role_id).is_none() {
160 return Err(Error::RoleNotFound(role_id.to_string()));
161 }
162
163 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 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 fn would_create_cycle(&self, child_id: &str, proposed_parent_id: &str) -> bool {
182 if child_id == proposed_parent_id {
184 return true;
185 }
186
187 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#[derive(Debug, Clone)]
208#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
209pub struct Role {
210 id: String,
212 name: String,
214 description: Option<String>,
216 permissions: PermissionSet,
218 metadata: HashMap<String, String>,
220 active: bool,
222}
223
224impl Role {
225 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 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 pub fn id(&self) -> &str {
247 &self.id
248 }
249
250 pub fn name(&self) -> &str {
252 &self.name
253 }
254
255 pub fn with_description(mut self, description: impl Into<String>) -> Self {
257 self.description = Some(description.into());
258 self
259 }
260
261 pub fn description(&self) -> Option<&str> {
263 self.description.as_deref()
264 }
265
266 pub fn add_permission(mut self, permission: Permission) -> Self {
268 self.permissions.add(permission);
269 self
270 }
271
272 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 pub fn remove_permission(&mut self, permission: &Permission) {
282 self.permissions.remove(permission);
283 }
284
285 pub fn has_permission_exact(&self, permission: &Permission) -> bool {
287 self.permissions.contains(permission)
288 }
289
290 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 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 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 pub fn permissions(&self) -> &PermissionSet {
337 &self.permissions
338 }
339
340 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 pub fn metadata(&self, key: &str) -> Option<&str> {
348 self.metadata.get(key).map(|s| s.as_str())
349 }
350
351 pub fn all_metadata(&self) -> &HashMap<String, String> {
353 &self.metadata
354 }
355
356 pub fn set_active(&mut self, active: bool) {
358 self.active = active;
359 }
360
361 pub fn is_active(&self) -> bool {
363 self.active
364 }
365
366 pub fn deactivate(mut self) -> Self {
368 self.active = false;
369 self
370 }
371
372 pub fn merge_permissions(&mut self, other: &Role) {
374 for permission in other.permissions() {
375 self.permissions.add(permission.clone());
376 }
377 }
378
379 pub fn parent_role_id(&self) -> Option<&str> {
406 None
410 }
411
412 pub fn child_role_ids(&self) -> Vec<&str> {
438 Vec::new()
442 }
443
444 pub fn is_root_role(&self) -> bool {
464 self.parent_role_id().is_none()
465 }
466
467 pub fn is_leaf_role(&self) -> bool {
486 self.child_role_ids().is_empty()
487 }
488
489 pub fn hierarchy_depth(&self) -> usize {
508 0
509 }
510
511 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#[derive(Debug, Clone)]
547#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
548pub struct RoleElevation {
549 role_name: String,
551 #[cfg_attr(feature = "persistence", serde(with = "instant_serde"))]
553 created_at: Instant,
554 duration: Option<Duration>,
556 reason: Option<String>,
558}
559
560impl RoleElevation {
561 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 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 pub fn role_name(&self) -> &str {
583 &self.role_name
584 }
585
586 pub fn created_at(&self) -> Instant {
588 self.created_at
589 }
590
591 pub fn duration(&self) -> Option<Duration> {
593 self.duration
594 }
595
596 pub fn reason(&self) -> Option<&str> {
598 self.reason.as_deref()
599 }
600
601 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 }
608 }
609
610 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 }
622 }
623}
624
625#[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 pub fn new() -> Self {
638 Self {
639 active: true,
640 ..Default::default()
641 }
642 }
643
644 pub fn name(mut self, name: impl Into<String>) -> Self {
646 self.name = Some(name.into());
647 self
648 }
649
650 pub fn description(mut self, description: impl Into<String>) -> Self {
652 self.description = Some(description.into());
653 self
654 }
655
656 pub fn permission(mut self, permission: Permission) -> Self {
658 self.permissions.push(permission);
659 self
660 }
661
662 pub fn permissions(mut self, permissions: impl IntoIterator<Item = Permission>) -> Self {
664 self.permissions.extend(permissions);
665 self
666 }
667
668 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 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 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 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 pub fn active(mut self, active: bool) -> Self {
756 self.active = active;
757 self
758 }
759
760 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#[cfg(feature = "persistence")]
788mod instant_serde {
789 use serde::{Deserialize, Deserializer, Serialize, Serializer};
790 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
791
792 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 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}