: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
fix(logs): detect gzip bodies by magic header (#68955)
Manoel Aranda Netobd44693313a7
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex c21bb71bdd22..42ed25860d7b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1792,6 +1792,7 @@ dependencies = ["capture","chrono","common-alloc",+ "common-compression","common-continuous-profiling","common-redis","common-types",@@ -1874,6 +1875,7 @@ dependencies = ["chrono","clickhouse","common-alloc",+ "common-compression","common-continuous-profiling","common-metrics","envconfig",diff --git a/rust/capture-logs/Cargo.toml b/rust/capture-logs/Cargo.tomlindex a9a2f8ce6662..305eab11bbf8 100644--- a/rust/capture-logs/Cargo.toml+++ b/rust/capture-logs/Cargo.toml@@ -14,6 +14,7 @@ axum = { workspace = true }common-metrics = { path = "../common/metrics" }common-alloc = { path = "../common/alloc" }common-continuous-profiling = { path = "../common/continuous_profiling" }+common-compression = { path = "../common/compression" }limiters = { path = "../common/limiters" }capture = { path = "../capture" }opentelemetry-proto = { workspace = true }diff --git a/rust/capture-logs/src/endpoints/datadog.rs b/rust/capture-logs/src/endpoints/datadog.rsindex 2fca92dbd521..9d445c919647 100644--- a/rust/capture-logs/src/endpoints/datadog.rs+++ b/rust/capture-logs/src/endpoints/datadog.rs@@ -1,5 +1,5 @@use crate::log_record::{override_timestamp, KafkaLogRow};-use crate::service::Service;+use crate::service::{decode_body_if_gzip_magic, Service};use axum::{extract::State,extract::{Path, Query},@@ -323,6 +323,8 @@ pub async fn export_datadog_logs_http(tracing::Span::current().record("token", &token);+ let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;+let logs: Vec<DatadogLog> = match serde_json::from_slice::<Vec<DatadogLog>>(&body) {Ok(logs) => logs,Err(_) => match serde_json::from_slice::<DatadogLog>(&body) {diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rsindex 0bfdac7e2978..0642ae96aae8 100644--- a/rust/capture-logs/src/main.rs+++ b/rust/capture-logs/src/main.rs@@ -118,7 +118,13 @@ async fn main() {let token_dropper = TokenDropper::new(&config.drop_events_by_token.unwrap_or_default());let token_dropper_arc = Arc::new(token_dropper);- let logs_service = match Service::new(kafka_sink, token_dropper_arc).await {+ let logs_service = match Service::new(+ kafka_sink,+ token_dropper_arc,+ config.max_request_body_size_bytes,+ )+ .await+ {Ok(service) => service,Err(e) => {error!("Failed to initialize log service: {}", e);diff --git a/rust/capture-logs/src/service.rs b/rust/capture-logs/src/service.rsindex 45c2dff5a5d8..432a638946a7 100644--- a/rust/capture-logs/src/service.rs+++ b/rust/capture-logs/src/service.rs@@ -8,6 +8,7 @@ use axum::{response::Json,};use bytes::Bytes;+use common_compression::{decompress_gzip_capped, has_gzip_magic_header, CompressionError};use limiters::token_dropper::TokenDropper;use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;@@ -303,6 +304,7 @@ pub fn parse_otel_message(json_bytes: &Bytes) -> Result<ExportLogsServiceRequestpub struct Service {pub(crate) sink: KafkaSink,pub(crate) token_dropper: Arc<TokenDropper>,+ pub(crate) max_request_body_size_bytes: usize,}#[derive(Deserialize)]@@ -314,14 +316,42 @@ impl Service {pub async fn new(kafka_sink: KafkaSink,token_dropper: Arc<TokenDropper>,+ max_request_body_size_bytes: usize,) -> Result<Self, anyhow::Error> {Ok(Self {sink: kafka_sink,token_dropper,+ max_request_body_size_bytes,})}}+pub(crate) fn decode_body_if_gzip_magic(+ body: Bytes,+ max_request_body_size_bytes: usize,+) -> Result<Bytes, (StatusCode, Json<serde_json::Value>)> {+ if !has_gzip_magic_header(&body) {+ return Ok(body);+ }++ match decompress_gzip_capped(&body, max_request_body_size_bytes) {+ Ok(decompressed) => Ok(Bytes::from(decompressed)),+ Err(CompressionError::OutputTooLarge {+ decompressed,+ limit,+ }) => Err((+ StatusCode::PAYLOAD_TOO_LARGE,+ Json(json!({+ "error": format!("Decompressed request body exceeds limit ({decompressed} > {limit} bytes)")+ })),+ )),+ Err(e) => Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": format!("Failed to decompress gzip request body: {e}")})),+ )),+ }+}+#[instrument(skip_all, fields(token = tracing::field::Empty,content_type = %headers.get("content-type")@@ -389,6 +419,8 @@ pub async fn export_logs_http(tracing::Span::current().record("token", token);+ let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;+// Try to decode as Protobuf, if this fails, try JSON.// We do this over relying on Content-Type headers to be as permissive as possible in what we accept.let export_request = match ExportLogsServiceRequest::decode(body.as_ref()) {@@ -577,6 +609,8 @@ pub async fn export_traces_http(tracing::Span::current().record("token", token);+ let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;+let export_request = match ExportTraceServiceRequest::decode(body.as_ref()) {Ok(request) => request,Err(proto_err) => match parse_otel_traces_message(&body) {@@ -752,6 +786,8 @@ pub async fn export_metrics_http(tracing::Span::current().record("token", token);+ let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;+let export_request = match ExportMetricsServiceRequest::decode(body.as_ref()) {Ok(request) => request,Err(proto_err) => match parse_otel_metrics_message(&body) {@@ -825,3 +861,42 @@ pub async fn export_metrics_http(Ok(Json(json!({})))}++#[cfg(test)]+mod tests {+ use super::*;+ use flate2::{write::GzEncoder, Compression};++ fn gzip(data: &[u8]) -> Bytes {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(data).unwrap();+ Bytes::from(encoder.finish().unwrap())+ }++ #[test]+ fn decode_body_if_gzip_magic_decompresses_without_header() {+ let body = gzip(br#"{"resourceLogs":[]}"#);++ let decoded = decode_body_if_gzip_magic(body, 1024).unwrap();++ assert_eq!(decoded, Bytes::from_static(br#"{"resourceLogs":[]}"#));+ }++ #[test]+ fn decode_body_if_gzip_magic_preserves_plain_body() {+ let body = Bytes::from_static(br#"{"resourceLogs":[]}"#);++ let decoded = decode_body_if_gzip_magic(body.clone(), 1024).unwrap();++ assert_eq!(decoded, body);+ }++ #[test]+ fn decode_body_if_gzip_magic_rejects_oversized_output() {+ let body = gzip(&vec![b'a'; 2048]);++ let err = decode_body_if_gzip_magic(body, 1024).unwrap_err();++ assert_eq!(err.0, StatusCode::PAYLOAD_TOO_LARGE);+ }+}diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.tomlindex 7cdd3dfa2dd7..38cd846a38db 100644--- a/rust/capture/Cargo.toml+++ b/rust/capture/Cargo.toml@@ -26,6 +26,7 @@ lifecycle = { path = "../common/lifecycle" }hyper = { workspace = true }hyper-util = { workspace = true }common-alloc = { path = "../common/alloc" }+common-compression = { path = "../common/compression" }common-continuous-profiling = { path = "../common/continuous_profiling" }common-redis = { path = "../common/redis" }common-types = { path = "../common/types" }diff --git a/rust/capture/src/payload/decompression.rs b/rust/capture/src/payload/decompression.rsindex 2d66e3a935ed..8381e1297a67 100644--- a/rust/capture/src/payload/decompression.rs+++ b/rust/capture/src/payload/decompression.rs@@ -6,6 +6,7 @@use std::io::prelude::*;use bytes::Bytes;+use common_compression::has_gzip_magic_header;use flate2::read::GzDecoder;use metrics;use tracing::{debug, info, instrument, warn, Span};@@ -21,8 +22,6 @@ use crate::{use super::types::Compression;-pub static GZIP_MAGIC_NUMBERS: [u8; 3] = [0x1f, 0x8b, 0x08];-// Metrics constantsconst METRIC_PAYLOAD_SIZE_EXCEEDED: &str = "capture_payload_size_exceeded";const METRIC_GZIP_DECOMPRESSION_RATIO: &str = "capture_gzip_decompression_ratio";@@ -113,8 +112,7 @@ pub fn decompress_payload();metrics::histogram!("capture_raw_payload_size").record(bytes.len() as f64);- let mut payload = if compression == Compression::Gzip || bytes.starts_with(&GZIP_MAGIC_NUMBERS)- {+ let mut payload = if compression == Compression::Gzip || has_gzip_magic_header(&bytes) {debug!(payload_len = bytes.len(),"decompress_payload: matched GZIP compression"diff --git a/rust/capture/src/test_endpoint.rs b/rust/capture/src/test_endpoint.rsindex fbbaa00241c2..ad8885e6f52d 100644--- a/rust/capture/src/test_endpoint.rs+++ b/rust/capture/src/test_endpoint.rs@@ -10,13 +10,14 @@ use axum::{use axum_client_ip::InsecureClientIp;use base64::Engine;use bytes::{Buf, Bytes};+use common_compression::has_gzip_magic_header;use flate2::bufread::GzDecoder;use tracing::error;use crate::{api::{CaptureError, CaptureResponse, CaptureResponseCode},extractors::extract_body_with_timeout,- payload::{decompression::GZIP_MAGIC_NUMBERS, Compression, EventFormData, EventQuery},+ payload::{Compression, EventFormData, EventQuery},router,utils::extract_and_verify_token,v0_request::RawRequest,@@ -191,7 +192,7 @@ pub async fn test_black_hole(}pub fn from_bytes(bytes: Bytes, limit: usize, comp: String) -> Result<RawRequest, CaptureError> {- let payload = if bytes.starts_with(&GZIP_MAGIC_NUMBERS) {+ let payload = if has_gzip_magic_header(&bytes) {metrics::counter!(GZIP_FOUND, "comp" => comp.clone()).increment(1);let len = bytes.len();let mut zipstream = GzDecoder::new(bytes.reader());diff --git a/rust/common/compression/src/lib.rs b/rust/common/compression/src/lib.rsindex 413f53599b1f..40ce13495ddb 100644--- a/rust/common/compression/src/lib.rs+++ b/rust/common/compression/src/lib.rs@@ -13,6 +13,15 @@ use std::io::{Read, Write};use thiserror::Error;use zstd::{Decoder, Encoder};+/// 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.+pub const GZIP_MAGIC_HEADER: [u8; 3] = [0x1f, 0x8b, 0x08];++pub fn has_gzip_magic_header(bytes: &[u8]) -> bool {+ bytes.starts_with(&GZIP_MAGIC_HEADER)+}+#[derive(Error, Debug)]pub enum CompressionError {#[error("IO error: {0}")]@@ -135,6 +144,13 @@ pub fn decompress_data(input: &[u8]) -> Result<String, CompressionError> {mod tests {use super::*;+ #[test]+ fn test_has_gzip_magic_header() {+ assert!(has_gzip_magic_header(&[0x1f, 0x8b, 0x08, 0x00]));+ assert!(!has_gzip_magic_header(&[0x1f, 0x8b]));+ assert!(!has_gzip_magic_header(b"{}"));+ }+#[test]fn test_gzip_compression_decompression() {let original = r#"{"large": "json", "with": ["many", "fields"], "number": 42}"#;diff --git a/rust/feature-flags/src/handler/decoding.rs b/rust/feature-flags/src/handler/decoding.rsindex ec38e1422345..271904619285 100644--- a/rust/feature-flags/src/handler/decoding.rs+++ b/rust/feature-flags/src/handler/decoding.rs@@ -10,7 +10,7 @@ use crate::{use axum::http::{header::CONTENT_TYPE, header::USER_AGENT, HeaderMap};use base64::{engine::general_purpose, Engine as _};use bytes::Bytes;-use common_compression;+use common_compression::{self, has_gzip_magic_header};use common_metrics::inc;use percent_encoding::percent_decode;@@ -117,7 +117,7 @@ pub(crate) fn decode_body(// Fallback: Auto-detect gzip by checking magic bytes (0x1f, 0x8b)// This handles cases where clients send gzipped data without proper headers- if body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b {+ if has_gzip_magic_header(&body) {tracing::debug!("Auto-detected gzip compression from magic bytes");inc(FLAG_REQUEST_KLUDGE_COUNTER,