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!(
753 "CAEP removing expired session: {}",
754 crate::utils::redact::fingerprint(session_id)
755 );
756 sessions_to_remove.push(session_id.clone());
757 }
758 else if oidc_session.sub != caep_session.subject {
760 tracing::warn!(
761 "CAEP session subject mismatch, removing: {}",
762 crate::utils::redact::fingerprint(session_id)
763 );
764 sessions_to_remove.push(session_id.clone());
765 }
766 } else {
767 tracing::info!(
768 "CAEP removing orphaned session: {}",
769 crate::utils::redact::fingerprint(session_id)
770 );
771 sessions_to_remove.push(session_id.clone());
772 }
773 }
774
775 for session_id in sessions_to_remove {
777 sessions.remove(&session_id);
778 }
779
780 Ok(())
781 }
782
783 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
785 tracing::info!("CAEP revoking access for subject: {}", subject);
786
787 let sessions_to_logout = {
789 let sessions = self.sessions.read().await;
790 sessions
791 .iter()
792 .filter(|(_, session)| session.subject == subject)
793 .map(|(session_id, session)| (session_id.clone(), session.clone()))
794 .collect::<Vec<_>>()
795 };
796
797 for (session_id, _) in &sessions_to_logout {
799 let logout_request =
801 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
802 session_id: session_id.clone(),
803 sub: subject.to_string(),
804 sid: Some(session_id.clone()),
805 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
808 let mut events = HashMap::new();
809 events.insert(
810 "caep_reason".to_string(),
811 serde_json::json!("automatic_revocation"),
812 );
813 events.insert(
814 "timestamp".to_string(),
815 serde_json::json!(Utc::now().timestamp()),
816 );
817 events
818 }),
819 };
820
821 match self.process_backchannel_logout(&logout_request).await {
824 Ok(_) => {
825 tracing::info!(
826 "Successfully initiated back-channel logout for session {} (subject: {})",
827 crate::utils::redact::fingerprint(session_id),
828 subject
829 );
830 }
831 Err(e) => {
832 tracing::error!(
833 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
834 crate::utils::redact::fingerprint(session_id),
835 subject,
836 e
837 );
838 }
839 }
840 }
841
842 let mut sessions = self.sessions.write().await;
844 sessions.retain(|_, session| session.subject != subject);
845
846 Ok(())
847 }
848
849 async fn process_backchannel_logout(
851 &self,
852 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
853 ) -> Result<()> {
854 let logout_metadata = self.logout_manager.get_discovery_metadata();
859 tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
860
861 let logout_token = self
863 .create_logout_token_for_caep_revocation(logout_request)
864 .await?;
865
866 self.handle_caep_logout(logout_request, &logout_token)
868 .await?;
869
870 tracing::info!("CAEP backchannel logout processed successfully");
871 Ok(())
872 }
873
874 async fn create_logout_token_for_caep_revocation(
876 &self,
877 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
878 ) -> Result<String> {
879 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
880 use serde_json::json;
881
882 let claims = json!({
884 "iss": logout_request.iss,
885 "sub": logout_request.sub,
886 "aud": ["caep-manager"],
887 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
888 "iat": chrono::Utc::now().timestamp(),
889 "jti": uuid::Uuid::new_v4().to_string(),
890 "sid": logout_request.sid,
891 "events": {
892 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
893 },
894 "caep_reason": logout_request.additional_events
895 .as_ref()
896 .and_then(|events| events.get("caep_reason"))
897 .unwrap_or(&serde_json::json!("automatic_revocation"))
898 });
899
900 let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
902 let header = Header::new(Algorithm::HS256);
903
904 let token = encode(&header, &claims, &key).map_err(|e| {
905 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
906 })?;
907
908 Ok(token)
909 }
910
911 async fn handle_caep_logout(
913 &self,
914 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
915 logout_token: &str,
916 ) -> Result<()> {
917 tracing::info!(
925 "Processing CAEP logout for session: {}",
926 crate::utils::redact::fingerprint(&logout_request.session_id)
927 );
928
929 {
931 let mut sessions = self.sessions.write().await;
932 if let Some(_session) = sessions.get(&logout_request.session_id) {
933 sessions.remove(&logout_request.session_id);
935 }
936 }
937
938 let caep_event = CaepEvent {
940 id: uuid::Uuid::new_v4(),
941 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
943 session_id: Some(logout_request.session_id.clone()),
944 timestamp: chrono::Utc::now(),
945 severity: CaepEventSeverity::High,
946 source: CaepEventSource {
947 system_id: "caep-manager".to_string(),
948 source_type: "caep_automatic_revocation".to_string(),
949 version: Some("1.0".to_string()),
950 metadata: std::collections::HashMap::new(),
951 },
952 risk_score: 1.0, location: None,
954 device_info: None,
955 event_data: serde_json::json!({
956 "logout_token": logout_token,
957 "initiator": "caep_automatic_revocation",
958 "reason": logout_request.additional_events
959 .as_ref()
960 .and_then(|events| events.get("caep_reason"))
961 .cloned()
962 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
963 }),
964 correlation_id: Some(uuid::Uuid::new_v4()),
965 };
966
967 if let Err(e) = self.event_broadcaster.send(caep_event) {
969 tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
970 }
971
972 tracing::info!(
973 "CAEP logout completed for session: {}",
974 crate::utils::redact::fingerprint(&logout_request.session_id)
975 );
976 Ok(())
977 }
978
979 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
981 let history = self.event_history.read().await;
982 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
983
984 let recent_events: Vec<_> = history
985 .iter()
986 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
987 .collect();
988
989 if recent_events.is_empty() {
990 return Ok(0.0);
991 }
992
993 let mut total_risk = 0.0;
995 let mut total_weight = 0.0;
996
997 for event in recent_events {
998 let weight = match event.severity {
999 CaepEventSeverity::Low => 1.0,
1000 CaepEventSeverity::Medium => 2.0,
1001 CaepEventSeverity::High => 4.0,
1002 CaepEventSeverity::Critical => 8.0,
1003 };
1004
1005 total_risk += event.risk_score * weight;
1006 total_weight += weight;
1007 }
1008
1009 Ok(if total_weight > 0.0 {
1010 (total_risk / total_weight).min(1.0)
1011 } else {
1012 0.0
1013 })
1014 }
1015
1016 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1018 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1020 if !self.session_manager.is_session_valid(session_id) {
1022 tracing::warn!(
1023 "CAEP received event for expired OIDC session: {}",
1024 crate::utils::redact::fingerprint(session_id)
1025 );
1026 let mut sessions = self.sessions.write().await;
1028 sessions.remove(session_id);
1029 return Ok(());
1030 }
1031
1032 if oidc_session.sub != event.subject {
1034 return Err(AuthError::validation(
1035 "Subject mismatch between CAEP event and OIDC session",
1036 ));
1037 }
1038 } else {
1039 tracing::warn!(
1040 "CAEP received event for unknown OIDC session: {}",
1041 crate::utils::redact::fingerprint(session_id)
1042 );
1043 return Err(AuthError::validation("Session not found in SessionManager"));
1044 }
1045
1046 let mut sessions = self.sessions.write().await;
1048
1049 let session_state =
1050 sessions
1051 .entry(session_id.to_string())
1052 .or_insert_with(|| CaepSessionState {
1053 session_id: session_id.to_string(),
1054 subject: event.subject.clone(),
1055 risk_score: event.risk_score,
1056 last_evaluation: None,
1057 active_events: Vec::new(),
1058 created_at: Utc::now(),
1059 last_activity: Utc::now(),
1060 is_quarantined: false,
1061 quarantine_until: None,
1062 });
1063
1064 session_state.risk_score = event.risk_score;
1065 session_state.last_activity = Utc::now();
1066 session_state.active_events.push(event.clone());
1067
1068 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1070 session_state
1071 .active_events
1072 .retain(|e| e.timestamp >= cutoff);
1073
1074 Ok(())
1075 }
1076
1077 async fn evaluate_rule_conditions(
1079 &self,
1080 rule: &CaepEvaluationRule,
1081 _subject: &str,
1082 event: Option<&CaepEvent>,
1083 risk_score: f32,
1084 ) -> Result<bool> {
1085 for condition in &rule.conditions {
1086 match condition {
1087 CaepRuleCondition::RiskScoreAbove { threshold } => {
1088 if risk_score <= *threshold {
1089 return Ok(false);
1090 }
1091 }
1092 CaepRuleCondition::SeverityAtLeast { severity } => {
1093 if let Some(event) = event {
1094 let event_severity_level = match event.severity {
1095 CaepEventSeverity::Critical => 4,
1096 CaepEventSeverity::High => 3,
1097 CaepEventSeverity::Medium => 2,
1098 CaepEventSeverity::Low => 1,
1099 };
1100
1101 let required_severity_level = match severity {
1102 CaepEventSeverity::Critical => 4,
1103 CaepEventSeverity::High => 3,
1104 CaepEventSeverity::Medium => 2,
1105 CaepEventSeverity::Low => 1,
1106 };
1107
1108 if event_severity_level < required_severity_level {
1109 return Ok(false);
1110 }
1111 } else {
1112 return Ok(false);
1113 }
1114 }
1115 CaepRuleCondition::LocationChange { suspicious_only } => {
1116 if let Some(event) = event {
1117 if let Some(location) = &event.location {
1118 if *suspicious_only && !location.is_suspicious {
1119 return Ok(false);
1120 }
1121 } else {
1122 return Ok(false);
1123 }
1124 } else {
1125 return Ok(false);
1126 }
1127 }
1128 CaepRuleCondition::UnknownDevice { require_trusted } => {
1129 if let Some(event) = event
1130 && let Some(device) = &event.device_info
1131 && *require_trusted
1132 && device.is_trusted
1133 {
1134 return Ok(false);
1135 }
1136 }
1137 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1138 let hour = Utc::now().hour();
1140 if (9..17).contains(&hour) {
1141 return Ok(false);
1142 }
1143 }
1144 CaepRuleCondition::Custom { expression } => {
1145 if !Self::evaluate_simple_expression(expression) {
1147 return Ok(false);
1148 }
1149 }
1150 }
1151 }
1152
1153 Ok(true)
1154 }
1155
1156 fn evaluate_simple_expression(expression: &str) -> bool {
1159 let parts: Vec<&str> = expression.split_whitespace().collect();
1160 if parts.len() != 3 {
1161 tracing::warn!(
1162 expression = expression,
1163 "Unrecognized custom CAEP expression format, defaulting to false"
1164 );
1165 return false;
1166 }
1167
1168 let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1169 let Ok(threshold) = value_str.parse::<f64>() else {
1170 tracing::warn!(
1171 expression = expression,
1172 "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1173 );
1174 return false;
1175 };
1176
1177 tracing::debug!(
1180 expression = expression,
1181 threshold = threshold,
1182 op = op,
1183 "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1184 );
1185 false
1186 }
1187
1188 fn determine_access_decision(
1190 &self,
1191 risk_score: f32,
1192 actions: &[CaepRuleAction],
1193 ) -> CaepAccessDecision {
1194 for action in actions {
1195 match action {
1196 CaepRuleAction::RevokeAccess { immediate: true } => {
1197 return CaepAccessDecision::Deny;
1198 }
1199 CaepRuleAction::RevokeAccess { immediate: false } => {
1200 return CaepAccessDecision::TemporaryDeny;
1201 }
1202 CaepRuleAction::RequireStepUp { .. } => {
1203 return CaepAccessDecision::AllowWithStepUp;
1204 }
1205 CaepRuleAction::QuarantineSession { .. } => {
1206 return CaepAccessDecision::TemporaryDeny;
1207 }
1208 _ => {}
1209 }
1210 }
1211
1212 if risk_score >= self.config.auto_revoke_threshold {
1213 CaepAccessDecision::Deny
1214 } else if risk_score >= 0.6 {
1215 CaepAccessDecision::AllowWithMonitoring
1216 } else {
1217 CaepAccessDecision::Allow
1218 }
1219 }
1220
1221 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1223 for action in &evaluation.required_actions {
1224 match action {
1225 CaepRuleAction::RevokeAccess { .. } => {
1226 self.revoke_subject_access(&evaluation.subject).await?;
1227 }
1228 CaepRuleAction::RequireStepUp { level } => {
1229 if let Some(_step_up_manager) = &self.step_up_manager {
1230 tracing::info!(
1232 "CAEP requiring step-up to level {} for subject {}",
1233 level,
1234 evaluation.subject
1235 );
1236 }
1237 }
1238 CaepRuleAction::SendNotification { channels } => {
1239 tracing::info!(
1240 "CAEP sending notification via channels {:?} for subject {}",
1241 channels,
1242 evaluation.subject
1243 );
1244 }
1245 CaepRuleAction::LogEvent { level } => {
1246 tracing::info!(
1247 "CAEP logging event at level {} for subject {}",
1248 level,
1249 evaluation.subject
1250 );
1251 }
1252 CaepRuleAction::TriggerWebhook { url } => {
1253 tracing::info!(
1254 "CAEP triggering webhook {} for subject {}",
1255 crate::utils::redact::url_origin(url),
1256 evaluation.subject
1257 );
1258 }
1259 CaepRuleAction::QuarantineSession { duration_minutes } => {
1260 self.quarantine_session(&evaluation.subject, *duration_minutes)
1261 .await?;
1262 }
1263 }
1264 }
1265
1266 Ok(())
1267 }
1268
1269 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1271 let mut sessions = self.sessions.write().await;
1272 let quarantine_until =
1273 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1274
1275 let mut quarantined_session_ids = Vec::new();
1277 for session in sessions.values_mut() {
1278 if session.subject == subject {
1279 session.is_quarantined = true;
1280 session.quarantine_until = Some(quarantine_until);
1281 quarantined_session_ids.push(session.session_id.clone());
1282 }
1283 }
1284
1285 tracing::info!(
1286 "CAEP quarantined {} sessions for subject {} until {}",
1287 quarantined_session_ids.len(),
1288 subject,
1289 quarantine_until
1290 );
1291
1292 Ok(())
1296 }
1297
1298 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1300 let handlers = self.event_handlers.read().await;
1301
1302 if let Some(event_handlers) = handlers.get(&event.event_type) {
1303 for handler in event_handlers {
1304 if let Err(e) = handler.handle_event(event).await {
1305 tracing::error!("CAEP event handler failed: {}", e);
1306 }
1307 }
1308 }
1309
1310 Ok(())
1311 }
1312
1313 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1315 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1317 if !self.session_manager.is_session_valid(session_id) {
1318 let mut sessions = self.sessions.write().await;
1320 sessions.remove(session_id);
1321 return Ok(None);
1322 }
1323
1324 let sessions = self.sessions.read().await;
1326 if let Some(caep_session) = sessions.get(session_id) {
1327 if caep_session.subject == oidc_session.sub {
1328 return Ok(Some(caep_session.clone()));
1329 } else {
1330 tracing::warn!(
1331 "Subject mismatch between CAEP and OIDC sessions for {}",
1332 crate::utils::redact::fingerprint(session_id)
1333 );
1334 return Ok(None);
1335 }
1336 }
1337 }
1338
1339 Ok(None)
1341 }
1342
1343 pub async fn get_event_history(
1345 &self,
1346 subject: &str,
1347 limit: Option<usize>,
1348 ) -> Result<Vec<CaepEvent>> {
1349 let history = self.event_history.read().await;
1350 let mut events: Vec<_> = history
1351 .iter()
1352 .filter(|e| e.subject == subject)
1353 .cloned()
1354 .collect();
1355
1356 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1357
1358 if let Some(limit) = limit {
1359 events.truncate(limit);
1360 }
1361
1362 Ok(events)
1363 }
1364
1365 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1367 let mut rules = self.rules.write().await;
1368
1369 rules.retain(|r| r.id != rule.id);
1371
1372 rules.push(rule);
1374 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1375
1376 Ok(())
1377 }
1378
1379 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1381 let mut rules = self.rules.write().await;
1382 let original_len = rules.len();
1383 rules.retain(|r| r.id != rule_id);
1384 Ok(rules.len() < original_len)
1385 }
1386
1387 pub async fn get_comprehensive_session_info(
1389 &self,
1390 session_id: &str,
1391 ) -> Result<Option<ComprehensiveSessionInfo>> {
1392 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1394 if !self.session_manager.is_session_valid(session_id) {
1395 return Ok(None);
1396 }
1397
1398 let caep_session = {
1400 let sessions = self.sessions.read().await;
1401 sessions.get(session_id).cloned()
1402 };
1403
1404 let comprehensive_info = ComprehensiveSessionInfo {
1405 oidc_session: oidc_session.clone(),
1406 is_monitored_by_caep: caep_session.is_some(),
1407 caep_session,
1408 };
1409
1410 Ok(Some(comprehensive_info))
1411 } else {
1412 Ok(None)
1413 }
1414 }
1415
1416 pub async fn get_subject_sessions(
1418 &self,
1419 subject: &str,
1420 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1421 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1422 let mut comprehensive_sessions = Vec::new();
1423
1424 for oidc_session in oidc_sessions {
1425 if self
1426 .session_manager
1427 .is_session_valid(&oidc_session.session_id)
1428 {
1429 let caep_session = {
1430 let sessions = self.sessions.read().await;
1431 sessions.get(&oidc_session.session_id).cloned()
1432 };
1433
1434 comprehensive_sessions.push(ComprehensiveSessionInfo {
1435 oidc_session: oidc_session.clone(),
1436 is_monitored_by_caep: caep_session.is_some(),
1437 caep_session,
1438 });
1439 }
1440 }
1441
1442 Ok(comprehensive_sessions)
1443 }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448 use super::*;
1449 use tokio;
1450
1451 #[tokio::test]
1452 async fn test_caep_event_creation() {
1453 let event = CaepEvent {
1454 id: Uuid::new_v4(),
1455 event_type: CaepEventType::RiskScoreChange,
1456 subject: "user123".to_string(),
1457 severity: CaepEventSeverity::High,
1458 timestamp: Utc::now(),
1459 source: CaepEventSource {
1460 system_id: "risk_engine".to_string(),
1461 source_type: "ml_model".to_string(),
1462 version: Some("1.0.0".to_string()),
1463 metadata: HashMap::new(),
1464 },
1465 risk_score: 0.85,
1466 session_id: Some("session123".to_string()),
1467 location: None,
1468 device_info: None,
1469 event_data: serde_json::json!({
1470 "previous_score": 0.3,
1471 "new_score": 0.85,
1472 "trigger": "suspicious_login_pattern"
1473 }),
1474 correlation_id: None,
1475 };
1476
1477 assert_eq!(event.subject, "user123");
1478 assert_eq!(event.risk_score, 0.85);
1479 assert!(matches!(event.severity, CaepEventSeverity::High));
1480 }
1481
1482 #[tokio::test]
1483 async fn test_caep_config_creation() {
1484 let config = CaepConfig::default();
1485 assert!(!config.event_stream_url.is_empty());
1486 assert!(config.auto_revoke);
1487 assert_eq!(config.auto_revoke_threshold, 0.8);
1488 }
1489
1490 #[tokio::test]
1491 async fn test_severity_comparison() {
1492 let high_level = match CaepEventSeverity::High {
1494 CaepEventSeverity::Critical => 4,
1495 CaepEventSeverity::High => 3,
1496 CaepEventSeverity::Medium => 2,
1497 CaepEventSeverity::Low => 1,
1498 };
1499
1500 let medium_level = match CaepEventSeverity::Medium {
1501 CaepEventSeverity::Critical => 4,
1502 CaepEventSeverity::High => 3,
1503 CaepEventSeverity::Medium => 2,
1504 CaepEventSeverity::Low => 1,
1505 };
1506
1507 assert!(high_level > medium_level);
1508 }
1509}