voirs-evaluation 0.1.0-rc.1

Quality evaluation and assessment framework for VoiRS
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! Role-Based Access Control (RBAC) system for enterprise evaluation security
//!
//! This module provides comprehensive Role-Based Access Control capabilities for
//! the VoiRS evaluation framework, enabling fine-grained permission management,
//! user role assignment, and access policy enforcement.
//!
//! # Features
//!
//! - **Role Management**: Define and manage user roles with hierarchical inheritance
//! - **Permission System**: Granular permissions for evaluation operations
//! - **Policy Enforcement**: Automatic access control enforcement for all operations
//! - **Audit Integration**: Complete audit trail of all access control decisions
//! - **Temporal Access**: Time-based access controls and expiration
//! - **Resource-Level Permissions**: Fine-grained control over specific evaluation resources
//! - **Multi-Tenancy**: Support for organizational isolation and tenant-based access
//!
//! # Example
//!
//! ```no_run
//! use voirs_evaluation::rbac::*;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create RBAC manager
//! let mut rbac = RbacManager::new();
//!
//! // Define roles
//! let admin_role = Role::new("admin")
//!     .with_permission(Permission::EvaluationExecute)
//!     .with_permission(Permission::EvaluationRead)
//!     .with_permission(Permission::EvaluationWrite)
//!     .with_permission(Permission::SystemAdmin);
//!
//! let analyst_role = Role::new("analyst")
//!     .with_permission(Permission::EvaluationExecute)
//!     .with_permission(Permission::EvaluationRead);
//!
//! // Add roles to system
//! rbac.add_role(admin_role).await?;
//! rbac.add_role(analyst_role).await?;
//!
//! // Assign user to role
//! rbac.assign_user_role("user@example.com", "analyst").await?;
//!
//! // Check permissions
//! assert!(rbac.has_permission("user@example.com", Permission::EvaluationRead).await?);
//! assert!(!rbac.has_permission("user@example.com", Permission::SystemAdmin).await?);
//! # Ok(())
//! # }
//! ```

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

/// RBAC errors
#[derive(Error, Debug)]
pub enum RbacError {
    /// Role not found
    #[error("Role not found: {role_name}")]
    RoleNotFound {
        /// Role name
        role_name: String,
    },

    /// User not found
    #[error("User not found: {user_id}")]
    UserNotFound {
        /// User ID
        user_id: String,
    },

    /// Permission denied
    #[error("Permission denied: user {user_id} lacks permission {permission:?}")]
    PermissionDenied {
        /// User ID
        user_id: String,
        /// Required permission
        permission: Permission,
    },

    /// Role already exists
    #[error("Role already exists: {role_name}")]
    RoleAlreadyExists {
        /// Role name
        role_name: String,
    },

    /// Invalid role hierarchy
    #[error("Invalid role hierarchy: {message}")]
    InvalidHierarchy {
        /// Error message
        message: String,
    },

    /// Access expired
    #[error("Access expired for user {user_id}")]
    AccessExpired {
        /// User ID
        user_id: String,
    },

    /// Tenant isolation violation
    #[error("Tenant isolation violation: {message}")]
    TenantViolation {
        /// Error message
        message: String,
    },
}

/// Permission types for evaluation operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Permission {
    // Evaluation permissions
    /// Execute quality evaluations
    EvaluationExecute,
    /// Read evaluation results
    EvaluationRead,
    /// Write/modify evaluation configurations
    EvaluationWrite,
    /// Delete evaluation results
    EvaluationDelete,
    /// Export evaluation data
    EvaluationExport,

    // Dataset permissions
    /// Read dataset content
    DatasetRead,
    /// Upload new datasets
    DatasetUpload,
    /// Modify dataset metadata
    DatasetModify,
    /// Delete datasets
    DatasetDelete,

    // Model permissions
    /// Execute model inference
    ModelExecute,
    /// Read model information
    ModelRead,
    /// Deploy new models
    ModelDeploy,
    /// Delete models
    ModelDelete,

    // Analytics permissions
    /// View analytics dashboards
    AnalyticsView,
    /// Create custom analytics
    AnalyticsCreate,
    /// Export analytics reports
    AnalyticsExport,

    // System permissions
    /// System administration
    SystemAdmin,
    /// User management
    UserManagement,
    /// Role management
    RoleManagement,
    /// Audit log access
    AuditAccess,
    /// Configuration management
    ConfigManagement,

    // Privacy permissions
    /// Access to PII data
    PrivacyPiiAccess,
    /// Privacy budget management
    PrivacyBudgetManage,
    /// Data anonymization
    PrivacyAnonymize,
}

impl Permission {
    /// Get all available permissions
    pub fn all() -> Vec<Permission> {
        vec![
            Permission::EvaluationExecute,
            Permission::EvaluationRead,
            Permission::EvaluationWrite,
            Permission::EvaluationDelete,
            Permission::EvaluationExport,
            Permission::DatasetRead,
            Permission::DatasetUpload,
            Permission::DatasetModify,
            Permission::DatasetDelete,
            Permission::ModelExecute,
            Permission::ModelRead,
            Permission::ModelDeploy,
            Permission::ModelDelete,
            Permission::AnalyticsView,
            Permission::AnalyticsCreate,
            Permission::AnalyticsExport,
            Permission::SystemAdmin,
            Permission::UserManagement,
            Permission::RoleManagement,
            Permission::AuditAccess,
            Permission::ConfigManagement,
            Permission::PrivacyPiiAccess,
            Permission::PrivacyBudgetManage,
            Permission::PrivacyAnonymize,
        ]
    }

    /// Get permission description
    pub fn description(&self) -> &'static str {
        match self {
            Permission::EvaluationExecute => "Execute quality evaluations",
            Permission::EvaluationRead => "Read evaluation results",
            Permission::EvaluationWrite => "Write/modify evaluation configurations",
            Permission::EvaluationDelete => "Delete evaluation results",
            Permission::EvaluationExport => "Export evaluation data",
            Permission::DatasetRead => "Read dataset content",
            Permission::DatasetUpload => "Upload new datasets",
            Permission::DatasetModify => "Modify dataset metadata",
            Permission::DatasetDelete => "Delete datasets",
            Permission::ModelExecute => "Execute model inference",
            Permission::ModelRead => "Read model information",
            Permission::ModelDeploy => "Deploy new models",
            Permission::ModelDelete => "Delete models",
            Permission::AnalyticsView => "View analytics dashboards",
            Permission::AnalyticsCreate => "Create custom analytics",
            Permission::AnalyticsExport => "Export analytics reports",
            Permission::SystemAdmin => "System administration",
            Permission::UserManagement => "User management",
            Permission::RoleManagement => "Role management",
            Permission::AuditAccess => "Audit log access",
            Permission::ConfigManagement => "Configuration management",
            Permission::PrivacyPiiAccess => "Access to PII data",
            Permission::PrivacyBudgetManage => "Privacy budget management",
            Permission::PrivacyAnonymize => "Data anonymization",
        }
    }
}

/// User role definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    /// Role name (unique identifier)
    pub name: String,
    /// Human-readable display name
    pub display_name: String,
    /// Role description
    pub description: String,
    /// Permissions granted by this role
    pub permissions: HashSet<Permission>,
    /// Parent roles (for hierarchical inheritance)
    pub parent_roles: Vec<String>,
    /// Priority level (higher = more privileged)
    pub priority: u32,
    /// Whether this role can be deleted
    pub system_role: bool,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

impl Role {
    /// Create new role
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        Self {
            display_name: name.clone(),
            name: name.clone(),
            description: String::new(),
            permissions: HashSet::new(),
            parent_roles: Vec::new(),
            priority: 0,
            system_role: false,
            metadata: HashMap::new(),
        }
    }

    /// Add permission to role
    pub fn with_permission(mut self, permission: Permission) -> Self {
        self.permissions.insert(permission);
        self
    }

    /// Add multiple permissions
    pub fn with_permissions(mut self, permissions: impl IntoIterator<Item = Permission>) -> Self {
        self.permissions.extend(permissions);
        self
    }

    /// Set parent role for inheritance
    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
        self.parent_roles.push(parent.into());
        self
    }

    /// Set display name
    pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = display_name.into();
        self
    }

    /// Set description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Set priority
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority;
        self
    }

    /// Mark as system role
    pub fn as_system_role(mut self) -> Self {
        self.system_role = true;
        self
    }

    /// Get all permissions (including inherited)
    pub fn effective_permissions(&self, all_roles: &HashMap<String, Role>) -> HashSet<Permission> {
        let mut permissions = self.permissions.clone();

        // Add inherited permissions from parent roles
        for parent_name in &self.parent_roles {
            if let Some(parent_role) = all_roles.get(parent_name) {
                permissions.extend(parent_role.effective_permissions(all_roles));
            }
        }

        permissions
    }
}

/// User access assignment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserAccess {
    /// User ID
    pub user_id: String,
    /// Assigned roles
    pub roles: HashSet<String>,
    /// Direct permissions (beyond roles)
    pub direct_permissions: HashSet<Permission>,
    /// Tenant ID for multi-tenancy
    pub tenant_id: Option<String>,
    /// Access expiration time
    pub expires_at: Option<DateTime<Utc>>,
    /// Whether account is enabled
    pub enabled: bool,
    /// User metadata
    pub metadata: HashMap<String, String>,
}

impl UserAccess {
    /// Create new user access
    pub fn new(user_id: impl Into<String>) -> Self {
        Self {
            user_id: user_id.into(),
            roles: HashSet::new(),
            direct_permissions: HashSet::new(),
            tenant_id: None,
            expires_at: None,
            enabled: true,
            metadata: HashMap::new(),
        }
    }

    /// Add role to user
    pub fn with_role(mut self, role: impl Into<String>) -> Self {
        self.roles.insert(role.into());
        self
    }

    /// Add direct permission
    pub fn with_permission(mut self, permission: Permission) -> Self {
        self.direct_permissions.insert(permission);
        self
    }

    /// Set tenant ID
    pub fn with_tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.tenant_id = Some(tenant_id.into());
        self
    }

    /// Set expiration
    pub fn with_expiration(mut self, expires_at: DateTime<Utc>) -> Self {
        self.expires_at = Some(expires_at);
        self
    }

    /// Check if access has expired
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at {
            Utc::now() > expires_at
        } else {
            false
        }
    }

    /// Check if user is enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled && !self.is_expired()
    }
}

/// Access decision with audit information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessDecision {
    /// Whether access is granted
    pub granted: bool,
    /// User ID
    pub user_id: String,
    /// Required permission
    pub permission: Permission,
    /// Reason for decision
    pub reason: String,
    /// Decision timestamp
    pub timestamp: DateTime<Utc>,
    /// Effective roles used
    pub effective_roles: Vec<String>,
}

/// RBAC Manager for access control
pub struct RbacManager {
    /// All defined roles
    roles: Arc<RwLock<HashMap<String, Role>>>,
    /// User access assignments
    user_access: Arc<RwLock<HashMap<String, UserAccess>>>,
    /// Access decision audit log
    audit_log: Arc<RwLock<Vec<AccessDecision>>>,
    /// Configuration
    config: RbacConfig,
}

/// RBAC configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RbacConfig {
    /// Enable audit logging
    pub enable_audit: bool,
    /// Maximum audit log size
    pub max_audit_entries: usize,
    /// Enable multi-tenancy
    pub enable_multi_tenancy: bool,
    /// Default tenant ID
    pub default_tenant: Option<String>,
}

impl Default for RbacConfig {
    fn default() -> Self {
        Self {
            enable_audit: true,
            max_audit_entries: 10000,
            enable_multi_tenancy: false,
            default_tenant: None,
        }
    }
}

impl RbacManager {
    /// Create new RBAC manager
    pub fn new() -> Self {
        Self::with_config(RbacConfig::default())
    }

    /// Create with custom configuration
    pub fn with_config(config: RbacConfig) -> Self {
        let mut manager = Self {
            roles: Arc::new(RwLock::new(HashMap::new())),
            user_access: Arc::new(RwLock::new(HashMap::new())),
            audit_log: Arc::new(RwLock::new(Vec::new())),
            config,
        };

        // Initialize with predefined system roles
        let _ = futures::executor::block_on(manager.initialize_system_roles());

        manager
    }

    /// Initialize predefined system roles
    async fn initialize_system_roles(&mut self) -> Result<(), RbacError> {
        // Super Admin role
        let super_admin = Role::new("super_admin")
            .with_display_name("Super Administrator")
            .with_description("Full system access with all permissions")
            .with_permissions(Permission::all())
            .with_priority(1000)
            .as_system_role();

        // Administrator role
        let admin = Role::new("administrator")
            .with_display_name("Administrator")
            .with_description("System administrator with management permissions")
            .with_permissions(vec![
                Permission::EvaluationExecute,
                Permission::EvaluationRead,
                Permission::EvaluationWrite,
                Permission::EvaluationDelete,
                Permission::DatasetRead,
                Permission::DatasetUpload,
                Permission::DatasetModify,
                Permission::ModelExecute,
                Permission::ModelRead,
                Permission::ModelDeploy,
                Permission::AnalyticsView,
                Permission::AnalyticsCreate,
                Permission::UserManagement,
                Permission::ConfigManagement,
                Permission::AuditAccess,
            ])
            .with_priority(900)
            .as_system_role();

        // Analyst role
        let analyst = Role::new("analyst")
            .with_display_name("Analyst")
            .with_description("Data analyst with evaluation and analytics access")
            .with_permissions(vec![
                Permission::EvaluationExecute,
                Permission::EvaluationRead,
                Permission::EvaluationExport,
                Permission::DatasetRead,
                Permission::ModelExecute,
                Permission::ModelRead,
                Permission::AnalyticsView,
                Permission::AnalyticsCreate,
                Permission::AnalyticsExport,
            ])
            .with_priority(500)
            .as_system_role();

        // Viewer role
        let viewer = Role::new("viewer")
            .with_display_name("Viewer")
            .with_description("Read-only access to evaluations and analytics")
            .with_permissions(vec![
                Permission::EvaluationRead,
                Permission::DatasetRead,
                Permission::ModelRead,
                Permission::AnalyticsView,
            ])
            .with_priority(100)
            .as_system_role();

        // Privacy Officer role
        let privacy_officer = Role::new("privacy_officer")
            .with_display_name("Privacy Officer")
            .with_description("Privacy and compliance management")
            .with_permissions(vec![
                Permission::PrivacyPiiAccess,
                Permission::PrivacyBudgetManage,
                Permission::PrivacyAnonymize,
                Permission::AuditAccess,
                Permission::EvaluationRead,
            ])
            .with_priority(700)
            .as_system_role();

        self.add_role(super_admin).await?;
        self.add_role(admin).await?;
        self.add_role(analyst).await?;
        self.add_role(viewer).await?;
        self.add_role(privacy_officer).await?;

        Ok(())
    }

    /// Add a new role
    pub async fn add_role(&mut self, role: Role) -> Result<(), RbacError> {
        let mut roles = self.roles.write().await;

        if roles.contains_key(&role.name) {
            return Err(RbacError::RoleAlreadyExists {
                role_name: role.name.clone(),
            });
        }

        // Validate parent roles exist
        for parent in &role.parent_roles {
            if !roles.contains_key(parent) {
                return Err(RbacError::RoleNotFound {
                    role_name: parent.clone(),
                });
            }
        }

        info!(
            "Adding role: {} with {} permissions",
            role.name,
            role.permissions.len()
        );
        roles.insert(role.name.clone(), role);

        Ok(())
    }

    /// Remove a role
    pub async fn remove_role(&mut self, role_name: &str) -> Result<(), RbacError> {
        let mut roles = self.roles.write().await;

        let role = roles
            .get(role_name)
            .ok_or_else(|| RbacError::RoleNotFound {
                role_name: role_name.to_string(),
            })?;

        if role.system_role {
            return Err(RbacError::InvalidHierarchy {
                message: format!("Cannot delete system role: {}", role_name),
            });
        }

        roles.remove(role_name);
        info!("Removed role: {}", role_name);

        Ok(())
    }

    /// Assign role to user
    pub async fn assign_user_role(
        &mut self,
        user_id: &str,
        role_name: &str,
    ) -> Result<(), RbacError> {
        // Verify role exists
        let roles = self.roles.read().await;
        if !roles.contains_key(role_name) {
            return Err(RbacError::RoleNotFound {
                role_name: role_name.to_string(),
            });
        }
        drop(roles);

        let mut users = self.user_access.write().await;
        let user_access = users
            .entry(user_id.to_string())
            .or_insert_with(|| UserAccess::new(user_id));

        user_access.roles.insert(role_name.to_string());

        info!("Assigned role '{}' to user '{}'", role_name, user_id);

        Ok(())
    }

    /// Remove role from user
    pub async fn revoke_user_role(
        &mut self,
        user_id: &str,
        role_name: &str,
    ) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;
        let user_access = users
            .get_mut(user_id)
            .ok_or_else(|| RbacError::UserNotFound {
                user_id: user_id.to_string(),
            })?;

        user_access.roles.remove(role_name);

        info!("Revoked role '{}' from user '{}'", role_name, user_id);

        Ok(())
    }

    /// Grant direct permission to user
    pub async fn grant_permission(
        &mut self,
        user_id: &str,
        permission: Permission,
    ) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;
        let user_access = users
            .entry(user_id.to_string())
            .or_insert_with(|| UserAccess::new(user_id));

        user_access.direct_permissions.insert(permission);

        info!(
            "Granted permission '{:?}' to user '{}'",
            permission, user_id
        );

        Ok(())
    }

    /// Revoke direct permission from user
    pub async fn revoke_permission(
        &mut self,
        user_id: &str,
        permission: Permission,
    ) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;
        let user_access = users
            .get_mut(user_id)
            .ok_or_else(|| RbacError::UserNotFound {
                user_id: user_id.to_string(),
            })?;

        user_access.direct_permissions.remove(&permission);

        info!(
            "Revoked permission '{:?}' from user '{}'",
            permission, user_id
        );

        Ok(())
    }

    /// Check if user has permission
    pub async fn has_permission(
        &self,
        user_id: &str,
        permission: Permission,
    ) -> Result<bool, RbacError> {
        let decision = self.check_access(user_id, permission).await?;
        Ok(decision.granted)
    }

    /// Check access and return detailed decision
    pub async fn check_access(
        &self,
        user_id: &str,
        permission: Permission,
    ) -> Result<AccessDecision, RbacError> {
        let users = self.user_access.read().await;
        let user_access = users.get(user_id);

        let mut decision = AccessDecision {
            granted: false,
            user_id: user_id.to_string(),
            permission,
            reason: String::new(),
            timestamp: Utc::now(),
            effective_roles: Vec::new(),
        };

        // User not found - deny access
        let user_access = match user_access {
            Some(ua) => ua,
            None => {
                decision.reason = "User not found".to_string();
                if self.config.enable_audit {
                    self.log_decision(decision.clone()).await;
                }
                return Ok(decision);
            }
        };

        // Check if account is enabled
        if !user_access.is_enabled() {
            decision.reason = if user_access.is_expired() {
                "Access expired".to_string()
            } else {
                "Account disabled".to_string()
            };
            if self.config.enable_audit {
                self.log_decision(decision.clone()).await;
            }
            return Ok(decision);
        }

        // Check direct permissions first
        if user_access.direct_permissions.contains(&permission) {
            decision.granted = true;
            decision.reason = "Direct permission granted".to_string();
            if self.config.enable_audit {
                self.log_decision(decision.clone()).await;
            }
            return Ok(decision);
        }

        // Check role-based permissions
        let roles = self.roles.read().await;
        let all_roles = roles.clone();

        for role_name in &user_access.roles {
            if let Some(role) = roles.get(role_name) {
                let effective_perms = role.effective_permissions(&all_roles);
                if effective_perms.contains(&permission) {
                    decision.granted = true;
                    decision.reason = format!("Permission granted via role '{}'", role_name);
                    decision.effective_roles.push(role_name.clone());

                    if self.config.enable_audit {
                        self.log_decision(decision.clone()).await;
                    }
                    return Ok(decision);
                }
            }
        }

        decision.reason = "Permission not granted by any role or direct assignment".to_string();
        if self.config.enable_audit {
            self.log_decision(decision.clone()).await;
        }

        Ok(decision)
    }

    /// Enforce permission (throw error if not granted)
    pub async fn enforce_permission(
        &self,
        user_id: &str,
        permission: Permission,
    ) -> Result<(), RbacError> {
        let decision = self.check_access(user_id, permission).await?;

        if decision.granted {
            Ok(())
        } else {
            Err(RbacError::PermissionDenied {
                user_id: user_id.to_string(),
                permission,
            })
        }
    }

    /// Get all permissions for a user
    pub async fn get_user_permissions(
        &self,
        user_id: &str,
    ) -> Result<HashSet<Permission>, RbacError> {
        let users = self.user_access.read().await;
        let user_access = users.get(user_id).ok_or_else(|| RbacError::UserNotFound {
            user_id: user_id.to_string(),
        })?;

        let mut permissions = user_access.direct_permissions.clone();

        let roles = self.roles.read().await;
        let all_roles = roles.clone();

        for role_name in &user_access.roles {
            if let Some(role) = roles.get(role_name) {
                permissions.extend(role.effective_permissions(&all_roles));
            }
        }

        Ok(permissions)
    }

    /// Get user's roles
    pub async fn get_user_roles(&self, user_id: &str) -> Result<Vec<Role>, RbacError> {
        let users = self.user_access.read().await;
        let user_access = users.get(user_id).ok_or_else(|| RbacError::UserNotFound {
            user_id: user_id.to_string(),
        })?;

        let roles = self.roles.read().await;
        let mut user_roles = Vec::new();

        for role_name in &user_access.roles {
            if let Some(role) = roles.get(role_name) {
                user_roles.push(role.clone());
            }
        }

        Ok(user_roles)
    }

    /// Log access decision
    async fn log_decision(&self, decision: AccessDecision) {
        let mut audit_log = self.audit_log.write().await;

        // Maintain maximum log size
        if audit_log.len() >= self.config.max_audit_entries {
            audit_log.remove(0);
        }

        audit_log.push(decision);
    }

    /// Get audit log
    pub async fn get_audit_log(&self) -> Vec<AccessDecision> {
        let audit_log = self.audit_log.read().await;
        audit_log.clone()
    }

    /// Get audit log for specific user
    pub async fn get_user_audit_log(&self, user_id: &str) -> Vec<AccessDecision> {
        let audit_log = self.audit_log.read().await;
        audit_log
            .iter()
            .filter(|d| d.user_id == user_id)
            .cloned()
            .collect()
    }

    /// Create new user
    pub async fn create_user(&mut self, user_access: UserAccess) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;

        info!("Creating user: {}", user_access.user_id);
        users.insert(user_access.user_id.clone(), user_access);

        Ok(())
    }

    /// Update user
    pub async fn update_user(&mut self, user_access: UserAccess) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;

        if !users.contains_key(&user_access.user_id) {
            return Err(RbacError::UserNotFound {
                user_id: user_access.user_id.clone(),
            });
        }

        info!("Updating user: {}", user_access.user_id);
        users.insert(user_access.user_id.clone(), user_access);

        Ok(())
    }

    /// Delete user
    pub async fn delete_user(&mut self, user_id: &str) -> Result<(), RbacError> {
        let mut users = self.user_access.write().await;

        if !users.contains_key(user_id) {
            return Err(RbacError::UserNotFound {
                user_id: user_id.to_string(),
            });
        }

        info!("Deleting user: {}", user_id);
        users.remove(user_id);

        Ok(())
    }

    /// Get all roles
    pub async fn get_all_roles(&self) -> Vec<Role> {
        let roles = self.roles.read().await;
        roles.values().cloned().collect()
    }

    /// Get role by name
    pub async fn get_role(&self, role_name: &str) -> Result<Role, RbacError> {
        let roles = self.roles.read().await;
        roles
            .get(role_name)
            .cloned()
            .ok_or_else(|| RbacError::RoleNotFound {
                role_name: role_name.to_string(),
            })
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_rbac_manager_creation() {
        let rbac = RbacManager::new();
        let roles = rbac.get_all_roles().await;

        // Should have predefined system roles
        assert!(!roles.is_empty());
        assert!(roles.iter().any(|r| r.name == "super_admin"));
        assert!(roles.iter().any(|r| r.name == "administrator"));
        assert!(roles.iter().any(|r| r.name == "analyst"));
        assert!(roles.iter().any(|r| r.name == "viewer"));
    }

    #[tokio::test]
    async fn test_role_assignment() {
        let mut rbac = RbacManager::new();

        // Assign role to user
        rbac.assign_user_role("user@example.com", "analyst")
            .await
            .unwrap();

        // Check permission
        assert!(rbac
            .has_permission("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap());
        assert!(!rbac
            .has_permission("user@example.com", Permission::SystemAdmin)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_direct_permission() {
        let mut rbac = RbacManager::new();

        // Grant direct permission
        rbac.grant_permission("user@example.com", Permission::ModelDeploy)
            .await
            .unwrap();

        // Check permission
        assert!(rbac
            .has_permission("user@example.com", Permission::ModelDeploy)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_permission_enforcement() {
        let mut rbac = RbacManager::new();

        rbac.assign_user_role("user@example.com", "viewer")
            .await
            .unwrap();

        // Should succeed
        rbac.enforce_permission("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap();

        // Should fail
        let result = rbac
            .enforce_permission("user@example.com", Permission::SystemAdmin)
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_role_hierarchy() {
        let mut rbac = RbacManager::new();

        // Create child role with parent
        let child_role = Role::new("custom_analyst")
            .with_parent("analyst")
            .with_permission(Permission::ModelDeploy);

        rbac.add_role(child_role).await.unwrap();
        rbac.assign_user_role("user@example.com", "custom_analyst")
            .await
            .unwrap();

        // Should have both parent and child permissions
        assert!(rbac
            .has_permission("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap()); // from parent
        assert!(rbac
            .has_permission("user@example.com", Permission::ModelDeploy)
            .await
            .unwrap()); // from child
    }

    #[tokio::test]
    async fn test_audit_logging() {
        let rbac = RbacManager::new();

        // Access should create audit log entry
        let _decision = rbac
            .check_access("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap();

        let audit_log = rbac.get_audit_log().await;
        assert!(!audit_log.is_empty());
        assert_eq!(audit_log[0].user_id, "user@example.com");
    }

    #[tokio::test]
    async fn test_user_permissions_aggregation() {
        let mut rbac = RbacManager::new();

        rbac.assign_user_role("user@example.com", "analyst")
            .await
            .unwrap();
        rbac.grant_permission("user@example.com", Permission::SystemAdmin)
            .await
            .unwrap();

        let permissions = rbac.get_user_permissions("user@example.com").await.unwrap();

        // Should have analyst permissions + direct SystemAdmin permission
        assert!(permissions.contains(&Permission::EvaluationRead));
        assert!(permissions.contains(&Permission::SystemAdmin));
    }

    #[tokio::test]
    async fn test_role_revocation() {
        let mut rbac = RbacManager::new();

        rbac.assign_user_role("user@example.com", "analyst")
            .await
            .unwrap();
        assert!(rbac
            .has_permission("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap());

        rbac.revoke_user_role("user@example.com", "analyst")
            .await
            .unwrap();
        assert!(!rbac
            .has_permission("user@example.com", Permission::EvaluationRead)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_custom_role_creation() {
        let mut rbac = RbacManager::new();

        let custom_role = Role::new("data_scientist")
            .with_display_name("Data Scientist")
            .with_description("Data science and ML experimentation")
            .with_permissions(vec![
                Permission::EvaluationExecute,
                Permission::EvaluationRead,
                Permission::DatasetRead,
                Permission::DatasetUpload,
                Permission::ModelExecute,
                Permission::AnalyticsView,
            ])
            .with_priority(600);

        rbac.add_role(custom_role).await.unwrap();

        let role = rbac.get_role("data_scientist").await.unwrap();
        assert_eq!(role.display_name, "Data Scientist");
        assert_eq!(role.permissions.len(), 6);
    }

    #[tokio::test]
    async fn test_system_role_protection() {
        let mut rbac = RbacManager::new();

        // Should not be able to delete system roles
        let result = rbac.remove_role("super_admin").await;
        assert!(result.is_err());
    }
}