mockforge_core/security/
access_review.rs

1//! Automated access review engine for compliance
2//!
3//! This module provides automated access review functionality for:
4//! - Quarterly user access reviews
5//! - Monthly privileged access reviews
6//! - Monthly API token reviews
7//! - Quarterly resource access reviews
8//!
9//! Compliance: SOC 2 CC6 (Logical Access), ISO 27001 A.9.2 (User Access Management)
10
11use chrono::{DateTime, Duration, Utc};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use uuid::Uuid;
15
16/// Review frequency types
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19#[serde(rename_all = "lowercase")]
20pub enum ReviewFrequency {
21    /// Monthly reviews
22    Monthly,
23    /// Quarterly reviews
24    Quarterly,
25    /// Annual reviews
26    Annually,
27}
28
29impl ReviewFrequency {
30    /// Get the duration for this frequency
31    pub fn duration(&self) -> Duration {
32        match self {
33            ReviewFrequency::Monthly => Duration::days(30),
34            ReviewFrequency::Quarterly => Duration::days(90),
35            ReviewFrequency::Annually => Duration::days(365),
36        }
37    }
38
39    /// Calculate the next review date from a given date
40    pub fn next_review_date(&self, from: DateTime<Utc>) -> DateTime<Utc> {
41        from + self.duration()
42    }
43}
44
45/// Review status
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "lowercase")]
48pub enum ReviewStatus {
49    /// Review is pending (not yet started)
50    Pending,
51    /// Review is in progress
52    InProgress,
53    /// Review is completed
54    Completed,
55    /// Review was cancelled
56    Cancelled,
57}
58
59/// Review type
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum ReviewType {
63    /// User access review
64    UserAccess,
65    /// Privileged access review
66    PrivilegedAccess,
67    /// API token review
68    ApiToken,
69    /// Resource access review
70    ResourceAccess,
71}
72
73/// User access information for review
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct UserAccessInfo {
76    /// User ID
77    pub user_id: Uuid,
78    /// Username
79    pub username: String,
80    /// Email address
81    pub email: String,
82    /// Current roles
83    pub roles: Vec<String>,
84    /// Permissions
85    pub permissions: Vec<String>,
86    /// Last login date
87    pub last_login: Option<DateTime<Utc>>,
88    /// Access granted date
89    pub access_granted: DateTime<Utc>,
90    /// Days since last activity
91    pub days_inactive: Option<u64>,
92    /// Whether user is active
93    pub is_active: bool,
94}
95
96/// Privileged access information
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct PrivilegedAccessInfo {
99    /// User ID
100    pub user_id: Uuid,
101    /// Username
102    pub username: String,
103    /// Privileged roles
104    pub roles: Vec<String>,
105    /// Whether MFA is enabled
106    pub mfa_enabled: bool,
107    /// Access justification
108    pub justification: Option<String>,
109    /// Justification expiration date
110    pub justification_expires: Option<DateTime<Utc>>,
111    /// Recent privileged actions count
112    pub recent_actions_count: u64,
113    /// Last privileged action date
114    pub last_privileged_action: Option<DateTime<Utc>>,
115}
116
117/// API token information for review
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct ApiTokenInfo {
120    /// Token ID
121    pub token_id: String,
122    /// Token name/description
123    pub name: Option<String>,
124    /// Token owner user ID
125    pub owner_id: Uuid,
126    /// Token scopes/permissions
127    pub scopes: Vec<String>,
128    /// Creation date
129    pub created_at: DateTime<Utc>,
130    /// Last usage date
131    pub last_used: Option<DateTime<Utc>>,
132    /// Expiration date
133    pub expires_at: Option<DateTime<Utc>>,
134    /// Days since last use
135    pub days_unused: Option<u64>,
136    /// Whether token is active
137    pub is_active: bool,
138}
139
140/// Resource access information
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct ResourceAccessInfo {
143    /// Resource type
144    pub resource_type: String,
145    /// Resource ID
146    pub resource_id: String,
147    /// Users with access
148    pub users_with_access: Vec<Uuid>,
149    /// Access levels
150    pub access_levels: HashMap<Uuid, String>,
151    /// Last access date per user
152    pub last_access: HashMap<Uuid, Option<DateTime<Utc>>>,
153}
154
155/// Review findings
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct ReviewFindings {
158    /// Number of inactive users
159    pub inactive_users: u32,
160    /// Number of users with excessive permissions
161    pub excessive_permissions: u32,
162    /// Number of users with no recent access
163    pub no_recent_access: u32,
164    /// Number of privileged users without MFA
165    pub privileged_without_mfa: u32,
166    /// Number of unused tokens
167    pub unused_tokens: u32,
168    /// Number of tokens with excessive scopes
169    pub excessive_scopes: u32,
170    /// Number of tokens expiring soon
171    pub expiring_soon: u32,
172    /// Additional custom findings
173    pub custom: HashMap<String, u32>,
174}
175
176/// Actions taken during review
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ReviewActions {
179    /// Number of users revoked
180    pub users_revoked: u32,
181    /// Number of permissions reduced
182    pub permissions_reduced: u32,
183    /// Number of MFA enforced
184    pub mfa_enforced: u32,
185    /// Number of tokens revoked
186    pub tokens_revoked: u32,
187    /// Number of tokens rotated
188    pub tokens_rotated: u32,
189    /// Number of scopes reduced
190    pub scopes_reduced: u32,
191    /// Additional custom actions
192    pub custom: HashMap<String, u32>,
193}
194
195/// Access review record
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct AccessReview {
198    /// Review ID
199    pub review_id: String,
200    /// Review type
201    pub review_type: ReviewType,
202    /// Review status
203    pub status: ReviewStatus,
204    /// Review date
205    pub review_date: DateTime<Utc>,
206    /// Due date for completion
207    pub due_date: DateTime<Utc>,
208    /// Total items reviewed
209    pub total_items: u32,
210    /// Items reviewed
211    pub items_reviewed: u32,
212    /// Review findings
213    pub findings: ReviewFindings,
214    /// Actions taken
215    pub actions_taken: ReviewActions,
216    /// Pending approvals count
217    pub pending_approvals: u32,
218    /// Next review date
219    pub next_review_date: DateTime<Utc>,
220    /// Review metadata
221    pub metadata: HashMap<String, serde_json::Value>,
222}
223
224/// User access review item (for approval workflow)
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct UserReviewItem {
227    /// Review ID
228    pub review_id: String,
229    /// User ID
230    pub user_id: Uuid,
231    /// User access information
232    pub access_info: UserAccessInfo,
233    /// Review status (pending, approved, rejected)
234    pub status: String,
235    /// Manager user ID (who should review)
236    pub manager_id: Option<Uuid>,
237    /// Approval deadline
238    pub approval_deadline: Option<DateTime<Utc>>,
239    /// Approved by
240    pub approved_by: Option<Uuid>,
241    /// Approved at
242    pub approved_at: Option<DateTime<Utc>>,
243    /// Rejection reason
244    pub rejection_reason: Option<String>,
245}
246
247/// Access review configuration
248#[derive(Debug, Clone, Serialize, Deserialize)]
249#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
250pub struct AccessReviewConfig {
251    /// Whether access review is enabled
252    pub enabled: bool,
253    /// User access review configuration
254    pub user_review: UserReviewConfig,
255    /// Privileged access review configuration
256    pub privileged_review: PrivilegedReviewConfig,
257    /// API token review configuration
258    pub token_review: TokenReviewConfig,
259    /// Resource access review configuration
260    pub resource_review: ResourceReviewConfig,
261    /// Notification configuration
262    pub notifications: NotificationConfig,
263}
264
265/// User access review configuration
266#[derive(Debug, Clone, Serialize, Deserialize)]
267#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
268pub struct UserReviewConfig {
269    /// Whether user review is enabled
270    pub enabled: bool,
271    /// Review frequency
272    pub frequency: ReviewFrequency,
273    /// Inactive threshold in days
274    pub inactive_threshold_days: u64,
275    /// Auto-revoke inactive users
276    pub auto_revoke_inactive: bool,
277    /// Require manager approval
278    pub require_manager_approval: bool,
279    /// Approval timeout in days
280    pub approval_timeout_days: u64,
281}
282
283/// Privileged access review configuration
284#[derive(Debug, Clone, Serialize, Deserialize)]
285#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
286pub struct PrivilegedReviewConfig {
287    /// Whether privileged review is enabled
288    pub enabled: bool,
289    /// Review frequency
290    pub frequency: ReviewFrequency,
291    /// Require MFA
292    pub require_mfa: bool,
293    /// Require justification
294    pub require_justification: bool,
295    /// Alert on privilege escalation
296    pub alert_on_escalation: bool,
297}
298
299/// API token review configuration
300#[derive(Debug, Clone, Serialize, Deserialize)]
301#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
302pub struct TokenReviewConfig {
303    /// Whether token review is enabled
304    pub enabled: bool,
305    /// Review frequency
306    pub frequency: ReviewFrequency,
307    /// Unused threshold in days
308    pub unused_threshold_days: u64,
309    /// Auto-revoke unused tokens
310    pub auto_revoke_unused: bool,
311    /// Rotation threshold in days (before expiration)
312    pub rotation_threshold_days: u64,
313}
314
315/// Resource access review configuration
316#[derive(Debug, Clone, Serialize, Deserialize)]
317#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
318pub struct ResourceReviewConfig {
319    /// Whether resource review is enabled
320    pub enabled: bool,
321    /// Review frequency
322    pub frequency: ReviewFrequency,
323    /// List of sensitive resources
324    pub sensitive_resources: Vec<String>,
325}
326
327/// Notification configuration
328#[derive(Debug, Clone, Serialize, Deserialize)]
329#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
330pub struct NotificationConfig {
331    /// Whether notifications are enabled
332    pub enabled: bool,
333    /// Notification channels (email, slack, etc.)
334    pub channels: Vec<String>,
335    /// Recipients (security_team, compliance_team, managers)
336    pub recipients: Vec<String>,
337}
338
339impl Default for AccessReviewConfig {
340    fn default() -> Self {
341        Self {
342            enabled: false,
343            user_review: UserReviewConfig {
344                enabled: true,
345                frequency: ReviewFrequency::Quarterly,
346                inactive_threshold_days: 90,
347                auto_revoke_inactive: true,
348                require_manager_approval: true,
349                approval_timeout_days: 30,
350            },
351            privileged_review: PrivilegedReviewConfig {
352                enabled: true,
353                frequency: ReviewFrequency::Monthly,
354                require_mfa: true,
355                require_justification: true,
356                alert_on_escalation: true,
357            },
358            token_review: TokenReviewConfig {
359                enabled: true,
360                frequency: ReviewFrequency::Monthly,
361                unused_threshold_days: 90,
362                auto_revoke_unused: true,
363                rotation_threshold_days: 30,
364            },
365            resource_review: ResourceReviewConfig {
366                enabled: true,
367                frequency: ReviewFrequency::Quarterly,
368                sensitive_resources: vec![
369                    "billing".to_string(),
370                    "user_data".to_string(),
371                    "audit_logs".to_string(),
372                    "security_settings".to_string(),
373                ],
374            },
375            notifications: NotificationConfig {
376                enabled: true,
377                channels: vec!["email".to_string()],
378                recipients: vec!["security_team".to_string(), "compliance_team".to_string()],
379            },
380        }
381    }
382}
383
384/// Access review engine
385///
386/// This engine manages automated access reviews according to the configured schedule
387/// and policies. It generates reports, tracks approvals, and can automatically
388/// revoke access when needed.
389pub struct AccessReviewEngine {
390    config: AccessReviewConfig,
391    /// Active reviews (review_id -> review)
392    active_reviews: HashMap<String, AccessReview>,
393    /// User review items (review_id -> user_id -> item)
394    user_review_items: HashMap<String, HashMap<Uuid, UserReviewItem>>,
395}
396
397impl AccessReviewEngine {
398    /// Create a new access review engine
399    pub fn new(config: AccessReviewConfig) -> Self {
400        Self {
401            config,
402            active_reviews: HashMap::new(),
403            user_review_items: HashMap::new(),
404        }
405    }
406
407    /// Generate a review ID based on type and date
408    pub fn generate_review_id(&self, review_type: ReviewType, date: DateTime<Utc>) -> String {
409        let type_str = match review_type {
410            ReviewType::UserAccess => "user",
411            ReviewType::PrivilegedAccess => "privileged",
412            ReviewType::ApiToken => "token",
413            ReviewType::ResourceAccess => "resource",
414        };
415
416        let date_str = date.format("%Y-%m-%d");
417        format!("review-{}-{}", date_str, type_str)
418    }
419
420    /// Start a user access review
421    ///
422    /// This generates a review report and creates review items for each user
423    /// that needs to be reviewed.
424    pub async fn start_user_access_review(
425        &mut self,
426        users: Vec<UserAccessInfo>,
427    ) -> Result<AccessReview, crate::Error> {
428        if !self.config.enabled || !self.config.user_review.enabled {
429            return Err(crate::Error::Generic("User access review is not enabled".to_string()));
430        }
431
432        let now = Utc::now();
433        let review_id = self.generate_review_id(ReviewType::UserAccess, now);
434        let due_date =
435            now + chrono::Duration::days(self.config.user_review.approval_timeout_days as i64);
436        let next_review = self.config.user_review.frequency.next_review_date(now);
437
438        // Analyze users and generate findings
439        let mut findings = ReviewFindings {
440            inactive_users: 0,
441            excessive_permissions: 0,
442            no_recent_access: 0,
443            privileged_without_mfa: 0,
444            unused_tokens: 0,
445            excessive_scopes: 0,
446            expiring_soon: 0,
447            custom: HashMap::new(),
448        };
449
450        let mut review_items = HashMap::new();
451
452        for user in &users {
453            // Check for inactive users
454            if let Some(days) = user.days_inactive {
455                if days > self.config.user_review.inactive_threshold_days {
456                    findings.inactive_users += 1;
457                }
458            }
459
460            // Check for no recent access
461            if user.last_login.is_none()
462                || user.last_login.unwrap() < now - chrono::Duration::days(90)
463            {
464                findings.no_recent_access += 1;
465            }
466
467            // Check for excessive permissions (heuristic: more than 10 permissions)
468            if user.permissions.len() > 10 {
469                findings.excessive_permissions += 1;
470            }
471
472            // Create review item
473            let review_item = UserReviewItem {
474                review_id: review_id.clone(),
475                user_id: user.user_id,
476                access_info: user.clone(),
477                status: "pending".to_string(),
478                manager_id: None, // Would be populated from user's manager relationship
479                approval_deadline: Some(due_date),
480                approved_by: None,
481                approved_at: None,
482                rejection_reason: None,
483            };
484
485            review_items.insert(user.user_id, review_item);
486        }
487
488        let review = AccessReview {
489            review_id: review_id.clone(),
490            review_type: ReviewType::UserAccess,
491            status: ReviewStatus::InProgress,
492            review_date: now,
493            due_date,
494            total_items: users.len() as u32,
495            items_reviewed: 0,
496            findings: findings.clone(),
497            actions_taken: ReviewActions {
498                users_revoked: 0,
499                permissions_reduced: 0,
500                mfa_enforced: 0,
501                tokens_revoked: 0,
502                tokens_rotated: 0,
503                scopes_reduced: 0,
504                custom: HashMap::new(),
505            },
506            pending_approvals: review_items.len() as u32,
507            next_review_date: next_review,
508            metadata: HashMap::new(),
509        };
510
511        self.active_reviews.insert(review_id.clone(), review.clone());
512        self.user_review_items.insert(review_id, review_items);
513
514        Ok(review)
515    }
516
517    /// Approve a user's access in a review
518    pub fn approve_user_access(
519        &mut self,
520        review_id: &str,
521        user_id: Uuid,
522        approved_by: Uuid,
523        justification: Option<String>,
524    ) -> Result<(), crate::Error> {
525        let review = self
526            .active_reviews
527            .get_mut(review_id)
528            .ok_or_else(|| crate::Error::Generic(format!("Review {} not found", review_id)))?;
529
530        let items = self.user_review_items.get_mut(review_id).ok_or_else(|| {
531            crate::Error::Generic(format!("Review items for {} not found", review_id))
532        })?;
533
534        let item = items.get_mut(&user_id).ok_or_else(|| {
535            crate::Error::Generic(format!("User {} not found in review", user_id))
536        })?;
537
538        item.status = "approved".to_string();
539        item.approved_by = Some(approved_by);
540        item.approved_at = Some(Utc::now());
541
542        review.items_reviewed += 1;
543        review.pending_approvals = review.pending_approvals.saturating_sub(1);
544
545        // Add justification to metadata if provided
546        if let Some(just) = justification {
547            review
548                .metadata
549                .insert(format!("justification_{}", user_id), serde_json::json!(just));
550        }
551
552        Ok(())
553    }
554
555    /// Revoke a user's access in a review
556    pub fn revoke_user_access(
557        &mut self,
558        review_id: &str,
559        user_id: Uuid,
560        revoked_by: Uuid,
561        reason: String,
562    ) -> Result<(), crate::Error> {
563        let review = self
564            .active_reviews
565            .get_mut(review_id)
566            .ok_or_else(|| crate::Error::Generic(format!("Review {} not found", review_id)))?;
567
568        let items = self.user_review_items.get_mut(review_id).ok_or_else(|| {
569            crate::Error::Generic(format!("Review items for {} not found", review_id))
570        })?;
571
572        let item = items.get_mut(&user_id).ok_or_else(|| {
573            crate::Error::Generic(format!("User {} not found in review", user_id))
574        })?;
575
576        item.status = "revoked".to_string();
577        item.rejection_reason = Some(reason.clone());
578
579        review.items_reviewed += 1;
580        review.pending_approvals = review.pending_approvals.saturating_sub(1);
581        review.actions_taken.users_revoked += 1;
582
583        // Add revocation reason to metadata
584        review
585            .metadata
586            .insert(format!("revocation_reason_{}", user_id), serde_json::json!(reason));
587
588        Ok(())
589    }
590
591    /// Update user permissions in a review
592    ///
593    /// This method updates the user's permissions/roles as part of a review action.
594    /// It tracks the permission change in the review and updates the review item.
595    pub fn update_user_permissions(
596        &mut self,
597        review_id: &str,
598        user_id: Uuid,
599        updated_by: Uuid,
600        new_roles: Vec<String>,
601        new_permissions: Vec<String>,
602        reason: Option<String>,
603    ) -> Result<(), crate::Error> {
604        let review = self
605            .active_reviews
606            .get_mut(review_id)
607            .ok_or_else(|| crate::Error::Generic(format!("Review {} not found", review_id)))?;
608
609        let items = self.user_review_items.get_mut(review_id).ok_or_else(|| {
610            crate::Error::Generic(format!("Review items for {} not found", review_id))
611        })?;
612
613        let item = items.get_mut(&user_id).ok_or_else(|| {
614            crate::Error::Generic(format!("User {} not found in review", user_id))
615        })?;
616
617        // Store old permissions for tracking
618        let old_roles = item.access_info.roles.clone();
619        let old_permissions = item.access_info.permissions.clone();
620
621        // Update the access info
622        item.access_info.roles = new_roles.clone();
623        item.access_info.permissions = new_permissions.clone();
624
625        // Mark as reviewed if permissions were reduced
626        let roles_reduced = new_roles.len() < old_roles.len();
627        let permissions_reduced = new_permissions.len() < old_permissions.len();
628
629        if roles_reduced || permissions_reduced {
630            item.status = "permissions_updated".to_string();
631            review.items_reviewed += 1;
632            review.pending_approvals = review.pending_approvals.saturating_sub(1);
633            review.actions_taken.permissions_reduced += 1;
634        }
635
636        // Store permission change metadata
637        let change_metadata = serde_json::json!({
638            "updated_by": updated_by.to_string(),
639            "old_roles": old_roles,
640            "new_roles": new_roles,
641            "old_permissions": old_permissions,
642            "new_permissions": new_permissions,
643            "reason": reason,
644            "updated_at": chrono::Utc::now(),
645        });
646        review
647            .metadata
648            .insert(format!("permission_update_{}", user_id), change_metadata);
649
650        Ok(())
651    }
652
653    /// Get review items for a review
654    pub fn get_review_items(&self, review_id: &str) -> Option<&HashMap<Uuid, UserReviewItem>> {
655        self.user_review_items.get(review_id)
656    }
657
658    /// Get a review by ID
659    pub fn get_review(&self, review_id: &str) -> Option<&AccessReview> {
660        self.active_reviews.get(review_id)
661    }
662
663    /// Get all active reviews
664    pub fn get_all_reviews(&self) -> Vec<&AccessReview> {
665        self.active_reviews.values().collect()
666    }
667
668    /// Check for reviews that need auto-revocation
669    ///
670    /// This checks all pending review items and automatically revokes access
671    /// for items that have exceeded their approval deadline.
672    pub fn check_auto_revocation(&mut self) -> Vec<(String, Uuid)> {
673        let now = Utc::now();
674        let mut revoked = Vec::new();
675
676        for (review_id, items) in &mut self.user_review_items {
677            let review = match self.active_reviews.get_mut(review_id) {
678                Some(r) => r,
679                None => continue,
680            };
681
682            if !self.config.user_review.auto_revoke_inactive {
683                continue;
684            }
685
686            for (user_id, item) in items.iter_mut() {
687                if item.status == "pending" {
688                    if let Some(deadline) = item.approval_deadline {
689                        if now > deadline {
690                            // Auto-revoke
691                            item.status = "auto_revoked".to_string();
692                            item.rejection_reason = Some(
693                                "Access automatically revoked due to missing approval within deadline".to_string(),
694                            );
695
696                            review.items_reviewed += 1;
697                            review.pending_approvals = review.pending_approvals.saturating_sub(1);
698                            review.actions_taken.users_revoked += 1;
699
700                            revoked.push((review_id.clone(), *user_id));
701                        }
702                    }
703                }
704            }
705        }
706
707        revoked
708    }
709
710    /// Complete a review
711    pub fn complete_review(&mut self, review_id: &str) -> Result<(), crate::Error> {
712        let review = self
713            .active_reviews
714            .get_mut(review_id)
715            .ok_or_else(|| crate::Error::Generic(format!("Review {} not found", review_id)))?;
716
717        review.status = ReviewStatus::Completed;
718
719        Ok(())
720    }
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    #[test]
728    fn test_review_frequency_duration() {
729        assert_eq!(ReviewFrequency::Monthly.duration(), Duration::days(30));
730        assert_eq!(ReviewFrequency::Quarterly.duration(), Duration::days(90));
731        assert_eq!(ReviewFrequency::Annually.duration(), Duration::days(365));
732    }
733
734    #[test]
735    fn test_generate_review_id() {
736        let config = AccessReviewConfig::default();
737        let engine = AccessReviewEngine::new(config);
738        let date = Utc::now();
739        let id = engine.generate_review_id(ReviewType::UserAccess, date);
740        assert!(id.starts_with("review-"));
741        assert!(id.contains("user"));
742    }
743
744    #[tokio::test]
745    async fn test_start_user_access_review() {
746        let mut config = AccessReviewConfig::default();
747        config.enabled = true;
748        config.user_review.enabled = true;
749
750        let mut engine = AccessReviewEngine::new(config);
751
752        let users = vec![
753            UserAccessInfo {
754                user_id: Uuid::new_v4(),
755                username: "user1".to_string(),
756                email: "user1@example.com".to_string(),
757                roles: vec!["editor".to_string()],
758                permissions: vec!["read".to_string(), "write".to_string()],
759                last_login: Some(Utc::now() - Duration::days(10)),
760                access_granted: Utc::now() - Duration::days(100),
761                days_inactive: Some(10),
762                is_active: true,
763            },
764            UserAccessInfo {
765                user_id: Uuid::new_v4(),
766                username: "user2".to_string(),
767                email: "user2@example.com".to_string(),
768                roles: vec!["admin".to_string()],
769                permissions: (0..15).map(|i| format!("perm{}", i)).collect(),
770                last_login: Some(Utc::now() - Duration::days(120)),
771                access_granted: Utc::now() - Duration::days(200),
772                days_inactive: Some(120),
773                is_active: true,
774            },
775        ];
776
777        let review = engine.start_user_access_review(users).await.unwrap();
778        assert_eq!(review.review_type, ReviewType::UserAccess);
779        assert_eq!(review.total_items, 2);
780        assert!(review.findings.inactive_users > 0);
781        assert!(review.findings.excessive_permissions > 0);
782    }
783
784    #[test]
785    fn test_approve_user_access() {
786        let mut config = AccessReviewConfig::default();
787        config.enabled = true;
788        config.user_review.enabled = true;
789
790        let mut engine = AccessReviewEngine::new(config);
791
792        let user = UserAccessInfo {
793            user_id: Uuid::new_v4(),
794            username: "user1".to_string(),
795            email: "user1@example.com".to_string(),
796            roles: vec!["editor".to_string()],
797            permissions: vec!["read".to_string()],
798            last_login: Some(Utc::now()),
799            access_granted: Utc::now() - Duration::days(10),
800            days_inactive: Some(0),
801            is_active: true,
802        };
803
804        // Start review
805        let review =
806            futures::executor::block_on(engine.start_user_access_review(vec![user.clone()]))
807                .unwrap();
808        let review_id = review.review_id.clone();
809
810        // Approve access
811        let approver_id = Uuid::new_v4();
812        engine.approve_user_access(&review_id, user.user_id, approver_id, None).unwrap();
813
814        let review = engine.get_review(&review_id).unwrap();
815        assert_eq!(review.items_reviewed, 1);
816        assert_eq!(review.pending_approvals, 0);
817    }
818
819    #[test]
820    fn test_revoke_user_access() {
821        let mut config = AccessReviewConfig::default();
822        config.enabled = true;
823        config.user_review.enabled = true;
824
825        let mut engine = AccessReviewEngine::new(config);
826
827        let user = UserAccessInfo {
828            user_id: Uuid::new_v4(),
829            username: "user1".to_string(),
830            email: "user1@example.com".to_string(),
831            roles: vec!["editor".to_string()],
832            permissions: vec!["read".to_string()],
833            last_login: Some(Utc::now()),
834            access_granted: Utc::now() - Duration::days(10),
835            days_inactive: Some(0),
836            is_active: true,
837        };
838
839        // Start review
840        let review =
841            futures::executor::block_on(engine.start_user_access_review(vec![user.clone()]))
842                .unwrap();
843        let review_id = review.review_id.clone();
844
845        // Revoke access
846        let revoker_id = Uuid::new_v4();
847        engine
848            .revoke_user_access(
849                &review_id,
850                user.user_id,
851                revoker_id,
852                "No longer needed".to_string(),
853            )
854            .unwrap();
855
856        let review = engine.get_review(&review_id).unwrap();
857        assert_eq!(review.actions_taken.users_revoked, 1);
858    }
859}