1use super::{MAX_CHALLENGE_BYTES, MIN_CHALLENGE_BYTES};
17
18#[derive(Debug, Clone)]
20pub struct ServerChallenge {
21 pub value: Vec<u8>,
23 pub window_end: u64,
25 pub accept_until: u64,
30}
31
32impl ServerChallenge {
33 pub fn new(value: Vec<u8>, window_end: u64, accept_until: u64) -> Self {
35 assert!(
36 value.len() >= MIN_CHALLENGE_BYTES && value.len() <= MAX_CHALLENGE_BYTES,
37 "challenge value must be {MIN_CHALLENGE_BYTES}..{MAX_CHALLENGE_BYTES} bytes"
38 );
39 Self {
40 value,
41 window_end,
42 accept_until,
43 }
44 }
45
46 pub fn is_valid_at(&self, presented: &[u8], now: u64) -> bool {
50 presented == self.value && now < self.accept_until
51 }
52
53 pub fn replay_record_expiry(&self, proof_exp: u64) -> u64 {
57 proof_exp.min(self.accept_until)
58 }
59}
60
61pub struct ChallengeManager {
66 challenges: parking_lot::RwLock<Vec<ServerChallenge>>,
70 overlap_seconds: u64,
73 window_seconds: u64,
75 generator: Option<Box<dyn Fn() -> Vec<u8> + Send + Sync>>,
79}
80
81pub const DEFAULT_CHALLENGE_WINDOW_SECS: u64 = 30;
85
86pub const DEFAULT_CHALLENGE_OVERLAP_SECS: u64 = 5;
89
90#[cfg(not(target_arch = "wasm32"))]
92pub fn random_challenge_value() -> Vec<u8> {
93 use rand::RngCore;
94 let mut bytes = vec![0u8; 32];
95 rand::rngs::OsRng.fill_bytes(&mut bytes);
96 debug_assert!(bytes.iter().any(|b| *b != 0), "CSPRNG returned all zeroes");
97 bytes
98}
99
100impl ChallengeManager {
101 pub fn new(initial: ServerChallenge, overlap_seconds: u64) -> Self {
104 Self {
105 challenges: parking_lot::RwLock::new(vec![initial]),
106 overlap_seconds,
107 window_seconds: DEFAULT_CHALLENGE_WINDOW_SECS,
108 generator: None,
109 }
110 }
111
112 #[cfg(not(target_arch = "wasm32"))]
129 pub fn rotating_for_domain(
130 domain: super::admission::ReplayDomainGuarantee,
131 window_seconds: u64,
132 overlap_seconds: u64,
133 now: u64,
134 ) -> Option<Self> {
135 if domain != super::admission::ReplayDomainGuarantee::SingleVerifierInstance {
136 return None;
137 }
138 Some(Self::rotating_with(
139 window_seconds,
140 overlap_seconds,
141 now,
142 random_challenge_value,
143 ))
144 }
145
146 pub fn rotating_with<F>(
149 window_seconds: u64,
150 overlap_seconds: u64,
151 now: u64,
152 generator: F,
153 ) -> Self
154 where
155 F: Fn() -> Vec<u8> + Send + Sync + 'static,
156 {
157 let initial = ServerChallenge::new(
158 generator(),
159 now + window_seconds,
160 now + window_seconds + overlap_seconds,
161 );
162 Self {
163 challenges: parking_lot::RwLock::new(vec![initial]),
164 overlap_seconds,
165 window_seconds,
166 generator: Some(Box::new(generator)),
167 }
168 }
169
170 pub fn current_or_rotate(&self, now: u64) -> Option<ServerChallenge> {
177 if let Some(current) = self.current(now) {
178 if now < current.window_end {
179 return Some(current);
180 }
181 }
182 let generator = self.generator.as_ref()?;
183 let mut chals = self.challenges.write();
184 if let Some(current) = chals.iter().rev().find(|c| now < c.window_end) {
186 return Some(current.clone());
187 }
188 let window_end = now + self.window_seconds;
189 let fresh =
190 ServerChallenge::new(generator(), window_end, window_end + self.overlap_seconds);
191 chals.retain(|c| c.accept_until > now);
192 chals.push(fresh.clone());
193 Some(fresh)
194 }
195
196 pub fn current(&self, now: u64) -> Option<ServerChallenge> {
201 let chals = self.challenges.read();
202 chals.iter().rev().find(|c| now < c.accept_until).cloned()
203 }
204
205 pub fn validate(&self, presented: &[u8], now: u64) -> Option<u64> {
211 let chals = self.challenges.read();
212 chals
213 .iter()
214 .find(|c| c.is_valid_at(presented, now))
215 .map(|c| c.accept_until)
216 }
217
218 pub fn rotate(&self, value: Vec<u8>, window_seconds: u64, now: u64) {
222 let window_end = now + window_seconds;
223 let accept_until = window_end + self.overlap_seconds;
224 let new = ServerChallenge::new(value, window_end, accept_until);
225 let mut chals = self.challenges.write();
226 chals.retain(|c| c.accept_until > now);
228 chals.push(new);
230 }
231}
232
233#[cfg(test)]
234#[allow(clippy::unwrap_used, clippy::expect_used)]
235mod tests {
236 use super::*;
237
238 #[test]
239 fn challenge_valid_within_window() {
240 let ch = ServerChallenge::new(vec![0xab; 16], 1000, 1010);
241 assert!(ch.is_valid_at(&[0xab; 16], 1005));
242 }
243
244 #[test]
245 fn challenge_invalid_after_deadline() {
246 let ch = ServerChallenge::new(vec![0xab; 16], 1000, 1010);
247 assert!(!ch.is_valid_at(&[0xab; 16], 1010));
248 assert!(!ch.is_valid_at(&[0xab; 16], 1020));
249 }
250
251 #[test]
252 fn challenge_invalid_wrong_value() {
253 let ch = ServerChallenge::new(vec![0xab; 16], 1000, 1010);
254 assert!(!ch.is_valid_at(&[0xcd; 16], 1005));
255 }
256
257 #[test]
258 fn replay_record_expiry_uses_min() {
259 let ch = ServerChallenge::new(vec![0xab; 16], 1000, 1010);
260 assert_eq!(ch.replay_record_expiry(1050), 1010);
262 assert_eq!(ch.replay_record_expiry(1005), 1005);
264 }
265
266 #[test]
272 fn validate_returns_the_matched_challenge_deadline_not_the_current_one() {
273 let mgr = ChallengeManager::new(ServerChallenge::new(vec![0x01; 16], 1000, 1005), 5);
274 mgr.rotate(vec![0x02; 16], 30, 1000); let old = mgr
277 .validate(&[0x01; 16], 1002)
278 .expect("rotated-out challenge is still acceptable inside its overlap");
279 let new = mgr
280 .validate(&[0x02; 16], 1002)
281 .expect("current challenge is acceptable");
282
283 assert_eq!(old, 1005, "matched deadline must be the old challenge's");
284 assert_eq!(new, 1035);
285 assert_ne!(
286 old,
287 mgr.current(1002)
288 .expect("a current challenge exists")
289 .accept_until,
290 "the matched deadline must not be the current challenge's deadline"
291 );
292 assert_eq!(1_000_000u64.min(old), 1005);
294 }
295
296 #[test]
299 fn validate_denies_expired_value_while_a_newer_one_is_live() {
300 let mgr = ChallengeManager::new(ServerChallenge::new(vec![0x01; 16], 1000, 1005), 5);
301 mgr.rotate(vec![0x02; 16], 30, 1000);
302 assert_eq!(mgr.validate(&[0x01; 16], 1006), None);
303 assert_eq!(mgr.validate(&[0x02; 16], 1006), Some(1035));
304 }
305
306 #[test]
308 fn validate_denies_unknown_value() {
309 let mgr = ChallengeManager::new(ServerChallenge::new(vec![0x01; 16], 1000, 1005), 5);
310 assert_eq!(mgr.validate(&[0xff; 16], 1002), None);
311 }
312
313 #[test]
316 fn rotation_prunes_expired_challenges() {
317 let mgr = ChallengeManager::new(ServerChallenge::new(vec![0x01; 16], 1000, 1005), 5);
318 mgr.rotate(vec![0x02; 16], 30, 1010);
319 assert_eq!(mgr.validate(&[0x01; 16], 1002), None);
320 assert_eq!(mgr.challenges.read().len(), 1);
321 }
322
323 #[test]
326 fn current_is_none_when_rotation_has_stalled() {
327 let mgr = ChallengeManager::new(ServerChallenge::new(vec![0x01; 16], 1000, 1005), 5);
328 assert!(mgr.current(1006).is_none());
329 assert!(
330 mgr.current_or_rotate(1006).is_none(),
331 "a manager with no value source cannot invent one"
332 );
333 }
334
335 fn counting_generator() -> impl Fn() -> Vec<u8> + Send + Sync + 'static {
338 let n = std::sync::atomic::AtomicU8::new(0);
339 move || {
340 let v = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
341 vec![v; 16]
342 }
343 }
344
345 #[test]
346 fn a_rotating_manager_starts_with_a_usable_challenge() {
347 let mgr = ChallengeManager::rotating_with(30, 5, 1000, counting_generator());
348 let ch = mgr.current_or_rotate(1000).expect("startup challenge");
349 assert_eq!(ch.value, vec![0u8; 16]);
350 assert_eq!(ch.window_end, 1030);
351 assert_eq!(ch.accept_until, 1035);
352 assert_eq!(mgr.validate(&ch.value, 1000), Some(1035));
353 }
354
355 #[test]
358 fn rotation_happens_when_the_window_elapses() {
359 let mgr = ChallengeManager::rotating_with(30, 5, 1000, counting_generator());
360 let first = mgr.current_or_rotate(1000).unwrap();
361 assert_eq!(mgr.current_or_rotate(1029).unwrap().value, first.value);
362
363 let second = mgr.current_or_rotate(1030).unwrap();
364 assert_ne!(second.value, first.value);
365
366 assert_eq!(mgr.validate(&first.value, 1032), Some(1035));
369 assert_eq!(mgr.validate(&first.value, 1035), None);
370 assert_eq!(mgr.validate(&second.value, 1032), Some(1065));
371 }
372
373 #[test]
375 fn a_long_idle_gap_produces_a_fresh_challenge() {
376 let mgr = ChallengeManager::rotating_with(30, 5, 1000, counting_generator());
377 let first = mgr.current_or_rotate(1000).unwrap();
378 let later = mgr.current_or_rotate(9_000).expect("a fresh challenge");
379 assert_ne!(later.value, first.value);
380 assert!(later.accept_until > 9_000);
381 assert_eq!(
382 mgr.validate(&first.value, 9_000),
383 None,
384 "the long-dead value must not re-validate"
385 );
386 }
387
388 #[cfg(not(target_arch = "wasm32"))]
389 #[test]
390 fn generated_challenge_values_are_random_and_in_profile() {
391 let a = random_challenge_value();
392 let b = random_challenge_value();
393 assert_eq!(a.len(), 32);
394 assert!(a.len() >= MIN_CHALLENGE_BYTES && a.len() <= MAX_CHALLENGE_BYTES);
395 assert_ne!(a, b, "two draws must not collide");
396 assert!(a.iter().any(|byte| *byte != 0));
397 }
398}