Skip to main content

auth_framework/
permissions.rs

1//! Permission and role-based access control (RBAC / ABAC).
2//!
3//! Core types for the authorization subsystem:
4//!
5//! - [`Permission`] — An `(action, resource)` pair representing a capability.
6//! - [`Role`] — A named set of permissions with optional inheritance.
7//! - [`UserPermissions`] — Resolved permissions for a single user.
8//! - [`PermissionChecker`] — Evaluates access decisions, including ABAC
9//!   policies and delegation chains.
10//!
11//! For the async, storage-backed authorization API see
12//! [`AuthorizationOperations`](crate::auth::AuthorizationOperations).
13
14/// Attribute-Based Access Control (ABAC) policy.
15///
16/// Associates a set of attribute rules with the permissions they grant.
17/// Evaluated by [`PermissionChecker::check_advanced_permission`].
18#[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    /// Create a new empty ABAC policy.
33    #[allow(clippy::new_without_default)] // adding Default would extend the public API of a release line
34    pub fn new() -> Self {
35        Self {
36            attributes: HashMap::new(),
37            rules: Vec::new(),
38        }
39    }
40
41    /// Add an attribute to the policy.
42    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    /// Add multiple attributes to the policy.
48    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    /// Add a rule to the policy.
60    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    /// Add multiple rules to the policy.
75    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/// Permission delegation record.
85///
86/// Represents a delegator granting a subset of their permissions to a delegatee,
87/// optionally for a limited time window.
88#[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    /// Create a new delegation with required fields.
98    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    /// Add permissions to the delegation.
108    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    /// Add a single permission to the delegation.
117    pub fn with_permission(mut self, permission: Permission) -> Self {
118        self.permissions.insert(permission);
119        self
120    }
121
122    /// Set the expiration time for the delegation.
123    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    /// Set the delegation to never expire.
129    pub fn permanent(mut self) -> Self {
130        self.expires_at = None;
131        self
132    }
133}
134
135impl PermissionChecker {
136    /// Check permission for a user with ABAC and delegation support.
137    ///
138    /// This is the low-level API with positional parameters.  For a more
139    /// readable alternative, use [`check_advanced`](Self::check_advanced)
140    /// with an [`AdvancedPermissionCheck`] builder.
141    ///
142    /// # Arguments
143    ///
144    /// * `user_id` — the user to check
145    /// * `permission` — the required permission
146    /// * `user_attributes` — runtime attributes for ABAC evaluation
147    /// * `abac_policy` — optional ABAC policy
148    /// * `delegations` — optional active delegations
149    /// * `role_resolver` — closure that resolves role names to definitions
150    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        // Check direct and role permissions
160        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        // Check ABAC policy
168        if let Some(policy) = abac_policy
169            && self.check_abac(user_attributes, permission, policy)
170        {
171            return true;
172        }
173        // Check delegation
174        if let Some(delegations) = delegations
175            && self.check_delegation(user_id, permission, delegations)
176        {
177            return true;
178        }
179        false
180    }
181    /// Check permission with ABAC policy
182    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    /// Check permission with delegation
200    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
222/// Builder for constructing an advanced permission check with ABAC policies,
223/// delegations, and role resolution.
224///
225/// Wraps the six parameters of
226/// [`PermissionChecker::check_advanced_permission`] into a self-documenting
227/// builder so callers don't need to remember parameter order.
228///
229/// # Example
230///
231/// ```rust,ignore
232/// use auth_framework::permissions::*;
233///
234/// let granted = checker.check_advanced(
235///     AdvancedPermissionCheck::new("user_123", &permission, &role_resolver)
236///         .user_attributes(&attrs)
237///         .abac_policy(&policy)
238///         .delegations(&delegations),
239/// );
240/// ```
241pub 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    /// Start building an advanced permission check with the required fields.
252    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    /// Provide user attributes for ABAC evaluation.
268    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    /// Provide an ABAC policy to evaluate against.
274    pub fn abac_policy(mut self, policy: &'a AbacPolicy) -> Self {
275        self.abac_policy = Some(policy);
276        self
277    }
278
279    /// Provide active delegations to consider.
280    pub fn delegations(mut self, delegations: &'a [Delegation]) -> Self {
281        self.delegations = Some(delegations);
282        self
283    }
284}
285
286impl PermissionChecker {
287    /// Check permission using an [`AdvancedPermissionCheck`] builder.
288    ///
289    /// This is the recommended entry point when combining RBAC, ABAC, and
290    /// delegation checks — it avoids the six positional parameters of the
291    /// legacy [`check_advanced_permission`](Self::check_advanced_permission).
292    ///
293    /// # Example
294    ///
295    /// ```rust,ignore
296    /// let allowed = checker.check_advanced(
297    ///     AdvancedPermissionCheck::new("user_1", &perm, &resolver)
298    ///         .user_attributes(&attrs)
299    ///         .abac_policy(&policy),
300    /// );
301    /// ```
302    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}
315/// Permission and role-based access control system.
316use crate::errors::{PermissionError, Result};
317use crate::tokens::AuthToken;
318use chrono;
319use serde::{Deserialize, Serialize};
320use serde_json;
321use std::collections::{HashMap, HashSet};
322
323/// Represents a permission with action and resource.
324#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
325pub struct Permission {
326    /// The action being performed (e.g., "read", "write", "delete")
327    pub action: String,
328
329    /// The resource being accessed (e.g., "documents", "users", "settings")
330    pub resource: String,
331
332    /// Optional resource instance (e.g., specific document ID)
333    pub instance: Option<String>,
334}
335
336/// Represents a role with associated permissions.
337#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct Role {
339    /// Optional unique identifier (populated when persisted via `AuthorizationEngine`)
340    pub id: Option<String>,
341
342    /// Role name
343    pub name: String,
344
345    /// Role description
346    pub description: Option<String>,
347
348    /// Permissions granted to this role
349    pub permissions: HashSet<Permission>,
350
351    /// Parent roles this role inherits from
352    pub parent_roles: HashSet<String>,
353
354    /// Whether this role is active
355    pub active: bool,
356
357    /// Arbitrary metadata key-value pairs
358    pub metadata: HashMap<String, String>,
359
360    /// When the role was created (populated when loaded from persistent storage)
361    pub created_at: Option<std::time::SystemTime>,
362
363    /// When the role was last modified
364    pub updated_at: Option<std::time::SystemTime>,
365}
366
367/// User permissions and roles.
368#[derive(Debug, Clone, Serialize, Deserialize)]
369pub struct UserPermissions {
370    /// User ID
371    pub user_id: String,
372
373    /// Direct permissions granted to the user
374    pub direct_permissions: HashSet<Permission>,
375
376    /// Roles assigned to the user
377    pub roles: HashSet<String>,
378
379    /// Cached computed permissions (includes role permissions)
380    pub computed_permissions: Option<HashSet<Permission>>,
381
382    /// When the permissions were last updated
383    pub last_updated: chrono::DateTime<chrono::Utc>,
384}
385
386/// Permission checker for validating access rights.
387#[derive(Debug, Clone)]
388pub struct PermissionChecker {
389    /// All defined roles
390    roles: HashMap<String, Role>,
391
392    /// User permissions cache
393    user_permissions: HashMap<String, UserPermissions>,
394
395    /// Permission hierarchy (for resource hierarchies)
396    resource_hierarchy: HashMap<String, Vec<String>>,
397}
398
399impl Permission {
400    /// Create a new permission.
401    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    /// Create a new permission with just an action (resource defaults to "*").
410    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    /// Create a new permission with a specific instance.
419    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    /// Parse a permission from a string format "action:resource" or "action:resource:instance".
432    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    /// Check if this permission matches another permission (considering wildcards).
457    pub fn matches(&self, other: &Permission) -> bool {
458        // Check action
459        if self.action != "*" && other.action != "*" && self.action != other.action {
460            return false;
461        }
462
463        // Check resource
464        if self.resource != "*" && other.resource != "*" && self.resource != other.resource {
465            return false;
466        }
467
468        // Check instance
469        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, // Specific instance doesn't match general permission
475            (None, Some(_)) => true,  // General permission matches specific instance
476        }
477    }
478
479    /// Check if this permission implies another permission.
480    pub fn implies(&self, other: &Permission) -> bool {
481        // A permission implies another if it's more general or equal
482        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, // General permission implies specific
486            (Some(self_instance), Some(other_instance)) => {
487                self_instance == "*" || self_instance == other_instance
488            }
489            (Some(_), None) => false, // Specific doesn't imply general
490        };
491
492        action_implies && resource_implies && instance_implies
493    }
494}
495
496impl Role {
497    /// Create a new role.
498    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    /// Set the role description.
513    pub fn with_description(mut self, description: impl Into<String>) -> Self {
514        self.description = Some(description.into());
515        self
516    }
517
518    /// Add a permission to the role.
519    pub fn add_permission(&mut self, permission: Permission) {
520        self.permissions.insert(permission);
521    }
522
523    /// Add multiple permissions to the role.
524    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    /// Add parent roles to the role.
532    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    /// Add metadata to the role.
544    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    /// Set the active status of the role.
557    pub fn with_active(mut self, active: bool) -> Self {
558        self.active = active;
559        self
560    }
561
562    /// Remove a permission from the role.
563    pub fn remove_permission(&mut self, permission: &Permission) {
564        self.permissions.remove(permission);
565    }
566
567    /// Add a parent role.
568    pub fn add_parent_role(&mut self, parent_role: impl Into<String>) {
569        self.parent_roles.insert(parent_role.into());
570    }
571
572    /// Check if the role has a specific permission.
573    pub fn has_permission(&self, permission: &Permission) -> bool {
574        self.permissions.iter().any(|p| p.implies(permission))
575    }
576
577    /// Get all permissions including inherited ones.
578    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        // Add permissions from parent roles
585        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    /// Activate or deactivate the role.
595    pub fn set_active(&mut self, active: bool) {
596        self.active = active;
597    }
598}
599
600impl PermissionChecker {
601    /// Remove all runtime roles, assignments, and cached permission state.
602    pub fn clear(&mut self) {
603        self.roles.clear();
604        self.user_permissions.clear();
605        self.resource_hierarchy.clear();
606    }
607
608    /// Return the currently assigned role names for a user.
609    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    /// Create new user permissions.
619    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    /// Add a direct permission to the user.
630    pub fn add_permission(&mut self, permission: Permission) {
631        self.direct_permissions.insert(permission);
632        self.computed_permissions = None; // Invalidate cache
633        self.last_updated = chrono::Utc::now();
634    }
635
636    /// Remove a direct permission from the user.
637    pub fn remove_permission(&mut self, permission: &Permission) {
638        self.direct_permissions.remove(permission);
639        self.computed_permissions = None; // Invalidate cache
640        self.last_updated = chrono::Utc::now();
641    }
642
643    /// Add a role to the user.
644    pub fn add_role(&mut self, role: impl Into<String>) {
645        self.roles.insert(role.into());
646        self.computed_permissions = None; // Invalidate cache
647        self.last_updated = chrono::Utc::now();
648    }
649
650    /// Remove a role from the user.
651    pub fn remove_role(&mut self, role: &str) {
652        self.roles.remove(role);
653        self.computed_permissions = None; // Invalidate cache
654        self.last_updated = chrono::Utc::now();
655    }
656
657    /// Compute all permissions for the user (including role permissions).
658    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            // Add permissions from roles
666            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        // SAFETY: guaranteed Some — either it was Some on entry or we just assigned it above.
678        self.computed_permissions
679            .as_ref()
680            .expect("computed_permissions is always Some after this block")
681    }
682
683    /// Check if the user has a specific permission.
684    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
694/// Returns `true` if `broader` is a higher-privilege action that implies `required`.
695///
696/// Action hierarchy:
697/// - `"manage"` / `"admin"` imply all common CRUD + management actions
698/// - `"write"` / `"update"` imply `"read"`
699fn broader_action_implies(broader: &str, required: &str) -> bool {
700    // Wildcard is handled in Permission::implies; exact match is handled before calling this.
701    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    /// Create a new permission checker.
716    pub fn new() -> Self {
717        Self {
718            roles: HashMap::new(),
719            user_permissions: HashMap::new(),
720            resource_hierarchy: HashMap::new(),
721        }
722    }
723
724    /// Add a role definition.
725    pub fn add_role(&mut self, role: Role) {
726        self.roles.insert(role.name.clone(), role);
727    }
728
729    /// Remove a role definition.
730    pub fn remove_role(&mut self, role_name: &str) {
731        self.roles.remove(role_name);
732    }
733
734    /// Get a role by name.
735    pub fn get_role(&self, role_name: &str) -> Option<&Role> {
736        self.roles.get(role_name)
737    }
738
739    /// Return all defined roles.
740    pub fn list_roles(&self) -> Vec<Role> {
741        self.roles.values().cloned().collect()
742    }
743
744    /// Set user permissions.
745    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    /// Get user permissions.
751    pub fn get_user_permissions(&self, user_id: &str) -> Option<&UserPermissions> {
752        self.user_permissions.get(user_id)
753    }
754
755    /// Get mutable user permissions.
756    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    /// Add a permission to a user.
761    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    /// Add a role to a user.
771    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    /// Remove a role from a user.
781    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    /// Count the number of defined roles.
788    pub fn role_count(&self) -> usize {
789        self.roles.len()
790    }
791
792    /// Count the number of users that have explicit permissions recorded.
793    pub fn user_count(&self) -> usize {
794        self.user_permissions.len()
795    }
796
797    /// Count the total number of direct permissions across all users.
798    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    /// Check if a user has a specific permission.
806    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    /// Check if a user has permission for a specific action on a resource.
817    pub fn check_access(&mut self, user_id: &str, action: &str, resource: &str) -> Result<bool> {
818        let permission = Permission::new(action, resource);
819
820        // First check direct permission
821        if self.check_permission(user_id, &permission)? {
822            return Ok(true);
823        }
824
825        // Check hierarchical permissions if direct permission not found
826        self.check_hierarchical_permission(user_id, action, resource)
827    }
828
829    /// Check if a user has permission for a specific action on a resource instance.
830    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    /// Check permission from an auth token.
842    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        // Check if the token has the required scope
852        let required_scope = permission.to_string();
853        if !token.has_scope(&required_scope) {
854            // Also check for wildcard scopes
855            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        // Check user permissions
868        self.check_permission(&token.user_id, permission)
869    }
870
871    /// Add resource hierarchy relationship
872    pub fn add_resource_hierarchy(&mut self, parent: String, children: Vec<String>) {
873        self.resource_hierarchy.insert(parent, children);
874    }
875
876    /// Get child resources for a parent resource
877    pub fn get_child_resources(&self, parent: &str) -> Option<&Vec<String>> {
878        self.resource_hierarchy.get(parent)
879    }
880
881    /// Check hierarchical permission - if user has permission on parent, they have it on children
882    pub fn check_hierarchical_permission(
883        &mut self,
884        user_id: &str,
885        action: &str,
886        resource: &str,
887    ) -> Result<bool> {
888        // Clone the hierarchy to avoid borrow checker issues
889        let hierarchy = self.resource_hierarchy.clone();
890
891        // Check all ancestor resources recursively
892        if self.has_ancestor_permission(&hierarchy, user_id, action, resource)? {
893            return Ok(true);
894        }
895
896        // Check for wildcard permissions that might apply
897        if self.check_wildcard_permissions(&hierarchy, user_id, action, resource)? {
898            return Ok(true);
899        }
900
901        Ok(false)
902    }
903
904    /// Check wildcard permissions that might apply to this resource
905    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        // Check if any parent resource has a wildcard permission that applies
913        for (parent_resource, children) in hierarchy {
914            if children.contains(&resource.to_string()) {
915                // Check for wildcard permission on parent (e.g., "projects.*" covering "documents")
916                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        // Also check direct wildcard on resource itself
927        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    /// Recursively check if user has permission on any ancestor resource
941    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        // Find direct parent resources
949        for (parent_resource, children) in hierarchy {
950            if children.contains(&resource.to_string()) {
951                // Check if user has the exact permission on the parent resource, OR any
952                // higher-privilege action that implies the required action (e.g. "manage"
953                // implies "read" and "write").
954                if self.check_permission_with_action_hierarchy(user_id, action, parent_resource)? {
955                    return Ok(true);
956                }
957
958                // Recursively check if user has permission on ancestor of this parent
959                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    /// Check if a user has permission for `action` on `resource`, considering action hierarchy.
969    ///
970    /// In addition to an exact match, higher-privilege actions imply less-privileged ones:
971    /// - `"manage"` / `"admin"` imply `"read"`, `"write"`, `"delete"`, `"create"`, `"list"`, `"update"`
972    /// - `"write"` / `"update"` imply `"read"`
973    fn check_permission_with_action_hierarchy(
974        &mut self,
975        user_id: &str,
976        required_action: &str,
977        resource: &str,
978    ) -> Result<bool> {
979        // First try exact match via the standard path
980        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        // Walk user's permissions and check action hierarchy
986        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    /// Create some default roles for common use cases.
1002    pub fn create_default_roles(&mut self) {
1003        // Admin role with all permissions
1004        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        // User role with basic permissions
1009        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        // Guest role with read-only access
1016        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    /// Load permissions from a configuration or database.
1023    pub fn load_permissions(&mut self, _config: &str) -> Result<()> {
1024        // This would typically load from a configuration file or database
1025        // For now, we'll create some default permissions
1026        self.create_default_roles();
1027        Ok(())
1028    }
1029
1030    /// Assign a role to a user.
1031    pub fn assign_role_to_user(&mut self, user_id: &str, role_name: &str) -> Result<()> {
1032        // Validate that role exists
1033        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        // Add role to user
1042        self.add_user_role(user_id, role_name);
1043        Ok(())
1044    }
1045
1046    /// Set role inheritance relationship.
1047    pub fn set_role_inheritance(&mut self, child_role: &str, parent_role: &str) -> Result<()> {
1048        // Validate that both roles exist
1049        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        // Update role inheritance
1065        if let Some(child) = self.roles.get_mut(child_role) {
1066            child.add_parent_role(parent_role);
1067        }
1068
1069        Ok(())
1070    }
1071
1072    /// Remove a permission from a user.
1073    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    /// Check if a user has a specific role.
1080    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    /// Get effective permissions for a user (including role-based permissions).
1089    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            // Create a mutable clone to compute permissions
1094            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); // Admin has all permissions
1191    }
1192}
1193
1194#[cfg(test)]
1195pub mod abac_delegation_tests;