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