1use crate::storage::AuthStorage;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::Arc;
15use tokio::time::{Duration, Instant};
16
17pub mod compliance;
18pub mod dashboard;
19pub mod metrics;
20pub mod reports;
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct AnalyticsConfig {
25 pub real_time_enabled: bool,
27
28 pub data_retention_days: u32,
30
31 pub collection_interval: Duration,
33
34 pub compliance_monitoring: bool,
36
37 pub performance_monitoring: bool,
39
40 pub max_event_buffer: usize,
42}
43
44impl Default for AnalyticsConfig {
45 fn default() -> Self {
46 Self {
47 real_time_enabled: true,
48 data_retention_days: 90,
49 collection_interval: Duration::from_secs(60),
50 compliance_monitoring: true,
51 performance_monitoring: true,
52 max_event_buffer: 10000,
53 }
54 }
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59pub enum RbacEventType {
60 RoleAssignment,
62 PermissionCheck,
64 RoleManagement,
66 Authentication,
68 Authorization,
70 PolicyViolation,
72 PrivilegeEscalation,
74 AccessAnomaly,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct AnalyticsEvent {
81 pub id: String,
83
84 pub event_type: RbacEventType,
86
87 pub timestamp: chrono::DateTime<chrono::Utc>,
89
90 pub user_id: Option<String>,
92
93 pub role_id: Option<String>,
95
96 pub resource: Option<String>,
98
99 pub action: Option<String>,
101
102 pub result: EventResult,
104
105 pub metadata: HashMap<String, String>,
107
108 pub duration_ms: Option<u64>,
110
111 pub source_ip: Option<String>,
113
114 pub user_agent: Option<String>,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
120pub enum EventResult {
121 Success,
122 Failure,
123 Denied,
124 Error,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct RoleUsageStats {
130 pub role_id: String,
132
133 pub role_name: String,
135
136 pub user_count: u32,
138
139 pub permission_checks: u64,
141
142 pub successful_access: u64,
144
145 pub denied_access: u64,
147
148 pub last_used: Option<chrono::DateTime<chrono::Utc>>,
150
151 pub avg_response_time_ms: f64,
153
154 pub top_resources: Vec<ResourceAccess>,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct ResourceAccess {
161 pub resource: String,
163
164 pub access_count: u64,
166
167 pub success_rate: f64,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct PermissionUsageStats {
174 pub permission_id: String,
176
177 pub check_count: u64,
179
180 pub success_rate: f64,
182
183 pub used_by_roles: crate::types::Roles,
185
186 pub top_users: Vec<UserActivity>,
188
189 pub peak_hours: Vec<u8>, }
192
193#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct UserActivity {
196 pub user_id: String,
198
199 pub activity_count: u64,
201
202 pub last_activity: chrono::DateTime<chrono::Utc>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct ComplianceMetrics {
209 pub role_assignment_compliance: f64,
211
212 pub permission_scoping_compliance: f64,
214
215 pub orphaned_permissions: u32,
217
218 pub over_privileged_users: u32,
220
221 pub unused_roles: u32,
223
224 pub avg_access_revocation_time_hours: f64,
226
227 pub policy_violations: u32,
229
230 pub security_incidents: u32,
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct PerformanceMetrics {
237 pub avg_permission_check_latency_ms: f64,
239
240 pub p95_permission_check_latency_ms: f64,
242
243 pub p99_permission_check_latency_ms: f64,
245
246 pub permission_checks_per_second: f64,
248
249 pub permission_cache_hit_rate: f64,
251
252 pub error_rate: f64,
254
255 pub cpu_usage_percent: f64,
257
258 pub memory_usage_mb: u64,
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct TimeSeriesData {
265 pub timestamp: chrono::DateTime<chrono::Utc>,
267
268 pub value: f64,
270
271 pub tags: HashMap<String, String>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct TrendAnalysis {
278 pub metric_name: String,
280
281 pub current_value: f64,
283
284 pub previous_value: f64,
286
287 pub change_percent: f64,
289
290 pub trend: TrendDirection,
292
293 pub data_points: Vec<TimeSeriesData>,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
299pub enum TrendDirection {
300 Increasing,
301 Decreasing,
302 Stable,
303 Volatile,
304}
305
306pub struct AnalyticsManager {
308 config: AnalyticsConfig,
309 storage: Arc<dyn AuthStorage>,
310 event_buffer: Vec<AnalyticsEvent>,
311 last_collection: Instant,
312}
313
314impl AnalyticsManager {
315 pub fn new(config: AnalyticsConfig, storage: Arc<dyn AuthStorage>) -> Self {
317 Self {
318 config,
319 storage,
320 event_buffer: Vec::new(),
321 last_collection: Instant::now(),
322 }
323 }
324
325 pub async fn record_event(&mut self, event: AnalyticsEvent) -> Result<(), AnalyticsError> {
327 if self.event_buffer.len() >= self.config.max_event_buffer {
328 self.flush_events().await?;
329 }
330
331 self.event_buffer.push(event);
332
333 if self.config.real_time_enabled {
334 self.process_real_time_event(
336 self.event_buffer
337 .last()
338 .expect("buffer non-empty after push"),
339 )
340 .await?;
341 }
342
343 Ok(())
344 }
345
346 pub async fn get_role_usage_stats(
348 &self,
349 _role_id: Option<&str>,
350 _time_range: Option<TimeRange>,
351 ) -> Result<Vec<RoleUsageStats>, AnalyticsError> {
352 let keys = self
353 .storage
354 .list_kv_keys("analytics_event_")
355 .await
356 .unwrap_or_default();
357 let mut stats: HashMap<String, RoleUsageStats> = HashMap::new();
358 for key in keys {
359 if let Ok(Some(data)) = self.storage.get_kv(&key).await
360 && let Ok(event) = serde_json::from_slice::<AnalyticsEvent>(&data)
361 && let Some(ref role) = event.role_id
362 {
363 let entry = stats.entry(role.clone()).or_insert_with(|| RoleUsageStats {
364 role_id: role.clone(),
365 role_name: role.clone(),
366 user_count: 1,
367 permission_checks: 0,
368 successful_access: 0,
369 denied_access: 0,
370 last_used: None,
371 avg_response_time_ms: 0.0,
372 top_resources: Vec::new(),
373 });
374 if event.event_type == RbacEventType::PermissionCheck {
375 entry.permission_checks += 1;
376 if let Some(action) = &event.action {
377 if action == "Granted" {
378 entry.successful_access += 1;
379 } else {
380 entry.denied_access += 1;
381 }
382 }
383 entry.last_used = Some(event.timestamp);
384 }
385 }
386 }
387 Ok(stats.into_values().collect())
388 }
389
390 pub async fn get_permission_usage_stats(
392 &self,
393 _permission_id: Option<&str>,
394 _time_range: Option<TimeRange>,
395 ) -> Result<Vec<PermissionUsageStats>, AnalyticsError> {
396 let keys = self
397 .storage
398 .list_kv_keys("analytics_event_")
399 .await
400 .unwrap_or_default();
401 let mut stats: HashMap<String, PermissionUsageStats> = HashMap::new();
402 for key in keys {
403 if let Ok(Some(data)) = self.storage.get_kv(&key).await
404 && let Ok(event) = serde_json::from_slice::<AnalyticsEvent>(&data)
405 && let Some(ref perm) = event.resource
406 {
407 let entry = stats
408 .entry(perm.clone())
409 .or_insert_with(|| PermissionUsageStats {
410 permission_id: perm.clone(),
411 check_count: 0,
412 success_rate: 1.0,
413 used_by_roles: crate::types::Roles::empty(),
414 top_users: Vec::new(),
415 peak_hours: Vec::new(),
416 });
417 if event.event_type == RbacEventType::PermissionCheck {
418 entry.check_count += 1;
419 }
420 }
421 }
422 Ok(stats.into_values().collect())
423 }
424
425 pub async fn get_compliance_metrics(
427 &self,
428 _time_range: Option<TimeRange>,
429 ) -> Result<ComplianceMetrics, AnalyticsError> {
430 let keys = self
431 .storage
432 .list_kv_keys("analytics_event_")
433 .await
434 .unwrap_or_default();
435 let mut total_events = 0;
436 let mut policy_violations = 0;
437 let mut orphaned_permissions = 0;
438 let mut security_incidents = 0;
439 let mut revocation_durations = Vec::new();
441 let mut escalation_users = std::collections::HashSet::new();
443
444 for key in keys {
445 if let Ok(Some(data)) = self.storage.get_kv(&key).await
446 && let Ok(event) = serde_json::from_slice::<AnalyticsEvent>(&data)
447 {
448 total_events += 1;
449 if let Some(action) = &event.action
450 && (action.contains("Violation") || action.contains("Denied"))
451 {
452 policy_violations += 1;
453 }
454 if event.event_type == RbacEventType::PermissionCheck
455 && event.action.as_deref() == Some("Orphaned")
456 {
457 orphaned_permissions += 1;
458 }
459 if matches!(
460 event.event_type,
461 RbacEventType::PolicyViolation
462 | RbacEventType::PrivilegeEscalation
463 | RbacEventType::AccessAnomaly
464 ) || event
465 .action
466 .as_deref()
467 .is_some_and(|action| action.contains("Incident"))
468 {
469 security_incidents += 1;
470 }
471 if event.event_type == RbacEventType::PrivilegeEscalation
473 && let Some(ref user) = event.user_id
474 {
475 escalation_users.insert(user.clone());
476 }
477 if let Some(ref action) = event.action
479 && (action.contains("Revoked") || action.contains("Revocation"))
480 && let Some(hours_str) = event.metadata.get("revocation_hours")
481 && let Ok(hours) = hours_str.parse::<f64>()
482 {
483 revocation_durations.push(hours);
484 }
485 }
486 }
487
488 let compliance_score = if total_events > 0 {
489 100.0 - ((policy_violations as f64 / total_events as f64) * 100.0)
490 } else {
491 100.0
492 };
493
494 let avg_access_revocation_time_hours = if !revocation_durations.is_empty() {
495 revocation_durations.iter().sum::<f64>() / revocation_durations.len() as f64
496 } else {
497 0.0 };
499
500 let unused_roles = {
502 let defined_roles = self
503 .storage
504 .list_kv_keys("rbac:role:")
505 .await
506 .unwrap_or_default();
507 let assigned: std::collections::HashSet<String> = {
508 let user_role_keys = self
509 .storage
510 .list_kv_keys("rbac:user_roles:")
511 .await
512 .unwrap_or_default();
513 let mut set = std::collections::HashSet::new();
514 for key in &user_role_keys {
515 if let Ok(Some(data)) = self.storage.get_kv(key).await
516 && let Ok(roles) = serde_json::from_slice::<Vec<String>>(&data)
517 {
518 set.extend(roles);
519 }
520 }
521 set
522 };
523 defined_roles
524 .iter()
525 .filter(|k: &&String| {
526 let role_name = k.strip_prefix("rbac:role:").unwrap_or(k);
527 !assigned.contains(role_name)
528 })
529 .count() as u32
530 };
531
532 Ok(ComplianceMetrics {
533 role_assignment_compliance: compliance_score,
534 permission_scoping_compliance: compliance_score,
535 orphaned_permissions,
536 over_privileged_users: escalation_users.len() as u32,
537 unused_roles,
538 avg_access_revocation_time_hours,
539 policy_violations,
540 security_incidents,
541 })
542 }
543
544 pub async fn get_performance_metrics(
546 &self,
547 _time_range: Option<TimeRange>,
548 ) -> Result<PerformanceMetrics, AnalyticsError> {
549 let keys = self
550 .storage
551 .list_kv_keys("analytics_event_")
552 .await
553 .unwrap_or_default();
554 let mut total_events = 0;
555 let mut total_duration_ms = 0.0;
556 let mut duration_samples = Vec::new();
557 let mut errors = 0;
558 let mut permission_check_timestamps = Vec::new();
559
560 for key in keys {
561 if let Ok(Some(data)) = self.storage.get_kv(&key).await
562 && let Ok(event) = serde_json::from_slice::<AnalyticsEvent>(&data)
563 {
564 total_events += 1;
565 if let Some(duration_ms) = event.duration_ms {
566 total_duration_ms += duration_ms as f64;
567 duration_samples.push(duration_ms);
568 }
569 if event.event_type == RbacEventType::PermissionCheck {
570 permission_check_timestamps.push(event.timestamp);
571 }
572 if matches!(event.result, EventResult::Failure | EventResult::Error) {
573 errors += 1;
574 }
575 }
576 }
577
578 duration_samples.sort_unstable();
579 let p95 = if duration_samples.is_empty() {
580 0.0
581 } else {
582 let index = ((duration_samples.len() as f64 * 0.95).floor() as usize)
583 .min(duration_samples.len() - 1);
584 duration_samples[index] as f64
585 };
586 let p99 = if duration_samples.is_empty() {
587 0.0
588 } else {
589 let index = ((duration_samples.len() as f64 * 0.99).floor() as usize)
590 .min(duration_samples.len() - 1);
591 duration_samples[index] as f64
592 };
593 let avg = if duration_samples.is_empty() {
594 0.0
595 } else {
596 total_duration_ms / duration_samples.len() as f64
597 };
598 let error_rate = if total_events > 0 {
599 errors as f64 / total_events as f64
600 } else {
601 0.0
602 };
603 permission_check_timestamps.sort_unstable();
604 let permission_checks_per_second = match (
605 permission_check_timestamps.first(),
606 permission_check_timestamps.last(),
607 ) {
608 (Some(first), Some(last)) if permission_check_timestamps.len() > 1 => {
609 let span_seconds = (*last - *first).num_seconds().max(1) as f64;
610 permission_check_timestamps.len() as f64 / span_seconds
611 }
612 _ => 0.0,
613 };
614
615 Ok(PerformanceMetrics {
616 avg_permission_check_latency_ms: avg,
617 p95_permission_check_latency_ms: p95,
618 p99_permission_check_latency_ms: p99,
619 permission_checks_per_second,
620 permission_cache_hit_rate: {
623 let cache_hits = self
624 .event_buffer
625 .iter()
626 .filter(|e| e.event_type == RbacEventType::PermissionCheck)
627 .filter(|e| e.metadata.get("cache_hit").is_some_and(|v| v == "true"))
628 .count();
629 let cache_total = self
630 .event_buffer
631 .iter()
632 .filter(|e| e.event_type == RbacEventType::PermissionCheck)
633 .count();
634 if cache_total > 0 {
635 cache_hits as f64 / cache_total as f64
636 } else {
637 0.0
638 }
639 },
640 error_rate,
641 cpu_usage_percent: {
643 let mut sys = sysinfo::System::new();
644 let pid = sysinfo::get_current_pid().ok();
645 if let Some(pid) = pid {
646 sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
647 sys.process(pid)
648 .map(|p| p.cpu_usage() as f64)
649 .unwrap_or(0.0)
650 } else {
651 0.0
652 }
653 },
654 memory_usage_mb: {
655 #[cfg(target_os = "linux")]
658 {
659 std::fs::read_to_string("/proc/self/statm")
660 .ok()
661 .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
662 .map(|pages| pages * 4096 / (1024 * 1024))
663 .unwrap_or(0)
664 }
665 #[cfg(not(target_os = "linux"))]
666 {
667 0
668 }
669 },
670 })
671 }
672
673 pub async fn get_trend_analysis(
675 &self,
676 metric_name: &str,
677 _time_range: Option<TimeRange>,
678 ) -> Result<TrendAnalysis, AnalyticsError> {
679 let keys = self
680 .storage
681 .list_kv_keys("analytics_event_")
682 .await
683 .unwrap_or_default();
684 let mut data_points = Vec::new();
685
686 for key in keys {
687 if let Ok(Some(data)) = self.storage.get_kv(&key).await
688 && let Ok(event) = serde_json::from_slice::<AnalyticsEvent>(&data)
689 {
690 data_points.push(TimeSeriesData {
691 timestamp: event.timestamp,
692 value: 1.0,
693 tags: event.metadata.clone(),
694 });
695 }
696 }
697
698 data_points.sort_by_key(|point| point.timestamp);
699 let midpoint = data_points.len() / 2;
700 let previous_value = midpoint as f64;
701 let current_value = (data_points.len() - midpoint) as f64;
702 let change_percent = if previous_value == 0.0 {
703 if current_value == 0.0 { 0.0 } else { 100.0 }
704 } else {
705 ((current_value - previous_value) / previous_value) * 100.0
706 };
707 let direction = if change_percent.abs() < 5.0 {
708 TrendDirection::Stable
709 } else if change_percent > 0.0 {
710 TrendDirection::Increasing
711 } else {
712 TrendDirection::Decreasing
713 };
714
715 Ok(TrendAnalysis {
716 metric_name: metric_name.to_string(),
717 current_value,
718 previous_value,
719 change_percent,
720 trend: direction,
721 data_points,
722 })
723 }
724
725 pub async fn generate_report(
727 &self,
728 report_type: ReportType,
729 time_range: TimeRange,
730 ) -> Result<AnalyticsReport, AnalyticsError> {
731 let role_stats = self
732 .get_role_usage_stats(None, Some(time_range.clone()))
733 .await?;
734 let permission_stats = self
735 .get_permission_usage_stats(None, Some(time_range.clone()))
736 .await?;
737 let compliance_metrics = self
738 .get_compliance_metrics(Some(time_range.clone()))
739 .await?;
740 let performance_metrics = self
741 .get_performance_metrics(Some(time_range.clone()))
742 .await?;
743
744 Ok(AnalyticsReport {
745 report_type,
746 time_range,
747 generated_at: chrono::Utc::now(),
748 role_stats,
749 permission_stats,
750 compliance_metrics: compliance_metrics.clone(),
751 performance_metrics: performance_metrics.clone(),
752 summary: self.generate_report_summary(&compliance_metrics, &performance_metrics),
753 })
754 }
755
756 async fn flush_events(&mut self) -> Result<(), AnalyticsError> {
758 if self.event_buffer.is_empty() {
759 return Ok(());
760 }
761
762 for event in &self.event_buffer {
764 if let Ok(json_data) = serde_json::to_vec(event) {
765 let key = format!("analytics_event_{}", event.id);
766 let ttl =
768 std::time::Duration::from_secs(self.config.data_retention_days as u64 * 86400);
769 let _ = self.storage.store_kv(&key, &json_data, Some(ttl)).await;
770 }
771 }
772
773 self.event_buffer.clear();
775 self.last_collection = Instant::now();
776
777 Ok(())
778 }
779
780 async fn process_real_time_event(&self, event: &AnalyticsEvent) -> Result<(), AnalyticsError> {
784 let json_data = serde_json::to_vec(event)?;
785 let key = format!("analytics_event_{}", event.id);
786 let ttl = std::time::Duration::from_secs(self.config.data_retention_days as u64 * 86400);
787 self.storage
788 .store_kv(&key, &json_data, Some(ttl))
789 .await
790 .map_err(|e| AnalyticsError::StorageError(e.to_string()))?;
791 Ok(())
792 }
793
794 fn generate_report_summary(
796 &self,
797 compliance: &ComplianceMetrics,
798 performance: &PerformanceMetrics,
799 ) -> String {
800 format!(
801 "RBAC Analytics Summary: {}% compliance, {:.1}ms avg latency, {:.1}% error rate",
802 compliance.role_assignment_compliance,
803 performance.avg_permission_check_latency_ms,
804 performance.error_rate * 100.0
805 )
806 }
807}
808
809#[derive(Debug, Clone, Serialize, Deserialize)]
811pub struct TimeRange {
812 pub start: chrono::DateTime<chrono::Utc>,
813 pub end: chrono::DateTime<chrono::Utc>,
814}
815
816impl TimeRange {
817 pub fn last_hours(hours: u32) -> Self {
819 let end = chrono::Utc::now();
820 let start = end - chrono::Duration::hours(hours as i64);
821 Self { start, end }
822 }
823
824 pub fn last_days(days: u32) -> Self {
826 let end = chrono::Utc::now();
827 let start = end - chrono::Duration::days(days as i64);
828 Self { start, end }
829 }
830
831 pub fn today() -> Self {
833 let now = chrono::Utc::now();
834 let start = now
835 .date_naive()
836 .and_hms_opt(0, 0, 0)
837 .expect("0,0,0 are valid h/m/s values")
838 .and_utc();
839 let end = now;
840 Self { start, end }
841 }
842}
843
844#[derive(Debug, Clone, Serialize, Deserialize)]
846pub enum ReportType {
847 Daily,
849 Weekly,
851 Monthly,
853 Compliance,
855 Performance,
857 Custom(String),
859}
860
861#[derive(Debug, Clone, Serialize, Deserialize)]
863pub struct AnalyticsReport {
864 pub report_type: ReportType,
865 pub time_range: TimeRange,
866 pub generated_at: chrono::DateTime<chrono::Utc>,
867 pub role_stats: Vec<RoleUsageStats>,
868 pub permission_stats: Vec<PermissionUsageStats>,
869 pub compliance_metrics: ComplianceMetrics,
870 pub performance_metrics: PerformanceMetrics,
871 pub summary: String,
872}
873
874#[derive(Debug, thiserror::Error)]
876pub enum AnalyticsError {
877 #[error("Data processing error: {0}")]
878 ProcessingError(String),
879
880 #[error("Storage error: {0}")]
881 StorageError(String),
882
883 #[error("Query error: {0}")]
884 QueryError(String),
885
886 #[error("Configuration error: {0}")]
887 ConfigError(String),
888
889 #[error("IO error: {0}")]
890 IoError(#[from] std::io::Error),
891
892 #[error("Serialization error: {0}")]
893 SerializationError(#[from] serde_json::Error),
894}
895
896#[cfg(test)]
897mod tests {
898 use super::*;
899
900 #[test]
901 fn test_analytics_config_default() {
902 let config = AnalyticsConfig::default();
903 assert!(config.real_time_enabled);
904 assert_eq!(config.data_retention_days, 90);
905 assert!(config.compliance_monitoring);
906 }
907
908 #[test]
909 fn test_time_range_creation() {
910 let range = TimeRange::last_hours(24);
911 assert!(range.end > range.start);
912
913 let today = TimeRange::today();
914 assert!(today.end > today.start);
915 }
916
917 #[tokio::test]
918 async fn test_analytics_manager_creation() {
919 let config = AnalyticsConfig::default();
920 let manager = AnalyticsManager::new(
921 config,
922 std::sync::Arc::new(crate::storage::MemoryStorage::new()),
923 );
924 assert_eq!(manager.event_buffer.len(), 0);
925 }
926
927 #[tokio::test]
928 async fn test_record_event() {
929 let config = AnalyticsConfig::default();
930 let mut manager = AnalyticsManager::new(
931 config,
932 std::sync::Arc::new(crate::storage::MemoryStorage::new()),
933 );
934
935 let event = AnalyticsEvent {
936 id: "test_event_1".to_string(),
937 event_type: RbacEventType::PermissionCheck,
938 timestamp: chrono::Utc::now(),
939 user_id: Some("user123".to_string()),
940 role_id: Some("admin".to_string()),
941 resource: Some("user_data".to_string()),
942 action: Some("read".to_string()),
943 result: EventResult::Success,
944 metadata: HashMap::new(),
945 duration_ms: Some(15),
946 source_ip: Some("192.168.1.1".to_string()),
947 user_agent: Some("TestAgent/1.0".to_string()),
948 };
949
950 let result = manager.record_event(event).await;
951 assert!(result.is_ok());
952 assert_eq!(manager.event_buffer.len(), 1);
953 }
954}