diff --git a/rust/src/protocol/envelope.rs b/rust/src/protocol/envelope.rs index f6d22c98..bb8af107 100644 --- a/rust/src/protocol/envelope.rs +++ b/rust/src/protocol/envelope.rs @@ -8,11 +8,14 @@ //! See "Envelope selection and codec environment" in `formal/guides/PROTOCOL.md`. use crate::codec::Payload; -use crate::limits::{DEFAULT_COMPRESSION_THRESHOLD_BYTES, DEFAULT_ZSTD_LEVEL, MAX_SAFE_INTEGER}; +use crate::limits::{ + DEFAULT_COMPRESSION_THRESHOLD_BYTES, DEFAULT_ZSTD_LEVEL, MAX_DECOMPRESSED_BYTES, + MAX_SAFE_INTEGER, +}; use crate::observe::CompressionOutcome; use super::frame::ProtocolError; -use super::text::replacement_utf8; +use super::text::{replacement_utf8, replacement_utf8_within}; /// Envelope byte `0x00`: the rest is raw serializer output whose own first /// byte would have collided with a marker. @@ -202,8 +205,15 @@ pub fn decompress_payload( match decode_first_zstd_frame(&payload.bytes[1..], max_decompressed_bytes) { Ok(decoded) => { let decoded = if marker == MARKER_ZSTD_UTF8 { + let Some(bytes) = replacement_utf8_within(&decoded, MAX_DECOMPRESSED_BYTES) + else { + return CompressionReadResult { + payload, + outcome: Some(CompressionOutcome::ReadOverLimit), + }; + }; Payload { - bytes: replacement_utf8(&decoded), + bytes, binary: false, } } else { @@ -493,6 +503,24 @@ mod tests { } } + #[test] + fn small_read_limits_count_raw_bytes_before_text_replacement() { + for (marker, expected) in [ + (MARKER_ZSTD_UTF8, Payload::text("\u{FFFD}")), + (MARKER_ZSTD_BINARY, Payload::binary([0xff])), + ] { + let mut bytes = vec![marker]; + bytes.extend_from_slice(&zstd_compress(&[0xff], 3).unwrap()); + let original = Payload::binary(bytes); + let decoded = decompress_payload(original.clone(), 1); + assert_eq!(decoded.outcome, Some(CompressionOutcome::Decompressed)); + assert_eq!(decoded.payload, expected); + let rejected = decompress_payload(original.clone(), 0); + assert_eq!(rejected.outcome, Some(CompressionOutcome::ReadOverLimit)); + assert_eq!(rejected.payload, original); + } + } + #[test] fn skippable_frames_decode_to_empty_output() { // Magic 0x184D2A50, 4-byte little-endian size, then that many bytes. diff --git a/rust/src/protocol/text.rs b/rust/src/protocol/text.rs index 2fb5c14f..7de2f758 100644 --- a/rust/src/protocol/text.rs +++ b/rust/src/protocol/text.rs @@ -14,9 +14,62 @@ pub fn replacement_utf8(bytes: &[u8]) -> Vec { String::from_utf8_lossy(bytes).into_owned().into_bytes() } +pub(super) fn replacement_utf8_within(bytes: &[u8], limit: usize) -> Option> { + if bytes.len() > limit { + return None; + } + if std::str::from_utf8(bytes).is_ok() { + return Some(bytes.to_vec()); + } + + // Count replacement growth before allocating; a tiny zstd frame can expand + // to malformed text whose repaired representation exceeds the read ceiling. + let mut len = bytes.len(); + for chunk in bytes.utf8_chunks() { + if !chunk.invalid().is_empty() { + len = len.checked_add(3 - chunk.invalid().len())?; + if len > limit { + return None; + } + } + } + let mut out = Vec::with_capacity(len); + for chunk in bytes.utf8_chunks() { + out.extend_from_slice(chunk.valid().as_bytes()); + if !chunk.invalid().is_empty() { + out.extend_from_slice("\u{FFFD}".as_bytes()); + } + } + Some(out) +} + #[cfg(test)] mod tests { - use super::replacement_utf8; + use super::{replacement_utf8, replacement_utf8_within}; + + #[test] + fn bounded_replacement_preserves_text_and_checks_exact_output_bytes() { + for (bytes, expected) in [ + (&b""[..], ""), + (&b"text"[..], "text"), + (&[0xff][..], "\u{FFFD}"), + (&[0xe2, 0x82][..], "\u{FFFD}"), + (&[0xe2, 0x82, b'A'][..], "\u{FFFD}A"), + (&[0xf0, 0x9f, 0x98][..], "\u{FFFD}"), + (&[0xed, 0xa0, 0x80][..], "\u{FFFD}\u{FFFD}\u{FFFD}"), + ("\u{FEFF}\0\u{FFFF}😀".as_bytes(), "\u{FEFF}\0\u{FFFF}😀"), + ] { + for limit in [expected.len(), expected.len() + 1] { + assert_eq!( + replacement_utf8_within(bytes, limit).unwrap(), + expected.as_bytes() + ); + } + if !expected.is_empty() { + assert_eq!(replacement_utf8_within(bytes, expected.len() - 1), None); + } + } + } fn decoded(bytes: &[u8]) -> String { String::from_utf8(replacement_utf8(bytes)).expect("replacement output is UTF-8") diff --git a/rust/tests/compression_resource.rs b/rust/tests/compression_resource.rs new file mode 100644 index 00000000..1a17a695 --- /dev/null +++ b/rust/tests/compression_resource.rs @@ -0,0 +1,166 @@ +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use dialcache::limits::MAX_DECOMPRESSED_BYTES; +use dialcache::observe::CompressionOutcome; +use dialcache::protocol::{decode_frame, decompress_payload, encode_frame}; +use dialcache::{ + BoxError, DialCache, Event, Frame, Identity, InvalidateRequest, Observer, Operation, Payload, + Policy, ReadContext, ReadRequest, ReadResult, Remote, WriteRequest, +}; +use futures::future::BoxFuture; +use parking_lot::Mutex; +use sha2::{Digest, Sha256}; + +struct CountingAllocator; + +thread_local! { + static ALLOCATED: Cell = const { Cell::new(0) }; +} + +fn count(bytes: usize) { + let _ = ALLOCATED.try_with(|allocated| allocated.set(allocated.get() + bytes)); +} + +// SAFETY: every call forwards to the system allocator unchanged. +unsafe impl GlobalAlloc for CountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + System.alloc(layout) + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + System.alloc_zeroed(layout) + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(new_size); + System.realloc(ptr, layout, new_size) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + System.dealloc(ptr, layout) + } +} + +#[global_allocator] +static ALLOCATOR: CountingAllocator = CountingAllocator; + +fn expanding_text() -> Payload { + // A 128 KiB window and 1536 RLE blocks: 192 MiB of FF becomes 576 MiB of UTF-8. + let mut bytes = vec![1, 0x28, 0xb5, 0x2f, 0xfd, 0, 0x38]; + for block in 0..1536 { + let header = 2u32 | ((128 << 10) << 3) | u32::from(block == 1535); + bytes.extend_from_slice(&header.to_le_bytes()[..3]); + bytes.push(0xff); + } + assert_eq!(bytes.len(), 6151); + assert_eq!( + hex::encode(Sha256::digest(&bytes)), + "87f67ab328f41b853343257bbc461bc52fd432b0ccca15ec19ba5772019c08c0" + ); + Payload::binary(bytes) +} + +#[test] +fn repaired_text_cannot_exceed_the_global_read_limit() { + let original = expanding_text(); + let before = ALLOCATED.with(Cell::get); + let result = decompress_payload(original.clone(), MAX_DECOMPRESSED_BYTES); + let allocated = ALLOCATED.with(Cell::get) - before; + assert_eq!(result.outcome, Some(CompressionOutcome::ReadOverLimit)); + assert_eq!(result.payload, original); + // The raw buffer's growth uses at most 512 MiB in total. Even one exact + // 576 MiB repair allocation exceeds this budget on its own. + assert!( + allocated < MAX_DECOMPRESSED_BYTES + (1 << 20), + "rejected text allocated {allocated} bytes" + ); +} + +struct FrameRemote { + bytes: Vec, + writes: AtomicUsize, +} + +impl Remote for FrameRemote { + fn read( + &self, + request: ReadRequest, + _: ReadContext, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + assert!(request.watermark_key.is_some()); + Ok(decode_frame(Some(&self.bytes), true, None)?) + }) + } + + fn write(&self, request: WriteRequest) -> BoxFuture<'_, Result<(), BoxError>> { + assert_eq!(request.frame.payload, Payload::text("\"source\"")); + self.writes.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Ok(()) }) + } + + fn invalidate(&self, _: InvalidateRequest) -> BoxFuture<'_, Result<(), BoxError>> { + unreachable!("the read must not invalidate") + } +} + +#[derive(Default)] +struct CompressionEvents(Mutex>); + +impl Observer for CompressionEvents { + fn observe(&self, event: &Event) { + if let Event::Compression { outcome, .. } = event { + self.0.lock().push(*outcome); + } + } +} + +#[tokio::test] +async fn disabled_compression_still_bounds_text_and_fails_open() { + let remote = Arc::new(FrameRemote { + bytes: encode_frame(&Frame { + created_at_ms: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64, + payload: expanding_text(), + }) + .unwrap(), + writes: AtomicUsize::new(0), + }); + assert_eq!(remote.bytes.len(), 6161); + let events = Arc::new(CompressionEvents::default()); + let cache = DialCache::builder() + .remote_arc(remote.clone()) + .observer_arc(events.clone()) + .local_capacity(0) + .disable_compression() + .build() + .unwrap(); + let guard = cache.enable_guard(); + let operation = + Operation::::new(Identity::new("item", "oversized", "read").tracked(true)) + .policy(Policy::default().remote_ttl_sec(60)); + let calls = Arc::new(AtomicUsize::new(0)); + let source_calls = calls.clone(); + let value = tokio::time::timeout( + Duration::from_secs(30), + cache.get_or_load(guard.scope(), operation, move |_| { + source_calls.fetch_add(1, Ordering::SeqCst); + async { Ok("source".to_string()) } + }), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(&*value, "source"); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(remote.writes.load(Ordering::SeqCst), 1); + assert_eq!(*events.0.lock(), [CompressionOutcome::ReadOverLimit]); +}