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