: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(common): tidy shared compression helpers (#58212)
Phil Haackf11144b1126f
diff --git a/rust/common/compression/src/lib.rs b/rust/common/compression/src/lib.rsindex 44fc0eb8f8cd..413f53599b1f 100644--- a/rust/common/compression/src/lib.rs+++ b/rust/common/compression/src/lib.rs@@ -20,14 +20,42 @@ pub enum CompressionError {#[error("Base64 decoding error: {0}")]Base64(#[from] base64::DecodeError),++ #[error("decompressed output exceeded limit ({decompressed} > {limit} bytes)")]+ OutputTooLarge { decompressed: usize, limit: usize },}-/// Gzip decompression+/// Gzip decompression with **no output cap**.+///+/// Safe only when the *compressed bytes* come from a trusted writer (rules+/// out gzip-bomb ratios) AND the uncompressed size is bounded somewhere+/// upstream. Cyclotron's VM-state path qualifies: bytes are produced by+/// `compress_vm_state` in this crate.+///+/// For HTTP request bodies, third-party blobs, or anything where an adversary+/// controls the compressed bytes or the uncompressed size, use+/// [`decompress_gzip_capped`] — gzip's worst-case ratio on adversarial input+/// is ~1000:1, so unbounded reads on untrusted bytes are a DoS vector.pub fn decompress_gzip(bytes: &[u8]) -> Result<Vec<u8>, CompressionError> {- let mut decoder = GzDecoder::new(bytes);- let mut decompressed = Vec::new();- decoder.read_to_end(&mut decompressed)?;- Ok(decompressed)+ decompress_gzip_capped(bytes, usize::MAX)+}++/// Gzip decompression with a hard output cap; see [`decompress_gzip`] for the+/// threat model. Returns [`CompressionError::OutputTooLarge`] when the+/// decompressed output would exceed `limit`.+pub fn decompress_gzip_capped(bytes: &[u8], limit: usize) -> Result<Vec<u8>, CompressionError> {+ let mut buf = Vec::new();+ GzDecoder::new(bytes)+ .take((limit as u64).saturating_add(1))+ .read_to_end(&mut buf)?;++ if buf.len() > limit {+ return Err(CompressionError::OutputTooLarge {+ decompressed: buf.len(),+ limit,+ });+ }+ Ok(buf)}/// Gzip compression@@ -212,4 +240,60 @@ mod tests {let result = decompress_zstd(&corrupted_zstd);assert!(result.is_err());}++ #[test]+ fn test_decompress_gzip_capped_under_limit() {+ let original = b"hello world";+ let compressed = compress_gzip(original).unwrap();+ let decompressed = decompress_gzip_capped(&compressed, 1024).unwrap();+ assert_eq!(decompressed, original);+ }++ #[test]+ fn test_decompress_gzip_capped_at_limit() {+ let original = vec![b'A'; 1024];+ let compressed = compress_gzip(&original).unwrap();+ let decompressed = decompress_gzip_capped(&compressed, 1024).unwrap();+ assert_eq!(decompressed.len(), 1024);+ assert_eq!(decompressed, original);+ }++ #[test]+ fn test_decompress_gzip_capped_over_limit() {+ let original = vec![b'A'; 1025];+ let compressed = compress_gzip(&original).unwrap();+ let result = decompress_gzip_capped(&compressed, 1024);+ assert!(matches!(+ result,+ Err(CompressionError::OutputTooLarge { decompressed, limit })+ if decompressed > 1024 && limit == 1024+ ));+ }++ #[test]+ fn test_decompress_gzip_capped_bomb_rejected() {+ // 64 KiB of zeros compresses to roughly 80 bytes — a small "bomb" that+ // would balloon to 64 KiB if decompressed unbounded.+ let bomb_decompressed = vec![0u8; 64 * 1024];+ let compressed = compress_gzip(&bomb_decompressed).unwrap();+ assert!(compressed.len() < 1024, "bomb should compress small");++ let result = decompress_gzip_capped(&compressed, 1024);+ match result {+ Err(CompressionError::OutputTooLarge {+ decompressed,+ limit,+ }) => {+ assert!(decompressed > 1024);+ assert_eq!(limit, 1024);+ }+ other => panic!("expected OutputTooLarge, got {other:?}"),+ }+ }++ #[test]+ fn test_decompress_gzip_capped_invalid_input() {+ let result = decompress_gzip_capped(b"not gzip data", 1024);+ assert!(matches!(result, Err(CompressionError::Io(_))));+ }}diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rsindex 4e13e09261b9..55e306a8d27e 100644--- a/rust/feature-flags/src/api/errors.rs+++ b/rust/feature-flags/src/api/errors.rs@@ -58,6 +58,8 @@ pub enum FlagError {Internal(String),#[error("failed to decode request: {0}")]RequestDecodingError(String),+ #[error("Decompressed request body exceeds limit ({decompressed} > {limit} bytes)")]+ PayloadTooLarge { decompressed: usize, limit: usize },#[error("failed to parse request: {0}")]RequestParsingError(#[from] serde_json::Error),#[error("No distinct_id in request")]@@ -160,6 +162,7 @@ impl FlagError {FlagError::RequestDecodingError(_) => ("request_decoding_error", 400),FlagError::RequestParsingError(_) => ("request_parsing_error", 400),FlagError::MissingDistinctId => ("missing_distinct_id", 400),+ FlagError::PayloadTooLarge { .. } => ("payload_too_large", 413),// Authentication errors (401)FlagError::NoTokenError => ("missing_token", 401),@@ -391,6 +394,16 @@ impl IntoResponse for FlagError {FlagError::RequestDecodingError(msg) => {(StatusCode::BAD_REQUEST, format!("Failed to decode request: {msg}. Please check your request format and try again."))}+ FlagError::PayloadTooLarge { decompressed, limit } => {+ tracing::warn!(decompressed, limit, "Decompressed request body exceeded cap");+ (+ StatusCode::PAYLOAD_TOO_LARGE,+ format!(+ "Decompressed request body exceeded {limit} bytes (got {decompressed}). \+ If this is a legitimate workload, contact PostHog support."+ ),+ )+ }FlagError::RequestParsingError(err) => {(StatusCode::BAD_REQUEST, format!("Failed to parse request: {err}. Please ensure your request is properly formatted and all required fields are present."))}@@ -583,6 +596,21 @@ impl IntoResponse for FlagError {}}+impl From<common_compression::CompressionError> for FlagError {+ fn from(e: common_compression::CompressionError) -> Self {+ match e {+ common_compression::CompressionError::OutputTooLarge {+ decompressed,+ limit,+ } => FlagError::PayloadTooLarge {+ decompressed,+ limit,+ },+ other => FlagError::RequestDecodingError(other.to_string()),+ }+ }+}+impl From<CustomRedisError> for FlagError {fn from(e: CustomRedisError) -> Self {match e {@@ -761,6 +789,10 @@ mod tests {.unwrap_err().into(), // RequestParsingErrorFlagError::MissingDistinctId,+ FlagError::PayloadTooLarge {+ decompressed: 5_000_000,+ limit: 4 * 1024 * 1024,+ },FlagError::NoTokenError,FlagError::TokenValidationError,FlagError::PersonalApiKeyInvalid,@@ -824,6 +856,14 @@ mod tests {assert_eq!(FlagError::MissingDistinctId.status_code(), 400);assert_eq!(FlagError::NoTokenError.status_code(), 401);assert_eq!(FlagError::TokenValidationError.status_code(), 401);+ assert_eq!(+ FlagError::PayloadTooLarge {+ decompressed: 5_000_000,+ limit: 4 * 1024 * 1024+ }+ .status_code(),+ 413+ );// 5xx errors (server errors)assert_eq!(FlagError::Internal("".into()).status_code(), 500);@@ -983,6 +1023,10 @@ mod tests {.unwrap_err().into(), // RequestParsingErrorFlagError::MissingDistinctId,+ FlagError::PayloadTooLarge {+ decompressed: 5_000_000,+ limit: 4 * 1024 * 1024,+ },FlagError::NoTokenError,FlagError::TokenValidationError,FlagError::PersonalApiKeyInvalid,diff --git a/rust/feature-flags/src/handler/decoding.rs b/rust/feature-flags/src/handler/decoding.rsindex 59692bedb2aa..4dfea31adc1e 100644--- a/rust/feature-flags/src/handler/decoding.rs+++ b/rust/feature-flags/src/handler/decoding.rs@@ -4,7 +4,7 @@ use crate::{types::{Compression, FlagsQueryParams},},flags::flag_request::FlagRequest,- metrics::consts::FLAG_REQUEST_KLUDGE_COUNTER,+ metrics::consts::{FLAG_GZIP_OUTPUT_EXCEEDED_COUNTER, FLAG_REQUEST_KLUDGE_COUNTER},utils::user_agent::UserAgentInfo,};use axum::http::{header::CONTENT_TYPE, header::USER_AGENT, HeaderMap};@@ -14,6 +14,11 @@ use common_compression;use common_metrics::inc;use percent_encoding::percent_decode;+/// 4 MiB cap on the decompressed `/flags` request body. The compressed body is+/// already capped at 2 MiB by axum's `DefaultBodyLimit` (`MAX_FLAGS_BODY_BYTES`),+/// so this is a backstop against gzip-bomb amplification.+const MAX_FLAGS_DECOMPRESSED_BYTES: usize = 4 * 1024 * 1024;+/// Lightweight token extraction for rate limiting./// Tries to extract the token without full request deserialization./// Falls back to None if extraction fails (caller should use IP).@@ -114,11 +119,18 @@ fn decode_body(}fn decompress_gzip(compressed: Bytes) -> Result<Bytes, FlagError> {- common_compression::decompress_gzip(&compressed)+ common_compression::decompress_gzip_capped(&compressed, MAX_FLAGS_DECOMPRESSED_BYTES).map(Bytes::from).map_err(|e| {- tracing::warn!("gzip decompression failed: {}", e);- FlagError::RequestDecodingError(format!("gzip decompression failed: {e}"))+ if matches!(+ e,+ common_compression::CompressionError::OutputTooLarge { .. }+ ) {+ inc(FLAG_GZIP_OUTPUT_EXCEEDED_COUNTER, &[], 1);+ } else {+ tracing::warn!("gzip decompression failed: {}", e);+ }+ FlagError::from(e)})}@@ -331,6 +343,60 @@ mod tests {assert_eq!(request.token, Some("test_token".to_string()));}+ #[test]+ fn test_gzip_bomb_rejected_with_payload_too_large() {+ // Compress 8 MiB of zeros — gzip's redundant-input case where the+ // decompressed size dwarfs the compressed size. Decompresses to+ // 8 MiB, which is well over MAX_FLAGS_DECOMPRESSED_BYTES (4 MiB).+ let bomb = vec![0u8; 8 * 1024 * 1024];+ let compressed = common_compression::compress_gzip(&bomb).unwrap();+ assert!(+ compressed.len() < 100_000,+ "bomb should compress small (got {} bytes)",+ compressed.len()+ );++ let mut headers = HeaderMap::new();+ headers.insert("content-encoding", "gzip".parse().unwrap());+ let query = FlagsQueryParams::default();++ let result = decode_request(&headers, Bytes::from(compressed), &query);+ match result {+ Err(FlagError::PayloadTooLarge {+ decompressed,+ limit,+ }) => {+ assert_eq!(limit, MAX_FLAGS_DECOMPRESSED_BYTES);+ assert!(+ decompressed > MAX_FLAGS_DECOMPRESSED_BYTES,+ "decompressed size {decompressed} should exceed cap {MAX_FLAGS_DECOMPRESSED_BYTES}"+ );+ }+ other => panic!("expected PayloadTooLarge, got {other:?}"),+ }+ }++ #[test]+ fn test_gzip_under_cap_still_works() {+ // A 1 MiB body is well over typical /flags traffic but still inside+ // the 4 MiB cap, so it must round-trip cleanly.+ let mut large_payload = String::from(r#"{"distinct_id": "u", "token": "t", "padding": ""#);+ large_payload.push_str(&"a".repeat(1024 * 1024));+ large_payload.push_str(r#""}"#);++ let gzipped = create_gzipped_json(&large_payload);+ let mut headers = HeaderMap::new();+ headers.insert("content-encoding", "gzip".parse().unwrap());+ let query = FlagsQueryParams::default();++ let result = decode_request(&headers, gzipped, &query);+ assert!(+ result.is_ok(),+ "1 MiB request body should decode under the 4 MiB cap, got {:?}",+ result.err()+ );+ }+#[test]fn test_explicit_gzip_compression_parameter() {let json_data = r#"{"distinct_id": "test", "token": "test_token"}"#;diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex d02c916e3d3a..f7d48e93dd24 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -93,6 +93,11 @@ pub const FLAG_BODY_READ_FAILED_COUNTER: &str = "flags_body_read_failed_total";// errors. Pod-level: no `team_id` label.pub const FLAG_BODY_READ_TOO_LARGE_COUNTER: &str = "flags_body_read_too_large_total";+// Counter for requests rejected because the gzip-*decompressed* body exceeded+// `MAX_FLAGS_DECOMPRESSED_BYTES`. Distinct from `FLAG_BODY_READ_TOO_LARGE_COUNTER`,+// which fires on the *compressed* size before decompression.+pub const FLAG_GZIP_OUTPUT_EXCEEDED_COUNTER: &str = "flags_gzip_output_exceeded_total";+// Per-phase wall-clock duration inside `process_request_inner`. Phases// match handler-level state transitions:// `auth → billing_check → cookieless → fetch_and_filter → evaluate →