1use chrono::{DateTime, Duration, Utc};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use uuid::Uuid;
15
16#[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,
23 Quarterly,
25 Annually,
27}
28
29impl ReviewFrequency {
30 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 pub fn next_review_date(&self, from: DateTime<Utc>) -> DateTime<Utc> {
41 from + self.duration()
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "lowercase")]
48pub enum ReviewStatus {
49 Pending,
51 InProgress,
53 Completed,
55 Cancelled,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum ReviewType {
63 UserAccess,
65 PrivilegedAccess,
67 ApiToken,
69 ResourceAccess,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct UserAccessInfo {
76 pub user_id: Uuid,
78 pub username: String,
80 pub email: String,
82 pub roles: Vec<String>,
84 pub permissions: Vec<String>,
86 pub last_login: Option<DateTime<Utc>>,
88 pub access_granted: DateTime<Utc>,
90 pub days_inactive: Option<u64>,
92 pub is_active: bool,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct PrivilegedAccessInfo {
99 pub user_id: Uuid,
101 pub username: String,
103 pub roles: Vec<String>,
105 pub mfa_enabled: bool,
107 pub justification: Option<String>,
109 pub justification_expires: Option<DateTime<Utc>>,
111 pub recent_actions_count: u64,
113 pub last_privileged_action: Option<DateTime<Utc>>,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct ApiTokenInfo {
120 pub token_id: String,
122 pub name: Option<String>,
124 pub owner_id: Uuid,
126 pub scopes: Vec<String>,
128 pub created_at: DateTime<Utc>,
130 pub last_used: Option<DateTime<Utc>>,
132 pub expires_at: Option<DateTime<Utc>>,
134 pub days_unused: Option<u64>,
136 pub is_active: bool,
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct ResourceAccessInfo {
143 pub resource_type: String,
145 pub resource_id: String,
147 pub users_with_access: Vec<Uuid>,
149 pub access_levels: HashMap<Uuid, String>,
151 pub last_access: HashMap<Uuid, Option<DateTime<Utc>>>,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct ReviewFindings {
158 pub inactive_users: u32,
160 pub excessive_permissions: u32,
162 pub no_recent_access: u32,
164 pub privileged_without_mfa: u32,
166 pub unused_tokens: u32,
168 pub excessive_scopes: u32,
170 pub expiring_soon: u32,
172 pub custom: HashMap<String, u32>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ReviewActions {
179 pub users_revoked: u32,
181 pub permissions_reduced: u32,
183 pub mfa_enforced: u32,
185 pub tokens_revoked: u32,
187 pub tokens_rotated: u32,
189 pub scopes_reduced: u32,
191 pub custom: HashMap<String, u32>,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct AccessReview {
198 pub review_id: String,
200 pub review_type: ReviewType,
202 pub status: ReviewStatus,
204 pub review_date: DateTime<Utc>,
206 pub due_date: DateTime<Utc>,
208 pub total_items: u32,
210 pub items_reviewed: u32,
212 pub findings: ReviewFindings,
214 pub actions_taken: ReviewActions,
216 pub pending_approvals: u32,
218 pub next_review_date: DateTime<Utc>,
220 pub metadata: HashMap<String, serde_json::Value>,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct UserReviewItem {
227 pub review_id: String,
229 pub user_id: Uuid,
231 pub access_info: UserAccessInfo,
233 pub status: String,
235 pub manager_id: Option<Uuid>,
237 pub approval_deadline: Option<DateTime<Utc>>,
239 pub approved_by: Option<Uuid>,
241 pub approved_at: Option<DateTime<Utc>>,
243 pub rejection_reason: Option<String>,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize)]
249#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
250pub struct AccessReviewConfig {
251 pub enabled: bool,
253 pub user_review: UserReviewConfig,
255 pub privileged_review: PrivilegedReviewConfig,
257 pub token_review: TokenReviewConfig,
259 pub resource_review: ResourceReviewConfig,
261 pub notifications: NotificationConfig,
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize)]
267#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
268pub struct UserReviewConfig {
269 pub enabled: bool,
271 pub frequency: ReviewFrequency,
273 pub inactive_threshold_days: u64,
275 pub auto_revoke_inactive: bool,
277 pub require_manager_approval: bool,
279 pub approval_timeout_days: u64,
281}
282
283#[derive(Debug, Clone, Serialize, Deserialize)]
285#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
286pub struct PrivilegedReviewConfig {
287 pub enabled: bool,
289 pub frequency: ReviewFrequency,
291 pub require_mfa: bool,
293 pub require_justification: bool,
295 pub alert_on_escalation: bool,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
301#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
302pub struct TokenReviewConfig {
303 pub enabled: bool,
305 pub frequency: ReviewFrequency,
307 pub unused_threshold_days: u64,
309 pub auto_revoke_unused: bool,
311 pub rotation_threshold_days: u64,
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
317#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
318pub struct ResourceReviewConfig {
319 pub enabled: bool,
321 pub frequency: ReviewFrequency,
323 pub sensitive_resources: Vec<String>,
325}
326
327#[derive(Debug, Clone, Serialize, Deserialize)]
329#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
330pub struct NotificationConfig {
331 pub enabled: bool,
333 pub channels: Vec<String>,
335 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
384pub struct AccessReviewEngine {
390 config: AccessReviewConfig,
391 active_reviews: HashMap<String, AccessReview>,
393 user_review_items: HashMap<String, HashMap<Uuid, UserReviewItem>>,
395}
396
397impl AccessReviewEngine {
398 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 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 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 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 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 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 if user.permissions.len() > 10 {
469 findings.excessive_permissions += 1;
470 }
471
472 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, 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 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 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 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 review
585 .metadata
586 .insert(format!("revocation_reason_{}", user_id), serde_json::json!(reason));
587
588 Ok(())
589 }
590
591 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 let old_roles = item.access_info.roles.clone();
619 let old_permissions = item.access_info.permissions.clone();
620
621 item.access_info.roles = new_roles.clone();
623 item.access_info.permissions = new_permissions.clone();
624
625 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 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 pub fn get_review_items(&self, review_id: &str) -> Option<&HashMap<Uuid, UserReviewItem>> {
655 self.user_review_items.get(review_id)
656 }
657
658 pub fn get_review(&self, review_id: &str) -> Option<&AccessReview> {
660 self.active_reviews.get(review_id)
661 }
662
663 pub fn get_all_reviews(&self) -> Vec<&AccessReview> {
665 self.active_reviews.values().collect()
666 }
667
668 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 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 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 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 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 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 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}