diff --git a/CHANGELOG.md b/CHANGELOG.md index 11d9152a4..4c916fe9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +### Axum buffered JSON limits and body API + +- **Breaking:** On Axum, ordinary `Json` and `ValidatedJson` now default to 2 MiB + (2,097,152 bytes) instead of 8 MiB. Explicit caps above the native ceiling are clamped + for JSON helpers and for generic buffered reads on JSON ingress, including form helpers and + pre-dispatch reads. To accept larger requests, set `EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES` + for standalone hosting or use the fallible `with_json_body_limit_bytes` builder on + `AxumRunOptions` or `AxumDevServer`. Overflow returns typed HTTP 413; malformed JSON + remains 400. Taken streams, forwarding, manual collection, and other providers' defaults + are unchanged. +- `Body` still exposes the same struct and exhaustive `BodyPayload`. The private policy + field changes `Body`'s size and debug output, but there is no source migration for payload + consumers. Policy and cache provenance follow the original body through reconstruction, + even after header or extension edits. Raw payload handoff drops the policy and preserves + exact egress ownership. + ### Portable HTTP And Request Lifecycles (PR #275) The changes below cover [PR #275](https://github.com/IABTechLab/edgezero/pull/275), including its diff --git a/Cargo.lock b/Cargo.lock index 6e1948807..c2d082ebe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -737,6 +737,7 @@ dependencies = [ "hyper-util", "libc", "log", + "mime", "redb", "reqwest", "serde", diff --git a/Cargo.toml b/Cargo.toml index fab4ba255..f7dfecd1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,6 +75,7 @@ libc = "0.2" miniz_oxide = { version = "=0.8.9", default-features = false, features = ["simd", "with-alloc"] } log-fastly = "=0.13.3" matchit = "0.9" +mime = "0.3" once_cell = "1" # 4.2 asserts that no read reference outlives its transaction. That check # is what caught the `AccessGuard` bug in the axum KV store, so the diff --git a/crates/edgezero-adapter-axum/Cargo.toml b/crates/edgezero-adapter-axum/Cargo.toml index bdccbc78e..d9c2b7a57 100644 --- a/crates/edgezero-adapter-axum/Cargo.toml +++ b/crates/edgezero-adapter-axum/Cargo.toml @@ -21,6 +21,7 @@ axum = [ "dep:http-body", "dep:hyper", "dep:hyper-util", + "dep:mime", "dep:reqwest", "dep:redb", ] @@ -51,6 +52,7 @@ http-body = { workspace = true, optional = true } hyper = { workspace = true, optional = true } hyper-util = { workspace = true, optional = true } log = { workspace = true } +mime = { workspace = true, optional = true } redb = { workspace = true, optional = true } reqwest = { workspace = true, optional = true } serde = { workspace = true } diff --git a/crates/edgezero-adapter-axum/src/connection.rs b/crates/edgezero-adapter-axum/src/connection.rs index 8931df4eb..5d82f145a 100644 --- a/crates/edgezero-adapter-axum/src/connection.rs +++ b/crates/edgezero-adapter-axum/src/connection.rs @@ -1546,7 +1546,7 @@ mod tests { #[tokio::test(flavor = "current_thread")] async fn json_extractor_overflow_reaches_custom_renderer_without_retry_after() { - use edgezero_core::context::DEFAULT_INBOUND_JSON_BYTES; + use crate::run_options::JsonBodyLimit; use edgezero_core::extractor::Json; #[edgezero_core::action] @@ -1565,7 +1565,7 @@ mod tests { .body(Body::from("extractor overflow")) .expect("custom error response") }); - let cap = DEFAULT_INBOUND_JSON_BYTES; + let cap = JsonBodyLimit::DEFAULT.get().get(); let body = serde_json::to_string(&serde_json::json!("x".repeat(cap - 1))) .expect("valid oversized JSON string"); assert_eq!(body.len(), cap + 1); diff --git a/crates/edgezero-adapter-axum/src/dev_server.rs b/crates/edgezero-adapter-axum/src/dev_server.rs index c5aa5f55f..afb850522 100644 --- a/crates/edgezero-adapter-axum/src/dev_server.rs +++ b/crates/edgezero-adapter-axum/src/dev_server.rs @@ -4,6 +4,8 @@ )] use std::any::Any; +use std::env::vars_os; +use std::ffi::OsString; use std::fs; use std::future::{self, Future}; use std::io; @@ -18,7 +20,7 @@ use std::time::Duration; use crate::outbound_executor::{AxumOutboundExecutor, AxumOutboundExecutorHandle}; pub use crate::run_options::AxumRunOptions; -use crate::run_options::failure; +use crate::run_options::{JsonBodyLimit, config_path, failure, native_limit_setting}; use anyhow::Context as _; use edgezero_core::probe::LifecyclePhase; use futures_util::FutureExt as _; @@ -142,6 +144,7 @@ struct Stores { pub struct AxumDevServer { app: App, config: AxumDevServerConfig, + json_body_limit: JsonBodyLimit, stores: Stores, } @@ -159,6 +162,7 @@ impl AxumDevServer { Self { app, config: AxumDevServerConfig::default(), + json_body_limit: JsonBodyLimit::DEFAULT, stores: Stores::default(), } } @@ -171,6 +175,7 @@ impl AxumDevServer { app, config, stores, + json_body_limit, } = self; run_local( ListenerSource::Bind(config.addr), @@ -179,7 +184,7 @@ impl AxumDevServer { }, config.ingress, future::pending::<()>(), - async move { prepare_transport(app, stores.into()) }, + async move { prepare_transport(app, stores.into(), json_body_limit) }, ) } @@ -205,6 +210,7 @@ impl AxumDevServer { app, config, stores, + json_body_limit, } = self; serve_with_stores( app, @@ -212,6 +218,7 @@ impl AxumDevServer { config.enable_ctrl_c, config.ingress, stores, + json_body_limit, shutdown, ) .await @@ -223,6 +230,7 @@ impl AxumDevServer { Self { app, config, + json_body_limit: JsonBodyLimit::DEFAULT, stores: Stores::default(), } } @@ -241,6 +249,16 @@ impl AxumDevServer { self } + /// Selects the ceiling for framework-managed JSON buffering, in bytes. + /// + /// # Errors + /// Rejects zero and values above the collector's representable capacity. + #[inline] + pub fn with_json_body_limit_bytes(mut self, limit: usize) -> anyhow::Result { + self.json_body_limit = JsonBodyLimit::new(limit)?; + Ok(self) + } + /// Attach a KV store to the dev server. /// /// The handle is shared across all requests, making the `Kv` extractor @@ -312,7 +330,7 @@ impl From for PreparedStores { } } -type PreparedApp = (App, PreparedStores, Arc); +type PreparedApp = (App, PreparedStores, Arc, JsonBodyLimit); type ConnectionResult = Result, Box>; type Connections = FuturesUnordered>>>; @@ -480,6 +498,7 @@ async fn serve_with_stores( enable_ctrl_c: bool, ingress: AxumIngressConfig, stores: Stores, + json_body_limit: JsonBodyLimit, shutdown: impl future::Future, ) -> anyhow::Result<()> { struct ShutdownOnDrop(Option>); @@ -508,6 +527,7 @@ async fn serve_with_stores( enable_ctrl_c, ingress, stores, + json_body_limit, shutdown_receiver, ) }); @@ -528,6 +548,7 @@ fn serve_local( enable_ctrl_c: bool, ingress: AxumIngressConfig, stores: Stores, + json_body_limit: JsonBodyLimit, shutdown_receiver: ShutdownReceiver<()>, ) -> anyhow::Result<()> { run_local( @@ -539,7 +560,7 @@ fn serve_local( async move { let _closed = shutdown_receiver.await; }, - async move { prepare_transport(app, stores.into()) }, + async move { prepare_transport(app, stores.into(), json_body_limit) }, ) } @@ -567,10 +588,14 @@ fn adopt_listener(source: ListenerSource) -> anyhow::Result { .map_err(|_error| failure("bind", "listener", "runtime adoption failed")) } -fn prepare_transport(app: App, stores: PreparedStores) -> anyhow::Result { +fn prepare_transport( + app: App, + stores: PreparedStores, + json_body_limit: JsonBodyLimit, +) -> anyhow::Result { let transport = AxumOutboundClient::try_transport() .map_err(|_error| failure("transport", "HTTP client", "initialization failed"))?; - Ok((app, stores, transport)) + Ok((app, stores, transport, json_body_limit)) } async fn next_signal(signals: &mut Option) -> anyhow::Result<()> { @@ -725,7 +750,7 @@ where } fn prepare_service( - (app, stores, transport): PreparedApp, + (app, stores, transport, json_body_limit): PreparedApp, ingress: AxumIngressConfig, reader: watch::Receiver, executor: AxumOutboundExecutorHandle, @@ -739,7 +764,8 @@ fn prepare_service( { log::warn!(target: BOOT_LOG_TARGET, "application head limits exceed Axum raw ingress limits; the parser rejects first"); } - let mut service = AxumServiceState::with_transport(app, transport, executor).with_phase(reader); + let mut service = AxumServiceState::with_transport(app, transport, executor, json_body_limit) + .with_phase(reader); if let Some(registry) = stores.config { service = service.with_config_registry(registry); } @@ -920,7 +946,7 @@ where A: Hooks, F: FnOnce() -> anyhow::Result<()>, { - let env = EnvConfig::from_env(); + let (env, json_body_limit) = capture_dev_environment(vars_os())?; if !A::owns_logging() { app_logger(&env) .init() @@ -948,11 +974,34 @@ where config: build_config_registry(metadata.config, &env, config_limits)?, secrets: build_secret_registry(metadata.secrets, &env), }; - prepare_transport(app, stores) + prepare_transport(app, stores, json_body_limit) }, ) } +fn capture_dev_environment(vars: I) -> anyhow::Result<(EnvConfig, JsonBodyLimit)> +where + I: IntoIterator, +{ + let mut pairs = Vec::new(); + for (os_key, os_value) in vars { + let Some(key) = os_key.to_str() else { + continue; + }; + let setting = config_path(key, cfg!(windows)).and_then(|path| native_limit_setting(&path)); + match (os_value.to_str(), setting) { + (Some(value), _) => pairs.push((key.to_owned(), value.to_owned())), + (None, Some(category)) => { + return Err(failure("settings", category, "non-Unicode value")); + } + (None, None) => {} + } + } + let env = EnvConfig::from_vars(pairs); + let limit = JsonBodyLimit::from_config(&env)?; + Ok((env, limit)) +} + fn init_logging(level: LevelFilter) -> anyhow::Result<()> where A: Hooks, @@ -1086,7 +1135,7 @@ where ); failure("initializer", "application", &category) })?; - Ok((app, stores, transport)) + Ok((app, stores, transport, options.json_body_limit())) }, ) } @@ -1816,6 +1865,81 @@ mod tests { assert!(!config.enable_ctrl_c); } + #[test] + fn json_limit_development_capture_and_explicit_router_builder() { + let (env, selected) = capture_dev_environment([ + ( + OsString::from("EDGEZERO__ADAPTER__HOST"), + OsString::from("invalid-host"), + ), + ( + OsString::from("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES"), + OsString::from("64"), + ), + ]) + .expect("permissive bind and strict JSON option"); + assert_eq!(selected.get().get(), 64); + assert_eq!(resolve_addr(&env).addr.ip(), addr::DEFAULT_HOST); + let router = RouterService::builder().build(); + let default = AxumDevServer::new(App::new(router.clone())); + assert_eq!(default.json_body_limit.get().get(), 2 * 1024 * 1024); + let explicit = AxumDevServer::with_config(App::new(router), AxumDevServerConfig::default()) + .with_json_body_limit_bytes(64) + .expect("builder"); + let prepared = prepare_transport( + explicit.app, + explicit.stores.into(), + explicit.json_body_limit, + ) + .expect("prepared transport"); + assert_eq!(prepared.3.get().get(), 64); + assert!( + AxumDevServer::new(App::new(RouterService::builder().build())) + .with_json_body_limit_bytes(0) + .is_err() + ); + } + + #[cfg(unix)] + #[test] + fn development_capture_skips_unrelated_binary_settings_but_rejects_binary_json_limit() { + use std::os::unix::ffi::OsStringExt as _; + let binary = OsString::from_vec(vec![0xff]); + let (env, selected) = capture_dev_environment([ + (binary.clone(), OsString::from("ignored")), + (OsString::from("UNRELATED"), binary.clone()), + (OsString::from("EDGEZERO__ADAPTER__HOST"), binary.clone()), + ( + OsString::from("EDGEZERO__STORES__KV__DEFAULT__NAME"), + binary.clone(), + ), + ]) + .expect("unrelated omissions"); + assert_eq!(selected.get().get(), 2 * 1024 * 1024); + assert!(env.adapter_host().is_none()); + assert_eq!(env.store_name("kv", "default"), "default"); + let error = capture_dev_environment([( + OsString::from("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES"), + binary, + )]) + .expect_err("recognized binary setting"); + assert!(error.to_string().contains("JSON_BODY_LIMIT_BYTES")); + assert_eq!(error.chain().count(), 1); + for (path, category) in [ + ("INGRESS__MAX_CONNECTIONS", "INGRESS"), + ("CONFIG_STORE__MAX_FILE_BYTES", "CONFIG_STORE"), + ] { + let owned_error = capture_dev_environment([( + OsString::from(format!("EDGEZERO__ADAPTER__{path}")), + OsString::from_vec(b"PRIVATE_SENTINEL\xff".to_vec()), + )]) + .expect_err("owned binary limit must fail"); + assert!(owned_error.to_string().contains(category)); + assert!(!format!("{owned_error:?}").contains("PRIVATE_SENTINEL")); + assert_eq!(owned_error.chain().count(), 1); + } + } + #[test] fn dev_server_new_uses_default_config() { use edgezero_core::router::RouterService; @@ -1826,6 +1950,122 @@ mod tests { assert!(server.config.enable_ctrl_c); } + async fn router_json_upload(addr: SocketAddr, body: String, status: u16) -> String { + use std::io::ErrorKind; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + use tokio::net::TcpStream; + use tokio::time::timeout; + + let socket = TcpStream::connect(addr).await.expect("upload connection"); + let (mut reader, mut writer) = socket.into_split(); + let request_head = format!( + "POST /json HTTP/1.1\r\nHost: fixture\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let mut bytes = Vec::new(); + // Keep reading an early 413 even if the peer stops accepting the upload. + let (sent, reading) = timeout(Duration::from_secs(5), async { + tokio::join!( + async { + writer.write_all(request_head.as_bytes()).await?; + writer.write_all(body.as_bytes()).await + }, + reader.read_to_end(&mut bytes) + ) + }) + .await + .expect("bounded upload and response"); + let response = String::from_utf8(bytes).expect("UTF-8 response"); + let (head, payload) = response + .split_once("\r\n\r\n") + .expect("usable response head"); + assert!( + head.starts_with(&format!("HTTP/1.1 {status} ")), + "{response}" + ); + let length = head + .lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().expect("response length")) + }) + .expect("finite response framing"); + assert_eq!(payload.len(), length, "complete response: {response}"); + if let Err(error) = reading { + assert!( + status == 413 && error.kind() == ErrorKind::ConnectionReset, + "response read: {error}" + ); + } + if let Err(error) = sent { + assert_eq!(status, 413, "upload failure without 413: {error}"); + } + payload.to_owned() + } + + #[tokio::test(flavor = "multi_thread")] + async fn router_only_json_boundaries_for_both_constructors() { + use edgezero_core::action; + use edgezero_core::extractor::Json; + use edgezero_core::http::StatusCode; + #[action] + async fn count_json(Json(value): Json) -> String { + value.len().to_string() + } + for (with_config, configured_limit) in [ + (false, None), + (true, None), + (false, Some(64)), + (true, Some(64)), + ] { + let listener = TokioTcpListener::bind("127.0.0.1:0") + .await + .expect("listener"); + let addr = listener.local_addr().expect("address"); + let router = RouterService::builder().post("/json", count_json).build(); + let server = if with_config { + AxumDevServer::with_config( + App::new(router), + AxumDevServerConfig { + addr, + enable_ctrl_c: false, + ..AxumDevServerConfig::default() + }, + ) + } else { + AxumDevServer::new(App::new(router)) + }; + let configured_server = if let Some(limit) = configured_limit { + server.with_json_body_limit_bytes(limit).expect("JSON cap") + } else { + server + }; + let serving = + tokio::spawn( + async move { configured_server.serve(listener, future::pending()).await }, + ); + let limit = configured_limit.unwrap_or(2 * 1024 * 1024); + for (bytes, status) in [ + (limit, StatusCode::OK), + (limit.saturating_add(1), StatusCode::PAYLOAD_TOO_LARGE), + ] { + let body = format!( + "\"{}\"", + "x".repeat(bytes.checked_sub(2).expect("delimiters")) + ); + let text = router_json_upload(addr, body, status.as_u16()).await; + if status == StatusCode::OK { + assert_eq!(text, limit.checked_sub(2).expect("length").to_string()); + } else { + assert!(text.contains("payload_too_large")); + } + } + serving.abort(); + assert!(serving.await.expect_err("cancel server").is_cancelled()); + } + } + #[test] fn dev_server_with_config_uses_custom_config() { use edgezero_core::router::RouterService; @@ -2349,6 +2589,7 @@ mod bounded_ingress_tests { ) .expect("ingress"), super::Stores::default(), + super::JsonBodyLimit::DEFAULT, pending(), )); if disconnect { @@ -2570,6 +2811,7 @@ mod bounded_ingress_tests { false, AxumIngressConfig::new(2, 8192, 100, Duration::from_secs(10)).unwrap(), super::Stores::default(), + super::JsonBodyLimit::DEFAULT, pending(), )); let mut handler = TcpStream::connect(address).await.unwrap(); diff --git a/crates/edgezero-adapter-axum/src/request.rs b/crates/edgezero-adapter-axum/src/request.rs index efe66ac18..4ec8d7e98 100644 --- a/crates/edgezero-adapter-axum/src/request.rs +++ b/crates/edgezero-adapter-axum/src/request.rs @@ -1,3 +1,4 @@ +use std::iter::Peekable; use std::net::SocketAddr; use std::pin::Pin; @@ -7,7 +8,7 @@ use axum::http::{Request, request::Parts}; use edgezero_core::body::Body; use edgezero_core::error::EdgeError; use edgezero_core::http::Request as CoreRequest; -use edgezero_core::http::header::HOST; +use edgezero_core::http::header::{CONTENT_TYPE, HOST}; use edgezero_core::http::{HeaderMap, Uri}; use edgezero_core::ingress::{ CapturedTarget, HeaderFidelity, InboundOrigin, OriginSource, Preservation, RequestIngress, @@ -22,6 +23,7 @@ use tokio::time::{Instant as TokioInstant, timeout_at}; use crate::context::AxumRequestContext; use crate::outbound::AxumOutboundClient; use crate::outbound_executor::AxumOutboundExecutorHandle; +use crate::run_options::JsonBodyLimit; /// Marks the plain HTTP listener owned by this adapter. #[derive(Clone, Copy)] @@ -29,6 +31,8 @@ pub(crate) struct HttpTransport; /// Convert an Axum/Hyper request into an `EdgeZero` core request while preserving streaming bodies /// and exposing connection metadata through `AxumRequestContext`. +/// Attaches a finite 2 MiB JSON buffering policy without reading ambient configuration. +/// Taken streams and manual body collection do not enforce this policy. /// /// # Errors /// Returns an error if the outbound client cannot be initialized. @@ -53,6 +57,7 @@ pub async fn into_core_request( axum_body, None, HttpClient::with_client(client), + JsonBodyLimit::DEFAULT, )) } @@ -61,7 +66,9 @@ pub(crate) fn into_core_request_parts( axum_body: AxumBody, read_lifetime: Option<(Deadline, MonotonicClock)>, outbound_client: HttpClient, + json_body_limit: JsonBodyLimit, ) -> CoreRequest { + let ingress_is_json = has_json_content_type(&parts.headers); let transport = parts.extensions.remove::(); let ingress = capture_request_ingress(&parts.uri, &parts.headers, transport); // A zero size hint can still leave trailers; only the transport's terminal signal is enough. @@ -76,7 +83,8 @@ pub(crate) fn into_core_request_parts( } }; - let mut core_request = CoreRequest::from_parts(parts, body); + let managed_body = body.with_buffered_json_policy(json_body_limit.get(), ingress_is_json); + let mut core_request = CoreRequest::from_parts(parts, managed_body); core_request.extensions_mut().insert(ingress); if let Some(remote_addr) = core_request @@ -147,6 +155,87 @@ fn inbound_origin( Some(origin) } +fn has_json_content_type(headers: &HeaderMap) -> bool { + headers + .get(CONTENT_TYPE) + .is_some_and(|value| is_json_media_type(value.as_bytes())) +} + +fn is_json_media_type(raw: &[u8]) -> bool { + let separator = raw + .iter() + .position(|&byte| byte == b';') + .unwrap_or(raw.len()); + let (essence_bytes, parameters) = raw.split_at(separator); + let Ok(essence) = str::from_utf8(essence_bytes) else { + return false; + }; + let Ok(media) = essence.trim_matches([' ', '\t']).parse::() else { + return false; + }; + (media == mime::APPLICATION_JSON + || (media.type_() == mime::APPLICATION && media.suffix() == Some(mime::JSON))) + && valid_media_type_parameters(parameters) +} + +// RFC 9110 §§5.6.2–5.6.6. `mime` parses the type/subtype but its parameter +// parser does not follow HTTP's OWS, empty entries, or quoted-pair rules. +fn valid_media_type_parameters(parameters: &[u8]) -> bool { + let mut bytes = parameters.iter().copied().peekable(); + while let Some(separator) = bytes.by_ref().find(|&byte| !is_ows(byte)) { + if separator != b';' { + return false; + } + while bytes.next_if(|&byte| is_ows(byte)).is_some() {} + if matches!(bytes.peek(), None | Some(b';')) { + continue; + } + if !consume_token(&mut bytes) || bytes.next() != Some(b'=') { + return false; + } + let valid_value = if bytes.next_if_eq(&b'"').is_some() { + consume_quoted_parameter(&mut bytes) + } else { + consume_token(&mut bytes) + }; + if !valid_value { + return false; + } + } + true +} + +fn is_ows(byte: u8) -> bool { + matches!(byte, b' ' | b'\t') +} + +fn is_token_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte) +} + +fn consume_token(bytes: &mut Peekable>) -> bool { + if bytes.next_if(|&byte| is_token_byte(byte)).is_none() { + return false; + } + while bytes.next_if(|&byte| is_token_byte(byte)).is_some() {} + true +} + +fn consume_quoted_parameter(bytes: &mut impl Iterator) -> bool { + loop { + match bytes.next() { + Some(b'"') => return true, + Some(b'\\') => { + if !matches!(bytes.next(), Some(b'\t' | b' '..=b'~' | 0x80..=0xff)) { + return false; + } + } + Some(b'\t' | b' '..=b'~' | 0x80..=0xff) => {} + _ => return false, + } + } +} + fn deadline_body( body_stream: BodyDataStream, deadline: Deadline, @@ -210,7 +299,7 @@ mod tests { use super::*; use crate::outbound_executor::AxumOutboundExecutor; use bytes::Bytes; - use edgezero_core::http::{Method, StatusCode}; + use edgezero_core::http::{HeaderValue, Method, StatusCode}; use edgezero_core::time::MonotonicInstant; use std::io; use std::sync::Arc; @@ -354,7 +443,13 @@ mod tests { let lifetime = admitted.then(|| (Deadline::at_instant(now), MonotonicClock::new(move || now))); let (parts, native) = request.into_parts(); - let core = into_core_request_parts(parts, native, lifetime, client.clone()); + let core = into_core_request_parts( + parts, + native, + lifetime, + client.clone(), + JsonBodyLimit::DEFAULT, + ); assert_eq!(core.body().as_bytes(), Some(b"".as_slice())); assert_eq!(polls.load(Ordering::SeqCst), 0); assert_eq!(drops.load(Ordering::SeqCst), 1); @@ -488,7 +583,8 @@ mod tests { .expect("request"); let (parts, body) = request.into_parts(); - let core_request = into_core_request_parts(parts, body, None, client); + let core_request = + into_core_request_parts(parts, body, None, client, JsonBodyLimit::DEFAULT); assert!( !core_request .extensions() @@ -514,6 +610,56 @@ mod tests { assert!(AxumRequestContext::get(&core_request).is_none()); } + #[test] + fn ingress_json_classifier_validates_media_type_syntax() { + for raw in [ + "application/json", + "APPLICATION/JSON; charset=utf-8", + "application/problem+json", + "application/vnd.fixture+json; profile=\"a;b\"", + "\tapplication/json \t;\tcharset=utf-8 \t; profile=\"\" \t", + "application/json; ; charset=utf-8;", + "application/problem+JSON; profile=\"a;b\\\"c\\\\d\te\"; version=1", + ] { + assert!(is_json_media_type(raw.as_bytes()), "{raw:?}"); + } + assert!(is_json_media_type(b"application/json; profile=\"\xff\"")); + for raw in [ + "text/json", + "application/jsonp", + "application/json+xml", + "application/json+", + "application/json; broken", + "application/json; charset=", + "application/json; charset =utf-8", + "application/json; charset= utf-8", + "application/json; profile=\"unterminated", + "application/json; profile=\"trailing escape\\\"", + "application/json; profile=\"value\"extra", + "application/json, text/plain", + "application /json", + "application/json extra", + "application/", + "", + ] { + assert!(!is_json_media_type(raw.as_bytes()), "{raw:?}"); + } + } + + #[test] + fn ingress_json_classifier_uses_only_the_first_content_type() { + for (first, second, json) in [ + ("application/json", "text/plain", true), + ("text/plain", "application/json", false), + ("application/json; broken", "application/json", false), + ] { + let mut headers = HeaderMap::new(); + headers.append(CONTENT_TYPE, HeaderValue::from_static(first)); + headers.append(CONTENT_TYPE, HeaderValue::from_static(second)); + assert_eq!(has_json_content_type(&headers), json); + } + } + #[tokio::test] async fn json_content_type_stays_streaming() { let executor_owner = AxumOutboundExecutor::new(); diff --git a/crates/edgezero-adapter-axum/src/run_options.rs b/crates/edgezero-adapter-axum/src/run_options.rs index fcde4558a..a612989e1 100644 --- a/crates/edgezero-adapter-axum/src/run_options.rs +++ b/crates/edgezero-adapter-axum/src/run_options.rs @@ -1,6 +1,7 @@ use std::env::vars_os; use std::ffi::OsString; use std::net::SocketAddr; +use std::num::NonZeroUsize; use std::path::{Path, PathBuf}; use std::str::FromStr as _; use std::time::{Duration, Instant}; @@ -12,6 +13,45 @@ use log::LevelFilter; const DEFAULT_SHUTDOWN_GRACE: Duration = Duration::from_secs(10); +/// Validated native JSON buffering ceiling. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct JsonBodyLimit(NonZeroUsize); + +impl JsonBodyLimit { + const CONFIG_PATH: [&str; 2] = ["adapter", "json_body_limit_bytes"]; + pub(crate) const DEFAULT: Self = + Self(NonZeroUsize::new(2 * 1024 * 1024).expect("positive default")); + const SETTING: &str = "JSON_BODY_LIMIT_BYTES"; + + pub(crate) fn from_config(env: &EnvConfig) -> anyhow::Result { + let Some(raw) = env.get(&Self::CONFIG_PATH) else { + return Ok(Self::DEFAULT); + }; + if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(Self::invalid()); + } + Self::new(raw.parse::().map_err(|_error| Self::invalid())?) + } + + pub(crate) fn get(self) -> NonZeroUsize { + self.0 + } + + fn invalid() -> anyhow::Error { + failure( + "settings", + Self::SETTING, + "invalid positive representable integer bytes", + ) + } + pub(crate) fn new(limit: usize) -> anyhow::Result { + NonZeroUsize::new(limit) + .filter(|value| value.get() <= isize::MAX.unsigned_abs()) + .map(Self) + .ok_or_else(Self::invalid) + } +} + /// Validated explicit production hosting options. Construction never selects a /// policy from build profile, cwd or container detection. Explicit constructors /// do not merge environment values; only `from_env` reads hosting environment. @@ -22,6 +62,7 @@ pub struct AxumRunOptions { data_dir: Option, env: EnvConfig, grace: Duration, + json_body_limit: JsonBodyLimit, level: LevelFilter, non_unicode_overrides: Vec>, } @@ -112,6 +153,7 @@ impl AxumRunOptions { .map_err(|_error| failure("settings", "LOGGING__LEVEL", "invalid level"))?; } options.grace = shutdown_grace(&env)?; + options.json_body_limit = JsonBodyLimit::from_config(&env)?; if let Some(root) = env.get(&["adapter", "config_dir"]) { options = options.with_config_dir(root)?; } @@ -122,6 +164,10 @@ impl AxumRunOptions { Ok(options) } + pub(crate) fn json_body_limit(&self) -> JsonBodyLimit { + self.json_body_limit + } + pub(crate) fn logging_level(&self) -> LevelFilter { self.level } @@ -141,6 +187,7 @@ impl AxumRunOptions { data_dir: None, env: EnvConfig::default(), grace: DEFAULT_SHUTDOWN_GRACE, + json_body_limit: JsonBodyLimit::DEFAULT, level: LevelFilter::Info, non_unicode_overrides: Vec::new(), }) @@ -228,6 +275,16 @@ impl AxumRunOptions { Ok(self) } + /// Selects the ceiling for framework-managed JSON buffering, in bytes. + /// + /// # Errors + /// Rejects zero and values above the collector's representable capacity. + #[inline] + pub fn with_json_body_limit_bytes(mut self, limit: usize) -> anyhow::Result { + self.json_body_limit = JsonBodyLimit::new(limit)?; + Ok(self) + } + /// Sets the level for framework-managed standalone logging. Embedding does /// not install a logger or change the host's log filter. #[inline] @@ -297,6 +354,7 @@ pub(crate) fn native_limit_setting(path: &[String]) -> Option<&'static str> { "max_file_bytes" | "max_entries" | "max_key_bytes" | "max_value_bytes" | "max_resident_bytes" | "max_startup_bytes", ] => Some("CONFIG_STORE"), + _ if segments.as_slice() == JsonBodyLimit::CONFIG_PATH => Some(JsonBodyLimit::SETTING), _ => None, } } @@ -348,6 +406,53 @@ mod tests { use super::*; use edgezero_core::app::StoreMetadata; + #[test] + fn json_body_limit_is_positive_decimal_and_representable() { + let key = "EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES"; + let defaults = AxumRunOptions::from_vars(Vec::<(String, String)>::new()).expect("defaults"); + assert_eq!(defaults.json_body_limit.get().get(), 2 * 1024 * 1024); + for bytes in [ + 1, + 64, + 9 * 1024 * 1024, + usize::try_from(isize::MAX).expect("maximum"), + ] { + let options = AxumRunOptions::from_vars([(key, bytes.to_string())]).expect("valid"); + assert_eq!(options.json_body_limit.get().get(), bytes); + assert_eq!( + defaults + .clone() + .with_json_body_limit_bytes(bytes) + .expect("builder") + .json_body_limit + .get() + .get(), + bytes + ); + } + for raw in [ + "", + "0", + "-1", + "+1", + " 64", + "64 ", + "1.5", + "2MiB", + "sentinel-limit", + "9999999999999999999999999999999999", + ] { + let error = AxumRunOptions::from_vars([(key, raw)]) + .err() + .expect("invalid"); + assert!(error.to_string().contains("JSON_BODY_LIMIT_BYTES")); + assert!(!format!("{error:?}").contains("sentinel")); + assert_eq!(error.chain().count(), 1); + } + assert!(defaults.clone().with_json_body_limit_bytes(0).is_err()); + assert!(defaults.with_json_body_limit_bytes(usize::MAX).is_err()); + } + #[test] fn defaults_and_invalid_supplied_scalars_are_distinct() { let options = AxumRunOptions::from_vars(Vec::<(String, String)>::new()).expect("defaults"); diff --git a/crates/edgezero-adapter-axum/src/service.rs b/crates/edgezero-adapter-axum/src/service.rs index 3491375f6..5ea9c8362 100644 --- a/crates/edgezero-adapter-axum/src/service.rs +++ b/crates/edgezero-adapter-axum/src/service.rs @@ -36,6 +36,7 @@ use crate::outbound::{AxumOutboundClient, native_time}; use crate::outbound_executor::AxumOutboundExecutorHandle; use crate::request::{HttpTransport, into_core_request_parts}; use crate::response::{AxumEgressBody, EgressConnection, prepare_egress_response}; +use crate::run_options::JsonBodyLimit; /// Private Hyper service error used only to close/reset an admission-aborted connection. #[derive(Debug, thiserror::Error)] @@ -48,6 +49,7 @@ pub(crate) struct AxumServiceState { app: Arc, config_registry: Option, executor: AxumOutboundExecutorHandle, + json_body_limit: JsonBodyLimit, kv_registry: Option, lifecycle: Option, outbound_client: Option, @@ -70,7 +72,7 @@ impl AxumServiceState { #[inline] #[cfg(test)] pub fn from_app(app: App, executor: AxumOutboundExecutorHandle) -> Self { - Self::from_app_with_client_factory(app, executor.clone(), |clock| { + Self::from_app_with_client_factory(app, executor.clone(), JsonBodyLimit::DEFAULT, |clock| { AxumOutboundClient::try_with_time(executor, native_time(clock)) .ok() .map(HttpClient::with_client) @@ -80,6 +82,7 @@ impl AxumServiceState { fn from_app_with_client_factory( app: App, executor: AxumOutboundExecutorHandle, + json_body_limit: JsonBodyLimit, initialize: impl FnOnce(MonotonicClock) -> Option, ) -> Self { let outbound_client = app @@ -90,6 +93,7 @@ impl AxumServiceState { app: Arc::new(app), executor, config_registry: None, + json_body_limit, kv_registry: None, lifecycle: None, outbound_client, @@ -101,8 +105,9 @@ impl AxumServiceState { app: App, transport: Arc, executor: AxumOutboundExecutorHandle, + json_body_limit: JsonBodyLimit, ) -> Self { - Self::from_app_with_client_factory(app, executor.clone(), |clock| { + Self::from_app_with_client_factory(app, executor.clone(), json_body_limit, |clock| { Some(HttpClient::with_client( AxumOutboundClient::with_transport_and_time( transport, @@ -262,6 +267,7 @@ impl AxumServiceState { native_body, Some((read_deadline, monotonic_clock)), outbound_client, + self.json_body_limit, ); if let Some(lifecycle) = &self.lifecycle { @@ -357,6 +363,7 @@ mod tests { use crate::outbound_executor::AxumOutboundExecutor; use async_stream::stream; use bytes::{Bytes, BytesMut}; + use edgezero_core::action; use edgezero_core::body::Body; use edgezero_core::config_store::{ BoundedStoreRead, ConfigStore, ConfigStoreError, ConfigStoreHandle, @@ -364,6 +371,7 @@ mod tests { }; use edgezero_core::context::RequestContext; use edgezero_core::error::EdgeError; + use edgezero_core::extractor::Json; use edgezero_core::http::{ HeaderMap, HeaderValue, Response as CoreResponse, StatusCode, response_builder, }; @@ -879,6 +887,151 @@ mod tests { } } + #[action] + async fn json_limit_probe(Json(value): Json) -> Result { + Ok(value.len().to_string()) + } + + fn managed_json_app(reports: &Arc>>) -> App { + let router = RouterService::builder() + .post("/json", json_limit_probe) + .build(); + let mut app = App::new(router); + app.set_response_egress_observer(RecordingEgressObserver(Arc::clone(reports))); + app + } + + fn managed_json_request(body: AxumBody) -> Request { + Request::builder() + .method("POST") + .uri("/json") + .header("content-type", "application/json") + .body(body) + .expect("request") + } + + #[tokio::test] + async fn managed_json_overflow_drops_source_once_stops_polling_and_keeps_error_egress() { + let executor_owner = AxumOutboundExecutor::new(); + let executor_handle = executor_owner.handle(); + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&polls); + let guard = DropSignal(Arc::clone(&drops)); + let source = poll_fn(move |_| { + let _retained = &guard; + let index = observed.fetch_add(1, Ordering::SeqCst); + let chunk = match index { + 0 => Bytes::from_static(b"\"ab"), + 1 => Bytes::from_static(b"cdef\""), + _ => panic!("source polled after oversized chunk"), + }; + Poll::Ready(Some(Ok::<_, io::Error>(chunk))) + }); + let reports = Arc::new(Mutex::new(Vec::new())); + let mut app = managed_json_app(&reports); + app.set_error_response_renderer(|error| { + assert_eq!(error.kind(), "payload_too_large"); + CoreResponse::new(Body::from("custom renderer")) + }); + let mut service = AxumServiceState::from_app(app, executor_handle.clone()); + service.json_body_limit = JsonBodyLimit::new(4).expect("cap"); + let request = managed_json_request(AxumBody::from_stream(source)); + let response = service + .dispatch_request(request, &EgressConnection::default(), None) + .await + .expect("dispatch"); + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert_eq!( + to_bytes(response.into_body(), 1024).await.expect("egress"), + "custom renderer" + ); + let observed_reports = reports.lock().expect("reports"); + assert_eq!(observed_reports.len(), 1); + assert_eq!( + observed_reports[0].outcome, + ResponseEgressOutcome::HostHandoff + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn managed_json_source_error_releases_partial_body_and_keeps_error_egress() { + let executor_owner = AxumOutboundExecutor::new(); + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&polls); + let guard = DropSignal(Arc::clone(&drops)); + let source = poll_fn(move |_| { + let _retained = &guard; + let result = match observed.fetch_add(1, Ordering::SeqCst) { + 0 => Ok(Bytes::from_static(b"\"ab")), + 1 => Err(io::Error::other("test source failure")), + _ => panic!("source polled after its error"), + }; + Poll::Ready(Some(result)) + }); + let reports = Arc::new(Mutex::new(Vec::new())); + let service = + AxumServiceState::from_app(managed_json_app(&reports), executor_owner.handle()); + let response = service + .oneshot(managed_json_request(AxumBody::from_stream(source))) + .await + .expect("dispatch"); + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + let payload = to_bytes(response.into_body(), 1024).await.expect("egress"); + let error: serde_json::Value = serde_json::from_slice(&payload).expect("JSON error"); + assert_eq!( + error + .pointer("/error/kind") + .and_then(serde_json::Value::as_str), + Some("internal") + ); + let observed_reports = reports.lock().expect("reports"); + assert_eq!(observed_reports.len(), 1); + assert_eq!( + observed_reports[0].outcome, + ResponseEgressOutcome::HostHandoff + ); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn managed_json_cancelled_partial_read_releases_source_without_egress() { + let executor_owner = AxumOutboundExecutor::new(); + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&polls); + let guard = DropSignal(Arc::clone(&drops)); + let source = poll_fn(move |_| { + let _retained = &guard; + match observed.fetch_add(1, Ordering::SeqCst) { + 0 => Poll::Ready(Some(Ok::<_, io::Error>(Bytes::from_static(b"\"ab")))), + 1 => Poll::Pending, + _ => panic!("source polled past the pending read"), + } + }); + let reports = Arc::new(Mutex::new(Vec::new())); + let service = + AxumServiceState::from_app(managed_json_app(&reports), executor_owner.handle()); + let mut dispatch = + Box::pin(service.oneshot(managed_json_request(AxumBody::from_stream(source)))); + assert!(futures_util::poll!(&mut dispatch).is_pending()); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(drops.load(Ordering::SeqCst), 0); + + drop(dispatch); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert!(reports.lock().expect("reports").is_empty()); + } + struct FixedConfigStore(String); #[test] @@ -890,9 +1043,12 @@ mod tests { ) .with_proxy_marker(false); let app = App::new(RouterService::builder().with_state(supplied).build()); - let service = AxumServiceState::from_app_with_client_factory(app, executor_handle, |_| { - panic!("supplied client must avoid transport initialization") - }); + let service = AxumServiceState::from_app_with_client_factory( + app, + executor_handle, + JsonBodyLimit::DEFAULT, + |_| panic!("supplied client must avoid transport initialization"), + ); assert!( !service .outbound_client diff --git a/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs b/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs index ee12956ff..f3964d509 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs @@ -20,8 +20,9 @@ use edgezero_adapter_axum::dev_server::{ }; use edgezero_core::app::{App, Hooks, StoreMetadata, StoresMetadata}; use edgezero_core::context::RequestContext; -use edgezero_core::extractor::{AppConfig, State}; +use edgezero_core::extractor::{AppConfig, Json, State}; use edgezero_core::key_value_store::KvHandle; +use edgezero_core::params::PathParams; use edgezero_core::probe::{self, LifecyclePhase, LifecycleReader}; use edgezero_core::router::RouterService; use edgezero_core::{Body, EdgeError, MonotonicClock, MonotonicInstant, action}; @@ -41,6 +42,7 @@ struct FixtureApp; )] impl Hooks for FixtureApp { fn configure(app: &mut App) -> Result<(), EdgeError> { + println!("HOOK_ENTERED"); log::info!("fixture configured"); if mode() == "hook-error" { return Err(EdgeError::internal(anyhow::anyhow!("HOOK_SENTINEL"))); @@ -61,6 +63,11 @@ impl Hooks for FixtureApp { fn routes() -> Result { Ok(RouterService::builder() + .post("/json", buffered_json) + .post("/json-explicit", explicit_json) + .post("/json-small", small_json) + .post("/generic", generic_body) + .post("/taken", taken_body) .get("/ready", probe::readiness) .get("/live", probe::liveness) .get("/fixture-ready", |ctx: RequestContext| async move { @@ -124,6 +131,53 @@ impl Hooks for FixtureApp { } } +#[action] +async fn buffered_json(Json(value): Json) -> Result { + println!("JSON_HANDLER_ENTERED"); + Ok(value.len().to_string()) +} + +#[action] +async fn explicit_json(ctx: RequestContext) -> Result { + let value: String = ctx.json_within(16 * 1024 * 1024).await?; + Ok(value.len().to_string()) +} + +#[action] +async fn small_json(ctx: RequestContext) -> Result { + let value: String = ctx.json_within(32).await?; + Ok(value.len().to_string()) +} + +#[action] +async fn generic_body(mut ctx: RequestContext) -> Result { + ctx.headers_mut().clear(); + ctx.extensions_mut().clear(); + let request = ctx.into_request()?; + let reconstructed = RequestContext::new(request, PathParams::default()); + Ok(reconstructed + .body_bytes(16 * 1024 * 1024) + .await? + .len() + .to_string()) +} + +#[action] +async fn taken_body(ctx: RequestContext) -> Result { + use futures::StreamExt as _; + let mut source = ctx + .take_body()? + .into_stream() + .map_err(|_body| EdgeError::bad_request("expected stream"))?; + let mut bytes = 0_usize; + while let Some(chunk) = source.next().await { + bytes = bytes + .checked_add(chunk?.len()) + .ok_or_else(|| EdgeError::bad_request("fixture accounting overflow"))?; + } + Ok(bytes.to_string()) +} + struct WorkGuard(&'static str); #[expect( @@ -348,6 +402,9 @@ fn repeated_embedding_logging(addr: SocketAddr) -> anyhow::Result<()> { fn embedded_server(selected: &str) -> anyhow::Result<()> { let address: SocketAddr = env::var("FIXTURE_BIND")?.parse()?; let mut options = AxumRunOptions::new(address)?; + if let Ok(raw) = env::var("FIXTURE_JSON_LIMIT") { + options = options.with_json_body_limit_bytes(raw.parse()?)?; + } if selected == "embedding" { options = options .with_config_dir(env::var("FIXTURE_CONFIG_ROOT")?)? diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 324fef3ed..d8a96f560 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -7,7 +7,7 @@ reason = "subprocess fixtures group setup, process ownership and acceptance scenarios" )] mod tests { - use std::ffi::OsStr; + use std::ffi::{OsStr, OsString}; use std::fs; use std::io::{self, BufRead as _, BufReader, Read, Write as _}; use std::net::{SocketAddr, TcpStream}; @@ -397,6 +397,226 @@ mod tests { log } + fn exact_json(bytes: usize) -> Vec { + assert!(bytes >= 2); + let mut body = vec![b'x'; bytes]; + body[0] = b'"'; + *body.last_mut().expect("JSON closing quote") = b'"'; + body + } + + fn upload( + server: &Server, + path: &str, + media: Option<&str>, + body: Vec, + chunked: bool, + ) -> String { + let mut socket = server.socket().expect("upload connection"); + let mut writer = socket.try_clone().expect("upload writer"); + let content_type = + media.map_or_else(String::new, |value| format!("Content-Type: {value}\r\n")); + let framing = if chunked { + "Transfer-Encoding: chunked\r\n".to_owned() + } else { + format!("Content-Length: {}\r\n", body.len()) + }; + let request_head = format!( + "POST {path} HTTP/1.1\r\nHost: fixture\r\n{content_type}{framing}Connection: close\r\n\r\n" + ); + let sending = thread::spawn(move || -> io::Result<()> { + writer.write_all(request_head.as_bytes())?; + for chunk in body.chunks(16 * 1024) { + if chunked { + write!(writer, "{:x}\r\n", chunk.len())?; + } + writer.write_all(chunk)?; + if chunked { + writer.write_all(b"\r\n")?; + } + } + if chunked { + writer.write_all(b"0\r\n\r\n")?; + } + Ok(()) + }); + let mut response = String::new(); + let reading = socket.read_to_string(&mut response); + let sent = sending.join().expect("bounded upload writer"); + let (head, payload) = response + .split_once("\r\n\r\n") + .expect("usable response head"); + let is_413 = head.starts_with("HTTP/1.1 413"); + let length = head + .lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().expect("response length")) + }) + .expect("finite response framing"); + assert_eq!(payload.len(), length, "complete response: {response}"); + if let Err(error) = reading { + assert!( + is_413 && error.kind() == io::ErrorKind::ConnectionReset, + "response read: {error}" + ); + } + if let Err(error) = sent { + assert!(is_413, "upload failure without 413: {error}"); + } + response + } + + fn assert_upload_status(response: &str, status: u16) { + assert!( + response.starts_with(&format!("HTTP/1.1 {status}")), + "{response}" + ); + if status == 413 { + let (_, body) = response.split_once("\r\n\r\n").expect("response"); + let value: Value = serde_json::from_str(body).expect("usable error body"); + assert_eq!(value["error"]["kind"], "payload_too_large"); + assert_eq!(value["error"]["message"], "request body too large"); + } + } + + #[test] + fn json_body_limit_wire_content_length_and_chunked() { + const DEFAULT_LIMIT: usize = 2 * 1024 * 1024; + + let roots = Roots::new(); + let addr = address(); + let mut server = Server::spawn(command("bare", &roots, addr), addr); + server.ready(); + server.wait_line("HOOK_ENTERED"); + for chunked in [false, true] { + assert_upload_status( + &upload( + &server, + "/json", + Some("application/json"), + exact_json(DEFAULT_LIMIT), + chunked, + ), + 200, + ); + server.wait_line("JSON_HANDLER_ENTERED"); + assert_upload_status( + &upload( + &server, + "/json", + Some("application/json"), + exact_json(DEFAULT_LIMIT + 1), + chunked, + ), + 413, + ); + } + server.signal("TERM"); + assert!(server.wait().success()); + assert_eq!(server.log().matches("JSON_HANDLER_ENTERED").count(), 2); + } + + #[test] + fn json_limit_overrides_helpers_generic_reads_and_taken_streams() { + for mode in ["bare", "bare-dev", "embedding-bare"] { + let roots = Roots::new(); + let addr = address(); + let mut launch = command(mode, &roots, addr); + launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", "64"); + if mode == "embedding-bare" { + launch.env("FIXTURE_JSON_LIMIT", "64").env( + "EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", + "INVALID_SENTINEL", + ); + } + let mut server = Server::spawn(launch, addr); + server.ready(); + for media in [ + None, + Some("text/plain"), + Some("APPLICATION/JSON; charset=utf-8"), + Some("application/vnd.fixture+json"), + ] { + assert_upload_status(&upload(&server, "/json", media, exact_json(64), false), 200); + assert_upload_status(&upload(&server, "/json", media, exact_json(65), true), 413); + } + assert_upload_status( + &upload(&server, "/json-explicit", None, exact_json(65), false), + 413, + ); + assert_upload_status( + &upload(&server, "/json-small", None, exact_json(32), false), + 200, + ); + assert_upload_status( + &upload(&server, "/json-small", None, exact_json(33), false), + 413, + ); + assert_upload_status( + &upload(&server, "/json", None, b"invalid json".to_vec(), false), + 400, + ); + for media in [ + "application/json", + "Application/Problem+JSON \t;\tcharset=utf-8; profile=\"\"", + ] { + assert_upload_status( + &upload(&server, "/generic", Some(media), exact_json(64), false), + 200, + ); + assert_upload_status( + &upload(&server, "/generic", Some(media), exact_json(65), true), + 413, + ); + } + for media in ["text/plain", "application/json+xml"] { + assert_upload_status( + &upload(&server, "/generic", Some(media), exact_json(65), false), + 200, + ); + } + for media in ["application/json", "application/octet-stream"] { + assert_upload_status( + &upload(&server, "/taken", Some(media), exact_json(4096), true), + 200, + ); + } + } + let roots = Roots::new(); + let addr = address(); + let cap = 9 * 1024 * 1024; + let mut launch = command("bare", &roots, addr); + launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", cap.to_string()); + let mut server = Server::spawn(launch, addr); + server.ready(); + assert_upload_status(&upload(&server, "/json", None, exact_json(cap), true), 200); + assert_upload_status( + &upload(&server, "/json", None, exact_json(cap + 1), false), + 413, + ); + } + + #[test] + fn invalid_json_limits_fail_before_application_hooks_in_dev_and_production() { + use std::os::unix::ffi::OsStringExt as _; + for mode in ["bare", "bare-dev"] { + for value in [ + OsString::from("0"), + OsString::from("INVALID_SENTINEL"), + OsString::from_vec(vec![0xff]), + ] { + let roots = Roots::new(); + let (addr, _addr_held) = reserved_address(); + let mut launch = command(mode, &roots, addr); + launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", value); + let log = failed(launch, addr, "JSON_BODY_LIMIT_BYTES"); + assert!(!log.contains("HOOK_ENTERED")); + } + } + } + #[test] fn both_signals_stop_idle_processes() { for signal in ["INT", "TERM"] { diff --git a/crates/edgezero-core/src/body.rs b/crates/edgezero-core/src/body.rs index d3d94c435..78c1107cc 100644 --- a/crates/edgezero-core/src/body.rs +++ b/crates/edgezero-core/src/body.rs @@ -1,6 +1,7 @@ use std::fmt; use std::io; use std::mem; +use std::num::NonZeroUsize; use std::pin::Pin; use std::task::{Context, Poll}; @@ -24,9 +25,37 @@ pub enum BodyPayload { pub struct Body { egress_owner: Option>, forwarded_content_length: Option, + ingress_buffer: Option, payload: BodyPayload, } +#[derive(Clone, Copy, Debug)] +pub(crate) struct BufferedJsonPolicy { + ceiling: NonZeroUsize, + ingress_is_json: bool, +} + +impl BufferedJsonPolicy { + pub(crate) fn ceiling(self) -> NonZeroUsize { + self.ceiling + } + + pub(crate) fn ingress_is_json(self) -> bool { + self.ingress_is_json + } +} + +#[derive(Debug)] +enum IngressBuffer { + Cached(BufferedJsonPolicy), + Initial(BufferedJsonPolicy), +} + +pub(crate) enum BodyTransfer { + Cached(Bytes), + Initial(Body), +} + struct ManualBodyStream { owner: Option, source: Option, @@ -130,6 +159,7 @@ impl Body { Self { egress_owner: egress_owner.map(Box::new), forwarded_content_length: None, + ingress_buffer: None, payload, } } @@ -142,6 +172,24 @@ impl Body { Self::from_parts(BodyPayload::Stream(stream.boxed_local()), None) } + pub(crate) fn from_transfer( + policy: Option, + transfer: BodyTransfer, + ) -> Self { + let (mut body, cached) = match transfer { + BodyTransfer::Initial(body) => (body, false), + BodyTransfer::Cached(bytes) => (Self::from_bytes(bytes), true), + }; + body.ingress_buffer = policy.map(|selected| { + if cached { + IngressBuffer::Cached(selected) + } else { + IngressBuffer::Initial(selected) + } + }); + body + } + pub(crate) fn has_egress_owner(&self) -> bool { self.egress_owner.is_some() } @@ -206,6 +254,8 @@ impl Body { /// Separates payload and its exact optional egress owner without copying bytes. /// The caller must retain the owner through terminal response egress. + /// This application-owned/transport boundary discards ingress buffering policy and provenance; + /// context reconstruction uses the private body-preserving transfer instead. #[must_use] #[inline] pub fn into_parts(mut self) -> (BodyPayload, Option) { @@ -217,13 +267,33 @@ impl Body { /// stream EOF, error, or drop; canonical egress extracts that owner before conversion. /// /// # Errors - /// Returns the original buffered body, including its owner, rather than discarding it. + /// Returns the original buffered body with its policy, cache provenance, and owner intact. #[inline] - pub fn into_stream(self) -> Result { - let (payload, owner) = self.into_parts(); + pub fn into_stream(mut self) -> Result { + let payload = mem::replace(&mut self.payload, BodyPayload::Once(Bytes::new())); match payload { - BodyPayload::Once(bytes) => Err(Self::from_parts(BodyPayload::Once(bytes), owner)), - BodyPayload::Stream(source) => Ok(manual_stream(source, owner)), + BodyPayload::Once(bytes) => { + self.payload = BodyPayload::Once(bytes); + Err(self) + } + BodyPayload::Stream(source) => Ok(manual_stream(source, self.take_egress_owner())), + } + } + + pub(crate) fn into_transfer(mut self) -> (Option, BodyTransfer) { + match self.ingress_buffer.take() { + Some(IngressBuffer::Cached(policy)) => { + let (payload, owner) = self.into_parts(); + match (payload, owner) { + (BodyPayload::Once(bytes), None) => (Some(policy), BodyTransfer::Cached(bytes)), + (retained_payload, retained_owner) => ( + Some(policy), + BodyTransfer::Initial(Self::from_parts(retained_payload, retained_owner)), + ), + } + } + Some(IngressBuffer::Initial(policy)) => (Some(policy), BodyTransfer::Initial(self)), + None => (None, BodyTransfer::Initial(self)), } } @@ -281,6 +351,28 @@ impl Body { ))), } } + + /// Attaches the ingress JSON buffering policy without polling or copying. + /// + /// The adapter must pass an already-validated ceiling and the JSON classification + /// of the original ingress headers. Reattaching leaves the first policy and body + /// provenance intact. + #[doc(hidden)] + #[must_use] + #[inline] + pub fn with_buffered_json_policy( + mut self, + ceiling: NonZeroUsize, + ingress_is_json: bool, + ) -> Self { + if self.ingress_buffer.is_none() { + self.ingress_buffer = Some(IngressBuffer::Initial(BufferedJsonPolicy { + ceiling, + ingress_is_json, + })); + } + self + } } impl ManualBodyStream { @@ -390,6 +482,7 @@ impl fmt::Debug for Body { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Body") + .field("ingress_buffer", &self.ingress_buffer) .field("payload", &self.payload) .field("egress_owner", &self.egress_owner.is_some()) .field("forwarded_content_length", &self.forwarded_content_length) @@ -656,6 +749,41 @@ mod tests { assert!(scope.check().is_err()); } + #[test] + fn ingress_policy_transfers_keep_the_exact_egress_owner_until_raw_handoff() { + for cached in [false, true] { + let original = Body::from("payload") + .with_buffered_json_policy(NonZeroUsize::new(4).expect("positive cap"), true); + let (policy, initial) = original.into_transfer(); + let transfer = if cached { + BodyTransfer::Cached(Bytes::from_static(b"payload")) + } else { + initial + }; + let owner = OutboundScopeOwner::response_body(); + let scope = owner.scope(); + let body = Body::from_transfer(policy, transfer) + .attach_egress_owner(owner) + .expect("attach exact owner"); + let (retained_policy, retained) = body.into_transfer(); + assert_eq!(retained_policy.expect("retained policy").ceiling().get(), 4); + scope + .check() + .expect("internal transfer keeps exact owner live"); + let reconstructed = Body::from_transfer(retained_policy, retained); + let (payload, exact_owner) = reconstructed.into_parts(); + scope.check().expect("raw split retains owner"); + let raw = Body::from_parts(payload, exact_owner); + let (removed_policy, raw_transfer) = raw.into_transfer(); + assert!(removed_policy.is_none()); + scope + .check() + .expect("raw handoff still owns the same scope"); + drop(raw_transfer); + assert!(scope.check().is_err()); + } + } + #[test] fn manual_stream_conversion_retains_owner_until_consumption() { let owner = OutboundScopeOwner::response_body(); @@ -774,14 +902,14 @@ mod tests { let buffered_debug = format!("{buffered:?}"); assert_eq!( buffered_debug, - "Body { payload: Once { len: 7 }, egress_owner: false, forwarded_content_length: None }" + "Body { ingress_buffer: None, payload: Once { len: 7 }, egress_owner: false, forwarded_content_length: None }" ); let stream = Body::stream(stream::iter(vec![Bytes::from_static(b"chunk")])); let stream_debug = format!("{stream:?}"); assert_eq!( stream_debug, - "Body { payload: Stream, egress_owner: false, forwarded_content_length: None }" + "Body { ingress_buffer: None, payload: Stream, egress_owner: false, forwarded_content_length: None }" ); } @@ -985,6 +1113,41 @@ mod tests { assert_eq!(returned_body.as_bytes(), Some(b"payload".as_slice())); } + #[test] + fn into_stream_returns_original_managed_buffered_body() { + for cached in [false, true] { + let bytes = Bytes::from_static(b"payload"); + let original = Body::from(bytes.clone()) + .with_buffered_json_policy(NonZeroUsize::new(7).expect("positive cap"), true); + let (policy, initial) = original.into_transfer(); + let transfer = if cached { + BodyTransfer::Cached(bytes.clone()) + } else { + initial + }; + let owner = OutboundScopeOwner::response_body(); + let scope = owner.scope(); + let body = Body::from_transfer(policy, transfer) + .attach_egress_owner(owner) + .expect("attach owner"); + let returned = body.into_stream().err().expect("original body"); + let ((false, Some(IngressBuffer::Initial(retained))) + | (true, Some(IngressBuffer::Cached(retained)))) = (cached, &returned.ingress_buffer) + else { + panic!("original policy and provenance"); + }; + assert_eq!(retained.ceiling().get(), 7); + assert!(retained.ingress_is_json()); + assert_eq!( + returned.as_bytes().expect("buffered").as_ptr(), + bytes.as_ptr() + ); + scope.check().expect("original owner stays live"); + drop(returned); + assert!(scope.check().is_err()); + } + } + #[test] fn is_stream_returns_false_for_buffered_body() { let body = Body::from("payload"); diff --git a/crates/edgezero-core/src/context.rs b/crates/edgezero-core/src/context.rs index dce1c1bd2..8b7ab4538 100644 --- a/crates/edgezero-core/src/context.rs +++ b/crates/edgezero-core/src/context.rs @@ -6,7 +6,7 @@ use std::{ task::Poll, }; -use crate::body::{Body, BodyStream}; +use crate::body::{Body, BodyStream, BodyTransfer, BufferedJsonPolicy}; use crate::config_store::ConfigExtractionLimits; use crate::error::{ BadGatewayReason, BudgetSource, EdgeError, RequestBodyOverflowOrigin, ResponseLimitReason, @@ -29,7 +29,7 @@ use crate::time::{Deadline, MonotonicClock, MonotonicInstant}; use futures_util::{StreamExt as _, stream}; use serde::de::DeserializeOwned; -/// Default maximum body size accepted by JSON extractors (8 MiB). +/// Default maximum body size for ordinary JSON extractors without an adapter ceiling (8 MiB). pub const DEFAULT_INBOUND_JSON_BYTES: usize = 8 * 1024 * 1024; /// Default maximum body size accepted by form extractors (1 MiB). pub const DEFAULT_INBOUND_FORM_BYTES: usize = 1024 * 1024; @@ -74,6 +74,15 @@ enum BodyState { Taken, } +impl BodyState { + fn from_transfer(transfer: BodyTransfer) -> Self { + match transfer { + BodyTransfer::Cached(bytes) => Self::Cached(bytes), + BodyTransfer::Initial(body) => Self::Initial(body), + } + } +} + #[derive(Clone, Copy)] pub(crate) enum FallbackDrainOutcome { Complete, @@ -289,6 +298,7 @@ impl StoredError { /// Request context exposed to handlers and middleware. pub struct RequestContext { body: RefCell, + body_policy: Option, config_extraction_limits: ConfigExtractionLimits, ingress_grant: RefCell>, input_guard: Option>, @@ -326,28 +336,49 @@ impl Drop for DrainGuard<'_> { } impl RequestContext { - /// Drains and caches the inbound body under the caller's byte cap. + /// Drains and caches the inbound body under the caller's byte cap. If the adapter + /// classified the original ingress as JSON, its buffering ceiling can lower `max`. /// /// # Errors - /// Returns 413 on overflow, 408 on an admitted read deadline, and preserves a sticky - /// source error for every later accessor. + /// Returns 413 on overflow or 408 on an admitted read deadline. Drain failures + /// remain sticky. A tighter caller cap on an intact cache does not poison it. #[inline] pub async fn body_bytes(&self, max: usize) -> Result { + self.buffered_bytes(max, false).await + } + + #[must_use] + #[inline] + pub fn body_kind(&self) -> BodyKind { + match &*self.body.borrow() { + BodyState::Cached(bytes) => BodyKind::Cached { len: bytes.len() }, + BodyState::Draining => BodyKind::Draining, + BodyState::Initial(_) => BodyKind::Initial, + BodyState::Poisoned(_) => BodyKind::Poisoned, + BodyState::Taken => BodyKind::Taken, + } + } + + async fn buffered_bytes( + &self, + requested_max: usize, + json: bool, + ) -> Result { + let max = self.body_policy.map_or(requested_max, |policy| { + if json || policy.ingress_is_json() { + requested_max.min(policy.ceiling().get()) + } else { + requested_max + } + }); let body = { let mut state = self.body.borrow_mut(); if matches!(&*state, BodyState::Initial(_)) { - if let Some(guard) = &self.input_guard - && let Err(error) = guard.check() - { - let stored = StoredError::capture(&error); - let returned = stored.to_edge_error(); - *state = BodyState::Poisoned(stored); - return Err(returned); - } - if self.input_guard.is_none() - && let Err(error) = - check_read_deadline(self.read_deadline, &self.monotonic_clock) - { + let input_check = self.input_guard.as_deref().map_or_else( + || check_read_deadline(self.read_deadline, &self.monotonic_clock), + InputGuard::check, + ); + if let Err(error) = input_check { let stored = StoredError::capture(&error); let returned = stored.to_edge_error(); *state = BodyState::Poisoned(stored); @@ -371,6 +402,12 @@ impl RequestContext { } match mem::replace(&mut *state, BodyState::Draining) { BodyState::Cached(bytes) => { + if let Err(error) = + prepare_protected_body(self.input_guard.as_deref(), Some(&bytes)) + { + *state = BodyState::Poisoned(StoredError::capture(&error)); + return Err(error); + } let result = check_cached_body(&bytes, max); *state = BodyState::Cached(bytes); return result; @@ -401,13 +438,13 @@ impl RequestContext { body: &self.body, }; let result = async { - let protected_body = prepare_protected_body(body, self.input_guard.as_deref())?; + prepare_protected_body(self.input_guard.as_deref(), body.buffered_bytes())?; let deadline = if self.input_guard.is_some() { None } else { self.read_deadline }; - drain_body(protected_body, max, deadline, &self.monotonic_clock).await + drain_body(body, max, deadline, &self.monotonic_clock).await } .await; match result { @@ -426,18 +463,6 @@ impl RequestContext { } } - #[must_use] - #[inline] - pub fn body_kind(&self) -> BodyKind { - match &*self.body.borrow() { - BodyState::Cached(bytes) => BodyKind::Cached { len: bytes.len() }, - BodyState::Draining => BodyKind::Draining, - BodyState::Initial(_) => BodyKind::Initial, - BodyState::Poisoned(_) => BodyKind::Poisoned, - BodyState::Taken => BodyKind::Taken, - } - } - #[must_use] #[inline] pub fn config_extraction_limits(&self) -> ConfigExtractionLimits { @@ -494,8 +519,8 @@ impl RequestContext { } let result = async { let unread = self.take_body()?; - let body = prepare_protected_body(unread, self.input_guard.as_deref())?; - drain_body_discard(body).await + prepare_protected_body(self.input_guard.as_deref(), unread.buffered_bytes())?; + drain_body_discard(unread).await } .await; if let Some(outcome) = self.fixed_input_outcome() { @@ -552,6 +577,7 @@ impl RequestContext { } /// Buffers at most `max` bytes and deserializes form-urlencoded data. + /// The adapter's buffering ceiling can lower `max` if the original ingress was JSON. /// /// # Errors /// Returns 413 on overflow, 400 on malformed input, and preserves body drain errors. @@ -594,13 +620,17 @@ impl RequestContext { return Err(error.to_edge_error()); } let body = match self.body.into_inner() { - BodyState::Cached(bytes) => Body::from(bytes), + BodyState::Cached(bytes) => { + Body::from_transfer(self.body_policy, BodyTransfer::Cached(bytes)) + } BodyState::Draining => { return Err(EdgeError::internal(anyhow::anyhow!( "body read in progress" ))); } - BodyState::Initial(body) => body, + BodyState::Initial(body) => { + Body::from_transfer(self.body_policy, BodyTransfer::Initial(body)) + } BodyState::Poisoned(error) => return Err(error.to_edge_error()), BodyState::Taken => Body::empty(), }; @@ -613,7 +643,13 @@ impl RequestContext { Ok(Request::from_parts(parts, body)) } - /// Buffers at most `max` bytes and deserializes JSON. + pub(crate) fn json_body_default(&self) -> usize { + self.body_policy + .map_or(DEFAULT_INBOUND_JSON_BYTES, |policy| policy.ceiling().get()) + } + + /// Buffers at most `max` bytes and deserializes JSON. An adapter's buffering ceiling + /// can lower `max`, regardless of the request's Content-Type. /// /// # Errors /// Returns 413 on overflow, 400 on malformed input, and preserves body drain errors. @@ -622,7 +658,7 @@ impl RequestContext { where T: DeserializeOwned, { - let bytes = self.body_bytes(max).await?; + let bytes = self.buffered_bytes(max, true).await?; serde_json::from_slice(bytes.as_ref()) .map_err(|err| EdgeError::bad_request(format!("invalid JSON payload: {err}"))) } @@ -671,9 +707,9 @@ impl RequestContext { Ok(()) } Err(buffered_source) => { - let buffered = prepare_protected_body(buffered_source, Some(&guard)) + prepare_protected_body(Some(&guard), buffered_source.buffered_bytes()) .map_err(|error| self.poison_protected_body(error))?; - let input = buffered.into_bytes().ok_or_else(|| { + let input = buffered_source.into_bytes().ok_or_else(|| { EdgeError::internal(anyhow::anyhow!("buffered body lost payload")) })?; match map(input).and_then(|bytes| check_cached_body(&bytes, max_output)) { @@ -707,8 +743,10 @@ impl RequestContext { #[inline] pub fn new(request: Request, params: PathParams) -> Self { let (parts, body) = request.into_parts(); + let (body_policy, transfer) = body.into_transfer(); Self { - body: RefCell::new(BodyState::Initial(body)), + body: RefCell::new(BodyState::from_transfer(transfer)), + body_policy, config_extraction_limits: ConfigExtractionLimits::default(), ingress_grant: RefCell::new(None), input_guard: None, @@ -735,10 +773,15 @@ impl RequestContext { violation: Cell::new(None), }); let (parts, raw_body) = request.into_parts(); - let body = guard_input(raw_body, Rc::clone(&guard)); + let (body_policy, transfer) = raw_body.into_transfer(); + let body = match transfer { + BodyTransfer::Initial(body) => BodyState::Initial(guard_input(body, Rc::clone(&guard))), + BodyTransfer::Cached(bytes) => BodyState::Cached(bytes), + }; let request_start = ingress.map_or_else(|| clock.now(), AdmittedIngress::request_start); Self { - body: RefCell::new(BodyState::Initial(body)), + body: RefCell::new(body), + body_policy, config_extraction_limits: ConfigExtractionLimits::default(), ingress_grant: RefCell::new(None), input_guard: Some(guard), @@ -948,17 +991,22 @@ impl RequestContext { } } -fn prepare_protected_body(body: Body, policy: Option<&InputGuard>) -> Result { - if let Some(guard) = policy { +fn prepare_protected_body( + input_guard: Option<&InputGuard>, + buffered: Option<&bytes::Bytes>, +) -> Result<(), EdgeError> { + if let Some(guard) = input_guard { guard.check()?; + // A restored cache hasn't been observed by this guard. Once it has, leave + // repeated reads and transformed output out of raw input accounting. if !guard.complete.get() - && let Some(bytes) = body.as_bytes() + && let Some(bytes) = buffered { guard.observe(bytes.len())?; guard.complete.set(true); } } - Ok(body) + Ok(()) } fn guard_input(body: Body, guard: Rc) -> Body { @@ -1137,6 +1185,387 @@ async fn drain_body_discard(body: Body) -> Result<(), EdgeError> { #[cfg(test)] mod tests { + mod managed_policy_tests { + use super::*; + use std::num::NonZeroUsize; + + #[test] + fn managed_form_family_keeps_caller_caps_and_typed_json_overflow() { + use crate::extractor::{Form, FromRequest as _, ValidatedForm, ValidatedFormWithin}; + use validator::Validate; + #[derive(Debug, Deserialize, Validate)] + struct Fields { + name: String, + } + let make = || { + ctx( + "/form", + managed(Body::from("name=a"), 5, true), + PathParams::default(), + ) + }; + assert_eq!( + block_on(make().form_within::(100)) + .expect_err("helper cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + block_on(Form::::from_request(&make())) + .err() + .expect("Form cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + block_on(ValidatedForm::::from_request(&make())) + .err() + .expect("validated Form cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + block_on(ValidatedFormWithin::::from_request(&make())) + .err() + .expect("within cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + let non_json = ctx( + "/form", + managed(Body::from("name=a"), 1, false), + PathParams::default(), + ); + assert_eq!( + block_on(Form::::from_request(&non_json)) + .expect("non-JSON generic") + .0 + .name, + "a" + ); + } + + #[test] + fn managed_source_bad_request_is_not_translated_by_message() { + let source = Body::from_stream(stream::iter([Err(EdgeError::bad_request( + "request body too large", + ))])); + let context = ctx("/source", managed(source, 1, true), PathParams::default()); + assert_eq!( + block_on(context.body_bytes(100)) + .expect_err("source error") + .status(), + StatusCode::BAD_REQUEST + ); + } + + fn managed(body: Body, cap: usize, is_json: bool) -> Body { + body.with_buffered_json_policy(NonZeroUsize::new(cap).expect("positive cap"), is_json) + } + + #[test] + fn managed_partial_cancellation_drops_source_once_and_poisons() { + struct DropSignal(Rc>); + #[expect( + clippy::missing_trait_methods, + reason = "`Drop::pin_drop` is unstable (`pin_ergonomics`) and conflicts with `drop`" + )] + impl Drop for DropSignal { + fn drop(&mut self) { + self.0.set(self.0.get().saturating_add(1)); + } + } + let drops = Rc::new(Cell::new(0_usize)); + let signal = DropSignal(Rc::clone(&drops)); + let polls = Rc::new(Cell::new(0_usize)); + let seen = Rc::clone(&polls); + let source = Body::from_stream(stream::poll_fn(move |_| { + let _retained = &signal; + let step = seen.get(); + seen.set(step.saturating_add(1)); + if step == 0 { + Poll::Ready(Some(Ok(Bytes::from_static(b"ab")))) + } else { + Poll::Pending + } + })); + let context = ctx("/body", managed(source, 4, true), PathParams::default()); + let mut reading = Box::pin(context.body_bytes(100)); + let mut task = Context::from_waker(noop_waker_ref()); + assert!(matches!(reading.as_mut().poll(&mut task), Poll::Pending)); + assert_eq!(polls.get(), 2); + assert_eq!(context.body_kind(), BodyKind::Draining); + drop(reading); + assert_eq!(drops.get(), 1); + assert_eq!(context.body_kind(), BodyKind::Poisoned); + let error = block_on(context.body_bytes(100)).expect_err("cancel poison"); + assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert!(error.message().contains("inbound body drain cancelled")); + assert_eq!( + context + .into_request() + .expect_err("sticky reconstruction") + .status(), + error.status() + ); + assert_eq!(polls.get(), 2); + assert_eq!(drops.get(), 1); + } + + #[test] + fn managed_deadline_tie_wins_over_overflow_without_repolling() { + let start = MonotonicInstant::now(); + let deadline = start.checked_add(Duration::from_secs(1)).expect("deadline"); + let now = Arc::new(Mutex::new(start)); + let poll_clock = Arc::clone(&now); + let observed_clock = Arc::clone(&now); + let polls = Rc::new(Cell::new(0_usize)); + let seen = Rc::clone(&polls); + let source = Body::from_stream(stream::poll_fn(move |_| { + seen.set(seen.get().saturating_add(1)); + *poll_clock.lock().expect("clock") = deadline; + Poll::Ready(Some(Ok(Bytes::from_static(b"oversized")))) + })); + let mut context = ctx("/body", managed(source, 1, true), PathParams::default()); + context.monotonic_clock = + MonotonicClock::new(move || *observed_clock.lock().expect("clock")); + context.read_deadline = Some(Deadline::at_instant(deadline)); + let error = block_on(context.body_bytes(100)).expect_err("deadline wins"); + assert!(matches!(error, EdgeError::RequestTimeout { .. })); + *now.lock().expect("clock") = start; + assert_eq!( + block_on(context.body_bytes(100)) + .expect_err("sticky deadline") + .status(), + StatusCode::REQUEST_TIMEOUT + ); + assert_eq!(context.body_kind(), BodyKind::Poisoned); + assert_eq!(polls.get(), 1); + } + + #[test] + fn managed_routed_reconstruction_restores_initial_and_cache_after_head_mutation() { + use crate::app::App; + use crate::extractor::{FromRequest as _, Json}; + use crate::ingress::{ + IngressBeginOutcome, IngressFraming, IngressHeadAccounting, IngressHeadParts, + }; + use crate::router::RouterService; + + #[derive(Clone)] + struct ExpectedBody { + bytes: Bytes, + kind: BodyKind, + } + + #[crate::action] + async fn handler(routed: RequestContext) -> Result<(), EdgeError> { + let expected = routed.extensions().get::().expect("fixture"); + assert_eq!(routed.extensions().get::(), Some(&99)); + let metadata = RouteMetadata::new(Method::GET, "/body"); + assert_eq!(routed.route_metadata(), Some(&metadata)); + assert_eq!(routed.headers()["content-type"], "text/plain"); + assert_eq!(routed.body_kind(), expected.kind); + let policy = routed.body_policy.expect("original policy"); + assert!(policy.ingress_is_json()); + assert_eq!(policy.ceiling().get(), expected.bytes.len()); + + let Json(value) = Json::::from_request(&routed).await?; + assert_eq!(value.len(), DEFAULT_INBOUND_JSON_BYTES); + assert_eq!( + routed + .body_bytes(expected.bytes.len().saturating_sub(1)) + .await + .expect_err("local cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + let retry = routed.body_bytes(usize::MAX).await?; + assert_eq!(retry.as_ptr(), expected.bytes.as_ptr()); + Ok(()) + } + + let app = App::new( + RouterService::builder() + .with_state(99_u32) + .get("/body", handler) + .build(), + ); + let bytes = Body::json(&"x".repeat(DEFAULT_INBOUND_JSON_BYTES)) + .expect("JSON above the portable limit") + .into_bytes() + .expect("buffered JSON"); + for cached in [false, true] { + let cap = bytes.len(); + let original = ctx( + "/body", + managed(Body::from(bytes.clone()), cap, true), + PathParams::default(), + ); + if cached { + block_on(original.body_bytes(cap)).expect("cache"); + } + let kind = original.body_kind(); + let mut request = original.into_request().expect("reconstruct"); + request + .headers_mut() + .insert("content-type", HeaderValue::from_static("text/plain")); + request.extensions_mut().clear(); + request.extensions_mut().insert(7_u32); + request.extensions_mut().insert(ExpectedBody { + bytes: bytes.clone(), + kind, + }); + let head = IngressHeadParts::from_request( + &request, + IngressHeadAccounting::HostManaged, + IngressFraming::HostManaged, + ); + let IngressBeginOutcome::Admitted(prepared) = app + .begin_ingress(head, app.monotonic_now()) + .expect("admission") + else { + panic!("admit"); + }; + let (resolved, ingress, _completion) = prepared.into_parts(); + let response = block_on(app.router().dispatch_resolved(resolved, request, ingress)) + .expect("route with injected state"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + } + } + + #[test] + fn managed_initial_reconstruction_preserves_policy_without_polling() { + let polls = Rc::new(Cell::new(0_usize)); + let observed = Rc::clone(&polls); + let initial_source = Body::from_stream(stream::poll_fn(move |_| { + observed.set(observed.get() + 1); + Poll::Ready(Some(Ok(Bytes::from_static(b"oversized")))) + })); + let original = ctx( + "/body", + managed(initial_source, 3, true), + PathParams::default(), + ); + let mut request = original.into_request().expect("initial reconstruction"); + request + .headers_mut() + .insert("content-type", HeaderValue::from_static("text/plain")); + request.extensions_mut().clear(); + let (parts, body) = request.into_parts(); + let reconstructed = RequestContext::new( + Request::from_parts(parts, managed(body, 100, false)), + PathParams::default(), + ); + assert_eq!(polls.get(), 0); + let error = block_on(reconstructed.body_bytes(100)).expect_err("original ceiling"); + assert_eq!(error.status(), StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(error.kind(), "payload_too_large"); + assert_eq!(polls.get(), 1); + assert_eq!( + block_on(reconstructed.body_bytes(1000)) + .expect_err("sticky") + .status(), + error.status() + ); + assert_eq!( + reconstructed.take_body().expect_err("sticky take").status(), + error.status() + ); + assert_eq!( + reconstructed + .into_request() + .expect_err("sticky reconstruction") + .status(), + error.status() + ); + assert_eq!(polls.get(), 1); + } + + #[test] + fn managed_cached_reconstruction_reuses_allocation_and_stateless_rechecks() { + let original = ctx( + "/body", + managed(Body::from("hello"), 5, true), + PathParams::default(), + ); + let bytes = block_on(original.body_bytes(5)).expect("exact cap"); + let mut request = original.into_request().expect("cached reconstruction"); + request.headers_mut().clear(); + request.extensions_mut().clear(); + let (parts, body) = request.into_parts(); + let reconstructed = RequestContext::new( + Request::from_parts(parts, managed(body, 100, false)), + PathParams::default(), + ); + assert_eq!(reconstructed.body_kind(), BodyKind::Cached { len: 5 }); + assert_eq!( + block_on(reconstructed.body_bytes(4)) + .expect_err("stricter cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + let retry = block_on(reconstructed.body_bytes(100)).expect("intact cache"); + assert_eq!(bytes.as_ptr(), retry.as_ptr()); + assert_eq!(reconstructed.body_kind(), BodyKind::Cached { len: 5 }); + } + + #[test] + fn managed_json_helpers_cap_non_json_ingress_but_generic_reads_do_not() { + let original = ctx( + "/body", + managed(Body::from("\"abcdef\""), 4, false), + PathParams::default(), + ); + let bytes = block_on(original.body_bytes(20)).expect("non-JSON generic read"); + let error = block_on(original.json_within::(20)).expect_err("JSON policy"); + assert_eq!(error.status(), StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(original.body_kind(), BodyKind::Cached { len: 8 }); + let request = original.into_request().expect("cached round trip"); + let reconstructed = RequestContext::new(request, PathParams::default()); + assert_eq!( + block_on(reconstructed.body_bytes(20)) + .expect("generic retry") + .as_ptr(), + bytes.as_ptr() + ); + assert_eq!( + block_on(reconstructed.json_within::(20)) + .expect_err("preserved ceiling") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + } + + #[test] + fn managed_initial_once_overflow_is_sticky_and_taken_content_is_unmanaged() { + let initial = ctx( + "/body", + managed(Body::from("large"), 2, true), + PathParams::default(), + ); + assert_eq!( + block_on(initial.body_bytes(10)) + .expect_err("overflow") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!(initial.body_kind(), BodyKind::Poisoned); + let taken = ctx( + "/body", + managed(Body::from("large"), 2, true), + PathParams::default(), + ) + .take_body() + .expect("take"); + assert!(taken.as_bytes().is_some()); + assert_eq!( + block_on(taken.into_bytes_bounded(5)).expect("manual cap"), + "large" + ); + } + } + use super::*; use crate::config_store::ready_config_store_bounded_read; use crate::http::{HeaderMap, HeaderValue, Method, StatusCode, request_builder}; diff --git a/crates/edgezero-core/src/extractor.rs b/crates/edgezero-core/src/extractor.rs index 51e355265..c7a38a7ce 100644 --- a/crates/edgezero-core/src/extractor.rs +++ b/crates/edgezero-core/src/extractor.rs @@ -14,7 +14,7 @@ use validator::Validate; use crate::app_config::{AppConfigMeta, SecretField, SecretKind, SecretPathSegment}; use crate::blob_envelope::{BlobEnvelope, BlobEnvelopeError}; use crate::config_store::{ConfigExtractionLimits, ConfigStoreError, ConfigStoreHandle}; -use crate::context::{DEFAULT_INBOUND_FORM_BYTES, DEFAULT_INBOUND_JSON_BYTES, RequestContext}; +use crate::context::{DEFAULT_INBOUND_FORM_BYTES, RequestContext}; use crate::error::{EdgeError, StoreExtractionReason}; use crate::http::HeaderMap; use crate::secret_store::SecretError; @@ -39,7 +39,7 @@ where { #[inline] async fn from_request(ctx: &RequestContext) -> Result { - ctx.json_within(DEFAULT_INBOUND_JSON_BYTES).await.map(Json) + ctx.json_within(ctx.json_body_default()).await.map(Json) } } @@ -1764,7 +1764,7 @@ mod tests { use crate::config_store::{ ConfigStore, ConfigStoreError, ConfigStoreHandle, ready_config_store_bounded_read, }; - use crate::context::RequestContext; + use crate::context::{DEFAULT_INBOUND_JSON_BYTES, RequestContext}; use crate::http::{HeaderValue, Method, StatusCode, request_builder}; use crate::params::PathParams; use crate::secret_store::{InMemorySecretStore, NoopSecretStore, SecretHandle, SecretStore}; diff --git a/crates/edgezero-core/src/outbound/batch.rs b/crates/edgezero-core/src/outbound/batch.rs index 97efdbc0a..a61fe197b 100644 --- a/crates/edgezero-core/src/outbound/batch.rs +++ b/crates/edgezero-core/src/outbound/batch.rs @@ -60,7 +60,7 @@ pub struct OutboundBatchItem { target_pointer_width = "64", expect( clippy::large_enum_variant, - reason = "terminal positional results stay inline; scalar Body framing metadata does not warrant a per-slot allocation" + reason = "terminal positional results stay inline; ingress body policy and scalar Body framing metadata do not warrant a per-slot allocation" ) )] #[derive(Debug)] diff --git a/crates/edgezero-core/src/pre_dispatch.rs b/crates/edgezero-core/src/pre_dispatch.rs index 4953a414a..87706df5c 100644 --- a/crates/edgezero-core/src/pre_dispatch.rs +++ b/crates/edgezero-core/src/pre_dispatch.rs @@ -13,10 +13,12 @@ pub struct PreDispatchRequest { } impl PreDispatchRequest { - /// Buffers the current body under `max` and the original raw input policy. + /// Buffers the current body under `max` and the original raw input policy. If the + /// adapter classified the original ingress as JSON, its buffering ceiling can lower `max`. /// /// # Errors /// Returns the existing sticky read error, 413 for overflow, or 408 for input expiry. + /// A tighter caller cap on an intact cache does not poison it. #[inline] pub async fn body_bytes(&self, max: usize) -> Result { self.context.body_bytes(max).await @@ -107,7 +109,8 @@ impl PreDispatchRequest { self.context.parts_mut() } - /// Buffers bounded input and installs bounded, synchronously transformed bytes. + /// Buffers input with the same limits as [`Self::body_bytes`]. Installs synchronously + /// transformed bytes bounded by `max_output`. /// /// # Errors /// Read, transform, and output overflow errors leave the shared body cell poisoned. @@ -154,7 +157,7 @@ mod tests { use super::*; use crate::app::App; use crate::body::Body; - use crate::error::{BadGatewayReason, BudgetSource}; + use crate::error::{BadGatewayReason, BudgetSource, RequestBodyOverflowOrigin}; use crate::error_detail::{FastlyFailureCause, ProviderFailureDetail, ProviderFailurePhase}; use crate::http::{Method, StatusCode, request_builder}; use crate::ingress::{ @@ -172,6 +175,7 @@ mod tests { use std::cell::Cell; use std::future::Future as _; use std::io::Error as IoError; + use std::num::NonZeroUsize; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; @@ -342,6 +346,127 @@ mod tests { ingress } + fn restored_cache() -> Request { + let body = Body::from("body") + .with_buffered_json_policy(NonZeroUsize::new(8).expect("managed cap"), true); + let context = RequestContext::new(request(body), PathParams::default()); + block_on(context.body_bytes(4)).expect("original cache"); + context.into_request().expect("restore cache") + } + + #[test] + fn restored_cache_fixed_outcome_is_typed_and_sticky() { + for expired in [false, true] { + let start = MonotonicInstant::now(); + let now = Arc::new(Mutex::new(start)); + let observed = Arc::clone(&now); + let ingress = admitted( + 3, + MonotonicClock::new(move || *observed.lock().expect("clock")), + ); + let wrapped = PreDispatchRequest::new(restored_cache(), Some(&ingress)); + assert_eq!(wrapped.body_kind(), BodyKind::Cached { len: 4 }); + if expired { + *now.lock().expect("clock") = + start.checked_add(Duration::from_secs(1)).expect("deadline"); + } + assert!(wrapped.fixed_outcome().is_none(), "no read yet"); + + let first = block_on(wrapped.body_bytes(8)).expect_err("fixed input limit"); + assert_eq!(wrapped.body_kind(), BodyKind::Poisoned); + *now.lock().expect("clock") = start; + let retry = block_on(wrapped.body_bytes(8)).expect_err("sticky fixed error"); + assert_eq!(retry.message(), first.message()); + let outcome = block_on(wrapped.discard()).expect("sticky discard outcome"); + if expired { + // The deadline wins even though these bytes also exceed the fallback cap. + assert!(matches!(first, EdgeError::RequestTimeout { .. })); + assert!(matches!(retry, EdgeError::RequestTimeout { .. })); + assert!(matches!(outcome, FallbackDrainOutcome::TimedOut)); + } else { + for error in [first, retry] { + assert!(matches!( + error, + EdgeError::PayloadTooLarge { + origin: RequestBodyOverflowOrigin::Inbound, + } + )); + } + assert!(matches!(outcome, FallbackDrainOutcome::Exceeded)); + } + } + } + + #[test] + fn restored_cache_discard_checks_fallback_limits() { + for expired in [false, true] { + let start = MonotonicInstant::now(); + let now = Arc::new(Mutex::new(start)); + let observed = Arc::clone(&now); + let ingress = admitted( + 3, + MonotonicClock::new(move || *observed.lock().expect("clock")), + ); + let wrapped = PreDispatchRequest::new(restored_cache(), Some(&ingress)); + if expired { + *now.lock().expect("clock") = + start.checked_add(Duration::from_secs(1)).expect("deadline"); + } + let outcome = block_on(wrapped.discard()).expect("fixed discard outcome"); + if expired { + assert!(matches!(outcome, FallbackDrainOutcome::TimedOut)); + } else { + assert!(matches!(outcome, FallbackDrainOutcome::Exceeded)); + } + } + } + + #[test] + fn restored_cache_read_then_discard_does_not_reaccount() { + let start = MonotonicInstant::now(); + let now = Arc::new(Mutex::new(start)); + let observed = Arc::clone(&now); + let ingress = admitted( + 4, + MonotonicClock::new(move || *observed.lock().expect("clock")), + ); + let wrapped = PreDispatchRequest::new(restored_cache(), Some(&ingress)); + let bytes = block_on(wrapped.body_bytes(4)).expect("exact fallback cap"); + *now.lock().expect("clock") = start.checked_add(Duration::from_secs(1)).expect("deadline"); + assert_eq!( + block_on(wrapped.body_bytes(3)) + .expect_err("local cap") + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!(wrapped.body_kind(), BodyKind::Cached { len: 4 }); + let cached = block_on(wrapped.body_bytes(4)).expect("cache retry"); + assert_eq!(cached.as_ptr(), bytes.as_ptr()); + assert!(matches!( + block_on(wrapped.discard()).expect("already consumed"), + FallbackDrainOutcome::Complete + )); + } + + #[test] + fn restored_cache_transform_does_not_charge_output() { + let ingress = admitted(4, MonotonicClock::default()); + let mut wrapped = PreDispatchRequest::new(restored_cache(), Some(&ingress)); + let output = Bytes::from_static(b"mapped"); + block_on(wrapped.transform_body(4, 6, |input| { + assert_eq!(input, "body"); + Ok(output.clone()) + })) + .expect("transform at the raw input cap"); + let bytes = block_on(wrapped.body_bytes(6)).expect("transformed cache"); + assert_eq!(bytes.as_ptr(), output.as_ptr()); + assert_eq!(wrapped.headers()["content-length"], "6"); + assert!(matches!( + block_on(wrapped.discard()).expect("discard transformed body"), + FallbackDrainOutcome::Complete + )); + } + #[test] fn reassembly_preserves_unread_empty_and_pending_bodies_after_expiry() { for buffered in [false, true] { diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock index b534b4870..0d0f25712 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock @@ -511,6 +511,7 @@ dependencies = [ "hyper-util", "libc", "log", + "mime", "redb", "reqwest", "serde", diff --git a/docs/guide/adapters/axum.md b/docs/guide/adapters/axum.md index d3f3b04ee..1cb2f85d0 100644 --- a/docs/guide/adapters/axum.md +++ b/docs/guide/adapters/axum.md @@ -148,6 +148,56 @@ mode, cancels remaining work and returns an error. Give the supervisor a longer stop timeout than the drain budget. The runner cannot preempt blocking application code. +## Buffered JSON body limits + +Every standard Axum hosting path defaults framework-managed JSON buffering to 2 MiB, +exactly 2,097,152 bytes. Valid JSON at the effective limit succeeds; one byte over returns +HTTP 413. Malformed JSON within the limit remains HTTP 400. + +For standalone development or production, select decimal integer bytes at startup: + +```bash +EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES=4194304 cargo run -p my-app-adapter-axum +``` + +The value must be positive and representable by the collector. Zero, signs, whitespace, +suffixes, fractions, overflowing values, and non-Unicode values fail startup before application +configuration or readiness. There is no unlimited sentinel, CLI flag, or manifest setting. +The selected value is captured once per run. It governs buffering after admission. The separate +[`AxumIngressConfig` settings](#bounded-http-1-ingress) govern HTTP/1 connections and request heads +before admission. + +For explicit production embedding or a router-only server, use the fallible builder: + +```rust +use edgezero_adapter_axum::dev_server::{AxumDevServer, AxumRunOptions}; + +let options = AxumRunOptions::new("127.0.0.1:8787".parse()?)? + .with_json_body_limit_bytes(4 * 1024 * 1024)?; +let server = AxumDevServer::new(app).with_json_body_limit_bytes(4 * 1024 * 1024)?; +``` + +Explicit options and router builders do not merge ambient settings. `AxumRunOptions::from_env` +is the deliberate environment-driven alternative. The low-level `into_core_request` converter +attaches the finite default without reading this environment setting. + +Ordinary `Json` and `ValidatedJson` use the selected ceiling, including overrides above the +portable 8 MiB fallback. Explicit JSON caps take the minimum of the caller cap and native ceiling, +regardless of Content-Type. Generic buffered helpers clamp their caller cap only when the original +ingress media type is `application/json` or `application/*+json`. For classification, the adapter +uses the first Content-Type field value. A missing or malformed value does not classify the body as +JSON or cause the adapter to reject it. Ordinary Form retains its 1 MiB caller cap, which the +native ceiling can lower on JSON ingress. + +Header and extension edits do not change policy, and rebuilding a request with the original +`Body` preserves it. Extracting the raw payload and constructing a new body does not carry it +over. See [buffered body limits](../handlers.md#buffered-body-limits) for middleware options. + +Taken streams and proxy forwarding receive no new aggregate size cap. Manual body collection +keeps its supplied cap and existing typed 413 overflow behavior. The ceiling bounds logical buffered +body bytes, not parsed JSON allocations, host buffers, concurrent requests, or process memory. +It does not promise client receipt or keep-alive reuse after rejection. + ## Bounded HTTP/1 Ingress The standard server entrypoints own a bounded pool of HTTP/1 connections. These limits apply diff --git a/docs/guide/handlers.md b/docs/guide/handlers.md index 3029c1034..ec1862fe1 100644 --- a/docs/guide/handlers.md +++ b/docs/guide/handlers.md @@ -97,6 +97,35 @@ async fn login(Json(body): Json) -> Text { } ``` +#### Buffered body limits + +Portable ordinary JSON extraction defaults to 8 MiB. On Axum, ordinary `Json` and +`ValidatedJson` instead use the native ceiling, which defaults to 2 MiB, exactly 2,097,152 bytes. +See [Axum body-limit configuration](./adapters/axum.md#buffered-json-body-limits). + +`json_within(max)` and `ValidatedJsonWithin` use the lower of the caller cap and the +Axum ceiling, even without a JSON Content-Type. Generic buffered reads do the same only on +original `application/json` or `application/*+json` ingress. That includes `body_bytes`, +`form_within`, the Form family, and pre-dispatch buffered reads. Ordinary Form still asks for +at most 1 MiB. Other generic reads keep their existing caps. Size overflow returns typed +HTTP 413; malformed JSON within the limit remains 400. + +The original ceiling and classification survive `into_request` followed by fresh or routed +context construction with the same `Body`, even after headers or extensions change. Successful +cached reconstruction reuses the bytes. A tighter size check does not poison that cache, but +a failure during the initial drain stays sticky. + +If middleware extracts raw bytes or a stream and constructs a new body, it discards that policy. +Ordinary JSON extraction on the replacement body uses the portable 8 MiB default. For protected +pre-dispatch rewrites, use `PreDispatchRequest::map_body` or `PreDispatchRequest::transform_body` +to keep the policy for subsequent buffered reads. + +`take_body` and stream forwarding remain incremental without a new total-size cap. Low-level +manual collection uses only its supplied cap and retains typed 413 overflow behavior. +`Body` remains a struct and `BodyPayload` is still exhaustive. Raw transport splitting with +`Body::into_parts` removes ingress metadata while retaining the exact optional egress owner, +which the transport must keep through terminal response egress. + ### Validated Extractors Use `validator` crate integration for input validation: diff --git a/docs/superpowers/plans/2026-10-06-axum-buffered-json-body-limit.md b/docs/superpowers/plans/2026-10-06-axum-buffered-json-body-limit.md new file mode 100644 index 000000000..ae3536feb --- /dev/null +++ b/docs/superpowers/plans/2026-10-06-axum-buffered-json-body-limit.md @@ -0,0 +1,79 @@ +# Axum buffered JSON request-body limit implementation plan + +Issue: [#393](https://github.com/IABTechLab/edgezero/issues/393). +Spec: [Axum configurable buffered JSON request-body limits](../specs/2026-10-06-axum-buffered-json-body-limit-design.md). +Review: [#407](https://github.com/IABTechLab/edgezero/pull/407). + +## Review baseline + +| Role | Revision inspected | +| --- | --- | +| #407 head before review fixes | `9750b0e3c7623b94a98cfa05960266450e7a60f2` | +| Immediate #406 base and merge base | `b67e78b9fd02b91855ee8ec09dcb89419f45f024` | +| Inherited #275 head at inspection | `0e2a58ae54860842c3490ff2ad2d79897bb06b37`, an ancestor of #406 | + +Review the feature delta against #406, not `main`. At this inspected base, #275 already supplies admission before conversion, lazy streams and read deadlines, bounds fixed fallback input, checks chunks before append, and owns the cache, sticky failures, typed 413 and response egress. Its bounded HTTP/1 close drain is inherited, not a #407 change. #406 supplies production startup and bounded shutdown. #407 adds the validated per-run Axum ceiling, immutable classification, body-owned policy transfer, and acceptance coverage through those paths. + +The pre-restack plan assumed a different `Body` and error model. The current branch keeps the `Body` struct and `BodyPayload` from #275. No public enum migration, second collector, or cross-provider status change belongs in this delta. The [historical plan at the review head](https://github.com/IABTechLab/edgezero/blob/9750b0e3c7623b94a98cfa05960266450e7a60f2/docs/superpowers/plans/2026-10-06-axum-buffered-json-body-limit.md) records the original sequencing, not acceptance of the current stack. + +## Review fixes + +1. Restore input-guard accounting for cached bodies entering a new protected dispatch. Share the buffered-input check with the existing path. Test fixed overflow and deadline handling, completed reads before fallback discard, transformed output, and non-poisoning caller-cap rechecks. Preserve the returned body when buffered `into_stream` conversion fails. +2. Recognize valid JSON media types with legal parameter whitespace and compare the full subtype or terminal suffix. Keep first-field classification and the existing malformed-header behavior. Share recognition of the JSON setting across dev and production without changing permissive dev handling for unrelated settings. +3. Add managed JSON dispatch evidence for source failure and pending cancellation, initial/cached reconstruction above 8 MiB with router state injection, and configured wire boundaries for both router-only constructors. Keep the existing read-while-uploading wire helper and its complete-response assertion. +4. Document the native config boundary, limit clamp, real compatibility changes, and the difference between reconstructing the original body and replacing a raw payload. Mark core policy attachment as an adapter hook; keep the existing first policy. No changes to neighboring PRs or publication are part of this pass. + +## Acceptance evidence + +| Contract | Check | +| --- | --- | +| Exact default and typed 413 on both HTTP/1 framings | `json_body_limit_wire_content_length_and_chunked`, with handler entry counts | +| Development/production/embedding overrides, media variants, explicit caps, malformed JSON and uncapped streams | `json_limit_overrides_helpers_generic_reads_and_taken_streams`, including an ordinary 9 MiB production override | +| Validation without leaking values or running app hooks | `json_body_limit_is_positive_decimal_and_representable` and `invalid_json_limits_fail_before_application_hooks_in_dev_and_production` | +| Classification and Form-family caller caps | `ingress_json_classifier_validates_media_type_syntax`, `ingress_json_classifier_uses_only_the_first_content_type` and the managed Form/JSON context tests | +| Lazy reassembly, immutable policy, cached reuse and raw handoff | `managed_routed_reconstruction_restores_initial_and_cache_after_head_mutation`, the fresh-context reconstructions, and `into_stream_returns_original_managed_buffered_body` | +| New input guard on restored cache | `restored_cache_*` tests for fixed limits, deadline, fallback discard and transformed output | +| Poll/drop counts and response lifecycle | `managed_json_overflow_drops_source_once_stops_polling_and_keeps_error_egress`, `managed_json_source_error_releases_partial_body_and_keeps_error_egress`, and `managed_json_cancelled_partial_read_releases_source_without_egress` | +| Router-only default and configured limit | `router_only_json_boundaries_for_both_constructors`, exact-cap/+1 on the wire through `AxumDevServer::new` and `AxumDevServer::with_config` | +| Admission ordering, owned egress and other adapters | Existing ingress, fallback, lifecycle, and shared provider suites; no new policy outside Axum | + +The [hosted run for `9750b0e3`](https://github.com/IABTechLab/edgezero/actions/runs/45768458564) passed before the review fixes. The hosted merge commit had the same tree as that head. That run is evidence for the tested tree only. The historical local runs are not current-head evidence. + +Use targeted core and Axum checks during iteration, then the repository's workspace, formatting, Clippy, feature and documentation checks on the combined patch. Use `test-utils` for the Axum subprocess suite. Record the commands, tested inputs and gaps at handoff; do not treat a filtered run as a full suite. For example: + +```sh +cargo test --locked -p edgezero-core --lib restored_cache_ +cargo test --locked -p edgezero-adapter-axum --lib managed_json_ +cargo test --locked -p edgezero-adapter-axum --features test-utils --test production_hosting json_ +cargo fmt --all -- --check +node scripts/check_outbound_docs_contract.mjs +``` + +### Local review verification + +Linux, Rust 1.98.1. Tested working-tree changes over `9750b0e3` above. The SHA-256 of `git diff -- crates Cargo.toml Cargo.lock` was `e883f099f9e2bac86e3ab94a5be127be7d05fe1b4adcb1e60aca403c2081ed19`. + +| Check | Result | +| --- | --- | +| `cargo test --locked -p edgezero-core --all-targets` and `--doc` | Passed, including all restored-cache, routed reconstruction, and body transfer regressions | +| `cargo test --locked -p edgezero-adapter-axum --all-targets --all-features` | Passed: 367 unit, 28 contract, and 16 subprocess tests; 1 ignored unit test | +| `router_only_json_boundaries_for_both_constructors` | Passed 30/30 consecutive Linux runs on the review patch; macOS not rerun | +| `cargo test --locked --workspace --all-targets` with non-TTY input | Parallel retry passed: 2,834 passed, 2 ignored. An earlier parallel run failed in the unchanged CLI `typed_push_envelope_sha_matches_hand_computed_hash` test with an invalid store selector. | +| Workspace format and strict Clippy, `cargo check --workspace --all-targets --features 'fastly cloudflare spin'` | Passed | +| Core `wasm32-unknown-unknown` check and Spin `wasm32-wasip2` check with `spin` | Passed | +| `cargo test --offline --locked --manifest-path crates/edgezero-test-harness/Cargo.toml` | 675 passed; 4 ignored | +| `npm run format`, `npm run lint`, `npm run build` from `docs/`, and `node scripts/check_outbound_docs_contract.mjs` from root | Passed | + +The wire fixtures prove receipt of a complete response in the tested cases, not a guarantee of receipt for all peers or a new shutdown contract. Provider build checks do not qualify provider deployments or all provider runtime behavior. + +## Merge-forward integration + +The merge takes #407's reviewed head `64447b46` and #406's `48097ab1` as parents. It keeps #406's production and development runner lifecycles and store preparation, and passes #407's selected JSON ceiling with the prepared app into the shared service. The production hosting fixtures keep both sets of cases, including explicit embedding that ignores an invalid ambient JSON setting. + +On Linux with Rust 1.98.1, the merged tree passed the all-feature Axum suite and the CI-shaped production-hosting run (23 subprocess tests), including 30/30 repeated router-only wire tests. Workspace tests passed (2,835 passed, 2 ignored), as did strict Clippy, formatting, feature compilation, portable production-handler checks on all three WASM targets, the Spin WASM check, and docs checks. This checks the current #406 integration, not the eventual accepted-stack gate below. + +## Acceptance after prerequisites + +- [ ] Record the accepted #275 revision and resulting #406 integration. The inspected ancestor is not evidence of acceptance. +- [ ] Re-audit admitted conversion, collection/cache, failure rendering, fallback discard, response egress and the hosting entry points. Check that the final stack still uses one collector and does not poll bodies before admission. Ordinary 404/405, refusals and aborts retain their no-read paths. +- [ ] Rerun affected core, Axum and hosting checks, including the real wire boundaries and interrupted/erroring reads. Attach results to the accepted inputs before treating #393 as complete. diff --git a/docs/superpowers/specs/2026-08-22-inbound-body-design.md b/docs/superpowers/specs/2026-08-22-inbound-body-design.md index 8b4d2888b..336435e79 100644 --- a/docs/superpowers/specs/2026-08-22-inbound-body-design.md +++ b/docs/superpowers/specs/2026-08-22-inbound-body-design.md @@ -11,6 +11,28 @@ > state machine. Outbound streaming proxy-forward consumes the resulting > `BodyCell`/`into_request()` contract but does not own it. +## Native JSON policy addendum, issue #393 + +The portable 8 MiB JSON default stays in place. The shared collector on the #275 baseline +already reports overflow as typed `PayloadTooLarge`/413, including for generic non-JSON +buffering. Older 400 overflow examples below predate that change. + +Axum-managed JSON buffering defaults to a configurable 2 MiB (2,097,152 bytes). JSON helpers +always use the policy; generic buffering uses it on captured JSON or +json ingress. Explicit +caller caps can tighten the ceiling. Ordinary Form retains its 1 MiB caller cap. Taken streams, +fallback discard, forwarding, and manual collection do not acquire the native JSON ceiling. + +The existing `Body` struct carries private policy and initial/cache provenance. Reconstructing +a request with the same body preserves them even if the head changes. Cached caller-cap checks +do not poison the cache; on re-entry through protected dispatch the new input guard still +accounts for the original bytes once. Raw `BodyPayload` handoff through `Body::into_parts` drops +the metadata while preserving the exact optional egress owner. Admission and completion +ownership are not part of the policy. + +See the [#393 spec](2026-10-06-axum-buffered-json-body-limit-design.md) and its implementation plan +for configuration and required evidence. Re-audit the inherited paths and rerun affected checks +once the prerequisite stack is accepted. + ## 1. Scope The goal is to stop adapters from pre-buffering unbounded inbound bodies while preserving diff --git a/docs/superpowers/specs/2026-10-06-axum-buffered-json-body-limit-design.md b/docs/superpowers/specs/2026-10-06-axum-buffered-json-body-limit-design.md new file mode 100644 index 000000000..4d7ebaad3 --- /dev/null +++ b/docs/superpowers/specs/2026-10-06-axum-buffered-json-body-limit-design.md @@ -0,0 +1,76 @@ +# Axum configurable buffered JSON request-body limits + +Initial design: 2026-10-06. Updated for the [#407 review](https://github.com/IABTechLab/edgezero/pull/407). + +Issue: [#393](https://github.com/IABTechLab/edgezero/issues/393), under [#391](https://github.com/IABTechLab/edgezero/issues/391). +Prerequisites: [#275](https://github.com/IABTechLab/edgezero/pull/275) and the immediate hosting base, [#406](https://github.com/IABTechLab/edgezero/pull/406). +The [plan](../plans/2026-10-06-axum-buffered-json-body-limit.md) records the inspected revisions and remaining acceptance work. Review on this stack does not certify the eventual accepted prerequisites. + +## Scope + +The standard Axum service defaults framework-managed JSON buffering to **2 MiB, exactly 2,097,152 bytes**, in development and production. The default comes from [Axum's buffering-extractor limit](https://docs.rs/axum/0.8.9/axum/extract/struct.DefaultBodyLimit.html), not from workload measurements. Valid JSON at the effective limit succeeds. Overflow returns typed HTTP 413 through the existing error and response lifecycle. JSON syntax errors within the limit remain 400. + +Keep conversion lazy and reuse the admitted read deadline, bounded collector, cache, and failure state inherited from #275. The collector checks actual bytes before append even without a declared length. It may reject a known oversized length earlier. No eager prebuffer, second collector, or buffer allocation based on the declared length is needed. + +The new ceiling does not govern `take_body`, proxy forwarding, fallback discard, or application-owned manual collection. It does not change non-Axum defaults or error categories. This issue adds no concurrent request limit, queue, stream-size or lifetime limit, timeout, handler cancellation policy, or overload policy. Do not add Tokio or a blanket `Send` bound to portable core. + +## Configuration + +| Entry point | Configuration | +| --- | --- | +| Standalone development or production | `EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES` | +| Explicit production hosting | `AxumRunOptions::with_json_body_limit_bytes(limit)` | +| Router-only serving | `AxumDevServer::with_json_body_limit_bytes(limit)` with either constructor | +| Low-level `into_core_request` converter | Finite 2 MiB default, no environment lookup | + +Standalone hosting captures the setting once, before application configuration and readiness. Omission uses the default. Explicit builders validate the limit when called. A supplied environment value is positive ASCII decimal bytes and must fit the collector's supported capacity. Reject zero, signs, whitespace, units, fractions, overflow, and non-Unicode values. Diagnostics identify the setting without echoing its value. No value disables the ceiling. The development runner still permits its existing unrelated omissions; explicit builders do not merge ambient settings. `AxumRunOptions::from_env` is the deliberate environment-driven choice. No manifest key, CLI flag, or reload behavior is added. + +The setting stays separate from `EDGEZERO__ADAPTER__INGRESS__*` and `AxumIngressConfig`. Those govern HTTP/1 listener and request-head mechanics before admission. This ceiling governs framework buffering after admission, including when the caller does not use the standard listener. It is not a framing limit. + +## Effective limit + +| Read | Effective limit on Axum | +| --- | --- | +| Ordinary `Json` or `ValidatedJson` | Configured ceiling, including an override above the portable 8 MiB default | +| `json_within` or `ValidatedJsonWithin` | Lower of the caller cap and native ceiling, regardless of Content-Type | +| `body_bytes`, `form_within`, Form family, pre-dispatch buffered reads | Lower of the caller cap and native ceiling on JSON-classified ingress; otherwise the existing caller cap | + +Ordinary Form still asks for at most 1 MiB. A ceiling above 1 MiB never raises that cap. Requests without an Axum policy use the existing portable defaults and explicit caps. The shared collector on the inspected base already returns typed 413 on body overflow, including for non-JSON generic reads and low-level bounded collection. #407 changes which cap applies on Axum, not how other overflows are classified. + +At conversion, capture the original JSON classification without reading any body bytes. Recognize `application/json` and application subtypes with a terminal `+json` suffix, case-insensitively, with valid parameters allowed. Classify from the first Content-Type field value. A missing or malformed value is not JSON for generic reads. JSON helpers apply the ceiling regardless. Classification never rejects a request or changes what JSON the handler can parse. + +```mermaid +flowchart TD + A[Validate the run setting] --> B[Existing head checks and admission] + B -->|Refused or aborted| C[Existing no-read path] + B -->|Admitted| D[Attach policy during lazy conversion] + D --> E{Body access} + E -->|Managed buffering| F[Resolve effective cap] + F --> G[Use existing collector or check cached bytes] + G -->|Drain overflow| H[Drop source and retain typed 413] + G -->|Success| I[Reuse cached bytes] + E -->|Taken stream or forwarding| J[Preserve incremental transfer] +``` + +## Ownership, cache, and lifecycle + +- Keep the existing `Body` struct and exhaustive `BodyPayload`. Private metadata carries the ceiling, ingress classification, and initial/cache provenance. The adapter attachment requires a validated host ceiling and never replaces an existing policy. Policy does not travel in a mutable header or extension. +- `RequestContext::into_request` followed by fresh or routed context construction preserves policy if the original body is retained. Changing headers, extensions or router state does not recapture the policy. Initial reconstruction does not poll the source. Cached reconstruction reuses the same allocation. Extracting raw bytes or a stream and building a replacement body deliberately sheds the metadata; a failed conversion that returns the original body does not. +- Where a reconstructed cache enters protected dispatch, the new dispatch's input guard still checks the deadline and fallback length and accounts for its original bytes once. A successful read completes that accounting before transforms. Repeat reads or later fallback discard do not charge output bytes or time out already completed input. The new dispatch does not inherit the old grant, guard, or completion. +- A failed initial drain keeps a sticky error. Preserve source-error categories, absolute deadline precedence, and the existing cancellation cleanup. Checking a tighter caller cap against intact cached bytes does not poison them. A fixed input guard failure is still sticky and must retain the existing application fallback outcome. +- `Body::into_parts` hands off the raw `BodyPayload` and exact optional egress owner without polling or copying. That raw handoff removes ingress metadata. No transport migration or change to response ownership is needed. Custom error rendering keeps the framework-mandated 413; cancellation before egress does not fabricate a response or completion report. + +The ceiling bounds logical body bytes retained by framework buffering. It does not bound allocation capacity, a chunk already delivered by the host, host/Hyper buffers, parsed JSON, handler allocations, concurrent requests, or process memory. A response handoff does not prove client receipt or keep-alive reuse. Keep the bounded close behavior inherited from #275 rather than adding another drain strategy here. + +## Compatibility and acceptance + +Existing Axum applications that buffer more than 2 MiB of JSON need an explicit host override. Explicit-cap reads on JSON ingress may now return 413 earlier even when their caller cap is larger. `Body`'s private layout and debug output change; its public struct/payload contract and exact egress ownership do not require a source migration. + +Prove the following against the actual hosting and dispatch paths where applicable. The plan maps these requirements to executable checks. + +- Valid JSON at the limit and one byte over, with handler invocation counts, for declared-length and chunked HTTP/1 uploads. Cover JSON/+json media types, parameters and mixed case; JSON extractors also work without a matching header. Verify non-JSON and taken JSON streams remain incremental. +- Smaller and larger overrides, including ordinary extraction above 8 MiB and configured router-only wire boundaries through both constructors. Invalid settings fail before application hooks in development and production; explicit embedding ignores ambient settings. +- Caller caps below and above the selected ceiling, generic and Form reads, and immutable classification through head mutation and actual router state injection. Cover initial and cached reconstruction above 8 MiB, no eager read, and cache reuse/non-poisoning rechecks. +- Existing admission-before-read and no-read refusal, abort and ordinary fallback paths. Verify protected cached re-entry preserves fixed fallback overflow/timeout and does not account for a transformed output as raw input. +- Overflow, source failure, and cancellation through managed Axum dispatch, with exact source release and no extra poll. Preserve timeout precedence, typed errors, custom error rendering and existing egress ownership where a response exists. +- Re-audit #275's collector, admission, fallback and egress paths and #406's hosting paths once the prerequisite stack is accepted. Repeat affected checks on the accepted integration. Provider runtime qualification, real deployment, and keeping every connection reusable after rejection are not claims of this issue. diff --git a/examples/app-demo/Cargo.lock b/examples/app-demo/Cargo.lock index f409cf47e..588e4a33d 100644 --- a/examples/app-demo/Cargo.lock +++ b/examples/app-demo/Cargo.lock @@ -793,6 +793,7 @@ dependencies = [ "hyper-util", "libc", "log", + "mime", "redb", "reqwest", "serde",