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