Skip to main content

auth_framework/server/security/
caep_continuous_access.rs

1//! # Continuous Access Evaluation Protocol (CAEP)
2//!
3//! This module implements the Continuous Access Evaluation Protocol (CAEP), enabling
4//! real-time access evaluation and revocation based on security events and risk changes.
5//!
6//! ## Overview
7//!
8//! CAEP extends traditional OAuth 2.0 and OpenID Connect by providing continuous
9//! monitoring and evaluation of access tokens, allowing for immediate revocation
10//! when security conditions change.
11//!
12//! ## Key Features
13//!
14//! - **Real-time Event Processing**: Continuous monitoring of security events
15//! - **Automatic Access Revocation**: Immediate token revocation on security events
16//! - **Cross-system Event Propagation**: Events can trigger actions across multiple systems
17//! - **Risk-based Evaluation**: Dynamic access decisions based on changing risk profiles
18//! - **Session State Management**: Continuous session validity assessment
19//!
20//! ## Event Types
21//!
22//! - **User Events**: Login/logout, profile changes, credential changes
23//! - **Session Events**: Session creation, modification, timeout, suspicious activity
24//! - **Risk Events**: Location changes, device changes, behavioral anomalies
25//! - **Policy Events**: Access policy updates, compliance violations
26//! - **System Events**: Service outages, security incidents
27//!
28//! ## Usage Example
29//!
30//! ```rust,no_run
31//! use auth_framework::server::security::caep_continuous_access::*;
32//! use auth_framework::server::{SessionManager, BackChannelLogoutManager};
33//! use chrono::Duration;
34//! use std::sync::Arc;
35//! use async_trait::async_trait;
36//!
37//! // Example event handler implementation
38//! struct RiskScoreHandler;
39//!
40//! #[async_trait]
41//! impl CaepEventHandler for RiskScoreHandler {
42//!     async fn handle_event(&self, event: &CaepEvent) -> auth_framework::errors::Result<()> {
43//!         if event.risk_score > 0.8 {
44//!             // High risk - would revoke access in real implementation
45//!             println!("High risk detected: {}", event.risk_score);
46//!         }
47//!         Ok(())
48//!     }
49//!
50//!     fn supported_event_types(&self) -> Vec<CaepEventType> {
51//!         vec![CaepEventType::RiskScoreChange]
52//!     }
53//! }
54//!
55//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
56//! // Initialize CAEP manager (simplified example - in real use, get managers from DI container)
57//! let config = CaepConfig {
58//!     event_stream_url: "wss://events.example.com/caep".to_string(),
59//!     evaluation_interval: Duration::from_std(std::time::Duration::from_secs(30))?,
60//!     auto_revoke: true,
61//!     ..Default::default()
62//! };
63//!
64//! // In real code, create these with proper configuration from your DI container
65//! # let session_config = Default::default();
66//! # let session_manager = Arc::new(SessionManager::new(session_config));
67//! # let logout_config = Default::default();
68//! # let logout_manager = Arc::new(BackChannelLogoutManager::new(logout_config, session_manager.as_ref().clone())?);
69//! # let mut caep_manager = CaepManager::new(config, session_manager, logout_manager).await?;
70//!
71//! // Register event handler
72//! caep_manager.register_event_handler(
73//!     CaepEventType::RiskScoreChange,
74//!     Arc::new(RiskScoreHandler)
75//! ).await?;
76//!
77//! // Start continuous evaluation
78//! caep_manager.start_continuous_evaluation().await?;
79//! # Ok(())
80//! # }
81//! ```
82
83use 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
97/// Type alias for complex event handler storage
98type EventHandlerMap = Arc<RwLock<HashMap<CaepEventType, Vec<Arc<dyn CaepEventHandler>>>>>;
99
100/// Configuration for Continuous Access Evaluation Protocol
101#[derive(Clone, Serialize, Deserialize)]
102pub struct CaepConfig {
103    /// URL for the event stream endpoint
104    pub event_stream_url: String,
105
106    /// How frequently to evaluate access decisions (default: 30 seconds)
107    pub evaluation_interval: Duration,
108
109    /// Whether to automatically revoke access on high-risk events
110    pub auto_revoke: bool,
111
112    /// Minimum risk score threshold for automatic revocation (0.0-1.0)
113    pub auto_revoke_threshold: f32,
114
115    /// Maximum number of concurrent event processors
116    pub max_concurrent_processors: usize,
117
118    /// Event retention period for audit trails
119    pub event_retention_period: Duration,
120
121    /// Cross-system event propagation endpoints
122    pub propagation_endpoints: Vec<String>,
123
124    /// Custom evaluation rules
125    pub evaluation_rules: Vec<CaepEvaluationRule>,
126
127    /// HMAC secret used to sign CAEP logout tokens (HS256).
128    /// **Must be set to a strong, randomly-generated secret in production.**
129    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        // SAFETY: CSPRNG failure at initialization is terminal; the framework
155        // cannot operate without entropy.
156        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            // Randomly generated at startup. Override with a persisted secret in production
175            // so that tokens remain verifiable across restarts.
176            signing_secret,
177        }
178    }
179}
180
181/// Types of CAEP events
182#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum CaepEventType {
185    /// User authentication events
186    UserLogin,
187    UserLogout,
188    UserProfileChange,
189    UserCredentialChange,
190
191    /// Session-related events
192    SessionCreated,
193    SessionModified,
194    SessionTimeout,
195    SessionSuspiciousActivity,
196
197    /// Risk assessment events
198    RiskScoreChange,
199    LocationChange,
200    DeviceChange,
201    BehavioralAnomaly,
202
203    /// Policy and compliance events
204    PolicyUpdate,
205    ComplianceViolation,
206    AccessPatternAnomaly,
207
208    /// System and security events
209    SystemOutage,
210    SecurityIncident,
211    DataBreach,
212
213    /// Custom events for extensibility
214    Custom(String),
215}
216
217/// Severity levels for CAEP events
218#[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/// Source of a CAEP event
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct CaepEventSource {
230    /// Identifier of the source system
231    pub system_id: String,
232
233    /// Type of source (e.g., "identity_provider", "risk_engine", "policy_engine")
234    pub source_type: String,
235
236    /// Version of the source system
237    pub version: Option<String>,
238
239    /// Additional source metadata
240    pub metadata: HashMap<String, serde_json::Value>,
241}
242
243/// A CAEP security event
244#[derive(Clone, Serialize, Deserialize)]
245pub struct CaepEvent {
246    /// Unique event identifier
247    pub id: Uuid,
248
249    /// Type of event
250    pub event_type: CaepEventType,
251
252    /// Subject (user) associated with the event
253    pub subject: String,
254
255    /// Severity level of the event
256    pub severity: CaepEventSeverity,
257
258    /// When the event occurred
259    pub timestamp: DateTime<Utc>,
260
261    /// Source of the event
262    pub source: CaepEventSource,
263
264    /// Current risk score (0.0-1.0)
265    pub risk_score: f32,
266
267    /// Session ID if applicable
268    pub session_id: Option<String>,
269
270    /// Geographic location information
271    pub location: Option<CaepLocationInfo>,
272
273    /// Device information
274    pub device_info: Option<CaepDeviceInfo>,
275
276    /// Event-specific data
277    pub event_data: serde_json::Value,
278
279    /// Correlation ID for related events
280    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/// Geographic location information for CAEP events
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct CaepLocationInfo {
308    /// Country code (ISO 3166-1 alpha-2)
309    pub country: Option<String>,
310
311    /// Region or state
312    pub region: Option<String>,
313
314    /// City name
315    pub city: Option<String>,
316
317    /// Latitude coordinate
318    pub latitude: Option<f64>,
319
320    /// Longitude coordinate
321    pub longitude: Option<f64>,
322
323    /// IP address
324    pub ip_address: Option<String>,
325
326    /// Whether location is considered suspicious
327    pub is_suspicious: bool,
328}
329
330/// Device information for CAEP events
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct CaepDeviceInfo {
333    /// Device identifier
334    pub device_id: Option<String>,
335
336    /// Device type (mobile, desktop, tablet, etc.)
337    pub device_type: Option<String>,
338
339    /// Operating system
340    pub os: Option<String>,
341
342    /// Browser or client application
343    pub client: Option<String>,
344
345    /// Whether device is trusted
346    pub is_trusted: bool,
347
348    /// Whether device binding is required
349    pub requires_binding: bool,
350}
351
352/// Evaluation rule for continuous access decisions
353#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct CaepEvaluationRule {
355    /// Rule identifier
356    pub id: String,
357
358    /// Human-readable description
359    pub description: String,
360
361    /// Event types this rule applies to
362    pub applicable_events: Vec<CaepEventType>,
363
364    /// Conditions that must be met
365    pub conditions: Vec<CaepRuleCondition>,
366
367    /// Actions to take when rule is triggered
368    pub actions: Vec<CaepRuleAction>,
369
370    /// Priority of this rule (higher numbers = higher priority)
371    pub priority: i32,
372
373    /// Whether rule is currently enabled
374    pub enabled: bool,
375}
376
377/// Condition for a CAEP evaluation rule
378#[derive(Debug, Clone, Serialize, Deserialize)]
379#[serde(tag = "type", rename_all = "snake_case")]
380pub enum CaepRuleCondition {
381    /// Risk score threshold condition
382    RiskScoreAbove { threshold: f32 },
383
384    /// Event severity condition
385    SeverityAtLeast { severity: CaepEventSeverity },
386
387    /// Location-based condition
388    LocationChange { suspicious_only: bool },
389
390    /// Device-based condition
391    UnknownDevice { require_trusted: bool },
392
393    /// Time-based condition
394    OutsideBusinessHours { timezone: String },
395
396    /// Custom condition with expression
397    Custom { expression: String },
398}
399
400/// Action to take when a CAEP rule is triggered
401#[derive(Clone, Serialize, Deserialize)]
402#[serde(tag = "type", rename_all = "snake_case")]
403pub enum CaepRuleAction {
404    /// Revoke access tokens for the subject
405    RevokeAccess { immediate: bool },
406
407    /// Require step-up authentication
408    RequireStepUp { level: String },
409
410    /// Send notification
411    SendNotification { channels: Vec<String> },
412
413    /// Log security event
414    LogEvent { level: String },
415
416    /// Trigger external webhook
417    TriggerWebhook { url: String },
418
419    /// Quarantine session
420    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            // A webhook URL can carry a token in its path or query.
440            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/// Result of a continuous access evaluation
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct CaepEvaluationResult {
455    /// Subject being evaluated
456    pub subject: String,
457
458    /// Current access decision
459    pub access_decision: CaepAccessDecision,
460
461    /// Current risk score
462    pub risk_score: f32,
463
464    /// Triggered rules
465    pub triggered_rules: Vec<String>,
466
467    /// Required actions
468    pub required_actions: Vec<CaepRuleAction>,
469
470    /// Evaluation timestamp
471    pub evaluated_at: DateTime<Utc>,
472
473    /// Next evaluation time
474    pub next_evaluation: DateTime<Utc>,
475}
476
477/// Access decision from CAEP evaluation
478#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
479#[serde(rename_all = "snake_case")]
480pub enum CaepAccessDecision {
481    /// Access granted - continue as normal
482    Allow,
483
484    /// Access granted but requires monitoring
485    AllowWithMonitoring,
486
487    /// Access granted but requires step-up authentication
488    AllowWithStepUp,
489
490    /// Access temporarily denied - retry later
491    TemporaryDeny,
492
493    /// Access permanently denied - revoke tokens
494    Deny,
495}
496
497/// State of a CAEP session
498#[derive(Clone, Serialize, Deserialize)]
499pub struct CaepSessionState {
500    /// Session identifier
501    pub session_id: String,
502
503    /// Subject (user) of the session
504    pub subject: String,
505
506    /// Current risk score
507    pub risk_score: f32,
508
509    /// Last evaluation result
510    pub last_evaluation: Option<CaepEvaluationResult>,
511
512    /// Active events for this session
513    pub active_events: Vec<CaepEvent>,
514
515    /// Session creation time
516    pub created_at: DateTime<Utc>,
517
518    /// Last activity time
519    pub last_activity: DateTime<Utc>,
520
521    /// Whether session is quarantined
522    pub is_quarantined: bool,
523
524    /// Quarantine end time if applicable
525    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/// Comprehensive session information combining OIDC and CAEP data
548#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct ComprehensiveSessionInfo {
550    /// OIDC session information
551    pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
552
553    /// CAEP session information if available
554    pub caep_session: Option<CaepSessionState>,
555
556    /// Whether this session is being monitored by CAEP
557    pub is_monitored_by_caep: bool,
558}
559
560/// Event handler trait for CAEP events
561#[async_trait]
562pub trait CaepEventHandler: Send + Sync {
563    /// Handle a CAEP event
564    async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
565
566    /// Get event types this handler can process
567    fn supported_event_types(&self) -> Vec<CaepEventType>;
568}
569
570/// Main CAEP manager for continuous access evaluation
571pub struct CaepManager {
572    /// Configuration
573    config: CaepConfig,
574
575    /// Session manager integration
576    session_manager: Arc<SessionManager>,
577
578    /// Logout manager for revocations
579    logout_manager: Arc<BackChannelLogoutManager>,
580
581    /// Step-up authentication manager
582    step_up_manager: Option<Arc<SteppedUpAuthManager>>,
583
584    /// Active sessions being monitored
585    sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
586
587    /// Event handlers by type
588    event_handlers: EventHandlerMap,
589
590    /// Event stream broadcaster
591    event_broadcaster: broadcast::Sender<CaepEvent>,
592
593    /// Evaluation timer
594    evaluation_interval: Interval,
595
596    /// Event history for audit trails
597    event_history: Arc<RwLock<Vec<CaepEvent>>>,
598
599    /// Evaluation rules
600    rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
601}
602
603impl CaepManager {
604    /// Create a new CAEP manager
605    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    /// Set step-up authentication manager
636    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    /// Register an event handler
642    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    /// Process a CAEP event
653    pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
654        // Add event to history
655        {
656            let mut history = self.event_history.write().await;
657            history.push(event.clone());
658
659            // Cleanup old events
660            let retention_cutoff = Utc::now() - self.config.event_retention_period;
661            history.retain(|e| e.timestamp >= retention_cutoff);
662        }
663
664        // Broadcast event
665        if let Err(e) = self.event_broadcaster.send(event.clone()) {
666            tracing::warn!("Failed to broadcast CAEP event: {}", e);
667        }
668
669        // Update session state
670        if let Some(session_id) = &event.session_id {
671            self.update_session_state(session_id, &event).await?;
672        }
673
674        // Evaluate access decision
675        let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
676
677        // Execute required actions
678        self.execute_actions(&evaluation_result).await?;
679
680        // Notify registered handlers
681        self.notify_handlers(&event).await?;
682
683        Ok(evaluation_result)
684    }
685
686    /// Evaluate continuous access for a subject
687    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            // Calculate risk from recent events
699            self.calculate_risk_score(subject).await?
700        };
701
702        // Apply evaluation rules
703        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        // Determine access decision
724        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    /// Start continuous evaluation loop
739    pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
740        loop {
741            self.evaluation_interval.tick().await;
742
743            // First, synchronize with SessionManager to clean up stale sessions
744            self.synchronize_with_session_manager().await?;
745
746            // Evaluate all active sessions
747            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    /// Synchronize CAEP sessions with SessionManager
762    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            // Check if session still exists and is valid in SessionManager
768            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                // Verify subject consistency
777                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        // Remove stale sessions
794        for session_id in sessions_to_remove {
795            sessions.remove(&session_id);
796        }
797
798        Ok(())
799    }
800
801    /// Revoke access for a subject
802    pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
803        tracing::info!("CAEP revoking access for subject: {}", subject);
804
805        // Find all sessions for this subject and initiate back-channel logout
806        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        // Process back-channel logout for each session
816        for (session_id, _) in &sessions_to_logout {
817            // Use the BackChannelLogoutManager to perform proper logout
818            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(), // In production, use actual issuer
824                    initiating_client_id: None,      // CAEP-initiated logout
825                    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            // Process the logout through the BackChannelLogoutManager
840            // Use async approach to handle logout manager integration
841            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        // Remove from CAEP active sessions after logout processing
861        let mut sessions = self.sessions.write().await;
862        sessions.retain(|_, session| session.subject != subject);
863
864        Ok(())
865    }
866
867    /// Process back-channel logout through the logout manager
868    async fn process_backchannel_logout(
869        &self,
870        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
871    ) -> Result<()> {
872        // Use the logout manager to process the logout request
873        // This integrates CAEP with the existing logout infrastructure
874
875        // Use the logout manager to get metadata and validate capabilities
876        let logout_metadata = self.logout_manager.get_discovery_metadata();
877        tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
878
879        // Create CAEP-specific logout token based on the result
880        let logout_token = self
881            .create_logout_token_for_caep_revocation(logout_request)
882            .await?;
883
884        // Handle CAEP-specific logout processing
885        self.handle_caep_logout(logout_request, &logout_token)
886            .await?;
887
888        tracing::info!("CAEP backchannel logout processed successfully");
889        Ok(())
890    }
891
892    /// Create logout token for CAEP-initiated revocation
893    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        // Create CAEP-specific logout token claims
901        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        // Use the configured signing secret; override CaepConfig::signing_secret in production.
919        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    /// Handle CAEP logout processing
930    async fn handle_caep_logout(
931        &self,
932        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
933        logout_token: &str,
934    ) -> Result<()> {
935        // This method integrates with the logout manager's functionality
936        // In a production system, this would:
937        // 1. Validate the logout token
938        // 2. Notify all relevant clients about the session termination
939        // 3. Update session state in persistent storage
940        // 4. Trigger any cleanup procedures
941
942        tracing::info!(
943            "Processing CAEP logout for session: {}",
944            crate::utils::redact::fingerprint(&logout_request.session_id)
945        );
946
947        // Update CAEP session state to reflect logout
948        {
949            let mut sessions = self.sessions.write().await;
950            if let Some(_session) = sessions.get(&logout_request.session_id) {
951                // Remove the session entirely as it's being terminated
952                sessions.remove(&logout_request.session_id);
953            }
954        }
955
956        // Emit CAEP event for the logout
957        let caep_event = CaepEvent {
958            id: uuid::Uuid::new_v4(),
959            event_type: CaepEventType::UserLogout, // Use existing event type
960            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, // High risk score for revoked sessions
971            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        // Broadcast the event
986        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    /// Calculate risk score for a subject based on recent events
998    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        // Calculate weighted risk score
1012        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    /// Update session state based on an event
1035    async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1036        // First, validate the session exists in the SessionManager
1037        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1038            // Verify the session is still valid
1039            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                // Remove from CAEP sessions as well
1045                let mut sessions = self.sessions.write().await;
1046                sessions.remove(session_id);
1047                return Ok(());
1048            }
1049
1050            // Ensure subjects match
1051            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        // Update CAEP-specific session state
1065        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        // Remove old events
1087        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    /// Evaluate rule conditions
1096    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                    // Simplified: assume business hours are 9 AM - 5 PM UTC
1157                    let hour = Utc::now().hour();
1158                    if (9..17).contains(&hour) {
1159                        return Ok(false);
1160                    }
1161                }
1162                CaepRuleCondition::Custom { expression } => {
1163                    // Basic expression evaluation: support "field op value" comparisons
1164                    if !Self::evaluate_simple_expression(expression) {
1165                        return Ok(false);
1166                    }
1167                }
1168            }
1169        }
1170
1171        Ok(true)
1172    }
1173
1174    /// Evaluate a simple comparison expression like "risk_score > 0.8"
1175    /// Returns false (safe default) for unrecognized or unparseable expressions.
1176    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        // Without runtime context binding, we can only validate the expression
1196        // is syntactically correct. Log and return false (safe default).
1197        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    /// Determine access decision based on risk and actions
1207    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    /// Execute required actions from evaluation
1240    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                        // Trigger step-up authentication
1249                        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    /// Quarantine a session
1288    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        // Update CAEP session state
1294        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        // In a production implementation, you might want to notify the SessionManager
1311        // about the quarantine status through a separate event or notification system
1312
1313        Ok(())
1314    }
1315
1316    /// Notify registered event handlers
1317    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    /// Get current session state
1332    pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1333        // First validate with SessionManager
1334        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1335            if !self.session_manager.is_session_valid(session_id) {
1336                // Session is expired in SessionManager, remove from CAEP as well
1337                let mut sessions = self.sessions.write().await;
1338                sessions.remove(session_id);
1339                return Ok(None);
1340            }
1341
1342            // Return CAEP session state if it exists and subjects match
1343            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        // No valid OIDC session found
1358        Ok(None)
1359    }
1360
1361    /// Get event history for a subject
1362    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    /// Add or update an evaluation rule
1384    pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1385        let mut rules = self.rules.write().await;
1386
1387        // Remove existing rule with same ID
1388        rules.retain(|r| r.id != rule.id);
1389
1390        // Insert new rule and sort by priority
1391        rules.push(rule);
1392        rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1393
1394        Ok(())
1395    }
1396
1397    /// Remove an evaluation rule
1398    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    /// Get comprehensive session information combining OIDC and CAEP data
1406    pub async fn get_comprehensive_session_info(
1407        &self,
1408        session_id: &str,
1409    ) -> Result<Option<ComprehensiveSessionInfo>> {
1410        // Get OIDC session information
1411        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            // Get CAEP session information if available
1417            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    /// Get all sessions for a subject with comprehensive information
1435    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        // Test severity level comparison logic
1511        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}