use crate::time::{Duration, Instant};
use std::collections::HashMap;
use std::sync::Mutex;
use crate::Sensitive;
pub const OIDC_STATE_TTL: Duration = Duration::from_secs(600);
#[derive(Debug)]
pub struct OidcStateEntry {
pub state: String,
pub nonce: String,
pub code_verifier: Sensitive<String>,
pub redirect_uri: String,
pub return_to: Option<String>,
}
pub trait OidcStateStore: Send + Sync {
fn save(&self, entry: OidcStateEntry) -> impl std::future::Future<Output = ()> + Send;
fn consume(
&self,
state: &str,
) -> impl std::future::Future<Output = Option<OidcStateEntry>> + Send;
}
struct Held {
entry: OidcStateEntry,
expires_at: Instant,
}
pub struct MemoryOidcStateStore {
entries: Mutex<HashMap<String, Held>>,
ttl: Duration,
}
impl Default for MemoryOidcStateStore {
fn default() -> Self {
Self::new()
}
}
impl MemoryOidcStateStore {
pub fn new() -> Self {
Self::with_ttl(OIDC_STATE_TTL)
}
pub fn with_ttl(ttl: Duration) -> Self {
Self {
entries: Mutex::new(HashMap::new()),
ttl: ttl.min(OIDC_STATE_TTL),
}
}
pub fn len(&self) -> usize {
self.sweep();
self.entries
.lock()
.expect("state store mutex poisoned")
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn sweep(&self) {
let now = Instant::now();
self.entries
.lock()
.expect("state store mutex poisoned")
.retain(|_, held| held.expires_at > now);
}
}
impl OidcStateStore for MemoryOidcStateStore {
async fn save(&self, entry: OidcStateEntry) {
self.sweep();
let expires_at = Instant::now() + self.ttl;
self.entries
.lock()
.expect("state store mutex poisoned")
.insert(entry.state.clone(), Held { entry, expires_at });
}
async fn consume(&self, state: &str) -> Option<OidcStateEntry> {
let held = self
.entries
.lock()
.expect("state store mutex poisoned")
.remove(state)?;
if held.expires_at <= Instant::now() {
return None;
}
Some(held.entry)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(state: &str) -> OidcStateEntry {
OidcStateEntry {
state: state.to_string(),
nonce: "nonce-value".to_string(),
code_verifier: Sensitive::new("verifier-value".to_string()),
redirect_uri: "https://app.example.com/cb".to_string(),
return_to: None,
}
}
#[tokio::test]
async fn consume_is_single_use() {
let store = MemoryOidcStateStore::new();
store.save(entry("s1")).await;
assert_eq!(store.len(), 1);
let consumed = store.consume("s1").await.expect("first consume succeeds");
assert_eq!(consumed.nonce, "nonce-value");
assert!(store.consume("s1").await.is_none(), "state is single-use");
}
#[tokio::test]
async fn consume_returns_none_for_unknown_state() {
let store = MemoryOidcStateStore::new();
assert!(store.consume("never-saved").await.is_none());
}
#[tokio::test]
async fn ttl_expiry_makes_an_entry_unavailable() {
let store = MemoryOidcStateStore::with_ttl(Duration::from_millis(20));
store.save(entry("s1")).await;
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
store.consume("s1").await.is_none(),
"expired entry must not be returned"
);
}
#[tokio::test]
async fn ttl_is_clamped_to_ten_minutes_maximum() {
let store = MemoryOidcStateStore::with_ttl(Duration::from_secs(3600));
store.save(entry("s1")).await;
assert!(store.consume("s1").await.is_some());
}
}