Unverified Commit 662fa5a2 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbo-persistence: bounds-check SST block reads

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 4872a879
...@@ -286,7 +286,9 @@ is used (checksum verification and decompression). On Unix, the lookup mapping t ...@@ -286,7 +286,9 @@ is used (checksum verification and decompression). On Unix, the lookup mapping t
- A best-effort `MADV_WILLNEED` for a block that spans more than one page, before any of its bytes is - A best-effort `MADV_WILLNEED` for a block that spans more than one page, before any of its bytes is
read: on its first full read in this open, and on every read of a medium value block (those bypass read: on its first full read in this open, and on every read of a medium value block (those bypass
the block cache). Without the hint, `MADV_RANDOM` would fault such a block in one page at a time. the block cache). Without the hint, `MADV_RANDOM` would fault such a block in one page at a time.
Blocks within a single page, and blocks whose checksum was already verified, get no hint. Blocks within a single page, and blocks whose checksum was already verified, get no hint. The hint
is issued only after the block's range has passed the bounds check, so a corrupt block offset
never causes a hint outside the data section.
If the system page size can't be determined, block hints are skipped, so `MADV_RANDOM` isn't applied If the system page size can't be determined, block hints are skipped, so `MADV_RANDOM` isn't applied
either and the mapping keeps the default advice. either and the mapping keeps the default advice.
......
...@@ -14,7 +14,7 @@ use std::{ ...@@ -14,7 +14,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail, ensure};
use byteorder::{BE, ReadBytesExt}; use byteorder::{BE, ReadBytesExt};
use fs_err::{self as fs, File}; use fs_err::{self as fs, File};
use lz4_flex::block::decompress_into; use lz4_flex::block::decompress_into;
...@@ -306,28 +306,29 @@ struct RawBlock { ...@@ -306,28 +306,29 @@ struct RawBlock {
} }
/// Reads, checksums, and decompresses a single block from the mmap. /// Reads, checksums, and decompresses a single block from the mmap.
///
/// The block's range is validated with the same check the database's readers use, so a corrupt
/// block directory is reported as an error instead of an out-of-bounds slice.
fn read_block( fn read_block(
mmap: &Mmap, mmap: &Mmap,
block_offsets_start: usize, block_offsets_start: usize,
block_index: u16, block_index: u16,
sequence_number: u32, meta: &StaticSortedFileMetaData,
compression: Compression, compression: Compression,
) -> Result<RawBlock> { ) -> Result<RawBlock> {
let offset = block_offsets_start + block_index as usize * size_of::<u32>(); let sequence_number = meta.sequence_number;
let range = meta.block_range(block_index, block_offsets_start, |i| {
let block_start = if block_index == 0 { let offset = block_offsets_start + i * size_of::<u32>();
0 u32::from_be_bytes(mmap[offset..offset + size_of::<u32>()].try_into().unwrap())
} else { })?;
(&mmap[offset - size_of::<u32>()..offset]).read_u32::<BE>()? as usize let block_start = range.start;
};
let block_end = (&mmap[offset..offset + size_of::<u32>()]).read_u32::<BE>()? as usize;
let uncompressed_length = let uncompressed_length =
(&mmap[block_start..block_start + size_of::<u32>()]).read_u32::<BE>()?; (&mmap[block_start..block_start + size_of::<u32>()]).read_u32::<BE>()?;
let expected_checksum = (&mmap let expected_checksum = (&mmap
[block_start + size_of::<u32>()..block_start + BLOCK_HEADER_SIZE]) [block_start + size_of::<u32>()..block_start + BLOCK_HEADER_SIZE])
.read_u32::<BE>()?; .read_u32::<BE>()?;
let compressed_data = &mmap[block_start + BLOCK_HEADER_SIZE..block_end]; let compressed_data = &mmap[block_start + BLOCK_HEADER_SIZE..range.end];
let compressed_size = compressed_data.len() as u64; let compressed_size = compressed_data.len() as u64;
let was_compressed = uncompressed_length > 0; let was_compressed = uncompressed_length > 0;
...@@ -358,9 +359,13 @@ fn read_block( ...@@ -358,9 +359,13 @@ fn read_block(
Compression::Zstd3 => zstd::bulk::decompress_to_buffer(compressed_data, &mut buffer) Compression::Zstd3 => zstd::bulk::decompress_to_buffer(compressed_data, &mut buffer)
.context("zstd decompression failed")?, .context("zstd decompression failed")?,
}; };
assert_eq!( ensure!(
bytes_written, uncompressed_length as usize, bytes_written == uncompressed_length as usize,
"Decompressed length does not match expected" "Decompressed length {} of block {} in {:08}.sst does not match expected {}",
bytes_written,
block_index,
sequence_number,
uncompressed_length
); );
buffer.into_boxed_slice() buffer.into_boxed_slice()
} else { } else {
...@@ -498,11 +503,11 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> { ...@@ -498,11 +503,11 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> {
..Default::default() ..Default::default()
}; };
let block_offsets_start = StaticSortedFileMetaData { let meta = StaticSortedFileMetaData {
sequence_number: info.sequence_number, sequence_number: info.sequence_number,
block_count: info.block_count, block_count: info.block_count,
} };
.checked_block_offsets_start(mmap.len())?; let block_offsets_start = meta.checked_block_offsets_start(mmap.len())?;
// Read the index block (always the last block) first to learn which blocks are key blocks. // Read the index block (always the last block) first to learn which blocks are key blocks.
// Without this, we'd have to guess block types from their first byte, which is wrong for // Without this, we'd have to guess block types from their first byte, which is wrong for
...@@ -512,7 +517,7 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> { ...@@ -512,7 +517,7 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> {
&mmap, &mmap,
block_offsets_start, block_offsets_start,
index_block_index, index_block_index,
info.sequence_number, &meta,
compression, compression,
)?; )?;
let key_block_indices = parse_key_block_indices(&index_raw.data); let key_block_indices = parse_key_block_indices(&index_raw.data);
...@@ -525,13 +530,7 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> { ...@@ -525,13 +530,7 @@ fn analyze_sst_file(db_path: &Path, info: &SstInfo) -> Result<SstStats> {
// Now iterate through all blocks, using the key block set for classification. // Now iterate through all blocks, using the key block set for classification.
for block_index in 0..index_block_index { for block_index in 0..index_block_index {
let raw = match read_block( let raw = match read_block(&mmap, block_offsets_start, block_index, &meta, compression) {
&mmap,
block_offsets_start,
block_index,
info.sequence_number,
compression,
) {
Ok(raw) => raw, Ok(raw) => raw,
Err(e) => { Err(e) => {
eprintln!( eprintln!(
...@@ -986,3 +985,105 @@ fn main() -> Result<()> { ...@@ -986,3 +985,105 @@ fn main() -> Result<()> {
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
/// Writes `bytes` as an SST file, memory-maps it and returns the mapping and its metadata.
/// The temporary directory is returned so the file outlives the mapping.
fn map_sst(
bytes: &[u8],
block_count: u16,
) -> (tempfile::TempDir, Mmap, StaticSortedFileMetaData) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("00000001.sst");
std::fs::write(&path, bytes).unwrap();
let file = File::open(&path).unwrap();
let mmap = unsafe { Mmap::map(file.file()).unwrap() };
let meta = StaticSortedFileMetaData {
sequence_number: 1,
block_count,
};
(dir, mmap, meta)
}
/// Builds an SST from raw block bytes (header included) followed by their end offsets.
fn sst_bytes(blocks: &[Vec<u8>]) -> Vec<u8> {
let mut bytes = blocks.concat();
let mut end = 0;
for block in blocks {
end += block.len() as u32;
bytes.extend_from_slice(&end.to_be_bytes());
}
bytes
}
fn uncompressed_block(data: &[u8]) -> Vec<u8> {
let mut block = 0_u32.to_be_bytes().to_vec();
block.extend_from_slice(&checksum_block(data).to_be_bytes());
block.extend_from_slice(data);
block
}
fn read_err(bytes: &[u8], block_count: u16, block_index: u16) -> String {
let (_dir, mmap, meta) = map_sst(bytes, block_count);
let block_offsets_start = meta.checked_block_offsets_start(mmap.len()).unwrap();
let Err(err) = read_block(
&mmap,
block_offsets_start,
block_index,
&meta,
Compression::Lz4,
) else {
panic!("read_block accepted block {block_index}");
};
format!("{err:#}")
}
#[test]
fn read_block_reads_valid_blocks() {
let bytes = sst_bytes(&[uncompressed_block(b"value"), uncompressed_block(b"\0index")]);
let (_dir, mmap, meta) = map_sst(&bytes, 2);
let block_offsets_start = meta.checked_block_offsets_start(mmap.len()).unwrap();
let raw = read_block(&mmap, block_offsets_start, 0, &meta, Compression::Lz4).unwrap();
assert_eq!(&*raw.data, b"value");
}
#[test]
fn read_block_rejects_out_of_range_block_index() {
let bytes = sst_bytes(&[uncompressed_block(b"index")]);
let message = read_err(&bytes, 1, 1);
assert!(message.contains("out of range"), "{message}");
}
#[test]
fn read_block_rejects_corrupt_value_block_offset() {
let mut bytes = sst_bytes(&[uncompressed_block(b"value"), uncompressed_block(b"index")]);
let directory_start = bytes.len() - 2 * size_of::<u32>();
bytes[directory_start..directory_start + 4].copy_from_slice(&u32::MAX.to_be_bytes());
let message = read_err(&bytes, 2, 0);
assert!(message.contains("not a valid block"), "{message}");
}
#[test]
fn read_block_rejects_corrupt_index_block_offset() {
let mut bytes = sst_bytes(&[uncompressed_block(b"value"), uncompressed_block(b"index")]);
let last_entry = bytes.len() - size_of::<u32>();
bytes[last_entry..].copy_from_slice(&(last_entry as u32 + 1).to_be_bytes());
let message = read_err(&bytes, 2, 1);
assert!(message.contains("not a valid block"), "{message}");
}
#[test]
fn read_block_rejects_decompressed_length_mismatch() {
let data = b"compressible compressible compressible";
let compressed = lz4_flex::block::compress(data);
// Claim one more byte than the compressed data decodes to.
let mut block = (data.len() as u32 + 1).to_be_bytes().to_vec();
block.extend_from_slice(&checksum_block(&compressed).to_be_bytes());
block.extend_from_slice(&compressed);
let message = read_err(&sst_bytes(&[block]), 1, 0);
assert!(message.contains("Decompressed length"), "{message}");
}
}
#[cfg(feature = "mmap")]
use std::ops::Range;
use std::{ use std::{
borrow::Cow, borrow::Cow,
cmp::Ordering, cmp::Ordering,
hash::BuildHasherDefault, hash::BuildHasherDefault,
io, io,
marker::PhantomData, marker::PhantomData,
ops::Range,
path::Path, path::Path,
rc::Rc, rc::Rc,
sync::{ sync::{
...@@ -338,42 +337,76 @@ impl StaticSortedFileMetaData { ...@@ -338,42 +337,76 @@ impl StaticSortedFileMetaData {
) )
}) })
} }
/// The validated byte range (8-byte header followed by the data) of block `block_index`.
///
/// Every block read goes through this check, independent of `strict_checks`: the block
/// directory is not covered by any checksum, so a corrupt offset must surface as an error
/// rather than an out-of-bounds slice or an unbounded allocation. The range is checked to be
/// ordered, large enough for a block header and within the data section that ends where the
/// directory starts at `block_offsets_start`.
///
/// `block_offsets_start` must be the directory start computed for the file's actual length
/// (normally once at open time with [`Self::checked_block_offsets_start`]), so the directory
/// holds `self.block_count` entries. `block_offset(i)` returns the directory's end offset of
/// block `i`; it is only called with `i < self.block_count`, so a reader over that directory
/// cannot go out of bounds.
pub fn block_range(
&self,
block_index: u16,
block_offsets_start: usize,
block_offset: impl Fn(usize) -> u32,
) -> Result<Range<usize>> {
ensure!(
block_index < self.block_count,
"block {} of {:08}.sst is out of range, the file has {} blocks",
block_index,
self.sequence_number,
self.block_count
);
let index = usize::from(block_index);
let start = if index == 0 {
0
} else {
block_offset(index - 1) as usize
};
let end = block_offset(index) as usize;
ensure!(
end.checked_sub(start)
.is_some_and(|len| len >= BLOCK_HEADER_SIZE)
&& end <= block_offsets_start,
"block {} of {:08}.sst spans bytes {}..{}, which is not a valid block within the {} \
byte data section",
block_index,
self.sequence_number,
start,
end,
block_offsets_start
);
Ok(start..end)
}
} }
/// Checks at open time that the index block (the file's last block) lies within the data section, /// Checks at open time that the index block (the file's last block) has a valid range, so that a
/// before the block directory at `block_offsets_start`, and is large enough for a block header. /// corrupt directory is reported when the file is opened. Requires `meta.block_count > 0`, as
/// /// ensured by [`StaticSortedFileMetaData::checked_block_offsets_start`].
/// Reading the index block indexes into the file by these offsets, which are otherwise only
/// range-checked with `strict_checks`. `block_offset(i)` returns the directory's end offset of
/// block `i`. Requires `meta.block_count > 0`, as ensured by
/// [`StaticSortedFileMetaData::checked_block_offsets_start`].
fn validate_index_block_range( fn validate_index_block_range(
meta: &StaticSortedFileMetaData, meta: &StaticSortedFileMetaData,
block_offsets_start: usize, block_offsets_start: usize,
block_offset: impl Fn(usize) -> u32, block_offset: impl Fn(usize) -> u32,
) -> Result<()> { ) -> Result<()> {
let index = usize::from(meta.block_count) - 1; meta.block_range(meta.block_count - 1, block_offsets_start, block_offset)
let start = if index == 0 { .context("invalid index block")?;
0
} else {
block_offset(index - 1) as usize
};
let end = block_offset(index) as usize;
ensure!(
end.checked_sub(start)
.is_some_and(|len| len >= BLOCK_HEADER_SIZE)
&& end <= block_offsets_start,
"index block {} of {:08}.sst spans bytes {}..{}, which is not a valid block within the {} \
byte data section",
index,
meta.sequence_number,
start,
end,
block_offsets_start
);
Ok(()) Ok(())
} }
/// Reads big-endian block directory entry `i` of a memory-mapped SST whose directory starts at
/// `block_offsets_start`.
#[cfg(feature = "mmap")]
fn mmap_block_offset(mmap: &[u8], block_offsets_start: usize, i: usize) -> u32 {
be::read_u32(&mmap[block_offsets_start + i * size_of::<u32>()..])
}
/// Reads and validates the block directory of an SST file for the file access mode. /// Reads and validates the block directory of an SST file for the file access mode.
fn read_block_offsets<T: From<Vec<u32>>>( fn read_block_offsets<T: From<Vec<u32>>>(
file: &File, file: &File,
...@@ -398,9 +431,7 @@ fn read_block_offsets<T: From<Vec<u32>>>( ...@@ -398,9 +431,7 @@ fn read_block_offsets<T: From<Vec<u32>>>(
#[cfg(feature = "mmap")] #[cfg(feature = "mmap")]
fn validate_mmap_layout(mmap: &Mmap, meta: &StaticSortedFileMetaData) -> Result<usize> { fn validate_mmap_layout(mmap: &Mmap, meta: &StaticSortedFileMetaData) -> Result<usize> {
let offset = meta.checked_block_offsets_start(mmap.len())?; let offset = meta.checked_block_offsets_start(mmap.len())?;
validate_index_block_range(meta, offset, |i| { validate_index_block_range(meta, offset, |i| mmap_block_offset(mmap, offset, i))?;
be::read_u32(&mmap[offset + i * size_of::<u32>()..])
})?;
Ok(offset) Ok(offset)
} }
...@@ -886,7 +917,7 @@ impl BlockRef<'_> { ...@@ -886,7 +917,7 @@ impl BlockRef<'_> {
/// Gets a block from the cache, or reads it from the mmap and inserts it. /// Gets a block from the cache, or reads it from the mmap and inserts it.
/// ///
/// Reads the block header exactly once via `get_raw_block_slice` (which /// Reads the block header exactly once via `get_raw_block_slice` (which
/// includes all `strict_checks` bounds guards). Uncompressed blocks bypass /// validates the block's range). Uncompressed blocks bypass
/// the cache and are borrowed from the mmap; their CRC is verified at most /// the cache and are borrowed from the mmap; their CRC is verified at most
/// once per file open, tracked by `verified_blocks`. Compressed blocks are /// once per file open, tracked by `verified_blocks`. Compressed blocks are
/// looked up in `cache`; on a miss they are decompressed, CRC-verified, and /// looked up in `cache`; on a miss they are decompressed, CRC-verified, and
...@@ -1049,63 +1080,18 @@ fn get_raw_block_slice<'a>( ...@@ -1049,63 +1080,18 @@ fn get_raw_block_slice<'a>(
block_index: u16, block_index: u16,
will_need: bool, will_need: bool,
) -> Result<(u32, u32, &'a [u8])> { ) -> Result<(u32, u32, &'a [u8])> {
#[cfg(feature = "strict_checks")] let block_offsets_start = meta.block_offsets_start(mmap.len());
if block_index >= meta.block_count { let range = meta.block_range(block_index, block_offsets_start, |i| {
bail!( mmap_block_offset(mmap, block_offsets_start, i)
"Corrupted file seq:{} block:{} > number of blocks {} (block_offsets: {:x})", })?;
meta.sequence_number, // Hint only after `block_range` has validated the range, so a corrupt offset never reaches
block_index, // `madvise`.
meta.block_count, if will_need {
meta.block_offsets_start(mmap.len()), will_need_range(mmap, range.clone());
); }
} let uncompressed_length = be::read_u32(&mmap[range.start..]);
let offset = meta.block_offsets_start(mmap.len()) + block_index as usize * 4; let checksum = be::read_u32(&mmap[range.start + 4..]);
#[cfg(feature = "strict_checks")] let block = &mmap[range.start + BLOCK_HEADER_SIZE..range.end];
if offset + 4 > mmap.len() {
bail!(
"Corrupted file seq:{} block:{} block offset locations {} + 4 bytes > file end {} \
(block_offsets: {:x})",
meta.sequence_number,
block_index,
offset,
mmap.len(),
meta.block_offsets_start(mmap.len()),
);
}
let block_start = if block_index == 0 {
0
} else {
be::read_u32(&mmap[offset - 4..]) as usize
};
let block_end = be::read_u32(&mmap[offset..]) as usize;
#[cfg(feature = "strict_checks")]
if block_end > mmap.len() || block_start > mmap.len() {
bail!(
"Corrupted file seq:{} block:{} block {} - {} > file end {} (block_offsets: {:x})",
meta.sequence_number,
block_index,
block_start,
block_end,
mmap.len(),
meta.block_offsets_start(mmap.len()),
);
}
ensure!(
block_start
.checked_add(BLOCK_HEADER_SIZE)
.is_some_and(|header_end| header_end <= block_end),
"block {} header truncated in {:08}.sst",
block_index,
meta.sequence_number
);
// Only hint ranges inside the mapping; without `strict_checks` a corrupt end offset isn't
// rejected before the slicing below panics.
if will_need && block_end <= mmap.len() {
will_need_range(mmap, block_start..block_end);
}
let uncompressed_length = be::read_u32(&mmap[block_start..]);
let checksum = be::read_u32(&mmap[block_start + 4..]);
let block = &mmap[block_start + BLOCK_HEADER_SIZE..block_end];
Ok((uncompressed_length, checksum, block)) Ok((uncompressed_length, checksum, block))
} }
...@@ -1129,34 +1115,33 @@ fn get_raw_block<'a>( ...@@ -1129,34 +1115,33 @@ fn get_raw_block<'a>(
file_len, file_len,
block_offsets, block_offsets,
} => { } => {
let index = block_index as usize; let (uncompressed_length, checksum, block) =
#[cfg(feature = "strict_checks")] read_file_block(file, *file_len, block_offsets, meta, block_index)?;
ensure!(index < block_offsets.len(), "block index out of bounds");
let block_start = if index == 0 {
0
} else {
block_offsets[index - 1] as usize
};
let block_end = block_offsets[index] as usize;
#[cfg(feature = "strict_checks")]
ensure!(block_end <= *file_len, "block end out of bounds");
let _ = file_len;
ensure!(
block_start + BLOCK_HEADER_SIZE <= block_end,
"block {} header truncated in {:08}.sst",
block_index,
meta.sequence_number
);
let mut bytes = vec![0; block_end - block_start];
pread(file.file(), &mut bytes, block_start as u64)?;
let uncompressed_length = be::read_u32(&bytes);
let checksum = be::read_u32(&bytes[4..]);
let block = bytes.split_off(BLOCK_HEADER_SIZE);
Ok((uncompressed_length, checksum, Cow::Owned(block))) Ok((uncompressed_length, checksum, Cow::Owned(block)))
} }
} }
} }
/// Reads a raw block of a file-backed SST with `pread`, after validating its range against the
/// block directory. Returns `(uncompressed_length, checksum, block_data)`.
fn read_file_block(
file: &File,
file_len: usize,
block_offsets: &[u32],
meta: &StaticSortedFileMetaData,
block_index: u16,
) -> Result<(u32, u32, Vec<u8>)> {
let range = meta.block_range(block_index, meta.block_offsets_start(file_len), |i| {
block_offsets[i]
})?;
let mut bytes = vec![0; range.len()];
pread(file.file(), &mut bytes, range.start as u64)?;
let uncompressed_length = be::read_u32(&bytes);
let checksum = be::read_u32(&bytes[4..]);
let block = bytes.split_off(BLOCK_HEADER_SIZE);
Ok((uncompressed_length, checksum, block))
}
fn pread(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<()> { fn pread(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<()> {
#[cfg(unix)] #[cfg(unix)]
{ {
...@@ -1292,29 +1277,8 @@ fn get_raw_block_iter( ...@@ -1292,29 +1277,8 @@ fn get_raw_block_iter(
file_len, file_len,
block_offsets, block_offsets,
} => { } => {
let index = block_index as usize; let (uncompressed_length, checksum, block) =
#[cfg(feature = "strict_checks")] read_file_block(file, *file_len, block_offsets, meta, block_index)?;
ensure!(index < block_offsets.len(), "block index out of bounds");
let block_start = if index == 0 {
0
} else {
block_offsets[index - 1] as usize
};
let block_end = block_offsets[index] as usize;
#[cfg(feature = "strict_checks")]
ensure!(block_end <= *file_len, "block end out of bounds");
let _ = file_len;
ensure!(
block_start + BLOCK_HEADER_SIZE <= block_end,
"block {} header truncated in {:08}.sst",
block_index,
meta.sequence_number
);
let mut bytes = vec![0; block_end - block_start];
pread(file.file(), &mut bytes, block_start as u64)?;
let uncompressed_length = be::read_u32(&bytes);
let checksum = be::read_u32(&bytes[4..]);
let block = bytes.split_off(BLOCK_HEADER_SIZE);
Ok(( Ok((
uncompressed_length, uncompressed_length,
checksum, checksum,
...@@ -2166,4 +2130,63 @@ mod tests { ...@@ -2166,4 +2130,63 @@ mod tests {
let err = validate_index_block_range(&meta, usize::MAX, |i| offsets[i]).unwrap_err(); let err = validate_index_block_range(&meta, usize::MAX, |i| offsets[i]).unwrap_err();
assert!(format!("{err:#}").contains("not a valid block")); assert!(format!("{err:#}").contains("not a valid block"));
} }
/// Asserts `block_range` rejects `block_index` with an error containing `expected`.
fn assert_block_range_err(offsets: &[u32], data_len: usize, block_index: u16, expected: &str) {
let meta = StaticSortedFileMetaData {
sequence_number: 7,
block_count: offsets.len() as u16,
};
let err = meta
.block_range(block_index, data_len, |i| offsets[i])
.unwrap_err();
let message = format!("{err:#}");
assert!(
message.contains(expected) && message.contains("00000007.sst"),
"block {block_index} of {offsets:?}: unexpected error: {message}"
);
}
#[test]
fn block_range_accepts_valid_blocks() {
let meta = StaticSortedFileMetaData {
sequence_number: 7,
block_count: 3,
};
let offsets = [10, 18, 30];
let range = |i| meta.block_range(i, 30, |i| offsets[i]).unwrap();
assert_eq!(range(0), 0..10);
assert_eq!(range(1), 10..18);
assert_eq!(range(2), 18..30);
}
#[test]
fn block_range_rejects_out_of_range_index() {
// Must not call the offset reader for the missing entry, which would panic here.
assert_block_range_err(&[10, 20], 20, 2, "out of range");
assert_block_range_err(&[10, 20], 20, u16::MAX, "out of range");
}
#[test]
fn block_range_rejects_end_past_data_section() {
assert_block_range_err(&[10, 21], 20, 1, "not a valid block");
assert_block_range_err(&[u32::MAX, 20], 20, 0, "not a valid block");
}
#[test]
fn block_range_rejects_start_after_end() {
assert_block_range_err(&[18, 10], 20, 1, "not a valid block");
assert_block_range_err(&[u32::MAX, 20], 20, 1, "not a valid block");
}
#[test]
fn block_range_rejects_block_too_short_for_header() {
assert_block_range_err(&[7, 20], 20, 0, "not a valid block");
assert_block_range_err(&[10, 17], 20, 1, "not a valid block");
}
#[test]
fn block_range_rejects_max_offsets() {
assert_block_range_err(&[u32::MAX, u32::MAX], usize::MAX, 1, "not a valid block");
}
} }
...@@ -1480,10 +1480,12 @@ impl<W: Write> IndexBlockBuilder<W> { ...@@ -1480,10 +1480,12 @@ impl<W: Write> IndexBlockBuilder<W> {
mod tests { mod tests {
use super::*; use super::*;
use crate::{ use crate::{
AccessMode,
key::hash_key, key::hash_key,
lookup_entry::LookupValue, lookup_entry::LookupValue,
static_sorted_file::{ static_sorted_file::{
BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData, BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileIter,
StaticSortedFileMetaData,
}, },
}; };
...@@ -1937,6 +1939,51 @@ mod tests { ...@@ -1937,6 +1939,51 @@ mod tests {
Ok(()) Ok(())
} }
/// A corrupt block offset is rejected by the shared bounds check before `MADV_WILLNEED`, so
/// no hint ever covers bytes outside the data section.
#[cfg(all(feature = "mmap", unix))]
#[test]
fn will_need_skips_corrupt_block_ranges() -> Result<()> {
use crate::static_sorted_file::will_need_log;
let dir = tempfile::tempdir()?;
let entries = will_need_entries();
let meta = write_sst(dir.path(), 1, &entries, MetaEntryFlags::default())?;
let path = dir.path().join("00000001.sst");
let original = std::fs::read(&path)?;
let table_start = original.len() - meta.block_count as usize * 4;
// Every block below the last data block: the last data block's end is the start of the
// index block, which is validated when the file is opened.
for block_index in 0..meta.block_count as usize - 2 {
let mut bytes = original.clone();
let entry = table_start + block_index * 4;
// Inside the mapping, but past the end of the data section.
bytes[entry..entry + 4].copy_from_slice(&(table_start as u32 + 4).to_be_bytes());
std::fs::write(&path, &bytes)?;
let sst = open_sst(dir.path(), 1, &meta)?;
will_need_log::take();
let kc = make_cache();
let vc = make_cache();
let errors = entries
.iter()
.filter_map(|e| sst.lookup::<_, false>(e.hash, &e.key, &kc, &vc).err())
.map(|err| format!("{err:#}"))
.collect::<Vec<_>>();
assert!(!errors.is_empty(), "block {block_index}: lookups succeeded");
assert!(
errors.iter().all(|err| err.contains("not a valid block")),
"block {block_index}: {errors:?}"
);
let hinted = will_need_log::take();
assert!(
hinted.iter().all(|range| range.end <= table_start),
"block {block_index}: hinted outside the data section: {hinted:?}"
);
}
Ok(())
}
#[test] #[test]
fn many_medium_values() -> Result<()> { fn many_medium_values() -> Result<()> {
let dir = tempfile::tempdir()?; let dir = tempfile::tempdir()?;
...@@ -2434,6 +2481,109 @@ mod tests { ...@@ -2434,6 +2481,109 @@ mod tests {
assert_corruption_detected(dir.path(), 1, &meta, &entries); assert_corruption_detected(dir.path(), 1, &meta, &entries);
} }
/// Reads every entry through both readers in every access mode and collects all errors.
/// A corrupt block offset must surface here as an error, not as a panic.
fn read_all_entries(
dir: &Path,
meta: StaticSortedFileMetaData,
entries: &[TestEntry],
) -> Vec<anyhow::Error> {
let mut errors = Vec::new();
let access_modes: &[AccessMode] = &[
#[cfg(feature = "mmap")]
AccessMode::Mmap,
AccessMode::File,
];
for &access_mode in access_modes {
match StaticSortedFile::open(dir, meta, Compression::Lz4, access_mode) {
Ok(sst) => {
let kc = make_cache();
let vc = make_cache();
// Look up every entry rather than stopping at the first error, so that each
// block, and with it the corrupt one, is read.
let lookup_errors = entries
.iter()
.filter_map(|e| sst.lookup::<_, false>(e.hash, &e.key, &kc, &vc).err())
.collect::<Vec<_>>();
assert!(
!lookup_errors.is_empty(),
"lookups ({access_mode:?}) succeeded despite a corrupt block offset"
);
errors.extend(lookup_errors);
}
Err(err) => errors.push(err),
}
match StaticSortedFileIter::open(dir, meta, Compression::Lz4, access_mode) {
Ok(iter) => {
if let Some(err) = iter.filter_map(|r| r.err()).next() {
errors.push(err);
} else {
panic!(
"iteration ({access_mode:?}) succeeded despite a corrupt block offset"
);
}
}
Err(err) => errors.push(err),
}
}
errors
}
/// Overwriting the directory entry of any non-index block with an offset outside the data
/// section must make reads fail with the shared block-range error, with or without
/// `strict_checks`.
#[test]
fn corrupt_block_offsets_are_rejected_on_read() -> Result<()> {
let mut entries = vec![TestEntry::medium(b"medium", &vec![0xAB; 8192])];
for i in 0..64u32 {
entries.push(TestEntry::small(
format!("small-{i:04}").as_bytes(),
&[i as u8; 64],
));
}
sort_entries(&mut entries);
let dir = tempfile::tempdir()?;
let written = write_sst(dir.path(), 1, &entries, MetaEntryFlags::default())?;
let meta = StaticSortedFileMetaData {
sequence_number: 1,
block_count: written.block_count,
};
assert!(
meta.block_count >= 3,
"expected value, key and index blocks, got {} blocks",
meta.block_count
);
let path = dir.path().join("00000001.sst");
let original = std::fs::read(&path)?;
let directory_start = meta.checked_block_offsets_start(original.len())?;
// Sanity check: the uncorrupted file reads back with the expected values.
let sst = open_sst(dir.path(), 1, &written)?;
let kc = make_cache();
let vc = make_cache();
for entry in &entries {
assert_lookup(&sst, entry, &kc, &vc)?;
}
drop(sst);
for block_index in 0..usize::from(meta.block_count) - 1 {
for bad_end in [u32::MAX, directory_start as u32 + 4] {
let mut bytes = original.clone();
let entry = directory_start + block_index * 4;
bytes[entry..entry + 4].copy_from_slice(&bad_end.to_be_bytes());
std::fs::write(&path, &bytes)?;
for err in read_all_entries(dir.path(), meta, &entries) {
let message = format!("{err:#}");
assert!(
message.contains("not a valid block") && message.contains("00000001.sst"),
"block {block_index} end {bad_end}: unexpected error: {message}"
);
}
}
}
Ok(())
}
#[test] #[test]
fn be_key_order_matches_byte_order() { fn be_key_order_matches_byte_order() {
let keys4: Vec<[u8; 4]> = vec![ let keys4: Vec<[u8; 4]> = vec![
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment