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