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