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!("CAEP removing expired session: {}", session_id);
753                    sessions_to_remove.push(session_id.clone());
754                }
755                // Verify subject consistency
756                else if oidc_session.sub != caep_session.subject {
757                    tracing::warn!("CAEP session subject mismatch, removing: {}", session_id);
758                    sessions_to_remove.push(session_id.clone());
759                }
760            } else {
761                tracing::info!("CAEP removing orphaned session: {}", session_id);
762                sessions_to_remove.push(session_id.clone());
763            }
764        }
765
766        // Remove stale sessions
767        for session_id in sessions_to_remove {
768            sessions.remove(&session_id);
769        }
770
771        Ok(())
772    }
773
774    /// Revoke access for a subject
775    pub async fn revoke_subject_access(&self, subject: &str) -> Result<()> {
776        tracing::info!("CAEP revoking access for subject: {}", subject);
777
778        // Find all sessions for this subject and initiate back-channel logout
779        let sessions_to_logout = {
780            let sessions = self.sessions.read().await;
781            sessions
782                .iter()
783                .filter(|(_, session)| session.subject == subject)
784                .map(|(session_id, session)| (session_id.clone(), session.clone()))
785                .collect::<Vec<_>>()
786        };
787
788        // Process back-channel logout for each session
789        for (session_id, _) in &sessions_to_logout {
790            // Use the BackChannelLogoutManager to perform proper logout
791            let logout_request =
792                crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest {
793                    session_id: session_id.clone(),
794                    sub: subject.to_string(),
795                    sid: Some(session_id.clone()),
796                    iss: "caep-manager".to_string(), // In production, use actual issuer
797                    initiating_client_id: None,      // CAEP-initiated logout
798                    additional_events: Some({
799                        let mut events = HashMap::new();
800                        events.insert(
801                            "caep_reason".to_string(),
802                            serde_json::json!("automatic_revocation"),
803                        );
804                        events.insert(
805                            "timestamp".to_string(),
806                            serde_json::json!(Utc::now().timestamp()),
807                        );
808                        events
809                    }),
810                };
811
812            // Process the logout through the BackChannelLogoutManager
813            // Use async approach to handle logout manager integration
814            match self.process_backchannel_logout(&logout_request).await {
815                Ok(_) => {
816                    tracing::info!(
817                        "Successfully initiated back-channel logout for session {} (subject: {})",
818                        session_id,
819                        subject
820                    );
821                }
822                Err(e) => {
823                    tracing::error!(
824                        "Failed to initiate back-channel logout for session {} (subject: {}): {}",
825                        session_id,
826                        subject,
827                        e
828                    );
829                }
830            }
831        }
832
833        // Remove from CAEP active sessions after logout processing
834        let mut sessions = self.sessions.write().await;
835        sessions.retain(|_, session| session.subject != subject);
836
837        Ok(())
838    }
839
840    /// Process back-channel logout through the logout manager
841    async fn process_backchannel_logout(
842        &self,
843        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
844    ) -> Result<()> {
845        // Use the logout manager to process the logout request
846        // This integrates CAEP with the existing logout infrastructure
847
848        // Use the logout manager to get metadata and validate capabilities
849        let logout_metadata = self.logout_manager.get_discovery_metadata();
850        tracing::info!("Logout manager capabilities: {:?}", logout_metadata);
851
852        // Create CAEP-specific logout token based on the result
853        let logout_token = self
854            .create_logout_token_for_caep_revocation(logout_request)
855            .await?;
856
857        // Handle CAEP-specific logout processing
858        self.handle_caep_logout(logout_request, &logout_token)
859            .await?;
860
861        tracing::info!("CAEP backchannel logout processed successfully");
862        Ok(())
863    }
864
865    /// Create logout token for CAEP-initiated revocation
866    async fn create_logout_token_for_caep_revocation(
867        &self,
868        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
869    ) -> Result<String> {
870        use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
871        use serde_json::json;
872
873        // Create CAEP-specific logout token claims
874        let claims = json!({
875            "iss": logout_request.iss,
876            "sub": logout_request.sub,
877            "aud": ["caep-manager"],
878            "exp": (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp(),
879            "iat": chrono::Utc::now().timestamp(),
880            "jti": uuid::Uuid::new_v4().to_string(),
881            "sid": logout_request.sid,
882            "events": {
883                "http://schemas.openid.net/secevent/caep/event-type/session-revoked": {}
884            },
885            "caep_reason": logout_request.additional_events
886                .as_ref()
887                .and_then(|events| events.get("caep_reason"))
888                .unwrap_or(&serde_json::json!("automatic_revocation"))
889        });
890
891        // Use the configured signing secret; override CaepConfig::signing_secret in production.
892        let key = EncodingKey::from_secret(self.config.signing_secret.as_bytes());
893        let header = Header::new(Algorithm::HS256);
894
895        let token = encode(&header, &claims, &key).map_err(|e| {
896            AuthError::auth_method("caep", format!("Failed to create logout token: {}", e))
897        })?;
898
899        Ok(token)
900    }
901
902    /// Handle CAEP logout processing
903    async fn handle_caep_logout(
904        &self,
905        logout_request: &crate::server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest,
906        logout_token: &str,
907    ) -> Result<()> {
908        // This method integrates with the logout manager's functionality
909        // In a production system, this would:
910        // 1. Validate the logout token
911        // 2. Notify all relevant clients about the session termination
912        // 3. Update session state in persistent storage
913        // 4. Trigger any cleanup procedures
914
915        tracing::info!(
916            "Processing CAEP logout for session: {}",
917            logout_request.session_id
918        );
919
920        // Update CAEP session state to reflect logout
921        {
922            let mut sessions = self.sessions.write().await;
923            if let Some(_session) = sessions.get(&logout_request.session_id) {
924                // Remove the session entirely as it's being terminated
925                sessions.remove(&logout_request.session_id);
926            }
927        }
928
929        // Emit CAEP event for the logout
930        let caep_event = CaepEvent {
931            id: uuid::Uuid::new_v4(),
932            event_type: CaepEventType::UserLogout, // Use existing event type
933            subject: logout_request.sub.clone(),
934            session_id: Some(logout_request.session_id.clone()),
935            timestamp: chrono::Utc::now(),
936            severity: CaepEventSeverity::High,
937            source: CaepEventSource {
938                system_id: "caep-manager".to_string(),
939                source_type: "caep_automatic_revocation".to_string(),
940                version: Some("1.0".to_string()),
941                metadata: std::collections::HashMap::new(),
942            },
943            risk_score: 1.0, // High risk score for revoked sessions
944            location: None,
945            device_info: None,
946            event_data: serde_json::json!({
947                "logout_token": logout_token,
948                "initiator": "caep_automatic_revocation",
949                "reason": logout_request.additional_events
950                    .as_ref()
951                    .and_then(|events| events.get("caep_reason"))
952                    .cloned()
953                    .unwrap_or_else(|| serde_json::json!("automatic_revocation"))
954            }),
955            correlation_id: Some(uuid::Uuid::new_v4()),
956        };
957
958        // Broadcast the event
959        if let Err(e) = self.event_broadcaster.send(caep_event) {
960            tracing::warn!("Failed to broadcast CAEP logout event: {}", e);
961        }
962
963        tracing::info!(
964            "CAEP logout completed for session: {}",
965            logout_request.session_id
966        );
967        Ok(())
968    }
969
970    /// Calculate risk score for a subject based on recent events
971    async fn calculate_risk_score(&self, subject: &str) -> Result<f32> {
972        let history = self.event_history.read().await;
973        let recent_cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
974
975        let recent_events: Vec<_> = history
976            .iter()
977            .filter(|e| e.subject == subject && e.timestamp >= recent_cutoff)
978            .collect();
979
980        if recent_events.is_empty() {
981            return Ok(0.0);
982        }
983
984        // Calculate weighted risk score
985        let mut total_risk = 0.0;
986        let mut total_weight = 0.0;
987
988        for event in recent_events {
989            let weight = match event.severity {
990                CaepEventSeverity::Low => 1.0,
991                CaepEventSeverity::Medium => 2.0,
992                CaepEventSeverity::High => 4.0,
993                CaepEventSeverity::Critical => 8.0,
994            };
995
996            total_risk += event.risk_score * weight;
997            total_weight += weight;
998        }
999
1000        Ok(if total_weight > 0.0 {
1001            (total_risk / total_weight).min(1.0)
1002        } else {
1003            0.0
1004        })
1005    }
1006
1007    /// Update session state based on an event
1008    async fn update_session_state(&self, session_id: &str, event: &CaepEvent) -> Result<()> {
1009        // First, validate the session exists in the SessionManager
1010        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1011            // Verify the session is still valid
1012            if !self.session_manager.is_session_valid(session_id) {
1013                tracing::warn!(
1014                    "CAEP received event for expired OIDC session: {}",
1015                    session_id
1016                );
1017                // Remove from CAEP sessions as well
1018                let mut sessions = self.sessions.write().await;
1019                sessions.remove(session_id);
1020                return Ok(());
1021            }
1022
1023            // Ensure subjects match
1024            if oidc_session.sub != event.subject {
1025                return Err(AuthError::validation(
1026                    "Subject mismatch between CAEP event and OIDC session",
1027                ));
1028            }
1029        } else {
1030            tracing::warn!(
1031                "CAEP received event for unknown OIDC session: {}",
1032                session_id
1033            );
1034            return Err(AuthError::validation("Session not found in SessionManager"));
1035        }
1036
1037        // Update CAEP-specific session state
1038        let mut sessions = self.sessions.write().await;
1039
1040        let session_state =
1041            sessions
1042                .entry(session_id.to_string())
1043                .or_insert_with(|| CaepSessionState {
1044                    session_id: session_id.to_string(),
1045                    subject: event.subject.clone(),
1046                    risk_score: event.risk_score,
1047                    last_evaluation: None,
1048                    active_events: Vec::new(),
1049                    created_at: Utc::now(),
1050                    last_activity: Utc::now(),
1051                    is_quarantined: false,
1052                    quarantine_until: None,
1053                });
1054
1055        session_state.risk_score = event.risk_score;
1056        session_state.last_activity = Utc::now();
1057        session_state.active_events.push(event.clone());
1058
1059        // Remove old events
1060        let cutoff = Utc::now() - Duration::try_hours(1).unwrap_or(Duration::zero());
1061        session_state
1062            .active_events
1063            .retain(|e| e.timestamp >= cutoff);
1064
1065        Ok(())
1066    }
1067
1068    /// Evaluate rule conditions
1069    async fn evaluate_rule_conditions(
1070        &self,
1071        rule: &CaepEvaluationRule,
1072        _subject: &str,
1073        event: Option<&CaepEvent>,
1074        risk_score: f32,
1075    ) -> Result<bool> {
1076        for condition in &rule.conditions {
1077            match condition {
1078                CaepRuleCondition::RiskScoreAbove { threshold } => {
1079                    if risk_score <= *threshold {
1080                        return Ok(false);
1081                    }
1082                }
1083                CaepRuleCondition::SeverityAtLeast { severity } => {
1084                    if let Some(event) = event {
1085                        let event_severity_level = match event.severity {
1086                            CaepEventSeverity::Critical => 4,
1087                            CaepEventSeverity::High => 3,
1088                            CaepEventSeverity::Medium => 2,
1089                            CaepEventSeverity::Low => 1,
1090                        };
1091
1092                        let required_severity_level = match severity {
1093                            CaepEventSeverity::Critical => 4,
1094                            CaepEventSeverity::High => 3,
1095                            CaepEventSeverity::Medium => 2,
1096                            CaepEventSeverity::Low => 1,
1097                        };
1098
1099                        if event_severity_level < required_severity_level {
1100                            return Ok(false);
1101                        }
1102                    } else {
1103                        return Ok(false);
1104                    }
1105                }
1106                CaepRuleCondition::LocationChange { suspicious_only } => {
1107                    if let Some(event) = event {
1108                        if let Some(location) = &event.location {
1109                            if *suspicious_only && !location.is_suspicious {
1110                                return Ok(false);
1111                            }
1112                        } else {
1113                            return Ok(false);
1114                        }
1115                    } else {
1116                        return Ok(false);
1117                    }
1118                }
1119                CaepRuleCondition::UnknownDevice { require_trusted } => {
1120                    if let Some(event) = event
1121                        && let Some(device) = &event.device_info
1122                        && *require_trusted
1123                        && device.is_trusted
1124                    {
1125                        return Ok(false);
1126                    }
1127                }
1128                CaepRuleCondition::OutsideBusinessHours { timezone: _ } => {
1129                    // Simplified: assume business hours are 9 AM - 5 PM UTC
1130                    let hour = Utc::now().hour();
1131                    if (9..17).contains(&hour) {
1132                        return Ok(false);
1133                    }
1134                }
1135                CaepRuleCondition::Custom { expression } => {
1136                    // Basic expression evaluation: support "field op value" comparisons
1137                    if !Self::evaluate_simple_expression(expression) {
1138                        return Ok(false);
1139                    }
1140                }
1141            }
1142        }
1143
1144        Ok(true)
1145    }
1146
1147    /// Evaluate a simple comparison expression like "risk_score > 0.8"
1148    /// Returns false (safe default) for unrecognized or unparseable expressions.
1149    fn evaluate_simple_expression(expression: &str) -> bool {
1150        let parts: Vec<&str> = expression.split_whitespace().collect();
1151        if parts.len() != 3 {
1152            tracing::warn!(
1153                expression = expression,
1154                "Unrecognized custom CAEP expression format, defaulting to false"
1155            );
1156            return false;
1157        }
1158
1159        let (_field, op, value_str) = (parts[0], parts[1], parts[2]);
1160        let Ok(threshold) = value_str.parse::<f64>() else {
1161            tracing::warn!(
1162                expression = expression,
1163                "Cannot parse threshold value in custom CAEP expression, defaulting to false"
1164            );
1165            return false;
1166        };
1167
1168        // Without runtime context binding, we can only validate the expression
1169        // is syntactically correct. Log and return false (safe default).
1170        tracing::debug!(
1171            expression = expression,
1172            threshold = threshold,
1173            op = op,
1174            "Custom CAEP expression parsed but no runtime context available, defaulting to false"
1175        );
1176        false
1177    }
1178
1179    /// Determine access decision based on risk and actions
1180    fn determine_access_decision(
1181        &self,
1182        risk_score: f32,
1183        actions: &[CaepRuleAction],
1184    ) -> CaepAccessDecision {
1185        for action in actions {
1186            match action {
1187                CaepRuleAction::RevokeAccess { immediate: true } => {
1188                    return CaepAccessDecision::Deny;
1189                }
1190                CaepRuleAction::RevokeAccess { immediate: false } => {
1191                    return CaepAccessDecision::TemporaryDeny;
1192                }
1193                CaepRuleAction::RequireStepUp { .. } => {
1194                    return CaepAccessDecision::AllowWithStepUp;
1195                }
1196                CaepRuleAction::QuarantineSession { .. } => {
1197                    return CaepAccessDecision::TemporaryDeny;
1198                }
1199                _ => {}
1200            }
1201        }
1202
1203        if risk_score >= self.config.auto_revoke_threshold {
1204            CaepAccessDecision::Deny
1205        } else if risk_score >= 0.6 {
1206            CaepAccessDecision::AllowWithMonitoring
1207        } else {
1208            CaepAccessDecision::Allow
1209        }
1210    }
1211
1212    /// Execute required actions from evaluation
1213    async fn execute_actions(&self, evaluation: &CaepEvaluationResult) -> Result<()> {
1214        for action in &evaluation.required_actions {
1215            match action {
1216                CaepRuleAction::RevokeAccess { .. } => {
1217                    self.revoke_subject_access(&evaluation.subject).await?;
1218                }
1219                CaepRuleAction::RequireStepUp { level } => {
1220                    if let Some(_step_up_manager) = &self.step_up_manager {
1221                        // Trigger step-up authentication
1222                        tracing::info!(
1223                            "CAEP requiring step-up to level {} for subject {}",
1224                            level,
1225                            evaluation.subject
1226                        );
1227                    }
1228                }
1229                CaepRuleAction::SendNotification { channels } => {
1230                    tracing::info!(
1231                        "CAEP sending notification via channels {:?} for subject {}",
1232                        channels,
1233                        evaluation.subject
1234                    );
1235                }
1236                CaepRuleAction::LogEvent { level } => {
1237                    tracing::info!(
1238                        "CAEP logging event at level {} for subject {}",
1239                        level,
1240                        evaluation.subject
1241                    );
1242                }
1243                CaepRuleAction::TriggerWebhook { url } => {
1244                    tracing::info!(
1245                        "CAEP triggering webhook {} for subject {}",
1246                        url,
1247                        evaluation.subject
1248                    );
1249                }
1250                CaepRuleAction::QuarantineSession { duration_minutes } => {
1251                    self.quarantine_session(&evaluation.subject, *duration_minutes)
1252                        .await?;
1253                }
1254            }
1255        }
1256
1257        Ok(())
1258    }
1259
1260    /// Quarantine a session
1261    async fn quarantine_session(&self, subject: &str, duration_minutes: u32) -> Result<()> {
1262        let mut sessions = self.sessions.write().await;
1263        let quarantine_until =
1264            Utc::now() + Duration::try_minutes(duration_minutes as i64).unwrap_or(Duration::zero());
1265
1266        // Update CAEP session state
1267        let mut quarantined_session_ids = Vec::new();
1268        for session in sessions.values_mut() {
1269            if session.subject == subject {
1270                session.is_quarantined = true;
1271                session.quarantine_until = Some(quarantine_until);
1272                quarantined_session_ids.push(session.session_id.clone());
1273            }
1274        }
1275
1276        tracing::info!(
1277            "CAEP quarantined {} sessions for subject {} until {}. Session IDs: {:?}",
1278            quarantined_session_ids.len(),
1279            subject,
1280            quarantine_until,
1281            quarantined_session_ids
1282        );
1283
1284        // In a production implementation, you might want to notify the SessionManager
1285        // about the quarantine status through a separate event or notification system
1286
1287        Ok(())
1288    }
1289
1290    /// Notify registered event handlers
1291    async fn notify_handlers(&self, event: &CaepEvent) -> Result<()> {
1292        let handlers = self.event_handlers.read().await;
1293
1294        if let Some(event_handlers) = handlers.get(&event.event_type) {
1295            for handler in event_handlers {
1296                if let Err(e) = handler.handle_event(event).await {
1297                    tracing::error!("CAEP event handler failed: {}", e);
1298                }
1299            }
1300        }
1301
1302        Ok(())
1303    }
1304
1305    /// Get current session state
1306    pub async fn get_session_state(&self, session_id: &str) -> Result<Option<CaepSessionState>> {
1307        // First validate with SessionManager
1308        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1309            if !self.session_manager.is_session_valid(session_id) {
1310                // Session is expired in SessionManager, remove from CAEP as well
1311                let mut sessions = self.sessions.write().await;
1312                sessions.remove(session_id);
1313                return Ok(None);
1314            }
1315
1316            // Return CAEP session state if it exists and subjects match
1317            let sessions = self.sessions.read().await;
1318            if let Some(caep_session) = sessions.get(session_id) {
1319                if caep_session.subject == oidc_session.sub {
1320                    return Ok(Some(caep_session.clone()));
1321                } else {
1322                    tracing::warn!(
1323                        "Subject mismatch between CAEP and OIDC sessions for {}",
1324                        session_id
1325                    );
1326                    return Ok(None);
1327                }
1328            }
1329        }
1330
1331        // No valid OIDC session found
1332        Ok(None)
1333    }
1334
1335    /// Get event history for a subject
1336    pub async fn get_event_history(
1337        &self,
1338        subject: &str,
1339        limit: Option<usize>,
1340    ) -> Result<Vec<CaepEvent>> {
1341        let history = self.event_history.read().await;
1342        let mut events: Vec<_> = history
1343            .iter()
1344            .filter(|e| e.subject == subject)
1345            .cloned()
1346            .collect();
1347
1348        events.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
1349
1350        if let Some(limit) = limit {
1351            events.truncate(limit);
1352        }
1353
1354        Ok(events)
1355    }
1356
1357    /// Add or update an evaluation rule
1358    pub async fn add_evaluation_rule(&self, rule: CaepEvaluationRule) -> Result<()> {
1359        let mut rules = self.rules.write().await;
1360
1361        // Remove existing rule with same ID
1362        rules.retain(|r| r.id != rule.id);
1363
1364        // Insert new rule and sort by priority
1365        rules.push(rule);
1366        rules.sort_by_key(|r| std::cmp::Reverse(r.priority));
1367
1368        Ok(())
1369    }
1370
1371    /// Remove an evaluation rule
1372    pub async fn remove_evaluation_rule(&self, rule_id: &str) -> Result<bool> {
1373        let mut rules = self.rules.write().await;
1374        let original_len = rules.len();
1375        rules.retain(|r| r.id != rule_id);
1376        Ok(rules.len() < original_len)
1377    }
1378
1379    /// Get comprehensive session information combining OIDC and CAEP data
1380    pub async fn get_comprehensive_session_info(
1381        &self,
1382        session_id: &str,
1383    ) -> Result<Option<ComprehensiveSessionInfo>> {
1384        // Get OIDC session information
1385        if let Some(oidc_session) = self.session_manager.get_session(session_id) {
1386            if !self.session_manager.is_session_valid(session_id) {
1387                return Ok(None);
1388            }
1389
1390            // Get CAEP session information if available
1391            let caep_session = {
1392                let sessions = self.sessions.read().await;
1393                sessions.get(session_id).cloned()
1394            };
1395
1396            let comprehensive_info = ComprehensiveSessionInfo {
1397                oidc_session: oidc_session.clone(),
1398                is_monitored_by_caep: caep_session.is_some(),
1399                caep_session,
1400            };
1401
1402            Ok(Some(comprehensive_info))
1403        } else {
1404            Ok(None)
1405        }
1406    }
1407
1408    /// Get all sessions for a subject with comprehensive information
1409    pub async fn get_subject_sessions(
1410        &self,
1411        subject: &str,
1412    ) -> Result<Vec<ComprehensiveSessionInfo>> {
1413        let oidc_sessions = self.session_manager.get_sessions_for_subject(subject);
1414        let mut comprehensive_sessions = Vec::new();
1415
1416        for oidc_session in oidc_sessions {
1417            if self
1418                .session_manager
1419                .is_session_valid(&oidc_session.session_id)
1420            {
1421                let caep_session = {
1422                    let sessions = self.sessions.read().await;
1423                    sessions.get(&oidc_session.session_id).cloned()
1424                };
1425
1426                comprehensive_sessions.push(ComprehensiveSessionInfo {
1427                    oidc_session: oidc_session.clone(),
1428                    is_monitored_by_caep: caep_session.is_some(),
1429                    caep_session,
1430                });
1431            }
1432        }
1433
1434        Ok(comprehensive_sessions)
1435    }
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440    use super::*;
1441    use tokio;
1442
1443    #[tokio::test]
1444    async fn test_caep_event_creation() {
1445        let event = CaepEvent {
1446            id: Uuid::new_v4(),
1447            event_type: CaepEventType::RiskScoreChange,
1448            subject: "user123".to_string(),
1449            severity: CaepEventSeverity::High,
1450            timestamp: Utc::now(),
1451            source: CaepEventSource {
1452                system_id: "risk_engine".to_string(),
1453                source_type: "ml_model".to_string(),
1454                version: Some("1.0.0".to_string()),
1455                metadata: HashMap::new(),
1456            },
1457            risk_score: 0.85,
1458            session_id: Some("session123".to_string()),
1459            location: None,
1460            device_info: None,
1461            event_data: serde_json::json!({
1462                "previous_score": 0.3,
1463                "new_score": 0.85,
1464                "trigger": "suspicious_login_pattern"
1465            }),
1466            correlation_id: None,
1467        };
1468
1469        assert_eq!(event.subject, "user123");
1470        assert_eq!(event.risk_score, 0.85);
1471        assert!(matches!(event.severity, CaepEventSeverity::High));
1472    }
1473
1474    #[tokio::test]
1475    async fn test_caep_config_creation() {
1476        let config = CaepConfig::default();
1477        assert!(!config.event_stream_url.is_empty());
1478        assert!(config.auto_revoke);
1479        assert_eq!(config.auto_revoke_threshold, 0.8);
1480    }
1481
1482    #[tokio::test]
1483    async fn test_severity_comparison() {
1484        // Test severity level comparison logic
1485        let high_level = match CaepEventSeverity::High {
1486            CaepEventSeverity::Critical => 4,
1487            CaepEventSeverity::High => 3,
1488            CaepEventSeverity::Medium => 2,
1489            CaepEventSeverity::Low => 1,
1490        };
1491
1492        let medium_level = match CaepEventSeverity::Medium {
1493            CaepEventSeverity::Critical => 4,
1494            CaepEventSeverity::High => 3,
1495            CaepEventSeverity::Medium => 2,
1496            CaepEventSeverity::Low => 1,
1497        };
1498
1499        assert!(high_level > medium_level);
1500    }
1501}