Skip to main content

qualia_core_db/net/qdnf/harness/
fuzz.rs

1//! E21.2 — deterministic bounded codec campaign. Not libFuzzer.
2
3use core::sync::atomic::{AtomicBool, Ordering};
4
5use crate::net::qdnf::frame::{decode_frame, encode_frame, FrameHeader};
6use crate::net::qdnf::link::discovery::Beacon;
7use crate::net::qdnf::policy_labels::{decode_label_into, encode_label_into, LabelFields};
8use crate::net::qdnf::registries::{FrameType, NextProtocol};
9use crate::net::qdnf::types::{LinkId, StrongDigest};
10
11/// libFuzzer / cargo-fuzz is not wired and has not been executed.
12pub fn libfuzzer_executed() -> bool {
13    false
14}
15
16static BOUNDED_RAN: AtomicBool = AtomicBool::new(false);
17
18/// True after [`run_bounded_codec_fuzz`] completes in this process.
19pub fn bounded_codec_fuzz_executed() -> bool {
20    BOUNDED_RAN.load(Ordering::SeqCst)
21}
22
23/// Campaign iteration cap. Enough to exercise codecs; small enough for CI.
24pub const BOUNDED_FUZZ_ITERATIONS: usize = 4096;
25
26/// Stack scratch for one trial. Tests may allocate; the decode loop does not.
27const SCRATCH: usize = 256;
28
29/// Counts for one campaign. `panics` must stay zero.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct FuzzCounts {
32    pub iterations: usize,
33    pub accepted: usize,
34    pub rejected: usize,
35    pub panics: usize,
36}
37
38fn mix(mut x: u64) -> u64 {
39    x ^= x.wrapping_shl(13);
40    x ^= x.wrapping_shr(7);
41    x ^= x.wrapping_shl(17);
42    x
43}
44
45fn fill_valid_frame(buf: &mut [u8; SCRATCH]) -> usize {
46    let header = FrameHeader::new(FrameType::DiscoveryBeacon, NextProtocol::QLink);
47    encode_frame(&header, &[], buf).unwrap_or(0)
48}
49
50fn fill_valid_beacon(buf: &mut [u8; SCRATCH]) -> usize {
51    let beacon = Beacon {
52        mode: crate::net::qdnf::link::discovery::DiscoveryMode::PrivatePairwise,
53        tag: [0x11u8; 16],
54        link_id: LinkId([0x22u8; 16]),
55        epoch: 7,
56        expiry_unix: 99,
57        mtu: 1280,
58    };
59    beacon.encode(buf).unwrap_or(0)
60}
61
62fn fill_valid_label(buf: &mut [u8; SCRATCH]) -> usize {
63    let mut issuer = StrongDigest::ZERO;
64    issuer.0[0] = 0xA1;
65    issuer.0[47] = 0x5C;
66    let fields = LabelFields::request(
67        crate::net::qdnf::policy_labels::Confidentiality::C1Private,
68        issuer,
69    );
70    encode_label_into(&fields, buf).unwrap_or(0)
71}
72
73/// Seeded byte stream over frame, label, and discovery-beacon decoders.
74///
75/// Never panics on malformed input: each trial is isolated with `catch_unwind`.
76/// The hot decode calls themselves take borrowed slices and stack `LabelFields`.
77pub fn run_bounded_codec_fuzz() -> FuzzCounts {
78    let mut counts = FuzzCounts {
79        iterations: 0,
80        accepted: 0,
81        rejected: 0,
82        panics: 0,
83    };
84    let mut seed = 0xC0DEC0DE_A5A5_u64;
85    let mut i = 0usize;
86    while i < BOUNDED_FUZZ_ITERATIONS {
87        let mut buf = [0u8; SCRATCH];
88        seed = mix(seed.wrapping_add(i as u64));
89        let structured = (seed & 7) == 0;
90        let kind = ((seed >> 3) & 3) as u8;
91        let mut len = if structured {
92            match kind % 3 {
93                0 => fill_valid_frame(&mut buf),
94                1 => fill_valid_label(&mut buf),
95                _ => fill_valid_beacon(&mut buf),
96            }
97        } else {
98            let n = ((seed >> 8) as usize) % (SCRATCH + 1);
99            let mut b = 0usize;
100            while b < n {
101                seed = mix(seed);
102                buf[b] = seed as u8;
103                b += 1;
104            }
105            n
106        };
107        seed = mix(seed);
108        if (seed & 1) == 1 && len > 0 {
109            let idx = ((seed >> 8) as usize) % len.max(1);
110            buf[idx] ^= (seed >> 16) as u8;
111        }
112        if len > SCRATCH {
113            len = SCRATCH;
114        }
115        let slice = &buf[..len];
116        let kind_run = kind;
117        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> bool {
118            match kind_run % 3 {
119                0 => decode_frame(slice).is_ok(),
120                1 => {
121                    let mut fields = LabelFields::blank();
122                    decode_label_into(slice, &mut fields).is_ok()
123                }
124                _ => Beacon::decode(slice).is_ok(),
125            }
126        }));
127        match panicked {
128            Ok(true) => {
129                counts.accepted = counts.accepted.saturating_add(1);
130            }
131            Ok(false) => {
132                counts.rejected = counts.rejected.saturating_add(1);
133            }
134            Err(_) => {
135                counts.panics = counts.panics.saturating_add(1);
136                counts.rejected = counts.rejected.saturating_add(1);
137            }
138        }
139        counts.iterations = counts.iterations.saturating_add(1);
140        i = i.saturating_add(1);
141    }
142    BOUNDED_RAN.store(true, Ordering::SeqCst);
143    counts
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn bounded_codec_fuzz_does_not_panic_and_is_not_libfuzzer() {
152        assert!(!libfuzzer_executed());
153        let counts = run_bounded_codec_fuzz();
154        assert!(bounded_codec_fuzz_executed());
155        assert_eq!(counts.iterations, BOUNDED_FUZZ_ITERATIONS);
156        assert_eq!(counts.panics, 0);
157        assert_eq!(
158            counts.accepted.saturating_add(counts.rejected),
159            counts.iterations
160        );
161        assert!(counts.accepted > 0, "structured seeds must be accepted");
162        assert!(counts.rejected > 0, "mutated bytes must be rejected");
163    }
164
165    #[test]
166    fn empty_and_truncated_inputs_are_rejected_without_panic() {
167        let _ = decode_frame(&[]);
168        let mut fields = LabelFields::blank();
169        let _ = decode_label_into(&[1, 2, 3], &mut fields);
170        let _ = Beacon::decode(&[0u8; 8]);
171        assert!(!libfuzzer_executed());
172    }
173}