|
| 1 | +//! JSON request bodies that may arrive gzip-encoded, decoded within a decompressed-size bound. |
| 2 | +
|
| 3 | +use std::io::{BufReader, Read}; |
| 4 | + |
| 5 | +use axum::http::{HeaderMap, StatusCode, header}; |
| 6 | +use flate2::read::MultiGzDecoder; |
| 7 | +use serde::de::DeserializeOwned; |
| 8 | + |
| 9 | +use crate::api::constants::{GZIP_ENCODING, IDENTITY_ENCODING, JSON_MEDIA_TYPE}; |
| 10 | +use crate::api::errors::ApiError; |
| 11 | +use crate::api::models::BoundedReader; |
| 12 | + |
| 13 | +/// `body` as JSON after its declared encoding; gzip streams into the parser and stops past `limit` bytes. |
| 14 | +pub(crate) fn request_json<T: DeserializeOwned>( |
| 15 | + headers: &HeaderMap, |
| 16 | + body: &[u8], |
| 17 | + limit: usize, |
| 18 | +) -> Result<T, ApiError> { |
| 19 | + if !json_content(headers) { |
| 20 | + return Err(rejection( |
| 21 | + StatusCode::UNSUPPORTED_MEDIA_TYPE, |
| 22 | + "expected an application/json body".into(), |
| 23 | + )); |
| 24 | + } |
| 25 | + match encodings(headers)?.as_slice() { |
| 26 | + [] => serde_json::from_slice(body).map_err(|error| parse_rejection(&error)), |
| 27 | + [encoding] if encoding == GZIP_ENCODING => { |
| 28 | + let mut reader = BoundedReader { |
| 29 | + inner: MultiGzDecoder::new(body), |
| 30 | + remaining: limit, |
| 31 | + exceeded: false, |
| 32 | + }; |
| 33 | + let parsed: Result<T, serde_json::Error> = |
| 34 | + serde_json::from_reader(BufReader::new(&mut reader)); |
| 35 | + match parsed { |
| 36 | + Ok(value) => Ok(value), |
| 37 | + Err(_) if reader.exceeded => Err(rejection( |
| 38 | + StatusCode::PAYLOAD_TOO_LARGE, |
| 39 | + format!("decompressed body exceeds {limit} bytes"), |
| 40 | + )), |
| 41 | + Err(error) if error.is_io() => Err(rejection( |
| 42 | + StatusCode::BAD_REQUEST, |
| 43 | + "request body is not valid gzip".into(), |
| 44 | + )), |
| 45 | + Err(error) => Err(parse_rejection(&error)), |
| 46 | + } |
| 47 | + } |
| 48 | + _ => Err(rejection( |
| 49 | + StatusCode::UNSUPPORTED_MEDIA_TYPE, |
| 50 | + "only gzip content encoding is accepted".into(), |
| 51 | + )), |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl<R: Read> Read for BoundedReader<R> { |
| 56 | + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> { |
| 57 | + let window = buffer.len().min(self.remaining.saturating_add(1)); |
| 58 | + let read = self.inner.read(&mut buffer[..window])?; |
| 59 | + if read > self.remaining { |
| 60 | + self.exceeded = true; |
| 61 | + return Err(std::io::Error::other("decompressed body exceeds its bound")); |
| 62 | + } |
| 63 | + self.remaining -= read; |
| 64 | + Ok(read) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fn json_content(headers: &HeaderMap) -> bool { |
| 69 | + let Some(value) = headers.get(header::CONTENT_TYPE) else { |
| 70 | + return false; |
| 71 | + }; |
| 72 | + let Ok(text) = value.to_str() else { |
| 73 | + return false; |
| 74 | + }; |
| 75 | + let essence: String = text |
| 76 | + .split(';') |
| 77 | + .next() |
| 78 | + .unwrap_or_default() |
| 79 | + .trim() |
| 80 | + .to_ascii_lowercase(); |
| 81 | + essence == JSON_MEDIA_TYPE |
| 82 | + || (essence.starts_with("application/") && essence.ends_with("+json")) |
| 83 | +} |
| 84 | + |
| 85 | +/// Declared encodings other than identity, in order; an unreadable header is refused. |
| 86 | +fn encodings(headers: &HeaderMap) -> Result<Vec<String>, ApiError> { |
| 87 | + let mut encodings: Vec<String> = Vec::new(); |
| 88 | + for value in headers.get_all(header::CONTENT_ENCODING) { |
| 89 | + let text = value.to_str().map_err(|_| { |
| 90 | + rejection( |
| 91 | + StatusCode::UNSUPPORTED_MEDIA_TYPE, |
| 92 | + "only gzip content encoding is accepted".into(), |
| 93 | + ) |
| 94 | + })?; |
| 95 | + encodings.extend( |
| 96 | + text.split(',') |
| 97 | + .map(|encoding| encoding.trim().to_ascii_lowercase()) |
| 98 | + .filter(|encoding| !encoding.is_empty() && encoding != IDENTITY_ENCODING), |
| 99 | + ); |
| 100 | + } |
| 101 | + Ok(encodings) |
| 102 | +} |
| 103 | + |
| 104 | +/// The statuses axum's JSON extractor uses: malformed JSON is 400, a wrong shape is 422. |
| 105 | +fn parse_rejection(error: &serde_json::Error) -> ApiError { |
| 106 | + if error.is_data() { |
| 107 | + rejection( |
| 108 | + StatusCode::UNPROCESSABLE_ENTITY, |
| 109 | + format!("Failed to deserialize the JSON body into the target type: {error}"), |
| 110 | + ) |
| 111 | + } else { |
| 112 | + rejection( |
| 113 | + StatusCode::BAD_REQUEST, |
| 114 | + format!("Failed to parse the request body as JSON: {error}"), |
| 115 | + ) |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +fn rejection(status: StatusCode, message: String) -> ApiError { |
| 120 | + ApiError { |
| 121 | + status, |
| 122 | + message, |
| 123 | + decision_id: None, |
| 124 | + } |
| 125 | +} |
0 commit comments