Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/fuzz_parsers.rs
536 lines · 21.7 KBRaw History
1//! fuzz_parsers — T16 / Gate G4: robustness (fuzz) targets for the LTX and WAL
2//! parsers.
3//!
4//! ## Contract under test
5//! The two byte-format readers in this crate — [`celld_ltx::ltx`]'s decode
6//! family ([`decode_file`], [`decode_file_pages`], [`decode_database_image`], and
7//! the `Header`/`PageHeader`/`Trailer` field parsers) and the SQLite WAL reader
8//! ([`WalReader`]) — are the **untrusted-input boundary**: every byte they see
9//! comes from object storage or a possibly-truncated/partially-written WAL on
10//! disk. The hard invariant for that boundary is:
11//!
12//! > For **any** input slice — empty, truncated, random, or an adversarially
13//! > mutated copy of a real file — these functions return `Err` (or a valid
14//! > parse). They MUST NOT panic, abort, hang, or read out of bounds.
15//!
16//! This mirrors the spirit of the upstream Go fuzz target
17//! `restore_fuzz_test.go` (`FuzzRestoreWithMissingCompactedFile`), which asserts
18//! the *restore pipeline* survives a randomly-deleted compacted file. We do not
19//! have compaction (KEEP scope is L0-only), so this suite instead drives the two
20//! lower-level parsers directly with malformed bytes — the resilience surface
21//! that actually parses untrusted input. Go gets this no-panic property "for
22//! free" from `recover()`/bounds-checked slices returning errors; in Rust an
23//! out-of-range slice *panics*, so the property must be asserted explicitly.
24//!
25//! ## How "no panic" is asserted
26//! Each parser call runs inside [`std::panic::catch_unwind`]. A caught panic
27//! fails the test and prints the exact input bytes (hex) plus the deterministic
28//! seed, so any regression is reproducible. A returned `Err` (or `Ok`) is the
29//! pass condition. (The panic hook is silenced for the duration so a *passing*
30//! run is quiet even though we are deliberately not panicking.)
31//!
32//! ## Determinism & budget
33//! cargo-fuzz is not wired up in this repo (no nightly/libFuzzer dependency in
34//! KEEP scope), so this is the "bounded in-tree fuzz-style test" the task allows:
35//! a fixed iteration budget driven by a small, self-contained SplitMix64 PRNG
36//! seeded from a constant. No new dependency, and every iteration is byte-for-byte
37//! reproducible from [`SEED`]. The corpus is the union of:
38//! * a hand-written **adversarial** set (empty, 1 byte, exactly a header,
39//! all-zeros, valid-magic-then-garbage, huge declared index size, …),
40//! * **random** buffers of random length, and
41//! * **mutated golden** bytes — the real-litestream L0 `.ltx` files and the
42//! golden SQLite WAL, hit with bit flips, byte sets, truncations, splices and
43//! zero-runs (the highest-signal fuzz inputs: structurally *almost* valid).
44
45use celld_ltx::ltx;
46use celld_ltx::wal::WalReader;
47use std::path::PathBuf;
48
49// ── Iteration budget (bounded so `cargo test` stays fast & reproducible) ─────
50
51/// Random-buffer iterations per parser.
52const RANDOM_ITERS: usize = 20_000;
53/// Mutation iterations per golden seed file. Bounded so the whole suite stays
54/// fast: each "almost valid" mutation can drive a full decode (LZ4 + checksum)
55/// across all three decode entrypoints, so this is the dominant cost. 800 × 6
56/// LTX seeds (= 4_800 mutated files) still hits every one of the 9 mutation
57/// strategies hundreds of times each. Raise locally for a longer soak.
58const MUTATION_ITERS: usize = 800;
59/// Fixed PRNG seed — every run is identical; a failure reproduces from this.
60const SEED: u64 = 0x5279_5374_795F_5232; // "RySty_R2"
61
62// ── Self-contained deterministic PRNG (SplitMix64) ───────────────────────────
63//
64// A tiny, well-known generator: zero dependencies, fully reproducible, fast
65// enough for tens of thousands of iterations. We only need "random-ish" bytes to
66// poke the parsers; statistical quality is irrelevant.
67struct SplitMix64(u64);
68
69impl SplitMix64 {
70 fn new(seed: u64) -> Self {
71 SplitMix64(seed)
72 }
73 #[inline]
74 fn next_u64(&mut self) -> u64 {
75 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
76 let mut z = self.0;
77 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
78 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
79 z ^ (z >> 31)
80 }
81 #[inline]
82 fn next_byte(&mut self) -> u8 {
83 self.next_u64() as u8
84 }
85 /// Uniform-ish in `[0, n)` for small `n` (modulo bias is irrelevant here).
86 #[inline]
87 fn below(&mut self, n: usize) -> usize {
88 if n == 0 {
89 0
90 } else {
91 (self.next_u64() % n as u64) as usize
92 }
93 }
94 fn fill(&mut self, buf: &mut [u8]) {
95 for b in buf.iter_mut() {
96 *b = self.next_byte();
97 }
98 }
99}
100
101// ── Golden-corpus loaders (read-only ground truth) ───────────────────────────
102
103/// All six real-litestream golden L0 `.ltx` files (immutable fixtures).
104fn golden_ltx_files() -> Vec<Vec<u8>> {
105 let mut base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
106 base.push("tests/fixtures/golden/replica/ltx/0");
107 (1u64..=6)
108 .map(|i| {
109 let name = format!("{:016x}-{:016x}.ltx", i, i);
110 let p = base.join(&name);
111 std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display()))
112 })
113 .collect()
114}
115
116/// The golden SQLite WAL fixture (immutable).
117fn golden_wal() -> Vec<u8> {
118 let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
119 p.push("tests/fixtures/golden/sample.wal");
120 std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display()))
121}
122
123// ── Panic-capture harness ────────────────────────────────────────────────────
124
125/// Runs `f` (a parser call on `input`) and converts a panic into a test failure
126/// that prints the offending bytes + seed for reproduction. The return value of
127/// `f` is intentionally discarded — we only care that it returned *something*
128/// rather than unwinding.
129fn assert_no_panic<T>(label: &str, input: &[u8], f: impl FnOnce() -> T + std::panic::UnwindSafe) {
130 let result = std::panic::catch_unwind(f);
131 if result.is_err() {
132 panic!(
133 "PANIC in {label} on {}-byte input (must return Err, never panic).\n\
134 seed=0x{SEED:016x}\nbytes(hex)={}",
135 input.len(),
136 hex_preview(input),
137 );
138 }
139}
140
141/// Hex of the input, capped so a failure message stays readable for big buffers.
142fn hex_preview(b: &[u8]) -> String {
143 const CAP: usize = 512;
144 let shown = &b[..b.len().min(CAP)];
145 let mut s = String::with_capacity(shown.len() * 2 + 16);
146 for byte in shown {
147 s.push_str(&format!("{byte:02x}"));
148 }
149 if b.len() > CAP {
150 s.push_str(&format!("… (+{} more bytes)", b.len() - CAP));
151 }
152 s
153}
154
155/// Drives EVERY LTX parser entrypoint over one input and asserts none panic.
156/// This is the function whose no-panic property the whole suite is protecting.
157fn exercise_ltx(input: &[u8]) {
158 // The three public decode entrypoints (the untrusted-input boundary the
159 // restore path and fault-injection rely on).
160 assert_no_panic("ltx::decode_file", input, || {
161 let _ = ltx::decode_file(input);
162 });
163 assert_no_panic("ltx::decode_file_pages", input, || {
164 let _ = ltx::decode_file_pages(input);
165 });
166 assert_no_panic("ltx::decode_database_image", input, || {
167 let _ = ltx::decode_database_image(input);
168 });
169 // The fixed-width field parsers (called with the raw slice; each must guard
170 // its own length rather than slicing blindly).
171 assert_no_panic("ltx::Header::parse", input, || {
172 let _ = ltx::Header::parse(input);
173 });
174 assert_no_panic("ltx::PageHeader::parse", input, || {
175 let _ = ltx::PageHeader::parse(input);
176 });
177 assert_no_panic("ltx::Trailer::parse", input, || {
178 let _ = ltx::Trailer::parse(input);
179 });
180}
181
182/// Drives the WAL reader over one input and asserts no panic: construction, a
183/// bounded `read_frame` drain, the `page_map` aggregation, a `frame_salts_until`
184/// scan, and `new_with_offset` at a handful of adversarial offsets.
185fn exercise_wal(input: &[u8]) {
186 assert_no_panic("WalReader::new+read_frame", input, || {
187 if let Ok(mut r) = WalReader::new(input) {
188 // Drain frames with a hard cap so a crafted header advertising a
189 // tiny page size can't make this loop run unboundedly.
190 let ps = r.page_size() as usize;
191 // A zero page size would make `read_frame`'s buffer empty; the reader
192 // must still terminate (it returns BufferSize/EOF), but guard anyway.
193 let mut buf = vec![0u8; ps];
194 for _ in 0..100_000 {
195 match r.read_frame(&mut buf) {
196 Ok(_) => {}
197 Err(_) => break,
198 }
199 }
200 }
201 });
202
203 assert_no_panic("WalReader::page_map", input, || {
204 if let Ok(mut r) = WalReader::new(input) {
205 let _ = r.page_map();
206 }
207 });
208
209 assert_no_panic("WalReader::frame_salts_until", input, || {
210 if let Ok(r) = WalReader::new(input) {
211 // Until a salt that very likely never appears → forces a full scan to
212 // EOF (the longest path through the scanner).
213 let _ = r.frame_salts_until((0xDEAD_BEEF, 0xFEED_FACE));
214 }
215 });
216
217 // Adversarial offsets into new_with_offset: negative-ish (0), the header
218 // boundary, unaligned, and well past EOF. None may panic.
219 for &off in &[
220 0i64,
221 celld_ltx::WAL_HEADER_SIZE as i64,
222 celld_ltx::WAL_HEADER_SIZE as i64 + 7,
223 celld_ltx::WAL_HEADER_SIZE as i64 + 4096 + 24,
224 i64::from(u32::MAX),
225 i64::MAX,
226 ] {
227 assert_no_panic("WalReader::new_with_offset", input, move || {
228 let _ = WalReader::new_with_offset(input, off, 0x1234_5678, 0x9ABC_DEF0);
229 });
230 }
231}
232
233// ── Byte-mutation strategies (applied to a fresh copy of a golden file) ──────
234
235/// Mutates `seed_bytes` in place with one randomly-chosen strategy and returns
236/// the result. Strategies are weighted toward "structurally almost valid"
237/// mutations (single/multi bit flips, field-sized byte sets, truncations) — the
238/// inputs most likely to slip past an early guard and reach deep indexing.
239fn mutate(rng: &mut SplitMix64, seed_bytes: &[u8]) -> Vec<u8> {
240 let mut b = seed_bytes.to_vec();
241 match rng.below(9) {
242 // Flip a single bit.
243 0 => {
244 if !b.is_empty() {
245 let i = rng.below(b.len());
246 b[i] ^= 1 << rng.below(8);
247 }
248 }
249 // Flip several bits at random positions.
250 1 => {
251 let k = 1 + rng.below(16);
252 for _ in 0..k {
253 if b.is_empty() {
254 break;
255 }
256 let i = rng.below(b.len());
257 b[i] ^= 1 << rng.below(8);
258 }
259 }
260 // Set a random byte to a random value.
261 2 => {
262 if !b.is_empty() {
263 let i = rng.below(b.len());
264 b[i] = rng.next_byte();
265 }
266 }
267 // Overwrite a contiguous run with random bytes (corrupt a whole field).
268 3 => {
269 if !b.is_empty() {
270 let start = rng.below(b.len());
271 let span = 1 + rng.below(16.min(b.len() - start).max(1));
272 for x in b.iter_mut().skip(start).take(span) {
273 *x = rng.next_byte();
274 }
275 }
276 }
277 // Truncate to a random shorter length (partial write / short read).
278 4 => {
279 let new_len = rng.below(b.len() + 1);
280 b.truncate(new_len);
281 }
282 // Truncate to *just below* a structural boundary (header / +page header /
283 // index size field) — boundary-adjacent lengths flush off-by-one bugs.
284 5 => {
285 let boundaries = [
286 ltx::HEADER_SIZE,
287 ltx::HEADER_SIZE + ltx::PAGE_HEADER_SIZE,
288 ltx::HEADER_SIZE + 1,
289 ltx::TRAILER_SIZE,
290 ltx::TRAILER_SIZE + 8,
291 b.len().saturating_sub(1),
292 b.len().saturating_sub(ltx::TRAILER_SIZE),
293 ];
294 let target = boundaries[rng.below(boundaries.len())];
295 b.truncate(target.min(b.len()));
296 }
297 // Zero out a contiguous run (e.g. wipe the magic, a length field, salts).
298 6 => {
299 if !b.is_empty() {
300 let start = rng.below(b.len());
301 let span = 1 + rng.below(32.min(b.len() - start).max(1));
302 for x in b.iter_mut().skip(start).take(span) {
303 *x = 0;
304 }
305 }
306 }
307 // Append random trailing bytes (overlong file / wrong size field).
308 7 => {
309 let extra = rng.below(64);
310 for _ in 0..extra {
311 b.push(rng.next_byte());
312 }
313 }
314 // Splice: drop a random middle chunk (shifts every later offset).
315 _ => {
316 if b.len() > 2 {
317 let start = rng.below(b.len());
318 let span = 1 + rng.below((b.len() - start).max(1));
319 let end = (start + span).min(b.len());
320 b.drain(start..end);
321 }
322 }
323 }
324 b
325}
326
327// ── Hand-written adversarial corpus (deterministic, always run) ──────────────
328
329/// Structured edge cases that target specific indexing arithmetic in the
330/// decoders. These are the cases a human reviewer would reach for; the random +
331/// mutation sweeps then widen coverage around them.
332fn adversarial_ltx_corpus() -> Vec<Vec<u8>> {
333 let floor = ltx::HEADER_SIZE + ltx::PAGE_HEADER_SIZE + 8 + ltx::TRAILER_SIZE;
334 // Degenerate lengths.
335 let mut v: Vec<Vec<u8>> = vec![
336 vec![], // empty
337 vec![0x00], // 1 byte
338 b"LTX".to_vec(), // partial magic
339 b"LTX1".to_vec(), // magic only
340 vec![0x00; ltx::HEADER_SIZE - 1], // one short of a header
341 vec![0x00; ltx::HEADER_SIZE], // exactly a (zero) header
342 vec![0xFF; ltx::HEADER_SIZE], // all-ones header
343 vec![0x00; floor], // the decode_file length floor, all zero
344 ];
345
346 // Valid magic, then garbage geometry of various plausible sizes.
347 for extra in [0usize, 8, 16, 32, 100, 200, 1000] {
348 let mut b = vec![0u8; ltx::HEADER_SIZE + extra];
349 b[0..4].copy_from_slice(ltx::MAGIC);
350 v.push(b);
351 }
352
353 // Valid magic + a header whose declared page-index size field is enormous
354 // (forces `checked_sub` underflow → must be Err, not panic). Build a buffer
355 // at the floor length and write 0xFFFF_FFFF_FFFF_FFFF into the size field.
356 {
357 let len = floor;
358 let mut b = vec![0u8; len];
359 b[0..4].copy_from_slice(ltx::MAGIC);
360 let size_off = len - ltx::TRAILER_SIZE - 8;
361 b[size_off..size_off + 8].copy_from_slice(&u64::MAX.to_be_bytes());
362 v.push(b);
363 }
364 // Same, but index size = exactly size_field_off (idx_start == 0 → below the
365 // header floor → Err) and index size = size_field_off+1 (underflow → Err).
366 for delta in [0i64, 1, -1] {
367 let len = floor + 64;
368 let mut b = vec![0u8; len];
369 b[0..4].copy_from_slice(ltx::MAGIC);
370 let size_off = len - ltx::TRAILER_SIZE - 8;
371 let declared = (size_off as i64 + delta).max(0) as u64;
372 b[size_off..size_off + 8].copy_from_slice(&declared.to_be_bytes());
373 v.push(b);
374 }
375
376 v
377}
378
379/// Adversarial WAL headers: every magic boundary, zero/huge page sizes, partial
380/// headers, and an otherwise-valid-looking header with a bogus checksum.
381fn adversarial_wal_corpus() -> Vec<Vec<u8>> {
382 let mut v: Vec<Vec<u8>> = vec![
383 vec![], // empty
384 vec![0x00; 10], // partial header
385 vec![0x00; celld_ltx::WAL_HEADER_SIZE], // zero header (bad magic)
386 ];
387
388 // Both valid magics with a zero page-size field (page size 0 is a footgun for
389 // the frame loop's buffer sizing).
390 for magic in [0x377f_0682u32, 0x377f_0683u32] {
391 let mut b = vec![0u8; celld_ltx::WAL_HEADER_SIZE];
392 b[0..4].copy_from_slice(&magic.to_be_bytes());
393 // version = 3007000 so we get past the version gate to the geometry.
394 b[4..8].copy_from_slice(&3_007_000u32.to_be_bytes());
395 // page size left 0.
396 v.push(b);
397 }
398 // Valid magic + huge page size (0x4000_0000) + a single short frame: the frame
399 // loop must not try to allocate/scan past the actual buffer.
400 {
401 let mut b = vec![0u8; celld_ltx::WAL_HEADER_SIZE + 100];
402 b[0..4].copy_from_slice(&0x377f_0682u32.to_be_bytes());
403 b[4..8].copy_from_slice(&3_007_000u32.to_be_bytes());
404 b[8..12].copy_from_slice(&0x4000_0000u32.to_be_bytes());
405 v.push(b);
406 }
407 v
408}
409
410// ── Tests ─────────────────────────────────────────────────────────────────────
411
412/// LTX decoders survive the hand-written adversarial corpus with no panic.
413#[test]
414fn ltx_adversarial_corpus_never_panics() {
415 for input in adversarial_ltx_corpus() {
416 exercise_ltx(&input);
417 }
418}
419
420/// **Regression guard**: the exact short-input that used to panic in
421/// `decode_database_image` (it sliced `bytes[0..HEADER_SIZE]` before any length
422/// check). It must now return an error, never unwind. Kept as a named test so the
423/// regression is obvious if it ever reappears.
424#[test]
425fn ltx_decode_database_image_short_input_returns_err_not_panic() {
426 for len in [0usize, 1, 10, 50, ltx::HEADER_SIZE - 1] {
427 let input = vec![0u8; len];
428 // Must not panic …
429 exercise_ltx(&input);
430 // … and specifically must be an Err (a short buffer is never a valid DB).
431 assert!(
432 ltx::decode_database_image(&input).is_err(),
433 "decode_database_image on {len} zero bytes must be Err"
434 );
435 }
436}
437
438/// LTX decoders survive a large sweep of fully-random buffers (random length and
439/// content) with no panic.
440#[test]
441fn ltx_random_bytes_never_panic() {
442 let mut rng = SplitMix64::new(SEED ^ 0x1111_1111_1111_1111);
443 // Bias lengths toward the structurally-interesting small range, but include
444 // some large buffers too.
445 let max_floor = ltx::HEADER_SIZE + ltx::PAGE_HEADER_SIZE + 8 + ltx::TRAILER_SIZE;
446 for _ in 0..RANDOM_ITERS {
447 let len = match rng.below(4) {
448 0 => rng.below(max_floor + 4), // sub/at the length floor
449 1 => max_floor + rng.below(256),
450 2 => rng.below(2048),
451 _ => rng.below(8192),
452 };
453 let mut buf = vec![0u8; len];
454 rng.fill(&mut buf);
455 // ~1 in 6 buffers gets a correct magic so more of them reach deep parsing.
456 if len >= 4 && rng.below(6) == 0 {
457 buf[0..4].copy_from_slice(ltx::MAGIC);
458 }
459 exercise_ltx(&buf);
460 }
461}
462
463/// LTX decoders survive mutated copies of every real golden `.ltx` file. These
464/// "almost valid" inputs are the highest-signal fuzz cases — they pass the early
465/// magic/length guards and exercise the page-walk, index, and checksum paths.
466#[test]
467fn ltx_mutated_golden_never_panics() {
468 let seeds = golden_ltx_files();
469 let mut rng = SplitMix64::new(SEED ^ 0x2222_2222_2222_2222);
470 for (idx, seed) in seeds.iter().enumerate() {
471 // Sanity: the pristine golden file decodes (proves the seed is real and
472 // our mutations are perturbing a genuinely-valid file).
473 assert!(
474 ltx::decode_file(seed).is_ok(),
475 "golden ltx seed #{idx} must decode cleanly before mutation"
476 );
477 for _ in 0..MUTATION_ITERS {
478 let m = mutate(&mut rng, seed);
479 exercise_ltx(&m);
480 }
481 }
482}
483
484/// WAL reader survives the hand-written adversarial header corpus with no panic.
485#[test]
486fn wal_adversarial_corpus_never_panics() {
487 for input in adversarial_wal_corpus() {
488 exercise_wal(&input);
489 }
490}
491
492/// WAL reader survives a large sweep of fully-random buffers with no panic.
493#[test]
494fn wal_random_bytes_never_panic() {
495 let mut rng = SplitMix64::new(SEED ^ 0x3333_3333_3333_3333);
496 for _ in 0..RANDOM_ITERS {
497 let len = match rng.below(4) {
498 0 => rng.below(celld_ltx::WAL_HEADER_SIZE + 4),
499 1 => celld_ltx::WAL_HEADER_SIZE + rng.below(256),
500 2 => rng.below(4096),
501 _ => rng.below(20_000),
502 };
503 let mut buf = vec![0u8; len];
504 rng.fill(&mut buf);
505 // Occasionally stamp a valid magic + version so the reader proceeds past
506 // the header into frame parsing.
507 if len >= celld_ltx::WAL_HEADER_SIZE && rng.below(5) == 0 {
508 let magic = if rng.below(2) == 0 {
509 0x377f_0682u32
510 } else {
511 0x377f_0683u32
512 };
513 buf[0..4].copy_from_slice(&magic.to_be_bytes());
514 buf[4..8].copy_from_slice(&3_007_000u32.to_be_bytes());
515 }
516 exercise_wal(&buf);
517 }
518}
519
520/// WAL reader survives mutated copies of the real golden SQLite WAL with no
521/// panic. Bit flips / truncations of a valid WAL probe the header-checksum,
522/// salt, frame-checksum, and offset arithmetic on near-valid input.
523#[test]
524fn wal_mutated_golden_never_panics() {
525 let seed = golden_wal();
526 // Sanity: the pristine WAL header is accepted (a real, valid seed).
527 assert!(
528 WalReader::new(&seed).is_ok(),
529 "golden WAL must construct a reader before mutation"
530 );
531 let mut rng = SplitMix64::new(SEED ^ 0x4444_4444_4444_4444);
532 for _ in 0..(MUTATION_ITERS * 2) {
533 let m = mutate(&mut rng, &seed);
534 exercise_wal(&m);
535 }
536}