#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
pub const UNKNOWN_CHALLENGE: &str =
"challenge was not issued by this verifier or has already been used";
pub trait ChallengeStore {
fn issue(&self, session_context: &[u8], ttl_seconds: i64) -> Result<(Vec<u8>, i64), String>;
fn validate(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String>;
fn consume(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String>;
}
impl<T: ChallengeStore + ?Sized> ChallengeStore for &T {
fn issue(&self, session_context: &[u8], ttl_seconds: i64) -> Result<(Vec<u8>, i64), String> {
(**self).issue(session_context, ttl_seconds)
}
fn validate(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String> {
(**self).validate(challenge, session_context, now)
}
fn consume(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String> {
(**self).consume(challenge, session_context, now)
}
}
#[cfg(feature = "std")]
mod memory {
use super::{ChallengeStore, UNKNOWN_CHALLENGE};
use crate::canonical::base64_std_encode;
use crate::crypto::generate_challenge;
use std::collections::HashMap;
use std::string::{String, ToString};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use std::vec::Vec;
struct Record {
session_context: Vec<u8>,
expires_at: i64,
}
pub struct MemoryChallengeStore {
records: Mutex<HashMap<String, Record>>,
max_size: usize,
}
impl MemoryChallengeStore {
pub fn new(max_size: usize) -> Self {
assert!(
max_size > 0,
"MemoryChallengeStore max_size must be >= 1, got 0"
);
MemoryChallengeStore {
records: Mutex::new(HashMap::new()),
max_size,
}
}
fn expire(records: &mut HashMap<String, Record>, now: i64) {
records.retain(|_, r| r.expires_at >= now);
}
fn lookup(
records: &mut HashMap<String, Record>,
challenge: &[u8],
session_context: &[u8],
now: i64,
) -> Option<String> {
Self::expire(records, now);
let key = base64_std_encode(challenge);
match records.get(&key) {
Some(r) if r.session_context == session_context => Some(key),
_ => None,
}
}
}
impl ChallengeStore for MemoryChallengeStore {
fn issue(
&self,
session_context: &[u8],
ttl_seconds: i64,
) -> Result<(Vec<u8>, i64), String> {
if !session_context.is_empty() && session_context.len() != 32 {
return Err(format!(
"session context must be empty or 32 bytes, got {}",
session_context.len()
));
}
if ttl_seconds <= 0 {
return Err(format!(
"challenge ttl must be positive, got {}",
ttl_seconds
));
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
let expires_at = now + ttl_seconds;
let challenge = generate_challenge();
let mut records = self.records.lock().expect("challenge store lock poisoned");
Self::expire(&mut records, now);
if records.len() >= self.max_size {
return Err("challenge store full — too many pending challenges".to_string());
}
records.insert(
base64_std_encode(&challenge),
Record {
session_context: session_context.to_vec(),
expires_at,
},
);
Ok((challenge, expires_at))
}
fn validate(
&self,
challenge: &[u8],
session_context: &[u8],
now: i64,
) -> Result<(), String> {
let mut records = self.records.lock().expect("challenge store lock poisoned");
match Self::lookup(&mut records, challenge, session_context, now) {
Some(_) => Ok(()),
None => Err(UNKNOWN_CHALLENGE.to_string()),
}
}
fn consume(
&self,
challenge: &[u8],
session_context: &[u8],
now: i64,
) -> Result<(), String> {
let mut records = self.records.lock().expect("challenge store lock poisoned");
match Self::lookup(&mut records, challenge, session_context, now) {
Some(key) => {
records.remove(&key);
Ok(())
}
None => Err(UNKNOWN_CHALLENGE.to_string()),
}
}
}
}
#[cfg(feature = "std")]
pub use memory::MemoryChallengeStore;