Skip to main content

hyprstream_rpc/proof/
challenge.rs

1//! Server challenge protocol for unattributed proofs.
2//!
3//! For unattributed proofs the server challenge (CWT `Nonce`, RFC 9711) is
4//! REQUIRED, not optional. The server maintains a rotating opaque challenge
5//! with a short reviewed window. Clients MAY reuse the current challenge
6//! across requests while `request_id` remains unique per request. A missing,
7//! expired, or unknown challenge in an unattributed proof denies before any
8//! replay-store insertion.
9//!
10//! Every `DispatchDenied` response carries the current challenge uniformly,
11//! regardless of the internal denial cause. A client without a challenge
12//! sends its request, receives `DispatchDenied` bearing a usable challenge,
13//! and performs at most one immediate bounded retry with a fresh
14//! `request_id`.
15
16use super::{MAX_CHALLENGE_BYTES, MIN_CHALLENGE_BYTES};
17
18/// A rotating server challenge with its acceptance deadline.
19#[derive(Debug, Clone)]
20pub struct ServerChallenge {
21    /// The opaque challenge value (16..64 bytes).
22    pub value: Vec<u8>,
23    /// The nominal window end (Unix seconds).
24    pub window_end: u64,
25    /// The acceptance deadline: `window_end` plus one bounded overlap for
26    /// retry and clock skew. A proof citing this value verifies iff
27    /// `verifier_now < challenge_accept_until` everywhere in the replay
28    /// admission domain.
29    pub accept_until: u64,
30}
31
32impl ServerChallenge {
33    /// Create a new challenge with the given value and deadline.
34    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    /// Check whether a presented challenge value is current at the given time.
47    ///
48    /// Returns `true` if the value matches and `now` precedes `accept_until`.
49    pub fn is_valid_at(&self, presented: &[u8], now: u64) -> bool {
50        presented == self.value && now < self.accept_until
51    }
52
53    /// The replay-record expiry for an unattributed proof using this challenge.
54    ///
55    /// `replay_record_expiry = min(proof.exp, challenge_accept_until)`
56    pub fn replay_record_expiry(&self, proof_exp: u64) -> u64 {
57        proof_exp.min(self.accept_until)
58    }
59}
60
61/// A rotating challenge manager that produces and validates challenges.
62///
63/// In production this rotates on a reviewed schedule (e.g. every 30 seconds
64/// with a 5-second overlap). Tests can use fixed values.
65pub struct ChallengeManager {
66    /// All still-acceptable challenges, including the current one and any
67    /// rotated-out values whose `accept_until` has not passed. A proof
68    /// citing any of these values validates if `now < accept_until`.
69    challenges: parking_lot::RwLock<Vec<ServerChallenge>>,
70    /// The overlap duration in seconds (how long after rotation a previous
71    /// challenge is still accepted).
72    overlap_seconds: u64,
73    /// The nominal rotation window in seconds, used by lazy rotation.
74    window_seconds: u64,
75    /// Source of fresh challenge values. `None` disables self-rotation — the
76    /// manager then only serves values a caller supplied explicitly, which is
77    /// how the deterministic tests drive rotation boundaries.
78    generator: Option<Box<dyn Fn() -> Vec<u8> + Send + Sync>>,
79}
80
81/// The default rotation window: short enough that stockpiling an unattributed
82/// proof is useless, long enough that a client may reuse one challenge across
83/// requests.
84pub const DEFAULT_CHALLENGE_WINDOW_SECS: u64 = 30;
85
86/// The default acceptance overlap past a window's end: one bounded retry plus
87/// clock skew, never a whole following window.
88pub const DEFAULT_CHALLENGE_OVERLAP_SECS: u64 = 5;
89
90/// Generate a fresh 32-byte challenge value from the OS CSPRNG.
91#[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    /// Create with an initial challenge and a rotation overlap. Self-rotation
102    /// is disabled: the caller drives [`Self::rotate`] explicitly.
103    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    /// Create a self-rotating manager seeded from the OS CSPRNG, for a
113    /// deployment whose replay admission domain is a single verifier instance.
114    ///
115    /// Rotation is lazy rather than timer-driven: the current challenge is
116    /// regenerated when its window has elapsed, at the moment it is next
117    /// needed. A server that stops serving therefore cannot leave a stale
118    /// challenge advertised, and there is no rotation task to stall.
119    ///
120    /// Returns `None` for any other replay domain. Challenge validity is
121    /// scoped to the replay admission domain and has **one exact deadline
122    /// shared by verification and replay garbage collection** (§4.7): an
123    /// independently random per-process challenge cannot provide that across
124    /// several verifiers, so a shared or affine-routed domain must install a
125    /// domain-wide challenge source instead of this one. Refusing here is why
126    /// a multi-instance deployment cannot silently disagree about challenge
127    /// freshness.
128    #[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    /// Self-rotating manager over an explicit value source. Production passes
147    /// [`random_challenge_value`]; tests pass a deterministic sequence.
148    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    /// The challenge to advertise on a denial, rotating first if the current
171    /// window has elapsed.
172    ///
173    /// Returns `None` only when the manager cannot produce one — a manager
174    /// with no value source whose challenges have all expired. The caller then
175    /// refuses service rather than advertising an unusable challenge.
176    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        // Re-check under the write lock: another thread may have rotated.
185        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    /// Get the current (newest still-valid) challenge for attaching to
197    /// `DispatchDenied`. Returns `None` if rotation has stalled and all
198    /// challenges have expired — the caller must refuse service rather than
199    /// advertise an unusable challenge.
200    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    /// Validate a presented challenge against all still-acceptable values.
206    /// Returns the matched challenge's `accept_until` if valid, or `None`.
207    /// This atomically returns the deadline so the caller can compute
208    /// `min(proof.exp, accept_until)` without a TOCTOU race against
209    /// rotation.
210    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    /// Rotate to a new challenge value. The previous challenge(s) remain
219    /// accepted until their own `accept_until` deadline, so a retry that
220    /// crosses rotation is not denied early.
221    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        // Prune expired challenges (accept_until has passed).
227        chals.retain(|c| c.accept_until > now);
228        // Push the new challenge.
229        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        // proof.exp = 1050, challenge_accept_until = 1010 → min = 1010
261        assert_eq!(ch.replay_record_expiry(1050), 1010);
262        // proof.exp = 1005, challenge_accept_until = 1010 → min = 1005
263        assert_eq!(ch.replay_record_expiry(1005), 1005);
264    }
265
266    /// A proof citing a rotated-out but still-acceptable challenge must be
267    /// retained against **its own** `accept_until`, not the current
268    /// challenge's. Validating and then separately reading `current()` would
269    /// return the wrong (later) deadline and let a rotated-out proof outlive
270    /// its acceptance window.
271    #[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); // new: window_end 1030, accept_until 1035
275
276        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        // The retention window follows the matched deadline.
293        assert_eq!(1_000_000u64.min(old), 1005);
294    }
295
296    /// Validation is a single atomic read: a value whose own deadline has
297    /// passed denies even while a newer challenge is live.
298    #[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    /// An unknown value denies regardless of timing.
307    #[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    /// Rotation prunes values whose acceptance deadline has passed, so a
314    /// stockpiled proof citing a long-dead challenge can never re-validate.
315    #[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    /// When every challenge has expired the manager advertises nothing: the
324    /// caller must refuse service rather than publish an unusable challenge.
325    #[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    // -- self-rotation -----------------------------------------------------
336
337    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    /// Rotation is lazy: the value is stable inside its window and changes
356    /// once the window has elapsed.
357    #[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        // The rotated-out value stays acceptable through its own overlap, and
367        // still reports its own deadline — a conforming retry is not denied.
368        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    /// A long idle gap does not leave an expired challenge advertised.
374    #[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}