taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

commit 63da6ff6754fefdf7cfefbbef8f46401a2a426af
parent 2bf451c13fbc8c26bccfc2e38b35d06e9241443a
Author: Antoine A <>
Date:   Thu, 19 Nov 2026 11:11:12 +0100

common: make request body limit configurable

Diffstat:
Mcommon/taler-api/src/extract.rs | 191++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
1 file changed, 131 insertions(+), 60 deletions(-)

diff --git a/common/taler-api/src/extract.rs b/common/taler-api/src/extract.rs @@ -28,32 +28,36 @@ use serde::de::DeserializeOwned; use taler_common::error_code::ErrorCode; use tracing::trace; use url::form_urlencoded; -use zlib_rs::{InflateConfig, ReturnCode}; +use zlib_rs::{Inflate, InflateConfig, InflateFlush, ReturnCode, Status}; use crate::{ constants::MAX_BODY_LENGTH, error::{ApiError, ApiResult, failure, failure_status}, }; -pub async fn decompressed_strict_body(headers: &HeaderMap, body: Body) -> ApiResult<Bytes> { - // Check content type +fn unsupported_media_type(message: impl std::fmt::Display) -> ApiError { + failure_status( + ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED, + message, + StatusCode::UNSUPPORTED_MEDIA_TYPE, + ) +} + +pub async fn decompressed_strict_body<const MAX_SIZE: usize>( + headers: &HeaderMap, + body: Body, +) -> ApiResult<Bytes> { + let too_large = |body: &str| { + failure( + ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT, + format!("{body} is suspiciously big > {MAX_SIZE}B"), + ) + }; + match headers.get(header::CONTENT_TYPE) { - Some(header) => { - if header.as_bytes() != b"application/json" { - return Err(failure_status( - ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED, - "Bad Content-Type header", - StatusCode::UNSUPPORTED_MEDIA_TYPE, - )); - } - } - None => { - return Err(failure_status( - ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED, - "Missing Content-Type header", - StatusCode::UNSUPPORTED_MEDIA_TYPE, - )); - } + Some(value) if value.as_bytes() == b"application/json" => {} + Some(_) => return Err(unsupported_media_type("Bad Content-Type header")), + None => return Err(unsupported_media_type("Missing Content-Type header")), } // Check content length if present and well formed @@ -61,12 +65,9 @@ pub async fn decompressed_strict_body(headers: &HeaderMap, body: Body) -> ApiRes .get(header::CONTENT_LENGTH) .and_then(|it| it.to_str().ok()) .and_then(|it| it.parse::<usize>().ok()) - && length > MAX_BODY_LENGTH + && length > MAX_SIZE { - return Err(failure( - ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT, - format!("Body is suspiciously big > {MAX_BODY_LENGTH}B"), - )); + return Err(too_large("Body")); } // Check compression @@ -74,29 +75,22 @@ pub async fn decompressed_strict_body(headers: &HeaderMap, body: Body) -> ApiRes if encoding == "deflate" { true } else { - return Err(failure_status( - ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED, - format!( - "Unsupported encoding '{}'", - String::from_utf8_lossy(encoding.as_bytes()) - ), - StatusCode::UNSUPPORTED_MEDIA_TYPE, - )); + return Err(unsupported_media_type(format!( + "Unsupported encoding '{}'", + String::from_utf8_lossy(encoding.as_bytes()) + ))); } } else { false }; // Buffer body - let body = http_body_util::Limited::new(body, MAX_BODY_LENGTH); + let body = http_body_util::Limited::new(body, MAX_SIZE); let bytes = match body.collect().await { Ok(chunks) => chunks.to_bytes(), Err(it) => match it.downcast::<http_body_util::LengthLimitError>() { Ok(_) => { - return Err(failure( - ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT, - format!("Body is suspiciously big > {MAX_BODY_LENGTH}B"), - )); + return Err(too_large("Body")); } Err(err) => { return Err(failure( @@ -108,22 +102,50 @@ pub async fn decompressed_strict_body(headers: &HeaderMap, body: Body) -> ApiRes }; let bytes = if compressed { - let mut buf = [0; MAX_BODY_LENGTH]; - let (decompressed, code) = - zlib_rs::decompress_slice(&mut buf, &bytes, InflateConfig::default()); - match code { - ReturnCode::Ok => Bytes::copy_from_slice(decompressed), - ReturnCode::BufError => { - return Err(failure( - ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT, - format!("Decompressed body is suspiciously big > {MAX_BODY_LENGTH}B"), - )); + let invalid = || { + failure( + ErrorCode::GENERIC_COMPRESSION_INVALID, + "Failed to decompress body: invalid compression", + ) + }; + if MAX_SIZE <= MAX_BODY_LENGTH { + let mut chunk = [0; MAX_BODY_LENGTH]; + let (decoded, code) = + zlib_rs::decompress_slice(&mut chunk[..MAX_SIZE], &bytes, InflateConfig::default()); + match code { + ReturnCode::Ok => Bytes::copy_from_slice(decoded), + ReturnCode::BufError => return Err(too_large("Decompressed body")), + _ => return Err(invalid()), } - _ => { - return Err(failure( - ErrorCode::GENERIC_COMPRESSION_INVALID, - "Failed to decompress body: invalid compression", - )); + } else { + // A zero window setting uses the history size advertised in the zlib header + let mut decoder = Inflate::new(true, 0); + // One extra byte distinguishes an exact fit from an oversized stream + let ceiling = MAX_SIZE.saturating_add(1); + let mut output = vec![0; bytes.len().clamp(256, MAX_BODY_LENGTH)]; + loop { + let consumed = decoder.total_in() as usize; + let written = decoder.total_out() as usize; + if written == output.len() { + output.resize(output.len().saturating_mul(2).min(ceiling), 0); + } + let status = decoder + .decompress( + &bytes[consumed..], + &mut output[written..], + InflateFlush::NoFlush, + ) + .map_err(|_| invalid())?; + if decoder.total_out() > MAX_SIZE as u64 { + return Err(too_large("Decompressed body")); + } else if status == Status::StreamEnd { + output.truncate(decoder.total_out() as usize); + break Bytes::from(output); + } else if written == decoder.total_out() as usize + && consumed == decoder.total_in() as usize + { + return Err(invalid()); + } } } } else { @@ -135,9 +157,9 @@ pub async fn decompressed_strict_body(headers: &HeaderMap, body: Body) -> ApiRes #[derive(Debug, Clone, Copy, Default)] #[must_use] -pub struct Req<T>(pub T); +pub struct Req<T, const MAX_SIZE: usize = MAX_BODY_LENGTH>(pub T); -impl<T, S> FromRequest<S> for Req<T> +impl<T, S, const MAX_SIZE: usize> FromRequest<S> for Req<T, MAX_SIZE> where T: DeserializeOwned, S: Send + Sync, @@ -146,13 +168,13 @@ where async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> { let (parts, body) = req.into_parts(); - let bytes = decompressed_strict_body(&parts.headers, body).await?; + let bytes = decompressed_strict_body::<MAX_SIZE>(&parts.headers, body).await?; Self::try_from(&bytes) } } -impl<T: DeserializeOwned> TryFrom<&Bytes> for Req<T> { +impl<T: DeserializeOwned, const MAX_SIZE: usize> TryFrom<&Bytes> for Req<T, MAX_SIZE> { type Error = ApiError; fn try_from(value: &Bytes) -> Result<Self, Self::Error> { @@ -166,9 +188,9 @@ impl<T: DeserializeOwned> TryFrom<&Bytes> for Req<T> { #[derive(Debug, Clone, Copy, Default)] #[must_use] -pub struct OptReq<T>(pub Option<T>); +pub struct OptReq<T, const MAX_SIZE: usize = MAX_BODY_LENGTH>(pub Option<T>); -impl<T, S> FromRequest<S> for OptReq<T> +impl<T, S, const MAX_SIZE: usize> FromRequest<S> for OptReq<T, MAX_SIZE> where T: DeserializeOwned, S: Send + Sync, @@ -180,8 +202,8 @@ where if !parts.headers.contains_key(CONTENT_TYPE) && body.size_hint().exact() == Some(0) { Ok(Self(None)) } else { - let bytes = decompressed_strict_body(&parts.headers, body).await?; - let req = Req::try_from(&bytes)?; + let bytes = decompressed_strict_body::<MAX_SIZE>(&parts.headers, body).await?; + let req = Req::<T, MAX_SIZE>::try_from(&bytes)?; Ok(Self(Some(req.0))) } } @@ -214,3 +236,52 @@ impl<T: serde::de::DeserializeOwned, S: Sync + Send> FromRequestParts<S> for Que Ok(Query(params)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn configured_decompression_limit() { + const LIMIT: usize = 2 * MAX_BODY_LENGTH + 2; + let value = "x".repeat(LIMIT - 2); + let json = serde_json::to_vec(&value).unwrap(); + let mut buffer = vec![0; json.len()]; + let (compressed, code) = + zlib_rs::compress_slice(&mut buffer, &json, zlib_rs::DeflateConfig::default()); + assert_eq!(code, ReturnCode::Ok); + + let request = |data: &[u8]| { + Request::builder() + .header(header::CONTENT_TYPE, "application/json") + .header(header::CONTENT_ENCODING, "deflate") + .body(Body::from(data.to_vec())) + .unwrap() + }; + assert!( + Req::<String>::from_request(request(compressed), &()) + .await + .is_err() + ); + let req = request(compressed); + assert_eq!( + Req::<String, LIMIT>::from_request(req, &()) + .await + .unwrap() + .0, + value + ); + let req = request(compressed); + assert!( + OptReq::<String, { LIMIT - 1 }>::from_request(req, &()) + .await + .is_err() + ); + let truncated = request(&compressed[..compressed.len() - 1]); + assert!( + Req::<String, LIMIT>::from_request(truncated, &()) + .await + .is_err() + ); + } +}