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(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 pub signing_secret: String,
130}
131
132impl std::fmt::Debug for CaepConfig {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 let mut d = f.debug_struct("CaepConfig");
135 d.field("event_stream_url", &self.event_stream_url);
136 d.field("evaluation_interval", &self.evaluation_interval);
137 d.field("auto_revoke", &self.auto_revoke);
138 d.field("auto_revoke_threshold", &self.auto_revoke_threshold);
139 d.field("max_concurrent_processors", &self.max_concurrent_processors);
140 d.field("event_retention_period", &self.event_retention_period);
141 d.field("propagation_endpoints", &self.propagation_endpoints);
142 d.field("evaluation_rules", &self.evaluation_rules);
143 d.field(
144 "signing_secret",
145 &crate::utils::redact::redacted(&self.signing_secret),
146 );
147 d.finish()
148 }
149}
150
151impl Default for CaepConfig {
152 fn default() -> Self {
153 use ring::rand::{SecureRandom, SystemRandom};
154 let rng = SystemRandom::new();
157 let mut bytes = [0u8; 32];
158 rng.fill(&mut bytes)
159 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
160 let signing_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
161 s.push_str(&format!("{b:02x}"));
162 s
163 });
164
165 Self {
166 event_stream_url: "wss://localhost:8080/caep/events".to_string(),
167 evaluation_interval: Duration::try_seconds(30).unwrap_or(Duration::zero()),
168 auto_revoke: true,
169 auto_revoke_threshold: 0.8,
170 max_concurrent_processors: 10,
171 event_retention_period: Duration::try_hours(24).unwrap_or(Duration::zero()),
172 propagation_endpoints: Vec::new(),
173 evaluation_rules: Vec::new(),
174 signing_secret,
177 }
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum CaepEventType {
185 UserLogin,
187 UserLogout,
188 UserProfileChange,
189 UserCredentialChange,
190
191 SessionCreated,
193 SessionModified,
194 SessionTimeout,
195 SessionSuspiciousActivity,
196
197 RiskScoreChange,
199 LocationChange,
200 DeviceChange,
201 BehavioralAnomaly,
202
203 PolicyUpdate,
205 ComplianceViolation,
206 AccessPatternAnomaly,
207
208 SystemOutage,
210 SecurityIncident,
211 DataBreach,
212
213 Custom(String),
215}
216
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[serde(rename_all = "snake_case")]
220pub enum CaepEventSeverity {
221 Low,
222 Medium,
223 High,
224 Critical,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct CaepEventSource {
230 pub system_id: String,
232
233 pub source_type: String,
235
236 pub version: Option<String>,
238
239 pub metadata: HashMap<String, serde_json::Value>,
241}
242
243#[derive(Clone, Serialize, Deserialize)]
245pub struct CaepEvent {
246 pub id: Uuid,
248
249 pub event_type: CaepEventType,
251
252 pub subject: String,
254
255 pub severity: CaepEventSeverity,
257
258 pub timestamp: DateTime<Utc>,
260
261 pub source: CaepEventSource,
263
264 pub risk_score: f32,
266
267 pub session_id: Option<String>,
269
270 pub location: Option<CaepLocationInfo>,
272
273 pub device_info: Option<CaepDeviceInfo>,
275
276 pub event_data: serde_json::Value,
278
279 pub correlation_id: Option<Uuid>,
281}
282
283impl std::fmt::Debug for CaepEvent {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 let mut d = f.debug_struct("CaepEvent");
286 d.field("id", &self.id);
287 d.field("event_type", &self.event_type);
288 d.field("subject", &self.subject);
289 d.field("severity", &self.severity);
290 d.field("timestamp", &self.timestamp);
291 d.field("source", &self.source);
292 d.field("risk_score", &self.risk_score);
293 d.field(
294 "session_id",
295 &crate::utils::redact::redacted(&self.session_id),
296 );
297 d.field("location", &self.location);
298 d.field("device_info", &self.device_info);
299 d.field("event_data", &self.event_data);
300 d.field("correlation_id", &self.correlation_id);
301 d.finish()
302 }
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct CaepLocationInfo {
308 pub country: Option<String>,
310
311 pub region: Option<String>,
313
314 pub city: Option<String>,
316
317 pub latitude: Option<f64>,
319
320 pub longitude: Option<f64>,
322
323 pub ip_address: Option<String>,
325
326 pub is_suspicious: bool,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct CaepDeviceInfo {
333 pub device_id: Option<String>,
335
336 pub device_type: Option<String>,
338
339 pub os: Option<String>,
341
342 pub client: Option<String>,
344
345 pub is_trusted: bool,
347
348 pub requires_binding: bool,
350}
351
352#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct CaepEvaluationRule {
355 pub id: String,
357
358 pub description: String,
360
361 pub applicable_events: Vec<CaepEventType>,
363
364 pub conditions: Vec<CaepRuleCondition>,
366
367 pub actions: Vec<CaepRuleAction>,
369
370 pub priority: i32,
372
373 pub enabled: bool,
375}
376
377#[derive(Debug, Clone, Serialize, Deserialize)]
379#[serde(tag = "type", rename_all = "snake_case")]
380pub enum CaepRuleCondition {
381 RiskScoreAbove { threshold: f32 },
383
384 SeverityAtLeast { severity: CaepEventSeverity },
386
387 LocationChange { suspicious_only: bool },
389
390 UnknownDevice { require_trusted: bool },
392
393 OutsideBusinessHours { timezone: String },
395
396 Custom { expression: String },
398}
399
400#[derive(Clone, Serialize, Deserialize)]
402#[serde(tag = "type", rename_all = "snake_case")]
403pub enum CaepRuleAction {
404 RevokeAccess { immediate: bool },
406
407 RequireStepUp { level: String },
409
410 SendNotification { channels: Vec<String> },
412
413 LogEvent { level: String },
415
416 TriggerWebhook { url: String },
418
419 QuarantineSession { duration_minutes: u32 },
421}
422
423impl std::fmt::Debug for CaepRuleAction {
424 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
425 match self {
426 Self::RevokeAccess { immediate } => f
427 .debug_struct("RevokeAccess")
428 .field("immediate", immediate)
429 .finish(),
430 Self::RequireStepUp { level } => f
431 .debug_struct("RequireStepUp")
432 .field("level", level)
433 .finish(),
434 Self::SendNotification { channels } => f
435 .debug_struct("SendNotification")
436 .field("channels", channels)
437 .finish(),
438 Self::LogEvent { level } => f.debug_struct("LogEvent").field("level", level).finish(),
439 Self::TriggerWebhook { url } => f
441 .debug_struct("TriggerWebhook")
442 .field("url", &crate::utils::redact::redacted(url))
443 .finish(),
444 Self::QuarantineSession { duration_minutes } => f
445 .debug_struct("QuarantineSession")
446 .field("duration_minutes", duration_minutes)
447 .finish(),
448 }
449 }
450}
451
452#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct CaepEvaluationResult {
455 pub subject: String,
457
458 pub access_decision: CaepAccessDecision,
460
461 pub risk_score: f32,
463
464 pub triggered_rules: Vec<String>,
466
467 pub required_actions: Vec<CaepRuleAction>,
469
470 pub evaluated_at: DateTime<Utc>,
472
473 pub next_evaluation: DateTime<Utc>,
475}
476
477#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
479#[serde(rename_all = "snake_case")]
480pub enum CaepAccessDecision {
481 Allow,
483
484 AllowWithMonitoring,
486
487 AllowWithStepUp,
489
490 TemporaryDeny,
492
493 Deny,
495}
496
497#[derive(Clone, Serialize, Deserialize)]
499pub struct CaepSessionState {
500 pub session_id: String,
502
503 pub subject: String,
505
506 pub risk_score: f32,
508
509 pub last_evaluation: Option<CaepEvaluationResult>,
511
512 pub active_events: Vec<CaepEvent>,
514
515 pub created_at: DateTime<Utc>,
517
518 pub last_activity: DateTime<Utc>,
520
521 pub is_quarantined: bool,
523
524 pub quarantine_until: Option<DateTime<Utc>>,
526}
527
528impl std::fmt::Debug for CaepSessionState {
529 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530 let mut d = f.debug_struct("CaepSessionState");
531 d.field(
532 "session_id",
533 &crate::utils::redact::redacted(&self.session_id),
534 );
535 d.field("subject", &self.subject);
536 d.field("risk_score", &self.risk_score);
537 d.field("last_evaluation", &self.last_evaluation);
538 d.field("active_events", &self.active_events);
539 d.field("created_at", &self.created_at);
540 d.field("last_activity", &self.last_activity);
541 d.field("is_quarantined", &self.is_quarantined);
542 d.field("quarantine_until", &self.quarantine_until);
543 d.finish()
544 }
545}
546
547#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct ComprehensiveSessionInfo {
550 pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
552
553 pub caep_session: Option<CaepSessionState>,
555
556 pub is_monitored_by_caep: bool,
558}
559
560#[async_trait]
562pub trait CaepEventHandler: Send + Sync {
563 async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
565
566 fn supported_event_types(&self) -> Vec<CaepEventType>;
568}
569
570pub struct CaepManager {
572 config: CaepConfig,
574
575 session_manager: Arc<SessionManager>,
577
578 logout_manager: Arc<BackChannelLogoutManager>,
580
581 step_up_manager: Option<Arc<SteppedUpAuthManager>>,
583
584 sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
586
587 event_handlers: EventHandlerMap,
589
590 event_broadcaster: broadcast::Sender<CaepEvent>,
592
593 evaluation_interval: Interval,
595
596 event_history: Arc<RwLock<Vec<CaepEvent>>>,
598
599 rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
601}
602
603impl CaepManager {
604 pub async fn new(
606 config: CaepConfig,
607 session_manager: Arc<SessionManager>,
608 logout_manager: Arc<BackChannelLogoutManager>,
609 ) -> Result<Self> {
610 let (event_broadcaster, _) = broadcast::channel(1000);
611 let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
612 AuthError::Configuration {
613 message: format!("Invalid evaluation interval: {}", e),
614 help: Some("Provide a valid duration for evaluation interval".to_string()),
615 docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
616 source: None,
617 suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
618 }
619 })?);
620
621 Ok(Self {
622 config: config.clone(),
623 session_manager,
624 logout_manager,
625 step_up_manager: None,
626 sessions: Arc::new(RwLock::new(HashMap::new())),
627 event_handlers: Arc::new(RwLock::new(HashMap::new())),
628 event_broadcaster,
629 evaluation_interval,
630 event_history: Arc::new(RwLock::new(Vec::new())),
631 rules: Arc::new(RwLock::new(config.evaluation_rules)),
632 })
633 }
634
635 pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
637 self.step_up_manager = Some(step_up_manager);
638 self
639 }
640
641 pub async fn register_event_handler(
643 &self,
644 event_type: CaepEventType,
645 handler: Arc<dyn CaepEventHandler>,
646 ) -> Result<()> {
647 let mut handlers = self.event_handlers.write().await;
648 handlers.entry(event_type).or_default().push(handler);
649 Ok(())
650 }
651
652 pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
654 {
656 let mut history = self.event_history.write().await;
657 history.push(event.clone());
658
659 let retention_cutoff = Utc::now() - self.config.event_retention_period;
661 history.retain(|e| e.timestamp >= retention_cutoff);
662 }
663
664 if let Err(e) = self.event_broadcaster.send(event.clone()) {
666 tracing::warn!("Failed to broadcast CAEP event: {}", e);
667 }
668
669 if let Some(session_id) = &event.session_id {
671 self.update_session_state(session_id, &event).await?;
672 }
673
674 let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
676
677 self.execute_actions(&evaluation_result).await?;
679
680 self.notify_handlers(&event).await?;
682
683 Ok(evaluation_result)
684 }
685
686 pub async fn evaluate_access(
688 &self,
689 subject: &str,
690 triggering_event: Option<&CaepEvent>,
691 ) -> Result<CaepEvaluationResult> {
692 let rules = self.rules.read().await;
693 let mut triggered_rules = Vec::new();
694 let mut required_actions = Vec::new();
695 let risk_score = if let Some(event) = triggering_event {
696 event.risk_score
697 } else {
698 self.calculate_risk_score(subject).await?
700 };
701
702 for rule in rules.iter() {
704 if !rule.enabled {
705 continue;
706 }
707
708 if let Some(event) = triggering_event
709 && !rule.applicable_events.contains(&event.event_type)
710 {
711 continue;
712 }
713
714 if self
715 .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
716 .await?
717 {
718 triggered_rules.push(rule.id.clone());
719 required_actions.extend(rule.actions.clone());
720 }
721 }
722
723 let access_decision = self.determine_access_decision(risk_score, &required_actions);
725
726 let now = Utc::now();
727 Ok(CaepEvaluationResult {
728 subject: subject.to_string(),
729 access_decision,
730 risk_score,
731 triggered_rules,
732 required_actions,
733 evaluated_at: now,
734 next_evaluation: now + self.config.evaluation_interval,
735 })
736 }
737
738 pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
740 loop {
741 self.evaluation_interval.tick().await;
742
743 self.synchronize_with_session_manager().await?;
745
746 let sessions = {
748 let sessions_guard = self.sessions.read().await;
749 sessions_guard.keys().cloned().collect::<Vec<_>>()
750 };
751
752 for session_id in sessions {
753 if let Some(session_state) = self.sessions.read().await.get(&session_id) {
754 let evaluation = self.evaluate_access(&session_state.subject, None).await?;
755 self.execute_actions(&evaluation).await?;
756 }
757 }
758 }
759 }
760
761 async fn synchronize_with_session_manager(&self) -> Result<()> {
763 let mut sessions = self.sessions.write().await;
764 let mut sessions_to_remove = Vec::new();
765
766 for (session_id, caep_session) in sessions.iter() {
767 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
769 if !self.session_manager.is_session_valid(session_id) {
770 tracing::info!(
771 "CAEP removing expired session: {}",
772 crate::utils::redact::fingerprint(session_id)
773 );
774 sessions_to_remove.push(session_id.clone());
775 }
776 else if oidc_session.sub != caep_session.subject {
778 tracing::warn!(
779 "CAEP session subject mismatch, removing: {}",
780 crate::utils::redact::fingerprint(session_id)
781 );
782 sessions_to_remove.push(session_id.clone());
783 }
784 } else {
785 tracing::info!(
786 "CAEP removing orphaned session: {}",
787 crate::utils::redact::fingerprint(session_id)
788 );
789 sessions_to_remove.push(session_id.clone());
790 }
791 }
792
793 for session_id in sessions_to_remove {
795 sessions.remove(&session_id);
796 }
797
798 Ok(())
799 }
800
801 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
803 tracing::info!("CAEP revoking access for subject: {}", subject);
804
805 let sessions_to_logout = {
807 let sessions = self.sessions.read().await;
808 sessions
809 .iter()
810 .filter(|(_, session)| session.subject == subject)
811 .map(|(session_id, session)| (session_id.clone(), session.clone()))
812 .collect::<Vec<_>>()
813 };
814
815 for (session_id, _) in &sessions_to_logout {
817 let logout_request =
819 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
820 session_id: session_id.clone(),
821 sub: subject.to_string(),
822 sid: Some(session_id.clone()),
823 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
826 let mut events = HashMap::new();
827 events.insert(
828 "caep_reason".to_string(),
829 serde_json::json!("automatic_revocation"),
830 );
831 events.insert(
832 "timestamp".to_string(),
833 serde_json::json!(Utc::now().timestamp()),
834 );
835 events
836 }),
837 };
838
839 match self.process_backchannel_logout(&logout_request).await {
842 Ok(_) => {
843 tracing::info!(
844 "Successfully initiated back-channel logout for session {} (subject: {})",
845 crate::utils::redact::fingerprint(session_id),
846 subject
847 );
848 }
849 Err(e) => {
850 tracing::error!(
851 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
852 crate::utils::redact::fingerprint(session_id),
853 subject,
854 e
855 );
856 }
857 }
858 }
859
860 let mut sessions = self.sessions.write().await;
862 sessions.retain(|_, session| session.subject != subject);
863
864 Ok(())
865 }
866
867 async fn process_backchannel_logout(
869 &self,
870 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
871 ) -> Result<()> {
872 let logout_metadata = self.logout_manager.get_discovery_metadata();
877 tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
878
879 let logout_token = self
881 .create_logout_token_for_caep_revocation(logout_request)
882 .await?;
883
884 self.handle_caep_logout(logout_request, &logout_token)
886 .await?;
887
888 tracing::info!("CAEP backchannel logout processed successfully");
889 Ok(())
890 }
891
892 async fn create_logout_token_for_caep_revocation(
894 &self,
895 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
896 ) -> Result<String> {
897 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
898 use serde_json::json;
899
900 let claims = json!({
902 "iss": logout_request.iss,
903 "sub": logout_request.sub,
904 "aud": ["caep-manager"],
905 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
906 "iat": chrono::Utc::now().timestamp(),
907 "jti": uuid::Uuid::new_v4().to_string(),
908 "sid": logout_request.sid,
909 "events": {
910 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
911 },
912 "caep_reason": logout_request.additional_events
913 .as_ref()
914 .and_then(|events| events.get("caep_reason"))
915 .unwrap_or(&serde_json::json!("automatic_revocation"))
916 });
917
918 let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
920 let header = Header::new(Algorithm::HS256);
921
922 let token = encode(&header, &claims, &key).map_err(|e| {
923 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
924 })?;
925
926 Ok(token)
927 }
928
929 async fn handle_caep_logout(
931 &self,
932 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
933 logout_token: &str,
934 ) -> Result<()> {
935 tracing::info!(
943 "Processing CAEP logout for session: {}",
944 crate::utils::redact::fingerprint(&logout_request.session_id)
945 );
946
947 {
949 let mut sessions = self.sessions.write().await;
950 if let Some(_session) = sessions.get(&logout_request.session_id) {
951 sessions.remove(&logout_request.session_id);
953 }
954 }
955
956 let caep_event = CaepEvent {
958 id: uuid::Uuid::new_v4(),
959 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
961 session_id: Some(logout_request.session_id.clone()),
962 timestamp: chrono::Utc::now(),
963 severity: CaepEventSeverity::High,
964 source: CaepEventSource {
965 system_id: "caep-manager".to_string(),
966 source_type: "caep_automatic_revocation".to_string(),
967 version: Some("1.0".to_string()),
968 metadata: std::collections::HashMap::new(),
969 },
970 risk_score: 1.0, location: None,
972 device_info: None,
973 event_data: serde_json::json!({
974 "logout_token": logout_token,
975 "initiator": "caep_automatic_revocation",
976 "reason": logout_request.additional_events
977 .as_ref()
978 .and_then(|events| events.get("caep_reason"))
979 .cloned()
980 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
981 }),
982 correlation_id: Some(uuid::Uuid::new_v4()),
983 };
984
985 if let Err(e) = self.event_broadcaster.send(caep_event) {
987 tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
988 }
989
990 tracing::info!(
991 "CAEP logout completed for session: {}",
992 crate::utils::redact::fingerprint(&logout_request.session_id)
993 );
994 Ok(())
995 }
996
997 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
999 let history = self.event_history.read().await;
1000 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1001
1002 let recent_events: Vec<_> = history
1003 .iter()
1004 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
1005 .collect();
1006
1007 if recent_events.is_empty() {
1008 return Ok(0.0);
1009 }
1010
1011 let mut total_risk = 0.0;
1013 let mut total_weight = 0.0;
1014
1015 for event in recent_events {
1016 let weight = match event.severity {
1017 CaepEventSeverity::Low => 1.0,
1018 CaepEventSeverity::Medium => 2.0,
1019 CaepEventSeverity::High => 4.0,
1020 CaepEventSeverity::Critical => 8.0,
1021 };
1022
1023 total_risk += event.risk_score * weight;
1024 total_weight += weight;
1025 }
1026
1027 Ok(if total_weight > 0.0 {
1028 (total_risk / total_weight).min(1.0)
1029 } else {
1030 0.0
1031 })
1032 }
1033
1034 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1036 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1038 if !self.session_manager.is_session_valid(session_id) {
1040 tracing::warn!(
1041 "CAEP received event for expired OIDC session: {}",
1042 crate::utils::redact::fingerprint(session_id)
1043 );
1044 let mut sessions = self.sessions.write().await;
1046 sessions.remove(session_id);
1047 return Ok(());
1048 }
1049
1050 if oidc_session.sub != event.subject {
1052 return Err(AuthError::validation(
1053 "Subject mismatch between CAEP event and OIDC session",
1054 ));
1055 }
1056 } else {
1057 tracing::warn!(
1058 "CAEP received event for unknown OIDC session: {}",
1059 crate::utils::redact::fingerprint(session_id)
1060 );
1061 return Err(AuthError::validation("Session not found in SessionManager"));
1062 }
1063
1064 let mut sessions = self.sessions.write().await;
1066
1067 let session_state =
1068 sessions
1069 .entry(session_id.to_string())
1070 .or_insert_with(|| CaepSessionState {
1071 session_id: session_id.to_string(),
1072 subject: event.subject.clone(),
1073 risk_score: event.risk_score,
1074 last_evaluation: None,
1075 active_events: Vec::new(),
1076 created_at: Utc::now(),
1077 last_activity: Utc::now(),
1078 is_quarantined: false,
1079 quarantine_until: None,
1080 });
1081
1082 session_state.risk_score = event.risk_score;
1083 session_state.last_activity = Utc::now();
1084 session_state.active_events.push(event.clone());
1085
1086 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1088 session_state
1089 .active_events
1090 .retain(|e| e.timestamp >= cutoff);
1091
1092 Ok(())
1093 }
1094
1095 async fn evaluate_rule_conditions(
1097 &self,
1098 rule: &CaepEvaluationRule,
1099 _subject: &str,
1100 event: Option<&CaepEvent>,
1101 risk_score: f32,
1102 ) -> Result<bool> {
1103 for condition in &rule.conditions {
1104 match condition {
1105 CaepRuleCondition::RiskScoreAbove { threshold } => {
1106 if risk_score <= *threshold {
1107 return Ok(false);
1108 }
1109 }
1110 CaepRuleCondition::SeverityAtLeast { severity } => {
1111 if let Some(event) = event {
1112 let event_severity_level = match event.severity {
1113 CaepEventSeverity::Critical => 4,
1114 CaepEventSeverity::High => 3,
1115 CaepEventSeverity::Medium => 2,
1116 CaepEventSeverity::Low => 1,
1117 };
1118
1119 let required_severity_level = match severity {
1120 CaepEventSeverity::Critical => 4,
1121 CaepEventSeverity::High => 3,
1122 CaepEventSeverity::Medium => 2,
1123 CaepEventSeverity::Low => 1,
1124 };
1125
1126 if event_severity_level < required_severity_level {
1127 return Ok(false);
1128 }
1129 } else {
1130 return Ok(false);
1131 }
1132 }
1133 CaepRuleCondition::LocationChange { suspicious_only } => {
1134 if let Some(event) = event {
1135 if let Some(location) = &event.location {
1136 if *suspicious_only && !location.is_suspicious {
1137 return Ok(false);
1138 }
1139 } else {
1140 return Ok(false);
1141 }
1142 } else {
1143 return Ok(false);
1144 }
1145 }
1146 CaepRuleCondition::UnknownDevice { require_trusted } => {
1147 if let Some(event) = event
1148 && let Some(device) = &event.device_info
1149 && *require_trusted
1150 && device.is_trusted
1151 {
1152 return Ok(false);
1153 }
1154 }
1155 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1156 let hour = Utc::now().hour();
1158 if (9..17).contains(&hour) {
1159 return Ok(false);
1160 }
1161 }
1162 CaepRuleCondition::Custom { expression } => {
1163 if !Self::evaluate_simple_expression(expression) {
1165 return Ok(false);
1166 }
1167 }
1168 }
1169 }
1170
1171 Ok(true)
1172 }
1173
1174 fn evaluate_simple_expression(expression: &str) -> bool {
1177 let parts: Vec<&str> = expression.split_whitespace().collect();
1178 if parts.len() != 3 {
1179 tracing::warn!(
1180 expression = expression,
1181 "Unrecognized custom CAEP expression format, defaulting to false"
1182 );
1183 return false;
1184 }
1185
1186 let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1187 let Ok(threshold) = value_str.parse::<f64>() else {
1188 tracing::warn!(
1189 expression = expression,
1190 "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1191 );
1192 return false;
1193 };
1194
1195 tracing::debug!(
1198 expression = expression,
1199 threshold = threshold,
1200 op = op,
1201 "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1202 );
1203 false
1204 }
1205
1206 fn determine_access_decision(
1208 &self,
1209 risk_score: f32,
1210 actions: &[CaepRuleAction],
1211 ) -> CaepAccessDecision {
1212 for action in actions {
1213 match action {
1214 CaepRuleAction::RevokeAccess { immediate: true } => {
1215 return CaepAccessDecision::Deny;
1216 }
1217 CaepRuleAction::RevokeAccess { immediate: false } => {
1218 return CaepAccessDecision::TemporaryDeny;
1219 }
1220 CaepRuleAction::RequireStepUp { .. } => {
1221 return CaepAccessDecision::AllowWithStepUp;
1222 }
1223 CaepRuleAction::QuarantineSession { .. } => {
1224 return CaepAccessDecision::TemporaryDeny;
1225 }
1226 _ => {}
1227 }
1228 }
1229
1230 if risk_score >= self.config.auto_revoke_threshold {
1231 CaepAccessDecision::Deny
1232 } else if risk_score >= 0.6 {
1233 CaepAccessDecision::AllowWithMonitoring
1234 } else {
1235 CaepAccessDecision::Allow
1236 }
1237 }
1238
1239 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1241 for action in &evaluation.required_actions {
1242 match action {
1243 CaepRuleAction::RevokeAccess { .. } => {
1244 self.revoke_subject_access(&evaluation.subject).await?;
1245 }
1246 CaepRuleAction::RequireStepUp { level } => {
1247 if let Some(_step_up_manager) = &self.step_up_manager {
1248 tracing::info!(
1250 "CAEP requiring step-up to level {} for subject {}",
1251 level,
1252 evaluation.subject
1253 );
1254 }
1255 }
1256 CaepRuleAction::SendNotification { channels } => {
1257 tracing::info!(
1258 "CAEP sending notification via channels {:?} for subject {}",
1259 channels,
1260 evaluation.subject
1261 );
1262 }
1263 CaepRuleAction::LogEvent { level } => {
1264 tracing::info!(
1265 "CAEP logging event at level {} for subject {}",
1266 level,
1267 evaluation.subject
1268 );
1269 }
1270 CaepRuleAction::TriggerWebhook { url } => {
1271 tracing::info!(
1272 "CAEP triggering webhook {} for subject {}",
1273 crate::utils::redact::url_origin(url),
1274 evaluation.subject
1275 );
1276 }
1277 CaepRuleAction::QuarantineSession { duration_minutes } => {
1278 self.quarantine_session(&evaluation.subject, *duration_minutes)
1279 .await?;
1280 }
1281 }
1282 }
1283
1284 Ok(())
1285 }
1286
1287 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1289 let mut sessions = self.sessions.write().await;
1290 let quarantine_until =
1291 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1292
1293 let mut quarantined_session_ids = Vec::new();
1295 for session in sessions.values_mut() {
1296 if session.subject == subject {
1297 session.is_quarantined = true;
1298 session.quarantine_until = Some(quarantine_until);
1299 quarantined_session_ids.push(session.session_id.clone());
1300 }
1301 }
1302
1303 tracing::info!(
1304 "CAEP quarantined {} sessions for subject {} until {}",
1305 quarantined_session_ids.len(),
1306 subject,
1307 quarantine_until
1308 );
1309
1310 Ok(())
1314 }
1315
1316 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1318 let handlers = self.event_handlers.read().await;
1319
1320 if let Some(event_handlers) = handlers.get(&event.event_type) {
1321 for handler in event_handlers {
1322 if let Err(e) = handler.handle_event(event).await {
1323 tracing::error!("CAEP event handler failed: {}", e);
1324 }
1325 }
1326 }
1327
1328 Ok(())
1329 }
1330
1331 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1333 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1335 if !self.session_manager.is_session_valid(session_id) {
1336 let mut sessions = self.sessions.write().await;
1338 sessions.remove(session_id);
1339 return Ok(None);
1340 }
1341
1342 let sessions = self.sessions.read().await;
1344 if let Some(caep_session) = sessions.get(session_id) {
1345 if caep_session.subject == oidc_session.sub {
1346 return Ok(Some(caep_session.clone()));
1347 } else {
1348 tracing::warn!(
1349 "Subject mismatch between CAEP and OIDC sessions for {}",
1350 crate::utils::redact::fingerprint(session_id)
1351 );
1352 return Ok(None);
1353 }
1354 }
1355 }
1356
1357 Ok(None)
1359 }
1360
1361 pub async fn get_event_history(
1363 &self,
1364 subject: &str,
1365 limit: Option<usize>,
1366 ) -> Result<Vec<CaepEvent>> {
1367 let history = self.event_history.read().await;
1368 let mut events: Vec<_> = history
1369 .iter()
1370 .filter(|e| e.subject == subject)
1371 .cloned()
1372 .collect();
1373
1374 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1375
1376 if let Some(limit) = limit {
1377 events.truncate(limit);
1378 }
1379
1380 Ok(events)
1381 }
1382
1383 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1385 let mut rules = self.rules.write().await;
1386
1387 rules.retain(|r| r.id != rule.id);
1389
1390 rules.push(rule);
1392 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1393
1394 Ok(())
1395 }
1396
1397 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1399 let mut rules = self.rules.write().await;
1400 let original_len = rules.len();
1401 rules.retain(|r| r.id != rule_id);
1402 Ok(rules.len() < original_len)
1403 }
1404
1405 pub async fn get_comprehensive_session_info(
1407 &self,
1408 session_id: &str,
1409 ) -> Result<Option<ComprehensiveSessionInfo>> {
1410 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1412 if !self.session_manager.is_session_valid(session_id) {
1413 return Ok(None);
1414 }
1415
1416 let caep_session = {
1418 let sessions = self.sessions.read().await;
1419 sessions.get(session_id).cloned()
1420 };
1421
1422 let comprehensive_info = ComprehensiveSessionInfo {
1423 oidc_session: oidc_session.clone(),
1424 is_monitored_by_caep: caep_session.is_some(),
1425 caep_session,
1426 };
1427
1428 Ok(Some(comprehensive_info))
1429 } else {
1430 Ok(None)
1431 }
1432 }
1433
1434 pub async fn get_subject_sessions(
1436 &self,
1437 subject: &str,
1438 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1439 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1440 let mut comprehensive_sessions = Vec::new();
1441
1442 for oidc_session in oidc_sessions {
1443 if self
1444 .session_manager
1445 .is_session_valid(&oidc_session.session_id)
1446 {
1447 let caep_session = {
1448 let sessions = self.sessions.read().await;
1449 sessions.get(&oidc_session.session_id).cloned()
1450 };
1451
1452 comprehensive_sessions.push(ComprehensiveSessionInfo {
1453 oidc_session: oidc_session.clone(),
1454 is_monitored_by_caep: caep_session.is_some(),
1455 caep_session,
1456 });
1457 }
1458 }
1459
1460 Ok(comprehensive_sessions)
1461 }
1462}
1463
1464#[cfg(test)]
1465mod tests {
1466 use super::*;
1467 use tokio;
1468
1469 #[tokio::test]
1470 async fn test_caep_event_creation() {
1471 let event = CaepEvent {
1472 id: Uuid::new_v4(),
1473 event_type: CaepEventType::RiskScoreChange,
1474 subject: "user123".to_string(),
1475 severity: CaepEventSeverity::High,
1476 timestamp: Utc::now(),
1477 source: CaepEventSource {
1478 system_id: "risk_engine".to_string(),
1479 source_type: "ml_model".to_string(),
1480 version: Some("1.0.0".to_string()),
1481 metadata: HashMap::new(),
1482 },
1483 risk_score: 0.85,
1484 session_id: Some("session123".to_string()),
1485 location: None,
1486 device_info: None,
1487 event_data: serde_json::json!({
1488 "previous_score": 0.3,
1489 "new_score": 0.85,
1490 "trigger": "suspicious_login_pattern"
1491 }),
1492 correlation_id: None,
1493 };
1494
1495 assert_eq!(event.subject, "user123");
1496 assert_eq!(event.risk_score, 0.85);
1497 assert!(matches!(event.severity, CaepEventSeverity::High));
1498 }
1499
1500 #[tokio::test]
1501 async fn test_caep_config_creation() {
1502 let config = CaepConfig::default();
1503 assert!(!config.event_stream_url.is_empty());
1504 assert!(config.auto_revoke);
1505 assert_eq!(config.auto_revoke_threshold, 0.8);
1506 }
1507
1508 #[tokio::test]
1509 async fn test_severity_comparison() {
1510 let high_level = match CaepEventSeverity::High {
1512 CaepEventSeverity::Critical => 4,
1513 CaepEventSeverity::High => 3,
1514 CaepEventSeverity::Medium => 2,
1515 CaepEventSeverity::Low => 1,
1516 };
1517
1518 let medium_level = match CaepEventSeverity::Medium {
1519 CaepEventSeverity::Critical => 4,
1520 CaepEventSeverity::High => 3,
1521 CaepEventSeverity::Medium => 2,
1522 CaepEventSeverity::Low => 1,
1523 };
1524
1525 assert!(high_level > medium_level);
1526 }
1527}