role_system/
context_integration.rs1use crate::{
4 auth_context::AuthenticationContext, core::RoleSystem, error::Result, resource::Resource,
5 storage::Storage, subject::Subject,
6};
7use std::collections::HashMap;
8
9pub trait ContextualPermissions<T: AuthenticationContext> {
11 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 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 fn check_contextual_permission(
45 &self,
46 context: &T,
47 action: &str,
48 resource: &Resource,
49 _additional_context: Option<HashMap<String, String>>, ) -> Result<bool> {
51 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 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 let subject = Subject::user(context.get_user_id().as_ref() as &str);
90
91 self.check_permission(&subject, action, resource)
96 }
97
98 fn check_scope_permission(&self, context: &T, required_scopes: &[String]) -> Result<bool> {
111 if !context.is_valid() {
113 return Ok(false);
114 }
115
116 let granted_scopes = context.get_granted_scopes();
117
118 for required in required_scopes {
120 if granted_scopes.contains(required) {
121 return Ok(true);
122 }
123
124 if required.contains(':') {
126 let parts: Vec<&str> = required.split(':').collect();
128
129 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 if granted_scopes.contains(&format!("*:{}", resource)) {
140 return Ok(true);
141 }
142
143 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 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 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 let context = JwtContext::new(
182 "user123".to_string(),
183 vec!["read:documents".to_string()],
184 true,
185 payload,
186 );
187
188 let document = Resource::new("doc1", "documents");
190
191 assert!(
193 role_system
194 .check_contextual_permission(&context, "read", &document, None)
195 .unwrap()
196 );
197
198 assert!(
200 !role_system
201 .check_contextual_permission(&context, "edit", &document, None)
202 .unwrap()
203 );
204
205 let subject = Subject::user(context.get_user_id().as_ref() as &str);
207 role_system.assign_role(&subject, "editor").unwrap();
208
209 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 let payload = HashMap::new();
223
224 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 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 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 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}