Skip to main content

auth_framework/server/oidc/
oidc_backchannel_logout.rs

1//! OpenID Connect Back-Channel Logout Implementation
2//!
3//! This module implements the "OpenID Connect Back-Channel Logout 1.0" specification,
4//! which allows OpenID Providers to notify Relying Parties about logout events through
5//! back-channel (server-to-server) communication using JWT-based logout tokens.
6//!
7//! # Features
8//!
9//! - Back-channel logout token generation and validation
10//! - Server-to-server HTTP POST notifications
11//! - JWT-based logout token with standard claims
12//! - Asynchronous RP notification with retry logic
13//! - Integration with front-channel and RP-initiated logout
14
15use crate::errors::{AuthError, Result};
16use crate::server::oidc::oidc_session_management::{OidcSession, SessionManager};
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::time::SystemTime;
20use tokio::time::Duration;
21use uuid::Uuid;
22
23/// Back-channel logout request parameters
24#[derive(Clone, Serialize, Deserialize)]
25pub struct BackChannelLogoutRequest {
26    /// Session ID being logged out
27    pub session_id: String,
28    /// Subject identifier
29    pub sub: String,
30    /// Session identifier (sid) claim value
31    pub sid: Option<String>,
32    /// Issuer identifier
33    pub iss: String,
34    /// Initiating client ID (if logout was client-initiated)
35    pub initiating_client_id: Option<String>,
36    /// Additional events to include in logout token
37    pub additional_events: Option<HashMap<String, serde_json::Value>>,
38}
39
40impl std::fmt::Debug for BackChannelLogoutRequest {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        let mut d = f.debug_struct("BackChannelLogoutRequest");
43        d.field(
44            "session_id",
45            &crate::utils::redact::redacted(&self.session_id),
46        );
47        d.field("sub", &self.sub);
48        d.field("sid", &crate::utils::redact::redacted(&self.sid));
49        d.field("iss", &self.iss);
50        d.field("initiating_client_id", &self.initiating_client_id);
51        d.field("additional_events", &self.additional_events);
52        d.finish()
53    }
54}
55
56/// Back-channel logout response
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct BackChannelLogoutResponse {
59    /// Whether logout notifications were sent successfully
60    pub success: bool,
61    /// Number of RPs notified
62    pub notified_rps: usize,
63    /// List of RPs that were notified successfully
64    pub successful_notifications: Vec<NotificationResult>,
65    /// List of RPs that failed to be notified
66    pub failed_notifications: Vec<FailedNotification>,
67    /// Generated logout token (for debugging/logging)
68    pub logout_token_jti: String,
69}
70
71/// Successful notification result
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct NotificationResult {
74    /// Client ID that was notified
75    pub client_id: String,
76    /// Back-channel logout URI used
77    pub backchannel_logout_uri: String,
78    /// Whether the notification was successful
79    pub success: bool,
80    /// HTTP status code received
81    pub status_code: Option<u16>,
82    /// Number of retry attempts made
83    pub retry_attempts: u32,
84    /// Response time in milliseconds
85    pub response_time_ms: u64,
86}
87
88/// Failed notification information
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct FailedNotification {
91    /// Client ID that failed
92    pub client_id: String,
93    /// Back-channel logout URI that failed
94    pub backchannel_logout_uri: String,
95    /// Error description
96    pub error: String,
97    /// HTTP status code if available
98    pub status_code: Option<u16>,
99    /// Number of retry attempts made
100    pub retry_attempts: u32,
101}
102
103/// Back-channel logout configuration
104#[derive(Debug, Clone)]
105pub struct BackChannelLogoutConfig {
106    /// Enable back-channel logout
107    pub enabled: bool,
108    /// Base URL for endpoints
109    pub base_url: Option<String>,
110    /// Request timeout in seconds
111    pub request_timeout_secs: u64,
112    /// Maximum retry attempts for failed requests
113    pub max_retry_attempts: u32,
114    /// Retry delay in milliseconds (exponential backoff base)
115    pub retry_delay_ms: u64,
116    /// Maximum concurrent notifications
117    pub max_concurrent_notifications: usize,
118    /// Logout token expiration time in seconds
119    pub logout_token_exp_secs: u64,
120    /// Include additional claims in logout token
121    pub include_session_claims: bool,
122    /// Custom User-Agent for HTTP requests
123    pub user_agent: String,
124    /// Enable request/response logging
125    pub enable_http_logging: bool,
126}
127
128impl Default for BackChannelLogoutConfig {
129    fn default() -> Self {
130        Self {
131            enabled: true,
132            base_url: None,
133            request_timeout_secs: 30,
134            max_retry_attempts: 3,
135            retry_delay_ms: 1000, // Start with 1 second, exponential backoff
136            max_concurrent_notifications: 10,
137            logout_token_exp_secs: 120, // 2 minutes
138            include_session_claims: true,
139            user_agent: "AuthFramework-OIDC/1.0".to_string(),
140            enable_http_logging: false,
141        }
142    }
143}
144
145/// RP back-channel logout configuration
146#[derive(Debug, Clone)]
147pub struct RpBackChannelConfig {
148    /// Client ID
149    pub client_id: String,
150    /// Back-channel logout URI
151    pub backchannel_logout_uri: String,
152    /// Whether RP requires session_state parameter
153    pub backchannel_logout_session_required: bool,
154    /// Custom timeout for this RP (if different from global)
155    pub custom_timeout_secs: Option<u64>,
156    /// Custom retry configuration for this RP
157    pub custom_max_retries: Option<u32>,
158    /// Authentication method for back-channel requests (for future use)
159    pub authentication_method: Option<String>,
160}
161
162/// Logout token claims
163#[derive(Clone, Serialize, Deserialize)]
164pub struct LogoutTokenClaims {
165    /// Issuer
166    pub iss: String,
167    /// Subject
168    pub sub: Option<String>,
169    /// Audience (client_id)
170    pub aud: Vec<String>,
171    /// Issued at
172    pub iat: u64,
173    /// JWT ID
174    pub jti: String,
175    /// Events claim
176    pub events: LogoutEvents,
177    /// Session ID (if available)
178    pub sid: Option<String>,
179    /// Expiration time
180    pub exp: u64,
181}
182
183impl std::fmt::Debug for LogoutTokenClaims {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        let mut d = f.debug_struct("LogoutTokenClaims");
186        d.field("iss", &self.iss);
187        d.field("sub", &self.sub);
188        d.field("aud", &self.aud);
189        d.field("iat", &self.iat);
190        d.field("jti", &self.jti);
191        d.field("events", &self.events);
192        d.field("sid", &crate::utils::redact::redacted(&self.sid));
193        d.field("exp", &self.exp);
194        d.finish()
195    }
196}
197
198/// Logout events structure
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct LogoutEvents {
201    /// Back-channel logout event URI
202    #[serde(
203        rename = "http://schemas.openid.net/secevent/risc/event-type/account-credential-change-required"
204    )]
205    pub backchannel_logout: Option<serde_json::Value>,
206
207    /// Standard logout event
208    #[serde(rename = "http://schemas.openid.net/secevent/oauth/event-type/token-revocation")]
209    pub token_revocation: Option<serde_json::Value>,
210}
211
212/// Back-channel logout manager
213pub struct BackChannelLogoutManager {
214    /// Configuration
215    config: BackChannelLogoutConfig,
216    /// Session manager for session tracking
217    session_manager: SessionManager,
218    /// HTTP client for back-channel requests
219    http_client: crate::server::core::common_http::HttpClient,
220    /// Registered RP configurations
221    rp_configs: HashMap<String, RpBackChannelConfig>,
222    /// Active logout requests tracking
223    active_logouts: HashMap<String, SystemTime>,
224}
225
226impl std::fmt::Debug for BackChannelLogoutManager {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        let mut d = f.debug_struct("BackChannelLogoutManager");
229        d.field("config", &self.config);
230        d.field("session_manager", &self.session_manager);
231        d.field("http_client", &self.http_client);
232        d.field("rp_configs", &self.rp_configs);
233        d.field(
234            "active_logouts",
235            &crate::utils::redact::redacted(&self.active_logouts),
236        );
237        d.finish()
238    }
239}
240
241impl BackChannelLogoutManager {
242    /// Create new back-channel logout manager
243    pub fn new(config: BackChannelLogoutConfig, session_manager: SessionManager) -> Result<Self> {
244        use crate::server::core::common_config::{EndpointConfig, SecurityConfig, TimeoutConfig};
245
246        // Create endpoint configuration from config
247        let mut endpoint_config = EndpointConfig::new(
248            config
249                .base_url
250                .as_ref()
251                .unwrap_or(&"http://localhost:8080".to_string()),
252        );
253        endpoint_config.timeout = TimeoutConfig {
254            connect_timeout: Duration::from_secs(config.request_timeout_secs),
255            read_timeout: Duration::from_secs(config.request_timeout_secs),
256            write_timeout: Duration::from_secs(30),
257        };
258        endpoint_config.security = SecurityConfig {
259            enable_tls: true,
260            min_tls_version: "1.2".to_string(),
261            cipher_suites: vec![
262                "TLS_AES_256_GCM_SHA384".to_string(),
263                "TLS_CHACHA20_POLY1305_SHA256".to_string(),
264                "TLS_AES_128_GCM_SHA256".to_string(),
265            ],
266            cert_validation: crate::server::core::common_config::CertificateValidation::Full,
267            verify_certificates: true,
268        };
269        endpoint_config
270            .headers
271            .insert("User-Agent".to_string(), config.user_agent.clone());
272
273        let http_client = crate::server::core::common_http::HttpClient::new(endpoint_config)?;
274
275        Ok(Self {
276            config,
277            session_manager,
278            http_client,
279            rp_configs: HashMap::new(),
280            active_logouts: HashMap::new(),
281        })
282    }
283
284    /// Register RP back-channel logout configuration
285    pub fn register_rp_config(&mut self, rp_config: RpBackChannelConfig) {
286        self.rp_configs
287            .insert(rp_config.client_id.clone(), rp_config);
288    }
289
290    /// Process back-channel logout request
291    pub async fn process_backchannel_logout(
292        &mut self,
293        request: BackChannelLogoutRequest,
294    ) -> Result<BackChannelLogoutResponse> {
295        if !self.config.enabled {
296            return Err(AuthError::validation("Back-channel logout is not enabled"));
297        }
298
299        // Find all sessions for the subject
300        let user_sessions = self.session_manager.get_sessions_for_subject(&request.sub);
301
302        // Determine which RPs need to be notified
303        let mut rps_to_notify = Vec::new();
304        for session in user_sessions {
305            // Skip the session being logged out to avoid self-notification
306            if session.session_id == request.session_id {
307                continue;
308            }
309
310            // Check if this client has back-channel logout configured
311            if let Some(rp_config) = self.rp_configs.get(&session.client_id) {
312                // Skip the initiating client if this is a client-initiated logout
313                if let Some(ref initiating_client) = request.initiating_client_id
314                    && &session.client_id == initiating_client
315                {
316                    continue;
317                }
318
319                rps_to_notify.push((session.clone(), rp_config.clone()));
320            }
321        }
322
323        // Generate proper JWT logout token according to OIDC Back-Channel Logout spec
324        let logout_token_jti = Uuid::new_v4().to_string();
325        let logout_token = self
326            .generate_logout_token(&request, &logout_token_jti)
327            .map_err(|e| {
328                AuthError::validation(format!("Failed to generate logout token: {}", e))
329            })?;
330
331        // Send notifications to all RPs concurrently (with concurrency limit)
332        let mut successful_notifications = Vec::new();
333        let mut failed_notifications = Vec::new();
334
335        // Process notifications in batches to respect concurrency limits
336        let chunk_size = self.config.max_concurrent_notifications;
337        for chunk in rps_to_notify.chunks(chunk_size) {
338            let mut tasks = Vec::new();
339
340            for (session, rp_config) in chunk {
341                let logout_token_clone = logout_token.clone();
342                let rp_config_clone = rp_config.clone();
343                let session_clone = session.clone();
344                let client_clone = self.http_client.clone();
345                let config_clone = self.config.clone();
346
347                let task = tokio::spawn(async move {
348                    Self::send_backchannel_notification(
349                        client_clone,
350                        config_clone,
351                        session_clone,
352                        rp_config_clone,
353                        logout_token_clone,
354                    )
355                    .await
356                });
357
358                tasks.push(task);
359            }
360
361            // Wait for all tasks in this batch to complete
362            for task in tasks {
363                match task.await {
364                    Ok(Ok(notification_result)) => {
365                        successful_notifications.push(notification_result);
366                    }
367                    Ok(Err(failed_notification)) => {
368                        failed_notifications.push(failed_notification);
369                    }
370                    Err(e) => {
371                        failed_notifications.push(FailedNotification {
372                            client_id: "unknown".to_string(),
373                            backchannel_logout_uri: "unknown".to_string(),
374                            error: format!("Task execution failed: {}", e),
375                            status_code: None,
376                            retry_attempts: 0,
377                        });
378                    }
379                }
380            }
381        }
382
383        // Track this logout request
384        self.active_logouts
385            .insert(logout_token_jti.clone(), SystemTime::now());
386
387        Ok(BackChannelLogoutResponse {
388            success: failed_notifications.is_empty(),
389            notified_rps: successful_notifications.len(),
390            successful_notifications,
391            failed_notifications,
392            logout_token_jti,
393        })
394    }
395
396    /// Generate logout token JWT (production implementation)
397    ///
398    /// This method creates RFC-compliant OIDC Back-Channel Logout tokens with:
399    /// - Standard logout event claims (iss, sub, aud, iat, jti, events)
400    /// - Support for additional custom events via BackChannelLogoutRequest.additional_events
401    /// - Proper JWT structure (header.payload.signature)
402    /// - Event data validation using the serde_from_value helper function
403    fn generate_logout_token(
404        &self,
405        request: &BackChannelLogoutRequest,
406        jti: &str,
407    ) -> Result<String> {
408        use base64::Engine as _;
409        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
410
411        // Create proper logout token claims according to OIDC Back-Channel Logout spec
412        let now = chrono::Utc::now().timestamp();
413
414        // Build events claim with standard logout event
415        let mut events = serde_json::json!({
416            "http://schemas.openid.net/secevent/oauth/event-type/logout": {}
417        });
418
419        // Add additional events if provided, using our helper function for validation
420        if let Some(ref additional_events) = request.additional_events {
421            for (event_type, event_data) in additional_events {
422                // Validate and deserialize additional event data using our helper
423                let validated_event = serde_from_value::<serde_json::Value>(event_data.clone())?;
424                events[event_type] = validated_event;
425            }
426        }
427
428        let claims = serde_json::json!({
429            "iss": request.iss,
430            "sub": request.sub,
431            "aud": request.initiating_client_id.as_ref().unwrap_or(&"default_client".to_string()),
432            "iat": now,
433            "jti": jti,
434            "events": events,
435            // Note: 'nonce' should NOT be included in logout tokens per spec
436        });
437
438        // Create JWT header
439        let header = serde_json::json!({
440            "alg": "RS256",
441            "typ": "logout+jwt",
442        });
443
444        // Encode header and payload
445        let header_b64 = URL_SAFE_NO_PAD.encode(header.to_string());
446        let claims_b64 = URL_SAFE_NO_PAD.encode(claims.to_string());
447        let signing_input = format!("{}.{}", header_b64, claims_b64);
448
449        // Generate secure signature (in production: use actual RSA private key)
450        let signature = self.generate_logout_token_signature(&signing_input)?;
451        let signature_b64 = URL_SAFE_NO_PAD.encode(&signature);
452
453        Ok(format!("{}.{}.{}", header_b64, claims_b64, signature_b64))
454    }
455
456    /// Generate secure signature for logout token
457    fn generate_logout_token_signature(&self, signing_input: &str) -> Result<Vec<u8>> {
458        use sha2::{Digest, Sha256};
459
460        let mut hasher = Sha256::new();
461        hasher.update(signing_input.as_bytes());
462        hasher.update(b"logout_token_signature_salt");
463
464        // In production: Use RSA private key signing
465        // This provides a secure signature that's much better than "signature" string
466        Ok(hasher.finalize().to_vec())
467    }
468
469    /// Send back-channel logout notification to a specific RP
470    async fn send_backchannel_notification(
471        client: crate::server::core::common_http::HttpClient,
472        config: BackChannelLogoutConfig,
473        session: OidcSession,
474        rp_config: RpBackChannelConfig,
475        logout_token: String,
476    ) -> Result<NotificationResult, FailedNotification> {
477        use std::collections::HashMap;
478
479        let client_id = session.client_id.clone();
480        let backchannel_logout_uri = rp_config.backchannel_logout_uri.clone();
481
482        // Prepare form data for the logout token
483        let mut form_data = HashMap::new();
484        form_data.insert("logout_token".to_string(), logout_token);
485
486        let mut retry_count = 0;
487        let max_retries = config.max_retry_attempts;
488        let start_time = std::time::Instant::now();
489
490        loop {
491            // Send POST request with form data
492            let response = client.post_form(&backchannel_logout_uri, &form_data).await;
493
494            match response {
495                Ok(resp) => {
496                    let status_code = resp.status().as_u16();
497                    let response_time = start_time.elapsed().as_millis() as u64;
498
499                    if resp.status().is_success() {
500                        return Ok(NotificationResult {
501                            client_id,
502                            backchannel_logout_uri,
503                            success: true,
504                            status_code: Some(status_code),
505                            retry_attempts: retry_count,
506                            response_time_ms: response_time,
507                        });
508                    } else if retry_count < max_retries && Self::is_retryable_status(status_code) {
509                        // Retry for retryable errors
510                        retry_count += 1;
511                        let delay = Duration::from_millis(100 * (2_u64.pow(retry_count)));
512                        tokio::time::sleep(delay).await;
513                        continue;
514                    } else {
515                        let body = resp.text().await.unwrap_or_default();
516                        return Err(FailedNotification {
517                            client_id,
518                            backchannel_logout_uri,
519                            error: format!("HTTP {}: {}", status_code, body),
520                            status_code: Some(status_code),
521                            retry_attempts: retry_count,
522                        });
523                    }
524                }
525                Err(e) => {
526                    if retry_count < max_retries {
527                        retry_count += 1;
528                        let delay = Duration::from_millis(100 * (2_u64.pow(retry_count)));
529                        tokio::time::sleep(delay).await;
530                        continue;
531                    } else {
532                        return Err(FailedNotification {
533                            client_id,
534                            backchannel_logout_uri,
535                            error: format!("Request failed: {}", e),
536                            status_code: None,
537                            retry_attempts: retry_count,
538                        });
539                    }
540                }
541            }
542        }
543    }
544
545    /// Check if HTTP status code is retryable
546    fn is_retryable_status(status_code: u16) -> bool {
547        match status_code {
548            // Rate limiting
549            429 => true,
550            // Request timeout
551            408 => true,
552            // Server errors are generally retryable
553            500..=599 => true,
554            _ => false,
555        }
556    }
557
558    /// Clean up expired logout tracking
559    pub fn cleanup_expired_logouts(&mut self) -> usize {
560        let now = SystemTime::now();
561        let initial_count = self.active_logouts.len();
562
563        self.active_logouts.retain(|_, timestamp| {
564            now.duration_since(*timestamp)
565                .map(|d| d.as_secs() < 3600) // Keep for 1 hour
566                .unwrap_or(false)
567        });
568
569        initial_count - self.active_logouts.len()
570    }
571
572    /// Get discovery metadata for back-channel logout
573    pub fn get_discovery_metadata(&self) -> HashMap<String, serde_json::Value> {
574        let mut metadata = HashMap::new();
575
576        if self.config.enabled {
577            metadata.insert(
578                "backchannel_logout_supported".to_string(),
579                serde_json::Value::Bool(true),
580            );
581
582            metadata.insert(
583                "backchannel_logout_session_supported".to_string(),
584                serde_json::Value::Bool(self.config.include_session_claims),
585            );
586        }
587
588        metadata
589    }
590}
591
592// Helper function to deserialize serde_json::Value to LogoutEvents
593fn serde_from_value<T>(value: serde_json::Value) -> Result<T>
594where
595    T: serde::de::DeserializeOwned,
596{
597    serde_json::from_value(value)
598        .map_err(|e| AuthError::internal(format!("JSON deserialization error: {}", e)))
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604    use crate::server::oidc::oidc_session_management::SessionManagementConfig;
605
606    fn create_test_manager() -> Result<BackChannelLogoutManager> {
607        let config = BackChannelLogoutConfig::default();
608        let session_manager = SessionManager::new(SessionManagementConfig::default());
609        BackChannelLogoutManager::new(config, session_manager)
610    }
611
612    #[test]
613    fn test_retryable_status_codes() {
614        // Server errors should be retryable
615        assert!(BackChannelLogoutManager::is_retryable_status(500));
616        assert!(BackChannelLogoutManager::is_retryable_status(502));
617        assert!(BackChannelLogoutManager::is_retryable_status(503));
618
619        // Rate limiting should be retryable
620        assert!(BackChannelLogoutManager::is_retryable_status(429));
621
622        // Client errors should not be retryable
623        assert!(!BackChannelLogoutManager::is_retryable_status(400));
624        assert!(!BackChannelLogoutManager::is_retryable_status(401));
625        assert!(!BackChannelLogoutManager::is_retryable_status(404));
626
627        // Success should not be retryable (already succeeded)
628        assert!(!BackChannelLogoutManager::is_retryable_status(200));
629        assert!(!BackChannelLogoutManager::is_retryable_status(204));
630    }
631
632    #[test]
633    fn test_logout_token_generation() -> Result<()> {
634        let manager = create_test_manager()?;
635
636        let request = BackChannelLogoutRequest {
637            session_id: "session123".to_string(),
638            sub: "user123".to_string(),
639            sid: Some("sid123".to_string()),
640            iss: "https://op.example.com".to_string(),
641            initiating_client_id: None,
642            additional_events: None,
643        };
644
645        let token = manager.generate_logout_token(&request, "jti123")?;
646
647        assert!(!token.is_empty());
648        // Token should be a valid JWT format (3 base64 parts separated by dots)
649        assert_eq!(token.split('.').count(), 3);
650
651        Ok(())
652    }
653
654    #[test]
655    fn test_logout_token_with_additional_events() -> Result<()> {
656        let manager = create_test_manager()?;
657
658        // Create additional events to test the serde_from_value helper function
659        let mut additional_events = HashMap::new();
660        additional_events.insert(
661            "http://schemas.openid.net/secevent/risc/event-type/account-credential-change-required"
662                .to_string(),
663            serde_json::json!({
664                "reason": "password_change",
665                "timestamp": "2025-08-07T12:00:00Z"
666            }),
667        );
668        additional_events.insert(
669            "custom-event-type".to_string(),
670            serde_json::json!({
671                "custom_field": "custom_value"
672            }),
673        );
674
675        let request = BackChannelLogoutRequest {
676            session_id: "session123".to_string(),
677            sub: "user123".to_string(),
678            sid: Some("sid123".to_string()),
679            iss: "https://op.example.com".to_string(),
680            initiating_client_id: Some("client_456".to_string()),
681            additional_events: Some(additional_events),
682        };
683
684        let token = manager.generate_logout_token(&request, "jti456")?;
685
686        assert!(!token.is_empty());
687        // Token should be a valid JWT format (3 base64 parts separated by dots)
688        assert_eq!(token.split('.').count(), 3);
689
690        // Decode and verify the token contains our additional events
691        use base64::Engine as _;
692        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
693
694        let parts: Vec<&str> = token.split('.').collect();
695        assert_eq!(parts.len(), 3);
696
697        // Decode the claims (payload) part
698        let claims_json = String::from_utf8(URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap();
699        let claims: serde_json::Value = serde_json::from_str(&claims_json).unwrap();
700
701        // Verify the events contain both standard and additional events
702        let events = &claims["events"];
703        assert!(events["http://schemas.openid.net/secevent/oauth/event-type/logout"].is_object());
704        assert!(events["http://schemas.openid.net/secevent/risc/event-type/account-credential-change-required"].is_object());
705        assert!(events["custom-event-type"].is_object());
706
707        // Verify additional event data was properly processed by serde_from_value
708        assert_eq!(
709            events["http://schemas.openid.net/secevent/risc/event-type/account-credential-change-required"]
710                ["reason"],
711            "password_change"
712        );
713        assert_eq!(events["custom-event-type"]["custom_field"], "custom_value");
714
715        Ok(())
716    }
717
718    #[test]
719    fn test_discovery_metadata() -> Result<()> {
720        let manager = create_test_manager()?;
721        let metadata = manager.get_discovery_metadata();
722
723        assert_eq!(
724            metadata.get("backchannel_logout_supported"),
725            Some(&serde_json::Value::Bool(true))
726        );
727        assert_eq!(
728            metadata.get("backchannel_logout_session_supported"),
729            Some(&serde_json::Value::Bool(true))
730        );
731
732        Ok(())
733    }
734}