Skip to main content

auth_framework/server/oidc/
oidc_frontchannel_logout.rs

1//! OpenID Connect Front-Channel Logout Implementation
2//!
3//! This module implements the "OpenID Connect Front-Channel Logout 1.0" specification,
4//! which allows OpenID Providers to notify Relying Parties about logout events through
5//! front-channel (browser) communication using invisible iframes.
6//!
7//! # Features
8//!
9//! - Front-channel logout notification management
10//! - Invisible iframe-based RP notification
11//! - Session identifier (sid) tracking
12//! - Logout token generation and validation
13//! - Integration with 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 uuid::Uuid;
21
22/// Front-channel logout request parameters
23#[derive(Clone, Serialize, Deserialize)]
24pub struct FrontChannelLogoutRequest {
25    /// Session ID being logged out
26    pub session_id: String,
27    /// Subject identifier
28    pub sub: String,
29    /// Session identifier (sid) claim value
30    pub sid: Option<String>,
31    /// Issuer identifier
32    pub iss: String,
33    /// Initiating client ID (if logout was client-initiated)
34    pub initiating_client_id: Option<String>,
35}
36
37impl std::fmt::Debug for FrontChannelLogoutRequest {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        let mut d = f.debug_struct("FrontChannelLogoutRequest");
40        d.field(
41            "session_id",
42            &crate::utils::redact::redacted(&self.session_id),
43        );
44        d.field("sub", &self.sub);
45        d.field("sid", &crate::utils::redact::redacted(&self.sid));
46        d.field("iss", &self.iss);
47        d.field("initiating_client_id", &self.initiating_client_id);
48        d.finish()
49    }
50}
51
52/// Front-channel logout response
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct FrontChannelLogoutResponse {
55    /// Whether logout notifications were sent successfully
56    pub success: bool,
57    /// Number of RPs notified
58    pub notified_rps: usize,
59    /// List of RPs that were notified
60    pub notified_clients: Vec<String>,
61    /// List of RPs that failed to be notified
62    pub failed_notifications: Vec<FailedNotification>,
63    /// HTML content for front-channel logout page
64    pub logout_page_html: String,
65}
66
67/// Failed notification information
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct FailedNotification {
70    /// Client ID that failed
71    pub client_id: String,
72    /// Front-channel logout URI that failed
73    pub frontchannel_logout_uri: String,
74    /// Error description
75    pub error: String,
76}
77
78/// Front-channel logout configuration
79#[derive(Debug, Clone)]
80pub struct FrontChannelLogoutConfig {
81    /// Enable front-channel logout
82    pub enabled: bool,
83    /// Maximum time to wait for iframe loads (milliseconds)
84    pub iframe_timeout_ms: u64,
85    /// Maximum number of concurrent iframe notifications
86    pub max_concurrent_notifications: usize,
87    /// Include session_state parameter in logout URIs
88    pub include_session_state: bool,
89    /// Default iframe dimensions
90    pub iframe_width: u32,
91    pub iframe_height: u32,
92    /// Enable JavaScript console logging for debugging
93    pub enable_debug_logging: bool,
94}
95
96impl Default for FrontChannelLogoutConfig {
97    fn default() -> Self {
98        Self {
99            enabled: true,
100            iframe_timeout_ms: 5000, // 5 seconds
101            max_concurrent_notifications: 10,
102            include_session_state: true,
103            iframe_width: 0,  // Hidden iframe
104            iframe_height: 0, // Hidden iframe
105            enable_debug_logging: false,
106        }
107    }
108}
109
110/// RP front-channel logout configuration
111#[derive(Debug, Clone)]
112pub struct RpFrontChannelConfig {
113    /// Client ID
114    pub client_id: String,
115    /// Front-channel logout URI
116    pub frontchannel_logout_uri: String,
117    /// Whether RP requires session_state parameter
118    pub frontchannel_logout_session_required: bool,
119    /// Custom timeout for this RP (if different from global)
120    pub custom_timeout_ms: Option<u64>,
121}
122
123/// Front-channel logout manager
124#[derive(Clone)]
125pub struct FrontChannelLogoutManager {
126    /// Configuration
127    config: FrontChannelLogoutConfig,
128    /// Session manager for session tracking
129    session_manager: SessionManager,
130    /// Registered RP configurations
131    rp_configs: HashMap<String, RpFrontChannelConfig>,
132    /// Active logout requests tracking
133    active_logouts: HashMap<String, SystemTime>,
134}
135
136impl std::fmt::Debug for FrontChannelLogoutManager {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        let mut d = f.debug_struct("FrontChannelLogoutManager");
139        d.field("config", &self.config);
140        d.field("session_manager", &self.session_manager);
141        d.field("rp_configs", &self.rp_configs);
142        d.field(
143            "active_logouts",
144            &crate::utils::redact::redacted(&self.active_logouts),
145        );
146        d.finish()
147    }
148}
149
150impl FrontChannelLogoutManager {
151    /// Create new front-channel logout manager
152    pub fn new(config: FrontChannelLogoutConfig, session_manager: SessionManager) -> Self {
153        Self {
154            config,
155            session_manager,
156            rp_configs: HashMap::new(),
157            active_logouts: HashMap::new(),
158        }
159    }
160
161    /// Register RP front-channel logout configuration
162    pub fn register_rp_config(&mut self, rp_config: RpFrontChannelConfig) {
163        self.rp_configs
164            .insert(rp_config.client_id.clone(), rp_config);
165    }
166
167    /// Process front-channel logout request
168    pub async fn process_frontchannel_logout(
169        &mut self,
170        request: FrontChannelLogoutRequest,
171    ) -> Result<FrontChannelLogoutResponse> {
172        if !self.config.enabled {
173            return Err(AuthError::validation("Front-channel logout is not enabled"));
174        }
175
176        // Find all sessions for the subject
177        let user_sessions = self.session_manager.get_sessions_for_subject(&request.sub);
178
179        // Determine which RPs need to be notified
180        let mut rps_to_notify = Vec::new();
181        let mut notified_clients = Vec::new();
182        let mut failed_notifications = Vec::new();
183
184        for session in user_sessions {
185            // Skip the session being logged out to avoid self-notification
186            if session.session_id == request.session_id {
187                continue;
188            }
189
190            // Check if this client has front-channel logout configured
191            if let Some(rp_config) = self.rp_configs.get(&session.client_id) {
192                // Skip the initiating client if this is a client-initiated logout
193                if let Some(ref initiating_client) = request.initiating_client_id
194                    && &session.client_id == initiating_client
195                {
196                    continue;
197                }
198
199                rps_to_notify.push((session.clone(), rp_config.clone()));
200            }
201        }
202
203        // Generate front-channel logout URLs for each RP
204        let mut iframe_urls = Vec::new();
205        for (session, rp_config) in &rps_to_notify {
206            match self.build_frontchannel_logout_url(session, rp_config, &request) {
207                Ok(url) => {
208                    iframe_urls.push((
209                        rp_config.client_id.clone(),
210                        url,
211                        rp_config.custom_timeout_ms,
212                    ));
213                    notified_clients.push(rp_config.client_id.clone());
214                }
215                Err(e) => {
216                    failed_notifications.push(FailedNotification {
217                        client_id: rp_config.client_id.clone(),
218                        frontchannel_logout_uri: rp_config.frontchannel_logout_uri.clone(),
219                        error: e.to_string(),
220                    });
221                }
222            }
223        }
224
225        // Generate the HTML page with hidden iframes
226        let logout_page_html = self.generate_frontchannel_logout_html(&iframe_urls);
227
228        // Track this logout request
229        let logout_id = Uuid::new_v4().to_string();
230        self.active_logouts.insert(logout_id, SystemTime::now());
231
232        Ok(FrontChannelLogoutResponse {
233            success: failed_notifications.is_empty(),
234            notified_rps: notified_clients.len(),
235            notified_clients,
236            failed_notifications,
237            logout_page_html,
238        })
239    }
240
241    /// Build front-channel logout URL for an RP
242    fn build_frontchannel_logout_url(
243        &self,
244        session: &OidcSession,
245        rp_config: &RpFrontChannelConfig,
246        logout_request: &FrontChannelLogoutRequest,
247    ) -> Result<String> {
248        let mut url = rp_config.frontchannel_logout_uri.clone();
249        let mut params = Vec::new();
250
251        // Add issuer parameter
252        params.push(format!("iss={}", urlencoding::encode(&logout_request.iss)));
253
254        // Add session identifier if available and required/configured
255        if self.config.include_session_state || rp_config.frontchannel_logout_session_required {
256            if let Some(sid) = &logout_request.sid {
257                params.push(format!("sid={}", urlencoding::encode(sid)));
258            } else {
259                // Generate sid from session if not provided
260                let sid = format!("sess_{}", &session.session_id[..8]);
261                params.push(format!("sid={}", urlencoding::encode(&sid)));
262            }
263        }
264
265        // Combine URL with parameters
266        let separator = if url.contains('?') { "&" } else { "?" };
267        if !params.is_empty() {
268            url = format!("{}{}{}", url, separator, params.join("&"));
269        }
270
271        // Validate the resulting URL
272        if !self.is_valid_frontchannel_url(&url) {
273            return Err(AuthError::validation("Invalid front-channel logout URL"));
274        }
275
276        Ok(url)
277    }
278
279    /// Validate front-channel logout URL
280    fn is_valid_frontchannel_url(&self, url: &str) -> bool {
281        // Basic URL validation
282        if url.is_empty() {
283            return false;
284        }
285
286        // Must be HTTPS in production (allow HTTP for localhost development)
287        if !url.starts_with("https://")
288            && !url.starts_with("http://localhost")
289            && !url.starts_with("http://127.0.0.1")
290        {
291            return false;
292        }
293
294        // Check for prohibited characters that could cause issues
295        if url.contains('\n') || url.contains('\r') || url.contains('<') || url.contains('>') {
296            return false;
297        }
298
299        true
300    }
301
302    /// Generate HTML page with hidden iframes for front-channel logout
303    fn generate_frontchannel_logout_html(
304        &self,
305        iframe_urls: &[(String, String, Option<u64>)],
306    ) -> String {
307        let mut iframes_html = String::new();
308        let mut timeout_scripts = String::new();
309
310        for (i, (client_id, url, custom_timeout)) in iframe_urls.iter().enumerate() {
311            let timeout = custom_timeout.unwrap_or(self.config.iframe_timeout_ms);
312
313            iframes_html.push_str(&format!(
314                r#"        <iframe id="fc_logout_{}" src="{}" width="{}" height="{}" style="display:none; visibility:hidden;"
315                onload="handleIframeLoad('{}')"
316                onerror="handleIframeError('{}')"></iframe>
317"#,
318                i, url, self.config.iframe_width, self.config.iframe_height, client_id, client_id
319            ));
320
321            // Add timeout for each iframe
322            timeout_scripts.push_str(&format!(
323                r#"            setTimeout(function() {{
324                handleIframeTimeout('{}', {});
325            }}, {});
326"#,
327                client_id, i, timeout
328            ));
329        }
330
331        let debug_logging = if self.config.enable_debug_logging {
332            "const DEBUG_LOGGING = true;"
333        } else {
334            "const DEBUG_LOGGING = false;"
335        };
336
337        format!(
338            r#"<!DOCTYPE html>
339<html>
340<head>
341    <title>Logging Out...</title>
342    <style>
343        body {{
344            font-family: Arial, sans-serif;
345            margin: 40px;
346            text-align: center;
347            background-color: #f8f9fa;
348        }}
349        .logout-container {{
350            max-width: 400px;
351            margin: 50px auto;
352            background: white;
353            padding: 40px;
354            border-radius: 8px;
355            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
356        }}
357        .spinner {{
358            border: 4px solid #f3f3f3;
359            border-top: 4px solid #007bff;
360            border-radius: 50%;
361            width: 50px;
362            height: 50px;
363            animation: spin 1s linear infinite;
364            margin: 20px auto;
365        }}
366        @keyframes spin {{
367            0% {{ transform: rotate(0deg); }}
368            100% {{ transform: rotate(360deg); }}
369        }}
370        .status {{ margin-top: 20px; color: #666; }}
371        .complete {{ color: #28a745; font-weight: bold; }}
372        .error {{ color: #dc3545; }}
373    </style>
374</head>
375<body>
376    <div class="logout-container">
377        <h1>🔐 Logging Out</h1>
378        <div class="spinner"></div>
379        <div id="status" class="status">
380            Notifying applications of logout...
381        </div>
382        <div id="progress" class="status">
383            <span id="completed">0</span> of <span id="total">{}</span> notifications sent
384        </div>
385    </div>
386
387    <!-- Hidden iframes for front-channel logout notifications -->
388{}
389
390    <script>
391        {}
392
393        let completedNotifications = 0;
394        let totalNotifications = {};
395        let errors = [];
396
397        function log(message) {{
398            if (DEBUG_LOGGING) {{
399                console.log('[FrontChannel Logout] ' + message);
400            }}
401        }}
402
403        function handleIframeLoad(clientId) {{
404            completedNotifications++;
405            log('Logout notification sent to: ' + clientId);
406            updateProgress();
407        }}
408
409        function handleIframeError(clientId) {{
410            completedNotifications++;
411            errors.push(clientId);
412            log('Logout notification failed for: ' + clientId);
413            updateProgress();
414        }}
415
416        function handleIframeTimeout(clientId, iframeIndex) {{
417            const iframe = document.getElementById('fc_logout_' + iframeIndex);
418            if (iframe && iframe.style.display !== 'none') {{
419                completedNotifications++;
420                errors.push(clientId + ' (timeout)');
421                log('Logout notification timeout for: ' + clientId);
422                updateProgress();
423            }}
424        }}
425
426        function updateProgress() {{
427            document.getElementById('completed').textContent = completedNotifications;
428
429            if (completedNotifications >= totalNotifications) {{
430                const statusEl = document.getElementById('status');
431                if (errors.length === 0) {{
432                    statusEl.textContent = 'Logout complete. All applications have been notified.';
433                    statusEl.className = 'status complete';
434                }} else {{
435                    statusEl.textContent = 'Logout complete with some errors.';
436                    statusEl.className = 'status error';
437                    log('Notifications failed for: ' + errors.join(', '));
438                }}
439
440                // Auto-close or redirect after a delay
441                setTimeout(function() {{
442                    window.close();
443                }}, 2000);
444            }}
445        }}
446
447        // Set up timeouts for all iframes
448        log('Starting front-channel logout for ' + totalNotifications + ' applications');
449{}
450
451        // Fallback timeout to ensure page doesn't hang
452        setTimeout(function() {{
453            if (completedNotifications < totalNotifications) {{
454                log('Global timeout reached, completing logout process');
455                completedNotifications = totalNotifications;
456                updateProgress();
457            }}
458        }}, {});
459    </script>
460</body>
461</html>"#,
462            iframe_urls.len(),
463            iframes_html,
464            debug_logging,
465            iframe_urls.len(),
466            timeout_scripts,
467            self.config.iframe_timeout_ms * 2 // Global timeout is double the iframe timeout
468        )
469    }
470
471    /// Clean up expired logout tracking
472    pub fn cleanup_expired_logouts(&mut self) -> usize {
473        let now = SystemTime::now();
474        let initial_count = self.active_logouts.len();
475
476        self.active_logouts.retain(|_, timestamp| {
477            now.duration_since(*timestamp)
478                .map(|d| d.as_secs() < 3600) // Keep for 1 hour
479                .unwrap_or(false)
480        });
481
482        initial_count - self.active_logouts.len()
483    }
484
485    /// Get discovery metadata for front-channel logout
486    pub fn get_discovery_metadata(&self) -> HashMap<String, serde_json::Value> {
487        let mut metadata = HashMap::new();
488
489        if self.config.enabled {
490            metadata.insert(
491                "frontchannel_logout_supported".to_string(),
492                serde_json::Value::Bool(true),
493            );
494
495            metadata.insert(
496                "frontchannel_logout_session_supported".to_string(),
497                serde_json::Value::Bool(true),
498            );
499        }
500
501        metadata
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508    use crate::server::oidc::oidc_session_management::SessionManagementConfig;
509
510    fn create_test_manager() -> FrontChannelLogoutManager {
511        let config = FrontChannelLogoutConfig::default();
512        let session_manager = SessionManager::new(SessionManagementConfig::default());
513        FrontChannelLogoutManager::new(config, session_manager)
514    }
515
516    #[test]
517    fn test_frontchannel_url_validation() {
518        let manager = create_test_manager();
519
520        // Valid HTTPS URL
521        assert!(
522            manager.is_valid_frontchannel_url("https://client.example.com/frontchannel_logout")
523        );
524
525        // Valid localhost HTTP (for development)
526        assert!(manager.is_valid_frontchannel_url("http://localhost:8080/logout"));
527
528        // Invalid - not HTTPS and not localhost
529        assert!(!manager.is_valid_frontchannel_url("http://example.com/logout"));
530
531        // Invalid - contains dangerous characters
532        assert!(!manager.is_valid_frontchannel_url("https://example.com/logout\n"));
533        assert!(!manager.is_valid_frontchannel_url("https://example.com/logout<script>"));
534
535        // Invalid - empty
536        assert!(!manager.is_valid_frontchannel_url(""));
537    }
538
539    #[tokio::test]
540    async fn test_frontchannel_logout_html_generation() {
541        let manager = create_test_manager();
542
543        let iframe_urls = vec![
544            (
545                "client1".to_string(),
546                "https://client1.example.com/logout".to_string(),
547                None,
548            ),
549            (
550                "client2".to_string(),
551                "https://client2.example.com/logout".to_string(),
552                Some(3000),
553            ),
554        ];
555
556        let html = manager.generate_frontchannel_logout_html(&iframe_urls);
557
558        println!("Generated HTML: {}", html);
559
560        assert!(html.contains("https://client1.example.com/logout"));
561        assert!(html.contains("https://client2.example.com/logout"));
562        assert!(html.contains("fc_logout_0"));
563        assert!(html.contains("fc_logout_1"));
564        assert!(html.contains("of <span id=\"total\">2</span> notifications"));
565        assert!(html.contains("handleIframeLoad"));
566        assert!(html.contains("handleIframeError"));
567    }
568
569    #[test]
570    fn test_frontchannel_logout_url_building() {
571        let manager = create_test_manager();
572
573        let session = OidcSession {
574            session_id: "session123".to_string(),
575            sub: "user123".to_string(),
576            client_id: "client456".to_string(),
577            created_at: 1000000000,
578            last_activity: 1000001000,
579            expires_at: 1000002000,
580            state: crate::server::oidc::oidc_session_management::SessionState::Authenticated,
581            browser_session_id: "browser_session_123".to_string(),
582            logout_tokens: vec![],
583            metadata: HashMap::new(),
584        };
585
586        let rp_config = RpFrontChannelConfig {
587            client_id: "client456".to_string(),
588            frontchannel_logout_uri: "https://client.example.com/fc_logout".to_string(),
589            frontchannel_logout_session_required: true,
590            custom_timeout_ms: None,
591        };
592
593        let logout_request = FrontChannelLogoutRequest {
594            session_id: "other_session".to_string(),
595            sub: "user123".to_string(),
596            sid: Some("sid123".to_string()),
597            iss: "https://op.example.com".to_string(),
598            initiating_client_id: None,
599        };
600
601        let url = manager
602            .build_frontchannel_logout_url(&session, &rp_config, &logout_request)
603            .unwrap();
604
605        assert!(url.contains("https://client.example.com/fc_logout"));
606        assert!(url.contains("iss=https%3A%2F%2Fop.example.com"));
607        assert!(url.contains("sid=sid123"));
608    }
609}