Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(capture): cap lz64 decompression like gzip (#102546)

Eli Reisman2d8fb3ac14e7
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index ea3a658e4ec0..80956cc61de7 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2810,6 +2810,7 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"flate2",
+ "lz-str",
"thiserror 2.0.18",
"zstd",
]
diff --git a/rust/capture/src/payload/decompression.rs b/rust/capture/src/payload/decompression.rs
index 8381e1297a67..549b518ea708 100644
--- a/rust/capture/src/payload/decompression.rs
+++ b/rust/capture/src/payload/decompression.rs
@@ -6,7 +6,7 @@
use std::io::prelude::*;
use bytes::Bytes;
-use common_compression::has_gzip_magic_header;
+use common_compression::{decompress_lz64_capped, has_gzip_magic_header, CompressionError};
use flate2::read::GzDecoder;
use metrics;
use tracing::{debug, info, instrument, warn, Span};
@@ -14,9 +14,7 @@ use tracing::{debug, info, instrument, warn, Span};
use crate::{
api::CaptureError,
prometheus::report_dropped_events,
- utils::{
- decode_base64, decompress_lz64, is_likely_base64, Base64Option, MAX_PAYLOAD_SNIPPET_SIZE,
- },
+ utils::{decode_base64, is_likely_base64, Base64Option, MAX_PAYLOAD_SNIPPET_SIZE},
v0_request::path_is_legacy_endpoint,
};
@@ -25,9 +23,11 @@ use super::types::Compression;
// Metrics constants
const METRIC_PAYLOAD_SIZE_EXCEEDED: &str = "capture_payload_size_exceeded";
const METRIC_GZIP_DECOMPRESSION_RATIO: &str = "capture_gzip_decompression_ratio";
+const METRIC_LZ64_DECOMPRESSION_RATIO: &str = "capture_lz64_decompression_ratio";
-/// Decompression ratios above this threshold are flagged as potential GZIP bombs.
+/// Decompression ratios above this threshold are flagged as potential bombs.
const GZIP_BOMB_RATIO_THRESHOLD: f64 = 20.0;
+const LZ64_BOMB_RATIO_THRESHOLD: f64 = 20.0;
/// Decompress GZIP data with chunked reads and bomb detection.
/// Returns raw bytes -- callers decide whether to convert to String.
@@ -85,6 +85,82 @@ pub fn decompress_gzip_to_bytes(compressed: &[u8], limit: usize) -> Result<Vec<u
Ok(buf)
}
+/// Decompress LZ64 (lz-string) data with an output cap and bomb detection.
+/// The payload arrives as the base64 text lz-string emits.
+pub fn decompress_lz64_to_string(payload: &[u8], limit: usize) -> Result<String, CaptureError> {
+ let b64_payload = std::str::from_utf8(payload).unwrap_or("INVALID_UTF8");
+
+ // The cap is the same byte budget gzip enforces. The decoder counts the
+ // UTF-8 size of what it emits, so a payload of multi-byte characters cannot
+ // clear the cap as code units and then exceed the budget once converted.
+ let decomp_utf16 = match decompress_lz64_capped(b64_payload, limit) {
+ Ok(units) => units,
+ Err(CompressionError::Lz64OutputTooLarge { bytes, .. }) => {
+ metrics::counter!(METRIC_PAYLOAD_SIZE_EXCEEDED, "kind" => "lz64").increment(1);
+ metrics::histogram!("capture_full_payload_size", "oversize" => "true")
+ .record(bytes as f64);
+ report_dropped_events("event_too_big", 1);
+
+ return Err(CaptureError::EventTooBig(format!(
+ "Decompressed LZ64 payload would exceed {limit} bytes"
+ )));
+ }
+ Err(_) => {
+ let max_chars: usize = std::cmp::min(payload.len(), MAX_PAYLOAD_SNIPPET_SIZE);
+ let payload_snippet = String::from_utf8(payload[..max_chars].to_vec())
+ .unwrap_or(String::from("INVALID_UTF8"));
+ debug!(
+ payload_snippet = payload_snippet,
+ "decompress_lz64: failed decompress to UTF16"
+ );
+ return Err(CaptureError::RequestDecodingError(String::from(
+ "decompress_lz64: failed decompress to UTF16",
+ )));
+ }
+ };
+
+ // the decompressed data is UTF16 so we need to convert it to UTF8 to
+ // obtain the JSON event batch payload we've come to know and love
+ let decompressed = match String::from_utf16(&decomp_utf16) {
+ Ok(result) => result,
+ Err(_) => {
+ return Err(CaptureError::RequestDecodingError(String::from(
+ "decompress_lz64: failed UTF16 to UTF8 conversion",
+ )));
+ }
+ };
+
+ // The decoder already charged these bytes against `limit`, so this holds for
+ // any payload it accepted. It stays as a backstop because an accounting bug
+ // in the decoder would otherwise reach the rest of the pipeline unbounded,
+ // and it records the same sample the decoder's own rejection records.
+ if decompressed.len() > limit {
+ metrics::counter!(METRIC_PAYLOAD_SIZE_EXCEEDED, "kind" => "lz64").increment(1);
+ metrics::histogram!("capture_full_payload_size", "oversize" => "true")
+ .record(decompressed.len() as f64);
+ report_dropped_events("event_too_big", 1);
+ return Err(CaptureError::EventTooBig(String::from(
+ "lz64 request payload size limit exceeded",
+ )));
+ }
+
+ if !payload.is_empty() {
+ let ratio = decompressed.len() as f64 / payload.len() as f64;
+ metrics::histogram!(METRIC_LZ64_DECOMPRESSION_RATIO).record(ratio);
+
+ if ratio > LZ64_BOMB_RATIO_THRESHOLD {
+ warn!(
+ compressed_size = payload.len(),
+ decompressed_size = decompressed.len(),
+ ratio = ratio,
+ "High LZ64 compression ratio detected - potential LZ64 bomb"
+ );
+ }
+ }
+
+ Ok(decompressed)
+}
+
/// Decompresses and decodes a payload based on compression hint and content detection.
/// This is shared logic used by both analytics and recording event processing.
///
@@ -133,7 +209,7 @@ pub fn decompress_payload(
payload_len = bytes.len(),
"decompress_payload: matched LZ64 compression"
);
- decompress_lz64(&bytes, limit)?
+ decompress_lz64_to_string(&bytes, limit)?
} else {
debug!(
path = path,
@@ -273,4 +349,40 @@ mod tests {
let result = decompress_gzip_to_bytes(garbage, 4096);
assert!(matches!(result, Err(CaptureError::RequestDecodingError(_))));
}
+
+ #[test]
+ fn test_decompress_payload_lz64_valid() {
+ let original = r#"[{"event":"$pageview","properties":{"token":"abc"}}]"#;
+ let compressed = lz_str::compress_to_base64(original);
+
+ let result = decompress_payload(
+ Bytes::from(compressed),
+ Compression::LZString,
+ 4096,
+ "/i/v0/e",
+ )
+ .unwrap();
+
+ assert_eq!(result, original);
+ }
+
+ #[test]
+ fn test_decompress_payload_lz64_rejects_oversized_output() {
+ // 1 MB of one repeated character, which lz-string packs into ~2KB
+ let compressed = lz_str::compress_to_base64(&"A".repeat(1024 * 1024));
+ assert!(compressed.len() < 16 * 1024);
+
+ let result = decompress_payload(
+ Bytes::from(compressed),
+ Compression::LZString,
+ 1024,
+ "/i/v0/e",
+ );
+
+ assert!(
+ matches!(result, Err(CaptureError::EventTooBig(_))),
+ "expected EventTooBig, got {:?}",
+ result
+ );
+ }
}
diff --git a/rust/capture/src/utils.rs b/rust/capture/src/utils.rs
index a364b07ecd01..9c8e36fe8765 100644
--- a/rust/capture/src/utils.rs
+++ b/rust/capture/src/utils.rs
@@ -10,7 +10,6 @@ use uuid::Uuid;
use crate::{
api::CaptureError,
payload::{Compression, EventFormData, EventQuery},
- prometheus::report_dropped_events,
token::validate_token,
};
@@ -188,46 +187,6 @@ pub fn decode_form(payload: &[u8]) -> Result<EventFormData, CaptureError> {
}
}
-pub fn decompress_lz64(payload: &[u8], limit: usize) -> Result<String, CaptureError> {
- // with lz64 the payload is a Base64 string that must be decoded prior to decompression
- let b64_payload = std::str::from_utf8(payload).unwrap_or("INVALID_UTF8");
- let decomp_utf16 = match lz_str::decompress_from_base64(b64_payload) {
- Some(v) => v,
- None => {
- let max_chars: usize = std::cmp::min(payload.len(), MAX_PAYLOAD_SNIPPET_SIZE);
- let payload_snippet = String::from_utf8(payload[..max_chars].to_vec())
- .unwrap_or(String::from("INVALID_UTF8"));
- debug!(
- payload_snippet = payload_snippet,
- "decompress_lz64: failed decompress to UTF16"
- );
- return Err(CaptureError::RequestDecodingError(String::from(
- "decompress_lz64: failed decompress to UTF16",
- )));
- }
- };
-
- // the decompressed data is UTF16 so we need to convert it to UTF8 to
- // obtain the JSON event batch payload we've come to know and love
- let decompressed = match String::from_utf16(&decomp_utf16) {
- Ok(result) => result,
- Err(_) => {
- return Err(CaptureError::RequestDecodingError(String::from(
- "decompress_lz64: failed UTF16 to UTF8 conversion",
- )));
- }
- };
-
- if decompressed.len() > limit {
- report_dropped_events("event_too_big", 1);
- return Err(CaptureError::EventTooBig(String::from(
- "lz64 request payload size limit exceeded",
- )));
- }
-
- Ok(decompressed)
-}
-
pub fn extract_and_verify_token(
events: &[RawEvent],
batch_token: Option<String>,
diff --git a/rust/common/compression/Cargo.toml b/rust/common/compression/Cargo.toml
index b59b8203d03f..f868fe7b8b3b 100644
--- a/rust/common/compression/Cargo.toml
+++ b/rust/common/compression/Cargo.toml
@@ -9,3 +9,7 @@ base64 = { workspace = true }
thiserror = { workspace = true }
zstd = "0.13"
+[dev-dependencies]
+# Reference implementation the capped lz64 decoder is checked against.
+lz-str = { workspace = true }
+
diff --git a/rust/common/compression/src/lib.rs b/rust/common/compression/src/lib.rs
index c5e84887d76a..7364ebd57701 100644
--- a/rust/common/compression/src/lib.rs
+++ b/rust/common/compression/src/lib.rs
@@ -6,6 +6,7 @@
//! Supports:
//! - gzip compression/decompression
//! - Base64 encoding/decoding
+//! - lz-string ("lz64") decompression with a capped output
use base64::{engine::general_purpose, Engine as _};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
@@ -13,6 +14,10 @@ use std::io::{Read, Write};
use thiserror::Error;
use zstd::{Decoder, Encoder};
+mod lz64;
+
+pub use lz64::decompress_lz64_capped;
+
/// Gzip streams start with the two-byte magic `1f 8b` (ID1, ID2), followed by
/// compression method `08` (deflate). All three bytes are checked together so
/// streams with an unrecognized compression method are not misidentified as gzip.
@@ -32,6 +37,12 @@ pub enum CompressionError {
#[error("decompressed output exceeded limit ({decompressed} > {limit} bytes)")]
OutputTooLarge { decompressed: usize, limit: usize },
+
+ #[error("lz-string data could not be decompressed")]
+ Lz64Invalid,
+
+ #[error("lz-string output exceeded limit ({bytes} > {limit} bytes of UTF-8)")]
+ Lz64OutputTooLarge { bytes: usize, limit: usize },
}
/// Gzip decompression with **no output cap**.
diff --git a/rust/common/compression/src/lz64.rs b/rust/common/compression/src/lz64.rs
new file mode 100644
index 000000000000..834649b4b9fb
--- /dev/null
+++ b/rust/common/compression/src/lz64.rs
@@ -0,0 +1,500 @@
+//! lz-string ("lz64") decompression with a hard cap on the output.
+//!
+//! Old PostHog SDKs send payloads compressed with lz-string's
+//! `compressToBase64`. The `lz-str` crate decompresses those in one shot with no
+//! way to stop it: LZW rebuilds a back-reference dictionary as it goes, so a few
+//! kilobytes of base64 can expand into gigabytes before the caller ever gets a
+//! length to check. This is that decoder with the cap checked on every emit, so
+//! an oversized payload is refused while it is still small.
+
+use crate::CompressionError;
+
+/// lz-string's base64 alphabet; a character's index is its 6-bit value.
+const BASE64_KEY: &[u8; 65] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+
+const BITS_PER_CHAR: u8 = 6;
+const START_CODE_BITS: u8 = 2;
+
+/// Stream codes: a literal byte, a literal UTF-16 unit, end of stream.
+const U8_CODE: u32 = 0;
+const U16_CODE: u32 = 1;
+const CLOSE_CODE: u32 = 2;
+
+/// Code width grows with the dictionary, which the output cap bounds, so only
+/// corrupt input gets here. Rejecting it keeps `1 << n` inside a `u32`.
+const MAX_CODE_BITS: u8 = 31;
+
+/// Decompress a string produced by lz-string's `compressToBase64`, refusing any
+/// stream that would emit more than `max_output_bytes` bytes of UTF-8.
+///
+/// Returns the raw UTF-16 units, as `lz_str::decompress_from_base64` does, so
+/// callers convert to a `String` themselves. The cap is denominated in UTF-8
+/// bytes rather than UTF-16 units because the caller's budget is a byte budget
+/// and the two differ by up to 3x: a BMP character above U+07FF occupies one
+/// UTF-16 unit and three UTF-8 bytes. Counting units against a byte budget would
+/// let such a payload reach three times the budget once converted.
+///
+/// The dictionary holds ranges into the output rather than its own copies, so
+/// peak memory stays a small multiple of the cap instead of paying a heap
+/// allocation per entry.
+pub fn decompress_lz64_capped(
+ compressed: &str,
+ max_output_bytes: usize,
+) -> Result<Vec<u16>, CompressionError> {
+ // Ranges into the output are u32. Every unit is at least one UTF-8 byte, so
+ // bounding bytes by u32::MAX also bounds the unit count that indexes them.
+ let limit = max_output_bytes.min(u32::MAX as usize);
+
+ // A reverse table; 255 marks a character outside the alphabet. Scanning the
+ // alphabet per character costs most of the decode time on a real event
+ // batch, where the output is about the size of the input.
+ const BASE64_VALUE: [u8; 256] = {
+ let mut table = [255u8; 256];
+ let mut i = 0;
+ while i < BASE64_KEY.len() {
+ table[BASE64_KEY[i] as usize] = i as u8;
+ i += 1;
+ }
+ table
+ };
+
+ // Characters outside the alphabet are skipped, matching lz-string.
+ let input = compressed.encode_utf16().filter_map(|c| {
+ let value = if c < 256 {
+ BASE64_VALUE[c as usize]
+ } else {
+ 255
+ };
+ (value != 255).then_some(u16::from(value))
+ });
+
+ let mut reader = match BitReader::new(input, BITS_PER_CHAR) {
+ Some(reader) => reader,
+ None => return Ok(Vec::new()),
+ };
+
+ let first = match reader
+ .read_bits(START_CODE_BITS)
+ .ok_or(CompressionError::Lz64Invalid)?
+ {
+ code @ (U8_CODE | U16_CODE) => read_literal(&mut reader, code)?,
+ CLOSE_CODE => return Ok(Vec::new()),
+ _ => return Err(CompressionError::Lz64Invalid),
+ };
+
+ let mut out = Output::new();
+ // The three reserved codes above are intercepted before any lookup, so these
+ // placeholder ranges are never read. They only keep dictionary indexes aligned.
+ let mut dictionary: Vec<(u32, u32)> = vec![(0, 0); 3];
+
+ out.push(first, limit)?;
+ dictionary.push((0, 1));
+
+ let mut w: (u32, u32) = (0, 1);
+ let mut num_bits: u8 = 3;
+ let mut enlarge_in: u64 = 4;
+
+ loop {
+ if num_bits > MAX_CODE_BITS {
+ return Err(CompressionError::Lz64Invalid);
+ }
+
+ let mut code = reader
+ .read_bits(num_bits)
+ .ok_or(CompressionError::Lz64Invalid)?;
+ let mut literal = None;
+
+ match code {
+ U8_CODE | U16_CODE => {
+ literal = Some(read_literal(&mut reader, code)?);
+ // The literal's entry is the single unit emitted below.
+ dictionary.push((out.len(), 1));
+ code = u32::try_from(dictionary.len() - 1)
+ .map_err(|_| CompressionError::Lz64Invalid)?;
+ enlarge_in -= 1;
+ }
+ CLOSE_CODE => return Ok(out.units),
+ _ => {}
+ }
+
+ if enlarge_in == 0 {
+ enlarge_in = 1 << num_bits;
+ num_bits += 1;
+ }
+
+ let entry = if let Some(unit) = literal {
+ out.push(unit, limit)?;
+ (out.len() - 1, 1)
+ } else if let Some(&(start, len)) = dictionary.get(code as usize) {
+ out.copy_range(start, len, limit)?;
+ (out.len() - len, len)
+ } else if code as usize == dictionary.len() {
+ // LZW's "code we are about to define" case: w plus w's first unit.
+ let (start, len) = w;
+ out.copy_range(start, len, limit)?;
+ let first_unit = out.units[start as usize];
+ out.push(first_unit, limit)?;
+ (out.len() - len - 1, len + 1)
+ } else {
+ return Err(CompressionError::Lz64Invalid);
+ };
+
+ // w plus entry's first unit is contiguous in `out`: entry was emitted
+ // directly after w, so its first unit sits one past the end of w.
+ dictionary.push((w.0, w.1 + 1));
+ enlarge_in -= 1;
+ w = entry;
+
+ if enlarge_in == 0 {
+ enlarge_in = 1 << num_bits;
+ num_bits += 1;
+ }
+ }
+}
+
+/// Reads the bit stream lz-string packs into base64 characters.
+struct BitReader<I> {
+ val: u16,
+ data: I,
+ position: u16,
+ reset_val: u16,
+}
+
+impl<I: Iterator<Item = u16>> BitReader<I> {
+ fn new(mut data: I, bits_per_char: u8) -> Option<Self> {
+ let reset_val = 1 << (bits_per_char - 1);
+ Some(BitReader {
+ val: data.next()?,
+ data,
+ position: reset_val,
+ reset_val,
+ })
+ }
+
+ fn read_bit(&mut self) -> Option<bool> {
+ let res = self.val & self.position;
+ self.position >>= 1;
+
+ if self.position == 0 {
+ self.position = self.reset_val;
+ self.val = self.data.next()?;
+ }
+
+ Some(res != 0)
+ }
+
+ fn read_bits(&mut self, n: u8) -> Option<u32> {
+ let mut res = 0;
+ let max_power: u32 = 1 << n;
+ let mut power: u32 = 1;
+ while power != max_power {
+ res |= u32::from(self.read_bit()?) * power;
+ power <<= 1;
+ }
+
+ Some(res)
+ }
+}
+
+fn read_literal<I: Iterator<Item = u16>>(
+ reader: &mut BitReader<I>,
+ code: u32,
+) -> Result<u16, CompressionError> {
+ let bits_to_read = if code == U8_CODE { 8 } else { 16 };
+ let value = reader
+ .read_bits(bits_to_read)
+ .ok_or(CompressionError::Lz64Invalid)?;
+
+ u16::try_from(value).map_err(|_| CompressionError::Lz64Invalid)
+}
+
+/// The decoded units and the size of their UTF-8 encoding, held together so the
+/// buffer cannot grow without the cap seeing it.
+struct Output {
+ units: Vec<u16>,
+ utf8_len: usize,
+}
+
+impl Output {
+ fn new() -> Self {
+ Output {
+ units: Vec::new(),
+ utf8_len: 0,
+ }
+ }
+
+ /// The cap keeps the output within `u32::MAX` units, so this never truncates.
+ fn len(&self) -> u32 {
+ self.units.len() as u32
+ }
+
+ fn push(&mut self, unit: u16, limit: usize) -> Result<(), CompressionError> {
+ self.charge(utf8_len_of(unit), limit)?;
+ self.units.push(unit);
+ Ok(())
+ }
+
+ fn copy_range(&mut self, start: u32, len: u32, limit: usize) -> Result<(), CompressionError> {
+ let (start, len) = (start as usize, len as usize);
+ let range = start..start + len;
+ let added: usize = self.units[range.clone()]
+ .iter()
+ .copied()
+ .map(utf8_len_of)
+ .sum();
+
+ self.charge(added, limit)?;
+ self.units.extend_from_within(range);
+ Ok(())
+ }
+
+ /// Adds to the running UTF-8 size, or refuses when that would pass the cap.
+ /// Charging before the write is what keeps the buffer bounded.
+ fn charge(&mut self, bytes: usize, limit: usize) -> Result<(), CompressionError> {
+ let total = self.utf8_len + bytes;
+ if total > limit {
+ return Err(CompressionError::Lz64OutputTooLarge {
+ bytes: total,
+ limit,
+ });
+ }
+
+ self.utf8_len = total;
+ Ok(())
+ }
+}
+
+/// UTF-8 length of one UTF-16 code unit. A surrogate is half of a pair that
+/// encodes as four UTF-8 bytes, so each half counts two and the pair sums to
+/// four. An unpaired surrogate never reaches a `String`, because the caller's
+/// UTF-16 to UTF-8 conversion rejects it.
+fn utf8_len_of(unit: u16) -> usize {
+ match unit {
+ 0x0000..=0x007F => 1,
+ 0x0080..=0x07FF => 2,
+ 0xD800..=0xDFFF => 2,
+ _ => 3,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const GENEROUS_LIMIT: usize = 1024 * 1024;
+
+ fn decompress_to_string(compressed: &str, limit: usize) -> Result<String, CompressionError> {
+ let units = decompress_lz64_capped(compressed, limit)?;
+ Ok(String::from_utf16(&units).unwrap())
+ }
+
+ /// This decoder is a port, so any divergence from `lz-str` silently drops
+ /// data an SDK sent. Both roundtrip tests exist to catch that.
+ #[test]
+ fn matches_lz_str_on_roundtrips() {
+ let cases = [
+ "",
+ "{}",
+ r#"{"event":"$pageview","properties":{"$lib":"web"}}"#,
+ // Repetition is what LZW's dictionary rewards, so exercise it.
+ &r#"{"event":"$pageview"},"#.repeat(500),
+ // Non-ASCII lands outside the u8 literal code path.
+ r#"{"event":"クリック","emoji":"🦔","accents":"ãéî"}"#,
+ &"a".repeat(100_000),
+ ];
+
+ for case in cases {
+ let compressed = lz_str::compress_to_base64(case);
+ let expected = lz_str::decompress_from_base64(&compressed).unwrap();
+
+ assert_eq!(
+ decompress_lz64_capped(&compressed, GENEROUS_LIMIT).unwrap(),
+ expected,
+ "diverged from lz-str on a {} char payload",
+ case.len()
+ );
+ assert_eq!(
+ decompress_to_string(&compressed, GENEROUS_LIMIT).unwrap(),
+ case
+ );
+ }
+ }
+
+ #[test]
+ fn matches_lz_str_on_generated_payloads() {
+ // A seeded generator, so a divergence reproduces instead of flaking.
+ let mut seed: u64 = 0x5eed;
+ let mut next = move || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
+ (seed >> 33) as usize
+ };
+
+ for case_index in 0..200 {
+ // A small alphabet with structure keeps the dictionary busy, which is
+ // where the port and lz-str could disagree.
+ let alphabet = [
+ "a",
+ "b",
+ "{",
+ "}",
+ "\"",
+ ":",
+ ",",
+ "0",
+ "$pageview",
+ "properties",
+ "🦔",
+ ];
+ let length = 1 + next() % 400;
+ let payload: String = (0..length)
+ .map(|_| alphabet[next() % alphabet.len()])
+ .collect();
+
+ let compressed = lz_str::compress_to_base64(&payload);
+
+ assert_eq!(
+ decompress_lz64_capped(&compressed, GENEROUS_LIMIT).unwrap(),
+ lz_str::decompress_from_base64(&compressed).unwrap(),
+ "diverged from lz-str on generated case {case_index}: {payload}"
+ );
+ }
+ }
+
+ #[test]
+ fn rejects_a_decompression_bomb_without_materializing_it() {
+ // ~2KB of base64 expanding to 1MB, well under any request body limit.
+ let bomb = lz_str::compress_to_base64(&"a".repeat(1024 * 1024));
+ assert!(bomb.len() < 16 * 1024);
+
+ let result = decompress_lz64_capped(&bomb, 4096);
+
+ assert!(matches!(
+ result,
+ Err(CompressionError::Lz64OutputTooLarge { limit, .. }) if limit == 4096
+ ));
+ }
+
+ #[test]
+ fn accepts_output_exactly_at_the_limit() {
+ let payload = "b".repeat(4096);
+ let compressed = lz_str::compress_to_base64(&payload);
+
+ assert_eq!(decompress_to_string(&compressed, 4096).unwrap(), payload);
+ }
+
+ #[test]
+ fn rejects_output_one_byte_over_the_limit() {
+ let compressed = lz_str::compress_to_base64(&"b".repeat(4097));
+
+ assert!(matches!(
+ decompress_lz64_capped(&compressed, 4096),
+ Err(CompressionError::Lz64OutputTooLarge { .. })
+ ));
+ }
+
+ /// The cap is a byte budget, so a payload of characters that cost more than
+ /// one byte each has to be charged for what it costs. Counting code units
+ /// here would let a caller's byte budget be exceeded threefold, which is the
+ /// whole allocation this cap exists to prevent.
+ #[test]
+ fn charges_multi_byte_characters_by_their_utf8_size() {
+ // U+4E00: one UTF-16 code unit, three UTF-8 bytes.
+ let payload = "\u{4E00}".repeat(1000);
+ let compressed = lz_str::compress_to_base64(&payload);
+ assert_eq!(payload.len(), 3000);
+
+ assert_eq!(decompress_to_string(&compressed, 3000).unwrap(), payload);
+
+ // A code-unit cap would accept this, because the payload is 1000 units.
+ assert!(matches!(
+ decompress_lz64_capped(&compressed, 2999),
+ Err(CompressionError::Lz64OutputTooLarge { limit, .. }) if limit == 2999
+ ));
+ }
+
+ /// A surrogate pair is two code units and four UTF-8 bytes, so each half
+ /// costs two. Charging three per unit, as a non-surrogate BMP character
+ /// costs, would reject payloads that fit.
+ #[test]
+ fn charges_surrogate_pairs_by_their_utf8_size() {
+ // U+1F600: two UTF-16 code units, four UTF-8 bytes.
+ let payload = "\u{1F600}".repeat(500);
+ let compressed = lz_str::compress_to_base64(&payload);
+ assert_eq!(payload.len(), 2000);
+
+ assert_eq!(decompress_to_string(&compressed, 2000).unwrap(), payload);
+
+ assert!(matches!(
+ decompress_lz64_capped(&compressed, 1999),
+ Err(CompressionError::Lz64OutputTooLarge { .. })
+ ));
+ }
+
+ #[test]
+ fn rejects_truncated_input() {
+ let compressed = lz_str::compress_to_base64(r#"{"event":"$pageview"}"#);
+
+ // Truncated mid-stream, and a stream that ends right after its first code.
+ for case in [&compressed[..compressed.len() / 2], "A"] {
+ assert!(
+ matches!(
+ decompress_lz64_capped(case, GENEROUS_LIMIT),
+ Err(CompressionError::Lz64Invalid)
+ ),
+ "expected {case:?} to be rejected"
+ );
+ }
+ }
+
+ /// A corrupted stream still decodes far enough to reach the dictionary
+ /// lookups, which a truncated one never does. The port has to agree with
+ /// lz-str on where such a stream stops: stopping later than lz-str ingests
+ /// bytes the sender never wrote, and stopping earlier drops events a client
+ /// on a lossy connection did write.
+ #[test]
+ fn matches_lz_str_on_corrupted_streams() {
+ let compressed = lz_str::compress_to_base64(&r#"{"event":"$pageview","i":0},"#.repeat(40));
+ let bytes = compressed.as_bytes();
+
+ let mut seed: u64 = 0xC0FFEE;
+ let mut next = move || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
+ (seed >> 33) as usize
+ };
+
+ for case_index in 0..300 {
+ let at = next() % bytes.len();
+ let mut corrupted = compressed.clone();
+ match case_index % 3 {
+ // Swap in another alphabet character, so the bit stream stays
+ // readable and decodes into different codes.
+ 0 => corrupted.replace_range(
+ at..at + 1,
+ &(BASE64_KEY[next() % BASE64_KEY.len()] as char).to_string(),
+ ),
+ // Outside the alphabet, which both decoders skip, shortening the stream.
+ 1 => corrupted.insert(at, '!'),
+ _ => {
+ corrupted.remove(at);
+ }
+ }
+
+ assert_eq!(
+ decompress_lz64_capped(&corrupted, GENEROUS_LIMIT).ok(),
+ lz_str::decompress_from_base64(&corrupted),
+ "diverged from lz-str on corrupted case {case_index}"
+ );
+ }
+ }
+
+ #[test]
+ fn input_with_no_alphabet_characters_decodes_to_nothing() {
+ // lz-string skips characters outside its alphabet, so these are empty streams.
+ for case in ["", "!!!!"] {
+ assert_eq!(
+ decompress_lz64_capped(case, GENEROUS_LIMIT).unwrap(),
+ lz_str::decompress_from_base64(case).unwrap()
+ );
+ }
+ }
+}