Skip to main content

quantaegis_drbg/
health.rs

1//! **NIST SP 800-90B Section 4.4** raw-noise continuous, startup, and on-demand health tests.
2//!
3//! # Critical FIPS 140-3 Scope Boundary
4//! Per **NIST SP 800-90B Sections 4.2–4.4** and **CMVP FIPS 140-3 IG D.T / D.U**, the Repetition
5//! Count Test (RCT) and Adaptive Proportion Test (APT) apply **exclusively to unconditioned raw
6//! samples emitted directly by a physical or jitter noise source**.
7//!
8//! They MUST NOT be applied post-hoc to already-conditioned OS CSPRNG outputs (such as `getrandom`,
9//! `BCryptGenRandom`, or `WebCrypto`) to claim ESV compliance.
10
11use quantaegis_core::{Error, Result, Zeroize};
12
13/// Minimum number of consecutive raw noise samples required for the SP 800-90B Section 4.3
14/// startup health test (`1,024`).
15pub const STARTUP_SAMPLE_COUNT: usize = 1_024;
16
17/// Default SP 800-90B Section 4.4.2 Adaptive Proportion Test window size for non-binary
18/// (multi-bit / byte) noise samples (`512`).
19pub const APT_NON_BINARY_WINDOW: usize = 512;
20
21/// SP 800-90B Section 4.4.2 Adaptive Proportion Test window size for binary (`0`/`1`) noise
22/// samples (`1,024`).
23pub const APT_BINARY_WINDOW: usize = 1_024;
24
25/// Standard SP 800-90B Section 4.4.2 APT alphabet category locking the fixed window size `W`.
26#[derive(Copy, Clone, Debug, Eq, PartialEq)]
27pub enum AptSourceKind {
28    /// Binary noise source (`0` / `1` samples): fixed window `W = 1,024`.
29    Binary,
30    /// Non-binary noise source (multi-bit symbols): fixed window `W = 512`.
31    NonBinary,
32}
33
34impl AptSourceKind {
35    /// Returns the SP 800-90B Section 4.4.2 mandated window size `W`.
36    #[inline]
37    pub const fn window_size(self) -> usize {
38        match self {
39            Self::Binary => APT_BINARY_WINDOW,
40            Self::NonBinary => APT_NON_BINARY_WINDOW,
41        }
42    }
43}
44
45/// **SP 800-90B Section 4.4.1 Repetition Count Test (RCT)** for raw noise samples.
46///
47/// Fails permanently with [`Error::EntropyHealthCheckFailed`] if the same sample value repeats
48/// `cutoff` or more consecutive times.
49pub struct RepetitionCountTest {
50    cutoff: u32,
51    last_sample: u64,
52    run_count: u32,
53    initialized: bool,
54    failed: bool,
55}
56
57impl RepetitionCountTest {
58    /// Creates a new RCT with cutoff `C >= 2` (computed from the noise source's assessed
59    /// min-entropy `H` and false-positive bound `alpha` per SP 800-90B §4.4.1).
60    pub const fn new(cutoff: u32) -> Result<Self> {
61        if cutoff < 2 {
62            return Err(Error::DrbgInvalidRequest);
63        }
64        Ok(Self {
65            cutoff,
66            last_sample: 0,
67            run_count: 0,
68            initialized: false,
69            failed: false,
70        })
71    }
72
73    /// Feeds one unconditioned raw noise sample into the RCT.
74    ///
75    /// Once failed, the test remains latched in the failure state.
76    pub fn observe(&mut self, sample: u64) -> Result<()> {
77        if self.failed {
78            return Err(Error::EntropyHealthCheckFailed);
79        }
80        if !self.initialized {
81            self.last_sample = sample;
82            self.run_count = 1;
83            self.initialized = true;
84            return Ok(());
85        }
86        if sample == self.last_sample {
87            self.run_count = self.run_count.saturating_add(1);
88            if self.run_count >= self.cutoff {
89                self.failed = true;
90                return Err(Error::EntropyHealthCheckFailed);
91            }
92        } else {
93            self.last_sample = sample;
94            self.run_count = 1;
95        }
96        Ok(())
97    }
98
99    /// Returns `true` if the RCT has latched a health-check failure.
100    #[inline]
101    pub const fn is_failed(&self) -> bool {
102        self.failed
103    }
104}
105
106impl Zeroize for RepetitionCountTest {
107    #[inline]
108    fn zeroize(&mut self) {
109        self.last_sample = 0;
110        self.run_count = 0;
111        self.initialized = false;
112    }
113}
114
115impl Drop for RepetitionCountTest {
116    #[inline]
117    fn drop(&mut self) {
118        self.zeroize();
119    }
120}
121
122/// **SP 800-90B Section 4.4.2 Adaptive Proportion Test (APT)** for raw noise samples.
123///
124/// Counts occurrences of the first sample in each fixed window of size `window_size` (`512` for
125/// non-binary sources or `1,024` for binary sources) and fails permanently with
126/// [`Error::EntropyHealthCheckFailed`] if the count reaches `cutoff`.
127pub struct AdaptiveProportionTest {
128    window_size: usize,
129    cutoff: u32,
130    reference_sample: u64,
131    matches_in_window: u32,
132    samples_in_window: usize,
133    failed: bool,
134}
135
136impl AdaptiveProportionTest {
137    /// Creates a new APT with `window_size >= 2` and `2 <= cutoff <= window_size`.
138    ///
139    /// For approved SP 800-90B noise sources, prefer [`Self::for_source_kind`] or
140    /// [`RawNoiseHealthMonitor::new`], which lock `window_size` to `1,024` (binary) or `512`
141    /// (non-binary).
142    pub const fn new(window_size: usize, cutoff: u32) -> Result<Self> {
143        if window_size < 2 || cutoff < 2 || (cutoff as usize) > window_size {
144            return Err(Error::DrbgInvalidRequest);
145        }
146        Ok(Self {
147            window_size,
148            cutoff,
149            reference_sample: 0,
150            matches_in_window: 0,
151            samples_in_window: 0,
152            failed: false,
153        })
154    }
155
156    /// Creates an APT locked to the SP 800-90B Section 4.4.2 standard window for `kind`.
157    pub const fn for_source_kind(kind: AptSourceKind, cutoff: u32) -> Result<Self> {
158        Self::new(kind.window_size(), cutoff)
159    }
160
161    /// Feeds one unconditioned raw noise sample into the APT.
162    ///
163    /// Once failed, the test remains latched in the failure state.
164    pub fn observe(&mut self, sample: u64) -> Result<()> {
165        if self.failed {
166            return Err(Error::EntropyHealthCheckFailed);
167        }
168        if self.samples_in_window == 0 {
169            self.reference_sample = sample;
170            self.matches_in_window = 1;
171            self.samples_in_window = 1;
172            return Ok(());
173        }
174
175        if sample == self.reference_sample {
176            self.matches_in_window = self.matches_in_window.saturating_add(1);
177            if self.matches_in_window >= self.cutoff {
178                self.failed = true;
179                return Err(Error::EntropyHealthCheckFailed);
180            }
181        }
182
183        self.samples_in_window += 1;
184        if self.samples_in_window >= self.window_size {
185            self.samples_in_window = 0;
186            self.matches_in_window = 0;
187            self.reference_sample = 0;
188        }
189        Ok(())
190    }
191
192    /// Returns `true` if the APT has latched a health-check failure.
193    #[inline]
194    pub const fn is_failed(&self) -> bool {
195        self.failed
196    }
197}
198
199impl Zeroize for AdaptiveProportionTest {
200    #[inline]
201    fn zeroize(&mut self) {
202        self.reference_sample = 0;
203        self.matches_in_window = 0;
204        self.samples_in_window = 0;
205    }
206}
207
208impl Drop for AdaptiveProportionTest {
209    #[inline]
210    fn drop(&mut self) {
211        self.zeroize();
212    }
213}
214
215/// Lifecycle monitor connecting SP 800-90B startup, continuous, and on-demand health tests for an
216/// unconditioned raw noise source.
217///
218/// Blocks readiness ([`Self::is_ready`] returns `false`) until [`STARTUP_SAMPLE_COUNT`] (`1,024`)
219/// consecutive raw samples pass both RCT and APT, then seamlessly carries RCT/APT state into
220/// continuous monitoring. Any failure latches permanently on the monitor.
221pub struct RawNoiseHealthMonitor {
222    rct: RepetitionCountTest,
223    apt: AdaptiveProportionTest,
224    startup_passed: usize,
225    failed: bool,
226}
227
228impl RawNoiseHealthMonitor {
229    /// Creates a new monitor with SP 800-90B mandated APT window (`1,024` binary / `512` non-binary)
230    /// and assessed cutoffs derived from the noise source's min-entropy and false-positive bound.
231    pub fn new(rct_cutoff: u32, kind: AptSourceKind, apt_cutoff: u32) -> Result<Self> {
232        let rct = RepetitionCountTest::new(rct_cutoff)?;
233        let apt = AdaptiveProportionTest::for_source_kind(kind, apt_cutoff)?;
234        Ok(Self {
235            rct,
236            apt,
237            startup_passed: 0,
238            failed: false,
239        })
240    }
241
242    /// Observes one unconditioned raw noise sample.
243    ///
244    /// Returns:
245    /// - `Ok(false)` while still executing the 1,024-sample startup test (output MUST remain blocked),
246    /// - `Ok(true)` once startup has completed and continuous health holds,
247    /// - `Err(Error::EntropyHealthCheckFailed)` on any RCT/APT failure (latched permanently).
248    pub fn observe(&mut self, sample: u64) -> Result<bool> {
249        if self.failed {
250            return Err(Error::EntropyHealthCheckFailed);
251        }
252        if self.rct.observe(sample).is_err() || self.apt.observe(sample).is_err() {
253            self.failed = true;
254            return Err(Error::EntropyHealthCheckFailed);
255        }
256        if self.startup_passed < STARTUP_SAMPLE_COUNT {
257            self.startup_passed += 1;
258        }
259        Ok(self.is_ready())
260    }
261
262    /// Runs an SP 800-90B Section 4.2 on-demand health test over at least `1,024` consecutive raw
263    /// samples; any failure permanently latches this monitor.
264    pub fn run_on_demand_test(&mut self, samples: &[u64]) -> Result<()> {
265        if self.failed {
266            return Err(Error::EntropyHealthCheckFailed);
267        }
268        if samples.len() < STARTUP_SAMPLE_COUNT {
269            return Err(Error::DrbgInvalidRequest);
270        }
271        for &sample in samples {
272            if self.observe(sample).is_err() {
273                return Err(Error::EntropyHealthCheckFailed);
274            }
275        }
276        Ok(())
277    }
278
279    /// Returns `true` iff the 1,024-sample startup test has completed and no failure has latched.
280    #[inline]
281    pub const fn is_ready(&self) -> bool {
282        !self.failed && self.startup_passed >= STARTUP_SAMPLE_COUNT
283    }
284
285    /// Returns `true` iff a permanent health-check failure has latched.
286    #[inline]
287    pub const fn is_failed(&self) -> bool {
288        self.failed
289    }
290}
291
292impl Zeroize for RawNoiseHealthMonitor {
293    #[inline]
294    fn zeroize(&mut self) {
295        self.rct.zeroize();
296        self.apt.zeroize();
297        self.startup_passed = 0;
298    }
299}
300
301impl Drop for RawNoiseHealthMonitor {
302    #[inline]
303    fn drop(&mut self) {
304        self.zeroize();
305    }
306}
307
308/// Runs a standalone **SP 800-90B Section 4.3 startup / on-demand health test** (RCT + APT) over
309/// a slice of at least [`STARTUP_SAMPLE_COUNT`] (`1,024`) consecutive unconditioned raw samples.
310pub fn run_raw_noise_health_test(
311    samples: &[u64],
312    rct_cutoff: u32,
313    apt_window: usize,
314    apt_cutoff: u32,
315) -> Result<()> {
316    if samples.len() < STARTUP_SAMPLE_COUNT {
317        return Err(Error::DrbgInvalidRequest);
318    }
319    let mut rct = RepetitionCountTest::new(rct_cutoff)?;
320    let mut apt = AdaptiveProportionTest::new(apt_window, apt_cutoff)?;
321    for &sample in samples {
322        rct.observe(sample)?;
323        apt.observe(sample)?;
324    }
325    Ok(())
326}
327
328#[cfg(test)]
329#[allow(clippy::expect_used)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn rct_triggers_at_exact_cutoff_and_latches() {
335        let mut rct = RepetitionCountTest::new(4).expect("valid cutoff");
336        assert_eq!(rct.observe(7), Ok(()));
337        assert_eq!(rct.observe(7), Ok(()));
338        assert_eq!(rct.observe(7), Ok(()));
339        assert_eq!(rct.observe(7), Err(Error::EntropyHealthCheckFailed));
340        assert!(rct.is_failed());
341        assert_eq!(rct.observe(8), Err(Error::EntropyHealthCheckFailed));
342    }
343
344    #[test]
345    fn apt_triggers_on_exact_last_sample_of_window_and_resets_otherwise() {
346        // Window size 4, cutoff 3: match on 1st, 2nd, and exact last (4th) sample fails.
347        let mut apt = AdaptiveProportionTest::new(4, 3).expect("valid apt");
348        assert_eq!(apt.observe(9), Ok(()));
349        assert_eq!(apt.observe(9), Ok(()));
350        assert_eq!(apt.observe(1), Ok(()));
351        assert_eq!(apt.observe(9), Err(Error::EntropyHealthCheckFailed));
352        assert!(apt.is_failed());
353        assert_eq!(apt.observe(2), Err(Error::EntropyHealthCheckFailed));
354
355        // Window 1 passes (2 matches < 3), window resets cleanly for Window 2.
356        let mut apt2 = AdaptiveProportionTest::new(4, 3).expect("valid apt");
357        assert_eq!(apt2.observe(9), Ok(()));
358        assert_eq!(apt2.observe(1), Ok(()));
359        assert_eq!(apt2.observe(9), Ok(()));
360        assert_eq!(apt2.observe(2), Ok(()));
361        assert_eq!(apt2.observe(5), Ok(()));
362        assert_eq!(apt2.observe(5), Ok(()));
363        assert_eq!(apt2.observe(5), Err(Error::EntropyHealthCheckFailed));
364    }
365
366    #[test]
367    fn startup_monitor_blocks_until_1024_and_catches_failure_on_1024th_sample() {
368        // Fails on exact 1,024th sample via RCT (cutoff 4: samples 1020..1023 identical).
369        let mut mon_fail =
370            RawNoiseHealthMonitor::new(4, AptSourceKind::NonBinary, 325).expect("valid monitor");
371        for i in 0..1_020u64 {
372            assert_eq!(mon_fail.observe(i & 0xff), Ok(false));
373            assert!(!mon_fail.is_ready());
374        }
375        assert_eq!(mon_fail.observe(0xfe), Ok(false));
376        assert_eq!(mon_fail.observe(0xfe), Ok(false));
377        assert_eq!(mon_fail.observe(0xfe), Ok(false));
378        // 1,024th sample triggers RCT and permanently latches.
379        assert_eq!(mon_fail.observe(0xfe), Err(Error::EntropyHealthCheckFailed));
380        assert!(mon_fail.is_failed());
381        assert!(!mon_fail.is_ready());
382        assert_eq!(mon_fail.observe(0x01), Err(Error::EntropyHealthCheckFailed));
383
384        // Clean 1,024 samples transition seamlessly into continuous monitoring.
385        let mut mon_ok =
386            RawNoiseHealthMonitor::new(4, AptSourceKind::NonBinary, 325).expect("valid monitor");
387        for i in 0..1_023u64 {
388            assert_eq!(mon_ok.observe(i & 0xff), Ok(false));
389        }
390        assert_eq!(mon_ok.observe(0xaa), Ok(true));
391        assert!(mon_ok.is_ready());
392
393        // Continuous state carries across the startup boundary (3 more 0xaa hits cutoff 4!).
394        assert_eq!(mon_ok.observe(0xaa), Ok(true));
395        assert_eq!(mon_ok.observe(0xaa), Ok(true));
396        assert_eq!(mon_ok.observe(0xaa), Err(Error::EntropyHealthCheckFailed));
397        assert!(!mon_ok.is_ready());
398        assert!(mon_ok.is_failed());
399    }
400
401    #[test]
402    fn standalone_startup_test_requires_at_least_1024_samples() {
403        let short = [0u64; STARTUP_SAMPLE_COUNT - 1];
404        assert_eq!(
405            run_raw_noise_health_test(&short, 5, APT_NON_BINARY_WINDOW, 325),
406            Err(Error::DrbgInvalidRequest)
407        );
408
409        let mut varied = [0u64; STARTUP_SAMPLE_COUNT];
410        for (i, slot) in varied.iter_mut().enumerate() {
411            *slot = (i as u64) & 0xff;
412        }
413        assert_eq!(
414            run_raw_noise_health_test(&varied, 5, APT_NON_BINARY_WINDOW, 325),
415            Ok(())
416        );
417    }
418}