: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(capture): drain oversize request bodies so clients receive the 413 (#85639)
Paweł Ledwońb37315b93c42
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.tomlindex b5c256d13703..c1bc6e870c64 100644--- a/rust/capture/Cargo.toml+++ b/rust/capture/Cargo.toml@@ -68,6 +68,9 @@ hmac = { workspace = true }[dev-dependencies]capture = { path = ".", features = ["test-utils"] }+# `test-util` enables the paused clock (`start_paused`) the body drain deadline+# tests use, so they assert the timeout without sleeping in real time.+tokio = { workspace = true, features = ["test-util"] }assert-json-diff = { workspace = true }brotli = "8"zstd = "0.13"diff --git a/rust/capture/src/extractors.rs b/rust/capture/src/extractors.rsindex 1554a4c7eccb..7b90fb19402c 100644--- a/rust/capture/src/extractors.rs+++ b/rust/capture/src/extractors.rs@@ -7,12 +7,129 @@ use std::time::Duration;use axum::body::Body;use bytes::{BufMut, Bytes, BytesMut};-use futures::StreamExt;+use futures::{Stream, StreamExt};use tracing::warn;use crate::api::CaptureError;const METRIC_BODY_READ_TIMEOUT: &str = "capture_body_read_timeout_total";+const METRIC_REJECTED_BODY_DRAIN: &str = "capture_rejected_body_drain_total";++/// Wall-clock ceiling on draining a body we have already rejected.+///+/// A per-chunk timeout does not bound this work. A client that sends one byte just+/// before each deadline resets the timer every time, so the byte budget alone would+/// let a drain run for as long as it takes to drip `payload_size_limit` bytes. One+/// deadline over the whole drain bounds it regardless of chunk cadence, and it also+/// covers deployments that leave the per-chunk timeout unset.+///+/// Kept short because this is work on a request we are already refusing.+pub const REJECTED_BODY_DRAIN_DEADLINE: Duration = Duration::from_secs(5);++/// Outcome of draining a request body we have already decided to reject.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DrainOutcome {+ /// The body was consumed in full, so the rejection can be written on a+ /// connection the client can keep using.+ Drained,+ /// We stopped early. The connection is torn down and the client may see a+ /// reset instead of our status code.+ Abandoned(DrainAbandoned),+}++/// Why a drain stopped before the body ended. Each cause calls for a different+/// response, so they are reported apart rather than as one bucket.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DrainAbandoned {+ /// The client sent more after the rejection than we were willing to read.+ Budget,+ /// The deadline elapsed first: a stalled client, or one dripping slowly.+ Deadline,+ /// The stream failed, so the connection is already gone.+ StreamError,+}++impl DrainOutcome {+ fn as_metric_tag(&self) -> &'static str {+ match self {+ DrainOutcome::Drained => "drained",+ DrainOutcome::Abandoned(_) => "abandoned",+ }+ }++ fn reason_metric_tag(&self) -> &'static str {+ match self {+ DrainOutcome::Drained => "complete",+ DrainOutcome::Abandoned(DrainAbandoned::Budget) => "budget",+ DrainOutcome::Abandoned(DrainAbandoned::Deadline) => "deadline",+ DrainOutcome::Abandoned(DrainAbandoned::StreamError) => "stream_error",+ }+ }+}++/// Read and discard the rest of a request body we have already decided to reject.+///+/// Hyper cannot complete a keep-alive HTTP/1.1 response while the request body is+/// still unread; it tears the connection down instead, and the client sees a reset+/// rather than our status code. Consuming the remainder first lets the rejection be+/// delivered normally.+///+/// The read is bounded two ways: `budget` bytes, and `deadline` of wall-clock time+/// across the whole drain. Neither bound depends on the client's chunk cadence, so a+/// client cannot make us read indefinitely just to be told no. Only rejection paths+/// reach this, so it costs nothing on the happy path.+pub async fn drain_rejected_body<S>(+ stream: &mut S,+ budget: usize,+ deadline: Duration,+ path: &str,+) -> DrainOutcome+where+ S: Stream<Item = Result<Bytes, axum::Error>> + Unpin,+{+ let mut drained: usize = 0;+ let drain = async {+ loop {+ match stream.next().await {+ Some(Ok(chunk)) => {+ drained += chunk.len();+ if drained > budget {+ break DrainOutcome::Abandoned(DrainAbandoned::Budget);+ }+ }+ // The stream broke while we discarded it, so the connection is already gone.+ Some(Err(_)) => break DrainOutcome::Abandoned(DrainAbandoned::StreamError),+ None => break DrainOutcome::Drained,+ }+ }+ };++ // Covers both a client that stops sending and one that drips just fast enough+ // to keep a per-chunk timer alive.+ let outcome = tokio::time::timeout(deadline, drain)+ .await+ .unwrap_or(DrainOutcome::Abandoned(DrainAbandoned::Deadline));++ metrics::counter!(+ METRIC_REJECTED_BODY_DRAIN,+ "path" => path.to_string(),+ "outcome" => outcome.as_metric_tag(),+ "reason" => outcome.reason_metric_tag(),+ )+ .increment(1);++ if matches!(outcome, DrainOutcome::Abandoned(_)) {+ warn!(+ path = path,+ reason = outcome.reason_metric_tag(),+ drained_bytes = drained,+ budget = budget,+ "Rejected body drain abandoned; client may see a reset instead of our status"+ );+ }++ outcome+}/// Extract body bytes from a streaming Body with a per-chunk timeout.///@@ -57,6 +174,21 @@ pub async fn extract_body_with_timeout(Some(Ok(chunk)) => {// Check size limit before appendingif buf.len() + chunk.len() > payload_size_limit {+ // The drain can run for seconds. Holding the buffer and the+ // oversize chunk across it turns every rejection into a memory+ // spike the size of the limit we just refused.+ drop(buf);+ drop(chunk);+ // Consume what is left so the 413 reaches the client rather than a+ // connection reset. Bounded by the size we were willing to accept+ // in the first place.+ drain_rejected_body(+ &mut stream,+ payload_size_limit,+ REJECTED_BODY_DRAIN_DEADLINE,+ path,+ )+ .await;return Err(CaptureError::EventTooBig(format!("Request body exceeds limit of {payload_size_limit} bytes")));@@ -78,16 +210,135 @@ pub async fn extract_body_with_timeout(Ok(buf.freeze())}+/// Test-only stream builders shared by the readers' test modules.+#[cfg(test)]+pub(crate) mod test_support {+ use bytes::Bytes;+ use futures::{stream, Stream, StreamExt};+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;++ /// A stream of `count` ten-byte chunks that records how many were pulled.+ pub(crate) fn counted_chunks(+ count: usize,+ ) -> (+ impl Stream<Item = Result<Bytes, axum::Error>> + Unpin,+ Arc<AtomicUsize>,+ ) {+ let pulled = Arc::new(AtomicUsize::new(0));+ let counter = pulled.clone();+ let chunks: Vec<Result<Bytes, axum::Error>> = (0..count)+ .map(|_| Ok(Bytes::from_static(b"0123456789")))+ .collect();+ let stream = Box::pin(stream::iter(chunks).inspect(move |_| {+ counter.fetch_add(1, Ordering::SeqCst);+ }));+ (stream, pulled)+ }+}+#[cfg(test)]mod tests {+ use super::test_support::counted_chunks;use super::*;use axum::body::Body;use bytes::Bytes;use futures::stream;+ use std::sync::atomic::Ordering;use std::time::Duration;const TEST_CHUNK_SIZE_KB: usize = 256;+ #[tokio::test]+ async fn drain_rejected_body_consumes_the_whole_stream() {+ let (mut stream, pulled) = counted_chunks(3);++ let outcome =+ drain_rejected_body(&mut stream, 1024, Duration::from_secs(30), "/test").await;++ assert_eq!(outcome, DrainOutcome::Drained);+ assert_eq!(pulled.load(Ordering::SeqCst), 3);+ }++ #[tokio::test]+ async fn drain_rejected_body_stops_once_the_budget_is_spent() {+ let (mut stream, pulled) = counted_chunks(10);++ // Budget of 25 bytes covers two ten-byte chunks; the third overruns it.+ let outcome = drain_rejected_body(&mut stream, 25, Duration::from_secs(30), "/test").await;++ assert_eq!(outcome, DrainOutcome::Abandoned(DrainAbandoned::Budget));+ assert_eq!(pulled.load(Ordering::SeqCst), 3);+ }++ #[tokio::test(start_paused = true)]+ async fn drain_rejected_body_gives_up_on_a_stalled_client() {+ let chunks: Vec<Result<Bytes, axum::Error>> = vec![Ok(Bytes::from_static(b"partial"))];+ let mut stream = Box::pin(stream::iter(chunks).chain(stream::pending()));++ let outcome =+ drain_rejected_body(&mut stream, 1024, Duration::from_millis(50), "/test").await;++ assert_eq!(outcome, DrainOutcome::Abandoned(DrainAbandoned::Deadline));+ }++ #[tokio::test]+ async fn drain_rejected_body_reports_a_broken_stream_apart_from_a_timeout() {+ // A mid-drain stream error must not be filed as budget or deadline: the+ // metric drives whether the budget is the value to change.+ let chunks: Vec<Result<Bytes, axum::Error>> = vec![+ Ok(Bytes::from_static(b"partial")),+ Err(axum::Error::new(std::io::Error::other("broken pipe"))),+ ];+ let mut stream = Box::pin(stream::iter(chunks));++ let outcome =+ drain_rejected_body(&mut stream, 1024, Duration::from_secs(30), "/test").await;++ assert_eq!(+ outcome,+ DrainOutcome::Abandoned(DrainAbandoned::StreamError)+ );+ }++ #[tokio::test(start_paused = true)]+ async fn drain_rejected_body_bounds_a_slow_drip_client() {+ // One byte every 10ms, forever. No single gap is long enough to trip a+ // per-chunk timer, and the byte budget alone would allow hours of this.+ let mut stream = Box::pin(stream::unfold((), |_| async {+ tokio::time::sleep(Duration::from_millis(10)).await;+ Some((Ok(Bytes::from_static(b"x")), ()))+ }));++ let started = tokio::time::Instant::now();+ let outcome = drain_rejected_body(+ &mut stream,+ 10 * 1024 * 1024,+ Duration::from_secs(5),+ "/test",+ )+ .await;++ // The reason proves which bound fired; the elapsed check proves the+ // deadline was honored rather than the drip simply ending.+ assert_eq!(outcome, DrainOutcome::Abandoned(DrainAbandoned::Deadline));+ assert!(started.elapsed() < Duration::from_secs(6));+ }++ #[tokio::test]+ async fn extract_body_drains_an_oversize_body_before_rejecting() {+ // Four ten-byte chunks against a 25-byte limit: the third trips it, and the+ // fourth must still be pulled so hyper can deliver the 413 on a live+ // connection instead of resetting.+ let (stream, pulled) = counted_chunks(4);+ let body = Body::from_stream(stream);++ let result = extract_body_with_timeout(body, 25, None, TEST_CHUNK_SIZE_KB, "/test").await;++ assert!(matches!(result, Err(CaptureError::EventTooBig(_))));+ assert_eq!(pulled.load(Ordering::SeqCst), 4);+ }+#[tokio::test]async fn test_extract_body_no_timeout() {let body = Body::from("hello world");diff --git a/rust/capture/src/payload/analytics.rs b/rust/capture/src/payload/analytics.rsindex 122afbdce042..1a7a18026bca 100644--- a/rust/capture/src/payload/analytics.rs+++ b/rust/capture/src/payload/analytics.rs@@ -29,6 +29,7 @@ use crate::{skip_all,fields(method, path, token, ip, historical_migration, compression, batch_size))]+#[allow(clippy::too_many_arguments)]pub async fn handle_event_payload(state: &State<router::State>,InsecureClientIp(ip): &InsecureClientIp,@@ -36,6 +37,7 @@ pub async fn handle_event_payload(headers: &HeaderMap,method: &Method,path: &MatchedPath,+ wire_limit: Option<router::WireBodyLimit>,body: Body,) -> Result<(ProcessingContext, Vec<RawEvent>), CaptureError> {let chatty_debug_enabled = headers.get("X-CAPTURE-DEBUG").is_some();@@ -53,9 +55,14 @@ pub async fn handle_event_payload(// - compression = hint to how "data" is encoded or compressed// Extract body with optional chunk timeout+ // Wire limit governs the streamed body; event_payload_size_limit is the+ // larger budget for what that body decompresses into.+ let wire_limit = wire_limit+ .map(|l| l.0)+ .unwrap_or(state.event_payload_size_limit);let body = extract_body_with_timeout(body,- state.event_payload_size_limit,+ wire_limit,state.body_chunk_read_timeout,state.body_read_chunk_size_kb,path.as_str(),diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rsindex 3457a5617332..bc21fa2a68de 100644--- a/rust/capture/src/payload/recordings.rs+++ b/rust/capture/src/payload/recordings.rs@@ -44,6 +44,7 @@ impl RecordingPayload {/// This is optimized to avoid the double serialization that would occur/// if we went through RawRequest -> Vec<RawEvent> -> process#[instrument(skip_all, fields(batch_size, params_compression))]+#[allow(clippy::too_many_arguments)]pub async fn handle_recording_payload(state: &State<router::State>,InsecureClientIp(ip): &InsecureClientIp,@@ -51,6 +52,7 @@ pub async fn handle_recording_payload(headers: &HeaderMap,method: &Method,path: &MatchedPath,+ wire_limit: Option<router::WireBodyLimit>,body: Body,) -> Result<(ProcessingContext, Vec<RawRecording>), CaptureError> {let chatty_debug_enabled = headers.get("X-CAPTURE-DEBUG").is_some();@@ -58,9 +60,14 @@ pub async fn handle_recording_payload(debug_or_info!(chatty_debug_enabled, headers=?headers, "entering handle_recording_payload");// Extract body with optional chunk timeout+ // Wire limit governs the streamed body; event_payload_size_limit is the+ // larger budget for what that body decompresses into.+ let wire_limit = wire_limit+ .map(|l| l.0)+ .unwrap_or(state.event_payload_size_limit);let body = extract_body_with_timeout(body,- state.event_payload_size_limit,+ wire_limit,state.body_chunk_read_timeout,state.body_read_chunk_size_kb,path.as_str(),diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex f5da6cb0b9e5..4a9ee3255b63 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -4,6 +4,7 @@ use std::time::Duration;use axum::extract::DefaultBodyLimit;use axum::http::Method;+use axum::Extension;use axum::{routing::{get, post},Router,@@ -31,9 +32,21 @@ use crate::metrics_middleware::track_metrics;use crate::quota_limiters::CaptureQuotaLimiter;use metrics_exporter_prometheus::PrometheusHandle;-const EVENT_BODY_SIZE: usize = 2 * 1024 * 1024; // 2MB-pub const BATCH_BODY_SIZE: usize = 20 * 1024 * 1024; // 20MB, up from the default 2MB used for normal event payloads-const RECORDING_BODY_SIZE: usize = 25 * 1024 * 1024; // 25MB, up from the default 2MB used for normal event payloads+/// Wire-body ceiling for every v0 analytics route. One handler serves `/e`,+/// `/batch`, `/capture`, `/track` and `/engage`, and a batch is accepted on any+/// of them, so the cap is a property of the pipeline rather than of the path.+pub const BATCH_BODY_SIZE: usize = 20 * 1024 * 1024; // 20MB++const RECORDING_BODY_SIZE: usize = 25 * 1024 * 1024; // 25MB++/// A route group's wire-body ceiling, carried as a request extension.+///+/// `DefaultBodyLimit` only inserts an extension that `Bytes`-style extractors+/// read. Handlers that stream take `Body`, which never reads it, so they would+/// otherwise fall back to the much larger decompressed budget. Both layers are+/// applied from the same constant so one number governs the route either way.+#[derive(Debug, Clone, Copy)]+pub struct WireBodyLimit(pub usize);#[derive(Clone)]pub struct State {@@ -228,7 +241,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.get(test_endpoint::test_black_hole).options(v0_endpoint::options),)- .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE));+ .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE))+ .layer(Extension(WireBodyLimit(BATCH_BODY_SIZE)));let batch_router = Router::new().route(@@ -257,7 +271,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.get(v0_endpoint::event).options(v0_endpoint::options),)- .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE)); // Have to use this, rather than RequestBodyLimitLayer, because we use `Bytes` in the handler (this limit applies specifically to Bytes body types)+ .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE))+ .layer(Extension(WireBodyLimit(BATCH_BODY_SIZE)));let event_router = Router::new().route(@@ -320,7 +335,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.get(v0_endpoint::event).options(v0_endpoint::options),)- .layer(DefaultBodyLimit::max(EVENT_BODY_SIZE));+ .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE))+ .layer(Extension(WireBodyLimit(BATCH_BODY_SIZE)));let status_router = Router::new().route("/", get(index))@@ -352,7 +368,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.get(v0_endpoint::recording).options(v0_endpoint::options),)- .layer(DefaultBodyLimit::max(RECORDING_BODY_SIZE));+ .layer(DefaultBodyLimit::max(RECORDING_BODY_SIZE))+ .layer(Extension(WireBodyLimit(RECORDING_BODY_SIZE)));// AI endpoint body limit is 110% of max sum of parts to account for multipart overheadlet ai_body_limit = (state.ai_max_sum_of_parts_bytes as f64 * 1.1) as usize;diff --git a/rust/capture/src/test_endpoint.rs b/rust/capture/src/test_endpoint.rsindex ad8885e6f52d..fcb4669c5803 100644--- a/rust/capture/src/test_endpoint.rs+++ b/rust/capture/src/test_endpoint.rs@@ -35,6 +35,7 @@ pub const UTF8_FAILED: &str = "capture_test_utf8_failed";// A handler that does nothing except try to parse the request, and produce a tonne of metrics// about failures. Once python capture is dead, we should remove file entirely.#[debug_handler]+#[allow(clippy::too_many_arguments)]pub async fn test_black_hole(state: State<router::State>,_ip: InsecureClientIp,@@ -42,12 +43,15 @@ pub async fn test_black_hole(headers: HeaderMap,_method: Method,_path: MatchedPath,+ wire_limit: Option<axum::Extension<router::WireBodyLimit>>,body: Body,) -> Result<Json<CaptureResponse>, CaptureError> {// Extract body with optional chunk timeoutlet body = extract_body_with_timeout(body,- state.event_payload_size_limit,+ wire_limit+ .map(|axum::Extension(l)| l.0)+ .unwrap_or(state.event_payload_size_limit),state.body_chunk_read_timeout,state.body_read_chunk_size_kb,"/test/black_hole",diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rsindex 82dd40ccac1c..9110c7c7ea05 100644--- a/rust/capture/src/v0_endpoint.rs+++ b/rust/capture/src/v0_endpoint.rs@@ -1,7 +1,7 @@use axum::body::Body;use axum::extract::{MatchedPath, Query, State};use axum::http::{HeaderMap, Method};-use axum::{debug_handler, Json};+use axum::{debug_handler, Extension, Json};use axum_client_ip::InsecureClientIp;use tracing::{instrument, Span};@@ -15,6 +15,7 @@ use crate::{#[instrument(skip(state, body, meta), fields(params_compression))]#[debug_handler]+#[allow(clippy::too_many_arguments)]pub async fn event(state: State<router::State>,ip: InsecureClientIp,@@ -22,6 +23,7 @@ pub async fn event(headers: HeaderMap,method: Method,path: MatchedPath,+ wire_limit: Option<Extension<router::WireBodyLimit>>,body: Body,) -> Result<CaptureResponse, CaptureError> {let mut params: EventQuery = meta.0;@@ -34,7 +36,18 @@ pub async fn event();}- match handle_event_payload(&state, &ip, &mut params, &headers, &method, &path, body).await {+ match handle_event_payload(+ &state,+ &ip,+ &mut params,+ &headers,+ &method,+ &path,+ wire_limit.map(|Extension(l)| l),+ body,+ )+ .await+ {Err(CaptureError::BillingLimit) => {// Short term: return OK here to avoid clients retrying over and over// Long term: v1 endpoints will return richer errors, sync w/SDK behavior@@ -106,6 +119,7 @@ pub async fn event())]#[debug_handler]+#[allow(clippy::too_many_arguments)]pub async fn recording(state: State<router::State>,ip: InsecureClientIp,@@ -113,11 +127,23 @@ pub async fn recording(headers: HeaderMap,method: Method,path: MatchedPath,+ wire_limit: Option<Extension<router::WireBodyLimit>>,body: Body,) -> Result<CaptureResponse, CaptureError> {let mut params: EventQuery = meta.0;- match handle_recording_payload(&state, &ip, &mut params, &headers, &method, &path, body).await {+ match handle_recording_payload(+ &state,+ &ip,+ &mut params,+ &headers,+ &method,+ &path,+ wire_limit.map(|Extension(l)| l),+ body,+ )+ .await+ {Err(CaptureError::BillingLimit) => Ok(CaptureResponse {status: CaptureResponseCode::Ok,quota_limited: Some(vec!["recordings".to_string()]),diff --git a/rust/capture/src/v1/util.rs b/rust/capture/src/v1/util.rsindex d9591b31a637..7a4e27cbc335 100644--- a/rust/capture/src/v1/util.rs+++ b/rust/capture/src/v1/util.rs@@ -6,6 +6,7 @@ use bytes::{BufMut, Bytes, BytesMut};use futures::StreamExt;use tokio::io::AsyncReadExt;+use crate::extractors::{drain_rejected_body, REJECTED_BODY_DRAIN_DEADLINE};use crate::v1::constants::{CAPTURE_V1_BODY_READ_TIMEOUT, CAPTURE_V1_DECOMPRESSION_ERRORS};use crate::v1::Error;@@ -58,6 +59,21 @@ pub async fn extract_body_with_timeout(match chunk_result {Some(Ok(chunk)) => {if buf.len() + chunk.len() > payload_size_limit {+ // The drain can run for seconds. Holding the buffer and the+ // oversize chunk across it turns every rejection into a memory+ // spike the size of the limit we just refused.+ drop(buf);+ drop(chunk);+ // Consume what is left so the 413 reaches the client rather than a+ // connection reset. Bounded by the size we were willing to accept+ // in the first place.+ drain_rejected_body(+ &mut stream,+ payload_size_limit,+ REJECTED_BODY_DRAIN_DEADLINE,+ path,+ )+ .await;return Err(Error::PayloadTooLarge(format!("Request body exceeds limit of {payload_size_limit} bytes")));@@ -65,9 +81,11 @@ pub async fn extract_body_with_timeout(buf.put(chunk);}Some(Err(e)) => {- // A body wrapped by axum's DefaultBodyLimit surfaces over-limit- // reads as a LengthLimitError in the stream; report those as 413- // rather than a generic decoding failure.+ // A LengthLimitError reaches us only when something wraps the body+ // in http_body_util::Limited. Nothing does on this route today:+ // the v1 DefaultBodyLimit layer only inserts a request extension,+ // and the `Body` extractor never reads it. Kept so the status stays+ // correct if a limited body is ever introduced upstream.if error_chain_has_length_limit(&e) {return Err(Error::PayloadTooLarge(format!("Request body exceeds limit of {payload_size_limit} bytes"@@ -251,6 +269,23 @@ mod tests {assert!(matches!(result, Err(Error::PayloadTooLarge(_))));}+ #[tokio::test]+ async fn extract_body_drains_an_oversize_body_before_rejecting() {+ use crate::extractors::test_support::counted_chunks;+ use std::sync::atomic::Ordering;++ // Four ten-byte chunks against a 25-byte limit: the third trips it, and the+ // fourth must still be pulled so hyper can deliver the 413 on a live+ // connection instead of resetting.+ let (stream, pulled) = counted_chunks(4);+ let body = Body::from_stream(stream);++ let result = extract_body_with_timeout(body, 25, None, TEST_CHUNK_SIZE_KB, "/test").await;++ assert!(matches!(result, Err(Error::PayloadTooLarge(_))));+ assert_eq!(pulled.load(Ordering::SeqCst), 4);+ }+#[tokio::test]async fn extract_body_timeout_fires() {let chunks: Vec<Result<Bytes, std::io::Error>> = vec![Ok(Bytes::from("partial"))];diff --git a/rust/capture/tests/events.rs b/rust/capture/tests/events.rsindex 66132e19f68e..03bd4ae148c2 100644--- a/rust/capture/tests/events.rs+++ b/rust/capture/tests/events.rs@@ -1256,7 +1256,7 @@ async fn it_routes_exceptions_and_heapmaps_to_separate_topics() -> Result<()> {}#[tokio::test]-async fn it_limits_non_batch_endpoints_to_2mb() -> Result<()> {+async fn it_limits_every_analytics_endpoint_to_the_same_wire_cap() -> Result<()> {setup_tracing();let token = random_string("token", 16);@@ -1266,68 +1266,46 @@ async fn it_limits_non_batch_endpoints_to_2mb() -> Result<()> {let histo_topic = EphemeralTopic::new().await;let server = ServerHandle::for_topics(&main_topic, &histo_topic).await;- let ok_event = json!({+ // One handler serves every analytics route, so the cap is the same on all of+ // them. Accept-side coverage lives in integration_wire_body_limits.rs, which+ // runs without Kafka.+ let over_cap = json!({"token": token,"event": "event1","distinct_id": distinct_id,"properties": {- "big": "a".repeat(2_000_000)+ "big": "a".repeat(21 * 1024 * 1024)}});- let nok_event = json!({- "token": token,- "event": "event2",- "distinct_id": distinct_id,- "properties": {- "big": "a".repeat(2_100_000)- }- });-- let res = server.capture_events(ok_event.to_string()).await;+ let res = server.capture_events(over_cap.to_string()).await;assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());- let res = server.capture_events(nok_event.to_string()).await;+ let res = server.capture_to_batch(over_cap.to_string()).await;assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());- Ok(())-}--#[tokio::test]-async fn it_limits_batch_endpoints_to_20mb() -> Result<()> {- setup_tracing();-- let token = random_string("token", 16);- let distinct_id = random_string("id", 16);-- let main_topic = EphemeralTopic::new().await;- let histo_topic = EphemeralTopic::new().await;- let server = ServerHandle::for_topics(&main_topic, &histo_topic).await;-- // Notably here, rust capture actually handles all endpoints with the same function, so we don't actually- // need to wrap these events in an array to send them to our batch endpoint- let ok_event = json!({+ // The accept side, on both routes, proven by the event reaching the topic.+ // It has to stay under the producer's 1MB message ceiling, so it cannot also+ // show that the cap is now 20MB rather than 2MB; that case needs an+ // in-process sink and lives in integration_wire_body_limits.rs.+ let accepted = json!({"token": token,- "event": "event1",+ "event": "event3","distinct_id": distinct_id,"properties": {- "big": "a".repeat(20_000_000)+ "big": "a".repeat(256 * 1024)}});- let nok_event = json!({- "token": token,- "event": "event2",- "distinct_id": distinct_id,- "properties": {- "big": "a".repeat(21_000_000)- }- });+ let res = server.capture_events(accepted.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());+ let got = main_topic.next_event()?;+ assert_eq!(got["event"], "event3");- let res = server.capture_to_batch(ok_event.to_string()).await;- assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());- let res = server.capture_to_batch(nok_event.to_string()).await;- assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());+ let res = server.capture_to_batch(accepted.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());+ let got = main_topic.next_event()?;+ assert_eq!(got["event"], "event3");Ok(())}diff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rsnew file mode 100644index 000000000000..ba8b6013d864--- /dev/null+++ b/rust/capture/tests/integration_wire_body_limits.rs@@ -0,0 +1,251 @@+#[path = "common/integration_utils.rs"]+mod integration_utils;++use async_trait::async_trait;+use axum::http::StatusCode;+use axum_test_helper::TestClient;+use capture::api::CaptureError;+use capture::config::CaptureMode;+use capture::quota_limiters::CaptureQuotaLimiter;+use capture::router::{router, BATCH_BODY_SIZE};+use capture::sinks::Event;+use capture::time::TimeSource;+use capture::v0_request::ProcessedEvent;+use chrono::{DateTime, Utc};+use common_redis::MockRedisClient;+use integration_utils::{test_lifecycle_handlers, DEFAULT_TEST_TIME};+use limiters::token_dropper::TokenDropper;+use std::sync::Arc;+use std::time::Duration;++use integration_utils::DEFAULT_CONFIG;++struct FixedTime {+ pub time: DateTime<Utc>,+}++impl TimeSource for FixedTime {+ fn current_time(&self) -> DateTime<Utc> {+ self.time+ }+}++#[derive(Clone)]+struct CapturingSink {+ events: Arc<tokio::sync::Mutex<Vec<ProcessedEvent>>>,+}++impl CapturingSink {+ fn new() -> Self {+ Self {+ events: Arc::new(tokio::sync::Mutex::new(Vec::new())),+ }+ }++ async fn count(&self) -> usize {+ self.events.lock().await.len()+ }+}++#[async_trait]+impl Event for CapturingSink {+ async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {+ self.events.lock().await.push(event);+ Ok(())+ }++ async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ self.events.lock().await.extend(events);+ Ok(())+ }+}++/// A client whose decompressed budget is far above the wire cap, so only the+/// wire cap can produce a 413. This mirrors production, where the decompressed+/// budget is five times the wire cap.+fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {+ let (readiness, liveness, _monitor) = test_lifecycle_handlers();+ let timesource = FixedTime {+ time: DateTime::parse_from_rfc3339(DEFAULT_TEST_TIME)+ .expect("Invalid fixed time format")+ .with_timezone(&Utc),+ };+ let redis = Arc::new(MockRedisClient::new());+ let sink = CapturingSink::new();+ let mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = mode;++ let app = router(+ timesource,+ readiness,+ liveness,+ Arc::new(sink.clone()),+ redis.clone(),+ None,+ CaptureQuotaLimiter::new(&cfg, redis, Duration::from_secs(60)),+ TokenDropper::default(),+ None,+ None,+ mode,+ None,+ BATCH_BODY_SIZE * 5,+ false,+ 1_i64,+ false,+ 0.0_f32,+ 26_214_400,+ None,+ 256,+ 10 * 1024 * 1024,+ 50 * 1024 * 1024,+ None,+ None,+ None,+ None,+ 8,+ None,+ false,+ None,+ );++ (TestClient::new(app), sink)+}++/// A body of `len` bytes that is valid JSON, so nothing before the size check+/// can reject it for a different reason.+fn body_of_len(len: usize) -> String {+ let envelope = r#"{"token":"phc_test","event":"e","distinct_id":"d","properties":{"big":""}}"#;+ let padding = len.saturating_sub(envelope.len());+ format!(+ r#"{{"token":"phc_test","event":"e","distinct_id":"d","properties":{{"big":"{}"}}}}"#,+ "a".repeat(padding)+ )+}++/// Every v0 analytics route shares one handler, so every one of them must share+/// one wire cap. Before this was wired through, `DefaultBodyLimit` was the only+/// thing carrying these numbers, and it does not apply to a `Body` extractor —+/// so each of these paths silently accepted the much larger decompressed budget.+#[tokio::test]+async fn every_v0_analytics_route_rejects_a_body_over_the_wire_cap() {+ let (client, _sink) = make_test_client(CaptureMode::Events);+ let over = body_of_len(BATCH_BODY_SIZE + 1024);++ for path in [+ "/e",+ "/i/v0/e",+ "/batch",+ "/i/v0/ai/batch",+ "/capture",+ "/track",+ "/engage",+ ] {+ let res = client+ .post(path)+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(over.clone())+ .send()+ .await;+ assert_eq!(+ StatusCode::PAYLOAD_TOO_LARGE,+ res.status(),+ "{path} accepted a body over the wire cap"+ );+ }+}++/// The cap must not be so tight that it rejects a legal body. This is the half+/// the pre-existing boundary tests stopped asserting, which is why a widened cap+/// went unnoticed.+#[tokio::test]+async fn every_v0_analytics_route_accepts_a_body_under_the_wire_cap() {+ let (client, sink) = make_test_client(CaptureMode::Events);+ // Comfortably over the 2MB cap the event routes used to carry, and well+ // under the shared 20MB one.+ let under = body_of_len(4 * 1024 * 1024);+ let mut ingested = 0usize;++ for path in [+ "/e",+ "/i/v0/e",+ "/batch",+ "/i/v0/ai/batch",+ "/capture",+ "/track",+ "/engage",+ ] {+ let res = client+ .post(path)+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(under.clone())+ .send()+ .await;+ assert_eq!(+ StatusCode::OK,+ res.status(),+ "{path} rejected a body inside the wire cap"+ );+ ingested += 1;+ assert_eq!(+ ingested,+ sink.count().await,+ "{path} returned 200 without producing the event"+ );+ }+}++/// The drain exists so a rejection can be written on a connection the client+/// keeps using. A small overshoot proves little, because hyper's own one-shot+/// drain absorbs a few leftover bytes by itself. This overshoots by half the cap,+/// which is far more than hyper will absorb, and asserts the status still lands+/// on a connection the next request can reuse.+///+/// The drain budget is one times the cap, so it covers bodies up to twice the+/// cap. Past that it gives up and the client sees a reset instead. Nothing in+/// production comes close: the largest bodies observed are well under the cap.+#[tokio::test]+async fn a_large_overshoot_still_delivers_the_status_instead_of_a_reset() {+ let (client, sink) = make_test_client(CaptureMode::Events);+ let res = client+ .post("/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(body_of_len(BATCH_BODY_SIZE + BATCH_BODY_SIZE / 2))+ .send()+ .await;++ assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());++ // The connection survived the rejection, so the next request works.+ let res = client+ .post("/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(body_of_len(1024))+ .send()+ .await;+ assert_eq!(StatusCode::OK, res.status());+ assert_eq!(+ 1,+ sink.count().await,+ "the retry after a rejection was lost"+ );+}++/// Replay keeps its own, larger cap. It runs a different handler, so the wiring+/// is separate and worth pinning apart from the analytics routes.+#[tokio::test]+async fn the_replay_route_rejects_a_body_over_its_own_wire_cap() {+ let (client, _sink) = make_test_client(CaptureMode::Recordings);+ let res = client+ .post("/s")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(body_of_len(26 * 1024 * 1024))+ .send()+ .await;++ assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, res.status());+}