//! Single-use values: a record of values that may be used once, each in a //! namespace and until a time, as `spec/OAUTH.md` says under "Single-use //! values". OAuth spends DPoP proofs' `jti`s, PKCE challenges and clients' //! `state`s in it; anything else that must refuse a replay may too. //! //! A value is claimed in memory, under the store's lock, which answers the //! `accounts.log` entry that keeps the claim: the caller logs it, in a frame //! of its own or with the change the value is spent on, and answers only //! once that frame is on disk. Entries are independent of one another, so //! they may be logged in any order. Each entry is forgotten once its time //! has passed, in memory and when the log is replayed. Values are kept as //! their SHA-256, so that what a client sends bounds nothing kept. use serde_json::{Value as Json, json}; use sha2::{Digest, Sha256}; use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap}; use std::sync::{Mutex, PoisonError}; /// The kind of `accounts.log` entry a claim is kept in. pub(crate) const ENTRY: &str = "spent"; /// A value, by its namespace and digest. type Key = (String, String); #[derive(Default)] struct Held { /// Until when each value is held, in seconds since the epoch. until: HashMap, /// The same, soonest first, to forget them as their times pass. queue: BinaryHeap>, } impl Held { /// Forget every value whose time has passed by `now`. fn forget(&mut self, now: u64) { while let Some(Reverse((t, _))) = self.queue.peek() && *t <= now { let Some(Reverse((t, k))) = self.queue.pop() else { break; }; if self.until.get(&k) == Some(&t) { self.until.remove(&k); } } } fn hold(&mut self, k: Key, until: u64) { let t = self.until.entry(k.clone()).or_insert(0); if until > *t { *t = until; self.queue.push(Reverse((until, k))); } } } /// The single-use values the server holds. #[derive(Default)] pub(crate) struct Replay { held: Mutex, } fn digest(value: &str) -> String { hex::encode(Sha256::digest(value.as_bytes())) } impl Replay { /// Claim `value` in `ns` until `until`: the entry that keeps the claim, to /// log, or None if the value is held there already. pub fn claim(&self, ns: &str, value: &str, now: u64, until: u64) -> Option { let k = (ns.to_string(), digest(value)); let mut h = self.held.lock().unwrap_or_else(PoisonError::into_inner); h.forget(now); if h.until.contains_key(&k) { return None; } let entry = json!({ "t": ENTRY, "ns": k.0, "v": k.1, "until": until }); h.hold(k, until); Some(entry) } /// Whether `value` is held in `ns` at `now`, claiming nothing. pub fn holds(&self, ns: &str, value: &str, now: u64) -> bool { let h = self.held.lock().unwrap_or_else(PoisonError::into_inner); h.until .get(&(ns.to_string(), digest(value))) .is_some_and(|t| *t > now) } /// Replay an entry `claim` answered, at `now`: one whose time has passed is forgotten. pub fn replay(&self, e: &Json, now: u64) -> Result<(), String> { let (Some(ns), Some(v), Some(until)) = (e["ns"].as_str(), e["v"].as_str(), e["until"].as_u64()) else { return Err(format!("a spent value with no ns, v or until: {e}")); }; if v.len() != 64 || !v.bytes().all(|b| b.is_ascii_hexdigit()) { return Err(format!("a spent value that is not a digest: {e}")); } if until > now { self.held .lock() .unwrap_or_else(PoisonError::into_inner) .hold((ns.to_string(), v.to_string()), until); } Ok(()) } /// Every value held at `now`, to compare across restarts. #[cfg(test)] pub fn snapshot(&self, now: u64) -> std::collections::BTreeMap { let h = self.held.lock().unwrap_or_else(PoisonError::into_inner); h.until .iter() .filter(|(_, t)| **t > now) .map(|(k, t)| (k.clone(), *t)) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn values_are_spent_once_until_their_time() { let r = Replay::default(); let e = r.claim("dpop", "a", 100, 300).unwrap(); assert_eq!(e["t"], ENTRY); assert!(r.claim("dpop", "a", 299, 400).is_none()); // Another namespace holds its own. assert!(r.claim("pkce", "a", 100, 300).is_some()); // Once its time has passed it is forgotten, and may be claimed again. assert!(r.claim("dpop", "a", 300, 500).is_some()); assert!(r.claim("dpop", "a", 499, 600).is_none()); assert_eq!(r.snapshot(450).len(), 1); } #[test] fn replayed_claims_hold_until_their_time() { let r = Replay::default(); let a = r.claim("ns", "a", 0, 100).unwrap(); let b = r.claim("ns", "b", 0, 1000).unwrap(); let again = Replay::default(); for e in [&a, &b, &b] { again.replay(e, 500).unwrap(); } assert!(again.claim("ns", "a", 500, 600).is_some()); assert!(again.claim("ns", "b", 500, 600).is_none()); assert!(again.replay(&json!({ "t": ENTRY, "ns": "x" }), 0).is_err()); assert!( again .replay( &json!({ "t": ENTRY, "ns": "x", "v": "short", "until": 5 }), 0 ) .is_err() ); } }