auth_framework/server/oidc/
oidc_session_management.rs1use crate::errors::{AuthError, Result};
16use base64::{Engine as _, engine::general_purpose::STANDARD};
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::time::{SystemTime, UNIX_EPOCH};
20use uuid::Uuid;
21
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24pub enum SessionState {
25 Authenticated,
27 Unauthenticated,
29 Changed,
31 Unknown,
33}
34
35#[derive(Clone, Serialize, Deserialize)]
37pub struct OidcSession {
38 pub session_id: String,
40 pub sub: String,
42 pub client_id: String,
44 pub created_at: u64,
46 pub last_activity: u64,
48 pub expires_at: u64,
50 pub state: SessionState,
52 pub browser_session_id: String,
54 pub logout_tokens: Vec<String>,
56 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#[derive(Debug, Clone)]
88pub struct SessionManagementConfig {
89 pub enabled: bool,
91 pub session_timeout: u64,
93 pub check_session_interval: u64,
95 pub enable_iframe_checking: bool,
97 pub check_session_iframe_endpoint: String,
99 pub end_session_endpoint: String,
101}
102
103impl Default for SessionManagementConfig {
104 fn default() -> Self {
105 Self {
106 enabled: true,
107 session_timeout: 3600, check_session_interval: 30, 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#[derive(Clone)]
118pub struct SessionManager {
119 config: SessionManagementConfig,
121 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#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct SessionCheckRequest {
137 pub client_id: String,
139 pub session_state: String,
141 pub origin: String,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct SessionCheckResponse {
148 pub state: SessionState,
150 pub session_state: Option<String>,
152}
153
154impl SessionManager {
155 pub fn new(config: SessionManagementConfig) -> Self {
157 Self {
158 config,
159 sessions: HashMap::new(),
160 }
161 }
162
163 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()
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, state: SessionState::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 pub fn get_session(&self, session_id: &str) -> Option<&OidcSession> {
195 self.sessions.get(session_id)
196 }
197
198 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()
204 .as_secs();
205 session.last_activity = now;
206 Ok(())
207 } else {
208 Err(AuthError::validation("Session not found"))
209 }
210 }
211
212 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()
218 .as_secs();
219
220 now - session.last_activity < self.config.session_timeout
221 } else {
222 false
223 }
224 }
225
226 fn generate_browser_session_id(&self, sub: &str, client_id: &str) -> Result<String> {
228 let data = format!("{}:{}:{}", sub, client_id, Uuid::new_v4());
231
232 Ok(STANDARD.encode(data))
234 }
235
236 pub fn check_session_state(
238 &self,
239 request: SessionCheckRequest,
240 ) -> Result<SessionCheckResponse> {
241 let session = self.sessions.values().find(|s| {
243 s.browser_session_id == request.session_state && s.client_id == request.client_id
244 });
245
246 if let Some(session) = session {
247 if self.is_session_valid(&session.session_id) {
248 Ok(SessionCheckResponse {
249 state: SessionState::Authenticated,
250 session_state: None, })
252 } else {
253 Ok(SessionCheckResponse {
254 state: SessionState::Unauthenticated,
255 session_state: None,
256 })
257 }
258 } else {
259 Ok(SessionCheckResponse {
260 state: SessionState::Unauthenticated,
261 session_state: None,
262 })
263 }
264 }
265
266 pub fn end_session(&mut self, session_id: &str) -> Result<OidcSession> {
268 if let Some(mut session) = self.sessions.remove(session_id) {
269 session.state = SessionState::Unauthenticated;
270 Ok(session)
271 } else {
272 Err(AuthError::validation("Session not found"))
273 }
274 }
275
276 pub fn get_check_session_iframe(&self, client_id: &str) -> String {
278 format!(
279 r#"<!DOCTYPE html>
280<html>
281<head>
282 <title>Session Check</title>
283 <script>
284 (function() {{
285 var client_id = "{}";
286 var check_interval = {} * 1000; // Convert to milliseconds
287
288 function getCookie(name) {{
289 var cookies = document.cookie.split(';');
290 for (var i = 0; i < cookies.length; i++) {{
291 var cookie = cookies[i].trim();
292 if (cookie.indexOf(name + '=') === 0) {{
293 return cookie.substring(name.length + 1);
294 }}
295 }}
296 return null;
297 }}
298
299 function checkSession() {{
300 var sessionState = getCookie('session_state');
301 if (sessionState) {{
302 // Notify parent window of session check
303 window.parent.postMessage({{
304 type: 'session_check',
305 client_id: client_id,
306 session_state: sessionState,
307 state: 'unchanged'
308 }}, '*');
309 }} else {{
310 window.parent.postMessage({{
311 type: 'session_check',
312 client_id: client_id,
313 state: 'unauthenticated'
314 }}, '*');
315 }}
316 }}
317
318 // Initial check
319 checkSession();
320
321 // Periodic checking
322 setInterval(checkSession, check_interval);
323
324 // Listen for messages from parent
325 window.addEventListener('message', function(e) {{
326 if (e.data && e.data.type === 'check_session') {{
327 checkSession();
328 }}
329 }});
330 }})();
331 </script>
332</head>
333<body>
334 <p>Session monitoring active...</p>
335</body>
336</html>"#,
337 client_id, self.config.check_session_interval
338 )
339 }
340
341 pub fn cleanup_expired_sessions(&mut self) -> usize {
343 let now = SystemTime::now()
344 .duration_since(UNIX_EPOCH)
345 .unwrap()
346 .as_secs();
347
348 let initial_count = self.sessions.len();
349
350 self.sessions
351 .retain(|_, session| now - session.last_activity < self.config.session_timeout);
352
353 initial_count - self.sessions.len()
354 }
355
356 pub fn get_sessions_for_subject(&self, sub: &str) -> Vec<&OidcSession> {
358 self.sessions
359 .values()
360 .filter(|session| session.sub == sub)
361 .collect()
362 }
363
364 pub fn add_logout_token(&mut self, session_id: &str, logout_token: String) -> Result<()> {
366 if let Some(session) = self.sessions.get_mut(session_id) {
367 session.logout_tokens.push(logout_token);
368 Ok(())
369 } else {
370 Err(AuthError::validation("Session not found"))
371 }
372 }
373
374 pub fn get_discovery_metadata(&self) -> HashMap<String, serde_json::Value> {
376 let mut metadata = HashMap::new();
377
378 if self.config.enabled {
379 metadata.insert(
380 "check_session_iframe".to_string(),
381 serde_json::Value::String(self.config.check_session_iframe_endpoint.clone()),
382 );
383 metadata.insert(
384 "end_session_endpoint".to_string(),
385 serde_json::Value::String(self.config.end_session_endpoint.clone()),
386 );
387 metadata.insert(
388 "frontchannel_logout_supported".to_string(),
389 serde_json::Value::Bool(true),
390 );
391 metadata.insert(
392 "frontchannel_logout_session_supported".to_string(),
393 serde_json::Value::Bool(true),
394 );
395 metadata.insert(
396 "backchannel_logout_supported".to_string(),
397 serde_json::Value::Bool(true),
398 );
399 metadata.insert(
400 "backchannel_logout_session_supported".to_string(),
401 serde_json::Value::Bool(true),
402 );
403 }
404
405 metadata
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn test_session_creation() {
415 let mut manager = SessionManager::new(SessionManagementConfig::default());
416
417 let mut metadata = HashMap::new();
418 metadata.insert("ip_address".to_string(), "192.168.1.1".to_string());
419
420 let session = manager
421 .create_session("user123".to_string(), "client456".to_string(), metadata)
422 .unwrap();
423
424 assert_eq!(session.sub, "user123");
425 assert_eq!(session.client_id, "client456");
426 assert_eq!(session.state, SessionState::Authenticated);
427 assert!(!session.browser_session_id.is_empty());
428 }
429
430 #[test]
431 fn test_session_validity() {
432 let mut manager = SessionManager::new(SessionManagementConfig {
433 session_timeout: 1, ..SessionManagementConfig::default()
435 });
436
437 let session = manager
438 .create_session(
439 "user123".to_string(),
440 "client456".to_string(),
441 HashMap::new(),
442 )
443 .unwrap();
444
445 assert!(manager.is_session_valid(&session.session_id));
446
447 std::thread::sleep(std::time::Duration::from_secs(2));
449
450 assert!(!manager.is_session_valid(&session.session_id));
451 }
452
453 #[test]
454 fn test_check_session_iframe_generation() {
455 let manager = SessionManager::new(SessionManagementConfig::default());
456
457 let html = manager.get_check_session_iframe("test_client");
458
459 assert!(html.contains("test_client"));
460 assert!(html.contains("session_check"));
461 assert!(html.contains("30 * 1000")); }
463}