taler-rust

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

extract.rs (8710B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2025, 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use axum::{
     18     body::{Body, Bytes, HttpBody},
     19     extract::{FromRequest, FromRequestParts, Request},
     20     http::{
     21         HeaderMap, StatusCode,
     22         header::{self, CONTENT_TYPE},
     23         request::Parts,
     24     },
     25 };
     26 use http_body_util::BodyExt as _;
     27 use serde::de::DeserializeOwned;
     28 use taler_common::error_code::ErrorCode;
     29 use tracing::trace;
     30 use url::form_urlencoded;
     31 use zlib_rs::{Inflate, InflateConfig, InflateFlush, ReturnCode, Status};
     32 
     33 use crate::{
     34     constants::SAFE_BODY_LENGTH,
     35     error::{ApiError, ApiResult, failure, failure_status},
     36 };
     37 
     38 fn unsupported_media_type(message: impl std::fmt::Display) -> ApiError {
     39     failure_status(
     40         ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED,
     41         message,
     42         StatusCode::UNSUPPORTED_MEDIA_TYPE,
     43     )
     44 }
     45 
     46 /// Read and decompress a JSON request body, enforcing a maximum body length
     47 pub async fn decompressed_json_body<const MAX_LENGTH: usize>(
     48     headers: &HeaderMap,
     49     body: Body,
     50 ) -> ApiResult<Bytes> {
     51     let too_large = |body: &str| {
     52         failure(
     53             ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT,
     54             format!("{body} is suspiciously big > {MAX_LENGTH}B"),
     55         )
     56     };
     57 
     58     let Some(content_type) = headers.get(CONTENT_TYPE) else {
     59         return Err(unsupported_media_type("Missing Content-Type header"));
     60     };
     61     // JSON has no media type parameters that affect how we decode it.
     62     let media_type = content_type
     63         .as_bytes()
     64         .split(|&byte| byte == b';')
     65         .next()
     66         .unwrap();
     67     if !media_type
     68         .trim_ascii()
     69         .eq_ignore_ascii_case(b"application/json")
     70     {
     71         return Err(unsupported_media_type("Bad Content-Type header"));
     72     }
     73 
     74     // Check content length if present and well formed
     75     if let Some(length) = headers
     76         .get(header::CONTENT_LENGTH)
     77         .and_then(|it| it.to_str().ok())
     78         .and_then(|it| it.parse::<usize>().ok())
     79         && length > MAX_LENGTH
     80     {
     81         return Err(too_large("Body"));
     82     }
     83 
     84     // Check compression
     85     let compressed = if let Some(encoding) = headers.get(header::CONTENT_ENCODING) {
     86         if encoding == "deflate" {
     87             true
     88         } else {
     89             return Err(unsupported_media_type(format!(
     90                 "Unsupported encoding '{}'",
     91                 String::from_utf8_lossy(encoding.as_bytes())
     92             )));
     93         }
     94     } else {
     95         false
     96     };
     97 
     98     // Buffer body
     99     let body = http_body_util::Limited::new(body, MAX_LENGTH);
    100     let bytes = match body.collect().await {
    101         Ok(chunks) => chunks.to_bytes(),
    102         Err(it) => match it.downcast::<http_body_util::LengthLimitError>() {
    103             Ok(_) => {
    104                 return Err(too_large("Body"));
    105             }
    106             Err(err) => {
    107                 return Err(failure_status(
    108                     ErrorCode::GENERIC_UNEXPECTED_REQUEST_ERROR,
    109                     format!("Failed to read body: {err}"),
    110                     StatusCode::BAD_REQUEST,
    111                 ));
    112             }
    113         },
    114     };
    115 
    116     let bytes = if compressed {
    117         let invalid = || {
    118             failure(
    119                 ErrorCode::GENERIC_COMPRESSION_INVALID,
    120                 "Failed to decompress body: invalid compression",
    121             )
    122         };
    123         if MAX_LENGTH <= SAFE_BODY_LENGTH {
    124             let mut chunk = [0; SAFE_BODY_LENGTH];
    125             let (decoded, code) = zlib_rs::decompress_slice(
    126                 &mut chunk[..MAX_LENGTH],
    127                 &bytes,
    128                 InflateConfig::default(),
    129             );
    130             match code {
    131                 ReturnCode::Ok => Bytes::copy_from_slice(decoded),
    132                 ReturnCode::BufError => return Err(too_large("Decompressed body")),
    133                 _ => return Err(invalid()),
    134             }
    135         } else {
    136             // A zero window setting uses the history size advertised in the zlib header
    137             let mut decoder = Inflate::new(true, 0);
    138             // One extra byte distinguishes an exact fit from an oversized stream
    139             let ceiling = MAX_LENGTH.saturating_add(1);
    140             let mut output = vec![0; bytes.len().clamp(256, SAFE_BODY_LENGTH)];
    141             loop {
    142                 let consumed = decoder.total_in() as usize;
    143                 let written = decoder.total_out() as usize;
    144                 if written == output.len() {
    145                     output.resize(output.len().saturating_mul(2).min(ceiling), 0);
    146                 }
    147                 let status = decoder
    148                     .decompress(
    149                         &bytes[consumed..],
    150                         &mut output[written..],
    151                         InflateFlush::NoFlush,
    152                     )
    153                     .map_err(|_| invalid())?;
    154                 if decoder.total_out() > MAX_LENGTH as u64 {
    155                     return Err(too_large("Decompressed body"));
    156                 } else if status == Status::StreamEnd {
    157                     output.truncate(decoder.total_out() as usize);
    158                     break Bytes::from(output);
    159                 } else if written == decoder.total_out() as usize
    160                     && consumed == decoder.total_in() as usize
    161                 {
    162                     return Err(invalid());
    163                 }
    164             }
    165         }
    166     } else {
    167         bytes
    168     };
    169     trace!(target: "api", "req {}", String::from_utf8_lossy(&bytes));
    170     Ok(bytes)
    171 }
    172 
    173 #[derive(Debug, Clone, Copy, Default)]
    174 #[must_use]
    175 pub struct Req<T, const MAX_LENGTH: usize = SAFE_BODY_LENGTH>(pub T);
    176 
    177 impl<T, S, const MAX_LENGTH: usize> FromRequest<S> for Req<T, MAX_LENGTH>
    178 where
    179     T: DeserializeOwned,
    180     S: Send + Sync,
    181 {
    182     type Rejection = ApiError;
    183 
    184     async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
    185         let (parts, body) = req.into_parts();
    186         let bytes = decompressed_json_body::<MAX_LENGTH>(&parts.headers, body).await?;
    187 
    188         Self::try_from(&bytes)
    189     }
    190 }
    191 
    192 impl<T: DeserializeOwned, const MAX_LENGTH: usize> TryFrom<&Bytes> for Req<T, MAX_LENGTH> {
    193     type Error = ApiError;
    194 
    195     fn try_from(value: &Bytes) -> Result<Self, Self::Error> {
    196         let mut de = serde_json::de::Deserializer::from_slice(value);
    197         let parsed = serde_path_to_error::deserialize(&mut de)?;
    198         de.end()?;
    199         Ok(Req(parsed))
    200     }
    201 }
    202 
    203 #[derive(Debug, Clone, Copy, Default)]
    204 #[must_use]
    205 pub struct OptReq<T, const MAX_LENGTH: usize = SAFE_BODY_LENGTH>(pub Option<T>);
    206 
    207 impl<T, S, const MAX_LENGTH: usize> FromRequest<S> for OptReq<T, MAX_LENGTH>
    208 where
    209     T: DeserializeOwned,
    210     S: Send + Sync,
    211 {
    212     type Rejection = ApiError;
    213 
    214     async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
    215         let (parts, body) = req.into_parts();
    216         if !parts.headers.contains_key(CONTENT_TYPE) && body.size_hint().exact() == Some(0) {
    217             Ok(Self(None))
    218         } else {
    219             let bytes = decompressed_json_body::<MAX_LENGTH>(&parts.headers, body).await?;
    220             let req = Req::<T, MAX_LENGTH>::try_from(&bytes)?;
    221             Ok(Self(Some(req.0)))
    222         }
    223     }
    224 }
    225 
    226 #[derive(Debug, Clone, Copy, Default)]
    227 pub struct Path<T: DeserializeOwned + Send>(pub T);
    228 
    229 impl<T: serde::de::DeserializeOwned + Send, S: Sync + Send> FromRequestParts<S> for Path<T> {
    230     type Rejection = ApiError;
    231 
    232     async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
    233         Ok(Self(
    234             axum::extract::Path::from_request_parts(parts, &()).await?.0,
    235         ))
    236     }
    237 }
    238 
    239 #[derive(Debug, Clone, Copy, Default)]
    240 pub struct Query<T>(pub T);
    241 
    242 impl<T: serde::de::DeserializeOwned, S: Sync + Send> FromRequestParts<S> for Query<T> {
    243     type Rejection = ApiError;
    244 
    245     async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
    246         let query = parts.uri.query().unwrap_or_default();
    247         let deserializer =
    248             serde_urlencoded::Deserializer::new(form_urlencoded::parse(query.as_bytes()));
    249         let params = serde_path_to_error::deserialize(deserializer)?;
    250         Ok(Query(params))
    251     }
    252 }