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;
96use zeroize::Zeroizing;
97
98/// Type alias for complex event handler storage
99type EventHandlerMap = Arc<RwLock<HashMap<CaepEventType, Vec<Arc<dyn CaepEventHandler>>>>>;
100
101/// Configuration for Continuous Access Evaluation Protocol
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct CaepConfig {
104    /// URL for the event stream endpoint
105    pub event_stream_url: String,
106
107    /// How frequently to evaluate access decisions (default: 30 seconds)
108    pub evaluation_interval: Duration,
109
110    /// Whether to automatically revoke access on high-risk events
111    pub auto_revoke: bool,
112
113    /// Minimum risk score threshold for automatic revocation (0.0-1.0)
114    pub auto_revoke_threshold: f32,
115
116    /// Maximum number of concurrent event processors
117    pub max_concurrent_processors: usize,
118
119    /// Event retention period for audit trails
120    pub event_retention_period: Duration,
121
122    /// Cross-system event propagation endpoints
123    pub propagation_endpoints: Vec<String>,
124
125    /// Custom evaluation rules
126    pub evaluation_rules: Vec<CaepEvaluationRule>,
127
128    /// HMAC secret used to sign CAEP logout tokens (HS256).
129    /// **Must be set to a strong, randomly-generated secret in production.**
130    pub signing_secret: Zeroizing<String>,
131}
132
133impl Default for CaepConfig {
134    fn default() -> Self {
135        use ring::rand::{SecureRandom, SystemRandom};
136        // SAFETY: CSPRNG failure at initialization is terminal; the framework
137        // cannot operate without entropy.
138        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            // Randomly generated at startup. Override with a persisted secret in production
157            // so that tokens remain verifiable across restarts.
158            signing_secret: signing_secret.into(),
159        }
160    }
161}
162
163/// Types of CAEP events
164#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
165#[serde(rename_all = "snake_case")]
166pub enum CaepEventType {
167    /// User authentication events
168    UserLogin,
169    UserLogout,
170    UserProfileChange,
171    UserCredentialChange,
172
173    /// Session-related events
174    SessionCreated,
175    SessionModified,
176    SessionTimeout,
177    SessionSuspiciousActivity,
178
179    /// Risk assessment events
180    RiskScoreChange,
181    LocationChange,
182    DeviceChange,
183    BehavioralAnomaly,
184
185    /// Policy and compliance events
186    PolicyUpdate,
187    ComplianceViolation,
188    AccessPatternAnomaly,
189
190    /// System and security events
191    SystemOutage,
192    SecurityIncident,
193    DataBreach,
194
195    /// Custom events for extensibility
196    Custom(String),
197}
198
199/// Severity levels for CAEP events
200#[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/// Source of a CAEP event
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct CaepEventSource {
212    /// Identifier of the source system
213    pub system_id: String,
214
215    /// Type of source (e.g., "identity_provider", "risk_engine", "policy_engine")
216    pub source_type: String,
217
218    /// Version of the source system
219    pub version: Option<String>,
220
221    /// Additional source metadata
222    pub metadata: HashMap<String, serde_json::Value>,
223}
224
225/// A CAEP security event
226#[derive(Clone, Serialize, Deserialize)]
227pub struct CaepEvent {
228    /// Unique event identifier
229    pub id: Uuid,
230
231    /// Type of event
232    pub event_type: CaepEventType,
233
234    /// Subject (user) associated with the event
235    pub subject: String,
236
237    /// Severity level of the event
238    pub severity: CaepEventSeverity,
239
240    /// When the event occurred
241    pub timestamp: DateTime<Utc>,
242
243    /// Source of the event
244    pub source: CaepEventSource,
245
246    /// Current risk score (0.0-1.0)
247    pub risk_score: f32,
248
249    /// Session ID if applicable
250    pub session_id: Option<String>,
251
252    /// Geographic location information
253    pub location: Option<CaepLocationInfo>,
254
255    /// Device information
256    pub device_info: Option<CaepDeviceInfo>,
257
258    /// Event-specific data
259    pub event_data: serde_json::Value,
260
261    /// Correlation ID for related events
262    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/// Geographic location information for CAEP events
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct CaepLocationInfo {
290    /// Country code (ISO 3166-1 alpha-2)
291    pub country: Option<String>,
292
293    /// Region or state
294    pub region: Option<String>,
295
296    /// City name
297    pub city: Option<String>,
298
299    /// Latitude coordinate
300    pub latitude: Option<f64>,
301
302    /// Longitude coordinate
303    pub longitude: Option<f64>,
304
305    /// IP address
306    pub ip_address: Option<String>,
307
308    /// Whether location is considered suspicious
309    pub is_suspicious: bool,
310}
311
312/// Device information for CAEP events
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct CaepDeviceInfo {
315    /// Device identifier
316    pub device_id: Option<String>,
317
318    /// Device type (mobile, desktop, tablet, etc.)
319    pub device_type: Option<String>,
320
321    /// Operating system
322    pub os: Option<String>,
323
324    /// Browser or client application
325    pub client: Option<String>,
326
327    /// Whether device is trusted
328    pub is_trusted: bool,
329
330    /// Whether device binding is required
331    pub requires_binding: bool,
332}
333
334/// Evaluation rule for continuous access decisions
335#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct CaepEvaluationRule {
337    /// Rule identifier
338    pub id: String,
339
340    /// Human-readable description
341    pub description: String,
342
343    /// Event types this rule applies to
344    pub applicable_events: Vec<CaepEventType>,
345
346    /// Conditions that must be met
347    pub conditions: Vec<CaepRuleCondition>,
348
349    /// Actions to take when rule is triggered
350    pub actions: Vec<CaepRuleAction>,
351
352    /// Priority of this rule (higher numbers = higher priority)
353    pub priority: i32,
354
355    /// Whether rule is currently enabled
356    pub enabled: bool,
357}
358
359/// Condition for a CAEP evaluation rule
360#[derive(Debug, Clone, Serialize, Deserialize)]
361#[serde(tag = "type", rename_all = "snake_case")]
362pub enum CaepRuleCondition {
363    /// Risk score threshold condition
364    RiskScoreAbove { threshold: f32 },
365
366    /// Event severity condition
367    SeverityAtLeast { severity: CaepEventSeverity },
368
369    /// Location-based condition
370    LocationChange { suspicious_only: bool },
371
372    /// Device-based condition
373    UnknownDevice { require_trusted: bool },
374
375    /// Time-based condition
376    OutsideBusinessHours { timezone: String },
377
378    /// Custom condition with expression
379    Custom { expression: String },
380}
381
382/// Action to take when a CAEP rule is triggered
383#[derive(Clone, Serialize, Deserialize)]
384#[serde(tag = "type", rename_all = "snake_case")]
385pub enum CaepRuleAction {
386    /// Revoke access tokens for the subject
387    RevokeAccess { immediate: bool },
388
389    /// Require step-up authentication
390    RequireStepUp { level: String },
391
392    /// Send notification
393    SendNotification { channels: Vec<String> },
394
395    /// Log security event
396    LogEvent { level: String },
397
398    /// Trigger external webhook
399    TriggerWebhook { url: String },
400
401    /// Quarantine session
402    QuarantineSession { duration_minutes: u32 },
403}
404
405impl std::fmt::Debug for CaepRuleAction {
406    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        match self {
408            Self::RevokeAccess { immediate } => f
409                .debug_struct("RevokeAccess")
410                .field("immediate", immediate)
411                .finish(),
412            Self::RequireStepUp { level } => f
413                .debug_struct("RequireStepUp")
414                .field("level", level)
415                .finish(),
416            Self::SendNotification { channels } => f
417                .debug_struct("SendNotification")
418                .field("channels", channels)
419                .finish(),
420            Self::LogEvent { level } => f.debug_struct("LogEvent").field("level", level).finish(),
421            // A webhook URL can carry a token in its path or query.
422            Self::TriggerWebhook { url } => f
423                .debug_struct("TriggerWebhook")
424                .field("url", &crate::utils::redact::redacted(url))
425                .finish(),
426            Self::QuarantineSession { duration_minutes } => f
427                .debug_struct("QuarantineSession")
428                .field("duration_minutes", duration_minutes)
429                .finish(),
430        }
431    }
432}
433
434/// Result of a continuous access evaluation
435#[derive(Debug, Clone, Serialize, Deserialize)]
436pub struct CaepEvaluationResult {
437    /// Subject being evaluated
438    pub subject: String,
439
440    /// Current access decision
441    pub access_decision: CaepAccessDecision,
442
443    /// Current risk score
444    pub risk_score: f32,
445
446    /// Triggered rules
447    pub triggered_rules: Vec<String>,
448
449    /// Required actions
450    pub required_actions: Vec<CaepRuleAction>,
451
452    /// Evaluation timestamp
453    pub evaluated_at: DateTime<Utc>,
454
455    /// Next evaluation time
456    pub next_evaluation: DateTime<Utc>,
457}
458
459/// Access decision from CAEP evaluation
460#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
461#[serde(rename_all = "snake_case")]
462pub enum CaepAccessDecision {
463    /// Access granted - continue as normal
464    Allow,
465
466    /// Access granted but requires monitoring
467    AllowWithMonitoring,
468
469    /// Access granted but requires step-up authentication
470    AllowWithStepUp,
471
472    /// Access temporarily denied - retry later
473    TemporaryDeny,
474
475    /// Access permanently denied - revoke tokens
476    Deny,
477}
478
479/// State of a CAEP session
480#[derive(Clone, Serialize, Deserialize)]
481pub struct CaepSessionState {
482    /// Session identifier
483    pub session_id: String,
484
485    /// Subject (user) of the session
486    pub subject: String,
487
488    /// Current risk score
489    pub risk_score: f32,
490
491    /// Last evaluation result
492    pub last_evaluation: Option<CaepEvaluationResult>,
493
494    /// Active events for this session
495    pub active_events: Vec<CaepEvent>,
496
497    /// Session creation time
498    pub created_at: DateTime<Utc>,
499
500    /// Last activity time
501    pub last_activity: DateTime<Utc>,
502
503    /// Whether session is quarantined
504    pub is_quarantined: bool,
505
506    /// Quarantine end time if applicable
507    pub quarantine_until: Option<DateTime<Utc>>,
508}
509
510impl std::fmt::Debug for CaepSessionState {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        let mut d = f.debug_struct("CaepSessionState");
513        d.field(
514            "session_id",
515            &crate::utils::redact::redacted(&self.session_id),
516        );
517        d.field("subject", &self.subject);
518        d.field("risk_score", &self.risk_score);
519        d.field("last_evaluation", &self.last_evaluation);
520        d.field("active_events", &self.active_events);
521        d.field("created_at", &self.created_at);
522        d.field("last_activity", &self.last_activity);
523        d.field("is_quarantined", &self.is_quarantined);
524        d.field("quarantine_until", &self.quarantine_until);
525        d.finish()
526    }
527}
528
529/// Comprehensive session information combining OIDC and CAEP data
530#[derive(Debug, Clone, Serialize, Deserialize)]
531pub struct ComprehensiveSessionInfo {
532    /// OIDC session information
533    pub oidc_session: crate::server::oidc::oidc_session_management::OidcSession,
534
535    /// CAEP session information if available
536    pub caep_session: Option<CaepSessionState>,
537
538    /// Whether this session is being monitored by CAEP
539    pub is_monitored_by_caep: bool,
540}
541
542/// Event handler trait for CAEP events
543#[async_trait]
544pub trait CaepEventHandler: Send + Sync {
545    /// Handle a CAEP event
546    async fn handle_event(&self, event: &CaepEvent) -> Result<()>;
547
548    /// Get event types this handler can process
549    fn supported_event_types(&self) -> Vec<CaepEventType>;
550}
551
552/// Main CAEP manager for continuous access evaluation
553pub struct CaepManager {
554    /// Configuration
555    config: CaepConfig,
556
557    /// Session manager integration
558    session_manager: Arc<SessionManager>,
559
560    /// Logout manager for revocations
561    logout_manager: Arc<BackChannelLogoutManager>,
562
563    /// Step-up authentication manager
564    step_up_manager: Option<Arc<SteppedUpAuthManager>>,
565
566    /// Active sessions being monitored
567    sessions: Arc<RwLock<HashMap<String, CaepSessionState>>>,
568
569    /// Event handlers by type
570    event_handlers: EventHandlerMap,
571
572    /// Event stream broadcaster
573    event_broadcaster: broadcast::Sender<CaepEvent>,
574
575    /// Evaluation timer
576    evaluation_interval: Interval,
577
578    /// Event history for audit trails
579    event_history: Arc<RwLock<Vec<CaepEvent>>>,
580
581    /// Evaluation rules
582    rules: Arc<RwLock<Vec<CaepEvaluationRule>>>,
583}
584
585impl CaepManager {
586    /// Create a new CAEP manager
587    pub async fn new(
588        config: CaepConfig,
589        session_manager: Arc<SessionManager>,
590        logout_manager: Arc<BackChannelLogoutManager>,
591    ) -> Result<Self> {
592        let (event_broadcaster, _) = broadcast::channel(1000);
593        let evaluation_interval = interval(config.evaluation_interval.to_std().map_err(|e| {
594            AuthError::Configuration {
595                message: format!("Invalid evaluation interval: {}", e),
596                help: Some("Provide a valid duration for evaluation interval".to_string()),
597                docs_url: Some("https://docs.auth-framework.com/configuration".to_string()),
598                source: None,
599                suggested_fix: Some("Check your configuration and ensure the evaluation interval is properly formatted".to_string()),
600            }
601        })?);
602
603        Ok(Self {
604            config: config.clone(),
605            session_manager,
606            logout_manager,
607            step_up_manager: None,
608            sessions: Arc::new(RwLock::new(HashMap::new())),
609            event_handlers: Arc::new(RwLock::new(HashMap::new())),
610            event_broadcaster,
611            evaluation_interval,
612            event_history: Arc::new(RwLock::new(Vec::new())),
613            rules: Arc::new(RwLock::new(config.evaluation_rules)),
614        })
615    }
616
617    /// Set step-up authentication manager
618    pub fn with_step_up_manager(mut self, step_up_manager: Arc<SteppedUpAuthManager>) -> Self {
619        self.step_up_manager = Some(step_up_manager);
620        self
621    }
622
623    /// Register an event handler
624    pub async fn register_event_handler(
625        &self,
626        event_type: CaepEventType,
627        handler: Arc<dyn CaepEventHandler>,
628    ) -> Result<()> {
629        let mut handlers = self.event_handlers.write().await;
630        handlers.entry(event_type).or_default().push(handler);
631        Ok(())
632    }
633
634    /// Process a CAEP event
635    pub async fn process_event(&self, event: CaepEvent) -> Result<CaepEvaluationResult> {
636        // Add event to history
637        {
638            let mut history = self.event_history.write().await;
639            history.push(event.clone());
640
641            // Cleanup old events
642            let retention_cutoff = Utc::now() - self.config.event_retention_period;
643            history.retain(|e| e.timestamp >= retention_cutoff);
644        }
645
646        // Broadcast event
647        if let Err(e) = self.event_broadcaster.send(event.clone()) {
648            tracing::warn!("Failed to broadcast CAEP event: {}", e);
649        }
650
651        // Update session state
652        if let Some(session_id) = &event.session_id {
653            self.update_session_state(session_id, &event).await?;
654        }
655
656        // Evaluate access decision
657        let evaluation_result = self.evaluate_access(&event.subject, Some(&event)).await?;
658
659        // Execute required actions
660        self.execute_actions(&evaluation_result).await?;
661
662        // Notify registered handlers
663        self.notify_handlers(&event).await?;
664
665        Ok(evaluation_result)
666    }
667
668    /// Evaluate continuous access for a subject
669    pub async fn evaluate_access(
670        &self,
671        subject: &str,
672        triggering_event: Option<&CaepEvent>,
673    ) -> Result<CaepEvaluationResult> {
674        let rules = self.rules.read().await;
675        let mut triggered_rules = Vec::new();
676        let mut required_actions = Vec::new();
677        let risk_score = if let Some(event) = triggering_event {
678            event.risk_score
679        } else {
680            // Calculate risk from recent events
681            self.calculate_risk_score(subject).await?
682        };
683
684        // Apply evaluation rules
685        for rule in rules.iter() {
686            if !rule.enabled {
687                continue;
688            }
689
690            if let Some(event) = triggering_event
691                && !rule.applicable_events.contains(&event.event_type)
692            {
693                continue;
694            }
695
696            if self
697                .evaluate_rule_conditions(rule, subject, triggering_event, risk_score)
698                .await?
699            {
700                triggered_rules.push(rule.id.clone());
701                required_actions.extend(rule.actions.clone());
702            }
703        }
704
705        // Determine access decision
706        let access_decision = self.determine_access_decision(risk_score, &required_actions);
707
708        let now = Utc::now();
709        Ok(CaepEvaluationResult {
710            subject: subject.to_string(),
711            access_decision,
712            risk_score,
713            triggered_rules,
714            required_actions,
715            evaluated_at: now,
716            next_evaluation: now + self.config.evaluation_interval,
717        })
718    }
719
720    /// Start continuous evaluation loop
721    pub async fn start_continuous_evaluation(&mut self) -> Result<()> {
722        loop {
723            self.evaluation_interval.tick().await;
724
725            // First, synchronize with SessionManager to clean up stale sessions
726            self.synchronize_with_session_manager().await?;
727
728            // Evaluate all active sessions
729            let sessions = {
730                let sessions_guard = self.sessions.read().await;
731                sessions_guard.keys().cloned().collect::<Vec<_>>()
732            };
733
734            for session_id in sessions {
735                if let Some(session_state) = self.sessions.read().await.get(&session_id) {
736                    let evaluation = self.evaluate_access(&session_state.subject, None).await?;
737                    self.execute_actions(&evaluation).await?;
738                }
739            }
740        }
741    }
742
743    /// Synchronize CAEP sessions with SessionManager
744    async fn synchronize_with_session_manager(&self) -> Result<()> {
745        let mut sessions = self.sessions.write().await;
746        let mut sessions_to_remove = Vec::new();
747
748        for (session_id, caep_session) in sessions.iter() {
749            // Check if session still exists and is valid in SessionManager
750            if let Some(oidc_session) = self.session_manager.get_session(session_id) {
751                if !self.session_manager.is_session_valid(session_id) {
752                    tracing::info!(
753                        "CAEP removing expired session: {}",
754                        crate::utils::redact::fingerprint(session_id)
755                    );
756                    sessions_to_remove.push(session_id.clone());
757                }
758                // Verify subject consistency
759                else if oidc_session.sub != caep_session.subject {
760                    tracing::warn!(
761                        "CAEP session subject mismatch, removing: {}",
762                        crate::utils::redact::fingerprint(session_id)
763                    );
764                    sessions_to_remove.push(session_id.clone());
765                }
766            } else {
767                tracing::info!(
768                    "CAEP removing orphaned session: {}",
769                    crate::utils::redact::fingerprint(session_id)
770                );
771                sessions_to_remove.push(session_id.clone());
772            }
773        }
774
775        // Remove stale sessions
776        for session_id in sessions_to_remove {
777            sessions.remove(&session_id);
778        }
779
780        Ok(())
781    }
782
783    /// Revoke access for a subject
784    pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
785        tracing::info!("CAEP revoking access for subject: {}", subject);
786
787        // Find all sessions for this subject and initiate back-channel logout
788        let sessions_to_logout = {
789            let sessions = self.sessions.read().await;
790            sessions
791                .iter()
792                .filter(|(_, session)| session.subject == subject)
793                .map(|(session_id, session)| (session_id.clone(), session.clone()))
794                .collect::<Vec<_>>()
795        };
796
797        // Process back-channel logout for each session
798        for (session_id, _) in &sessions_to_logout {
799            // Use the BackChannelLogoutManager to perform proper logout
800            let logout_request =
801                crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
802                    session_id: session_id.clone(),
803                    sub: subject.to_string(),
804                    sid: Some(session_id.clone()),
805                    iss: "caep-manager".to_string(), // In production, use actual issuer
806                    initiating_client_id: None,      // CAEP-initiated logout
807                    additional_events: Some({
808                        let mut events = HashMap::new();
809                        events.insert(
810                            "caep_reason".to_string(),
811                            serde_json::json!("automatic_revocation"),
812                        );
813                        events.insert(
814                            "timestamp".to_string(),
815                            serde_json::json!(Utc::now().timestamp()),
816                        );
817                        events
818                    }),
819                };
820
821            // Process the logout through the BackChannelLogoutManager
822            // Use async approach to handle logout manager integration
823            match self.process_backchannel_logout(&logout_request).await {
824                Ok(_) => {
825                    tracing::info!(
826                        "Successfully initiated back-channel logout for session {} (subject: {})",
827                        crate::utils::redact::fingerprint(session_id),
828                        subject
829                    );
830                }
831                Err(e) => {
832                    tracing::error!(
833                        "Failed to initiate back-channel logout for session {} (subject: {}): {}",
834                        crate::utils::redact::fingerprint(session_id),
835                        subject,
836                        e
837                    );
838                }
839            }
840        }
841
842        // Remove from CAEP active sessions after logout processing
843        let mut sessions = self.sessions.write().await;
844        sessions.retain(|_, session| session.subject != subject);
845
846        Ok(())
847    }
848
849    /// Process back-channel logout through the logout manager
850    async fn process_backchannel_logout(
851        &self,
852        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
853    ) -> Result<()> {
854        // Use the logout manager to process the logout request
855        // This integrates CAEP with the existing logout infrastructure
856
857        // Use the logout manager to get metadata and validate capabilities
858        let logout_metadata = self.logout_manager.get_discovery_metadata();
859        tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
860
861        // Create CAEP-specific logout token based on the result
862        let logout_token = self
863            .create_logout_token_for_caep_revocation(logout_request)
864            .await?;
865
866        // Handle CAEP-specific logout processing
867        self.handle_caep_logout(logout_request, &logout_token)
868            .await?;
869
870        tracing::info!("CAEP backchannel logout processed successfully");
871        Ok(())
872    }
873
874    /// Create logout token for CAEP-initiated revocation
875    async fn create_logout_token_for_caep_revocation(
876        &self,
877        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
878    ) -> Result<String> {
879        use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
880        use serde_json::json;
881
882        // Create CAEP-specific logout token claims
883        let claims = json!({
884            "iss": logout_request.iss,
885            "sub": logout_request.sub,
886            "aud": ["caep-manager"],
887            "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
888            "iat": chrono::Utc::now().timestamp(),
889            "jti": uuid::Uuid::new_v4().to_string(),
890            "sid": logout_request.sid,
891            "events": {
892                "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
893            },
894            "caep_reason": logout_request.additional_events
895                .as_ref()
896                .and_then(|events| events.get("caep_reason"))
897                .unwrap_or(&serde_json::json!("automatic_revocation"))
898        });
899
900        // Use the configured signing secret; override CaepConfig::signing_secret in production.
901        let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
902        let header = Header::new(Algorithm::HS256);
903
904        let token = encode(&header, &claims, &key).map_err(|e| {
905            AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
906        })?;
907
908        Ok(token)
909    }
910
911    /// Handle CAEP logout processing
912    async fn handle_caep_logout(
913        &self,
914        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
915        logout_token: &str,
916    ) -> Result<()> {
917        // This method integrates with the logout manager's functionality
918        // In a production system, this would:
919        // 1. Validate the logout token
920        // 2. Notify all relevant clients about the session termination
921        // 3. Update session state in persistent storage
922        // 4. Trigger any cleanup procedures
923
924        tracing::info!(
925            "Processing CAEP logout for session: {}",
926            crate::utils::redact::fingerprint(&logout_request.session_id)
927        );
928
929        // Update CAEP session state to reflect logout
930        {
931            let mut sessions = self.sessions.write().await;
932            if let Some(_session) = sessions.get(&logout_request.session_id) {
933                // Remove the session entirely as it's being terminated
934                sessions.remove(&logout_request.session_id);
935            }
936        }
937
938        // Emit CAEP event for the logout
939        let caep_event = CaepEvent {
940            id: uuid::Uuid::new_v4(),
941            event_type: CaepEventType::UserLogout, // Use existing event type
942            subject: logout_request.sub.clone(),
943            session_id: Some(logout_request.session_id.clone()),
944            timestamp: chrono::Utc::now(),
945            severity: CaepEventSeverity::High,
946            source: CaepEventSource {
947                system_id: "caep-manager".to_string(),
948                source_type: "caep_automatic_revocation".to_string(),
949                version: Some("1.0".to_string()),
950                metadata: std::collections::HashMap::new(),
951            },
952            risk_score: 1.0, // High risk score for revoked sessions
953            location: None,
954            device_info: None,
955            event_data: serde_json::json!({
956                "logout_token": logout_token,
957                "initiator": "caep_automatic_revocation",
958                "reason": logout_request.additional_events
959                    .as_ref()
960                    .and_then(|events| events.get("caep_reason"))
961                    .cloned()
962                    .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
963            }),
964            correlation_id: Some(uuid::Uuid::new_v4()),
965        };
966
967        // Broadcast the event
968        if let Err(e) = self.event_broadcaster.send(caep_event) {
969            tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
970        }
971
972        tracing::info!(
973            "CAEP logout completed for session: {}",
974            crate::utils::redact::fingerprint(&logout_request.session_id)
975        );
976        Ok(())
977    }
978
979    /// Calculate risk score for a subject based on recent events
980    async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
981        let history = self.event_history.read().await;
982        let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
983
984        let recent_events: Vec<_> = history
985            .iter()
986            .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
987            .collect();
988
989        if recent_events.is_empty() {
990            return Ok(0.0);
991        }
992
993        // Calculate weighted risk score
994        let mut total_risk = 0.0;
995        let mut total_weight = 0.0;
996
997        for event in recent_events {
998            let weight = match event.severity {
999                CaepEventSeverity::Low => 1.0,
1000                CaepEventSeverity::Medium => 2.0,
1001                CaepEventSeverity::High => 4.0,
1002                CaepEventSeverity::Critical => 8.0,
1003            };
1004
1005            total_risk += event.risk_score * weight;
1006            total_weight += weight;
1007        }
1008
1009        Ok(if total_weight > 0.0 {
1010            (total_risk / total_weight).min(1.0)
1011        } else {
1012            0.0
1013        })
1014    }
1015
1016    /// Update session state based on an event
1017    async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1018        // First, validate the session exists in the SessionManager
1019        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1020            // Verify the session is still valid
1021            if !self.session_manager.is_session_valid(session_id) {
1022                tracing::warn!(
1023                    "CAEP received event for expired OIDC session: {}",
1024                    crate::utils::redact::fingerprint(session_id)
1025                );
1026                // Remove from CAEP sessions as well
1027                let mut sessions = self.sessions.write().await;
1028                sessions.remove(session_id);
1029                return Ok(());
1030            }
1031
1032            // Ensure subjects match
1033            if oidc_session.sub != event.subject {
1034                return Err(AuthError::validation(
1035                    "Subject mismatch between CAEP event and OIDC session",
1036                ));
1037            }
1038        } else {
1039            tracing::warn!(
1040                "CAEP received event for unknown OIDC session: {}",
1041                crate::utils::redact::fingerprint(session_id)
1042            );
1043            return Err(AuthError::validation("Session not found in SessionManager"));
1044        }
1045
1046        // Update CAEP-specific session state
1047        let mut sessions = self.sessions.write().await;
1048
1049        let session_state =
1050            sessions
1051                .entry(session_id.to_string())
1052                .or_insert_with(|| CaepSessionState {
1053                    session_id: session_id.to_string(),
1054                    subject: event.subject.clone(),
1055                    risk_score: event.risk_score,
1056                    last_evaluation: None,
1057                    active_events: Vec::new(),
1058                    created_at: Utc::now(),
1059                    last_activity: Utc::now(),
1060                    is_quarantined: false,
1061                    quarantine_until: None,
1062                });
1063
1064        session_state.risk_score = event.risk_score;
1065        session_state.last_activity = Utc::now();
1066        session_state.active_events.push(event.clone());
1067
1068        // Remove old events
1069        let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1070        session_state
1071            .active_events
1072            .retain(|e| e.timestamp >= cutoff);
1073
1074        Ok(())
1075    }
1076
1077    /// Evaluate rule conditions
1078    async fn evaluate_rule_conditions(
1079        &self,
1080        rule: &CaepEvaluationRule,
1081        _subject: &str,
1082        event: Option<&CaepEvent>,
1083        risk_score: f32,
1084    ) -> Result<bool> {
1085        for condition in &rule.conditions {
1086            match condition {
1087                CaepRuleCondition::RiskScoreAbove { threshold } => {
1088                    if risk_score <= *threshold {
1089                        return Ok(false);
1090                    }
1091                }
1092                CaepRuleCondition::SeverityAtLeast { severity } => {
1093                    if let Some(event) = event {
1094                        let event_severity_level = match event.severity {
1095                            CaepEventSeverity::Critical => 4,
1096                            CaepEventSeverity::High => 3,
1097                            CaepEventSeverity::Medium => 2,
1098                            CaepEventSeverity::Low => 1,
1099                        };
1100
1101                        let required_severity_level = match severity {
1102                            CaepEventSeverity::Critical => 4,
1103                            CaepEventSeverity::High => 3,
1104                            CaepEventSeverity::Medium => 2,
1105                            CaepEventSeverity::Low => 1,
1106                        };
1107
1108                        if event_severity_level < required_severity_level {
1109                            return Ok(false);
1110                        }
1111                    } else {
1112                        return Ok(false);
1113                    }
1114                }
1115                CaepRuleCondition::LocationChange { suspicious_only } => {
1116                    if let Some(event) = event {
1117                        if let Some(location) = &event.location {
1118                            if *suspicious_only && !location.is_suspicious {
1119                                return Ok(false);
1120                            }
1121                        } else {
1122                            return Ok(false);
1123                        }
1124                    } else {
1125                        return Ok(false);
1126                    }
1127                }
1128                CaepRuleCondition::UnknownDevice { require_trusted } => {
1129                    if let Some(event) = event
1130                        && let Some(device) = &event.device_info
1131                        && *require_trusted
1132                        && device.is_trusted
1133                    {
1134                        return Ok(false);
1135                    }
1136                }
1137                CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1138                    // Simplified: assume business hours are 9 AM - 5 PM UTC
1139                    let hour = Utc::now().hour();
1140                    if (9..17).contains(&hour) {
1141                        return Ok(false);
1142                    }
1143                }
1144                CaepRuleCondition::Custom { expression } => {
1145                    // Basic expression evaluation: support "field op value" comparisons
1146                    if !Self::evaluate_simple_expression(expression) {
1147                        return Ok(false);
1148                    }
1149                }
1150            }
1151        }
1152
1153        Ok(true)
1154    }
1155
1156    /// Evaluate a simple comparison expression like "risk_score > 0.8"
1157    /// Returns false (safe default) for unrecognized or unparseable expressions.
1158    fn evaluate_simple_expression(expression: &str) -> bool {
1159        let parts: Vec<&str> = expression.split_whitespace().collect();
1160        if parts.len() != 3 {
1161            tracing::warn!(
1162                expression = expression,
1163                "Unrecognized custom CAEP expression format, defaulting to false"
1164            );
1165            return false;
1166        }
1167
1168        let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1169        let Ok(threshold) = value_str.parse::<f64>() else {
1170            tracing::warn!(
1171                expression = expression,
1172                "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1173            );
1174            return false;
1175        };
1176
1177        // Without runtime context binding, we can only validate the expression
1178        // is syntactically correct. Log and return false (safe default).
1179        tracing::debug!(
1180            expression = expression,
1181            threshold = threshold,
1182            op = op,
1183            "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1184        );
1185        false
1186    }
1187
1188    /// Determine access decision based on risk and actions
1189    fn determine_access_decision(
1190        &self,
1191        risk_score: f32,
1192        actions: &[CaepRuleAction],
1193    ) -> CaepAccessDecision {
1194        for action in actions {
1195            match action {
1196                CaepRuleAction::RevokeAccess { immediate: true } => {
1197                    return CaepAccessDecision::Deny;
1198                }
1199                CaepRuleAction::RevokeAccess { immediate: false } => {
1200                    return CaepAccessDecision::TemporaryDeny;
1201                }
1202                CaepRuleAction::RequireStepUp { .. } => {
1203                    return CaepAccessDecision::AllowWithStepUp;
1204                }
1205                CaepRuleAction::QuarantineSession { .. } => {
1206                    return CaepAccessDecision::TemporaryDeny;
1207                }
1208                _ => {}
1209            }
1210        }
1211
1212        if risk_score >= self.config.auto_revoke_threshold {
1213            CaepAccessDecision::Deny
1214        } else if risk_score >= 0.6 {
1215            CaepAccessDecision::AllowWithMonitoring
1216        } else {
1217            CaepAccessDecision::Allow
1218        }
1219    }
1220
1221    /// Execute required actions from evaluation
1222    async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1223        for action in &evaluation.required_actions {
1224            match action {
1225                CaepRuleAction::RevokeAccess { .. } => {
1226                    self.revoke_subject_access(&evaluation.subject).await?;
1227                }
1228                CaepRuleAction::RequireStepUp { level } => {
1229                    if let Some(_step_up_manager) = &self.step_up_manager {
1230                        // Trigger step-up authentication
1231                        tracing::info!(
1232                            "CAEP requiring step-up to level {} for subject {}",
1233                            level,
1234                            evaluation.subject
1235                        );
1236                    }
1237                }
1238                CaepRuleAction::SendNotification { channels } => {
1239                    tracing::info!(
1240                        "CAEP sending notification via channels {:?} for subject {}",
1241                        channels,
1242                        evaluation.subject
1243                    );
1244                }
1245                CaepRuleAction::LogEvent { level } => {
1246                    tracing::info!(
1247                        "CAEP logging event at level {} for subject {}",
1248                        level,
1249                        evaluation.subject
1250                    );
1251                }
1252                CaepRuleAction::TriggerWebhook { url } => {
1253                    tracing::info!(
1254                        "CAEP triggering webhook {} for subject {}",
1255                        crate::utils::redact::url_origin(url),
1256                        evaluation.subject
1257                    );
1258                }
1259                CaepRuleAction::QuarantineSession { duration_minutes } => {
1260                    self.quarantine_session(&evaluation.subject, *duration_minutes)
1261                        .await?;
1262                }
1263            }
1264        }
1265
1266        Ok(())
1267    }
1268
1269    /// Quarantine a session
1270    async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1271        let mut sessions = self.sessions.write().await;
1272        let quarantine_until =
1273            Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1274
1275        // Update CAEP session state
1276        let mut quarantined_session_ids = Vec::new();
1277        for session in sessions.values_mut() {
1278            if session.subject == subject {
1279                session.is_quarantined = true;
1280                session.quarantine_until = Some(quarantine_until);
1281                quarantined_session_ids.push(session.session_id.clone());
1282            }
1283        }
1284
1285        tracing::info!(
1286            "CAEP quarantined {} sessions for subject {} until {}",
1287            quarantined_session_ids.len(),
1288            subject,
1289            quarantine_until
1290        );
1291
1292        // In a production implementation, you might want to notify the SessionManager
1293        // about the quarantine status through a separate event or notification system
1294
1295        Ok(())
1296    }
1297
1298    /// Notify registered event handlers
1299    async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1300        let handlers = self.event_handlers.read().await;
1301
1302        if let Some(event_handlers) = handlers.get(&event.event_type) {
1303            for handler in event_handlers {
1304                if let Err(e) = handler.handle_event(event).await {
1305                    tracing::error!("CAEP event handler failed: {}", e);
1306                }
1307            }
1308        }
1309
1310        Ok(())
1311    }
1312
1313    /// Get current session state
1314    pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1315        // First validate with SessionManager
1316        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1317            if !self.session_manager.is_session_valid(session_id) {
1318                // Session is expired in SessionManager, remove from CAEP as well
1319                let mut sessions = self.sessions.write().await;
1320                sessions.remove(session_id);
1321                return Ok(None);
1322            }
1323
1324            // Return CAEP session state if it exists and subjects match
1325            let sessions = self.sessions.read().await;
1326            if let Some(caep_session) = sessions.get(session_id) {
1327                if caep_session.subject == oidc_session.sub {
1328                    return Ok(Some(caep_session.clone()));
1329                } else {
1330                    tracing::warn!(
1331                        "Subject mismatch between CAEP and OIDC sessions for {}",
1332                        crate::utils::redact::fingerprint(session_id)
1333                    );
1334                    return Ok(None);
1335                }
1336            }
1337        }
1338
1339        // No valid OIDC session found
1340        Ok(None)
1341    }
1342
1343    /// Get event history for a subject
1344    pub async fn get_event_history(
1345        &self,
1346        subject: &str,
1347        limit: Option<usize>,
1348    ) -> Result<Vec<CaepEvent>> {
1349        let history = self.event_history.read().await;
1350        let mut events: Vec<_> = history
1351            .iter()
1352            .filter(|e| e.subject == subject)
1353            .cloned()
1354            .collect();
1355
1356        events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1357
1358        if let Some(limit) = limit {
1359            events.truncate(limit);
1360        }
1361
1362        Ok(events)
1363    }
1364
1365    /// Add or update an evaluation rule
1366    pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1367        let mut rules = self.rules.write().await;
1368
1369        // Remove existing rule with same ID
1370        rules.retain(|r| r.id != rule.id);
1371
1372        // Insert new rule and sort by priority
1373        rules.push(rule);
1374        rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1375
1376        Ok(())
1377    }
1378
1379    /// Remove an evaluation rule
1380    pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1381        let mut rules = self.rules.write().await;
1382        let original_len = rules.len();
1383        rules.retain(|r| r.id != rule_id);
1384        Ok(rules.len() < original_len)
1385    }
1386
1387    /// Get comprehensive session information combining OIDC and CAEP data
1388    pub async fn get_comprehensive_session_info(
1389        &self,
1390        session_id: &str,
1391    ) -> Result<Option<ComprehensiveSessionInfo>> {
1392        // Get OIDC session information
1393        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1394            if !self.session_manager.is_session_valid(session_id) {
1395                return Ok(None);
1396            }
1397
1398            // Get CAEP session information if available
1399            let caep_session = {
1400                let sessions = self.sessions.read().await;
1401                sessions.get(session_id).cloned()
1402            };
1403
1404            let comprehensive_info = ComprehensiveSessionInfo {
1405                oidc_session: oidc_session.clone(),
1406                is_monitored_by_caep: caep_session.is_some(),
1407                caep_session,
1408            };
1409
1410            Ok(Some(comprehensive_info))
1411        } else {
1412            Ok(None)
1413        }
1414    }
1415
1416    /// Get all sessions for a subject with comprehensive information
1417    pub async fn get_subject_sessions(
1418        &self,
1419        subject: &str,
1420    ) -> Result<Vec<ComprehensiveSessionInfo>> {
1421        let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1422        let mut comprehensive_sessions = Vec::new();
1423
1424        for oidc_session in oidc_sessions {
1425            if self
1426                .session_manager
1427                .is_session_valid(&oidc_session.session_id)
1428            {
1429                let caep_session = {
1430                    let sessions = self.sessions.read().await;
1431                    sessions.get(&oidc_session.session_id).cloned()
1432                };
1433
1434                comprehensive_sessions.push(ComprehensiveSessionInfo {
1435                    oidc_session: oidc_session.clone(),
1436                    is_monitored_by_caep: caep_session.is_some(),
1437                    caep_session,
1438                });
1439            }
1440        }
1441
1442        Ok(comprehensive_sessions)
1443    }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448    use super::*;
1449    use tokio;
1450
1451    #[tokio::test]
1452    async fn test_caep_event_creation() {
1453        let event = CaepEvent {
1454            id: Uuid::new_v4(),
1455            event_type: CaepEventType::RiskScoreChange,
1456            subject: "user123".to_string(),
1457            severity: CaepEventSeverity::High,
1458            timestamp: Utc::now(),
1459            source: CaepEventSource {
1460                system_id: "risk_engine".to_string(),
1461                source_type: "ml_model".to_string(),
1462                version: Some("1.0.0".to_string()),
1463                metadata: HashMap::new(),
1464            },
1465            risk_score: 0.85,
1466            session_id: Some("session123".to_string()),
1467            location: None,
1468            device_info: None,
1469            event_data: serde_json::json!({
1470                "previous_score": 0.3,
1471                "new_score": 0.85,
1472                "trigger": "suspicious_login_pattern"
1473            }),
1474            correlation_id: None,
1475        };
1476
1477        assert_eq!(event.subject, "user123");
1478        assert_eq!(event.risk_score, 0.85);
1479        assert!(matches!(event.severity, CaepEventSeverity::High));
1480    }
1481
1482    #[tokio::test]
1483    async fn test_caep_config_creation() {
1484        let config = CaepConfig::default();
1485        assert!(!config.event_stream_url.is_empty());
1486        assert!(config.auto_revoke);
1487        assert_eq!(config.auto_revoke_threshold, 0.8);
1488    }
1489
1490    #[tokio::test]
1491    async fn test_severity_comparison() {
1492        // Test severity level comparison logic
1493        let high_level = match CaepEventSeverity::High {
1494            CaepEventSeverity::Critical => 4,
1495            CaepEventSeverity::High => 3,
1496            CaepEventSeverity::Medium => 2,
1497            CaepEventSeverity::Low => 1,
1498        };
1499
1500        let medium_level = match CaepEventSeverity::Medium {
1501            CaepEventSeverity::Critical => 4,
1502            CaepEventSeverity::High => 3,
1503            CaepEventSeverity::Medium => 2,
1504            CaepEventSeverity::Low => 1,
1505        };
1506
1507        assert!(high_level > medium_level);
1508    }
1509}