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;
96
97type EventHandlerMap = Arc<RwLock<HashMap<CaepEventType, Vec<Arc<dyn CaepEventHandler>>>>>;
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct CaepConfig {
103 pub event_stream_url: String,
105
106 pub evaluation_interval: Duration,
108
109 pub auto_revoke: bool,
111
112 pub auto_revoke_threshold: f32,
114
115 pub max_concurrent_processors: usize,
117
118 pub event_retention_period: Duration,
120
121 pub propagation_endpoints: Vec<String>,
123
124 pub evaluation_rules: Vec<CaepEvaluationRule>,
126}
127
128impl Default for CaepConfig {
129 fn default() -> Self {
130 Self {
131 event_stream_url: "wss://localhost:8080/caep/events".to_string(),
132 evaluation_interval: Duration::try_seconds(30).unwrap_or(Duration::zero()),
133 auto_revoke: true,
134 auto_revoke_threshold: 0.8,
135 max_concurrent_processors: 10,
136 event_retention_period: Duration::try_hours(24).unwrap_or(Duration::zero()),
137 propagation_endpoints: Vec::new(),
138 evaluation_rules: Vec::new(),
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum CaepEventType {
147 UserLogin,
149 UserLogout,
150 UserProfileChange,
151 UserCredentialChange,
152
153 SessionCreated,
155 SessionModified,
156 SessionTimeout,
157 SessionSuspiciousActivity,
158
159 RiskScoreChange,
161 LocationChange,
162 DeviceChange,
163 BehavioralAnomaly,
164
165 PolicyUpdate,
167 ComplianceViolation,
168 AccessPatternAnomaly,
169
170 SystemOutage,
172 SecurityIncident,
173 DataBreach,
174
175 Custom(String),
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181#[serde(rename_all = "snake_case")]
182pub enum CaepEventSeverity {
183 Low,
184 Medium,
185 High,
186 Critical,
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct CaepEventSource {
192 pub system_id: String,
194
195 pub source_type: String,
197
198 pub version: Option<String>,
200
201 pub metadata: HashMap<String, serde_json::Value>,
203}
204
205#[derive(Clone, Serialize, Deserialize)]
207pub struct CaepEvent {
208 pub id: Uuid,
210
211 pub event_type: CaepEventType,
213
214 pub subject: String,
216
217 pub severity: CaepEventSeverity,
219
220 pub timestamp: DateTime<Utc>,
222
223 pub source: CaepEventSource,
225
226 pub risk_score: f32,
228
229 pub session_id: Option<String>,
231
232 pub location: Option<CaepLocationInfo>,
234
235 pub device_info: Option<CaepDeviceInfo>,
237
238 pub event_data: serde_json::Value,
240
241 pub correlation_id: Option<Uuid>,
243}
244
245impl std::fmt::Debug for CaepEvent {
246 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247 let mut d = f.debug_struct("CaepEvent");
248 d.field("id", &self.id);
249 d.field("event_type", &self.event_type);
250 d.field("subject", &self.subject);
251 d.field("severity", &self.severity);
252 d.field("timestamp", &self.timestamp);
253 d.field("source", &self.source);
254 d.field("risk_score", &self.risk_score);
255 d.field(
256 "session_id",
257 &crate::utils::redact::redacted(&self.session_id),
258 );
259 d.field("location", &self.location);
260 d.field("device_info", &self.device_info);
261 d.field("event_data", &self.event_data);
262 d.field("correlation_id", &self.correlation_id);
263 d.finish()
264 }
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct CaepLocationInfo {
270 pub country: Option<String>,
272
273 pub region: Option<String>,
275
276 pub city: Option<String>,
278
279 pub latitude: Option<f64>,
281
282 pub longitude: Option<f64>,
284
285 pub ip_address: Option<String>,
287
288 pub is_suspicious: bool,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct CaepDeviceInfo {
295 pub device_id: Option<String>,
297
298 pub device_type: Option<String>,
300
301 pub os: Option<String>,
303
304 pub client: Option<String>,
306
307 pub is_trusted: bool,
309
310 pub requires_binding: bool,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct CaepEvaluationRule {
317 pub id: String,
319
320 pub description: String,
322
323 pub applicable_events: Vec<CaepEventType>,
325
326 pub conditions: Vec<CaepRuleCondition>,
328
329 pub actions: Vec<CaepRuleAction>,
331
332 pub priority: i32,
334
335 pub enabled: bool,
337}
338
339#[derive(Debug, Clone, Serialize, Deserialize)]
341#[serde(tag = "type", rename_all = "snake_case")]
342pub enum CaepRuleCondition {
343 RiskScoreAbove { threshold: f32 },
345
346 SeverityAtLeast { severity: CaepEventSeverity },
348
349 LocationChange { suspicious_only: bool },
351
352 UnknownDevice { require_trusted: bool },
354
355 OutsideBusinessHours { timezone: String },
357
358 Custom { expression: String },
360}
361
362#[derive(Clone, Serialize, Deserialize)]
364#[serde(tag = "type", rename_all = "snake_case")]
365pub enum CaepRuleAction {
366 RevokeAccess { immediate: bool },
368
369 RequireStepUp { level: String },
371
372 SendNotification { channels: Vec<String> },
374
375 LogEvent { level: String },
377
378 TriggerWebhook { url: String },
380
381 QuarantineSession { duration_minutes: u32 },
383}
384
385impl std::fmt::Debug for CaepRuleAction {
386 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
387 match self {
388 Self::RevokeAccess { immediate } => f
389 .debug_struct("RevokeAccess")
390 .field("immediate", immediate)
391 .finish(),
392 Self::RequireStepUp { level } => f
393 .debug_struct("RequireStepUp")
394 .field("level", level)
395 .finish(),
396 Self::SendNotification { channels } => f
397 .debug_struct("SendNotification")
398 .field("channels", channels)
399 .finish(),
400 Self::LogEvent { level } => f.debug_struct("LogEvent").field("level", level).finish(),
401 Self::TriggerWebhook { url } => f
403 .debug_struct("TriggerWebhook")
404 .field("url", &crate::utils::redact::redacted(url))
405 .finish(),
406 Self::QuarantineSession { duration_minutes } => f
407 .debug_struct("QuarantineSession")
408 .field("duration_minutes", duration_minutes)
409 .finish(),
410 }
411 }
412}
413
414#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct CaepEvaluationResult {
417 pub subject: String,
419
420 pub access_decision: CaepAccessDecision,
422
423 pub risk_score: f32,
425
426 pub triggered_rules: Vec<String>,
428
429 pub required_actions: Vec<CaepRuleAction>,
431
432 pub evaluated_at: DateTime<Utc>,
434
435 pub next_evaluation: DateTime<Utc>,
437}
438
439#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
441#[serde(rename_all = "snake_case")]
442pub enum CaepAccessDecision {
443 Allow,
445
446 AllowWithMonitoring,
448
449 AllowWithStepUp,
451
452 TemporaryDeny,
454
455 Deny,
457}
458
459#[derive(Clone, Serialize, Deserialize)]
461pub struct CaepSessionState {
462 pub session_id: String,
464
465 pub subject: String,
467
468 pub risk_score: f32,
470
471 pub last_evaluation: Option<CaepEvaluationResult>,
473
474 pub active_events: Vec<CaepEvent>,
476
477 pub created_at: DateTime<Utc>,
479
480 pub last_activity: DateTime<Utc>,
482
483 pub is_quarantined: bool,
485
486 pub quarantine_until: Option<DateTime<Utc>>,
488}
489
490impl std::fmt::Debug for CaepSessionState {
491 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492 let mut d = f.debug_struct("CaepSessionState");
493 d.field(
494 "session_id",
495 &crate::utils::redact::redacted(&self.session_id),
496 );
497 d.field("subject", &self.subject);
498 d.field("risk_score", &self.risk_score);
499 d.field("last_evaluation", &self.last_evaluation);
500 d.field("active_events", &self.active_events);
501 d.field("created_at", &self.created_at);
502 d.field("last_activity", &self.last_activity);
503 d.field("is_quarantined", &self.is_quarantined);
504 d.field("quarantine_until", &self.quarantine_until);
505 d.finish()
506 }
507}
508
509#[derive(Debug, Clone, Serialize, Deserialize)]
511pub struct ComprehensiveSessionInfo {
512 pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
514
515 pub caep_session: Option<CaepSessionState>,
517
518 pub is_monitored_by_caep: bool,
520}
521
522#[async_trait]
524pub trait CaepEventHandler: Send + Sync {
525 async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
527
528 fn supported_event_types(&self) -> Vec<CaepEventType>;
530}
531
532pub struct CaepManager {
534 config: CaepConfig,
536
537 session_manager: Arc<SessionManager>,
539
540 logout_manager: Arc<BackChannelLogoutManager>,
542
543 step_up_manager: Option<Arc<SteppedUpAuthManager>>,
545
546 sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
548
549 event_handlers: EventHandlerMap,
551
552 event_broadcaster: broadcast::Sender<CaepEvent>,
554
555 evaluation_interval: Interval,
557
558 event_history: Arc<RwLock<Vec<CaepEvent>>>,
560
561 rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
563}
564
565impl CaepManager {
566 pub async fn new(
568 config: CaepConfig,
569 session_manager: Arc<SessionManager>,
570 logout_manager: Arc<BackChannelLogoutManager>,
571 ) -> Result<Self> {
572 let (event_broadcaster, _) = broadcast::channel(1000);
573 let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
574 AuthError::Configuration {
575 message: format!("Invalid evaluation interval: {}", e),
576 help: Some("Provide a valid duration for evaluation interval".to_string()),
577 docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
578 source: None,
579 suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
580 }
581 })?);
582
583 Ok(Self {
584 config: config.clone(),
585 session_manager,
586 logout_manager,
587 step_up_manager: None,
588 sessions: Arc::new(RwLock::new(HashMap::new())),
589 event_handlers: Arc::new(RwLock::new(HashMap::new())),
590 event_broadcaster,
591 evaluation_interval,
592 event_history: Arc::new(RwLock::new(Vec::new())),
593 rules: Arc::new(RwLock::new(config.evaluation_rules)),
594 })
595 }
596
597 pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
599 self.step_up_manager = Some(step_up_manager);
600 self
601 }
602
603 pub async fn register_event_handler(
605 &self,
606 event_type: CaepEventType,
607 handler: Arc<dyn CaepEventHandler>,
608 ) -> Result<()> {
609 let mut handlers = self.event_handlers.write().await;
610 handlers.entry(event_type).or_default().push(handler);
611 Ok(())
612 }
613
614 pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
616 {
618 let mut history = self.event_history.write().await;
619 history.push(event.clone());
620
621 let retention_cutoff = Utc::now() - self.config.event_retention_period;
623 history.retain(|e| e.timestamp >= retention_cutoff);
624 }
625
626 if let Err(e) = self.event_broadcaster.send(event.clone()) {
628 log::warn!("Failed to broadcast CAEP event: {}", e);
629 }
630
631 if let Some(session_id) = &event.session_id {
633 self.update_session_state(session_id, &event).await?;
634 }
635
636 let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
638
639 self.execute_actions(&evaluation_result).await?;
641
642 self.notify_handlers(&event).await?;
644
645 Ok(evaluation_result)
646 }
647
648 pub async fn evaluate_access(
650 &self,
651 subject: &str,
652 triggering_event: Option<&CaepEvent>,
653 ) -> Result<CaepEvaluationResult> {
654 let rules = self.rules.read().await;
655 let mut triggered_rules = Vec::new();
656 let mut required_actions = Vec::new();
657 let risk_score = if let Some(event) = triggering_event {
658 event.risk_score
659 } else {
660 self.calculate_risk_score(subject).await?
662 };
663
664 for rule in rules.iter() {
666 if !rule.enabled {
667 continue;
668 }
669
670 if let Some(event) = triggering_event
671 && !rule.applicable_events.contains(&event.event_type)
672 {
673 continue;
674 }
675
676 if self
677 .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
678 .await?
679 {
680 triggered_rules.push(rule.id.clone());
681 required_actions.extend(rule.actions.clone());
682 }
683 }
684
685 let access_decision = self.determine_access_decision(risk_score, &required_actions);
687
688 let now = Utc::now();
689 Ok(CaepEvaluationResult {
690 subject: subject.to_string(),
691 access_decision,
692 risk_score,
693 triggered_rules,
694 required_actions,
695 evaluated_at: now,
696 next_evaluation: now + self.config.evaluation_interval,
697 })
698 }
699
700 pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
702 loop {
703 self.evaluation_interval.tick().await;
704
705 self.synchronize_with_session_manager().await?;
707
708 let sessions = {
710 let sessions_guard = self.sessions.read().await;
711 sessions_guard.keys().cloned().collect::<Vec<_>>()
712 };
713
714 for session_id in sessions {
715 if let Some(session_state) = self.sessions.read().await.get(&session_id) {
716 let evaluation = self.evaluate_access(&session_state.subject, None).await?;
717 self.execute_actions(&evaluation).await?;
718 }
719 }
720 }
721 }
722
723 async fn synchronize_with_session_manager(&self) -> Result<()> {
725 let mut sessions = self.sessions.write().await;
726 let mut sessions_to_remove = Vec::new();
727
728 for (session_id, caep_session) in sessions.iter() {
729 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
731 if !self.session_manager.is_session_valid(session_id) {
732 log::info!(
733 "CAEP removing expired session: {}",
734 crate::utils::redact::fingerprint(session_id)
735 );
736 sessions_to_remove.push(session_id.clone());
737 }
738 else if oidc_session.sub != caep_session.subject {
740 log::warn!(
741 "CAEP session subject mismatch, removing: {}",
742 crate::utils::redact::fingerprint(session_id)
743 );
744 sessions_to_remove.push(session_id.clone());
745 }
746 } else {
747 log::info!(
748 "CAEP removing orphaned session: {}",
749 crate::utils::redact::fingerprint(session_id)
750 );
751 sessions_to_remove.push(session_id.clone());
752 }
753 }
754
755 for session_id in sessions_to_remove {
757 sessions.remove(&session_id);
758 }
759
760 Ok(())
761 }
762
763 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
765 log::info!("CAEP revoking access for subject: {}", subject);
766
767 let sessions_to_logout = {
769 let sessions = self.sessions.read().await;
770 sessions
771 .iter()
772 .filter(|(_, session)| session.subject == subject)
773 .map(|(session_id, session)| (session_id.clone(), session.clone()))
774 .collect::<Vec<_>>()
775 };
776
777 for (session_id, _) in &sessions_to_logout {
779 let logout_request =
781 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
782 session_id: session_id.clone(),
783 sub: subject.to_string(),
784 sid: Some(session_id.clone()),
785 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
788 let mut events = HashMap::new();
789 events.insert(
790 "caep_reason".to_string(),
791 serde_json::json!("automatic_revocation"),
792 );
793 events.insert(
794 "timestamp".to_string(),
795 serde_json::json!(Utc::now().timestamp()),
796 );
797 events
798 }),
799 };
800
801 match self.process_backchannel_logout(&logout_request).await {
804 Ok(_) => {
805 log::info!(
806 "Successfully initiated back-channel logout for session {} (subject: {})",
807 crate::utils::redact::fingerprint(session_id),
808 subject
809 );
810 }
811 Err(e) => {
812 log::error!(
813 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
814 crate::utils::redact::fingerprint(session_id),
815 subject,
816 e
817 );
818 }
819 }
820 }
821
822 let mut sessions = self.sessions.write().await;
824 sessions.retain(|_, session| session.subject != subject);
825
826 Ok(())
827 }
828
829 async fn process_backchannel_logout(
831 &self,
832 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
833 ) -> Result<()> {
834 let logout_metadata = self.logout_manager.get_discovery_metadata();
839 log::info!("Logout manager capabilities: {:?}", logout_metadata);
840
841 let logout_token = self
843 .create_logout_token_for_caep_revocation(logout_request)
844 .await?;
845
846 self.handle_caep_logout(logout_request, &logout_token)
848 .await?;
849
850 log::info!("CAEP backchannel logout processed successfully");
851 Ok(())
852 }
853
854 async fn create_logout_token_for_caep_revocation(
856 &self,
857 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
858 ) -> Result<String> {
859 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
860 use serde_json::json;
861
862 let claims = json!({
864 "iss": logout_request.iss,
865 "sub": logout_request.sub,
866 "aud": ["caep-manager"],
867 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
868 "iat": chrono::Utc::now().timestamp(),
869 "jti": uuid::Uuid::new_v4().to_string(),
870 "sid": logout_request.sid,
871 "events": {
872 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
873 },
874 "caep_reason": logout_request.additional_events
875 .as_ref()
876 .and_then(|events| events.get("caep_reason"))
877 .unwrap_or(&serde_json::json!("automatic_revocation"))
878 });
879
880 let key = EncodingKey::from_secret("caep-secret".as_ref());
882 let header = Header::new(Algorithm::HS256);
883
884 let token = encode(&header, &claims, &key).map_err(|e| {
885 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
886 })?;
887
888 Ok(token)
889 }
890
891 async fn handle_caep_logout(
893 &self,
894 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
895 logout_token: &str,
896 ) -> Result<()> {
897 log::info!(
905 "Processing CAEP logout for session: {}",
906 crate::utils::redact::fingerprint(&logout_request.session_id)
907 );
908
909 {
911 let mut sessions = self.sessions.write().await;
912 if let Some(_session) = sessions.get(&logout_request.session_id) {
913 sessions.remove(&logout_request.session_id);
915 }
916 }
917
918 let caep_event = CaepEvent {
920 id: uuid::Uuid::new_v4(),
921 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
923 session_id: Some(logout_request.session_id.clone()),
924 timestamp: chrono::Utc::now(),
925 severity: CaepEventSeverity::High,
926 source: CaepEventSource {
927 system_id: "caep-manager".to_string(),
928 source_type: "caep_automatic_revocation".to_string(),
929 version: Some("1.0".to_string()),
930 metadata: std::collections::HashMap::new(),
931 },
932 risk_score: 1.0, location: None,
934 device_info: None,
935 event_data: serde_json::json!({
936 "logout_token": logout_token,
937 "initiator": "caep_automatic_revocation",
938 "reason": logout_request.additional_events
939 .as_ref()
940 .and_then(|events| events.get("caep_reason"))
941 .cloned()
942 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
943 }),
944 correlation_id: Some(uuid::Uuid::new_v4()),
945 };
946
947 if let Err(e) = self.event_broadcaster.send(caep_event) {
949 log::warn!("Failed to broadcast CAEP logout event: {}", e);
950 }
951
952 log::info!(
953 "CAEP logout completed for session: {}",
954 crate::utils::redact::fingerprint(&logout_request.session_id)
955 );
956 Ok(())
957 }
958
959 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
961 let history = self.event_history.read().await;
962 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
963
964 let recent_events: Vec<_> = history
965 .iter()
966 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
967 .collect();
968
969 if recent_events.is_empty() {
970 return Ok(0.0);
971 }
972
973 let mut total_risk = 0.0;
975 let mut total_weight = 0.0;
976
977 for event in recent_events {
978 let weight = match event.severity {
979 CaepEventSeverity::Low => 1.0,
980 CaepEventSeverity::Medium => 2.0,
981 CaepEventSeverity::High => 4.0,
982 CaepEventSeverity::Critical => 8.0,
983 };
984
985 total_risk += event.risk_score * weight;
986 total_weight += weight;
987 }
988
989 Ok(if total_weight > 0.0 {
990 (total_risk / total_weight).min(1.0)
991 } else {
992 0.0
993 })
994 }
995
996 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
998 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1000 if !self.session_manager.is_session_valid(session_id) {
1002 log::warn!(
1003 "CAEP received event for expired OIDC session: {}",
1004 crate::utils::redact::fingerprint(session_id)
1005 );
1006 let mut sessions = self.sessions.write().await;
1008 sessions.remove(session_id);
1009 return Ok(());
1010 }
1011
1012 if oidc_session.sub != event.subject {
1014 return Err(AuthError::validation(
1015 "Subject mismatch between CAEP event and OIDC session",
1016 ));
1017 }
1018 } else {
1019 log::warn!(
1020 "CAEP received event for unknown OIDC session: {}",
1021 crate::utils::redact::fingerprint(session_id)
1022 );
1023 return Err(AuthError::validation("Session not found in SessionManager"));
1024 }
1025
1026 let mut sessions = self.sessions.write().await;
1028
1029 let session_state =
1030 sessions
1031 .entry(session_id.to_string())
1032 .or_insert_with(|| CaepSessionState {
1033 session_id: session_id.to_string(),
1034 subject: event.subject.clone(),
1035 risk_score: event.risk_score,
1036 last_evaluation: None,
1037 active_events: Vec::new(),
1038 created_at: Utc::now(),
1039 last_activity: Utc::now(),
1040 is_quarantined: false,
1041 quarantine_until: None,
1042 });
1043
1044 session_state.risk_score = event.risk_score;
1045 session_state.last_activity = Utc::now();
1046 session_state.active_events.push(event.clone());
1047
1048 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1050 session_state
1051 .active_events
1052 .retain(|e| e.timestamp >= cutoff);
1053
1054 Ok(())
1055 }
1056
1057 async fn evaluate_rule_conditions(
1059 &self,
1060 rule: &CaepEvaluationRule,
1061 _subject: &str,
1062 event: Option<&CaepEvent>,
1063 risk_score: f32,
1064 ) -> Result<bool> {
1065 for condition in &rule.conditions {
1066 match condition {
1067 CaepRuleCondition::RiskScoreAbove { threshold } => {
1068 if risk_score <= *threshold {
1069 return Ok(false);
1070 }
1071 }
1072 CaepRuleCondition::SeverityAtLeast { severity } => {
1073 if let Some(event) = event {
1074 let event_severity_level = match event.severity {
1075 CaepEventSeverity::Critical => 4,
1076 CaepEventSeverity::High => 3,
1077 CaepEventSeverity::Medium => 2,
1078 CaepEventSeverity::Low => 1,
1079 };
1080
1081 let required_severity_level = match severity {
1082 CaepEventSeverity::Critical => 4,
1083 CaepEventSeverity::High => 3,
1084 CaepEventSeverity::Medium => 2,
1085 CaepEventSeverity::Low => 1,
1086 };
1087
1088 if event_severity_level < required_severity_level {
1089 return Ok(false);
1090 }
1091 } else {
1092 return Ok(false);
1093 }
1094 }
1095 CaepRuleCondition::LocationChange { suspicious_only } => {
1096 if let Some(event) = event {
1097 if let Some(location) = &event.location {
1098 if *suspicious_only && !location.is_suspicious {
1099 return Ok(false);
1100 }
1101 } else {
1102 return Ok(false);
1103 }
1104 } else {
1105 return Ok(false);
1106 }
1107 }
1108 CaepRuleCondition::UnknownDevice { require_trusted } => {
1109 if let Some(event) = event
1110 && let Some(device) = &event.device_info
1111 && *require_trusted
1112 && device.is_trusted
1113 {
1114 return Ok(false);
1115 }
1116 }
1117 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1118 let hour = Utc::now().hour();
1120 if (9..17).contains(&hour) {
1121 return Ok(false);
1122 }
1123 }
1124 CaepRuleCondition::Custom { expression: _ } => {
1125 }
1128 }
1129 }
1130
1131 Ok(true)
1132 }
1133
1134 fn determine_access_decision(
1136 &self,
1137 risk_score: f32,
1138 actions: &[CaepRuleAction],
1139 ) -> CaepAccessDecision {
1140 for action in actions {
1141 match action {
1142 CaepRuleAction::RevokeAccess { immediate: true } => {
1143 return CaepAccessDecision::Deny;
1144 }
1145 CaepRuleAction::RevokeAccess { immediate: false } => {
1146 return CaepAccessDecision::TemporaryDeny;
1147 }
1148 CaepRuleAction::RequireStepUp { .. } => {
1149 return CaepAccessDecision::AllowWithStepUp;
1150 }
1151 CaepRuleAction::QuarantineSession { .. } => {
1152 return CaepAccessDecision::TemporaryDeny;
1153 }
1154 _ => {}
1155 }
1156 }
1157
1158 if risk_score >= self.config.auto_revoke_threshold {
1159 CaepAccessDecision::Deny
1160 } else if risk_score >= 0.6 {
1161 CaepAccessDecision::AllowWithMonitoring
1162 } else {
1163 CaepAccessDecision::Allow
1164 }
1165 }
1166
1167 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1169 for action in &evaluation.required_actions {
1170 match action {
1171 CaepRuleAction::RevokeAccess { .. } => {
1172 self.revoke_subject_access(&evaluation.subject).await?;
1173 }
1174 CaepRuleAction::RequireStepUp { level } => {
1175 if let Some(_step_up_manager) = &self.step_up_manager {
1176 log::info!(
1178 "CAEP requiring step-up to level {} for subject {}",
1179 level,
1180 evaluation.subject
1181 );
1182 }
1183 }
1184 CaepRuleAction::SendNotification { channels } => {
1185 log::info!(
1186 "CAEP sending notification via channels {:?} for subject {}",
1187 channels,
1188 evaluation.subject
1189 );
1190 }
1191 CaepRuleAction::LogEvent { level } => {
1192 log::info!(
1193 "CAEP logging event at level {} for subject {}",
1194 level,
1195 evaluation.subject
1196 );
1197 }
1198 CaepRuleAction::TriggerWebhook { url } => {
1199 log::info!(
1200 "CAEP triggering webhook {} for subject {}",
1201 crate::utils::redact::url_origin(url),
1202 evaluation.subject
1203 );
1204 }
1205 CaepRuleAction::QuarantineSession { duration_minutes } => {
1206 self.quarantine_session(&evaluation.subject, *duration_minutes)
1207 .await?;
1208 }
1209 }
1210 }
1211
1212 Ok(())
1213 }
1214
1215 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1217 let mut sessions = self.sessions.write().await;
1218 let quarantine_until =
1219 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1220
1221 let mut quarantined_session_ids = Vec::new();
1223 for session in sessions.values_mut() {
1224 if session.subject == subject {
1225 session.is_quarantined = true;
1226 session.quarantine_until = Some(quarantine_until);
1227 quarantined_session_ids.push(session.session_id.clone());
1228 }
1229 }
1230
1231 log::info!(
1232 "CAEP quarantined {} sessions for subject {} until {}",
1233 quarantined_session_ids.len(),
1234 subject,
1235 quarantine_until
1236 );
1237
1238 Ok(())
1242 }
1243
1244 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1246 let handlers = self.event_handlers.read().await;
1247
1248 if let Some(event_handlers) = handlers.get(&event.event_type) {
1249 for handler in event_handlers {
1250 if let Err(e) = handler.handle_event(event).await {
1251 log::error!("CAEP event handler failed: {}", e);
1252 }
1253 }
1254 }
1255
1256 Ok(())
1257 }
1258
1259 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1261 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1263 if !self.session_manager.is_session_valid(session_id) {
1264 let mut sessions = self.sessions.write().await;
1266 sessions.remove(session_id);
1267 return Ok(None);
1268 }
1269
1270 let sessions = self.sessions.read().await;
1272 if let Some(caep_session) = sessions.get(session_id) {
1273 if caep_session.subject == oidc_session.sub {
1274 return Ok(Some(caep_session.clone()));
1275 } else {
1276 log::warn!(
1277 "Subject mismatch between CAEP and OIDC sessions for {}",
1278 crate::utils::redact::fingerprint(session_id)
1279 );
1280 return Ok(None);
1281 }
1282 }
1283 }
1284
1285 Ok(None)
1287 }
1288
1289 pub async fn get_event_history(
1291 &self,
1292 subject: &str,
1293 limit: Option<usize>,
1294 ) -> Result<Vec<CaepEvent>> {
1295 let history = self.event_history.read().await;
1296 let mut events: Vec<_> = history
1297 .iter()
1298 .filter(|e| e.subject == subject)
1299 .cloned()
1300 .collect();
1301
1302 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1303
1304 if let Some(limit) = limit {
1305 events.truncate(limit);
1306 }
1307
1308 Ok(events)
1309 }
1310
1311 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1313 let mut rules = self.rules.write().await;
1314
1315 rules.retain(|r| r.id != rule.id);
1317
1318 rules.push(rule);
1320 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1321
1322 Ok(())
1323 }
1324
1325 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1327 let mut rules = self.rules.write().await;
1328 let original_len = rules.len();
1329 rules.retain(|r| r.id != rule_id);
1330 Ok(rules.len() < original_len)
1331 }
1332
1333 pub async fn get_comprehensive_session_info(
1335 &self,
1336 session_id: &str,
1337 ) -> Result<Option<ComprehensiveSessionInfo>> {
1338 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1340 if !self.session_manager.is_session_valid(session_id) {
1341 return Ok(None);
1342 }
1343
1344 let caep_session = {
1346 let sessions = self.sessions.read().await;
1347 sessions.get(session_id).cloned()
1348 };
1349
1350 let comprehensive_info = ComprehensiveSessionInfo {
1351 oidc_session: oidc_session.clone(),
1352 is_monitored_by_caep: caep_session.is_some(),
1353 caep_session,
1354 };
1355
1356 Ok(Some(comprehensive_info))
1357 } else {
1358 Ok(None)
1359 }
1360 }
1361
1362 pub async fn get_subject_sessions(
1364 &self,
1365 subject: &str,
1366 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1367 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1368 let mut comprehensive_sessions = Vec::new();
1369
1370 for oidc_session in oidc_sessions {
1371 if self
1372 .session_manager
1373 .is_session_valid(&oidc_session.session_id)
1374 {
1375 let caep_session = {
1376 let sessions = self.sessions.read().await;
1377 sessions.get(&oidc_session.session_id).cloned()
1378 };
1379
1380 comprehensive_sessions.push(ComprehensiveSessionInfo {
1381 oidc_session: oidc_session.clone(),
1382 is_monitored_by_caep: caep_session.is_some(),
1383 caep_session,
1384 });
1385 }
1386 }
1387
1388 Ok(comprehensive_sessions)
1389 }
1390}
1391
1392#[cfg(test)]
1393mod tests {
1394 use super::*;
1395 use tokio;
1396
1397 #[tokio::test]
1398 async fn test_caep_event_creation() {
1399 let event = CaepEvent {
1400 id: Uuid::new_v4(),
1401 event_type: CaepEventType::RiskScoreChange,
1402 subject: "user123".to_string(),
1403 severity: CaepEventSeverity::High,
1404 timestamp: Utc::now(),
1405 source: CaepEventSource {
1406 system_id: "risk_engine".to_string(),
1407 source_type: "ml_model".to_string(),
1408 version: Some("1.0.0".to_string()),
1409 metadata: HashMap::new(),
1410 },
1411 risk_score: 0.85,
1412 session_id: Some("session123".to_string()),
1413 location: None,
1414 device_info: None,
1415 event_data: serde_json::json!({
1416 "previous_score": 0.3,
1417 "new_score": 0.85,
1418 "trigger": "suspicious_login_pattern"
1419 }),
1420 correlation_id: None,
1421 };
1422
1423 assert_eq!(event.subject, "user123");
1424 assert_eq!(event.risk_score, 0.85);
1425 assert!(matches!(event.severity, CaepEventSeverity::High));
1426 }
1427
1428 #[tokio::test]
1429 async fn test_caep_config_creation() {
1430 let config = CaepConfig::default();
1431 assert!(!config.event_stream_url.is_empty());
1432 assert!(config.auto_revoke);
1433 assert_eq!(config.auto_revoke_threshold, 0.8);
1434 }
1435
1436 #[tokio::test]
1437 async fn test_severity_comparison() {
1438 let high_level = match CaepEventSeverity::High {
1440 CaepEventSeverity::Critical => 4,
1441 CaepEventSeverity::High => 3,
1442 CaepEventSeverity::Medium => 2,
1443 CaepEventSeverity::Low => 1,
1444 };
1445
1446 let medium_level = match CaepEventSeverity::Medium {
1447 CaepEventSeverity::Critical => 4,
1448 CaepEventSeverity::High => 3,
1449 CaepEventSeverity::Medium => 2,
1450 CaepEventSeverity::Low => 1,
1451 };
1452
1453 assert!(high_level > medium_level);
1454 }
1455}