1#[derive(Debug, Clone)]
19pub struct AbacPolicy {
20 pub attributes: HashMap<String, serde_json::Value>,
21 pub rules: Vec<AbacRule>,
22}
23
24#[derive(Debug, Clone)]
25pub struct AbacRule {
26 pub attribute: String,
27 pub expected_value: serde_json::Value,
28 pub permission: Permission,
29}
30
31impl Default for AbacPolicy {
32 fn default() -> Self {
33 Self::new()
34 }
35}
36
37impl AbacPolicy {
38 pub fn new() -> Self {
40 Self {
41 attributes: HashMap::new(),
42 rules: Vec::new(),
43 }
44 }
45
46 pub fn with_attribute(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
48 self.attributes.insert(key.into(), value);
49 self
50 }
51
52 pub fn with_attributes<I, K>(mut self, attributes: I) -> Self
54 where
55 I: IntoIterator<Item = (K, serde_json::Value)>,
56 K: Into<String>,
57 {
58 for (key, value) in attributes {
59 self.attributes.insert(key.into(), value);
60 }
61 self
62 }
63
64 pub fn with_rule(
66 mut self,
67 attribute: impl Into<String>,
68 expected_value: serde_json::Value,
69 permission: Permission,
70 ) -> Self {
71 self.rules.push(AbacRule {
72 attribute: attribute.into(),
73 expected_value,
74 permission,
75 });
76 self
77 }
78
79 pub fn with_rules<I>(mut self, rules: I) -> Self
81 where
82 I: IntoIterator<Item = AbacRule>,
83 {
84 self.rules.extend(rules);
85 self
86 }
87}
88
89#[derive(Debug, Clone)]
94pub struct Delegation {
95 pub delegator: String,
96 pub delegatee: String,
97 pub permissions: HashSet<Permission>,
98 pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
99}
100
101impl Delegation {
102 pub fn new(delegator: impl Into<String>, delegatee: impl Into<String>) -> Self {
104 Self {
105 delegator: delegator.into(),
106 delegatee: delegatee.into(),
107 permissions: HashSet::new(),
108 expires_at: None,
109 }
110 }
111
112 pub fn with_permissions<I>(mut self, permissions: I) -> Self
114 where
115 I: IntoIterator<Item = Permission>,
116 {
117 self.permissions.extend(permissions);
118 self
119 }
120
121 pub fn with_permission(mut self, permission: Permission) -> Self {
123 self.permissions.insert(permission);
124 self
125 }
126
127 pub fn with_expiry(mut self, expires_at: chrono::DateTime<chrono::Utc>) -> Self {
129 self.expires_at = Some(expires_at);
130 self
131 }
132
133 pub fn permanent(mut self) -> Self {
135 self.expires_at = None;
136 self
137 }
138}
139
140impl PermissionChecker {
141 pub fn check_advanced_permission(
156 &self,
157 user_id: &str,
158 permission: &Permission,
159 user_attributes: &HashMap<String, serde_json::Value>,
160 abac_policy: Option<&AbacPolicy>,
161 delegations: Option<&[Delegation]>,
162 role_resolver: &dyn Fn(&str) -> Option<Role>,
163 ) -> bool {
164 let has_basic = self.user_permissions.get(user_id).is_some_and(|up| {
166 let mut up = up.clone();
167 up.has_permission(permission, role_resolver)
168 });
169 if has_basic {
170 return true;
171 }
172 if let Some(policy) = abac_policy
174 && self.check_abac(user_attributes, permission, policy)
175 {
176 return true;
177 }
178 if let Some(delegations) = delegations
180 && self.check_delegation(user_id, permission, delegations)
181 {
182 return true;
183 }
184 false
185 }
186 pub fn check_abac(
188 &self,
189 user_attributes: &HashMap<String, serde_json::Value>,
190 permission: &Permission,
191 abac_policy: &AbacPolicy,
192 ) -> bool {
193 for rule in &abac_policy.rules {
194 if let Some(attr_value) = user_attributes.get(&rule.attribute)
195 && attr_value == &rule.expected_value
196 && rule.permission.implies(permission)
197 {
198 return true;
199 }
200 }
201 false
202 }
203
204 pub fn check_delegation(
206 &self,
207 user_id: &str,
208 permission: &Permission,
209 delegations: &[Delegation],
210 ) -> bool {
211 for delegation in delegations {
212 if delegation.delegatee == user_id
213 && delegation.permissions.iter().any(|p| p.implies(permission))
214 {
215 if let Some(expiry) = delegation.expires_at
216 && expiry < chrono::Utc::now()
217 {
218 continue;
219 }
220 return true;
221 }
222 }
223 false
224 }
225}
226
227pub struct AdvancedPermissionCheck<'a> {
247 user_id: &'a str,
248 permission: &'a Permission,
249 user_attributes: Option<&'a HashMap<String, serde_json::Value>>,
250 abac_policy: Option<&'a AbacPolicy>,
251 delegations: Option<&'a [Delegation]>,
252 role_resolver: &'a dyn Fn(&str) -> Option<Role>,
253}
254
255impl<'a> AdvancedPermissionCheck<'a> {
256 pub fn new(
258 user_id: &'a str,
259 permission: &'a Permission,
260 role_resolver: &'a dyn Fn(&str) -> Option<Role>,
261 ) -> Self {
262 Self {
263 user_id,
264 permission,
265 user_attributes: None,
266 abac_policy: None,
267 delegations: None,
268 role_resolver,
269 }
270 }
271
272 pub fn user_attributes(mut self, attrs: &'a HashMap<String, serde_json::Value>) -> Self {
274 self.user_attributes = Some(attrs);
275 self
276 }
277
278 pub fn abac_policy(mut self, policy: &'a AbacPolicy) -> Self {
280 self.abac_policy = Some(policy);
281 self
282 }
283
284 pub fn delegations(mut self, delegations: &'a [Delegation]) -> Self {
286 self.delegations = Some(delegations);
287 self
288 }
289}
290
291impl PermissionChecker {
292 pub fn check_advanced(&self, check: AdvancedPermissionCheck<'_>) -> bool {
308 static EMPTY: std::sync::LazyLock<HashMap<String, serde_json::Value>> =
309 std::sync::LazyLock::new(HashMap::new);
310 self.check_advanced_permission(
311 check.user_id,
312 check.permission,
313 check.user_attributes.unwrap_or(&EMPTY),
314 check.abac_policy,
315 check.delegations,
316 check.role_resolver,
317 )
318 }
319}
320use crate::errors::{PermissionError, Result};
322use crate::tokens::AuthToken;
323use chrono;
324use serde::{Deserialize, Serialize};
325use serde_json;
326use std::collections::{HashMap, HashSet};
327
328#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
330pub struct Permission {
331 pub action: String,
333
334 pub resource: String,
336
337 pub instance: Option<String>,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct Role {
344 pub id: Option<String>,
346
347 pub name: String,
349
350 pub description: Option<String>,
352
353 pub permissions: HashSet<Permission>,
355
356 pub parent_roles: HashSet<String>,
358
359 pub active: bool,
361
362 pub metadata: HashMap<String, String>,
364
365 pub created_at: Option<std::time::SystemTime>,
367
368 pub updated_at: Option<std::time::SystemTime>,
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
374pub struct UserPermissions {
375 pub user_id: String,
377
378 pub direct_permissions: HashSet<Permission>,
380
381 pub roles: HashSet<String>,
383
384 pub computed_permissions: Option<HashSet<Permission>>,
386
387 pub last_updated: chrono::DateTime<chrono::Utc>,
389}
390
391#[derive(Debug, Clone)]
393pub struct PermissionChecker {
394 roles: HashMap<String, Role>,
396
397 user_permissions: HashMap<String, UserPermissions>,
399
400 resource_hierarchy: HashMap<String, Vec<String>>,
402}
403
404impl Permission {
405 pub fn new(action: impl Into<String>, resource: impl Into<String>) -> Self {
407 Self {
408 action: action.into(),
409 resource: resource.into(),
410 instance: None,
411 }
412 }
413
414 pub fn from_action(action: impl Into<String>) -> Self {
416 Self {
417 action: action.into(),
418 resource: "*".to_string(),
419 instance: None,
420 }
421 }
422
423 pub fn with_instance(
425 action: impl Into<String>,
426 resource: impl Into<String>,
427 instance: impl Into<String>,
428 ) -> Self {
429 Self {
430 action: action.into(),
431 resource: resource.into(),
432 instance: Some(instance.into()),
433 }
434 }
435
436 pub fn parse(permission_str: &str) -> Result<Self> {
438 let parts: Vec<&str> = permission_str.split(':').collect();
439
440 match parts.len() {
441 2 => Ok(Self::new(parts[0], parts[1])),
442 3 => Ok(Self::with_instance(parts[0], parts[1], parts[2])),
443 _ => Err(PermissionError::invalid_format(format!(
444 "Invalid permission format: {permission_str}"
445 ))
446 .into()),
447 }
448 }
449}
450
451impl std::fmt::Display for Permission {
452 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453 match &self.instance {
454 Some(instance) => write!(f, "{}:{}:{}", self.action, self.resource, instance),
455 None => write!(f, "{}:{}", self.action, self.resource),
456 }
457 }
458}
459
460impl Permission {
461 pub fn matches(&self, other: &Permission) -> bool {
463 if self.action != "*" && other.action != "*" && self.action != other.action {
465 return false;
466 }
467
468 if self.resource != "*" && other.resource != "*" && self.resource != other.resource {
470 return false;
471 }
472
473 match (&self.instance, &other.instance) {
475 (Some(self_instance), Some(other_instance)) => {
476 self_instance == "*" || other_instance == "*" || self_instance == other_instance
477 }
478 (None, None) => true,
479 (Some(_), None) => false, (None, Some(_)) => true, }
482 }
483
484 pub fn implies(&self, other: &Permission) -> bool {
486 let action_implies = self.action == "*" || self.action == other.action;
488 let resource_implies = self.resource == "*" || self.resource == other.resource;
489 let instance_implies = match (&self.instance, &other.instance) {
490 (None, _) => true, (Some(self_instance), Some(other_instance)) => {
492 self_instance == "*" || self_instance == other_instance
493 }
494 (Some(_), None) => false, };
496
497 action_implies && resource_implies && instance_implies
498 }
499}
500
501impl Role {
502 pub fn new(name: impl Into<String>) -> Self {
504 Self {
505 id: None,
506 name: name.into(),
507 description: None,
508 permissions: HashSet::new(),
509 parent_roles: HashSet::new(),
510 active: true,
511 metadata: HashMap::new(),
512 created_at: None,
513 updated_at: None,
514 }
515 }
516
517 pub fn with_description(mut self, description: impl Into<String>) -> Self {
519 self.description = Some(description.into());
520 self
521 }
522
523 pub fn add_permission(&mut self, permission: Permission) {
525 self.permissions.insert(permission);
526 }
527
528 pub fn with_permissions(mut self, permissions: Vec<Permission>) -> Self {
530 for permission in permissions {
531 self.permissions.insert(permission);
532 }
533 self
534 }
535
536 pub fn with_parent_roles<I, S>(mut self, parent_roles: I) -> Self
538 where
539 I: IntoIterator<Item = S>,
540 S: Into<String>,
541 {
542 for parent_role in parent_roles {
543 self.parent_roles.insert(parent_role.into());
544 }
545 self
546 }
547
548 pub fn with_metadata<I, K, V>(mut self, metadata: I) -> Self
550 where
551 I: IntoIterator<Item = (K, V)>,
552 K: Into<String>,
553 V: Into<String>,
554 {
555 for (key, value) in metadata {
556 self.metadata.insert(key.into(), value.into());
557 }
558 self
559 }
560
561 pub fn with_active(mut self, active: bool) -> Self {
563 self.active = active;
564 self
565 }
566
567 pub fn remove_permission(&mut self, permission: &Permission) {
569 self.permissions.remove(permission);
570 }
571
572 pub fn add_parent_role(&mut self, parent_role: impl Into<String>) {
574 self.parent_roles.insert(parent_role.into());
575 }
576
577 pub fn has_permission(&self, permission: &Permission) -> bool {
579 self.permissions.iter().any(|p| p.implies(permission))
580 }
581
582 pub fn get_all_permissions(
584 &self,
585 role_resolver: &dyn Fn(&str) -> Option<Role>,
586 ) -> HashSet<Permission> {
587 let mut all_permissions = self.permissions.clone();
588
589 for parent_role_name in &self.parent_roles {
591 if let Some(parent_role) = role_resolver(parent_role_name) {
592 all_permissions.extend(parent_role.get_all_permissions(role_resolver));
593 }
594 }
595
596 all_permissions
597 }
598
599 pub fn set_active(&mut self, active: bool) {
601 self.active = active;
602 }
603}
604
605impl PermissionChecker {
606 pub fn clear(&mut self) {
608 self.roles.clear();
609 self.user_permissions.clear();
610 self.resource_hierarchy.clear();
611 }
612
613 pub fn get_user_roles(&self, user_id: &str) -> Vec<String> {
615 self.user_permissions
616 .get(user_id)
617 .map(|permissions| permissions.roles.iter().cloned().collect())
618 .unwrap_or_default()
619 }
620}
621
622impl UserPermissions {
623 pub fn new(user_id: impl Into<String>) -> Self {
625 Self {
626 user_id: user_id.into(),
627 direct_permissions: HashSet::new(),
628 roles: HashSet::new(),
629 computed_permissions: None,
630 last_updated: chrono::Utc::now(),
631 }
632 }
633
634 pub fn add_permission(&mut self, permission: Permission) {
636 self.direct_permissions.insert(permission);
637 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
639 }
640
641 pub fn remove_permission(&mut self, permission: &Permission) {
643 self.direct_permissions.remove(permission);
644 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
646 }
647
648 pub fn add_role(&mut self, role: impl Into<String>) {
650 self.roles.insert(role.into());
651 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
653 }
654
655 pub fn remove_role(&mut self, role: &str) {
657 self.roles.remove(role);
658 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
660 }
661
662 pub fn compute_permissions(
664 &mut self,
665 role_resolver: &dyn Fn(&str) -> Option<Role>,
666 ) -> &HashSet<Permission> {
667 if self.computed_permissions.is_none() {
668 let mut all_permissions = self.direct_permissions.clone();
669
670 for role_name in &self.roles {
672 if let Some(role) = role_resolver(role_name)
673 && role.active
674 {
675 all_permissions.extend(role.get_all_permissions(role_resolver));
676 }
677 }
678
679 self.computed_permissions = Some(all_permissions);
680 }
681
682 self.computed_permissions
684 .as_ref()
685 .expect("computed_permissions is always Some after this block")
686 }
687
688 pub fn has_permission(
690 &mut self,
691 permission: &Permission,
692 role_resolver: &dyn Fn(&str) -> Option<Role>,
693 ) -> bool {
694 let all_permissions = self.compute_permissions(role_resolver);
695 all_permissions.iter().any(|p| p.implies(permission))
696 }
697}
698
699fn broader_action_implies(broader: &str, required: &str) -> bool {
705 if broader == required {
707 return true;
708 }
709 match broader {
710 "manage" | "admin" => matches!(
711 required,
712 "read" | "write" | "delete" | "create" | "list" | "update" | "get"
713 ),
714 "write" | "update" => matches!(required, "read" | "get" | "list"),
715 _ => false,
716 }
717}
718
719impl PermissionChecker {
720 pub fn new() -> Self {
722 Self {
723 roles: HashMap::new(),
724 user_permissions: HashMap::new(),
725 resource_hierarchy: HashMap::new(),
726 }
727 }
728
729 pub fn add_role(&mut self, role: Role) {
731 self.roles.insert(role.name.clone(), role);
732 }
733
734 pub fn remove_role(&mut self, role_name: &str) {
736 self.roles.remove(role_name);
737 }
738
739 pub fn get_role(&self, role_name: &str) -> Option<&Role> {
741 self.roles.get(role_name)
742 }
743
744 pub fn list_roles(&self) -> Vec<Role> {
746 self.roles.values().cloned().collect()
747 }
748
749 pub fn set_user_permissions(&mut self, user_permissions: UserPermissions) {
751 self.user_permissions
752 .insert(user_permissions.user_id.clone(), user_permissions);
753 }
754
755 pub fn get_user_permissions(&self, user_id: &str) -> Option<&UserPermissions> {
757 self.user_permissions.get(user_id)
758 }
759
760 pub fn get_user_permissions_mut(&mut self, user_id: &str) -> Option<&mut UserPermissions> {
762 self.user_permissions.get_mut(user_id)
763 }
764
765 pub fn add_user_permission(&mut self, user_id: &str, permission: Permission) {
767 let user_perms = self
768 .user_permissions
769 .entry(user_id.to_string())
770 .or_insert_with(|| UserPermissions::new(user_id));
771
772 user_perms.add_permission(permission);
773 }
774
775 pub fn add_user_role(&mut self, user_id: &str, role: impl Into<String>) {
777 let user_perms = self
778 .user_permissions
779 .entry(user_id.to_string())
780 .or_insert_with(|| UserPermissions::new(user_id));
781
782 user_perms.add_role(role);
783 }
784
785 pub fn remove_user_role(&mut self, user_id: &str, role_name: &str) {
787 if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
788 user_perms.remove_role(role_name);
789 }
790 }
791
792 pub fn role_count(&self) -> usize {
794 self.roles.len()
795 }
796
797 pub fn user_count(&self) -> usize {
799 self.user_permissions.len()
800 }
801
802 pub fn total_direct_permission_count(&self) -> usize {
804 self.user_permissions
805 .values()
806 .map(|up| up.direct_permissions.len())
807 .sum()
808 }
809
810 pub fn check_permission(&mut self, user_id: &str, permission: &Permission) -> Result<bool> {
812 let user_perms = self.user_permissions.get_mut(user_id).ok_or_else(|| {
813 PermissionError::access_denied(permission.to_string(), "unknown user".to_string())
814 })?;
815
816 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
817
818 Ok(user_perms.has_permission(permission, &role_resolver))
819 }
820
821 pub fn check_access(&mut self, user_id: &str, action: &str, resource: &str) -> Result<bool> {
823 let permission = Permission::new(action, resource);
824
825 if self.check_permission(user_id, &permission)? {
827 return Ok(true);
828 }
829
830 self.check_hierarchical_permission(user_id, action, resource)
832 }
833
834 pub fn check_instance_access(
836 &mut self,
837 user_id: &str,
838 action: &str,
839 resource: &str,
840 instance: &str,
841 ) -> Result<bool> {
842 let permission = Permission::with_instance(action, resource, instance);
843 self.check_permission(user_id, &permission)
844 }
845
846 pub fn check_token_permission(
848 &mut self,
849 token: &AuthToken,
850 permission: &Permission,
851 ) -> Result<bool> {
852 if !token.is_valid() {
853 return Ok(false);
854 }
855
856 let required_scope = permission.to_string();
858 if !token.has_scope(&required_scope) {
859 let wildcard_action = format!("*:{}", permission.resource);
861 let wildcard_resource = format!("{}:*", permission.action);
862 let wildcard_all = "*:*".to_string();
863
864 if !token.has_scope(&wildcard_action)
865 && !token.has_scope(&wildcard_resource)
866 && !token.has_scope(&wildcard_all)
867 {
868 return Ok(false);
869 }
870 }
871
872 self.check_permission(&token.user_id, permission)
874 }
875
876 pub fn add_resource_hierarchy(&mut self, parent: String, children: Vec<String>) {
878 self.resource_hierarchy.insert(parent, children);
879 }
880
881 pub fn get_child_resources(&self, parent: &str) -> Option<&Vec<String>> {
883 self.resource_hierarchy.get(parent)
884 }
885
886 pub fn check_hierarchical_permission(
888 &mut self,
889 user_id: &str,
890 action: &str,
891 resource: &str,
892 ) -> Result<bool> {
893 let hierarchy = self.resource_hierarchy.clone();
895
896 if self.has_ancestor_permission(&hierarchy, user_id, action, resource)? {
898 return Ok(true);
899 }
900
901 if self.check_wildcard_permissions(&hierarchy, user_id, action, resource)? {
903 return Ok(true);
904 }
905
906 Ok(false)
907 }
908
909 fn check_wildcard_permissions(
911 &mut self,
912 hierarchy: &HashMap<String, Vec<String>>,
913 user_id: &str,
914 action: &str,
915 resource: &str,
916 ) -> Result<bool> {
917 for (parent_resource, children) in hierarchy {
919 if children.contains(&resource.to_string()) {
920 let wildcard_permission = Permission::new(action, format!("{}.*", parent_resource));
922 if self
923 .check_permission(user_id, &wildcard_permission)
924 .unwrap_or(false)
925 {
926 return Ok(true);
927 }
928 }
929 }
930
931 if let Some(_children) = hierarchy.get(resource) {
933 let wildcard_permission = Permission::new(action, format!("{}.*", resource));
934 if self
935 .check_permission(user_id, &wildcard_permission)
936 .unwrap_or(false)
937 {
938 return Ok(true);
939 }
940 }
941
942 Ok(false)
943 }
944
945 fn has_ancestor_permission(
947 &mut self,
948 hierarchy: &HashMap<String, Vec<String>>,
949 user_id: &str,
950 action: &str,
951 resource: &str,
952 ) -> Result<bool> {
953 for (parent_resource, children) in hierarchy {
955 if children.contains(&resource.to_string()) {
956 if self.check_permission_with_action_hierarchy(user_id, action, parent_resource)? {
960 return Ok(true);
961 }
962
963 if self.has_ancestor_permission(hierarchy, user_id, action, parent_resource)? {
965 return Ok(true);
966 }
967 }
968 }
969
970 Ok(false)
971 }
972
973 fn check_permission_with_action_hierarchy(
979 &mut self,
980 user_id: &str,
981 required_action: &str,
982 resource: &str,
983 ) -> Result<bool> {
984 let exact = Permission::new(required_action, resource);
986 if self.check_permission(user_id, &exact).unwrap_or(false) {
987 return Ok(true);
988 }
989
990 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
992 let user_perms = match self.user_permissions.get_mut(user_id) {
993 Some(p) => p,
994 None => return Ok(false),
995 };
996 let all_perms = user_perms.compute_permissions(&role_resolver);
997
998 Ok(all_perms.iter().any(|p| {
999 let resource_match = p.resource == "*" || p.resource == resource;
1000 let action_match =
1001 p.action == "*" || broader_action_implies(&p.action, required_action);
1002 resource_match && action_match
1003 }))
1004 }
1005
1006 pub fn create_default_roles(&mut self) {
1008 let mut admin_role = Role::new("admin").with_description("Administrator with full access");
1010 admin_role.add_permission(Permission::new("*", "*"));
1011 self.add_role(admin_role);
1012
1013 let mut user_role = Role::new("user").with_description("Regular user with basic access");
1015 user_role.add_permission(Permission::new("read", "profile"));
1016 user_role.add_permission(Permission::new("write", "profile"));
1017 user_role.add_permission(Permission::new("read", "public"));
1018 self.add_role(user_role);
1019
1020 let mut guest_role =
1022 Role::new("guest").with_description("Guest user with read-only access");
1023 guest_role.add_permission(Permission::new("read", "public"));
1024 self.add_role(guest_role);
1025 }
1026
1027 pub fn load_permissions(&mut self, _config: &str) -> Result<()> {
1029 self.create_default_roles();
1032 Ok(())
1033 }
1034
1035 pub fn assign_role_to_user(&mut self, user_id: &str, role_name: &str) -> Result<()> {
1037 if !self.roles.contains_key(role_name) {
1039 return Err(PermissionError::access_denied(
1040 role_name.to_string(),
1041 "Role does not exist".to_string(),
1042 )
1043 .into());
1044 }
1045
1046 self.add_user_role(user_id, role_name);
1048 Ok(())
1049 }
1050
1051 pub fn set_role_inheritance(&mut self, child_role: &str, parent_role: &str) -> Result<()> {
1053 if !self.roles.contains_key(child_role) {
1055 return Err(PermissionError::access_denied(
1056 child_role.to_string(),
1057 "Child role does not exist".to_string(),
1058 )
1059 .into());
1060 }
1061 if !self.roles.contains_key(parent_role) {
1062 return Err(PermissionError::access_denied(
1063 parent_role.to_string(),
1064 "Parent role does not exist".to_string(),
1065 )
1066 .into());
1067 }
1068
1069 if let Some(child) = self.roles.get_mut(child_role) {
1071 child.add_parent_role(parent_role);
1072 }
1073
1074 Ok(())
1075 }
1076
1077 pub fn remove_user_permission(&mut self, user_id: &str, permission: &Permission) {
1079 if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
1080 user_perms.remove_permission(permission);
1081 }
1082 }
1083
1084 pub fn user_has_role(&self, user_id: &str, role_name: &str) -> bool {
1086 if let Some(user_perms) = self.user_permissions.get(user_id) {
1087 user_perms.roles.contains(role_name)
1088 } else {
1089 false
1090 }
1091 }
1092
1093 pub fn get_effective_permissions(&self, user_id: &str) -> Vec<String> {
1095 if let Some(user_perms) = self.user_permissions.get(user_id) {
1096 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
1097
1098 let mut user_perms_clone = user_perms.clone();
1100 let all_permissions = user_perms_clone.compute_permissions(&role_resolver);
1101
1102 all_permissions.iter().map(|p| p.to_string()).collect()
1103 } else {
1104 Vec::new()
1105 }
1106 }
1107}
1108
1109impl Default for PermissionChecker {
1110 fn default() -> Self {
1111 Self::new()
1112 }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117 use super::*;
1118
1119 #[test]
1120 fn test_permission_parsing() {
1121 let perm = Permission::parse("read:documents").unwrap();
1122 assert_eq!(perm.action, "read");
1123 assert_eq!(perm.resource, "documents");
1124 assert_eq!(perm.instance, None);
1125
1126 let perm = Permission::parse("write:documents:123").unwrap();
1127 assert_eq!(perm.action, "write");
1128 assert_eq!(perm.resource, "documents");
1129 assert_eq!(perm.instance, Some("123".to_string()));
1130 }
1131
1132 #[test]
1133 fn test_permission_matching() {
1134 let perm1 = Permission::new("read", "documents");
1135 let perm2 = Permission::new("read", "documents");
1136 let perm3 = Permission::new("write", "documents");
1137 let wildcard = Permission::new("*", "documents");
1138
1139 assert!(perm1.matches(&perm2));
1140 assert!(!perm1.matches(&perm3));
1141 assert!(wildcard.matches(&perm1));
1142 assert!(wildcard.matches(&perm3));
1143 }
1144
1145 #[test]
1146 fn test_permission_implies() {
1147 let general = Permission::new("read", "documents");
1148 let specific = Permission::with_instance("read", "documents", "123");
1149 let wildcard = Permission::new("*", "*");
1150
1151 assert!(general.implies(&specific));
1152 assert!(!specific.implies(&general));
1153 assert!(wildcard.implies(&general));
1154 assert!(wildcard.implies(&specific));
1155 }
1156
1157 #[test]
1158 fn test_role_permissions() {
1159 let mut role = Role::new("editor");
1160 role.add_permission(Permission::new("read", "documents"));
1161 role.add_permission(Permission::new("write", "documents"));
1162
1163 let read_perm = Permission::new("read", "documents");
1164 let delete_perm = Permission::new("delete", "documents");
1165
1166 assert!(role.has_permission(&read_perm));
1167 assert!(!role.has_permission(&delete_perm));
1168 }
1169
1170 #[test]
1171 fn test_user_permissions() {
1172 let mut user_perms = UserPermissions::new("user123");
1173 user_perms.add_permission(Permission::new("read", "profile"));
1174 user_perms.add_role("user");
1175
1176 let role_resolver = |_: &str| Some(Role::new("user"));
1177
1178 let read_perm = Permission::new("read", "profile");
1179 assert!(user_perms.has_permission(&read_perm, &role_resolver));
1180 }
1181
1182 #[test]
1183 fn test_permission_checker() {
1184 let mut checker = PermissionChecker::new();
1185 checker.create_default_roles();
1186
1187 checker.add_user_role("user123", "admin");
1188
1189 let result = checker
1190 .check_access("user123", "read", "documents")
1191 .unwrap();
1192 assert!(result);
1193
1194 let result = checker.check_access("user123", "delete", "system").unwrap();
1195 assert!(result); }
1197}
1198
1199#[cfg(test)]
1200pub mod abac_delegation_tests;