oxigdal-security 0.1.7

Enterprise security features for OxiGDAL: encryption, access control, compliance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Role-Based Access Control (RBAC).

use crate::access_control::{
    AccessControlEvaluator, AccessDecision, AccessRequest, Action, ResourceType,
    permissions::Permission, roles::Role,
};
use crate::error::{Result, SecurityError};
use dashmap::DashMap;
use std::collections::HashSet;
use std::sync::Arc;

/// RBAC policy engine.
pub struct RbacEngine {
    /// Role assignments (subject_id -> role_ids).
    role_assignments: Arc<DashMap<String, HashSet<String>>>,
    /// Roles (role_id -> Role).
    roles: Arc<DashMap<String, Role>>,
    /// Permissions (permission_id -> Permission).
    permissions: Arc<DashMap<String, Permission>>,
    /// Role inheritance (child_role_id -> parent_role_ids).
    role_inheritance: Arc<DashMap<String, HashSet<String>>>,
}

impl RbacEngine {
    /// Create a new RBAC engine.
    pub fn new() -> Self {
        Self {
            role_assignments: Arc::new(DashMap::new()),
            roles: Arc::new(DashMap::new()),
            permissions: Arc::new(DashMap::new()),
            role_inheritance: Arc::new(DashMap::new()),
        }
    }

    /// Add a role.
    pub fn add_role(&self, role: Role) -> Result<()> {
        self.roles.insert(role.id.clone(), role);
        Ok(())
    }

    /// Get a role by ID.
    pub fn get_role(&self, role_id: &str) -> Option<Role> {
        self.roles.get(role_id).map(|r| r.clone())
    }

    /// Remove a role.
    pub fn remove_role(&self, role_id: &str) -> Result<()> {
        self.roles.remove(role_id);
        self.role_inheritance.remove(role_id);

        // Remove role assignments
        for mut assignment in self.role_assignments.iter_mut() {
            assignment.value_mut().remove(role_id);
        }

        Ok(())
    }

    /// List all roles.
    pub fn list_roles(&self) -> Vec<Role> {
        self.roles.iter().map(|r| r.value().clone()).collect()
    }

    /// Add a permission.
    pub fn add_permission(&self, permission: Permission) -> Result<()> {
        self.permissions.insert(permission.id.clone(), permission);
        Ok(())
    }

    /// Get a permission by ID.
    pub fn get_permission(&self, permission_id: &str) -> Option<Permission> {
        self.permissions.get(permission_id).map(|p| p.clone())
    }

    /// Assign a role to a subject.
    pub fn assign_role(&self, subject_id: &str, role_id: &str) -> Result<()> {
        // Verify role exists
        if !self.roles.contains_key(role_id) {
            return Err(SecurityError::role_not_found(role_id));
        }

        self.role_assignments
            .entry(subject_id.to_string())
            .or_default()
            .insert(role_id.to_string());

        Ok(())
    }

    /// Revoke a role from a subject.
    pub fn revoke_role(&self, subject_id: &str, role_id: &str) -> Result<()> {
        if let Some(mut roles) = self.role_assignments.get_mut(subject_id) {
            roles.remove(role_id);
        }
        Ok(())
    }

    /// Get roles assigned to a subject.
    pub fn get_subject_roles(&self, subject_id: &str) -> Vec<String> {
        self.role_assignments
            .get(subject_id)
            .map(|roles| roles.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Set role inheritance (child inherits from parent).
    pub fn set_role_inheritance(&self, child_role_id: &str, parent_role_id: &str) -> Result<()> {
        // Verify both roles exist
        if !self.roles.contains_key(child_role_id) {
            return Err(SecurityError::role_not_found(child_role_id));
        }
        if !self.roles.contains_key(parent_role_id) {
            return Err(SecurityError::role_not_found(parent_role_id));
        }

        // Check for circular inheritance
        if self.would_create_cycle(child_role_id, parent_role_id) {
            return Err(SecurityError::policy_evaluation(
                "Circular role inheritance detected",
            ));
        }

        self.role_inheritance
            .entry(child_role_id.to_string())
            .or_default()
            .insert(parent_role_id.to_string());

        Ok(())
    }

    /// Get all roles for a subject including inherited roles.
    pub fn get_effective_roles(&self, subject_id: &str) -> HashSet<String> {
        let mut effective_roles = HashSet::new();
        let direct_roles = self.get_subject_roles(subject_id);

        for role_id in direct_roles {
            self.collect_inherited_roles(&role_id, &mut effective_roles);
        }

        effective_roles
    }

    /// Collect all inherited roles recursively.
    fn collect_inherited_roles(&self, role_id: &str, collected: &mut HashSet<String>) {
        if collected.contains(role_id) {
            return;
        }

        collected.insert(role_id.to_string());

        if let Some(parents) = self.role_inheritance.get(role_id) {
            for parent_id in parents.iter() {
                self.collect_inherited_roles(parent_id, collected);
            }
        }
    }

    /// Check if adding inheritance would create a cycle.
    fn would_create_cycle(&self, child_id: &str, parent_id: &str) -> bool {
        let mut visited = HashSet::new();
        self.has_cycle(parent_id, child_id, &mut visited)
    }

    /// Check for cycles in role inheritance.
    fn has_cycle(&self, current: &str, target: &str, visited: &mut HashSet<String>) -> bool {
        if current == target {
            return true;
        }

        if visited.contains(current) {
            return false;
        }

        visited.insert(current.to_string());

        if let Some(parents) = self.role_inheritance.get(current) {
            for parent in parents.iter() {
                if self.has_cycle(parent, target, visited) {
                    return true;
                }
            }
        }

        false
    }

    /// Check if a subject has a specific permission on a specific resource.
    ///
    /// `resource_id` is matched against each candidate [`Permission`]'s
    /// `resource_pattern` (via [`Permission::matches_resource`]). A
    /// permission with no pattern (`resource_pattern: None`) matches every
    /// resource of the given `resource_type`; a permission scoped with
    /// [`Permission::with_pattern`] only grants access to resources whose
    /// ID matches that pattern.
    pub fn has_permission(
        &self,
        subject_id: &str,
        action: Action,
        resource_type: ResourceType,
        resource_id: &str,
    ) -> bool {
        let effective_roles = self.get_effective_roles(subject_id);

        for role_id in effective_roles {
            if let Some(role) = self.roles.get(&role_id) {
                for permission_id in &role.permissions {
                    if let Some(permission) = self.permissions.get(permission_id)
                        && permission.action == action
                        && permission.resource_type == resource_type
                        && permission.matches_resource(resource_id)
                    {
                        return true;
                    }
                }
            }
        }

        false
    }

    /// Get all permissions for a subject.
    pub fn get_subject_permissions(&self, subject_id: &str) -> Vec<Permission> {
        let effective_roles = self.get_effective_roles(subject_id);
        let mut permissions = Vec::new();
        let mut seen = HashSet::new();

        for role_id in effective_roles {
            if let Some(role) = self.roles.get(&role_id) {
                for permission_id in &role.permissions {
                    if !seen.contains(permission_id)
                        && let Some(permission) = self.permissions.get(permission_id)
                    {
                        permissions.push(permission.clone());
                        seen.insert(permission_id.clone());
                    }
                }
            }
        }

        permissions
    }

    /// Clear all role assignments.
    pub fn clear_assignments(&self) {
        self.role_assignments.clear();
    }

    /// Clear all roles.
    pub fn clear_roles(&self) {
        self.roles.clear();
        self.role_inheritance.clear();
    }

    /// Clear all permissions.
    pub fn clear_permissions(&self) {
        self.permissions.clear();
    }
}

impl Default for RbacEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl AccessControlEvaluator for RbacEngine {
    fn evaluate(&self, request: &AccessRequest) -> Result<AccessDecision> {
        let has_permission = self.has_permission(
            &request.subject.id,
            request.action,
            request.resource.resource_type,
            &request.resource.id,
        );

        if has_permission {
            Ok(AccessDecision::Allow)
        } else {
            Ok(AccessDecision::Deny)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::access_control::permissions::Permission;
    use crate::access_control::roles::Role;

    #[test]
    fn test_role_assignment() {
        let engine = RbacEngine::new();
        let role = Role::new("admin".to_string(), "Administrator".to_string());

        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "admin")
            .expect("Failed to assign role");

        let roles = engine.get_subject_roles("user-123");
        assert_eq!(roles.len(), 1);
        assert!(roles.contains(&"admin".to_string()));
    }

    #[test]
    fn test_role_revocation() {
        let engine = RbacEngine::new();
        let role = Role::new("admin".to_string(), "Administrator".to_string());

        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "admin")
            .expect("Failed to assign role");
        engine
            .revoke_role("user-123", "admin")
            .expect("Failed to revoke role");

        let roles = engine.get_subject_roles("user-123");
        assert_eq!(roles.len(), 0);
    }

    #[test]
    fn test_role_inheritance() {
        let engine = RbacEngine::new();

        let admin_role = Role::new("admin".to_string(), "Administrator".to_string());
        let user_role = Role::new("user".to_string(), "User".to_string());

        engine
            .add_role(admin_role)
            .expect("Failed to add admin role");
        engine.add_role(user_role).expect("Failed to add user role");

        engine
            .set_role_inheritance("admin", "user")
            .expect("Failed to set inheritance");

        engine
            .assign_role("user-123", "admin")
            .expect("Failed to assign role");

        let effective_roles = engine.get_effective_roles("user-123");
        assert_eq!(effective_roles.len(), 2);
        assert!(effective_roles.contains("admin"));
        assert!(effective_roles.contains("user"));
    }

    #[test]
    fn test_circular_inheritance_prevention() {
        let engine = RbacEngine::new();

        let role_a = Role::new("role-a".to_string(), "Role A".to_string());
        let role_b = Role::new("role-b".to_string(), "Role B".to_string());

        engine.add_role(role_a).expect("Failed to add role A");
        engine.add_role(role_b).expect("Failed to add role B");

        engine
            .set_role_inheritance("role-a", "role-b")
            .expect("Failed to set inheritance");

        // This should fail due to circular dependency
        let result = engine.set_role_inheritance("role-b", "role-a");
        assert!(result.is_err());
    }

    #[test]
    fn test_permission_check() {
        let engine = RbacEngine::new();

        let permission = Permission::new(
            "read-dataset".to_string(),
            "Read Dataset".to_string(),
            Action::Read,
            ResourceType::Dataset,
        );

        let mut role = Role::new("viewer".to_string(), "Viewer".to_string());
        role.add_permission("read-dataset".to_string());

        engine
            .add_permission(permission)
            .expect("Failed to add permission");
        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "viewer")
            .expect("Failed to assign role");

        assert!(engine.has_permission(
            "user-123",
            Action::Read,
            ResourceType::Dataset,
            "dataset-456"
        ));
        assert!(!engine.has_permission(
            "user-123",
            Action::Write,
            ResourceType::Dataset,
            "dataset-456"
        ));
    }

    #[test]
    fn test_permission_resource_pattern_is_enforced() {
        // Regression test: a permission scoped with `.with_pattern(...)`
        // must only grant access to resources whose ID matches the
        // pattern, not to every resource of the given ResourceType.
        let engine = RbacEngine::new();

        let scoped_permission = Permission::new(
            "read-dataset-123".to_string(),
            "Read Dataset 123".to_string(),
            Action::Read,
            ResourceType::Dataset,
        )
        .with_pattern("dataset-123".to_string());

        let mut role = Role::new("scoped-viewer".to_string(), "Scoped Viewer".to_string());
        role.add_permission("read-dataset-123".to_string());

        engine
            .add_permission(scoped_permission)
            .expect("Failed to add permission");
        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "scoped-viewer")
            .expect("Failed to assign role");

        // Access to the exact resource the permission is scoped to must be
        // granted.
        assert!(engine.has_permission(
            "user-123",
            Action::Read,
            ResourceType::Dataset,
            "dataset-123"
        ));

        // Before the fix, this incorrectly returned `true` because
        // resource identity was discarded entirely -- the resource-scoped
        // grant became resource-type-wide.
        assert!(!engine.has_permission(
            "user-123",
            Action::Read,
            ResourceType::Dataset,
            "dataset-999"
        ));
    }

    #[test]
    fn test_permission_resource_pattern_glob_is_enforced() {
        let engine = RbacEngine::new();

        let scoped_permission = Permission::new(
            "read-dataset-glob".to_string(),
            "Read Dataset Glob".to_string(),
            Action::Read,
            ResourceType::Dataset,
        )
        .with_pattern("dataset-*".to_string());

        let mut role = Role::new("glob-viewer".to_string(), "Glob Viewer".to_string());
        role.add_permission("read-dataset-glob".to_string());

        engine
            .add_permission(scoped_permission)
            .expect("Failed to add permission");
        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "glob-viewer")
            .expect("Failed to assign role");

        assert!(engine.has_permission(
            "user-123",
            Action::Read,
            ResourceType::Dataset,
            "dataset-abc"
        ));
        assert!(!engine.has_permission(
            "user-123",
            Action::Read,
            ResourceType::Dataset,
            "other-abc"
        ));
    }

    #[test]
    fn test_evaluate_respects_resource_pattern() {
        // Regression test at the AccessControlEvaluator::evaluate level
        // (the code path actually exercised by PolicyEngine), not just
        // has_permission directly.
        use crate::access_control::{AccessContext, AccessRequest, Resource, Subject, SubjectType};

        let engine = RbacEngine::new();

        let scoped_permission = Permission::new(
            "read-dataset-123".to_string(),
            "Read Dataset 123".to_string(),
            Action::Read,
            ResourceType::Dataset,
        )
        .with_pattern("dataset-123".to_string());

        let mut role = Role::new("scoped-viewer".to_string(), "Scoped Viewer".to_string());
        role.add_permission("read-dataset-123".to_string());

        engine
            .add_permission(scoped_permission)
            .expect("Failed to add permission");
        engine.add_role(role).expect("Failed to add role");
        engine
            .assign_role("user-123", "scoped-viewer")
            .expect("Failed to assign role");

        let subject = Subject::new("user-123".to_string(), SubjectType::User);
        let allowed_resource = Resource::new("dataset-123".to_string(), ResourceType::Dataset);
        let denied_resource = Resource::new("dataset-999".to_string(), ResourceType::Dataset);

        let allowed_request = AccessRequest::new(
            subject.clone(),
            allowed_resource,
            Action::Read,
            AccessContext::new(),
        );
        let denied_request =
            AccessRequest::new(subject, denied_resource, Action::Read, AccessContext::new());

        assert_eq!(
            engine.evaluate(&allowed_request).expect("evaluate failed"),
            AccessDecision::Allow
        );
        assert_eq!(
            engine.evaluate(&denied_request).expect("evaluate failed"),
            AccessDecision::Deny
        );
    }
}