Skip to main content

saml2_sp/
session.rs

1// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC
2// SPDX-License-Identifier: MIT
3
4use std::collections::HashMap;
5use std::sync::Mutex;
6
7use crate::replay::now_ms;
8use crate::response::SamlLogin;
9
10/// The SAML attribute a Shared Signals subject is taken from when none is named.
11pub const DEFAULT_SUBJECT_ATTRIBUTE: &str = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
12
13const MAIL: &[&str] = &[
14    "urn:oid:0.9.2342.19200300.100.1.3",
15    "mail",
16    "email",
17    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
18];
19const EMAIL_NAMEID: &str = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
20
21/// One local session the receiver can end.
22#[derive(Clone, Debug)]
23pub struct SessionRecord {
24    pub local_id: String,
25    pub person: String,
26    pub email: String,
27    pub idp_session: String,
28    pub expires_at_ms: Option<i64>,
29}
30
31/// Which local sessions belong to which person.
32pub struct MemorySessionIndex {
33    sessions: Mutex<IndexState>,
34    max: usize,
35}
36
37struct IndexState {
38    sessions: HashMap<String, SessionRecord>,
39    order: Vec<String>,
40}
41
42impl MemorySessionIndex {
43    pub fn new(max_entries: usize) -> Self {
44        Self {
45            sessions: Mutex::new(IndexState { sessions: HashMap::new(), order: Vec::new() }),
46            max: if max_entries == 0 { 100_000 } else { max_entries },
47        }
48    }
49
50    pub fn add(&self, mut session: SessionRecord) {
51        if !session.email.is_empty() {
52            session.email = session.email.to_ascii_lowercase();
53        }
54        let mut state = self.sessions.lock().expect("sessions");
55        if !state.sessions.contains_key(&session.local_id) && state.sessions.len() >= self.max {
56            let now = now_ms();
57            let expired: Vec<String> = state.order.iter().filter(|key| {
58                state.sessions.get(*key).and_then(|v| v.expires_at_ms).is_some_and(|t| t <= now)
59            }).cloned().collect();
60            for key in expired {
61                drop_locked(&mut state, &key);
62            }
63            while state.sessions.len() >= self.max && !state.order.is_empty() {
64                let key = state.order[0].clone();
65                drop_locked(&mut state, &key);
66            }
67        }
68        if !state.sessions.contains_key(&session.local_id) {
69            state.order.push(session.local_id.clone());
70        }
71        state.sessions.insert(session.local_id.clone(), session);
72    }
73
74    pub fn remove(&self, local_id: &str) {
75        let mut state = self.sessions.lock().expect("sessions");
76        drop_locked(&mut state, local_id);
77    }
78
79    pub fn by_person(&self, person: &str) -> Vec<String> {
80        self.find(|session| session.person == person)
81    }
82
83    pub fn by_email(&self, email: &str) -> Vec<String> {
84        let wanted = email.to_ascii_lowercase();
85        self.find(|session| session.email == wanted)
86    }
87
88    pub fn by_idp_session(&self, idp_session: &str) -> Vec<String> {
89        self.find(|session| session.idp_session == idp_session)
90    }
91
92    fn find(&self, mut matches: impl FnMut(&SessionRecord) -> bool) -> Vec<String> {
93        let now = now_ms();
94        let mut state = self.sessions.lock().expect("sessions");
95        let mut out = Vec::new();
96        let mut keep = Vec::new();
97        let order = std::mem::take(&mut state.order);
98        for key in order {
99            let Some(value) = state.sessions.get(&key) else { continue };
100            if value.expires_at_ms.is_some_and(|t| t <= now) {
101                state.sessions.remove(&key);
102                continue;
103            }
104            if matches(value) {
105                out.push(key.clone());
106            }
107            keep.push(key);
108        }
109        state.order = keep;
110        out
111    }
112}
113
114fn drop_locked(state: &mut IndexState, local_id: &str) {
115    state.sessions.remove(local_id);
116    state.order.retain(|id| id != local_id);
117}
118
119/// The index record for a SAML login.
120pub fn tracked_from(local_id: &str, login: &SamlLogin, subject_attribute: &str, expires_at_ms: Option<i64>) -> SessionRecord {
121    let attribute = if subject_attribute.is_empty() { DEFAULT_SUBJECT_ATTRIBUTE } else { subject_attribute };
122    let person = login.attributes.get(attribute).and_then(|v| v.first()).cloned().unwrap_or_default();
123    let mut email = String::new();
124    for name in MAIL {
125        if let Some(value) = login.attributes.get(*name).and_then(|v| v.first()) {
126            if !value.is_empty() {
127                email = value.clone();
128                break;
129            }
130        }
131    }
132    if email.is_empty() && login.name_id_format == EMAIL_NAMEID {
133        email = login.name_id.clone();
134    }
135    let when = expires_at_ms.or(login.session_not_on_or_after_ms);
136    SessionRecord {
137        local_id: local_id.to_string(),
138        person,
139        email,
140        idp_session: login.session_index.clone(),
141        expires_at_ms: when,
142    }
143}