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 Default for AbacPolicy {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl AbacPolicy {
38    /// Create a new empty ABAC policy.
39    pub fn new() -> Self {
40        Self {
41            attributes: HashMap::new(),
42            rules: Vec::new(),
43        }
44    }
45
46    /// Add an attribute to the policy.
47    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    /// Add multiple attributes to the policy.
53    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    /// Add a rule to the policy.
65    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    /// Add multiple rules to the policy.
80    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/// Permission delegation record.
90///
91/// Represents a delegator granting a subset of their permissions to a delegatee,
92/// optionally for a limited time window.
93#[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    /// Create a new delegation with required fields.
103    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    /// Add permissions to the delegation.
113    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    /// Add a single permission to the delegation.
122    pub fn with_permission(mut self, permission: Permission) -> Self {
123        self.permissions.insert(permission);
124        self
125    }
126
127    /// Set the expiration time for the delegation.
128    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    /// Set the delegation to never expire.
134    pub fn permanent(mut self) -> Self {
135        self.expires_at = None;
136        self
137    }
138}
139
140impl PermissionChecker {
141    /// Check permission for a user with ABAC and delegation support.
142    ///
143    /// This is the low-level API with positional parameters.  For a more
144    /// readable alternative, use [`check_advanced`](Self::check_advanced)
145    /// with an [`AdvancedPermissionCheck`] builder.
146    ///
147    /// # Arguments
148    ///
149    /// * `user_id` — the user to check
150    /// * `permission` — the required permission
151    /// * `user_attributes` — runtime attributes for ABAC evaluation
152    /// * `abac_policy` — optional ABAC policy
153    /// * `delegations` — optional active delegations
154    /// * `role_resolver` — closure that resolves role names to definitions
155    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        // Check direct and role permissions
165        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        // Check ABAC policy
173        if let Some(policy) = abac_policy
174            && self.check_abac(user_attributes, permission, policy)
175        {
176            return true;
177        }
178        // Check delegation
179        if let Some(delegations) = delegations
180            && self.check_delegation(user_id, permission, delegations)
181        {
182            return true;
183        }
184        false
185    }
186    /// Check permission with ABAC policy
187    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    /// Check permission with delegation
205    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
227/// Builder for constructing an advanced permission check with ABAC policies,
228/// delegations, and role resolution.
229///
230/// Wraps the six parameters of
231/// [`PermissionChecker::check_advanced_permission`] into a self-documenting
232/// builder so callers don't need to remember parameter order.
233///
234/// # Example
235///
236/// ```rust,ignore
237/// use auth_framework::permissions::*;
238///
239/// let granted = checker.check_advanced(
240///     AdvancedPermissionCheck::new("user_123", &permission, &role_resolver)
241///         .user_attributes(&attrs)
242///         .abac_policy(&policy)
243///         .delegations(&delegations),
244/// );
245/// ```
246pub 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    /// Start building an advanced permission check with the required fields.
257    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    /// Provide user attributes for ABAC evaluation.
273    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    /// Provide an ABAC policy to evaluate against.
279    pub fn abac_policy(mut self, policy: &'a AbacPolicy) -> Self {
280        self.abac_policy = Some(policy);
281        self
282    }
283
284    /// Provide active delegations to consider.
285    pub fn delegations(mut self, delegations: &'a [Delegation]) -> Self {
286        self.delegations = Some(delegations);
287        self
288    }
289}
290
291impl PermissionChecker {
292    /// Check permission using an [`AdvancedPermissionCheck`] builder.
293    ///
294    /// This is the recommended entry point when combining RBAC, ABAC, and
295    /// delegation checks — it avoids the six positional parameters of the
296    /// legacy [`check_advanced_permission`](Self::check_advanced_permission).
297    ///
298    /// # Example
299    ///
300    /// ```rust,ignore
301    /// let allowed = checker.check_advanced(
302    ///     AdvancedPermissionCheck::new("user_1", &perm, &resolver)
303    ///         .user_attributes(&attrs)
304    ///         .abac_policy(&policy),
305    /// );
306    /// ```
307    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}
320/// Permission and role-based access control system.
321use crate::errors::{PermissionError, Result};
322use crate::tokens::AuthToken;
323use chrono;
324use serde::{Deserialize, Serialize};
325use serde_json;
326use std::collections::{HashMap, HashSet};
327
328/// Represents a permission with action and resource.
329#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
330pub struct Permission {
331    /// The action being performed (e.g., "read", "write", "delete")
332    pub action: String,
333
334    /// The resource being accessed (e.g., "documents", "users", "settings")
335    pub resource: String,
336
337    /// Optional resource instance (e.g., specific document ID)
338    pub instance: Option<String>,
339}
340
341/// Represents a role with associated permissions.
342#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct Role {
344    /// Optional unique identifier (populated when persisted via `AuthorizationEngine`)
345    pub id: Option<String>,
346
347    /// Role name
348    pub name: String,
349
350    /// Role description
351    pub description: Option<String>,
352
353    /// Permissions granted to this role
354    pub permissions: HashSet<Permission>,
355
356    /// Parent roles this role inherits from
357    pub parent_roles: HashSet<String>,
358
359    /// Whether this role is active
360    pub active: bool,
361
362    /// Arbitrary metadata key-value pairs
363    pub metadata: HashMap<String, String>,
364
365    /// When the role was created (populated when loaded from persistent storage)
366    pub created_at: Option<std::time::SystemTime>,
367
368    /// When the role was last modified
369    pub updated_at: Option<std::time::SystemTime>,
370}
371
372/// User permissions and roles.
373#[derive(Debug, Clone, Serialize, Deserialize)]
374pub struct UserPermissions {
375    /// User ID
376    pub user_id: String,
377
378    /// Direct permissions granted to the user
379    pub direct_permissions: HashSet<Permission>,
380
381    /// Roles assigned to the user
382    pub roles: HashSet<String>,
383
384    /// Cached computed permissions (includes role permissions)
385    pub computed_permissions: Option<HashSet<Permission>>,
386
387    /// When the permissions were last updated
388    pub last_updated: chrono::DateTime<chrono::Utc>,
389}
390
391/// Permission checker for validating access rights.
392#[derive(Debug, Clone)]
393pub struct PermissionChecker {
394    /// All defined roles
395    roles: HashMap<String, Role>,
396
397    /// User permissions cache
398    user_permissions: HashMap<String, UserPermissions>,
399
400    /// Permission hierarchy (for resource hierarchies)
401    resource_hierarchy: HashMap<String, Vec<String>>,
402}
403
404impl Permission {
405    /// Create a new permission.
406    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    /// Create a new permission with just an action (resource defaults to "*").
415    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    /// Create a new permission with a specific instance.
424    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    /// Parse a permission from a string format "action:resource" or "action:resource:instance".
437    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    /// Check if this permission matches another permission (considering wildcards).
462    pub fn matches(&self, other: &Permission) -> bool {
463        // Check action
464        if self.action != "*" && other.action != "*" && self.action != other.action {
465            return false;
466        }
467
468        // Check resource
469        if self.resource != "*" && other.resource != "*" && self.resource != other.resource {
470            return false;
471        }
472
473        // Check instance
474        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, // Specific instance doesn't match general permission
480            (None, Some(_)) => true,  // General permission matches specific instance
481        }
482    }
483
484    /// Check if this permission implies another permission.
485    pub fn implies(&self, other: &Permission) -> bool {
486        // A permission implies another if it's more general or equal
487        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, // General permission implies specific
491            (Some(self_instance), Some(other_instance)) => {
492                self_instance == "*" || self_instance == other_instance
493            }
494            (Some(_), None) => false, // Specific doesn't imply general
495        };
496
497        action_implies && resource_implies && instance_implies
498    }
499}
500
501impl Role {
502    /// Create a new role.
503    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    /// Set the role description.
518    pub fn with_description(mut self, description: impl Into<String>) -> Self {
519        self.description = Some(description.into());
520        self
521    }
522
523    /// Add a permission to the role.
524    pub fn add_permission(&mut self, permission: Permission) {
525        self.permissions.insert(permission);
526    }
527
528    /// Add multiple permissions to the role.
529    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    /// Add parent roles to the role.
537    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    /// Add metadata to the role.
549    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    /// Set the active status of the role.
562    pub fn with_active(mut self, active: bool) -> Self {
563        self.active = active;
564        self
565    }
566
567    /// Remove a permission from the role.
568    pub fn remove_permission(&mut self, permission: &Permission) {
569        self.permissions.remove(permission);
570    }
571
572    /// Add a parent role.
573    pub fn add_parent_role(&mut self, parent_role: impl Into<String>) {
574        self.parent_roles.insert(parent_role.into());
575    }
576
577    /// Check if the role has a specific permission.
578    pub fn has_permission(&self, permission: &Permission) -> bool {
579        self.permissions.iter().any(|p| p.implies(permission))
580    }
581
582    /// Get all permissions including inherited ones.
583    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        // Add permissions from parent roles
590        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    /// Activate or deactivate the role.
600    pub fn set_active(&mut self, active: bool) {
601        self.active = active;
602    }
603}
604
605impl PermissionChecker {
606    /// Remove all runtime roles, assignments, and cached permission state.
607    pub fn clear(&mut self) {
608        self.roles.clear();
609        self.user_permissions.clear();
610        self.resource_hierarchy.clear();
611    }
612
613    /// Return the currently assigned role names for a user.
614    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    /// Create new user permissions.
624    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    /// Add a direct permission to the user.
635    pub fn add_permission(&mut self, permission: Permission) {
636        self.direct_permissions.insert(permission);
637        self.computed_permissions = None; // Invalidate cache
638        self.last_updated = chrono::Utc::now();
639    }
640
641    /// Remove a direct permission from the user.
642    pub fn remove_permission(&mut self, permission: &Permission) {
643        self.direct_permissions.remove(permission);
644        self.computed_permissions = None; // Invalidate cache
645        self.last_updated = chrono::Utc::now();
646    }
647
648    /// Add a role to the user.
649    pub fn add_role(&mut self, role: impl Into<String>) {
650        self.roles.insert(role.into());
651        self.computed_permissions = None; // Invalidate cache
652        self.last_updated = chrono::Utc::now();
653    }
654
655    /// Remove a role from the user.
656    pub fn remove_role(&mut self, role: &str) {
657        self.roles.remove(role);
658        self.computed_permissions = None; // Invalidate cache
659        self.last_updated = chrono::Utc::now();
660    }
661
662    /// Compute all permissions for the user (including role permissions).
663    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            // Add permissions from roles
671            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        // SAFETY: guaranteed Some — either it was Some on entry or we just assigned it above.
683        self.computed_permissions
684            .as_ref()
685            .expect("computed_permissions is always Some after this block")
686    }
687
688    /// Check if the user has a specific permission.
689    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
699/// Returns `true` if `broader` is a higher-privilege action that implies `required`.
700///
701/// Action hierarchy:
702/// - `"manage"` / `"admin"` imply all common CRUD + management actions
703/// - `"write"` / `"update"` imply `"read"`
704fn broader_action_implies(broader: &str, required: &str) -> bool {
705    // Wildcard is handled in Permission::implies; exact match is handled before calling this.
706    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    /// Create a new permission checker.
721    pub fn new() -> Self {
722        Self {
723            roles: HashMap::new(),
724            user_permissions: HashMap::new(),
725            resource_hierarchy: HashMap::new(),
726        }
727    }
728
729    /// Add a role definition.
730    pub fn add_role(&mut self, role: Role) {
731        self.roles.insert(role.name.clone(), role);
732    }
733
734    /// Remove a role definition.
735    pub fn remove_role(&mut self, role_name: &str) {
736        self.roles.remove(role_name);
737    }
738
739    /// Get a role by name.
740    pub fn get_role(&self, role_name: &str) -> Option<&Role> {
741        self.roles.get(role_name)
742    }
743
744    /// Return all defined roles.
745    pub fn list_roles(&self) -> Vec<Role> {
746        self.roles.values().cloned().collect()
747    }
748
749    /// Set user permissions.
750    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    /// Get user permissions.
756    pub fn get_user_permissions(&self, user_id: &str) -> Option<&UserPermissions> {
757        self.user_permissions.get(user_id)
758    }
759
760    /// Get mutable user permissions.
761    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    /// Add a permission to a user.
766    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    /// Add a role to a user.
776    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    /// Remove a role from a user.
786    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    /// Count the number of defined roles.
793    pub fn role_count(&self) -> usize {
794        self.roles.len()
795    }
796
797    /// Count the number of users that have explicit permissions recorded.
798    pub fn user_count(&self) -> usize {
799        self.user_permissions.len()
800    }
801
802    /// Count the total number of direct permissions across all users.
803    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    /// Check if a user has a specific permission.
811    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    /// Check if a user has permission for a specific action on a resource.
822    pub fn check_access(&mut self, user_id: &str, action: &str, resource: &str) -> Result<bool> {
823        let permission = Permission::new(action, resource);
824
825        // First check direct permission
826        if self.check_permission(user_id, &permission)? {
827            return Ok(true);
828        }
829
830        // Check hierarchical permissions if direct permission not found
831        self.check_hierarchical_permission(user_id, action, resource)
832    }
833
834    /// Check if a user has permission for a specific action on a resource instance.
835    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    /// Check permission from an auth token.
847    pub fn check_token_permission(
848        &mut self,
849        token: &AuthToken,
850        permission: &Permission,
851    ) -> Result<bool> {
852        if !token.is_valid() {
853            return Ok(false);
854        }
855
856        // Check if the token has the required scope
857        let required_scope = permission.to_string();
858        if !token.has_scope(&required_scope) {
859            // Also check for wildcard scopes
860            let wildcard_action = format!("*:{}", permission.resource);
861            let wildcard_resource = format!("{}:*", permission.action);
862            let wildcard_all = "*:*".to_string();
863
864            if !token.has_scope(&wildcard_action)
865                && !token.has_scope(&wildcard_resource)
866                && !token.has_scope(&wildcard_all)
867            {
868                return Ok(false);
869            }
870        }
871
872        // Check user permissions
873        self.check_permission(&token.user_id, permission)
874    }
875
876    /// Add resource hierarchy relationship
877    pub fn add_resource_hierarchy(&mut self, parent: String, children: Vec<String>) {
878        self.resource_hierarchy.insert(parent, children);
879    }
880
881    /// Get child resources for a parent resource
882    pub fn get_child_resources(&self, parent: &str) -> Option<&Vec<String>> {
883        self.resource_hierarchy.get(parent)
884    }
885
886    /// Check hierarchical permission - if user has permission on parent, they have it on children
887    pub fn check_hierarchical_permission(
888        &mut self,
889        user_id: &str,
890        action: &str,
891        resource: &str,
892    ) -> Result<bool> {
893        // Clone the hierarchy to avoid borrow checker issues
894        let hierarchy = self.resource_hierarchy.clone();
895
896        // Check all ancestor resources recursively
897        if self.has_ancestor_permission(&hierarchy, user_id, action, resource)? {
898            return Ok(true);
899        }
900
901        // Check for wildcard permissions that might apply
902        if self.check_wildcard_permissions(&hierarchy, user_id, action, resource)? {
903            return Ok(true);
904        }
905
906        Ok(false)
907    }
908
909    /// Check wildcard permissions that might apply to this resource
910    fn check_wildcard_permissions(
911        &mut self,
912        hierarchy: &HashMap<String, Vec<String>>,
913        user_id: &str,
914        action: &str,
915        resource: &str,
916    ) -> Result<bool> {
917        // Check if any parent resource has a wildcard permission that applies
918        for (parent_resource, children) in hierarchy {
919            if children.contains(&resource.to_string()) {
920                // Check for wildcard permission on parent (e.g., "projects.*" covering "documents")
921                let wildcard_permission = Permission::new(action, format!("{}.*", parent_resource));
922                if self
923                    .check_permission(user_id, &wildcard_permission)
924                    .unwrap_or(false)
925                {
926                    return Ok(true);
927                }
928            }
929        }
930
931        // Also check direct wildcard on resource itself
932        if let Some(_children) = hierarchy.get(resource) {
933            let wildcard_permission = Permission::new(action, format!("{}.*", resource));
934            if self
935                .check_permission(user_id, &wildcard_permission)
936                .unwrap_or(false)
937            {
938                return Ok(true);
939            }
940        }
941
942        Ok(false)
943    }
944
945    /// Recursively check if user has permission on any ancestor resource
946    fn has_ancestor_permission(
947        &mut self,
948        hierarchy: &HashMap<String, Vec<String>>,
949        user_id: &str,
950        action: &str,
951        resource: &str,
952    ) -> Result<bool> {
953        // Find direct parent resources
954        for (parent_resource, children) in hierarchy {
955            if children.contains(&resource.to_string()) {
956                // Check if user has the exact permission on the parent resource, OR any
957                // higher-privilege action that implies the required action (e.g. "manage"
958                // implies "read" and "write").
959                if self.check_permission_with_action_hierarchy(user_id, action, parent_resource)? {
960                    return Ok(true);
961                }
962
963                // Recursively check if user has permission on ancestor of this parent
964                if self.has_ancestor_permission(hierarchy, user_id, action, parent_resource)? {
965                    return Ok(true);
966                }
967            }
968        }
969
970        Ok(false)
971    }
972
973    /// Check if a user has permission for `action` on `resource`, considering action hierarchy.
974    ///
975    /// In addition to an exact match, higher-privilege actions imply less-privileged ones:
976    /// - `"manage"` / `"admin"` imply `"read"`, `"write"`, `"delete"`, `"create"`, `"list"`, `"update"`
977    /// - `"write"` / `"update"` imply `"read"`
978    fn check_permission_with_action_hierarchy(
979        &mut self,
980        user_id: &str,
981        required_action: &str,
982        resource: &str,
983    ) -> Result<bool> {
984        // First try exact match via the standard path
985        let exact = Permission::new(required_action, resource);
986        if self.check_permission(user_id, &exact).unwrap_or(false) {
987            return Ok(true);
988        }
989
990        // Walk user's permissions and check action hierarchy
991        let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
992        let user_perms = match self.user_permissions.get_mut(user_id) {
993            Some(p) => p,
994            None => return Ok(false),
995        };
996        let all_perms = user_perms.compute_permissions(&role_resolver);
997
998        Ok(all_perms.iter().any(|p| {
999            let resource_match = p.resource == "*" || p.resource == resource;
1000            let action_match =
1001                p.action == "*" || broader_action_implies(&p.action, required_action);
1002            resource_match && action_match
1003        }))
1004    }
1005
1006    /// Create some default roles for common use cases.
1007    pub fn create_default_roles(&mut self) {
1008        // Admin role with all permissions
1009        let mut admin_role = Role::new("admin").with_description("Administrator with full access");
1010        admin_role.add_permission(Permission::new("*", "*"));
1011        self.add_role(admin_role);
1012
1013        // User role with basic permissions
1014        let mut user_role = Role::new("user").with_description("Regular user with basic access");
1015        user_role.add_permission(Permission::new("read", "profile"));
1016        user_role.add_permission(Permission::new("write", "profile"));
1017        user_role.add_permission(Permission::new("read", "public"));
1018        self.add_role(user_role);
1019
1020        // Guest role with read-only access
1021        let mut guest_role =
1022            Role::new("guest").with_description("Guest user with read-only access");
1023        guest_role.add_permission(Permission::new("read", "public"));
1024        self.add_role(guest_role);
1025    }
1026
1027    /// Load permissions from a configuration or database.
1028    pub fn load_permissions(&mut self, _config: &str) -> Result<()> {
1029        // This would typically load from a configuration file or database
1030        // For now, we'll create some default permissions
1031        self.create_default_roles();
1032        Ok(())
1033    }
1034
1035    /// Assign a role to a user.
1036    pub fn assign_role_to_user(&mut self, user_id: &str, role_name: &str) -> Result<()> {
1037        // Validate that role exists
1038        if !self.roles.contains_key(role_name) {
1039            return Err(PermissionError::access_denied(
1040                role_name.to_string(),
1041                "Role does not exist".to_string(),
1042            )
1043            .into());
1044        }
1045
1046        // Add role to user
1047        self.add_user_role(user_id, role_name);
1048        Ok(())
1049    }
1050
1051    /// Set role inheritance relationship.
1052    pub fn set_role_inheritance(&mut self, child_role: &str, parent_role: &str) -> Result<()> {
1053        // Validate that both roles exist
1054        if !self.roles.contains_key(child_role) {
1055            return Err(PermissionError::access_denied(
1056                child_role.to_string(),
1057                "Child role does not exist".to_string(),
1058            )
1059            .into());
1060        }
1061        if !self.roles.contains_key(parent_role) {
1062            return Err(PermissionError::access_denied(
1063                parent_role.to_string(),
1064                "Parent role does not exist".to_string(),
1065            )
1066            .into());
1067        }
1068
1069        // Update role inheritance
1070        if let Some(child) = self.roles.get_mut(child_role) {
1071            child.add_parent_role(parent_role);
1072        }
1073
1074        Ok(())
1075    }
1076
1077    /// Remove a permission from a user.
1078    pub fn remove_user_permission(&mut self, user_id: &str, permission: &Permission) {
1079        if let Some(user_perms) = self.user_permissions.get_mut(user_id) {
1080            user_perms.remove_permission(permission);
1081        }
1082    }
1083
1084    /// Check if a user has a specific role.
1085    pub fn user_has_role(&self, user_id: &str, role_name: &str) -> bool {
1086        if let Some(user_perms) = self.user_permissions.get(user_id) {
1087            user_perms.roles.contains(role_name)
1088        } else {
1089            false
1090        }
1091    }
1092
1093    /// Get effective permissions for a user (including role-based permissions).
1094    pub fn get_effective_permissions(&self, user_id: &str) -> Vec<String> {
1095        if let Some(user_perms) = self.user_permissions.get(user_id) {
1096            let role_resolver = |role_name: &str| self.roles.get(role_name).cloned();
1097
1098            // Create a mutable clone to compute permissions
1099            let mut user_perms_clone = user_perms.clone();
1100            let all_permissions = user_perms_clone.compute_permissions(&role_resolver);
1101
1102            all_permissions.iter().map(|p| p.to_string()).collect()
1103        } else {
1104            Vec::new()
1105        }
1106    }
1107}
1108
1109impl Default for PermissionChecker {
1110    fn default() -> Self {
1111        Self::new()
1112    }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118
1119    #[test]
1120    fn test_permission_parsing() {
1121        let perm = Permission::parse("read:documents").unwrap();
1122        assert_eq!(perm.action, "read");
1123        assert_eq!(perm.resource, "documents");
1124        assert_eq!(perm.instance, None);
1125
1126        let perm = Permission::parse("write:documents:123").unwrap();
1127        assert_eq!(perm.action, "write");
1128        assert_eq!(perm.resource, "documents");
1129        assert_eq!(perm.instance, Some("123".to_string()));
1130    }
1131
1132    #[test]
1133    fn test_permission_matching() {
1134        let perm1 = Permission::new("read", "documents");
1135        let perm2 = Permission::new("read", "documents");
1136        let perm3 = Permission::new("write", "documents");
1137        let wildcard = Permission::new("*", "documents");
1138
1139        assert!(perm1.matches(&perm2));
1140        assert!(!perm1.matches(&perm3));
1141        assert!(wildcard.matches(&perm1));
1142        assert!(wildcard.matches(&perm3));
1143    }
1144
1145    #[test]
1146    fn test_permission_implies() {
1147        let general = Permission::new("read", "documents");
1148        let specific = Permission::with_instance("read", "documents", "123");
1149        let wildcard = Permission::new("*", "*");
1150
1151        assert!(general.implies(&specific));
1152        assert!(!specific.implies(&general));
1153        assert!(wildcard.implies(&general));
1154        assert!(wildcard.implies(&specific));
1155    }
1156
1157    #[test]
1158    fn test_role_permissions() {
1159        let mut role = Role::new("editor");
1160        role.add_permission(Permission::new("read", "documents"));
1161        role.add_permission(Permission::new("write", "documents"));
1162
1163        let read_perm = Permission::new("read", "documents");
1164        let delete_perm = Permission::new("delete", "documents");
1165
1166        assert!(role.has_permission(&read_perm));
1167        assert!(!role.has_permission(&delete_perm));
1168    }
1169
1170    #[test]
1171    fn test_user_permissions() {
1172        let mut user_perms = UserPermissions::new("user123");
1173        user_perms.add_permission(Permission::new("read", "profile"));
1174        user_perms.add_role("user");
1175
1176        let role_resolver = |_: &str| Some(Role::new("user"));
1177
1178        let read_perm = Permission::new("read", "profile");
1179        assert!(user_perms.has_permission(&read_perm, &role_resolver));
1180    }
1181
1182    #[test]
1183    fn test_permission_checker() {
1184        let mut checker = PermissionChecker::new();
1185        checker.create_default_roles();
1186
1187        checker.add_user_role("user123", "admin");
1188
1189        let result = checker
1190            .check_access("user123", "read", "documents")
1191            .unwrap();
1192        assert!(result);
1193
1194        let result = checker.check_access("user123", "delete", "system").unwrap();
1195        assert!(result); // Admin has all permissions
1196    }
1197}
1198
1199#[cfg(test)]
1200pub mod abac_delegation_tests;