Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/fuzz_bundle.rs
218 lines · 7.2 KBRaw History
1//! fuzz_bundle — robustness targets for the bundle envelope
2//! ([`celld_ltx::bundle`]), in the style of `fuzz_parsers.rs`.
3//!
4//! ## Contract under test
5//! `decode_rows` and `slice` are an untrusted-input boundary: every byte
6//! they see comes from object storage. The invariants:
7//!
8//! > For ANY input slice — empty, truncated, random, or an adversarially
9//! > mutated copy of a real bundle — `decode_rows` returns `Err` or a
10//! > valid parse, and `slice` on any returned row returns `Err` or an
11//! > in-bounds slice. They MUST NOT panic or read out of bounds.
12//!
13//! > A TRUNCATED bundle is refused deterministically: the trailer (footer
14//! > length + magic) sits at the object's end, so any proper prefix of a
15//! > bundle whose payloads do not embed a counterfeit trailer fails to
16//! > decode. Torn objects cannot exist at rest (an object store PUT is
17//! > atomic), so this discipline is defense in depth for the read path,
18//! > not a crash-recovery requirement.
19//!
20//! A payload CAN embed counterfeit trailer bytes — the envelope adds no
21//! checksum, by the envelope rule (never a new format). For such inputs
22//! the boundary contract still holds: a coincidental parse yields rows
23//! whose slices are bounds-checked, and the corrupt L0 bytes they carry
24//! are caught downstream by the LTX checksums the per-cell path already
25//! validates.
26
27use celld_ltx::bundle::{decode_rows, encode, slice, BundleEntry};
28
29const RANDOM_ITERS: usize = 20_000;
30const MUTATION_ITERS: usize = 4_000;
31const SEED: u64 = 0x424E_444C_5F52_5931; // "BNDL_RY1"
32
33struct SplitMix64(u64);
34
35impl SplitMix64 {
36 fn next_u64(&mut self) -> u64 {
37 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
38 let mut z = self.0;
39 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
40 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
41 z ^ (z >> 31)
42 }
43
44 fn below(&mut self, n: usize) -> usize {
45 (self.next_u64() % n as u64) as usize
46 }
47
48 fn fill(&mut self, buf: &mut [u8]) {
49 for byte in buf.iter_mut() {
50 *byte = self.next_u64() as u8;
51 }
52 }
53}
54
55fn assert_no_panic(label: &str, input: &[u8]) {
56 let hook = std::panic::take_hook();
57 std::panic::set_hook(Box::new(|_| {}));
58 let outcome = std::panic::catch_unwind(|| {
59 if let Ok(rows) = decode_rows(input) {
60 for row in &rows {
61 // Err or an in-bounds slice; a panic here is the failure.
62 let _ = slice(input, row);
63 }
64 }
65 });
66 std::panic::set_hook(hook);
67 assert!(
68 outcome.is_ok(),
69 "{label}: panic on {} bytes: {:02x?}",
70 input.len(),
71 &input[..input.len().min(64)]
72 );
73}
74
75/// A representative bundle whose payloads carry no counterfeit trailer.
76fn golden() -> Vec<u8> {
77 let entries = vec![
78 BundleEntry {
79 cell: "cell-alpha".into(),
80 cell_epoch: 2,
81 txid: 41,
82 bytes: vec![0x11; 96],
83 },
84 BundleEntry {
85 cell: "cell-beta".into(),
86 cell_epoch: 7,
87 txid: 1,
88 bytes: Vec::new(),
89 },
90 BundleEntry {
91 cell: "z".into(),
92 cell_epoch: 1,
93 txid: u64::MAX,
94 bytes: vec![0x22; 7],
95 },
96 ];
97 encode(&entries).unwrap()
98}
99
100#[test]
101fn every_truncation_of_a_bundle_is_refused() {
102 let bundle = golden();
103 for cut in 0..bundle.len() {
104 assert!(
105 decode_rows(&bundle[..cut]).is_err(),
106 "a {cut}-byte prefix of a {}-byte bundle must not decode",
107 bundle.len()
108 );
109 }
110}
111
112#[test]
113fn random_bytes_never_panic() {
114 let mut rng = SplitMix64(SEED);
115 for _ in 0..RANDOM_ITERS {
116 let mut buf = vec![0_u8; rng.below(512)];
117 rng.fill(&mut buf);
118 assert_no_panic("random", &buf);
119 }
120}
121
122#[test]
123fn mutated_golden_never_panics() {
124 let bundle = golden();
125 let mut rng = SplitMix64(SEED ^ 0xACE1);
126 for _ in 0..MUTATION_ITERS {
127 let mut copy = bundle.clone();
128 match rng.below(5) {
129 // Bit flip.
130 0 => {
131 let index = rng.below(copy.len());
132 copy[index] ^= 1 << rng.below(8);
133 }
134 // Byte set.
135 1 => {
136 let index = rng.below(copy.len());
137 copy[index] = rng.next_u64() as u8;
138 }
139 // Truncate.
140 2 => copy.truncate(rng.below(copy.len())),
141 // Splice two halves at mismatched offsets.
142 3 => {
143 let a = rng.below(copy.len());
144 let b = rng.below(copy.len());
145 let tail: Vec<u8> = copy[b..].to_vec();
146 copy.truncate(a);
147 copy.extend_from_slice(&tail);
148 }
149 // Zero a run.
150 _ => {
151 let start = rng.below(copy.len());
152 let len = rng.below(copy.len() - start + 1);
153 for byte in &mut copy[start..start + len] {
154 *byte = 0;
155 }
156 }
157 }
158 assert_no_panic("mutated", &copy);
159 }
160}
161
162/// A payload that embeds a counterfeit trailer must still honor the
163/// boundary contract when the object is cut exactly at the counterfeit.
164#[test]
165fn an_embedded_counterfeit_trailer_stays_in_bounds() {
166 // The payload's final 8 bytes claim "footer of length 0" + magic, so
167 // the prefix ending at the payload IS a decodable (empty) bundle;
168 // deeper cuts and full reads must parse or refuse without panicking.
169 let mut payload = vec![0x33_u8; 40];
170 payload.extend_from_slice(&0_u32.to_le_bytes());
171 payload.extend_from_slice(b"CLB1");
172 let bundle = encode(&[BundleEntry {
173 cell: "trap".into(),
174 cell_epoch: 1,
175 txid: 1,
176 bytes: payload,
177 }])
178 .unwrap();
179 for cut in 0..=bundle.len() {
180 assert_no_panic("counterfeit", &bundle[..cut]);
181 }
182 // The complete object still decodes to the true row, byte-identical.
183 let rows = decode_rows(&bundle).unwrap();
184 assert_eq!(rows.len(), 1);
185 assert_eq!(slice(&bundle, &rows[0]).unwrap().len(), 48);
186}
187
188/// Round-trip property over randomized entries: whatever goes in comes
189/// back byte-identical, including empty payloads and empty bundles.
190#[test]
191fn random_round_trips_are_byte_identical() {
192 let mut rng = SplitMix64(SEED ^ 0x5EED);
193 for _ in 0..200 {
194 let count = rng.below(6);
195 let entries: Vec<BundleEntry> = (0..count)
196 .map(|index| {
197 let mut bytes = vec![0_u8; rng.below(300)];
198 rng.fill(&mut bytes);
199 BundleEntry {
200 cell: format!("cell-{index}-{}", rng.below(1000)),
201 cell_epoch: rng.next_u64(),
202 txid: rng.next_u64(),
203 bytes,
204 }
205 })
206 .collect();
207 let bundle = encode(&entries).unwrap();
208 let rows = decode_rows(&bundle).unwrap();
209 assert_eq!(rows.len(), entries.len());
210 for (row, entry) in rows.iter().zip(&entries) {
211 assert_eq!(slice(&bundle, row).unwrap(), entry.bytes.as_slice());
212 assert_eq!(
213 (row.cell.as_str(), row.cell_epoch, row.txid),
214 (entry.cell.as_str(), entry.cell_epoch, entry.txid)
215 );
216 }
217 }
218}