Skip to main content

auth_framework/server/oidc/
oidc_session_management.rs

1//! OpenID Connect Session Management Implementation
2//!
3//! This module provides comprehensive session management capabilities for OpenID Connect,
4//! serving as the foundation for RP-Initiated Logout, Front-Channel Logout,
5//! Back-Channel Logout, and other session-related specifications.
6//!
7//! # Features
8//!
9//! - Session state monitoring
10//! - Session management endpoints
11//! - iframe-based session checking
12//! - Session change notifications
13//! - Multi-tab session coordination
14
15use crate::errors::{AuthError, Result};
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::collections::HashMap;
19use std::time::{SystemTime, UNIX_EPOCH};
20use uuid::Uuid;
21
22/// Session state enumeration
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24pub enum OidcSessionState {
25    /// User is authenticated
26    Authenticated,
27    /// User is not authenticated
28    Unauthenticated,
29    /// Session state changed
30    Changed,
31    /// Session state unknown/error
32    Unknown,
33}
34
35/// OpenID Connect session information
36#[derive(Clone, Serialize, Deserialize)]
37pub struct OidcSession {
38    /// Unique session identifier
39    pub session_id: String,
40    /// Subject (user) identifier
41    pub sub: String,
42    /// Client ID for this session
43    pub client_id: String,
44    /// Session creation timestamp
45    pub created_at: u64,
46    /// Last activity timestamp
47    pub last_activity: u64,
48    /// Session expiration timestamp
49    pub expires_at: u64,
50    /// Session state
51    pub state: OidcSessionState,
52    /// Browser session identifier (session_state parameter)
53    pub browser_session_id: String,
54    /// Associated logout tokens for backchannel logout
55    pub logout_tokens: Vec<String>,
56    /// Session metadata
57    pub metadata: HashMap<String, String>,
58}
59
60impl std::fmt::Debug for OidcSession {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        let mut d = f.debug_struct("OidcSession");
63        d.field(
64            "session_id",
65            &crate::utils::redact::redacted(&self.session_id),
66        );
67        d.field("sub", &self.sub);
68        d.field("client_id", &self.client_id);
69        d.field("created_at", &self.created_at);
70        d.field("last_activity", &self.last_activity);
71        d.field("expires_at", &self.expires_at);
72        d.field("state", &self.state);
73        d.field(
74            "browser_session_id",
75            &crate::utils::redact::redacted(&self.browser_session_id),
76        );
77        d.field("logout_tokens", &self.logout_tokens);
78        d.field("metadata", &self.metadata);
79        d.finish()
80    }
81}
82
83/// Session Management configuration
84#[derive(Debug, Clone)]
85pub struct SessionManagementConfig {
86    /// Enable session management features
87    pub enabled: bool,
88    /// Session timeout in seconds
89    pub session_timeout: u64,
90    /// Check session interval in seconds
91    pub check_session_interval: u64,
92    /// Enable iframe session checking
93    pub enable_iframe_checking: bool,
94    /// Session management endpoints
95    pub check_session_iframe_endpoint: String,
96    /// End session endpoint
97    pub end_session_endpoint: String,
98}
99
100impl Default for SessionManagementConfig {
101    fn default() -> Self {
102        Self {
103            enabled: true,
104            session_timeout: 3600,      // 1 hour
105            check_session_interval: 30, // 30 seconds
106            enable_iframe_checking: true,
107            check_session_iframe_endpoint: "/connect/checksession".to_string(),
108            end_session_endpoint: "/connect/endsession".to_string(),
109        }
110    }
111}
112
113/// Session Management provider
114#[derive(Clone)]
115pub struct SessionManager {
116    /// Configuration
117    config: SessionManagementConfig,
118    /// Active sessions storage
119    sessions: HashMap<String, OidcSession>,
120}
121
122impl std::fmt::Debug for SessionManager {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        let mut d = f.debug_struct("SessionManager");
125        d.field("config", &self.config);
126        d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
127        d.finish()
128    }
129}
130
131/// Session check request parameters
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct SessionCheckRequest {
134    /// Client ID
135    pub client_id: String,
136    /// Session state value
137    pub session_state: String,
138    /// Origin for CORS
139    pub origin: String,
140}
141
142/// Session check response
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct SessionCheckResponse {
145    /// Session state
146    pub state: OidcSessionState,
147    /// New session state value if changed
148    pub session_state: Option<String>,
149}
150
151impl SessionManager {
152    /// Create new session manager
153    pub fn new(config: SessionManagementConfig) -> Self {
154        Self {
155            config,
156            sessions: HashMap::new(),
157        }
158    }
159
160    /// Create new session
161    pub fn create_session(
162        &mut self,
163        sub: String,
164        client_id: String,
165        metadata: HashMap<String, String>,
166    ) -> Result<OidcSession> {
167        let now = SystemTime::now()
168            .duration_since(UNIX_EPOCH)
169            .unwrap_or_default()
170            .as_secs();
171
172        let session = OidcSession {
173            session_id: Uuid::new_v4().to_string(),
174            sub: sub.clone(),
175            client_id: client_id.clone(),
176            created_at: now,
177            last_activity: now,
178            expires_at: now + 3600, // Default 1 hour expiration
179            state: OidcSessionState::Authenticated,
180            browser_session_id: self.generate_browser_session_id(&sub, &client_id)?,
181            logout_tokens: Vec::new(),
182            metadata,
183        };
184
185        self.sessions
186            .insert(session.session_id.clone(), session.clone());
187        Ok(session)
188    }
189
190    /// Get session by ID
191    pub fn get_session(&self, session_id: &str) -> Option<&OidcSession> {
192        self.sessions.get(session_id)
193    }
194
195    /// Update session activity
196    pub fn update_session_activity(&mut self, session_id: &str) -> Result<()> {
197        if let Some(session) = self.sessions.get_mut(session_id) {
198            let now = SystemTime::now()
199                .duration_since(UNIX_EPOCH)
200                .unwrap_or_default()
201                .as_secs();
202            session.last_activity = now;
203            Ok(())
204        } else {
205            Err(AuthError::validation("Session not found"))
206        }
207    }
208
209    /// Check if session is valid (not expired)
210    pub fn is_session_valid(&self, session_id: &str) -> bool {
211        if let Some(session) = self.get_session(session_id) {
212            let now = SystemTime::now()
213                .duration_since(UNIX_EPOCH)
214                .unwrap_or_default()
215                .as_secs();
216
217            now - session.last_activity < self.config.session_timeout
218        } else {
219            false
220        }
221    }
222
223    /// Generate an opaque browser session ID for the OIDC `session_state` parameter.
224    ///
225    /// Uses SHA-256(sub || client_id || random UUID) so the result is a fixed-length
226    /// opaque token that does not leak user identity or client information in the URL.
227    fn generate_browser_session_id(&self, sub: &str, client_id: &str) -> Result<String> {
228        let nonce = Uuid::new_v4().to_string();
229        let mut hasher = Sha256::new();
230        hasher.update(sub.as_bytes());
231        hasher.update(b":");
232        hasher.update(client_id.as_bytes());
233        hasher.update(b":");
234        hasher.update(nonce.as_bytes());
235        let hash = hasher.finalize();
236        Ok(hex::encode(hash))
237    }
238
239    /// Check session state for iframe polling
240    pub fn check_session_state(
241        &self,
242        request: SessionCheckRequest,
243    ) -> Result<SessionCheckResponse> {
244        // Find session by browser session ID
245        let session = self.sessions.values().find(|s| {
246            s.browser_session_id == request.session_state && s.client_id == request.client_id
247        });
248
249        if let Some(session) = session {
250            if self.is_session_valid(&session.session_id) {
251                Ok(SessionCheckResponse {
252                    state: OidcSessionState::Authenticated,
253                    session_state: None, // No change
254                })
255            } else {
256                Ok(SessionCheckResponse {
257                    state: OidcSessionState::Unauthenticated,
258                    session_state: None,
259                })
260            }
261        } else {
262            Ok(SessionCheckResponse {
263                state: OidcSessionState::Unauthenticated,
264                session_state: None,
265            })
266        }
267    }
268
269    /// End session (logout)
270    pub fn end_session(&mut self, session_id: &str) -> Result<OidcSession> {
271        if let Some(mut session) = self.sessions.remove(session_id) {
272            session.state = OidcSessionState::Unauthenticated;
273            Ok(session)
274        } else {
275            Err(AuthError::validation("Session not found"))
276        }
277    }
278
279    /// Get check session iframe HTML
280    pub fn get_check_session_iframe(&self, client_id: &str) -> String {
281        format!(
282            r#"<!DOCTYPE html>
283<html>
284<head>
285    <title>Session Check</title>
286    <script>
287        (function() {{
288            var client_id = "{}";
289            var check_interval = {} * 1000; // Convert to milliseconds
290
291            function getCookie(name) {{
292                var cookies = document.cookie.split(';');
293                for (var i = 0; i < cookies.length; i++) {{
294                    var cookie = cookies[i].trim();
295                    if (cookie.indexOf(name + '=') === 0) {{
296                        return cookie.substring(name.length + 1);
297                    }}
298                }}
299                return null;
300            }}
301
302            function checkSession() {{
303                var OidcSessionState = getCookie('session_state');
304                if (OidcSessionState) {{
305                    // Notify parent window of session check
306                    window.parent.postMessage({{
307                        type: 'session_check',
308                        client_id: client_id,
309                        session_state: OidcSessionState,
310                        state: 'unchanged'
311                    }}, '*');
312                }} else {{
313                    window.parent.postMessage({{
314                        type: 'session_check',
315                        client_id: client_id,
316                        state: 'unauthenticated'
317                    }}, '*');
318                }}
319            }}
320
321            // Initial check
322            checkSession();
323
324            // Periodic checking
325            setInterval(checkSession, check_interval);
326
327            // Listen for messages from parent
328            window.addEventListener('message', function(e) {{
329                if (e.data && e.data.type === 'check_session') {{
330                    checkSession();
331                }}
332            }});
333        }})();
334    </script>
335</head>
336<body>
337    <p>Session monitoring active...</p>
338</body>
339</html>"#,
340            client_id, self.config.check_session_interval
341        )
342    }
343
344    /// Clean up expired sessions
345    pub fn cleanup_expired_sessions(&mut self) -> usize {
346        let now = SystemTime::now()
347            .duration_since(UNIX_EPOCH)
348            .unwrap_or_default()
349            .as_secs();
350
351        let initial_count = self.sessions.len();
352
353        self.sessions
354            .retain(|_, session| now - session.last_activity < self.config.session_timeout);
355
356        initial_count - self.sessions.len()
357    }
358
359    /// Get all sessions for a subject
360    pub fn get_sessions_for_subject(&self, sub: &str) -> Vec<&OidcSession> {
361        self.sessions
362            .values()
363            .filter(|session| session.sub == sub)
364            .collect()
365    }
366
367    /// Add logout token to session (for backchannel logout)
368    pub fn add_logout_token(&mut self, session_id: &str, logout_token: String) -> Result<()> {
369        if let Some(session) = self.sessions.get_mut(session_id) {
370            session.logout_tokens.push(logout_token);
371            Ok(())
372        } else {
373            Err(AuthError::validation("Session not found"))
374        }
375    }
376
377    /// Get session management discovery metadata
378    pub fn get_discovery_metadata(&self) -> HashMap<String, serde_json::Value> {
379        let mut metadata = HashMap::new();
380
381        if self.config.enabled {
382            metadata.insert(
383                "check_session_iframe".to_string(),
384                serde_json::Value::String(self.config.check_session_iframe_endpoint.clone()),
385            );
386            metadata.insert(
387                "end_session_endpoint".to_string(),
388                serde_json::Value::String(self.config.end_session_endpoint.clone()),
389            );
390            metadata.insert(
391                "frontchannel_logout_supported".to_string(),
392                serde_json::Value::Bool(true),
393            );
394            metadata.insert(
395                "frontchannel_logout_session_supported".to_string(),
396                serde_json::Value::Bool(true),
397            );
398            metadata.insert(
399                "backchannel_logout_supported".to_string(),
400                serde_json::Value::Bool(true),
401            );
402            metadata.insert(
403                "backchannel_logout_session_supported".to_string(),
404                serde_json::Value::Bool(true),
405            );
406        }
407
408        metadata
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn test_session_creation() {
418        let mut manager = SessionManager::new(SessionManagementConfig::default());
419
420        let mut metadata = HashMap::new();
421        metadata.insert("ip_address".to_string(), "192.168.1.1".to_string());
422
423        let session = manager
424            .create_session("user123".to_string(), "client456".to_string(), metadata)
425            .unwrap();
426
427        assert_eq!(session.sub, "user123");
428        assert_eq!(session.client_id, "client456");
429        assert_eq!(session.state, OidcSessionState::Authenticated);
430        assert!(!session.browser_session_id.is_empty());
431    }
432
433    #[test]
434    fn test_session_validity() {
435        // Whole-second clock: the timeout is checked as `now - last_activity < timeout` on integer
436        // seconds, so a short timeout and a real sleep make the first assertion fail whenever the
437        // second ticks over during `create_session`. Use a long timeout and move the activity time.
438        let timeout = 60;
439        let mut manager = SessionManager::new(SessionManagementConfig {
440            session_timeout: timeout,
441            ..SessionManagementConfig::default()
442        });
443
444        let session = manager
445            .create_session(
446                "user123".to_string(),
447                "client456".to_string(),
448                HashMap::new(),
449            )
450            .unwrap();
451
452        assert!(manager.is_session_valid(&session.session_id));
453
454        // Activity `timeout - 5` seconds ago: still valid. (The margin absorbs the second boundary.)
455        manager
456            .sessions
457            .get_mut(&session.session_id)
458            .unwrap()
459            .last_activity = session.last_activity - (timeout - 5);
460        assert!(manager.is_session_valid(&session.session_id));
461
462        // Activity `timeout + 1` seconds ago: expired.
463        manager
464            .sessions
465            .get_mut(&session.session_id)
466            .unwrap()
467            .last_activity = session.last_activity - (timeout + 1);
468        assert!(!manager.is_session_valid(&session.session_id));
469
470        // An unknown session is never valid.
471        assert!(!manager.is_session_valid("no-such-session"));
472    }
473
474    #[test]
475    fn test_check_session_iframe_generation() {
476        let manager = SessionManager::new(SessionManagementConfig::default());
477
478        let html = manager.get_check_session_iframe("test_client");
479
480        assert!(html.contains("test_client"));
481        assert!(html.contains("session_check"));
482        assert!(html.contains("30 * 1000")); // Default interval
483    }
484}