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(Debug, 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
405#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct CaepEvaluationResult {
408 pub subject: String,
410
411 pub access_decision: CaepAccessDecision,
413
414 pub risk_score: f32,
416
417 pub triggered_rules: Vec<String>,
419
420 pub required_actions: Vec<CaepRuleAction>,
422
423 pub evaluated_at: DateTime<Utc>,
425
426 pub next_evaluation: DateTime<Utc>,
428}
429
430#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
432#[serde(rename_all = "snake_case")]
433pub enum CaepAccessDecision {
434 Allow,
436
437 AllowWithMonitoring,
439
440 AllowWithStepUp,
442
443 TemporaryDeny,
445
446 Deny,
448}
449
450#[derive(Clone, Serialize, Deserialize)]
452pub struct CaepSessionState {
453 pub session_id: String,
455
456 pub subject: String,
458
459 pub risk_score: f32,
461
462 pub last_evaluation: Option<CaepEvaluationResult>,
464
465 pub active_events: Vec<CaepEvent>,
467
468 pub created_at: DateTime<Utc>,
470
471 pub last_activity: DateTime<Utc>,
473
474 pub is_quarantined: bool,
476
477 pub quarantine_until: Option<DateTime<Utc>>,
479}
480
481impl std::fmt::Debug for CaepSessionState {
482 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
483 let mut d = f.debug_struct("CaepSessionState");
484 d.field(
485 "session_id",
486 &crate::utils::redact::redacted(&self.session_id),
487 );
488 d.field("subject", &self.subject);
489 d.field("risk_score", &self.risk_score);
490 d.field("last_evaluation", &self.last_evaluation);
491 d.field("active_events", &self.active_events);
492 d.field("created_at", &self.created_at);
493 d.field("last_activity", &self.last_activity);
494 d.field("is_quarantined", &self.is_quarantined);
495 d.field("quarantine_until", &self.quarantine_until);
496 d.finish()
497 }
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct ComprehensiveSessionInfo {
503 pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
505
506 pub caep_session: Option<CaepSessionState>,
508
509 pub is_monitored_by_caep: bool,
511}
512
513#[async_trait]
515pub trait CaepEventHandler: Send + Sync {
516 async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
518
519 fn supported_event_types(&self) -> Vec<CaepEventType>;
521}
522
523pub struct CaepManager {
525 config: CaepConfig,
527
528 session_manager: Arc<SessionManager>,
530
531 logout_manager: Arc<BackChannelLogoutManager>,
533
534 step_up_manager: Option<Arc<SteppedUpAuthManager>>,
536
537 sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
539
540 event_handlers: EventHandlerMap,
542
543 event_broadcaster: broadcast::Sender<CaepEvent>,
545
546 evaluation_interval: Interval,
548
549 event_history: Arc<RwLock<Vec<CaepEvent>>>,
551
552 rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
554}
555
556impl CaepManager {
557 pub async fn new(
559 config: CaepConfig,
560 session_manager: Arc<SessionManager>,
561 logout_manager: Arc<BackChannelLogoutManager>,
562 ) -> Result<Self> {
563 let (event_broadcaster, _) = broadcast::channel(1000);
564 let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
565 AuthError::Configuration {
566 message: format!("Invalid evaluation interval: {}", e),
567 help: Some("Provide a valid duration for evaluation interval".to_string()),
568 docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
569 source: None,
570 suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
571 }
572 })?);
573
574 Ok(Self {
575 config: config.clone(),
576 session_manager,
577 logout_manager,
578 step_up_manager: None,
579 sessions: Arc::new(RwLock::new(HashMap::new())),
580 event_handlers: Arc::new(RwLock::new(HashMap::new())),
581 event_broadcaster,
582 evaluation_interval,
583 event_history: Arc::new(RwLock::new(Vec::new())),
584 rules: Arc::new(RwLock::new(config.evaluation_rules)),
585 })
586 }
587
588 pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
590 self.step_up_manager = Some(step_up_manager);
591 self
592 }
593
594 pub async fn register_event_handler(
596 &self,
597 event_type: CaepEventType,
598 handler: Arc<dyn CaepEventHandler>,
599 ) -> Result<()> {
600 let mut handlers = self.event_handlers.write().await;
601 handlers.entry(event_type).or_default().push(handler);
602 Ok(())
603 }
604
605 pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
607 {
609 let mut history = self.event_history.write().await;
610 history.push(event.clone());
611
612 let retention_cutoff = Utc::now() - self.config.event_retention_period;
614 history.retain(|e| e.timestamp >= retention_cutoff);
615 }
616
617 if let Err(e) = self.event_broadcaster.send(event.clone()) {
619 tracing::warn!("Failed to broadcast CAEP event: {}", e);
620 }
621
622 if let Some(session_id) = &event.session_id {
624 self.update_session_state(session_id, &event).await?;
625 }
626
627 let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
629
630 self.execute_actions(&evaluation_result).await?;
632
633 self.notify_handlers(&event).await?;
635
636 Ok(evaluation_result)
637 }
638
639 pub async fn evaluate_access(
641 &self,
642 subject: &str,
643 triggering_event: Option<&CaepEvent>,
644 ) -> Result<CaepEvaluationResult> {
645 let rules = self.rules.read().await;
646 let mut triggered_rules = Vec::new();
647 let mut required_actions = Vec::new();
648 let risk_score = if let Some(event) = triggering_event {
649 event.risk_score
650 } else {
651 self.calculate_risk_score(subject).await?
653 };
654
655 for rule in rules.iter() {
657 if !rule.enabled {
658 continue;
659 }
660
661 if let Some(event) = triggering_event
662 && !rule.applicable_events.contains(&event.event_type)
663 {
664 continue;
665 }
666
667 if self
668 .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
669 .await?
670 {
671 triggered_rules.push(rule.id.clone());
672 required_actions.extend(rule.actions.clone());
673 }
674 }
675
676 let access_decision = self.determine_access_decision(risk_score, &required_actions);
678
679 let now = Utc::now();
680 Ok(CaepEvaluationResult {
681 subject: subject.to_string(),
682 access_decision,
683 risk_score,
684 triggered_rules,
685 required_actions,
686 evaluated_at: now,
687 next_evaluation: now + self.config.evaluation_interval,
688 })
689 }
690
691 pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
693 loop {
694 self.evaluation_interval.tick().await;
695
696 self.synchronize_with_session_manager().await?;
698
699 let sessions = {
701 let sessions_guard = self.sessions.read().await;
702 sessions_guard.keys().cloned().collect::<Vec<_>>()
703 };
704
705 for session_id in sessions {
706 if let Some(session_state) = self.sessions.read().await.get(&session_id) {
707 let evaluation = self.evaluate_access(&session_state.subject, None).await?;
708 self.execute_actions(&evaluation).await?;
709 }
710 }
711 }
712 }
713
714 async fn synchronize_with_session_manager(&self) -> Result<()> {
716 let mut sessions = self.sessions.write().await;
717 let mut sessions_to_remove = Vec::new();
718
719 for (session_id, caep_session) in sessions.iter() {
720 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
722 if !self.session_manager.is_session_valid(session_id) {
723 tracing::info!("CAEP removing expired session: {}", session_id);
724 sessions_to_remove.push(session_id.clone());
725 }
726 else if oidc_session.sub != caep_session.subject {
728 tracing::warn!("CAEP session subject mismatch, removing: {}", session_id);
729 sessions_to_remove.push(session_id.clone());
730 }
731 } else {
732 tracing::info!("CAEP removing orphaned session: {}", session_id);
733 sessions_to_remove.push(session_id.clone());
734 }
735 }
736
737 for session_id in sessions_to_remove {
739 sessions.remove(&session_id);
740 }
741
742 Ok(())
743 }
744
745 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
747 tracing::info!("CAEP revoking access for subject: {}", subject);
748
749 let sessions_to_logout = {
751 let sessions = self.sessions.read().await;
752 sessions
753 .iter()
754 .filter(|(_, session)| session.subject == subject)
755 .map(|(session_id, session)| (session_id.clone(), session.clone()))
756 .collect::<Vec<_>>()
757 };
758
759 for (session_id, _) in &sessions_to_logout {
761 let logout_request =
763 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
764 session_id: session_id.clone(),
765 sub: subject.to_string(),
766 sid: Some(session_id.clone()),
767 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
770 let mut events = HashMap::new();
771 events.insert(
772 "caep_reason".to_string(),
773 serde_json::json!("automatic_revocation"),
774 );
775 events.insert(
776 "timestamp".to_string(),
777 serde_json::json!(Utc::now().timestamp()),
778 );
779 events
780 }),
781 };
782
783 match self.process_backchannel_logout(&logout_request).await {
786 Ok(_) => {
787 tracing::info!(
788 "Successfully initiated back-channel logout for session {} (subject: {})",
789 session_id,
790 subject
791 );
792 }
793 Err(e) => {
794 tracing::error!(
795 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
796 session_id,
797 subject,
798 e
799 );
800 }
801 }
802 }
803
804 let mut sessions = self.sessions.write().await;
806 sessions.retain(|_, session| session.subject != subject);
807
808 Ok(())
809 }
810
811 async fn process_backchannel_logout(
813 &self,
814 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
815 ) -> Result<()> {
816 let logout_metadata = self.logout_manager.get_discovery_metadata();
821 tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
822
823 let logout_token = self
825 .create_logout_token_for_caep_revocation(logout_request)
826 .await?;
827
828 self.handle_caep_logout(logout_request, &logout_token)
830 .await?;
831
832 tracing::info!("CAEP backchannel logout processed successfully");
833 Ok(())
834 }
835
836 async fn create_logout_token_for_caep_revocation(
838 &self,
839 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
840 ) -> Result<String> {
841 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
842 use serde_json::json;
843
844 let claims = json!({
846 "iss": logout_request.iss,
847 "sub": logout_request.sub,
848 "aud": ["caep-manager"],
849 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
850 "iat": chrono::Utc::now().timestamp(),
851 "jti": uuid::Uuid::new_v4().to_string(),
852 "sid": logout_request.sid,
853 "events": {
854 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
855 },
856 "caep_reason": logout_request.additional_events
857 .as_ref()
858 .and_then(|events| events.get("caep_reason"))
859 .unwrap_or(&serde_json::json!("automatic_revocation"))
860 });
861
862 let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
864 let header = Header::new(Algorithm::HS256);
865
866 let token = encode(&header, &claims, &key).map_err(|e| {
867 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
868 })?;
869
870 Ok(token)
871 }
872
873 async fn handle_caep_logout(
875 &self,
876 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
877 logout_token: &str,
878 ) -> Result<()> {
879 tracing::info!(
887 "Processing CAEP logout for session: {}",
888 logout_request.session_id
889 );
890
891 {
893 let mut sessions = self.sessions.write().await;
894 if let Some(_session) = sessions.get(&logout_request.session_id) {
895 sessions.remove(&logout_request.session_id);
897 }
898 }
899
900 let caep_event = CaepEvent {
902 id: uuid::Uuid::new_v4(),
903 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
905 session_id: Some(logout_request.session_id.clone()),
906 timestamp: chrono::Utc::now(),
907 severity: CaepEventSeverity::High,
908 source: CaepEventSource {
909 system_id: "caep-manager".to_string(),
910 source_type: "caep_automatic_revocation".to_string(),
911 version: Some("1.0".to_string()),
912 metadata: std::collections::HashMap::new(),
913 },
914 risk_score: 1.0, location: None,
916 device_info: None,
917 event_data: serde_json::json!({
918 "logout_token": logout_token,
919 "initiator": "caep_automatic_revocation",
920 "reason": logout_request.additional_events
921 .as_ref()
922 .and_then(|events| events.get("caep_reason"))
923 .cloned()
924 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
925 }),
926 correlation_id: Some(uuid::Uuid::new_v4()),
927 };
928
929 if let Err(e) = self.event_broadcaster.send(caep_event) {
931 tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
932 }
933
934 tracing::info!(
935 "CAEP logout completed for session: {}",
936 logout_request.session_id
937 );
938 Ok(())
939 }
940
941 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
943 let history = self.event_history.read().await;
944 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
945
946 let recent_events: Vec<_> = history
947 .iter()
948 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
949 .collect();
950
951 if recent_events.is_empty() {
952 return Ok(0.0);
953 }
954
955 let mut total_risk = 0.0;
957 let mut total_weight = 0.0;
958
959 for event in recent_events {
960 let weight = match event.severity {
961 CaepEventSeverity::Low => 1.0,
962 CaepEventSeverity::Medium => 2.0,
963 CaepEventSeverity::High => 4.0,
964 CaepEventSeverity::Critical => 8.0,
965 };
966
967 total_risk += event.risk_score * weight;
968 total_weight += weight;
969 }
970
971 Ok(if total_weight > 0.0 {
972 (total_risk / total_weight).min(1.0)
973 } else {
974 0.0
975 })
976 }
977
978 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
980 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
982 if !self.session_manager.is_session_valid(session_id) {
984 tracing::warn!(
985 "CAEP received event for expired OIDC session: {}",
986 session_id
987 );
988 let mut sessions = self.sessions.write().await;
990 sessions.remove(session_id);
991 return Ok(());
992 }
993
994 if oidc_session.sub != event.subject {
996 return Err(AuthError::validation(
997 "Subject mismatch between CAEP event and OIDC session",
998 ));
999 }
1000 } else {
1001 tracing::warn!(
1002 "CAEP received event for unknown OIDC session: {}",
1003 session_id
1004 );
1005 return Err(AuthError::validation("Session not found in SessionManager"));
1006 }
1007
1008 let mut sessions = self.sessions.write().await;
1010
1011 let session_state =
1012 sessions
1013 .entry(session_id.to_string())
1014 .or_insert_with(|| CaepSessionState {
1015 session_id: session_id.to_string(),
1016 subject: event.subject.clone(),
1017 risk_score: event.risk_score,
1018 last_evaluation: None,
1019 active_events: Vec::new(),
1020 created_at: Utc::now(),
1021 last_activity: Utc::now(),
1022 is_quarantined: false,
1023 quarantine_until: None,
1024 });
1025
1026 session_state.risk_score = event.risk_score;
1027 session_state.last_activity = Utc::now();
1028 session_state.active_events.push(event.clone());
1029
1030 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1032 session_state
1033 .active_events
1034 .retain(|e| e.timestamp >= cutoff);
1035
1036 Ok(())
1037 }
1038
1039 async fn evaluate_rule_conditions(
1041 &self,
1042 rule: &CaepEvaluationRule,
1043 _subject: &str,
1044 event: Option<&CaepEvent>,
1045 risk_score: f32,
1046 ) -> Result<bool> {
1047 for condition in &rule.conditions {
1048 match condition {
1049 CaepRuleCondition::RiskScoreAbove { threshold } => {
1050 if risk_score <= *threshold {
1051 return Ok(false);
1052 }
1053 }
1054 CaepRuleCondition::SeverityAtLeast { severity } => {
1055 if let Some(event) = event {
1056 let event_severity_level = match event.severity {
1057 CaepEventSeverity::Critical => 4,
1058 CaepEventSeverity::High => 3,
1059 CaepEventSeverity::Medium => 2,
1060 CaepEventSeverity::Low => 1,
1061 };
1062
1063 let required_severity_level = match severity {
1064 CaepEventSeverity::Critical => 4,
1065 CaepEventSeverity::High => 3,
1066 CaepEventSeverity::Medium => 2,
1067 CaepEventSeverity::Low => 1,
1068 };
1069
1070 if event_severity_level < required_severity_level {
1071 return Ok(false);
1072 }
1073 } else {
1074 return Ok(false);
1075 }
1076 }
1077 CaepRuleCondition::LocationChange { suspicious_only } => {
1078 if let Some(event) = event {
1079 if let Some(location) = &event.location {
1080 if *suspicious_only && !location.is_suspicious {
1081 return Ok(false);
1082 }
1083 } else {
1084 return Ok(false);
1085 }
1086 } else {
1087 return Ok(false);
1088 }
1089 }
1090 CaepRuleCondition::UnknownDevice { require_trusted } => {
1091 if let Some(event) = event
1092 && let Some(device) = &event.device_info
1093 && *require_trusted
1094 && device.is_trusted
1095 {
1096 return Ok(false);
1097 }
1098 }
1099 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1100 let hour = Utc::now().hour();
1102 if (9..17).contains(&hour) {
1103 return Ok(false);
1104 }
1105 }
1106 CaepRuleCondition::Custom { expression } => {
1107 if !Self::evaluate_simple_expression(expression) {
1109 return Ok(false);
1110 }
1111 }
1112 }
1113 }
1114
1115 Ok(true)
1116 }
1117
1118 fn evaluate_simple_expression(expression: &str) -> bool {
1121 let parts: Vec<&str> = expression.split_whitespace().collect();
1122 if parts.len() != 3 {
1123 tracing::warn!(
1124 expression = expression,
1125 "Unrecognized custom CAEP expression format, defaulting to false"
1126 );
1127 return false;
1128 }
1129
1130 let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1131 let Ok(threshold) = value_str.parse::<f64>() else {
1132 tracing::warn!(
1133 expression = expression,
1134 "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1135 );
1136 return false;
1137 };
1138
1139 tracing::debug!(
1142 expression = expression,
1143 threshold = threshold,
1144 op = op,
1145 "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1146 );
1147 false
1148 }
1149
1150 fn determine_access_decision(
1152 &self,
1153 risk_score: f32,
1154 actions: &[CaepRuleAction],
1155 ) -> CaepAccessDecision {
1156 for action in actions {
1157 match action {
1158 CaepRuleAction::RevokeAccess { immediate: true } => {
1159 return CaepAccessDecision::Deny;
1160 }
1161 CaepRuleAction::RevokeAccess { immediate: false } => {
1162 return CaepAccessDecision::TemporaryDeny;
1163 }
1164 CaepRuleAction::RequireStepUp { .. } => {
1165 return CaepAccessDecision::AllowWithStepUp;
1166 }
1167 CaepRuleAction::QuarantineSession { .. } => {
1168 return CaepAccessDecision::TemporaryDeny;
1169 }
1170 _ => {}
1171 }
1172 }
1173
1174 if risk_score >= self.config.auto_revoke_threshold {
1175 CaepAccessDecision::Deny
1176 } else if risk_score >= 0.6 {
1177 CaepAccessDecision::AllowWithMonitoring
1178 } else {
1179 CaepAccessDecision::Allow
1180 }
1181 }
1182
1183 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1185 for action in &evaluation.required_actions {
1186 match action {
1187 CaepRuleAction::RevokeAccess { .. } => {
1188 self.revoke_subject_access(&evaluation.subject).await?;
1189 }
1190 CaepRuleAction::RequireStepUp { level } => {
1191 if let Some(_step_up_manager) = &self.step_up_manager {
1192 tracing::info!(
1194 "CAEP requiring step-up to level {} for subject {}",
1195 level,
1196 evaluation.subject
1197 );
1198 }
1199 }
1200 CaepRuleAction::SendNotification { channels } => {
1201 tracing::info!(
1202 "CAEP sending notification via channels {:?} for subject {}",
1203 channels,
1204 evaluation.subject
1205 );
1206 }
1207 CaepRuleAction::LogEvent { level } => {
1208 tracing::info!(
1209 "CAEP logging event at level {} for subject {}",
1210 level,
1211 evaluation.subject
1212 );
1213 }
1214 CaepRuleAction::TriggerWebhook { url } => {
1215 tracing::info!(
1216 "CAEP triggering webhook {} for subject {}",
1217 url,
1218 evaluation.subject
1219 );
1220 }
1221 CaepRuleAction::QuarantineSession { duration_minutes } => {
1222 self.quarantine_session(&evaluation.subject, *duration_minutes)
1223 .await?;
1224 }
1225 }
1226 }
1227
1228 Ok(())
1229 }
1230
1231 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1233 let mut sessions = self.sessions.write().await;
1234 let quarantine_until =
1235 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1236
1237 let mut quarantined_session_ids = Vec::new();
1239 for session in sessions.values_mut() {
1240 if session.subject == subject {
1241 session.is_quarantined = true;
1242 session.quarantine_until = Some(quarantine_until);
1243 quarantined_session_ids.push(session.session_id.clone());
1244 }
1245 }
1246
1247 tracing::info!(
1248 "CAEP quarantined {} sessions for subject {} until {}. Session IDs: {:?}",
1249 quarantined_session_ids.len(),
1250 subject,
1251 quarantine_until,
1252 quarantined_session_ids
1253 );
1254
1255 Ok(())
1259 }
1260
1261 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1263 let handlers = self.event_handlers.read().await;
1264
1265 if let Some(event_handlers) = handlers.get(&event.event_type) {
1266 for handler in event_handlers {
1267 if let Err(e) = handler.handle_event(event).await {
1268 tracing::error!("CAEP event handler failed: {}", e);
1269 }
1270 }
1271 }
1272
1273 Ok(())
1274 }
1275
1276 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1278 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1280 if !self.session_manager.is_session_valid(session_id) {
1281 let mut sessions = self.sessions.write().await;
1283 sessions.remove(session_id);
1284 return Ok(None);
1285 }
1286
1287 let sessions = self.sessions.read().await;
1289 if let Some(caep_session) = sessions.get(session_id) {
1290 if caep_session.subject == oidc_session.sub {
1291 return Ok(Some(caep_session.clone()));
1292 } else {
1293 tracing::warn!(
1294 "Subject mismatch between CAEP and OIDC sessions for {}",
1295 session_id
1296 );
1297 return Ok(None);
1298 }
1299 }
1300 }
1301
1302 Ok(None)
1304 }
1305
1306 pub async fn get_event_history(
1308 &self,
1309 subject: &str,
1310 limit: Option<usize>,
1311 ) -> Result<Vec<CaepEvent>> {
1312 let history = self.event_history.read().await;
1313 let mut events: Vec<_> = history
1314 .iter()
1315 .filter(|e| e.subject == subject)
1316 .cloned()
1317 .collect();
1318
1319 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1320
1321 if let Some(limit) = limit {
1322 events.truncate(limit);
1323 }
1324
1325 Ok(events)
1326 }
1327
1328 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1330 let mut rules = self.rules.write().await;
1331
1332 rules.retain(|r| r.id != rule.id);
1334
1335 rules.push(rule);
1337 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1338
1339 Ok(())
1340 }
1341
1342 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1344 let mut rules = self.rules.write().await;
1345 let original_len = rules.len();
1346 rules.retain(|r| r.id != rule_id);
1347 Ok(rules.len() < original_len)
1348 }
1349
1350 pub async fn get_comprehensive_session_info(
1352 &self,
1353 session_id: &str,
1354 ) -> Result<Option<ComprehensiveSessionInfo>> {
1355 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1357 if !self.session_manager.is_session_valid(session_id) {
1358 return Ok(None);
1359 }
1360
1361 let caep_session = {
1363 let sessions = self.sessions.read().await;
1364 sessions.get(session_id).cloned()
1365 };
1366
1367 let comprehensive_info = ComprehensiveSessionInfo {
1368 oidc_session: oidc_session.clone(),
1369 is_monitored_by_caep: caep_session.is_some(),
1370 caep_session,
1371 };
1372
1373 Ok(Some(comprehensive_info))
1374 } else {
1375 Ok(None)
1376 }
1377 }
1378
1379 pub async fn get_subject_sessions(
1381 &self,
1382 subject: &str,
1383 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1384 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1385 let mut comprehensive_sessions = Vec::new();
1386
1387 for oidc_session in oidc_sessions {
1388 if self
1389 .session_manager
1390 .is_session_valid(&oidc_session.session_id)
1391 {
1392 let caep_session = {
1393 let sessions = self.sessions.read().await;
1394 sessions.get(&oidc_session.session_id).cloned()
1395 };
1396
1397 comprehensive_sessions.push(ComprehensiveSessionInfo {
1398 oidc_session: oidc_session.clone(),
1399 is_monitored_by_caep: caep_session.is_some(),
1400 caep_session,
1401 });
1402 }
1403 }
1404
1405 Ok(comprehensive_sessions)
1406 }
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411 use super::*;
1412 use tokio;
1413
1414 #[tokio::test]
1415 async fn test_caep_event_creation() {
1416 let event = CaepEvent {
1417 id: Uuid::new_v4(),
1418 event_type: CaepEventType::RiskScoreChange,
1419 subject: "user123".to_string(),
1420 severity: CaepEventSeverity::High,
1421 timestamp: Utc::now(),
1422 source: CaepEventSource {
1423 system_id: "risk_engine".to_string(),
1424 source_type: "ml_model".to_string(),
1425 version: Some("1.0.0".to_string()),
1426 metadata: HashMap::new(),
1427 },
1428 risk_score: 0.85,
1429 session_id: Some("session123".to_string()),
1430 location: None,
1431 device_info: None,
1432 event_data: serde_json::json!({
1433 "previous_score": 0.3,
1434 "new_score": 0.85,
1435 "trigger": "suspicious_login_pattern"
1436 }),
1437 correlation_id: None,
1438 };
1439
1440 assert_eq!(event.subject, "user123");
1441 assert_eq!(event.risk_score, 0.85);
1442 assert!(matches!(event.severity, CaepEventSeverity::High));
1443 }
1444
1445 #[tokio::test]
1446 async fn test_caep_config_creation() {
1447 let config = CaepConfig::default();
1448 assert!(!config.event_stream_url.is_empty());
1449 assert!(config.auto_revoke);
1450 assert_eq!(config.auto_revoke_threshold, 0.8);
1451 }
1452
1453 #[tokio::test]
1454 async fn test_severity_comparison() {
1455 let high_level = match CaepEventSeverity::High {
1457 CaepEventSeverity::Critical => 4,
1458 CaepEventSeverity::High => 3,
1459 CaepEventSeverity::Medium => 2,
1460 CaepEventSeverity::Low => 1,
1461 };
1462
1463 let medium_level = match CaepEventSeverity::Medium {
1464 CaepEventSeverity::Critical => 4,
1465 CaepEventSeverity::High => 3,
1466 CaepEventSeverity::Medium => 2,
1467 CaepEventSeverity::Low => 1,
1468 };
1469
1470 assert!(high_level > medium_level);
1471 }
1472}