1use crate::errors::{AuthError, Result};
84use crate::server::core::stepped_up_auth::SteppedUpAuthManager;
85use crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutManager;
86use crate::server::oidc::oidc_session_management::SessionManager;
87
88use async_trait::async_trait;
89use chrono::{DateTime, Duration, Timelike, Utc};
90use serde::{Deserialize, Serialize};
91use std::collections::HashMap;
92use std::sync::Arc;
93use tokio::sync::{RwLock, broadcast};
94use tokio::time::{Interval, interval};
95use uuid::Uuid;
96use zeroize::Zeroizing;
97
98type EventHandlerMap = Arc<RwLock<HashMap<CaepEventType, Vec<Arc<dyn CaepEventHandler>>>>>;
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct CaepConfig {
104 pub event_stream_url: String,
106
107 pub evaluation_interval: Duration,
109
110 pub auto_revoke: bool,
112
113 pub auto_revoke_threshold: f32,
115
116 pub max_concurrent_processors: usize,
118
119 pub event_retention_period: Duration,
121
122 pub propagation_endpoints: Vec<String>,
124
125 pub evaluation_rules: Vec<CaepEvaluationRule>,
127
128 pub signing_secret: Zeroizing<String>,
131}
132
133impl Default for CaepConfig {
134 fn default() -> Self {
135 use ring::rand::{SecureRandom, SystemRandom};
136 let rng = SystemRandom::new();
139 let mut bytes = [0u8; 32];
140 rng.fill(&mut bytes)
141 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
142 let signing_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
143 s.push_str(&format!("{b:02x}"));
144 s
145 });
146
147 Self {
148 event_stream_url: "wss://localhost:8080/caep/events".to_string(),
149 evaluation_interval: Duration::try_seconds(30).unwrap_or(Duration::zero()),
150 auto_revoke: true,
151 auto_revoke_threshold: 0.8,
152 max_concurrent_processors: 10,
153 event_retention_period: Duration::try_hours(24).unwrap_or(Duration::zero()),
154 propagation_endpoints: Vec::new(),
155 evaluation_rules: Vec::new(),
156 signing_secret: signing_secret.into(),
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
165#[serde(rename_all = "snake_case")]
166pub enum CaepEventType {
167 UserLogin,
169 UserLogout,
170 UserProfileChange,
171 UserCredentialChange,
172
173 SessionCreated,
175 SessionModified,
176 SessionTimeout,
177 SessionSuspiciousActivity,
178
179 RiskScoreChange,
181 LocationChange,
182 DeviceChange,
183 BehavioralAnomaly,
184
185 PolicyUpdate,
187 ComplianceViolation,
188 AccessPatternAnomaly,
189
190 SystemOutage,
192 SecurityIncident,
193 DataBreach,
194
195 Custom(String),
197}
198
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202pub enum CaepEventSeverity {
203 Low,
204 Medium,
205 High,
206 Critical,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct CaepEventSource {
212 pub system_id: String,
214
215 pub source_type: String,
217
218 pub version: Option<String>,
220
221 pub metadata: HashMap<String, serde_json::Value>,
223}
224
225#[derive(Clone, Serialize, Deserialize)]
227pub struct CaepEvent {
228 pub id: Uuid,
230
231 pub event_type: CaepEventType,
233
234 pub subject: String,
236
237 pub severity: CaepEventSeverity,
239
240 pub timestamp: DateTime<Utc>,
242
243 pub source: CaepEventSource,
245
246 pub risk_score: f32,
248
249 pub session_id: Option<String>,
251
252 pub location: Option<CaepLocationInfo>,
254
255 pub device_info: Option<CaepDeviceInfo>,
257
258 pub event_data: serde_json::Value,
260
261 pub correlation_id: Option<Uuid>,
263}
264
265impl std::fmt::Debug for CaepEvent {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 let mut d = f.debug_struct("CaepEvent");
268 d.field("id", &self.id);
269 d.field("event_type", &self.event_type);
270 d.field("subject", &self.subject);
271 d.field("severity", &self.severity);
272 d.field("timestamp", &self.timestamp);
273 d.field("source", &self.source);
274 d.field("risk_score", &self.risk_score);
275 d.field(
276 "session_id",
277 &crate::utils::redact::redacted(&self.session_id),
278 );
279 d.field("location", &self.location);
280 d.field("device_info", &self.device_info);
281 d.field("event_data", &self.event_data);
282 d.field("correlation_id", &self.correlation_id);
283 d.finish()
284 }
285}
286
287#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct CaepLocationInfo {
290 pub country: Option<String>,
292
293 pub region: Option<String>,
295
296 pub city: Option<String>,
298
299 pub latitude: Option<f64>,
301
302 pub longitude: Option<f64>,
304
305 pub ip_address: Option<String>,
307
308 pub is_suspicious: bool,
310}
311
312#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct CaepDeviceInfo {
315 pub device_id: Option<String>,
317
318 pub device_type: Option<String>,
320
321 pub os: Option<String>,
323
324 pub client: Option<String>,
326
327 pub is_trusted: bool,
329
330 pub requires_binding: bool,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct CaepEvaluationRule {
337 pub id: String,
339
340 pub description: String,
342
343 pub applicable_events: Vec<CaepEventType>,
345
346 pub conditions: Vec<CaepRuleCondition>,
348
349 pub actions: Vec<CaepRuleAction>,
351
352 pub priority: i32,
354
355 pub enabled: bool,
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize)]
361#[serde(tag = "type", rename_all = "snake_case")]
362pub enum CaepRuleCondition {
363 RiskScoreAbove { threshold: f32 },
365
366 SeverityAtLeast { severity: CaepEventSeverity },
368
369 LocationChange { suspicious_only: bool },
371
372 UnknownDevice { require_trusted: bool },
374
375 OutsideBusinessHours { timezone: String },
377
378 Custom { expression: String },
380}
381
382#[derive(Clone, Serialize, Deserialize)]
384#[serde(tag = "type", rename_all = "snake_case")]
385pub enum CaepRuleAction {
386 RevokeAccess { immediate: bool },
388
389 RequireStepUp { level: String },
391
392 SendNotification { channels: Vec<String> },
394
395 LogEvent { level: String },
397
398 TriggerWebhook { url: String },
400
401 QuarantineSession { duration_minutes: u32 },
403}
404
405impl std::fmt::Debug for CaepRuleAction {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 match self {
408 Self::RevokeAccess { immediate } => f
409 .debug_struct("RevokeAccess")
410 .field("immediate", immediate)
411 .finish(),
412 Self::RequireStepUp { level } => f
413 .debug_struct("RequireStepUp")
414 .field("level", level)
415 .finish(),
416 Self::SendNotification { channels } => f
417 .debug_struct("SendNotification")
418 .field("channels", channels)
419 .finish(),
420 Self::LogEvent { level } => f.debug_struct("LogEvent").field("level", level).finish(),
421 Self::TriggerWebhook { url } => f
423 .debug_struct("TriggerWebhook")
424 .field("url", &crate::utils::redact::redacted(url))
425 .finish(),
426 Self::QuarantineSession { duration_minutes } => f
427 .debug_struct("QuarantineSession")
428 .field("duration_minutes", duration_minutes)
429 .finish(),
430 }
431 }
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
436pub struct CaepEvaluationResult {
437 pub subject: String,
439
440 pub access_decision: CaepAccessDecision,
442
443 pub risk_score: f32,
445
446 pub triggered_rules: Vec<String>,
448
449 pub required_actions: Vec<CaepRuleAction>,
451
452 pub evaluated_at: DateTime<Utc>,
454
455 pub next_evaluation: DateTime<Utc>,
457}
458
459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
461#[serde(rename_all = "snake_case")]
462pub enum CaepAccessDecision {
463 Allow,
465
466 AllowWithMonitoring,
468
469 AllowWithStepUp,
471
472 TemporaryDeny,
474
475 Deny,
477}
478
479#[derive(Clone, Serialize, Deserialize)]
481pub struct CaepSessionState {
482 pub session_id: String,
484
485 pub subject: String,
487
488 pub risk_score: f32,
490
491 pub last_evaluation: Option<CaepEvaluationResult>,
493
494 pub active_events: Vec<CaepEvent>,
496
497 pub created_at: DateTime<Utc>,
499
500 pub last_activity: DateTime<Utc>,
502
503 pub is_quarantined: bool,
505
506 pub quarantine_until: Option<DateTime<Utc>>,
508}
509
510impl std::fmt::Debug for CaepSessionState {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 let mut d = f.debug_struct("CaepSessionState");
513 d.field(
514 "session_id",
515 &crate::utils::redact::redacted(&self.session_id),
516 );
517 d.field("subject", &self.subject);
518 d.field("risk_score", &self.risk_score);
519 d.field("last_evaluation", &self.last_evaluation);
520 d.field("active_events", &self.active_events);
521 d.field("created_at", &self.created_at);
522 d.field("last_activity", &self.last_activity);
523 d.field("is_quarantined", &self.is_quarantined);
524 d.field("quarantine_until", &self.quarantine_until);
525 d.finish()
526 }
527}
528
529#[derive(Debug, Clone, Serialize, Deserialize)]
531pub struct ComprehensiveSessionInfo {
532 pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
534
535 pub caep_session: Option<CaepSessionState>,
537
538 pub is_monitored_by_caep: bool,
540}
541
542#[async_trait]
544pub trait CaepEventHandler: Send + Sync {
545 async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
547
548 fn supported_event_types(&self) -> Vec<CaepEventType>;
550}
551
552pub struct CaepManager {
554 config: CaepConfig,
556
557 session_manager: Arc<SessionManager>,
559
560 logout_manager: Arc<BackChannelLogoutManager>,
562
563 step_up_manager: Option<Arc<SteppedUpAuthManager>>,
565
566 sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
568
569 event_handlers: EventHandlerMap,
571
572 event_broadcaster: broadcast::Sender<CaepEvent>,
574
575 evaluation_interval: Interval,
577
578 event_history: Arc<RwLock<Vec<CaepEvent>>>,
580
581 rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
583}
584
585impl CaepManager {
586 pub async fn new(
588 config: CaepConfig,
589 session_manager: Arc<SessionManager>,
590 logout_manager: Arc<BackChannelLogoutManager>,
591 ) -> Result<Self> {
592 let (event_broadcaster, _) = broadcast::channel(1000);
593 let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
594 AuthError::Configuration {
595 message: format!("Invalid evaluation interval: {}", e),
596 help: Some("Provide a valid duration for evaluation interval".to_string()),
597 docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
598 source: None,
599 suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
600 }
601 })?);
602
603 Ok(Self {
604 config: config.clone(),
605 session_manager,
606 logout_manager,
607 step_up_manager: None,
608 sessions: Arc::new(RwLock::new(HashMap::new())),
609 event_handlers: Arc::new(RwLock::new(HashMap::new())),
610 event_broadcaster,
611 evaluation_interval,
612 event_history: Arc::new(RwLock::new(Vec::new())),
613 rules: Arc::new(RwLock::new(config.evaluation_rules)),
614 })
615 }
616
617 pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
619 self.step_up_manager = Some(step_up_manager);
620 self
621 }
622
623 pub async fn register_event_handler(
625 &self,
626 event_type: CaepEventType,
627 handler: Arc<dyn CaepEventHandler>,
628 ) -> Result<()> {
629 let mut handlers = self.event_handlers.write().await;
630 handlers.entry(event_type).or_default().push(handler);
631 Ok(())
632 }
633
634 pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
636 {
638 let mut history = self.event_history.write().await;
639 history.push(event.clone());
640
641 let retention_cutoff = Utc::now() - self.config.event_retention_period;
643 history.retain(|e| e.timestamp >= retention_cutoff);
644 }
645
646 if let Err(e) = self.event_broadcaster.send(event.clone()) {
648 tracing::warn!("Failed to broadcast CAEP event: {}", e);
649 }
650
651 if let Some(session_id) = &event.session_id {
653 self.update_session_state(session_id, &event).await?;
654 }
655
656 let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
658
659 self.execute_actions(&evaluation_result).await?;
661
662 self.notify_handlers(&event).await?;
664
665 Ok(evaluation_result)
666 }
667
668 pub async fn evaluate_access(
670 &self,
671 subject: &str,
672 triggering_event: Option<&CaepEvent>,
673 ) -> Result<CaepEvaluationResult> {
674 let rules = self.rules.read().await;
675 let mut triggered_rules = Vec::new();
676 let mut required_actions = Vec::new();
677 let risk_score = if let Some(event) = triggering_event {
678 event.risk_score
679 } else {
680 self.calculate_risk_score(subject).await?
682 };
683
684 for rule in rules.iter() {
686 if !rule.enabled {
687 continue;
688 }
689
690 if let Some(event) = triggering_event
691 && !rule.applicable_events.contains(&event.event_type)
692 {
693 continue;
694 }
695
696 if self
697 .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
698 .await?
699 {
700 triggered_rules.push(rule.id.clone());
701 required_actions.extend(rule.actions.clone());
702 }
703 }
704
705 let access_decision = self.determine_access_decision(risk_score, &required_actions);
707
708 let now = Utc::now();
709 Ok(CaepEvaluationResult {
710 subject: subject.to_string(),
711 access_decision,
712 risk_score,
713 triggered_rules,
714 required_actions,
715 evaluated_at: now,
716 next_evaluation: now + self.config.evaluation_interval,
717 })
718 }
719
720 pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
722 loop {
723 self.evaluation_interval.tick().await;
724
725 self.synchronize_with_session_manager().await?;
727
728 let sessions = {
730 let sessions_guard = self.sessions.read().await;
731 sessions_guard.keys().cloned().collect::<Vec<_>>()
732 };
733
734 for session_id in sessions {
735 if let Some(session_state) = self.sessions.read().await.get(&session_id) {
736 let evaluation = self.evaluate_access(&session_state.subject, None).await?;
737 self.execute_actions(&evaluation).await?;
738 }
739 }
740 }
741 }
742
743 async fn synchronize_with_session_manager(&self) -> Result<()> {
745 let mut sessions = self.sessions.write().await;
746 let mut sessions_to_remove = Vec::new();
747
748 for (session_id, caep_session) in sessions.iter() {
749 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
751 if !self.session_manager.is_session_valid(session_id) {
752 tracing::info!("CAEP removing expired session: {}", session_id);
753 sessions_to_remove.push(session_id.clone());
754 }
755 else if oidc_session.sub != caep_session.subject {
757 tracing::warn!("CAEP session subject mismatch, removing: {}", session_id);
758 sessions_to_remove.push(session_id.clone());
759 }
760 } else {
761 tracing::info!("CAEP removing orphaned session: {}", session_id);
762 sessions_to_remove.push(session_id.clone());
763 }
764 }
765
766 for session_id in sessions_to_remove {
768 sessions.remove(&session_id);
769 }
770
771 Ok(())
772 }
773
774 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
776 tracing::info!("CAEP revoking access for subject: {}", subject);
777
778 let sessions_to_logout = {
780 let sessions = self.sessions.read().await;
781 sessions
782 .iter()
783 .filter(|(_, session)| session.subject == subject)
784 .map(|(session_id, session)| (session_id.clone(), session.clone()))
785 .collect::<Vec<_>>()
786 };
787
788 for (session_id, _) in &sessions_to_logout {
790 let logout_request =
792 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
793 session_id: session_id.clone(),
794 sub: subject.to_string(),
795 sid: Some(session_id.clone()),
796 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
799 let mut events = HashMap::new();
800 events.insert(
801 "caep_reason".to_string(),
802 serde_json::json!("automatic_revocation"),
803 );
804 events.insert(
805 "timestamp".to_string(),
806 serde_json::json!(Utc::now().timestamp()),
807 );
808 events
809 }),
810 };
811
812 match self.process_backchannel_logout(&logout_request).await {
815 Ok(_) => {
816 tracing::info!(
817 "Successfully initiated back-channel logout for session {} (subject: {})",
818 session_id,
819 subject
820 );
821 }
822 Err(e) => {
823 tracing::error!(
824 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
825 session_id,
826 subject,
827 e
828 );
829 }
830 }
831 }
832
833 let mut sessions = self.sessions.write().await;
835 sessions.retain(|_, session| session.subject != subject);
836
837 Ok(())
838 }
839
840 async fn process_backchannel_logout(
842 &self,
843 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
844 ) -> Result<()> {
845 let logout_metadata = self.logout_manager.get_discovery_metadata();
850 tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
851
852 let logout_token = self
854 .create_logout_token_for_caep_revocation(logout_request)
855 .await?;
856
857 self.handle_caep_logout(logout_request, &logout_token)
859 .await?;
860
861 tracing::info!("CAEP backchannel logout processed successfully");
862 Ok(())
863 }
864
865 async fn create_logout_token_for_caep_revocation(
867 &self,
868 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
869 ) -> Result<String> {
870 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
871 use serde_json::json;
872
873 let claims = json!({
875 "iss": logout_request.iss,
876 "sub": logout_request.sub,
877 "aud": ["caep-manager"],
878 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
879 "iat": chrono::Utc::now().timestamp(),
880 "jti": uuid::Uuid::new_v4().to_string(),
881 "sid": logout_request.sid,
882 "events": {
883 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
884 },
885 "caep_reason": logout_request.additional_events
886 .as_ref()
887 .and_then(|events| events.get("caep_reason"))
888 .unwrap_or(&serde_json::json!("automatic_revocation"))
889 });
890
891 let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
893 let header = Header::new(Algorithm::HS256);
894
895 let token = encode(&header, &claims, &key).map_err(|e| {
896 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
897 })?;
898
899 Ok(token)
900 }
901
902 async fn handle_caep_logout(
904 &self,
905 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
906 logout_token: &str,
907 ) -> Result<()> {
908 tracing::info!(
916 "Processing CAEP logout for session: {}",
917 logout_request.session_id
918 );
919
920 {
922 let mut sessions = self.sessions.write().await;
923 if let Some(_session) = sessions.get(&logout_request.session_id) {
924 sessions.remove(&logout_request.session_id);
926 }
927 }
928
929 let caep_event = CaepEvent {
931 id: uuid::Uuid::new_v4(),
932 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
934 session_id: Some(logout_request.session_id.clone()),
935 timestamp: chrono::Utc::now(),
936 severity: CaepEventSeverity::High,
937 source: CaepEventSource {
938 system_id: "caep-manager".to_string(),
939 source_type: "caep_automatic_revocation".to_string(),
940 version: Some("1.0".to_string()),
941 metadata: std::collections::HashMap::new(),
942 },
943 risk_score: 1.0, location: None,
945 device_info: None,
946 event_data: serde_json::json!({
947 "logout_token": logout_token,
948 "initiator": "caep_automatic_revocation",
949 "reason": logout_request.additional_events
950 .as_ref()
951 .and_then(|events| events.get("caep_reason"))
952 .cloned()
953 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
954 }),
955 correlation_id: Some(uuid::Uuid::new_v4()),
956 };
957
958 if let Err(e) = self.event_broadcaster.send(caep_event) {
960 tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
961 }
962
963 tracing::info!(
964 "CAEP logout completed for session: {}",
965 logout_request.session_id
966 );
967 Ok(())
968 }
969
970 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
972 let history = self.event_history.read().await;
973 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
974
975 let recent_events: Vec<_> = history
976 .iter()
977 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
978 .collect();
979
980 if recent_events.is_empty() {
981 return Ok(0.0);
982 }
983
984 let mut total_risk = 0.0;
986 let mut total_weight = 0.0;
987
988 for event in recent_events {
989 let weight = match event.severity {
990 CaepEventSeverity::Low => 1.0,
991 CaepEventSeverity::Medium => 2.0,
992 CaepEventSeverity::High => 4.0,
993 CaepEventSeverity::Critical => 8.0,
994 };
995
996 total_risk += event.risk_score * weight;
997 total_weight += weight;
998 }
999
1000 Ok(if total_weight > 0.0 {
1001 (total_risk / total_weight).min(1.0)
1002 } else {
1003 0.0
1004 })
1005 }
1006
1007 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1009 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1011 if !self.session_manager.is_session_valid(session_id) {
1013 tracing::warn!(
1014 "CAEP received event for expired OIDC session: {}",
1015 session_id
1016 );
1017 let mut sessions = self.sessions.write().await;
1019 sessions.remove(session_id);
1020 return Ok(());
1021 }
1022
1023 if oidc_session.sub != event.subject {
1025 return Err(AuthError::validation(
1026 "Subject mismatch between CAEP event and OIDC session",
1027 ));
1028 }
1029 } else {
1030 tracing::warn!(
1031 "CAEP received event for unknown OIDC session: {}",
1032 session_id
1033 );
1034 return Err(AuthError::validation("Session not found in SessionManager"));
1035 }
1036
1037 let mut sessions = self.sessions.write().await;
1039
1040 let session_state =
1041 sessions
1042 .entry(session_id.to_string())
1043 .or_insert_with(|| CaepSessionState {
1044 session_id: session_id.to_string(),
1045 subject: event.subject.clone(),
1046 risk_score: event.risk_score,
1047 last_evaluation: None,
1048 active_events: Vec::new(),
1049 created_at: Utc::now(),
1050 last_activity: Utc::now(),
1051 is_quarantined: false,
1052 quarantine_until: None,
1053 });
1054
1055 session_state.risk_score = event.risk_score;
1056 session_state.last_activity = Utc::now();
1057 session_state.active_events.push(event.clone());
1058
1059 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1061 session_state
1062 .active_events
1063 .retain(|e| e.timestamp >= cutoff);
1064
1065 Ok(())
1066 }
1067
1068 async fn evaluate_rule_conditions(
1070 &self,
1071 rule: &CaepEvaluationRule,
1072 _subject: &str,
1073 event: Option<&CaepEvent>,
1074 risk_score: f32,
1075 ) -> Result<bool> {
1076 for condition in &rule.conditions {
1077 match condition {
1078 CaepRuleCondition::RiskScoreAbove { threshold } => {
1079 if risk_score <= *threshold {
1080 return Ok(false);
1081 }
1082 }
1083 CaepRuleCondition::SeverityAtLeast { severity } => {
1084 if let Some(event) = event {
1085 let event_severity_level = match event.severity {
1086 CaepEventSeverity::Critical => 4,
1087 CaepEventSeverity::High => 3,
1088 CaepEventSeverity::Medium => 2,
1089 CaepEventSeverity::Low => 1,
1090 };
1091
1092 let required_severity_level = match severity {
1093 CaepEventSeverity::Critical => 4,
1094 CaepEventSeverity::High => 3,
1095 CaepEventSeverity::Medium => 2,
1096 CaepEventSeverity::Low => 1,
1097 };
1098
1099 if event_severity_level < required_severity_level {
1100 return Ok(false);
1101 }
1102 } else {
1103 return Ok(false);
1104 }
1105 }
1106 CaepRuleCondition::LocationChange { suspicious_only } => {
1107 if let Some(event) = event {
1108 if let Some(location) = &event.location {
1109 if *suspicious_only && !location.is_suspicious {
1110 return Ok(false);
1111 }
1112 } else {
1113 return Ok(false);
1114 }
1115 } else {
1116 return Ok(false);
1117 }
1118 }
1119 CaepRuleCondition::UnknownDevice { require_trusted } => {
1120 if let Some(event) = event
1121 && let Some(device) = &event.device_info
1122 && *require_trusted
1123 && device.is_trusted
1124 {
1125 return Ok(false);
1126 }
1127 }
1128 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1129 let hour = Utc::now().hour();
1131 if (9..17).contains(&hour) {
1132 return Ok(false);
1133 }
1134 }
1135 CaepRuleCondition::Custom { expression } => {
1136 if !Self::evaluate_simple_expression(expression) {
1138 return Ok(false);
1139 }
1140 }
1141 }
1142 }
1143
1144 Ok(true)
1145 }
1146
1147 fn evaluate_simple_expression(expression: &str) -> bool {
1150 let parts: Vec<&str> = expression.split_whitespace().collect();
1151 if parts.len() != 3 {
1152 tracing::warn!(
1153 expression = expression,
1154 "Unrecognized custom CAEP expression format, defaulting to false"
1155 );
1156 return false;
1157 }
1158
1159 let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1160 let Ok(threshold) = value_str.parse::<f64>() else {
1161 tracing::warn!(
1162 expression = expression,
1163 "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1164 );
1165 return false;
1166 };
1167
1168 tracing::debug!(
1171 expression = expression,
1172 threshold = threshold,
1173 op = op,
1174 "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1175 );
1176 false
1177 }
1178
1179 fn determine_access_decision(
1181 &self,
1182 risk_score: f32,
1183 actions: &[CaepRuleAction],
1184 ) -> CaepAccessDecision {
1185 for action in actions {
1186 match action {
1187 CaepRuleAction::RevokeAccess { immediate: true } => {
1188 return CaepAccessDecision::Deny;
1189 }
1190 CaepRuleAction::RevokeAccess { immediate: false } => {
1191 return CaepAccessDecision::TemporaryDeny;
1192 }
1193 CaepRuleAction::RequireStepUp { .. } => {
1194 return CaepAccessDecision::AllowWithStepUp;
1195 }
1196 CaepRuleAction::QuarantineSession { .. } => {
1197 return CaepAccessDecision::TemporaryDeny;
1198 }
1199 _ => {}
1200 }
1201 }
1202
1203 if risk_score >= self.config.auto_revoke_threshold {
1204 CaepAccessDecision::Deny
1205 } else if risk_score >= 0.6 {
1206 CaepAccessDecision::AllowWithMonitoring
1207 } else {
1208 CaepAccessDecision::Allow
1209 }
1210 }
1211
1212 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1214 for action in &evaluation.required_actions {
1215 match action {
1216 CaepRuleAction::RevokeAccess { .. } => {
1217 self.revoke_subject_access(&evaluation.subject).await?;
1218 }
1219 CaepRuleAction::RequireStepUp { level } => {
1220 if let Some(_step_up_manager) = &self.step_up_manager {
1221 tracing::info!(
1223 "CAEP requiring step-up to level {} for subject {}",
1224 level,
1225 evaluation.subject
1226 );
1227 }
1228 }
1229 CaepRuleAction::SendNotification { channels } => {
1230 tracing::info!(
1231 "CAEP sending notification via channels {:?} for subject {}",
1232 channels,
1233 evaluation.subject
1234 );
1235 }
1236 CaepRuleAction::LogEvent { level } => {
1237 tracing::info!(
1238 "CAEP logging event at level {} for subject {}",
1239 level,
1240 evaluation.subject
1241 );
1242 }
1243 CaepRuleAction::TriggerWebhook { url } => {
1244 tracing::info!(
1245 "CAEP triggering webhook {} for subject {}",
1246 url,
1247 evaluation.subject
1248 );
1249 }
1250 CaepRuleAction::QuarantineSession { duration_minutes } => {
1251 self.quarantine_session(&evaluation.subject, *duration_minutes)
1252 .await?;
1253 }
1254 }
1255 }
1256
1257 Ok(())
1258 }
1259
1260 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1262 let mut sessions = self.sessions.write().await;
1263 let quarantine_until =
1264 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1265
1266 let mut quarantined_session_ids = Vec::new();
1268 for session in sessions.values_mut() {
1269 if session.subject == subject {
1270 session.is_quarantined = true;
1271 session.quarantine_until = Some(quarantine_until);
1272 quarantined_session_ids.push(session.session_id.clone());
1273 }
1274 }
1275
1276 tracing::info!(
1277 "CAEP quarantined {} sessions for subject {} until {}. Session IDs: {:?}",
1278 quarantined_session_ids.len(),
1279 subject,
1280 quarantine_until,
1281 quarantined_session_ids
1282 );
1283
1284 Ok(())
1288 }
1289
1290 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1292 let handlers = self.event_handlers.read().await;
1293
1294 if let Some(event_handlers) = handlers.get(&event.event_type) {
1295 for handler in event_handlers {
1296 if let Err(e) = handler.handle_event(event).await {
1297 tracing::error!("CAEP event handler failed: {}", e);
1298 }
1299 }
1300 }
1301
1302 Ok(())
1303 }
1304
1305 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1307 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1309 if !self.session_manager.is_session_valid(session_id) {
1310 let mut sessions = self.sessions.write().await;
1312 sessions.remove(session_id);
1313 return Ok(None);
1314 }
1315
1316 let sessions = self.sessions.read().await;
1318 if let Some(caep_session) = sessions.get(session_id) {
1319 if caep_session.subject == oidc_session.sub {
1320 return Ok(Some(caep_session.clone()));
1321 } else {
1322 tracing::warn!(
1323 "Subject mismatch between CAEP and OIDC sessions for {}",
1324 session_id
1325 );
1326 return Ok(None);
1327 }
1328 }
1329 }
1330
1331 Ok(None)
1333 }
1334
1335 pub async fn get_event_history(
1337 &self,
1338 subject: &str,
1339 limit: Option<usize>,
1340 ) -> Result<Vec<CaepEvent>> {
1341 let history = self.event_history.read().await;
1342 let mut events: Vec<_> = history
1343 .iter()
1344 .filter(|e| e.subject == subject)
1345 .cloned()
1346 .collect();
1347
1348 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1349
1350 if let Some(limit) = limit {
1351 events.truncate(limit);
1352 }
1353
1354 Ok(events)
1355 }
1356
1357 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1359 let mut rules = self.rules.write().await;
1360
1361 rules.retain(|r| r.id != rule.id);
1363
1364 rules.push(rule);
1366 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1367
1368 Ok(())
1369 }
1370
1371 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1373 let mut rules = self.rules.write().await;
1374 let original_len = rules.len();
1375 rules.retain(|r| r.id != rule_id);
1376 Ok(rules.len() < original_len)
1377 }
1378
1379 pub async fn get_comprehensive_session_info(
1381 &self,
1382 session_id: &str,
1383 ) -> Result<Option<ComprehensiveSessionInfo>> {
1384 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1386 if !self.session_manager.is_session_valid(session_id) {
1387 return Ok(None);
1388 }
1389
1390 let caep_session = {
1392 let sessions = self.sessions.read().await;
1393 sessions.get(session_id).cloned()
1394 };
1395
1396 let comprehensive_info = ComprehensiveSessionInfo {
1397 oidc_session: oidc_session.clone(),
1398 is_monitored_by_caep: caep_session.is_some(),
1399 caep_session,
1400 };
1401
1402 Ok(Some(comprehensive_info))
1403 } else {
1404 Ok(None)
1405 }
1406 }
1407
1408 pub async fn get_subject_sessions(
1410 &self,
1411 subject: &str,
1412 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1413 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1414 let mut comprehensive_sessions = Vec::new();
1415
1416 for oidc_session in oidc_sessions {
1417 if self
1418 .session_manager
1419 .is_session_valid(&oidc_session.session_id)
1420 {
1421 let caep_session = {
1422 let sessions = self.sessions.read().await;
1423 sessions.get(&oidc_session.session_id).cloned()
1424 };
1425
1426 comprehensive_sessions.push(ComprehensiveSessionInfo {
1427 oidc_session: oidc_session.clone(),
1428 is_monitored_by_caep: caep_session.is_some(),
1429 caep_session,
1430 });
1431 }
1432 }
1433
1434 Ok(comprehensive_sessions)
1435 }
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440 use super::*;
1441 use tokio;
1442
1443 #[tokio::test]
1444 async fn test_caep_event_creation() {
1445 let event = CaepEvent {
1446 id: Uuid::new_v4(),
1447 event_type: CaepEventType::RiskScoreChange,
1448 subject: "user123".to_string(),
1449 severity: CaepEventSeverity::High,
1450 timestamp: Utc::now(),
1451 source: CaepEventSource {
1452 system_id: "risk_engine".to_string(),
1453 source_type: "ml_model".to_string(),
1454 version: Some("1.0.0".to_string()),
1455 metadata: HashMap::new(),
1456 },
1457 risk_score: 0.85,
1458 session_id: Some("session123".to_string()),
1459 location: None,
1460 device_info: None,
1461 event_data: serde_json::json!({
1462 "previous_score": 0.3,
1463 "new_score": 0.85,
1464 "trigger": "suspicious_login_pattern"
1465 }),
1466 correlation_id: None,
1467 };
1468
1469 assert_eq!(event.subject, "user123");
1470 assert_eq!(event.risk_score, 0.85);
1471 assert!(matches!(event.severity, CaepEventSeverity::High));
1472 }
1473
1474 #[tokio::test]
1475 async fn test_caep_config_creation() {
1476 let config = CaepConfig::default();
1477 assert!(!config.event_stream_url.is_empty());
1478 assert!(config.auto_revoke);
1479 assert_eq!(config.auto_revoke_threshold, 0.8);
1480 }
1481
1482 #[tokio::test]
1483 async fn test_severity_comparison() {
1484 let high_level = match CaepEventSeverity::High {
1486 CaepEventSeverity::Critical => 4,
1487 CaepEventSeverity::High => 3,
1488 CaepEventSeverity::Medium => 2,
1489 CaepEventSeverity::Low => 1,
1490 };
1491
1492 let medium_level = match CaepEventSeverity::Medium {
1493 CaepEventSeverity::Critical => 4,
1494 CaepEventSeverity::High => 3,
1495 CaepEventSeverity::Medium => 2,
1496 CaepEventSeverity::Low => 1,
1497 };
1498
1499 assert!(high_level > medium_level);
1500 }
1501}