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