taler-rust

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

commit cca31fd6bd8e04e16d92ecfe9dbd45eb38725a80
parent 0a2e37767d11194b28dda94a6669adb9502219c5
Author: Antoine A <>
Date:   Thu, 19 Nov 2026 13:16:43 +0100

taler-api: improve naming and documentation

Diffstat:
Mcommon/taler-api/src/constants.rs | 3++-
Mcommon/taler-api/src/extract.rs | 44++++++++++++++++++++++++--------------------
Mcommon/taler-api/src/test.rs | 4++--
3 files changed, 28 insertions(+), 23 deletions(-)

diff --git a/common/taler-api/src/constants.rs b/common/taler-api/src/constants.rs @@ -20,4 +20,5 @@ pub const WIRE_GATEWAY_API_VERSION: LibtoolVersion = LibtoolVersion::new(5, 0, 0 pub const PREPARED_TRANSFER_API_VERSION: LibtoolVersion = LibtoolVersion::new(1, 0, 0); pub const REVENUE_API_VERSION: LibtoolVersion = LibtoolVersion::new(1, 1, 1); pub const OBSERVABILITY_API_VERSION: LibtoolVersion = LibtoolVersion::new(0, 0, 0); -pub const MAX_BODY_LENGTH: usize = 4 * 1024; // 4kB +/// Default body length limit, suffices for most simple JSON requests and enables stack buffer optimization +pub const SAFE_BODY_LENGTH: usize = 4 * 1024; diff --git a/common/taler-api/src/extract.rs b/common/taler-api/src/extract.rs @@ -31,7 +31,7 @@ use url::form_urlencoded; use zlib_rs::{Inflate, InflateConfig, InflateFlush, ReturnCode, Status}; use crate::{ - constants::MAX_BODY_LENGTH, + constants::SAFE_BODY_LENGTH, error::{ApiError, ApiResult, failure, failure_status}, }; @@ -43,14 +43,15 @@ fn unsupported_media_type(message: impl std::fmt::Display) -> ApiError { ) } -pub async fn decompressed_strict_body<const MAX_SIZE: usize>( +/// Read and decompress a JSON request body, enforcing a maximum body length +pub async fn decompressed_json_body<const MAX_LENGTH: 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"), + format!("{body} is suspiciously big > {MAX_LENGTH}B"), ) }; @@ -75,7 +76,7 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( .get(header::CONTENT_LENGTH) .and_then(|it| it.to_str().ok()) .and_then(|it| it.parse::<usize>().ok()) - && length > MAX_SIZE + && length > MAX_LENGTH { return Err(too_large("Body")); } @@ -95,7 +96,7 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( }; // Buffer body - let body = http_body_util::Limited::new(body, MAX_SIZE); + let body = http_body_util::Limited::new(body, MAX_LENGTH); let bytes = match body.collect().await { Ok(chunks) => chunks.to_bytes(), Err(it) => match it.downcast::<http_body_util::LengthLimitError>() { @@ -119,10 +120,13 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( "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()); + if MAX_LENGTH <= SAFE_BODY_LENGTH { + let mut chunk = [0; SAFE_BODY_LENGTH]; + let (decoded, code) = zlib_rs::decompress_slice( + &mut chunk[..MAX_LENGTH], + &bytes, + InflateConfig::default(), + ); match code { ReturnCode::Ok => Bytes::copy_from_slice(decoded), ReturnCode::BufError => return Err(too_large("Decompressed body")), @@ -132,8 +136,8 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( // 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)]; + let ceiling = MAX_LENGTH.saturating_add(1); + let mut output = vec![0; bytes.len().clamp(256, SAFE_BODY_LENGTH)]; loop { let consumed = decoder.total_in() as usize; let written = decoder.total_out() as usize; @@ -147,7 +151,7 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( InflateFlush::NoFlush, ) .map_err(|_| invalid())?; - if decoder.total_out() > MAX_SIZE as u64 { + if decoder.total_out() > MAX_LENGTH as u64 { return Err(too_large("Decompressed body")); } else if status == Status::StreamEnd { output.truncate(decoder.total_out() as usize); @@ -168,9 +172,9 @@ pub async fn decompressed_strict_body<const MAX_SIZE: usize>( #[derive(Debug, Clone, Copy, Default)] #[must_use] -pub struct Req<T, const MAX_SIZE: usize = MAX_BODY_LENGTH>(pub T); +pub struct Req<T, const MAX_LENGTH: usize = SAFE_BODY_LENGTH>(pub T); -impl<T, S, const MAX_SIZE: usize> FromRequest<S> for Req<T, MAX_SIZE> +impl<T, S, const MAX_LENGTH: usize> FromRequest<S> for Req<T, MAX_LENGTH> where T: DeserializeOwned, S: Send + Sync, @@ -179,13 +183,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::<MAX_SIZE>(&parts.headers, body).await?; + let bytes = decompressed_json_body::<MAX_LENGTH>(&parts.headers, body).await?; Self::try_from(&bytes) } } -impl<T: DeserializeOwned, const MAX_SIZE: usize> TryFrom<&Bytes> for Req<T, MAX_SIZE> { +impl<T: DeserializeOwned, const MAX_LENGTH: usize> TryFrom<&Bytes> for Req<T, MAX_LENGTH> { type Error = ApiError; fn try_from(value: &Bytes) -> Result<Self, Self::Error> { @@ -198,9 +202,9 @@ impl<T: DeserializeOwned, const MAX_SIZE: usize> TryFrom<&Bytes> for Req<T, MAX_ #[derive(Debug, Clone, Copy, Default)] #[must_use] -pub struct OptReq<T, const MAX_SIZE: usize = MAX_BODY_LENGTH>(pub Option<T>); +pub struct OptReq<T, const MAX_LENGTH: usize = SAFE_BODY_LENGTH>(pub Option<T>); -impl<T, S, const MAX_SIZE: usize> FromRequest<S> for OptReq<T, MAX_SIZE> +impl<T, S, const MAX_LENGTH: usize> FromRequest<S> for OptReq<T, MAX_LENGTH> where T: DeserializeOwned, S: Send + Sync, @@ -212,8 +216,8 @@ where if !parts.headers.contains_key(CONTENT_TYPE) && body.size_hint().exact() == Some(0) { Ok(Self(None)) } else { - let bytes = decompressed_strict_body::<MAX_SIZE>(&parts.headers, body).await?; - let req = Req::<T, MAX_SIZE>::try_from(&bytes)?; + let bytes = decompressed_json_body::<MAX_LENGTH>(&parts.headers, body).await?; + let req = Req::<T, MAX_LENGTH>::try_from(&bytes)?; Ok(Self(Some(req.0))) } } diff --git a/common/taler-api/src/test.rs b/common/taler-api/src/test.rs @@ -55,7 +55,7 @@ use tokio::sync::watch::Sender; use crate::{ api::TalerRouter, auth::AuthMethod, - constants::MAX_BODY_LENGTH, + constants::SAFE_BODY_LENGTH, db::TypeHelper as _, test::{api::TestApi, db::notification_listener}, }; @@ -229,7 +229,7 @@ async fn body_parsing(db: PgPool) { let huge_body = TransferRequest { credit_account: payto(format!( "payto:://test?message={:A<1$}", - "payout", MAX_BODY_LENGTH + "payout", SAFE_BODY_LENGTH )), ..normal_body };