1use std::collections::HashMap;
5use std::sync::Mutex;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use crate::error::{err, SamlError};
9
10pub struct MemoryReplayCache {
12 entries: Mutex<HashMap<String, i64>>,
13 max: usize,
14}
15
16impl MemoryReplayCache {
17 pub fn new(max_entries: usize) -> Self {
18 Self { entries: Mutex::new(HashMap::new()), max: if max_entries == 0 { 10_000 } else { max_entries } }
19 }
20
21 pub fn check_and_record(&self, assertion_id: &str, expires_at_ms: i64) -> Result<bool, SamlError> {
23 let now = now_ms();
24 let mut entries = self.entries.lock().expect("replay");
25 if let Some(until) = entries.get(assertion_id) {
26 if *until > now {
27 return Ok(true);
28 }
29 }
30 if entries.len() >= self.max {
31 entries.retain(|_, until| *until > now);
32 if entries.len() >= self.max {
33 return Err(err("replay", format!("the replay cache holds {} live assertions and cannot record another", self.max)));
34 }
35 }
36 entries.insert(assertion_id.to_string(), expires_at_ms);
37 Ok(false)
38 }
39}
40
41pub(crate) fn now_ms() -> i64 {
42 SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
43}