Skip to main content

role_system/
context_integration.rs

1//! Contextual permission checking with external authentication contexts.
2
3use crate::{
4    auth_context::AuthenticationContext, core::RoleSystem, error::Result, resource::Resource,
5    storage::Storage, subject::Subject,
6};
7use std::collections::HashMap;
8
9// Extension methods for RoleSystem when working with AuthenticationContext
10pub trait ContextualPermissions<T: AuthenticationContext> {
11    /// Check permission using an authentication context
12    fn check_contextual_permission(
13        &self,
14        context: &T,
15        action: &str,
16        resource: &Resource,
17        additional_context: Option<HashMap<String, String>>,
18    ) -> Result<bool>;
19
20    /// Check permission against a list of required scopes
21    fn check_scope_permission(&self, context: &T, required_scopes: &[String]) -> Result<bool>;
22}
23
24impl<S, T> ContextualPermissions<T> for RoleSystem<S>
25where
26    S: Storage,
27    T: AuthenticationContext,
28{
29    /// Check permission using an authentication context.
30    ///
31    /// This method combines role-based permissions with any scopes/permissions
32    /// granted directly by the authentication context (e.g., JWT token scopes).
33    ///
34    /// # Arguments
35    ///
36    /// * `context` - The authentication context to use
37    /// * `action` - The action to check permission for
38    /// * `resource` - The resource to check permission for
39    /// * `additional_context` - Additional context values for conditional permissions
40    ///
41    /// # Returns
42    ///
43    /// `true` if permission is granted, `false` otherwise
44    fn check_contextual_permission(
45        &self,
46        context: &T,
47        action: &str,
48        resource: &Resource,
49        _additional_context: Option<HashMap<String, String>>, // Prefixed with _ to mark as intentionally unused
50    ) -> Result<bool> {
51        // 1. Check if context is valid
52        if !context.is_valid() {
53            #[cfg(feature = "audit")]
54            log::warn!(
55                "Permission check denied: invalid authentication context for action '{}' on resource '{}'",
56                action,
57                resource.id()
58            );
59
60            return Ok(false);
61        }
62
63        // 2. Check if the context grants the permission directly through scopes
64        let permission_string = format!("{}:{}", action, resource.resource_type());
65        let instance_permission_string =
66            format!("{}:{}:{}", action, resource.resource_type(), resource.id());
67
68        let granted_scopes = context.get_granted_scopes();
69        let has_scope = granted_scopes.iter().any(|scope| {
70            scope == &permission_string
71                || scope == &instance_permission_string
72                || scope == "*:*"
73                || scope == &format!("*:{}", resource.resource_type())
74                || scope == &format!("{}:*", action)
75        });
76
77        if has_scope {
78            #[cfg(feature = "audit")]
79            log::info!(
80                "Permission granted via authentication context scope for action '{}' on resource '{}'",
81                action,
82                resource.id()
83            );
84
85            return Ok(true);
86        }
87
88        // 3. Check role-based permissions for the user from the context
89        let subject = Subject::user(context.get_user_id().as_ref() as &str);
90
91        // Note: We're not using the additional_context or context data
92        // from the authentication context for now
93
94        // Delegate to the standard permission check
95        self.check_permission(&subject, action, resource)
96    }
97
98    /// Check permission against a list of required scopes.
99    ///
100    /// This is useful for API endpoints that require specific scopes.
101    ///
102    /// # Arguments
103    ///
104    /// * `context` - The authentication context to use
105    /// * `required_scopes` - List of required scopes (any match grants permission)
106    ///
107    /// # Returns
108    ///
109    /// `true` if any required scope is granted, `false` otherwise
110    fn check_scope_permission(&self, context: &T, required_scopes: &[String]) -> Result<bool> {
111        // Check if context is valid
112        if !context.is_valid() {
113            return Ok(false);
114        }
115
116        let granted_scopes = context.get_granted_scopes();
117
118        // Check if any required scope is present in granted scopes
119        for required in required_scopes {
120            if granted_scopes.contains(required) {
121                return Ok(true);
122            }
123
124            // Check for wildcard scopes
125            if required.contains(':') {
126                // Split into parts (e.g., "read:documents")
127                let parts: Vec<&str> = required.split(':').collect();
128
129                // Check if wildcards cover this scope
130                if granted_scopes.contains(&"*:*".to_string()) {
131                    return Ok(true);
132                }
133
134                if parts.len() >= 2 {
135                    let action = parts[0];
136                    let resource = parts[1];
137
138                    // Check action wildcards (e.g., "*:documents")
139                    if granted_scopes.contains(&format!("*:{}", resource)) {
140                        return Ok(true);
141                    }
142
143                    // Check resource wildcards (e.g., "read:*")
144                    if granted_scopes.contains(&format!("{}:*", action)) {
145                        return Ok(true);
146                    }
147                }
148            }
149        }
150
151        Ok(false)
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use crate::auth_context::JwtContext;
159    use crate::core::RoleSystem;
160    use crate::permission::Permission;
161    use crate::role::Role;
162    use std::collections::HashMap;
163
164    #[test]
165    fn test_jwt_context_permissions() {
166        let mut role_system = RoleSystem::new();
167
168        // Create and register roles
169        let editor = Role::new("editor")
170            .add_permission(Permission::new("edit", "documents"))
171            .add_permission(Permission::new("read", "documents"));
172
173        role_system.register_role(editor).unwrap();
174
175        // Create a simple HashMap for the payload instead of using serde_json
176        let mut payload = HashMap::new();
177        payload.insert("exp".to_string(), "1625097600".to_string());
178        payload.insert("iat".to_string(), "1625011200".to_string());
179
180        // Create JWT context with direct scope grants
181        let context = JwtContext::new(
182            "user123".to_string(),
183            vec!["read:documents".to_string()],
184            true,
185            payload,
186        );
187
188        // Test document resource
189        let document = Resource::new("doc1", "documents");
190
191        // Direct scope permission should be granted
192        assert!(
193            role_system
194                .check_contextual_permission(&context, "read", &document, None)
195                .unwrap()
196        );
197
198        // Permission not in token scopes should be denied (since user has no roles)
199        assert!(
200            !role_system
201                .check_contextual_permission(&context, "edit", &document, None)
202                .unwrap()
203        );
204
205        // Now assign the editor role to the user
206        let subject = Subject::user(context.get_user_id().as_ref() as &str);
207        role_system.assign_role(&subject, "editor").unwrap();
208
209        // Now edit permission should be granted via role
210        assert!(
211            role_system
212                .check_contextual_permission(&context, "edit", &document, None)
213                .unwrap()
214        );
215    }
216
217    #[test]
218    fn test_scope_permission() {
219        let role_system = RoleSystem::new();
220
221        // Create a simple HashMap for the payload
222        let payload = HashMap::new();
223
224        // Create JWT context with scopes
225        let context = JwtContext::new(
226            "user123".to_string(),
227            vec!["read:documents".to_string(), "write:posts".to_string()],
228            true,
229            payload,
230        );
231
232        // Check individual scope permissions
233        assert!(
234            role_system
235                .check_scope_permission(&context, &["read:documents".to_string()])
236                .unwrap()
237        );
238        assert!(
239            role_system
240                .check_scope_permission(&context, &["write:posts".to_string()])
241                .unwrap()
242        );
243        assert!(
244            !role_system
245                .check_scope_permission(&context, &["admin:users".to_string()])
246                .unwrap()
247        );
248
249        // Check multiple required scopes (any match should succeed)
250        assert!(
251            role_system
252                .check_scope_permission(
253                    &context,
254                    &["read:documents".to_string(), "admin:users".to_string()]
255                )
256                .unwrap()
257        );
258
259        // Check with wildcard
260        let admin_context = JwtContext::new(
261            "admin".to_string(),
262            vec!["*:*".to_string()],
263            true,
264            HashMap::new(),
265        );
266
267        assert!(
268            role_system
269                .check_scope_permission(&admin_context, &["read:any".to_string()])
270                .unwrap()
271        );
272        assert!(
273            role_system
274                .check_scope_permission(&admin_context, &["admin:users".to_string()])
275                .unwrap()
276        );
277    }
278}