ratify_protocol/challenge_store.rs
1//! ChallengeStore — single-use tracking for verifier-issued challenges
2//! (SPEC §10).
3//!
4//! `verify_bundle` consumes a challenge through this interface at the
5//! locked point in the algorithm: after the structural, chain, and
6//! challenge-signature checks pass, and before authorization evaluation —
7//! so a forged presentation cannot burn a legitimate challenge, and a
8//! cryptographically valid presentation spends its challenge even when
9//! authorization is subsequently denied.
10//!
11//! The bundled implementation is in-memory ([`MemoryChallengeStore`],
12//! `std` only). Deployments that need issuance state to survive restarts
13//! or span verifier replicas implement the trait over shared storage;
14//! `consume` MUST remain atomic (compare-and-set) so two concurrent
15//! presentations of one challenge cannot both succeed.
16
17#[cfg(not(feature = "std"))]
18use alloc::{string::String, vec::Vec};
19
20/// The uniform rejection detail for a challenge that cannot be consumed:
21/// never issued, expired, already consumed, or issued under a different
22/// session binding. Deliberately identical across those cases so a
23/// rejection's public detail does not distinguish them. `verify_bundle`
24/// normalizes EVERY store failure — custom-store error strings included —
25/// to this text in the public result, so implementations cannot leak
26/// record state through error strings even accidentally.
27pub const UNKNOWN_CHALLENGE: &str =
28 "challenge was not issued by this verifier or has already been used";
29
30/// Tracks verifier-issued challenges so each is accepted at most once
31/// within its freshness window (SPEC §10).
32pub trait ChallengeStore {
33 /// Generate a fresh challenge bound to `session_context` (which must
34 /// be empty or exactly 32 bytes; empty = unbound), valid for
35 /// `ttl_seconds` (which must be positive). Returns the challenge and
36 /// its expiry (unix seconds).
37 fn issue(&self, session_context: &[u8], ttl_seconds: i64) -> Result<(Vec<u8>, i64), String>;
38
39 /// Report whether `challenge` could be consumed right now — issued,
40 /// unexpired, unconsumed, and bound to `session_context` — WITHOUT
41 /// consuming it. `verify_bundle` calls this before any signature work.
42 fn validate(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String>;
43
44 /// Atomically remove the challenge's issuance record. Exactly one
45 /// consume of a given challenge may ever succeed; all later calls
46 /// (and calls with a mismatched `session_context`, which do NOT
47 /// remove the record) return an error. Removing the record keeps the
48 /// store's capacity a count of PENDING challenges — a consumed
49 /// challenge frees its slot immediately.
50 fn consume(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String>;
51}
52
53// A shared reference to a store is itself a store, so one store can serve
54// many verifications (`challenge_store: Some(Box::new(&store))`).
55impl<T: ChallengeStore + ?Sized> ChallengeStore for &T {
56 fn issue(&self, session_context: &[u8], ttl_seconds: i64) -> Result<(Vec<u8>, i64), String> {
57 (**self).issue(session_context, ttl_seconds)
58 }
59 fn validate(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String> {
60 (**self).validate(challenge, session_context, now)
61 }
62 fn consume(&self, challenge: &[u8], session_context: &[u8], now: i64) -> Result<(), String> {
63 (**self).consume(challenge, session_context, now)
64 }
65}
66
67#[cfg(feature = "std")]
68mod memory {
69 use super::{ChallengeStore, UNKNOWN_CHALLENGE};
70 use crate::canonical::base64_std_encode;
71 use crate::crypto::generate_challenge;
72 use std::collections::HashMap;
73 use std::string::{String, ToString};
74 use std::sync::Mutex;
75 use std::time::{SystemTime, UNIX_EPOCH};
76 use std::vec::Vec;
77
78 struct Record {
79 session_context: Vec<u8>,
80 expires_at: i64,
81 }
82
83 /// In-memory [`ChallengeStore`]: mutex-guarded map with lazy expiry
84 /// and a capacity cap. Single-process only — state does not survive
85 /// restarts (an unconsumed challenge dies with the process, which
86 /// fails closed), and replicas sharing verification traffic would
87 /// each accept the same challenge once. Deployments spanning
88 /// processes or hosts need a [`ChallengeStore`] over shared storage
89 /// whose `consume` is atomic (e.g. a single-row DELETE ... RETURNING).
90 pub struct MemoryChallengeStore {
91 records: Mutex<HashMap<String, Record>>,
92 max_size: usize,
93 }
94
95 impl MemoryChallengeStore {
96 /// Create a store holding at most `max_size` pending challenges.
97 ///
98 /// # Panics
99 ///
100 /// Panics if `max_size` is 0 — a store that can never hold a
101 /// challenge is a misconfiguration, not a policy.
102 pub fn new(max_size: usize) -> Self {
103 assert!(
104 max_size > 0,
105 "MemoryChallengeStore max_size must be >= 1, got 0"
106 );
107 MemoryChallengeStore {
108 records: Mutex::new(HashMap::new()),
109 max_size,
110 }
111 }
112
113 fn expire(records: &mut HashMap<String, Record>, now: i64) {
114 records.retain(|_, r| r.expires_at >= now);
115 }
116
117 /// Resolve a presentable record key, or None. A session-context
118 /// mismatch fails WITHOUT touching the record, so a presentation
119 /// under the wrong binding cannot burn the legitimate one.
120 fn lookup(
121 records: &mut HashMap<String, Record>,
122 challenge: &[u8],
123 session_context: &[u8],
124 now: i64,
125 ) -> Option<String> {
126 Self::expire(records, now);
127 let key = base64_std_encode(challenge);
128 match records.get(&key) {
129 Some(r) if r.session_context == session_context => Some(key),
130 _ => None,
131 }
132 }
133 }
134
135 impl ChallengeStore for MemoryChallengeStore {
136 fn issue(
137 &self,
138 session_context: &[u8],
139 ttl_seconds: i64,
140 ) -> Result<(Vec<u8>, i64), String> {
141 if !session_context.is_empty() && session_context.len() != 32 {
142 return Err(format!(
143 "session context must be empty or 32 bytes, got {}",
144 session_context.len()
145 ));
146 }
147 if ttl_seconds <= 0 {
148 return Err(format!(
149 "challenge ttl must be positive, got {}",
150 ttl_seconds
151 ));
152 }
153 let now = SystemTime::now()
154 .duration_since(UNIX_EPOCH)
155 .unwrap_or_default()
156 .as_secs() as i64;
157 let expires_at = now + ttl_seconds;
158 let challenge = generate_challenge();
159 let mut records = self.records.lock().expect("challenge store lock poisoned");
160 Self::expire(&mut records, now);
161 if records.len() >= self.max_size {
162 return Err("challenge store full — too many pending challenges".to_string());
163 }
164 records.insert(
165 base64_std_encode(&challenge),
166 Record {
167 session_context: session_context.to_vec(),
168 expires_at,
169 },
170 );
171 Ok((challenge, expires_at))
172 }
173
174 fn validate(
175 &self,
176 challenge: &[u8],
177 session_context: &[u8],
178 now: i64,
179 ) -> Result<(), String> {
180 let mut records = self.records.lock().expect("challenge store lock poisoned");
181 match Self::lookup(&mut records, challenge, session_context, now) {
182 Some(_) => Ok(()),
183 None => Err(UNKNOWN_CHALLENGE.to_string()),
184 }
185 }
186
187 // Check-and-remove under one lock: of two concurrent
188 // presentations of the same challenge, exactly one can succeed.
189 // Removal frees the record's capacity slot immediately; a
190 // session-context mismatch leaves the record in place.
191 fn consume(
192 &self,
193 challenge: &[u8],
194 session_context: &[u8],
195 now: i64,
196 ) -> Result<(), String> {
197 let mut records = self.records.lock().expect("challenge store lock poisoned");
198 match Self::lookup(&mut records, challenge, session_context, now) {
199 Some(key) => {
200 records.remove(&key);
201 Ok(())
202 }
203 None => Err(UNKNOWN_CHALLENGE.to_string()),
204 }
205 }
206 }
207}
208
209#[cfg(feature = "std")]
210pub use memory::MemoryChallengeStore;