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_validated_permission(
850 &mut self,
851 token: &crate::tokens::ValidatedToken,
852 permission: &Permission,
853 ) -> Result<bool> {
854 self.check_token_permission_inner(token.token(), permission)
855 }
856
857 #[deprecated(
861 since = "0.6.0",
862 note = "does not validate the token; use `check_validated_permission` with a `ValidatedToken`"
863 )]
864 pub fn check_token_permission(
865 &mut self,
866 token: &AuthToken,
867 permission: &Permission,
868 ) -> Result<bool> {
869 self.check_token_permission_inner(token, permission)
870 }
871
872 fn check_token_permission_inner(
873 &mut self,
874 token: &AuthToken,
875 permission: &Permission,
876 ) -> Result<bool> {
877 if !token.is_valid() {
878 return Ok(false);
879 }
880
881 let required_scope = permission.to_string();
883 if !token.has_scope(&required_scope) {
884 let wildcard_action = format!("*:{}", permission.resource);
886 let wildcard_resource = format!("{}:*", permission.action);
887 let wildcard_all = "*:*".to_string();
888
889 if !token.has_scope(&wildcard_action)
890 && !token.has_scope(&wildcard_resource)
891 && !token.has_scope(&wildcard_all)
892 {
893 return Ok(false);
894 }
895 }
896
897 self.check_permission(&token.user_id, permission)
899 }
900
901 pub fn add_resource_hierarchy(&mut self, parent: String, children: Vec<String>) {
903 self.resource_hierarchy.insert(parent, children);
904 }
905
906 pub fn get_child_resources(&self, parent: &str) -> Option<&Vec<String>> {
908 self.resource_hierarchy.get(parent)
909 }
910
911 pub fn check_hierarchical_permission(
913 &mut self,
914 user_id: &str,
915 action: &str,
916 resource: &str,
917 ) -> Result<bool> {
918 let hierarchy = self.resource_hierarchy.clone();
920
921 if self.has_ancestor_permission(&hierarchy, user_id, action, resource)? {
923 return Ok(true);
924 }
925
926 if self.check_wildcard_permissions(&hierarchy, user_id, action, resource)? {
928 return Ok(true);
929 }
930
931 Ok(false)
932 }
933
934 fn check_wildcard_permissions(
936 &mut self,
937 hierarchy: &HashMap<String, Vec<String>>,
938 user_id: &str,
939 action: &str,
940 resource: &str,
941 ) -> Result<bool> {
942 for (parent_resource, children) in hierarchy {
944 if children.contains(&resource.to_string()) {
945 let wildcard_permission = Permission::new(action, format!("{}.*", parent_resource));
947 if self
948 .check_permission(user_id, &wildcard_permission)
949 .unwrap_or(false)
950 {
951 return Ok(true);
952 }
953 }
954 }
955
956 if let Some(_children) = hierarchy.get(resource) {
958 let wildcard_permission = Permission::new(action, format!("{}.*", resource));
959 if self
960 .check_permission(user_id, &wildcard_permission)
961 .unwrap_or(false)
962 {
963 return Ok(true);
964 }
965 }
966
967 Ok(false)
968 }
969
970 fn has_ancestor_permission(
972 &mut self,
973 hierarchy: &HashMap<String, Vec<String>>,
974 user_id: &str,
975 action: &str,
976 resource: &str,
977 ) -> Result<bool> {
978 for (parent_resource, children) in hierarchy {
980 if children.contains(&resource.to_string()) {
981 if self.check_permission_with_action_hierarchy(user_id, action, parent_resource)? {
985 return Ok(true);
986 }
987
988 if self.has_ancestor_permission(hierarchy, user_id, action, parent_resource)? {
990 return Ok(true);
991 }
992 }
993 }
994
995 Ok(false)
996 }
997
998 fn check_permission_with_action_hierarchy(
1004 &mut self,
1005 user_id: &str,
1006 required_action: &str,
1007 resource: &str,
1008 ) -> Result<bool> {
1009 let exact = Permission::new(required_action, resource);
1011 if self.check_permission(user_id, &exact).unwrap_or(false) {
1012 return Ok(true);
1013 }
1014
1015 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
1017 let user_perms = match self.user_permissions.get_mut(user_id) {
1018 Some(p) => p,
1019 None => return Ok(false),
1020 };
1021 let all_perms = user_perms.compute_permissions(&role_resolver);
1022
1023 Ok(all_perms.iter().any(|p| {
1024 let resource_match = p.resource == "*" || p.resource == resource;
1025 let action_match =
1026 p.action == "*" || broader_action_implies(&p.action, required_action);
1027 resource_match && action_match
1028 }))
1029 }
1030
1031 pub fn create_default_roles(&mut self) {
1033 let mut admin_role = Role::new("admin").with_description("Administrator with full access");
1035 admin_role.add_permission(Permission::new("*", "*"));
1036 self.add_role(admin_role);
1037
1038 let mut user_role = Role::new("user").with_description("Regular user with basic access");
1040 user_role.add_permission(Permission::new("read", "profile"));
1041 user_role.add_permission(Permission::new("write", "profile"));
1042 user_role.add_permission(Permission::new("read", "public"));
1043 self.add_role(user_role);
1044
1045 let mut guest_role =
1047 Role::new("guest").with_description("Guest user with read-only access");
1048 guest_role.add_permission(Permission::new("read", "public"));
1049 self.add_role(guest_role);
1050 }
1051
1052 pub fn load_permissions(&mut self, _config: &str) -> Result<()> {
1054 self.create_default_roles();
1057 Ok(())
1058 }
1059
1060 pub fn assign_role_to_user(&mut self, user_id: &str, role_name: &str) -> Result<()> {
1062 if !self.roles.contains_key(role_name) {
1064 return Err(PermissionError::access_denied(
1065 role_name.to_string(),
1066 "Role does not exist".to_string(),
1067 )
1068 .into());
1069 }
1070
1071 self.add_user_role(user_id, role_name);
1073 Ok(())
1074 }
1075
1076 pub fn set_role_inheritance(&mut self, child_role: &str, parent_role: &str) -> Result<()> {
1078 if !self.roles.contains_key(child_role) {
1080 return Err(PermissionError::access_denied(
1081 child_role.to_string(),
1082 "Child role does not exist".to_string(),
1083 )
1084 .into());
1085 }
1086 if !self.roles.contains_key(parent_role) {
1087 return Err(PermissionError::access_denied(
1088 parent_role.to_string(),
1089 "Parent role does not exist".to_string(),
1090 )
1091 .into());
1092 }
1093
1094 if let Some(child) = self.roles.get_mut(child_role) {
1096 child.add_parent_role(parent_role);
1097 }
1098
1099 Ok(())
1100 }
1101
1102 pub fn remove_user_permission(&mut self, user_id: &str, permission: &Permission) {
1104 if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
1105 user_perms.remove_permission(permission);
1106 }
1107 }
1108
1109 pub fn user_has_role(&self, user_id: &str, role_name: &str) -> bool {
1111 if let Some(user_perms) = self.user_permissions.get(user_id) {
1112 user_perms.roles.contains(role_name)
1113 } else {
1114 false
1115 }
1116 }
1117
1118 pub fn get_effective_permissions(&self, user_id: &str) -> Vec<String> {
1120 if let Some(user_perms) = self.user_permissions.get(user_id) {
1121 let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
1122
1123 let mut user_perms_clone = user_perms.clone();
1125 let all_permissions = user_perms_clone.compute_permissions(&role_resolver);
1126
1127 all_permissions.iter().map(|p| p.to_string()).collect()
1128 } else {
1129 Vec::new()
1130 }
1131 }
1132}
1133
1134impl Default for PermissionChecker {
1135 fn default() -> Self {
1136 Self::new()
1137 }
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142 use super::*;
1143
1144 #[test]
1145 fn test_permission_parsing() {
1146 let perm = Permission::parse("read:documents").unwrap();
1147 assert_eq!(perm.action, "read");
1148 assert_eq!(perm.resource, "documents");
1149 assert_eq!(perm.instance, None);
1150
1151 let perm = Permission::parse("write:documents:123").unwrap();
1152 assert_eq!(perm.action, "write");
1153 assert_eq!(perm.resource, "documents");
1154 assert_eq!(perm.instance, Some("123".to_string()));
1155 }
1156
1157 #[test]
1158 fn test_permission_matching() {
1159 let perm1 = Permission::new("read", "documents");
1160 let perm2 = Permission::new("read", "documents");
1161 let perm3 = Permission::new("write", "documents");
1162 let wildcard = Permission::new("*", "documents");
1163
1164 assert!(perm1.matches(&perm2));
1165 assert!(!perm1.matches(&perm3));
1166 assert!(wildcard.matches(&perm1));
1167 assert!(wildcard.matches(&perm3));
1168 }
1169
1170 #[test]
1171 fn test_permission_implies() {
1172 let general = Permission::new("read", "documents");
1173 let specific = Permission::with_instance("read", "documents", "123");
1174 let wildcard = Permission::new("*", "*");
1175
1176 assert!(general.implies(&specific));
1177 assert!(!specific.implies(&general));
1178 assert!(wildcard.implies(&general));
1179 assert!(wildcard.implies(&specific));
1180 }
1181
1182 #[test]
1183 fn test_role_permissions() {
1184 let mut role = Role::new("editor");
1185 role.add_permission(Permission::new("read", "documents"));
1186 role.add_permission(Permission::new("write", "documents"));
1187
1188 let read_perm = Permission::new("read", "documents");
1189 let delete_perm = Permission::new("delete", "documents");
1190
1191 assert!(role.has_permission(&read_perm));
1192 assert!(!role.has_permission(&delete_perm));
1193 }
1194
1195 #[test]
1196 fn test_user_permissions() {
1197 let mut user_perms = UserPermissions::new("user123");
1198 user_perms.add_permission(Permission::new("read", "profile"));
1199 user_perms.add_role("user");
1200
1201 let role_resolver = |_: &str| Some(Role::new("user"));
1202
1203 let read_perm = Permission::new("read", "profile");
1204 assert!(user_perms.has_permission(&read_perm, &role_resolver));
1205 }
1206
1207 #[test]
1208 fn test_permission_checker() {
1209 let mut checker = PermissionChecker::new();
1210 checker.create_default_roles();
1211
1212 checker.add_user_role("user123", "admin");
1213
1214 let result = checker
1215 .check_access("user123", "read", "documents")
1216 .unwrap();
1217 assert!(result);
1218
1219 let result = checker.check_access("user123", "delete", "system").unwrap();
1220 assert!(result); }
1222}
1223
1224#[cfg(test)]
1225pub mod abac_delegation_tests;