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 AbacPolicy {
32 #[allow(clippy::new_without_default)] pub fn new() -> Self {
35 Self {
36 attributes: HashMap::new(),
37 rules: Vec::new(),
38 }
39 }
40
41 pub fn with_attribute(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
43 self.attributes.insert(key.into(), value);
44 self
45 }
46
47 pub fn with_attributes<I, K>(mut self, attributes: I) -> Self
49 where
50 I: IntoIterator<Item = (K, serde_json::Value)>,
51 K: Into<String>,
52 {
53 for (key, value) in attributes {
54 self.attributes.insert(key.into(), value);
55 }
56 self
57 }
58
59 pub fn with_rule(
61 mut self,
62 attribute: impl Into<String>,
63 expected_value: serde_json::Value,
64 permission: Permission,
65 ) -> Self {
66 self.rules.push(AbacRule {
67 attribute: attribute.into(),
68 expected_value,
69 permission,
70 });
71 self
72 }
73
74 pub fn with_rules<I>(mut self, rules: I) -> Self
76 where
77 I: IntoIterator<Item = AbacRule>,
78 {
79 self.rules.extend(rules);
80 self
81 }
82}
83
84#[derive(Debug, Clone)]
89pub struct Delegation {
90 pub delegator: String,
91 pub delegatee: String,
92 pub permissions: HashSet<Permission>,
93 pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
94}
95
96impl Delegation {
97 pub fn new(delegator: impl Into<String>, delegatee: impl Into<String>) -> Self {
99 Self {
100 delegator: delegator.into(),
101 delegatee: delegatee.into(),
102 permissions: HashSet::new(),
103 expires_at: None,
104 }
105 }
106
107 pub fn with_permissions<I>(mut self, permissions: I) -> Self
109 where
110 I: IntoIterator<Item = Permission>,
111 {
112 self.permissions.extend(permissions);
113 self
114 }
115
116 pub fn with_permission(mut self, permission: Permission) -> Self {
118 self.permissions.insert(permission);
119 self
120 }
121
122 pub fn with_expiry(mut self, expires_at: chrono::DateTime<chrono::Utc>) -> Self {
124 self.expires_at = Some(expires_at);
125 self
126 }
127
128 pub fn permanent(mut self) -> Self {
130 self.expires_at = None;
131 self
132 }
133}
134
135impl PermissionChecker {
136 pub fn check_advanced_permission(
151 &self,
152 user_id: &str,
153 permission: &Permission,
154 user_attributes: &HashMap<String, serde_json::Value>,
155 abac_policy: Option<&AbacPolicy>,
156 delegations: Option<&[Delegation]>,
157 role_resolver: &dyn Fn(&str) -> Option<Role>,
158 ) -> bool {
159 let has_basic = self.user_permissions.get(user_id).is_some_and(|up| {
161 let mut up = up.clone();
162 up.has_permission(permission, role_resolver)
163 });
164 if has_basic {
165 return true;
166 }
167 if let Some(policy) = abac_policy
169 && self.check_abac(user_attributes, permission, policy)
170 {
171 return true;
172 }
173 if let Some(delegations) = delegations
175 && self.check_delegation(user_id, permission, delegations)
176 {
177 return true;
178 }
179 false
180 }
181 pub fn check_abac(
183 &self,
184 user_attributes: &HashMap<String, serde_json::Value>,
185 permission: &Permission,
186 abac_policy: &AbacPolicy,
187 ) -> bool {
188 for rule in &abac_policy.rules {
189 if let Some(attr_value) = user_attributes.get(&rule.attribute)
190 && attr_value == &rule.expected_value
191 && rule.permission.implies(permission)
192 {
193 return true;
194 }
195 }
196 false
197 }
198
199 pub fn check_delegation(
201 &self,
202 user_id: &str,
203 permission: &Permission,
204 delegations: &[Delegation],
205 ) -> bool {
206 for delegation in delegations {
207 if delegation.delegatee == user_id
208 && delegation.permissions.iter().any(|p| p.implies(permission))
209 {
210 if let Some(expiry) = delegation.expires_at
211 && expiry < chrono::Utc::now()
212 {
213 continue;
214 }
215 return true;
216 }
217 }
218 false
219 }
220}
221
222pub struct AdvancedPermissionCheck<'a> {
242 user_id: &'a str,
243 permission: &'a Permission,
244 user_attributes: Option<&'a HashMap<String, serde_json::Value>>,
245 abac_policy: Option<&'a AbacPolicy>,
246 delegations: Option<&'a [Delegation]>,
247 role_resolver: &'a dyn Fn(&str) -> Option<Role>,
248}
249
250impl<'a> AdvancedPermissionCheck<'a> {
251 pub fn new(
253 user_id: &'a str,
254 permission: &'a Permission,
255 role_resolver: &'a dyn Fn(&str) -> Option<Role>,
256 ) -> Self {
257 Self {
258 user_id,
259 permission,
260 user_attributes: None,
261 abac_policy: None,
262 delegations: None,
263 role_resolver,
264 }
265 }
266
267 pub fn user_attributes(mut self, attrs: &'a HashMap<String, serde_json::Value>) -> Self {
269 self.user_attributes = Some(attrs);
270 self
271 }
272
273 pub fn abac_policy(mut self, policy: &'a AbacPolicy) -> Self {
275 self.abac_policy = Some(policy);
276 self
277 }
278
279 pub fn delegations(mut self, delegations: &'a [Delegation]) -> Self {
281 self.delegations = Some(delegations);
282 self
283 }
284}
285
286impl PermissionChecker {
287 pub fn check_advanced(&self, check: AdvancedPermissionCheck<'_>) -> bool {
303 static EMPTY: std::sync::LazyLock<HashMap<String, serde_json::Value>> =
304 std::sync::LazyLock::new(HashMap::new);
305 self.check_advanced_permission(
306 check.user_id,
307 check.permission,
308 check.user_attributes.unwrap_or(&EMPTY),
309 check.abac_policy,
310 check.delegations,
311 check.role_resolver,
312 )
313 }
314}
315use crate::errors::{PermissionError, Result};
317use crate::tokens::AuthToken;
318use chrono;
319use serde::{Deserialize, Serialize};
320use serde_json;
321use std::collections::{HashMap, HashSet};
322
323#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
325pub struct Permission {
326 pub action: String,
328
329 pub resource: String,
331
332 pub instance: Option<String>,
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct Role {
339 pub id: Option<String>,
341
342 pub name: String,
344
345 pub description: Option<String>,
347
348 pub permissions: HashSet<Permission>,
350
351 pub parent_roles: HashSet<String>,
353
354 pub active: bool,
356
357 pub metadata: HashMap<String, String>,
359
360 pub created_at: Option<std::time::SystemTime>,
362
363 pub updated_at: Option<std::time::SystemTime>,
365}
366
367#[derive(Debug, Clone, Serialize, Deserialize)]
369pub struct UserPermissions {
370 pub user_id: String,
372
373 pub direct_permissions: HashSet<Permission>,
375
376 pub roles: HashSet<String>,
378
379 pub computed_permissions: Option<HashSet<Permission>>,
381
382 pub last_updated: chrono::DateTime<chrono::Utc>,
384}
385
386#[derive(Debug, Clone)]
388pub struct PermissionChecker {
389 roles: HashMap<String, Role>,
391
392 user_permissions: HashMap<String, UserPermissions>,
394
395 resource_hierarchy: HashMap<String, Vec<String>>,
397}
398
399impl Permission {
400 pub fn new(action: impl Into<String>, resource: impl Into<String>) -> Self {
402 Self {
403 action: action.into(),
404 resource: resource.into(),
405 instance: None,
406 }
407 }
408
409 pub fn from_action(action: impl Into<String>) -> Self {
411 Self {
412 action: action.into(),
413 resource: "*".to_string(),
414 instance: None,
415 }
416 }
417
418 pub fn with_instance(
420 action: impl Into<String>,
421 resource: impl Into<String>,
422 instance: impl Into<String>,
423 ) -> Self {
424 Self {
425 action: action.into(),
426 resource: resource.into(),
427 instance: Some(instance.into()),
428 }
429 }
430
431 pub fn parse(permission_str: &str) -> Result<Self> {
433 let parts: Vec<&str> = permission_str.split(':').collect();
434
435 match parts.len() {
436 2 => Ok(Self::new(parts[0], parts[1])),
437 3 => Ok(Self::with_instance(parts[0], parts[1], parts[2])),
438 _ => Err(PermissionError::invalid_format(format!(
439 "Invalid permission format: {permission_str}"
440 ))
441 .into()),
442 }
443 }
444}
445
446impl std::fmt::Display for Permission {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 match &self.instance {
449 Some(instance) => write!(f, "{}:{}:{}", self.action, self.resource, instance),
450 None => write!(f, "{}:{}", self.action, self.resource),
451 }
452 }
453}
454
455impl Permission {
456 pub fn matches(&self, other: &Permission) -> bool {
458 if self.action != "*" && other.action != "*" && self.action != other.action {
460 return false;
461 }
462
463 if self.resource != "*" && other.resource != "*" && self.resource != other.resource {
465 return false;
466 }
467
468 match (&self.instance, &other.instance) {
470 (Some(self_instance), Some(other_instance)) => {
471 self_instance == "*" || other_instance == "*" || self_instance == other_instance
472 }
473 (None, None) => true,
474 (Some(_), None) => false, (None, Some(_)) => true, }
477 }
478
479 pub fn implies(&self, other: &Permission) -> bool {
481 let action_implies = self.action == "*" || self.action == other.action;
483 let resource_implies = self.resource == "*" || self.resource == other.resource;
484 let instance_implies = match (&self.instance, &other.instance) {
485 (None, _) => true, (Some(self_instance), Some(other_instance)) => {
487 self_instance == "*" || self_instance == other_instance
488 }
489 (Some(_), None) => false, };
491
492 action_implies && resource_implies && instance_implies
493 }
494}
495
496impl Role {
497 pub fn new(name: impl Into<String>) -> Self {
499 Self {
500 id: None,
501 name: name.into(),
502 description: None,
503 permissions: HashSet::new(),
504 parent_roles: HashSet::new(),
505 active: true,
506 metadata: HashMap::new(),
507 created_at: None,
508 updated_at: None,
509 }
510 }
511
512 pub fn with_description(mut self, description: impl Into<String>) -> Self {
514 self.description = Some(description.into());
515 self
516 }
517
518 pub fn add_permission(&mut self, permission: Permission) {
520 self.permissions.insert(permission);
521 }
522
523 pub fn with_permissions(mut self, permissions: Vec<Permission>) -> Self {
525 for permission in permissions {
526 self.permissions.insert(permission);
527 }
528 self
529 }
530
531 pub fn with_parent_roles<I, S>(mut self, parent_roles: I) -> Self
533 where
534 I: IntoIterator<Item = S>,
535 S: Into<String>,
536 {
537 for parent_role in parent_roles {
538 self.parent_roles.insert(parent_role.into());
539 }
540 self
541 }
542
543 pub fn with_metadata<I, K, V>(mut self, metadata: I) -> Self
545 where
546 I: IntoIterator<Item = (K, V)>,
547 K: Into<String>,
548 V: Into<String>,
549 {
550 for (key, value) in metadata {
551 self.metadata.insert(key.into(), value.into());
552 }
553 self
554 }
555
556 pub fn with_active(mut self, active: bool) -> Self {
558 self.active = active;
559 self
560 }
561
562 pub fn remove_permission(&mut self, permission: &Permission) {
564 self.permissions.remove(permission);
565 }
566
567 pub fn add_parent_role(&mut self, parent_role: impl Into<String>) {
569 self.parent_roles.insert(parent_role.into());
570 }
571
572 pub fn has_permission(&self, permission: &Permission) -> bool {
574 self.permissions.iter().any(|p| p.implies(permission))
575 }
576
577 pub fn get_all_permissions(
579 &self,
580 role_resolver: &dyn Fn(&str) -> Option<Role>,
581 ) -> HashSet<Permission> {
582 let mut all_permissions = self.permissions.clone();
583
584 for parent_role_name in &self.parent_roles {
586 if let Some(parent_role) = role_resolver(parent_role_name) {
587 all_permissions.extend(parent_role.get_all_permissions(role_resolver));
588 }
589 }
590
591 all_permissions
592 }
593
594 pub fn set_active(&mut self, active: bool) {
596 self.active = active;
597 }
598}
599
600impl PermissionChecker {
601 pub fn clear(&mut self) {
603 self.roles.clear();
604 self.user_permissions.clear();
605 self.resource_hierarchy.clear();
606 }
607
608 pub fn get_user_roles(&self, user_id: &str) -> Vec<String> {
610 self.user_permissions
611 .get(user_id)
612 .map(|permissions| permissions.roles.iter().cloned().collect())
613 .unwrap_or_default()
614 }
615}
616
617impl UserPermissions {
618 pub fn new(user_id: impl Into<String>) -> Self {
620 Self {
621 user_id: user_id.into(),
622 direct_permissions: HashSet::new(),
623 roles: HashSet::new(),
624 computed_permissions: None,
625 last_updated: chrono::Utc::now(),
626 }
627 }
628
629 pub fn add_permission(&mut self, permission: Permission) {
631 self.direct_permissions.insert(permission);
632 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
634 }
635
636 pub fn remove_permission(&mut self, permission: &Permission) {
638 self.direct_permissions.remove(permission);
639 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
641 }
642
643 pub fn add_role(&mut self, role: impl Into<String>) {
645 self.roles.insert(role.into());
646 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
648 }
649
650 pub fn remove_role(&mut self, role: &str) {
652 self.roles.remove(role);
653 self.computed_permissions = None; self.last_updated = chrono::Utc::now();
655 }
656
657 pub fn compute_permissions(
659 &mut self,
660 role_resolver: &dyn Fn(&str) -> Option<Role>,
661 ) -> &HashSet<Permission> {
662 if self.computed_permissions.is_none() {
663 let mut all_permissions = self.direct_permissions.clone();
664
665 for role_name in &self.roles {
667 if let Some(role) = role_resolver(role_name)
668 && role.active
669 {
670 all_permissions.extend(role.get_all_permissions(role_resolver));
671 }
672 }
673
674 self.computed_permissions = Some(all_permissions);
675 }
676
677 self.computed_permissions
679 .as_ref()
680 .expect("computed_permissions is always Some after this block")
681 }
682
683 pub fn has_permission(
685 &mut self,
686 permission: &Permission,
687 role_resolver: &dyn Fn(&str) -> Option<Role>,
688 ) -> bool {
689 let all_permissions = self.compute_permissions(role_resolver);
690 all_permissions.iter().any(|p| p.implies(permission))
691 }
692}
693
694fn broader_action_implies(broader: &str, required: &str) -> bool {
700 if broader == required {
702 return true;
703 }
704 match broader {
705 "manage" | "admin" => matches!(
706 required,
707 "read" | "write" | "delete" | "create" | "list" | "update" | "get"
708 ),
709 "write" | "update" => matches!(required, "read" | "get" | "list"),
710 _ => false,
711 }
712}
713
714impl PermissionChecker {
715 pub fn new() -> Self {
717 Self {
718 roles: HashMap::new(),
719 user_permissions: HashMap::new(),
720 resource_hierarchy: HashMap::new(),
721 }
722 }
723
724 pub fn add_role(&mut self, role: Role) {
726 self.roles.insert(role.name.clone(), role);
727 }
728
729 pub fn remove_role(&mut self, role_name: &str) {
731 self.roles.remove(role_name);
732 }
733
734 pub fn get_role(&self, role_name: &str) -> Option<&Role> {
736 self.roles.get(role_name)
737 }
738
739 pub fn list_roles(&self) -> Vec<Role> {
741 self.roles.values().cloned().collect()
742 }
743
744 pub fn set_user_permissions(&mut self, user_permissions: UserPermissions) {
746 self.user_permissions
747 .insert(user_permissions.user_id.clone(), user_permissions);
748 }
749
750 pub fn get_user_permissions(&self, user_id: &str) -> Option<&UserPermissions> {
752 self.user_permissions.get(user_id)
753 }
754
755 pub fn get_user_permissions_mut(&mut self, user_id: &str) -> Option<&mut UserPermissions> {
757 self.user_permissions.get_mut(user_id)
758 }
759
760 pub fn add_user_permission(&mut self, user_id: &str, permission: Permission) {
762 let user_perms = self
763 .user_permissions
764 .entry(user_id.to_string())
765 .or_insert_with(|| UserPermissions::new(user_id));
766
767 user_perms.add_permission(permission);
768 }
769
770 pub fn add_user_role(&mut self, user_id: &str, role: impl Into<String>) {
772 let user_perms = self
773 .user_permissions
774 .entry(user_id.to_string())
775 .or_insert_with(|| UserPermissions::new(user_id));
776
777 user_perms.add_role(role);
778 }
779
780 pub fn remove_user_role(&mut self, user_id: &str, role_name: &str) {
782 if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
783 user_perms.remove_role(role_name);
784 }
785 }
786
787 pub fn role_count(&self) -> usize {
789 self.roles.len()
790 }
791
792 pub fn user_count(&self) -> usize {
794 self.user_permissions.len()
795 }
796
797 pub fn total_direct_permission_count(&self) -> usize {
799 self.user_permissions
800 .values()
801 .map(|up| up.direct_permissions.len())
802 .sum()
803 }
804
805 pub fn check_permission(&mut self, user_id: &str, permission: &Permission) -> Result<bool> {
807 let user_perms = self.user_permissions.get_mut(user_id).ok_or_else(|| {
808 PermissionError::access_denied(permission.to_string(), "unknown user".to_string())
809 })?;
810
811 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
812
813 Ok(user_perms.has_permission(permission, &role_resolver))
814 }
815
816 pub fn check_access(&mut self, user_id: &str, action: &str, resource: &str) -> Result<bool> {
818 let permission = Permission::new(action, resource);
819
820 if self.check_permission(user_id, &permission)? {
822 return Ok(true);
823 }
824
825 self.check_hierarchical_permission(user_id, action, resource)
827 }
828
829 pub fn check_instance_access(
831 &mut self,
832 user_id: &str,
833 action: &str,
834 resource: &str,
835 instance: &str,
836 ) -> Result<bool> {
837 let permission = Permission::with_instance(action, resource, instance);
838 self.check_permission(user_id, &permission)
839 }
840
841 pub fn check_token_permission(
843 &mut self,
844 token: &AuthToken,
845 permission: &Permission,
846 ) -> Result<bool> {
847 if !token.is_valid() {
848 return Ok(false);
849 }
850
851 let required_scope = permission.to_string();
853 if !token.has_scope(&required_scope) {
854 let wildcard_action = format!("*:{}", permission.resource);
856 let wildcard_resource = format!("{}:*", permission.action);
857 let wildcard_all = "*:*".to_string();
858
859 if !token.has_scope(&wildcard_action)
860 && !token.has_scope(&wildcard_resource)
861 && !token.has_scope(&wildcard_all)
862 {
863 return Ok(false);
864 }
865 }
866
867 self.check_permission(&token.user_id, permission)
869 }
870
871 pub fn add_resource_hierarchy(&mut self, parent: String, children: Vec<String>) {
873 self.resource_hierarchy.insert(parent, children);
874 }
875
876 pub fn get_child_resources(&self, parent: &str) -> Option<&Vec<String>> {
878 self.resource_hierarchy.get(parent)
879 }
880
881 pub fn check_hierarchical_permission(
883 &mut self,
884 user_id: &str,
885 action: &str,
886 resource: &str,
887 ) -> Result<bool> {
888 let hierarchy = self.resource_hierarchy.clone();
890
891 if self.has_ancestor_permission(&hierarchy, user_id, action, resource)? {
893 return Ok(true);
894 }
895
896 if self.check_wildcard_permissions(&hierarchy, user_id, action, resource)? {
898 return Ok(true);
899 }
900
901 Ok(false)
902 }
903
904 fn check_wildcard_permissions(
906 &mut self,
907 hierarchy: &HashMap<String, Vec<String>>,
908 user_id: &str,
909 action: &str,
910 resource: &str,
911 ) -> Result<bool> {
912 for (parent_resource, children) in hierarchy {
914 if children.contains(&resource.to_string()) {
915 let wildcard_permission = Permission::new(action, format!("{}.*", parent_resource));
917 if self
918 .check_permission(user_id, &wildcard_permission)
919 .unwrap_or(false)
920 {
921 return Ok(true);
922 }
923 }
924 }
925
926 if let Some(_children) = hierarchy.get(resource) {
928 let wildcard_permission = Permission::new(action, format!("{}.*", resource));
929 if self
930 .check_permission(user_id, &wildcard_permission)
931 .unwrap_or(false)
932 {
933 return Ok(true);
934 }
935 }
936
937 Ok(false)
938 }
939
940 fn has_ancestor_permission(
942 &mut self,
943 hierarchy: &HashMap<String, Vec<String>>,
944 user_id: &str,
945 action: &str,
946 resource: &str,
947 ) -> Result<bool> {
948 for (parent_resource, children) in hierarchy {
950 if children.contains(&resource.to_string()) {
951 if self.check_permission_with_action_hierarchy(user_id, action, parent_resource)? {
955 return Ok(true);
956 }
957
958 if self.has_ancestor_permission(hierarchy, user_id, action, parent_resource)? {
960 return Ok(true);
961 }
962 }
963 }
964
965 Ok(false)
966 }
967
968 fn check_permission_with_action_hierarchy(
974 &mut self,
975 user_id: &str,
976 required_action: &str,
977 resource: &str,
978 ) -> Result<bool> {
979 let exact = Permission::new(required_action, resource);
981 if self.check_permission(user_id, &exact).unwrap_or(false) {
982 return Ok(true);
983 }
984
985 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
987 let user_perms = match self.user_permissions.get_mut(user_id) {
988 Some(p) => p,
989 None => return Ok(false),
990 };
991 let all_perms = user_perms.compute_permissions(&role_resolver);
992
993 Ok(all_perms.iter().any(|p| {
994 let resource_match = p.resource == "*" || p.resource == resource;
995 let action_match =
996 p.action == "*" || broader_action_implies(&p.action, required_action);
997 resource_match && action_match
998 }))
999 }
1000
1001 pub fn create_default_roles(&mut self) {
1003 let mut admin_role = Role::new("admin").with_description("Administrator with full access");
1005 admin_role.add_permission(Permission::new("*", "*"));
1006 self.add_role(admin_role);
1007
1008 let mut user_role = Role::new("user").with_description("Regular user with basic access");
1010 user_role.add_permission(Permission::new("read", "profile"));
1011 user_role.add_permission(Permission::new("write", "profile"));
1012 user_role.add_permission(Permission::new("read", "public"));
1013 self.add_role(user_role);
1014
1015 let mut guest_role =
1017 Role::new("guest").with_description("Guest user with read-only access");
1018 guest_role.add_permission(Permission::new("read", "public"));
1019 self.add_role(guest_role);
1020 }
1021
1022 pub fn load_permissions(&mut self, _config: &str) -> Result<()> {
1024 self.create_default_roles();
1027 Ok(())
1028 }
1029
1030 pub fn assign_role_to_user(&mut self, user_id: &str, role_name: &str) -> Result<()> {
1032 if !self.roles.contains_key(role_name) {
1034 return Err(PermissionError::access_denied(
1035 role_name.to_string(),
1036 "Role does not exist".to_string(),
1037 )
1038 .into());
1039 }
1040
1041 self.add_user_role(user_id, role_name);
1043 Ok(())
1044 }
1045
1046 pub fn set_role_inheritance(&mut self, child_role: &str, parent_role: &str) -> Result<()> {
1048 if !self.roles.contains_key(child_role) {
1050 return Err(PermissionError::access_denied(
1051 child_role.to_string(),
1052 "Child role does not exist".to_string(),
1053 )
1054 .into());
1055 }
1056 if !self.roles.contains_key(parent_role) {
1057 return Err(PermissionError::access_denied(
1058 parent_role.to_string(),
1059 "Parent role does not exist".to_string(),
1060 )
1061 .into());
1062 }
1063
1064 if let Some(child) = self.roles.get_mut(child_role) {
1066 child.add_parent_role(parent_role);
1067 }
1068
1069 Ok(())
1070 }
1071
1072 pub fn remove_user_permission(&mut self, user_id: &str, permission: &Permission) {
1074 if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
1075 user_perms.remove_permission(permission);
1076 }
1077 }
1078
1079 pub fn user_has_role(&self, user_id: &str, role_name: &str) -> bool {
1081 if let Some(user_perms) = self.user_permissions.get(user_id) {
1082 user_perms.roles.contains(role_name)
1083 } else {
1084 false
1085 }
1086 }
1087
1088 pub fn get_effective_permissions(&self, user_id: &str) -> Vec<String> {
1090 if let Some(user_perms) = self.user_permissions.get(user_id) {
1091 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
1092
1093 let mut user_perms_clone = user_perms.clone();
1095 let all_permissions = user_perms_clone.compute_permissions(&role_resolver);
1096
1097 all_permissions.iter().map(|p| p.to_string()).collect()
1098 } else {
1099 Vec::new()
1100 }
1101 }
1102}
1103
1104impl Default for PermissionChecker {
1105 fn default() -> Self {
1106 Self::new()
1107 }
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112 use super::*;
1113
1114 #[test]
1115 fn test_permission_parsing() {
1116 let perm = Permission::parse("read:documents").unwrap();
1117 assert_eq!(perm.action, "read");
1118 assert_eq!(perm.resource, "documents");
1119 assert_eq!(perm.instance, None);
1120
1121 let perm = Permission::parse("write:documents:123").unwrap();
1122 assert_eq!(perm.action, "write");
1123 assert_eq!(perm.resource, "documents");
1124 assert_eq!(perm.instance, Some("123".to_string()));
1125 }
1126
1127 #[test]
1128 fn test_permission_matching() {
1129 let perm1 = Permission::new("read", "documents");
1130 let perm2 = Permission::new("read", "documents");
1131 let perm3 = Permission::new("write", "documents");
1132 let wildcard = Permission::new("*", "documents");
1133
1134 assert!(perm1.matches(&perm2));
1135 assert!(!perm1.matches(&perm3));
1136 assert!(wildcard.matches(&perm1));
1137 assert!(wildcard.matches(&perm3));
1138 }
1139
1140 #[test]
1141 fn test_permission_implies() {
1142 let general = Permission::new("read", "documents");
1143 let specific = Permission::with_instance("read", "documents", "123");
1144 let wildcard = Permission::new("*", "*");
1145
1146 assert!(general.implies(&specific));
1147 assert!(!specific.implies(&general));
1148 assert!(wildcard.implies(&general));
1149 assert!(wildcard.implies(&specific));
1150 }
1151
1152 #[test]
1153 fn test_role_permissions() {
1154 let mut role = Role::new("editor");
1155 role.add_permission(Permission::new("read", "documents"));
1156 role.add_permission(Permission::new("write", "documents"));
1157
1158 let read_perm = Permission::new("read", "documents");
1159 let delete_perm = Permission::new("delete", "documents");
1160
1161 assert!(role.has_permission(&read_perm));
1162 assert!(!role.has_permission(&delete_perm));
1163 }
1164
1165 #[test]
1166 fn test_user_permissions() {
1167 let mut user_perms = UserPermissions::new("user123");
1168 user_perms.add_permission(Permission::new("read", "profile"));
1169 user_perms.add_role("user");
1170
1171 let role_resolver = |_: &str| Some(Role::new("user"));
1172
1173 let read_perm = Permission::new("read", "profile");
1174 assert!(user_perms.has_permission(&read_perm, &role_resolver));
1175 }
1176
1177 #[test]
1178 fn test_permission_checker() {
1179 let mut checker = PermissionChecker::new();
1180 checker.create_default_roles();
1181
1182 checker.add_user_role("user123", "admin");
1183
1184 let result = checker
1185 .check_access("user123", "read", "documents")
1186 .unwrap();
1187 assert!(result);
1188
1189 let result = checker.check_access("user123", "delete", "system").unwrap();
1190 assert!(result); }
1192}
1193
1194#[cfg(test)]
1195pub mod abac_delegation_tests;