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(Debug, 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
265#[derive(Debug, Clone, Serialize, Deserialize)]
267pub struct CaepLocationInfo {
268 pub country: Option<String>,
270
271 pub region: Option<String>,
273
274 pub city: Option<String>,
276
277 pub latitude: Option<f64>,
279
280 pub longitude: Option<f64>,
282
283 pub ip_address: Option<String>,
285
286 pub is_suspicious: bool,
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct CaepDeviceInfo {
293 pub device_id: Option<String>,
295
296 pub device_type: Option<String>,
298
299 pub os: Option<String>,
301
302 pub client: Option<String>,
304
305 pub is_trusted: bool,
307
308 pub requires_binding: bool,
310}
311
312#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct CaepEvaluationRule {
315 pub id: String,
317
318 pub description: String,
320
321 pub applicable_events: Vec<CaepEventType>,
323
324 pub conditions: Vec<CaepRuleCondition>,
326
327 pub actions: Vec<CaepRuleAction>,
329
330 pub priority: i32,
332
333 pub enabled: bool,
335}
336
337#[derive(Debug, Clone, Serialize, Deserialize)]
339#[serde(tag = "type", rename_all = "snake_case")]
340pub enum CaepRuleCondition {
341 RiskScoreAbove { threshold: f32 },
343
344 SeverityAtLeast { severity: CaepEventSeverity },
346
347 LocationChange { suspicious_only: bool },
349
350 UnknownDevice { require_trusted: bool },
352
353 OutsideBusinessHours { timezone: String },
355
356 Custom { expression: String },
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize)]
362#[serde(tag = "type", rename_all = "snake_case")]
363pub enum CaepRuleAction {
364 RevokeAccess { immediate: bool },
366
367 RequireStepUp { level: String },
369
370 SendNotification { channels: Vec<String> },
372
373 LogEvent { level: String },
375
376 TriggerWebhook { url: String },
378
379 QuarantineSession { duration_minutes: u32 },
381}
382
383#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct CaepEvaluationResult {
386 pub subject: String,
388
389 pub access_decision: CaepAccessDecision,
391
392 pub risk_score: f32,
394
395 pub triggered_rules: Vec<String>,
397
398 pub required_actions: Vec<CaepRuleAction>,
400
401 pub evaluated_at: DateTime<Utc>,
403
404 pub next_evaluation: DateTime<Utc>,
406}
407
408#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
410#[serde(rename_all = "snake_case")]
411pub enum CaepAccessDecision {
412 Allow,
414
415 AllowWithMonitoring,
417
418 AllowWithStepUp,
420
421 TemporaryDeny,
423
424 Deny,
426}
427
428#[derive(Debug, Clone, Serialize, Deserialize)]
430pub struct CaepSessionState {
431 pub session_id: String,
433
434 pub subject: String,
436
437 pub risk_score: f32,
439
440 pub last_evaluation: Option<CaepEvaluationResult>,
442
443 pub active_events: Vec<CaepEvent>,
445
446 pub created_at: DateTime<Utc>,
448
449 pub last_activity: DateTime<Utc>,
451
452 pub is_quarantined: bool,
454
455 pub quarantine_until: Option<DateTime<Utc>>,
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize)]
461pub struct ComprehensiveSessionInfo {
462 pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
464
465 pub caep_session: Option<CaepSessionState>,
467
468 pub is_monitored_by_caep: bool,
470}
471
472#[async_trait]
474pub trait CaepEventHandler: Send + Sync {
475 async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
477
478 fn supported_event_types(&self) -> Vec<CaepEventType>;
480}
481
482pub struct CaepManager {
484 config: CaepConfig,
486
487 session_manager: Arc<SessionManager>,
489
490 logout_manager: Arc<BackChannelLogoutManager>,
492
493 step_up_manager: Option<Arc<SteppedUpAuthManager>>,
495
496 sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
498
499 event_handlers: EventHandlerMap,
501
502 event_broadcaster: broadcast::Sender<CaepEvent>,
504
505 evaluation_interval: Interval,
507
508 event_history: Arc<RwLock<Vec<CaepEvent>>>,
510
511 rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
513}
514
515impl CaepManager {
516 pub async fn new(
518 config: CaepConfig,
519 session_manager: Arc<SessionManager>,
520 logout_manager: Arc<BackChannelLogoutManager>,
521 ) -> Result<Self> {
522 let (event_broadcaster, _) = broadcast::channel(1000);
523 let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
524 AuthError::Configuration {
525 message: format!("Invalid evaluation interval: {}", e),
526 help: Some("Provide a valid duration for evaluation interval".to_string()),
527 docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
528 source: None,
529 suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
530 }
531 })?);
532
533 Ok(Self {
534 config: config.clone(),
535 session_manager,
536 logout_manager,
537 step_up_manager: None,
538 sessions: Arc::new(RwLock::new(HashMap::new())),
539 event_handlers: Arc::new(RwLock::new(HashMap::new())),
540 event_broadcaster,
541 evaluation_interval,
542 event_history: Arc::new(RwLock::new(Vec::new())),
543 rules: Arc::new(RwLock::new(config.evaluation_rules)),
544 })
545 }
546
547 pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
549 self.step_up_manager = Some(step_up_manager);
550 self
551 }
552
553 pub async fn register_event_handler(
555 &self,
556 event_type: CaepEventType,
557 handler: Arc<dyn CaepEventHandler>,
558 ) -> Result<()> {
559 let mut handlers = self.event_handlers.write().await;
560 handlers.entry(event_type).or_default().push(handler);
561 Ok(())
562 }
563
564 pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
566 {
568 let mut history = self.event_history.write().await;
569 history.push(event.clone());
570
571 let retention_cutoff = Utc::now() - self.config.event_retention_period;
573 history.retain(|e| e.timestamp >= retention_cutoff);
574 }
575
576 if let Err(e) = self.event_broadcaster.send(event.clone()) {
578 tracing::warn!("Failed to broadcast CAEP event: {}", e);
579 }
580
581 if let Some(session_id) = &event.session_id {
583 self.update_session_state(session_id, &event).await?;
584 }
585
586 let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
588
589 self.execute_actions(&evaluation_result).await?;
591
592 self.notify_handlers(&event).await?;
594
595 Ok(evaluation_result)
596 }
597
598 pub async fn evaluate_access(
600 &self,
601 subject: &str,
602 triggering_event: Option<&CaepEvent>,
603 ) -> Result<CaepEvaluationResult> {
604 let rules = self.rules.read().await;
605 let mut triggered_rules = Vec::new();
606 let mut required_actions = Vec::new();
607 let risk_score = if let Some(event) = triggering_event {
608 event.risk_score
609 } else {
610 self.calculate_risk_score(subject).await?
612 };
613
614 for rule in rules.iter() {
616 if !rule.enabled {
617 continue;
618 }
619
620 if let Some(event) = triggering_event
621 && !rule.applicable_events.contains(&event.event_type)
622 {
623 continue;
624 }
625
626 if self
627 .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
628 .await?
629 {
630 triggered_rules.push(rule.id.clone());
631 required_actions.extend(rule.actions.clone());
632 }
633 }
634
635 let access_decision = self.determine_access_decision(risk_score, &required_actions);
637
638 let now = Utc::now();
639 Ok(CaepEvaluationResult {
640 subject: subject.to_string(),
641 access_decision,
642 risk_score,
643 triggered_rules,
644 required_actions,
645 evaluated_at: now,
646 next_evaluation: now + self.config.evaluation_interval,
647 })
648 }
649
650 pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
652 loop {
653 self.evaluation_interval.tick().await;
654
655 self.synchronize_with_session_manager().await?;
657
658 let sessions = {
660 let sessions_guard = self.sessions.read().await;
661 sessions_guard.keys().cloned().collect::<Vec<_>>()
662 };
663
664 for session_id in sessions {
665 if let Some(session_state) = self.sessions.read().await.get(&session_id) {
666 let evaluation = self.evaluate_access(&session_state.subject, None).await?;
667 self.execute_actions(&evaluation).await?;
668 }
669 }
670 }
671 }
672
673 async fn synchronize_with_session_manager(&self) -> Result<()> {
675 let mut sessions = self.sessions.write().await;
676 let mut sessions_to_remove = Vec::new();
677
678 for (session_id, caep_session) in sessions.iter() {
679 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
681 if !self.session_manager.is_session_valid(session_id) {
682 tracing::info!("CAEP removing expired session: {}", session_id);
683 sessions_to_remove.push(session_id.clone());
684 }
685 else if oidc_session.sub != caep_session.subject {
687 tracing::warn!("CAEP session subject mismatch, removing: {}", session_id);
688 sessions_to_remove.push(session_id.clone());
689 }
690 } else {
691 tracing::info!("CAEP removing orphaned session: {}", session_id);
692 sessions_to_remove.push(session_id.clone());
693 }
694 }
695
696 for session_id in sessions_to_remove {
698 sessions.remove(&session_id);
699 }
700
701 Ok(())
702 }
703
704 pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
706 tracing::info!("CAEP revoking access for subject: {}", subject);
707
708 let sessions_to_logout = {
710 let sessions = self.sessions.read().await;
711 sessions
712 .iter()
713 .filter(|(_, session)| session.subject == subject)
714 .map(|(session_id, session)| (session_id.clone(), session.clone()))
715 .collect::<Vec<_>>()
716 };
717
718 for (session_id, _) in &sessions_to_logout {
720 let logout_request =
722 crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
723 session_id: session_id.clone(),
724 sub: subject.to_string(),
725 sid: Some(session_id.clone()),
726 iss: "caep-manager".to_string(), initiating_client_id: None, additional_events: Some({
729 let mut events = HashMap::new();
730 events.insert(
731 "caep_reason".to_string(),
732 serde_json::json!("automatic_revocation"),
733 );
734 events.insert(
735 "timestamp".to_string(),
736 serde_json::json!(Utc::now().timestamp()),
737 );
738 events
739 }),
740 };
741
742 match self.process_backchannel_logout(&logout_request).await {
745 Ok(_) => {
746 tracing::info!(
747 "Successfully initiated back-channel logout for session {} (subject: {})",
748 session_id,
749 subject
750 );
751 }
752 Err(e) => {
753 tracing::error!(
754 "Failed to initiate back-channel logout for session {} (subject: {}): {}",
755 session_id,
756 subject,
757 e
758 );
759 }
760 }
761 }
762
763 let mut sessions = self.sessions.write().await;
765 sessions.retain(|_, session| session.subject != subject);
766
767 Ok(())
768 }
769
770 async fn process_backchannel_logout(
772 &self,
773 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
774 ) -> Result<()> {
775 let logout_metadata = self.logout_manager.get_discovery_metadata();
780 tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
781
782 let logout_token = self
784 .create_logout_token_for_caep_revocation(logout_request)
785 .await?;
786
787 self.handle_caep_logout(logout_request, &logout_token)
789 .await?;
790
791 tracing::info!("CAEP backchannel logout processed successfully");
792 Ok(())
793 }
794
795 async fn create_logout_token_for_caep_revocation(
797 &self,
798 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
799 ) -> Result<String> {
800 use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
801 use serde_json::json;
802
803 let claims = json!({
805 "iss": logout_request.iss,
806 "sub": logout_request.sub,
807 "aud": ["caep-manager"],
808 "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
809 "iat": chrono::Utc::now().timestamp(),
810 "jti": uuid::Uuid::new_v4().to_string(),
811 "sid": logout_request.sid,
812 "events": {
813 "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
814 },
815 "caep_reason": logout_request.additional_events
816 .as_ref()
817 .and_then(|events| events.get("caep_reason"))
818 .unwrap_or(&serde_json::json!("automatic_revocation"))
819 });
820
821 let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
823 let header = Header::new(Algorithm::HS256);
824
825 let token = encode(&header, &claims, &key).map_err(|e| {
826 AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
827 })?;
828
829 Ok(token)
830 }
831
832 async fn handle_caep_logout(
834 &self,
835 logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
836 logout_token: &str,
837 ) -> Result<()> {
838 tracing::info!(
846 "Processing CAEP logout for session: {}",
847 logout_request.session_id
848 );
849
850 {
852 let mut sessions = self.sessions.write().await;
853 if let Some(_session) = sessions.get(&logout_request.session_id) {
854 sessions.remove(&logout_request.session_id);
856 }
857 }
858
859 let caep_event = CaepEvent {
861 id: uuid::Uuid::new_v4(),
862 event_type: CaepEventType::UserLogout, subject: logout_request.sub.clone(),
864 session_id: Some(logout_request.session_id.clone()),
865 timestamp: chrono::Utc::now(),
866 severity: CaepEventSeverity::High,
867 source: CaepEventSource {
868 system_id: "caep-manager".to_string(),
869 source_type: "caep_automatic_revocation".to_string(),
870 version: Some("1.0".to_string()),
871 metadata: std::collections::HashMap::new(),
872 },
873 risk_score: 1.0, location: None,
875 device_info: None,
876 event_data: serde_json::json!({
877 "logout_token": logout_token,
878 "initiator": "caep_automatic_revocation",
879 "reason": logout_request.additional_events
880 .as_ref()
881 .and_then(|events| events.get("caep_reason"))
882 .cloned()
883 .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
884 }),
885 correlation_id: Some(uuid::Uuid::new_v4()),
886 };
887
888 if let Err(e) = self.event_broadcaster.send(caep_event) {
890 tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
891 }
892
893 tracing::info!(
894 "CAEP logout completed for session: {}",
895 logout_request.session_id
896 );
897 Ok(())
898 }
899
900 async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
902 let history = self.event_history.read().await;
903 let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
904
905 let recent_events: Vec<_> = history
906 .iter()
907 .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
908 .collect();
909
910 if recent_events.is_empty() {
911 return Ok(0.0);
912 }
913
914 let mut total_risk = 0.0;
916 let mut total_weight = 0.0;
917
918 for event in recent_events {
919 let weight = match event.severity {
920 CaepEventSeverity::Low => 1.0,
921 CaepEventSeverity::Medium => 2.0,
922 CaepEventSeverity::High => 4.0,
923 CaepEventSeverity::Critical => 8.0,
924 };
925
926 total_risk += event.risk_score * weight;
927 total_weight += weight;
928 }
929
930 Ok(if total_weight > 0.0 {
931 (total_risk / total_weight).min(1.0)
932 } else {
933 0.0
934 })
935 }
936
937 async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
939 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
941 if !self.session_manager.is_session_valid(session_id) {
943 tracing::warn!(
944 "CAEP received event for expired OIDC session: {}",
945 session_id
946 );
947 let mut sessions = self.sessions.write().await;
949 sessions.remove(session_id);
950 return Ok(());
951 }
952
953 if oidc_session.sub != event.subject {
955 return Err(AuthError::validation(
956 "Subject mismatch between CAEP event and OIDC session",
957 ));
958 }
959 } else {
960 tracing::warn!(
961 "CAEP received event for unknown OIDC session: {}",
962 session_id
963 );
964 return Err(AuthError::validation("Session not found in SessionManager"));
965 }
966
967 let mut sessions = self.sessions.write().await;
969
970 let session_state =
971 sessions
972 .entry(session_id.to_string())
973 .or_insert_with(|| CaepSessionState {
974 session_id: session_id.to_string(),
975 subject: event.subject.clone(),
976 risk_score: event.risk_score,
977 last_evaluation: None,
978 active_events: Vec::new(),
979 created_at: Utc::now(),
980 last_activity: Utc::now(),
981 is_quarantined: false,
982 quarantine_until: None,
983 });
984
985 session_state.risk_score = event.risk_score;
986 session_state.last_activity = Utc::now();
987 session_state.active_events.push(event.clone());
988
989 let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
991 session_state
992 .active_events
993 .retain(|e| e.timestamp >= cutoff);
994
995 Ok(())
996 }
997
998 async fn evaluate_rule_conditions(
1000 &self,
1001 rule: &CaepEvaluationRule,
1002 _subject: &str,
1003 event: Option<&CaepEvent>,
1004 risk_score: f32,
1005 ) -> Result<bool> {
1006 for condition in &rule.conditions {
1007 match condition {
1008 CaepRuleCondition::RiskScoreAbove { threshold } => {
1009 if risk_score <= *threshold {
1010 return Ok(false);
1011 }
1012 }
1013 CaepRuleCondition::SeverityAtLeast { severity } => {
1014 if let Some(event) = event {
1015 let event_severity_level = match event.severity {
1016 CaepEventSeverity::Critical => 4,
1017 CaepEventSeverity::High => 3,
1018 CaepEventSeverity::Medium => 2,
1019 CaepEventSeverity::Low => 1,
1020 };
1021
1022 let required_severity_level = match severity {
1023 CaepEventSeverity::Critical => 4,
1024 CaepEventSeverity::High => 3,
1025 CaepEventSeverity::Medium => 2,
1026 CaepEventSeverity::Low => 1,
1027 };
1028
1029 if event_severity_level < required_severity_level {
1030 return Ok(false);
1031 }
1032 } else {
1033 return Ok(false);
1034 }
1035 }
1036 CaepRuleCondition::LocationChange { suspicious_only } => {
1037 if let Some(event) = event {
1038 if let Some(location) = &event.location {
1039 if *suspicious_only && !location.is_suspicious {
1040 return Ok(false);
1041 }
1042 } else {
1043 return Ok(false);
1044 }
1045 } else {
1046 return Ok(false);
1047 }
1048 }
1049 CaepRuleCondition::UnknownDevice { require_trusted } => {
1050 if let Some(event) = event
1051 && let Some(device) = &event.device_info
1052 && *require_trusted
1053 && device.is_trusted
1054 {
1055 return Ok(false);
1056 }
1057 }
1058 CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1059 let hour = Utc::now().hour();
1061 if (9..17).contains(&hour) {
1062 return Ok(false);
1063 }
1064 }
1065 CaepRuleCondition::Custom { expression } => {
1066 if !Self::evaluate_simple_expression(expression) {
1068 return Ok(false);
1069 }
1070 }
1071 }
1072 }
1073
1074 Ok(true)
1075 }
1076
1077 fn evaluate_simple_expression(expression: &str) -> bool {
1080 let parts: Vec<&str> = expression.split_whitespace().collect();
1081 if parts.len() != 3 {
1082 tracing::warn!(
1083 expression = expression,
1084 "Unrecognized custom CAEP expression format, defaulting to false"
1085 );
1086 return false;
1087 }
1088
1089 let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1090 let Ok(threshold) = value_str.parse::<f64>() else {
1091 tracing::warn!(
1092 expression = expression,
1093 "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1094 );
1095 return false;
1096 };
1097
1098 tracing::debug!(
1101 expression = expression,
1102 threshold = threshold,
1103 op = op,
1104 "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1105 );
1106 false
1107 }
1108
1109 fn determine_access_decision(
1111 &self,
1112 risk_score: f32,
1113 actions: &[CaepRuleAction],
1114 ) -> CaepAccessDecision {
1115 for action in actions {
1116 match action {
1117 CaepRuleAction::RevokeAccess { immediate: true } => {
1118 return CaepAccessDecision::Deny;
1119 }
1120 CaepRuleAction::RevokeAccess { immediate: false } => {
1121 return CaepAccessDecision::TemporaryDeny;
1122 }
1123 CaepRuleAction::RequireStepUp { .. } => {
1124 return CaepAccessDecision::AllowWithStepUp;
1125 }
1126 CaepRuleAction::QuarantineSession { .. } => {
1127 return CaepAccessDecision::TemporaryDeny;
1128 }
1129 _ => {}
1130 }
1131 }
1132
1133 if risk_score >= self.config.auto_revoke_threshold {
1134 CaepAccessDecision::Deny
1135 } else if risk_score >= 0.6 {
1136 CaepAccessDecision::AllowWithMonitoring
1137 } else {
1138 CaepAccessDecision::Allow
1139 }
1140 }
1141
1142 async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1144 for action in &evaluation.required_actions {
1145 match action {
1146 CaepRuleAction::RevokeAccess { .. } => {
1147 self.revoke_subject_access(&evaluation.subject).await?;
1148 }
1149 CaepRuleAction::RequireStepUp { level } => {
1150 if let Some(_step_up_manager) = &self.step_up_manager {
1151 tracing::info!(
1153 "CAEP requiring step-up to level {} for subject {}",
1154 level,
1155 evaluation.subject
1156 );
1157 }
1158 }
1159 CaepRuleAction::SendNotification { channels } => {
1160 tracing::info!(
1161 "CAEP sending notification via channels {:?} for subject {}",
1162 channels,
1163 evaluation.subject
1164 );
1165 }
1166 CaepRuleAction::LogEvent { level } => {
1167 tracing::info!(
1168 "CAEP logging event at level {} for subject {}",
1169 level,
1170 evaluation.subject
1171 );
1172 }
1173 CaepRuleAction::TriggerWebhook { url } => {
1174 tracing::info!(
1175 "CAEP triggering webhook {} for subject {}",
1176 url,
1177 evaluation.subject
1178 );
1179 }
1180 CaepRuleAction::QuarantineSession { duration_minutes } => {
1181 self.quarantine_session(&evaluation.subject, *duration_minutes)
1182 .await?;
1183 }
1184 }
1185 }
1186
1187 Ok(())
1188 }
1189
1190 async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1192 let mut sessions = self.sessions.write().await;
1193 let quarantine_until =
1194 Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1195
1196 let mut quarantined_session_ids = Vec::new();
1198 for session in sessions.values_mut() {
1199 if session.subject == subject {
1200 session.is_quarantined = true;
1201 session.quarantine_until = Some(quarantine_until);
1202 quarantined_session_ids.push(session.session_id.clone());
1203 }
1204 }
1205
1206 tracing::info!(
1207 "CAEP quarantined {} sessions for subject {} until {}. Session IDs: {:?}",
1208 quarantined_session_ids.len(),
1209 subject,
1210 quarantine_until,
1211 quarantined_session_ids
1212 );
1213
1214 Ok(())
1218 }
1219
1220 async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1222 let handlers = self.event_handlers.read().await;
1223
1224 if let Some(event_handlers) = handlers.get(&event.event_type) {
1225 for handler in event_handlers {
1226 if let Err(e) = handler.handle_event(event).await {
1227 tracing::error!("CAEP event handler failed: {}", e);
1228 }
1229 }
1230 }
1231
1232 Ok(())
1233 }
1234
1235 pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1237 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1239 if !self.session_manager.is_session_valid(session_id) {
1240 let mut sessions = self.sessions.write().await;
1242 sessions.remove(session_id);
1243 return Ok(None);
1244 }
1245
1246 let sessions = self.sessions.read().await;
1248 if let Some(caep_session) = sessions.get(session_id) {
1249 if caep_session.subject == oidc_session.sub {
1250 return Ok(Some(caep_session.clone()));
1251 } else {
1252 tracing::warn!(
1253 "Subject mismatch between CAEP and OIDC sessions for {}",
1254 session_id
1255 );
1256 return Ok(None);
1257 }
1258 }
1259 }
1260
1261 Ok(None)
1263 }
1264
1265 pub async fn get_event_history(
1267 &self,
1268 subject: &str,
1269 limit: Option<usize>,
1270 ) -> Result<Vec<CaepEvent>> {
1271 let history = self.event_history.read().await;
1272 let mut events: Vec<_> = history
1273 .iter()
1274 .filter(|e| e.subject == subject)
1275 .cloned()
1276 .collect();
1277
1278 events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1279
1280 if let Some(limit) = limit {
1281 events.truncate(limit);
1282 }
1283
1284 Ok(events)
1285 }
1286
1287 pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1289 let mut rules = self.rules.write().await;
1290
1291 rules.retain(|r| r.id != rule.id);
1293
1294 rules.push(rule);
1296 rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1297
1298 Ok(())
1299 }
1300
1301 pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1303 let mut rules = self.rules.write().await;
1304 let original_len = rules.len();
1305 rules.retain(|r| r.id != rule_id);
1306 Ok(rules.len() < original_len)
1307 }
1308
1309 pub async fn get_comprehensive_session_info(
1311 &self,
1312 session_id: &str,
1313 ) -> Result<Option<ComprehensiveSessionInfo>> {
1314 if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1316 if !self.session_manager.is_session_valid(session_id) {
1317 return Ok(None);
1318 }
1319
1320 let caep_session = {
1322 let sessions = self.sessions.read().await;
1323 sessions.get(session_id).cloned()
1324 };
1325
1326 let comprehensive_info = ComprehensiveSessionInfo {
1327 oidc_session: oidc_session.clone(),
1328 is_monitored_by_caep: caep_session.is_some(),
1329 caep_session,
1330 };
1331
1332 Ok(Some(comprehensive_info))
1333 } else {
1334 Ok(None)
1335 }
1336 }
1337
1338 pub async fn get_subject_sessions(
1340 &self,
1341 subject: &str,
1342 ) -> Result<Vec<ComprehensiveSessionInfo>> {
1343 let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1344 let mut comprehensive_sessions = Vec::new();
1345
1346 for oidc_session in oidc_sessions {
1347 if self
1348 .session_manager
1349 .is_session_valid(&oidc_session.session_id)
1350 {
1351 let caep_session = {
1352 let sessions = self.sessions.read().await;
1353 sessions.get(&oidc_session.session_id).cloned()
1354 };
1355
1356 comprehensive_sessions.push(ComprehensiveSessionInfo {
1357 oidc_session: oidc_session.clone(),
1358 is_monitored_by_caep: caep_session.is_some(),
1359 caep_session,
1360 });
1361 }
1362 }
1363
1364 Ok(comprehensive_sessions)
1365 }
1366}
1367
1368#[cfg(test)]
1369mod tests {
1370 use super::*;
1371 use tokio;
1372
1373 #[tokio::test]
1374 async fn test_caep_event_creation() {
1375 let event = CaepEvent {
1376 id: Uuid::new_v4(),
1377 event_type: CaepEventType::RiskScoreChange,
1378 subject: "user123".to_string(),
1379 severity: CaepEventSeverity::High,
1380 timestamp: Utc::now(),
1381 source: CaepEventSource {
1382 system_id: "risk_engine".to_string(),
1383 source_type: "ml_model".to_string(),
1384 version: Some("1.0.0".to_string()),
1385 metadata: HashMap::new(),
1386 },
1387 risk_score: 0.85,
1388 session_id: Some("session123".to_string()),
1389 location: None,
1390 device_info: None,
1391 event_data: serde_json::json!({
1392 "previous_score": 0.3,
1393 "new_score": 0.85,
1394 "trigger": "suspicious_login_pattern"
1395 }),
1396 correlation_id: None,
1397 };
1398
1399 assert_eq!(event.subject, "user123");
1400 assert_eq!(event.risk_score, 0.85);
1401 assert!(matches!(event.severity, CaepEventSeverity::High));
1402 }
1403
1404 #[tokio::test]
1405 async fn test_caep_config_creation() {
1406 let config = CaepConfig::default();
1407 assert!(!config.event_stream_url.is_empty());
1408 assert!(config.auto_revoke);
1409 assert_eq!(config.auto_revoke_threshold, 0.8);
1410 }
1411
1412 #[tokio::test]
1413 async fn test_severity_comparison() {
1414 let high_level = match CaepEventSeverity::High {
1416 CaepEventSeverity::Critical => 4,
1417 CaepEventSeverity::High => 3,
1418 CaepEventSeverity::Medium => 2,
1419 CaepEventSeverity::Low => 1,
1420 };
1421
1422 let medium_level = match CaepEventSeverity::Medium {
1423 CaepEventSeverity::Critical => 4,
1424 CaepEventSeverity::High => 3,
1425 CaepEventSeverity::Medium => 2,
1426 CaepEventSeverity::Low => 1,
1427 };
1428
1429 assert!(high_level > medium_level);
1430 }
1431}