2021-01-09 13:17:19 +00:00
|
|
|
//! For JSON helper documentation, see [`Json`].
|
|
|
|
|
|
|
|
use std::{
|
|
|
|
fmt,
|
|
|
|
future::Future,
|
|
|
|
marker::PhantomData,
|
|
|
|
ops,
|
|
|
|
pin::Pin,
|
|
|
|
sync::Arc,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
2019-03-10 17:53:56 +00:00
|
|
|
|
2019-04-13 21:50:54 +00:00
|
|
|
use bytes::BytesMut;
|
2021-04-01 14:26:13 +00:00
|
|
|
use futures_core::{ready, stream::Stream as _};
|
2021-01-09 13:17:19 +00:00
|
|
|
use serde::{de::DeserializeOwned, Serialize};
|
2019-03-10 17:53:56 +00:00
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
use actix_http::Payload;
|
2019-03-10 17:53:56 +00:00
|
|
|
|
2021-06-19 19:21:13 +00:00
|
|
|
#[cfg(feature = "__compress")]
|
2019-04-13 21:50:54 +00:00
|
|
|
use crate::dev::Decompress;
|
2021-01-09 13:17:19 +00:00
|
|
|
use crate::{
|
2021-12-04 19:40:47 +00:00
|
|
|
body::EitherBody,
|
2021-01-09 13:17:19 +00:00
|
|
|
error::{Error, JsonPayloadError},
|
|
|
|
extract::FromRequest,
|
|
|
|
http::header::CONTENT_LENGTH,
|
|
|
|
request::HttpRequest,
|
|
|
|
web, HttpMessage, HttpResponse, Responder,
|
|
|
|
};
|
2019-03-10 17:53:56 +00:00
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// JSON extractor and responder.
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// `Json` has two uses: JSON responses, and extracting typed data from JSON request payloads.
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// # Extractor
|
|
|
|
/// To extract typed data from a request body, the inner type `T` must implement the
|
|
|
|
/// [`serde::Deserialize`] trait.
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
2021-09-11 15:48:47 +00:00
|
|
|
/// Use [`JsonConfig`] to configure extraction options.
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// ```
|
|
|
|
/// use actix_web::{post, web, App};
|
|
|
|
/// use serde::Deserialize;
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
/// struct Info {
|
|
|
|
/// username: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// /// deserialize `Info` from request's body
|
2021-01-09 13:17:19 +00:00
|
|
|
/// #[post("/")]
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index(info: web::Json<Info>) -> String {
|
2019-03-10 17:53:56 +00:00
|
|
|
/// format!("Welcome {}!", info.username)
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// # Responder
|
|
|
|
/// The `Json` type JSON formatted responses. A handler may return a value of type
|
|
|
|
/// `Json<T>` where `T` is the type of a structure to serialize into JSON. The type `T` must
|
|
|
|
/// implement [`serde::Serialize`].
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// ```
|
|
|
|
/// use actix_web::{post, web, HttpRequest};
|
|
|
|
/// use serde::Serialize;
|
2019-10-07 05:29:11 +00:00
|
|
|
///
|
2019-03-10 17:53:56 +00:00
|
|
|
/// #[derive(Serialize)]
|
2021-01-09 13:17:19 +00:00
|
|
|
/// struct Info {
|
2019-03-10 17:53:56 +00:00
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// #[post("/{name}")]
|
|
|
|
/// async fn index(req: HttpRequest) -> web::Json<Info> {
|
|
|
|
/// web::Json(Info {
|
|
|
|
/// name: req.match_info().get("name").unwrap().to_owned(),
|
|
|
|
/// })
|
2019-03-10 17:53:56 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-04-09 02:22:51 +00:00
|
|
|
#[derive(Debug)]
|
2019-03-10 17:53:56 +00:00
|
|
|
pub struct Json<T>(pub T);
|
|
|
|
|
|
|
|
impl<T> Json<T> {
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Unwrap into inner `T` value.
|
2019-03-10 17:53:56 +00:00
|
|
|
pub fn into_inner(self) -> T {
|
|
|
|
self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ops::Deref for Json<T> {
|
|
|
|
type Target = T;
|
|
|
|
|
|
|
|
fn deref(&self) -> &T {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ops::DerefMut for Json<T> {
|
|
|
|
fn deref_mut(&mut self) -> &mut T {
|
|
|
|
&mut self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-01 08:53:26 +00:00
|
|
|
impl<T: fmt::Display> fmt::Display for Json<T> {
|
2019-12-07 18:46:51 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2019-03-10 17:53:56 +00:00
|
|
|
fmt::Display::fmt(&self.0, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-01 08:53:26 +00:00
|
|
|
impl<T: Serialize> Serialize for Json<T> {
|
2021-03-07 22:11:39 +00:00
|
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
|
|
where
|
|
|
|
S: serde::Serializer,
|
|
|
|
{
|
|
|
|
self.0.serialize(serializer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Creates response with OK status code, correct content type header, and serialized JSON payload.
|
|
|
|
///
|
|
|
|
/// If serialization failed
|
2019-03-10 17:53:56 +00:00
|
|
|
impl<T: Serialize> Responder for Json<T> {
|
2021-12-04 19:40:47 +00:00
|
|
|
type Body = EitherBody<String>;
|
|
|
|
|
|
|
|
fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
|
2021-01-08 22:17:19 +00:00
|
|
|
match serde_json::to_string(&self.0) {
|
2021-12-04 19:40:47 +00:00
|
|
|
Ok(body) => match HttpResponse::Ok()
|
2021-01-09 13:17:19 +00:00
|
|
|
.content_type(mime::APPLICATION_JSON)
|
2021-12-04 19:40:47 +00:00
|
|
|
.message_body(body)
|
|
|
|
{
|
|
|
|
Ok(res) => res.map_into_left_body(),
|
|
|
|
Err(err) => HttpResponse::from_error(err).map_into_right_body(),
|
|
|
|
},
|
|
|
|
|
|
|
|
Err(err) => {
|
|
|
|
HttpResponse::from_error(JsonPayloadError::Serialize(err)).map_into_right_body()
|
|
|
|
}
|
2021-01-08 22:17:19 +00:00
|
|
|
}
|
2019-03-10 17:53:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// See [here](#extractor) for example of usage as an extractor.
|
2021-09-11 16:27:50 +00:00
|
|
|
impl<T: DeserializeOwned> FromRequest for Json<T> {
|
2019-03-10 17:53:56 +00:00
|
|
|
type Error = Error;
|
2020-12-16 23:34:33 +00:00
|
|
|
type Future = JsonExtractFut<T>;
|
2019-03-10 17:53:56 +00:00
|
|
|
|
|
|
|
#[inline]
|
2019-04-13 21:50:54 +00:00
|
|
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
2020-09-02 21:12:07 +00:00
|
|
|
let config = JsonConfig::from_req(req);
|
|
|
|
|
|
|
|
let limit = config.limit;
|
2021-09-11 16:27:50 +00:00
|
|
|
let ctype_required = config.content_type_required;
|
|
|
|
let ctype_fn = config.content_type.as_deref();
|
2020-09-02 21:12:07 +00:00
|
|
|
let err_handler = config.err_handler.clone();
|
2019-03-10 17:53:56 +00:00
|
|
|
|
2020-12-16 23:34:33 +00:00
|
|
|
JsonExtractFut {
|
|
|
|
req: Some(req.clone()),
|
2021-09-11 16:27:50 +00:00
|
|
|
fut: JsonBody::new(req, payload, ctype_fn, ctype_required).limit(limit),
|
2020-12-16 23:34:33 +00:00
|
|
|
err_handler,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type JsonErrorHandler =
|
|
|
|
Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>;
|
|
|
|
|
|
|
|
pub struct JsonExtractFut<T> {
|
|
|
|
req: Option<HttpRequest>,
|
|
|
|
fut: JsonBody<T>,
|
|
|
|
err_handler: JsonErrorHandler,
|
|
|
|
}
|
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
impl<T: DeserializeOwned> Future for JsonExtractFut<T> {
|
2020-12-16 23:34:33 +00:00
|
|
|
type Output = Result<Json<T>, Error>;
|
|
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
|
|
let this = self.get_mut();
|
|
|
|
|
|
|
|
let res = ready!(Pin::new(&mut this.fut).poll(cx));
|
|
|
|
|
|
|
|
let res = match res {
|
2021-01-09 13:17:19 +00:00
|
|
|
Err(err) => {
|
2020-12-16 23:34:33 +00:00
|
|
|
let req = this.req.take().unwrap();
|
|
|
|
log::debug!(
|
|
|
|
"Failed to deserialize Json from payload. \
|
2019-06-28 04:44:53 +00:00
|
|
|
Request path: {}",
|
2020-12-16 23:34:33 +00:00
|
|
|
req.path()
|
|
|
|
);
|
2020-09-02 21:12:07 +00:00
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
if let Some(err_handler) = this.err_handler.as_ref() {
|
|
|
|
Err((*err_handler)(err, &req))
|
2020-12-16 23:34:33 +00:00
|
|
|
} else {
|
2021-01-09 13:17:19 +00:00
|
|
|
Err(err.into())
|
2019-11-20 17:33:22 +00:00
|
|
|
}
|
2020-12-16 23:34:33 +00:00
|
|
|
}
|
|
|
|
Ok(data) => Ok(Json(data)),
|
|
|
|
};
|
|
|
|
|
|
|
|
Poll::Ready(res)
|
2019-03-10 17:53:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// `Json` extractor configuration.
|
2020-03-16 23:23:54 +00:00
|
|
|
///
|
2021-02-10 12:10:03 +00:00
|
|
|
/// # Examples
|
2021-01-09 13:17:19 +00:00
|
|
|
/// ```
|
|
|
|
/// use actix_web::{error, post, web, App, FromRequest, HttpResponse};
|
|
|
|
/// use serde::Deserialize;
|
2019-03-10 17:53:56 +00:00
|
|
|
///
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
/// struct Info {
|
2021-01-09 13:17:19 +00:00
|
|
|
/// name: String,
|
2019-03-10 17:53:56 +00:00
|
|
|
/// }
|
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// // `Json` extraction is bound by custom `JsonConfig` applied to App.
|
|
|
|
/// #[post("/")]
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index(info: web::Json<Info>) -> String {
|
2021-01-09 13:17:19 +00:00
|
|
|
/// format!("Welcome {}!", info.name)
|
2019-03-10 17:53:56 +00:00
|
|
|
/// }
|
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// // custom `Json` extractor configuration
|
|
|
|
/// let json_cfg = web::JsonConfig::default()
|
|
|
|
/// // limit request payload size
|
|
|
|
/// .limit(4096)
|
|
|
|
/// // only accept text/plain content type
|
|
|
|
/// .content_type(|mime| mime == mime::TEXT_PLAIN)
|
|
|
|
/// // use custom error handler
|
|
|
|
/// .error_handler(|err, req| {
|
2021-04-09 17:07:10 +00:00
|
|
|
/// error::InternalError::from_response(err, HttpResponse::Conflict().into()).into()
|
2021-01-09 13:17:19 +00:00
|
|
|
/// });
|
2020-09-10 14:40:20 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// App::new()
|
|
|
|
/// .app_data(json_cfg)
|
|
|
|
/// .service(index);
|
|
|
|
/// ```
|
2019-03-10 17:53:56 +00:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct JsonConfig {
|
|
|
|
limit: usize,
|
2020-12-16 23:34:33 +00:00
|
|
|
err_handler: JsonErrorHandler,
|
2019-06-12 10:45:05 +00:00
|
|
|
content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
|
2021-09-11 16:27:50 +00:00
|
|
|
content_type_required: bool,
|
2019-03-10 17:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl JsonConfig {
|
2021-06-16 14:52:49 +00:00
|
|
|
/// Set maximum accepted payload size. By default this limit is 2MB.
|
2019-03-10 17:53:56 +00:00
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Set custom error handler.
|
2019-03-10 17:53:56 +00:00
|
|
|
pub fn error_handler<F>(mut self, f: F) -> Self
|
|
|
|
where
|
2019-05-13 03:04:08 +00:00
|
|
|
F: Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync + 'static,
|
2019-03-10 17:53:56 +00:00
|
|
|
{
|
2020-09-02 21:12:07 +00:00
|
|
|
self.err_handler = Some(Arc::new(f));
|
2019-03-10 17:53:56 +00:00
|
|
|
self
|
|
|
|
}
|
2019-06-12 10:45:05 +00:00
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Set predicate for allowed content types.
|
2019-06-12 10:45:05 +00:00
|
|
|
pub fn content_type<F>(mut self, predicate: F) -> Self
|
|
|
|
where
|
|
|
|
F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
|
|
|
|
{
|
|
|
|
self.content_type = Some(Arc::new(predicate));
|
|
|
|
self
|
|
|
|
}
|
2020-09-02 21:12:07 +00:00
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
/// Sets whether or not the request must have a `Content-Type` header to be parsed.
|
|
|
|
pub fn content_type_required(mut self, content_type_required: bool) -> Self {
|
|
|
|
self.content_type_required = content_type_required;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-09-02 21:12:07 +00:00
|
|
|
/// Extract payload config from app data. Check both `T` and `Data<T>`, in that order, and fall
|
|
|
|
/// back to the default payload config.
|
|
|
|
fn from_req(req: &HttpRequest) -> &Self {
|
|
|
|
req.app_data::<Self>()
|
|
|
|
.or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
|
2020-10-01 09:19:09 +00:00
|
|
|
.unwrap_or(&DEFAULT_CONFIG)
|
2020-09-02 21:12:07 +00:00
|
|
|
}
|
2019-03-10 17:53:56 +00:00
|
|
|
}
|
|
|
|
|
2021-06-16 14:52:49 +00:00
|
|
|
const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb
|
|
|
|
|
2021-01-15 05:38:50 +00:00
|
|
|
/// Allow shared refs used as default.
|
2020-09-02 21:12:07 +00:00
|
|
|
const DEFAULT_CONFIG: JsonConfig = JsonConfig {
|
2021-06-16 14:52:49 +00:00
|
|
|
limit: DEFAULT_LIMIT,
|
2020-09-02 21:12:07 +00:00
|
|
|
err_handler: None,
|
|
|
|
content_type: None,
|
2021-09-11 16:27:50 +00:00
|
|
|
content_type_required: true,
|
2020-09-02 21:12:07 +00:00
|
|
|
};
|
|
|
|
|
2019-03-10 17:53:56 +00:00
|
|
|
impl Default for JsonConfig {
|
|
|
|
fn default() -> Self {
|
2020-09-02 21:12:07 +00:00
|
|
|
DEFAULT_CONFIG.clone()
|
2019-03-10 17:53:56 +00:00
|
|
|
}
|
|
|
|
}
|
2019-03-17 05:04:09 +00:00
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Future that resolves to some `T` when parsed from a JSON payload.
|
2019-03-17 05:04:09 +00:00
|
|
|
///
|
2021-09-11 16:27:50 +00:00
|
|
|
/// Can deserialize any type `T` that implements [`Deserialize`][serde::Deserialize].
|
2019-03-17 05:04:09 +00:00
|
|
|
///
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Returns error if:
|
2021-09-11 16:27:50 +00:00
|
|
|
/// - `Content-Type` is not `application/json` when `ctype_required` (passed to [`new`][Self::new])
|
|
|
|
/// is `true`.
|
|
|
|
/// - `Content-Length` is greater than [limit](JsonBody::limit()).
|
|
|
|
/// - The payload, when consumed, is not valid JSON.
|
2021-01-09 13:17:19 +00:00
|
|
|
pub enum JsonBody<T> {
|
2020-12-16 23:34:33 +00:00
|
|
|
Error(Option<JsonPayloadError>),
|
|
|
|
Body {
|
|
|
|
limit: usize,
|
2021-09-11 16:27:50 +00:00
|
|
|
/// Length as reported by `Content-Length` header, if present.
|
2020-12-16 23:34:33 +00:00
|
|
|
length: Option<usize>,
|
2021-06-19 19:21:13 +00:00
|
|
|
#[cfg(feature = "__compress")]
|
2020-12-16 23:34:33 +00:00
|
|
|
payload: Decompress<Payload>,
|
2021-06-19 19:21:13 +00:00
|
|
|
#[cfg(not(feature = "__compress"))]
|
2020-12-16 23:34:33 +00:00
|
|
|
payload: Payload,
|
|
|
|
buf: BytesMut,
|
2021-01-09 13:17:19 +00:00
|
|
|
_res: PhantomData<T>,
|
2020-12-16 23:34:33 +00:00
|
|
|
},
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
|
2021-01-09 13:17:19 +00:00
|
|
|
impl<T> Unpin for JsonBody<T> {}
|
2020-12-16 23:34:33 +00:00
|
|
|
|
2021-09-01 08:53:26 +00:00
|
|
|
impl<T: DeserializeOwned> JsonBody<T> {
|
2021-01-09 13:17:19 +00:00
|
|
|
/// Create a new future to decode a JSON request payload.
|
2020-06-22 19:09:48 +00:00
|
|
|
#[allow(clippy::borrow_interior_mutable_const)]
|
2019-06-12 10:45:05 +00:00
|
|
|
pub fn new(
|
|
|
|
req: &HttpRequest,
|
|
|
|
payload: &mut Payload,
|
2021-09-11 16:27:50 +00:00
|
|
|
ctype_fn: Option<&(dyn Fn(mime::Mime) -> bool + Send + Sync)>,
|
|
|
|
ctype_required: bool,
|
2019-06-12 10:45:05 +00:00
|
|
|
) -> Self {
|
2019-03-17 05:04:09 +00:00
|
|
|
// check content-type
|
2021-09-11 16:27:50 +00:00
|
|
|
let can_parse_json = if let Ok(Some(mime)) = req.mime_type() {
|
2019-06-12 10:45:05 +00:00
|
|
|
mime.subtype() == mime::JSON
|
|
|
|
|| mime.suffix() == Some(mime::JSON)
|
2021-09-11 16:27:50 +00:00
|
|
|
|| ctype_fn.map_or(false, |predicate| predicate(mime))
|
2019-03-17 05:04:09 +00:00
|
|
|
} else {
|
2021-09-11 16:27:50 +00:00
|
|
|
// if `ctype_required` is false, assume payload is
|
|
|
|
// json even when content-type header is missing
|
|
|
|
!ctype_required
|
2019-03-17 05:04:09 +00:00
|
|
|
};
|
2019-06-12 10:45:05 +00:00
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
if !can_parse_json {
|
2020-12-16 23:34:33 +00:00
|
|
|
return JsonBody::Error(Some(JsonPayloadError::ContentType));
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
|
2020-12-16 23:34:33 +00:00
|
|
|
let length = req
|
2019-06-28 04:44:53 +00:00
|
|
|
.headers()
|
|
|
|
.get(&CONTENT_LENGTH)
|
|
|
|
.and_then(|l| l.to_str().ok())
|
|
|
|
.and_then(|s| s.parse::<usize>().ok());
|
2019-12-15 07:28:54 +00:00
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
// Notice the content-length is not checked against limit of json config here.
|
2020-12-16 23:34:33 +00:00
|
|
|
// As the internal usage always call JsonBody::limit after JsonBody::new.
|
|
|
|
// And limit check to return an error variant of JsonBody happens there.
|
|
|
|
|
2021-06-19 19:21:13 +00:00
|
|
|
let payload = {
|
|
|
|
cfg_if::cfg_if! {
|
|
|
|
if #[cfg(feature = "__compress")] {
|
|
|
|
Decompress::from_headers(payload.take(), req.headers())
|
|
|
|
} else {
|
|
|
|
payload.take()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-03-17 05:04:09 +00:00
|
|
|
|
2020-12-16 23:34:33 +00:00
|
|
|
JsonBody::Body {
|
2021-06-16 14:52:49 +00:00
|
|
|
limit: DEFAULT_LIMIT,
|
2020-12-16 23:34:33 +00:00
|
|
|
length,
|
|
|
|
payload,
|
|
|
|
buf: BytesMut::with_capacity(8192),
|
|
|
|
_res: PhantomData,
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-16 14:52:49 +00:00
|
|
|
/// Set maximum accepted payload size. The default limit is 2MB.
|
2020-12-16 23:34:33 +00:00
|
|
|
pub fn limit(self, limit: usize) -> Self {
|
|
|
|
match self {
|
|
|
|
JsonBody::Body {
|
|
|
|
length,
|
|
|
|
payload,
|
|
|
|
buf,
|
|
|
|
..
|
|
|
|
} => {
|
|
|
|
if let Some(len) = length {
|
|
|
|
if len > limit {
|
2021-06-16 14:52:49 +00:00
|
|
|
return JsonBody::Error(Some(JsonPayloadError::OverflowKnownLength {
|
|
|
|
length: len,
|
|
|
|
limit,
|
|
|
|
}));
|
2020-12-16 23:34:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
JsonBody::Body {
|
|
|
|
limit,
|
|
|
|
length,
|
|
|
|
payload,
|
|
|
|
buf,
|
|
|
|
_res: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
JsonBody::Error(e) => JsonBody::Error(e),
|
|
|
|
}
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
impl<T: DeserializeOwned> Future for JsonBody<T> {
|
2021-01-09 13:17:19 +00:00
|
|
|
type Output = Result<T, JsonPayloadError>;
|
2019-03-17 05:04:09 +00:00
|
|
|
|
2020-12-16 23:34:33 +00:00
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
|
|
let this = self.get_mut();
|
|
|
|
|
|
|
|
match this {
|
|
|
|
JsonBody::Body {
|
|
|
|
limit,
|
|
|
|
buf,
|
|
|
|
payload,
|
|
|
|
..
|
|
|
|
} => loop {
|
|
|
|
let res = ready!(Pin::new(&mut *payload).poll_next(cx));
|
|
|
|
match res {
|
|
|
|
Some(chunk) => {
|
|
|
|
let chunk = chunk?;
|
2021-06-16 14:52:49 +00:00
|
|
|
let buf_len = buf.len() + chunk.len();
|
|
|
|
if buf_len > *limit {
|
|
|
|
return Poll::Ready(Err(JsonPayloadError::Overflow {
|
|
|
|
limit: *limit,
|
|
|
|
}));
|
2020-12-16 23:34:33 +00:00
|
|
|
} else {
|
|
|
|
buf.extend_from_slice(&chunk);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None => {
|
2021-08-13 17:49:58 +00:00
|
|
|
let json = serde_json::from_slice::<T>(buf)
|
2021-04-12 09:30:28 +00:00
|
|
|
.map_err(JsonPayloadError::Deserialize)?;
|
2020-12-16 23:34:33 +00:00
|
|
|
return Poll::Ready(Ok(json));
|
2019-11-20 17:33:22 +00:00
|
|
|
}
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
2020-12-16 23:34:33 +00:00
|
|
|
},
|
|
|
|
JsonBody::Error(e) => Poll::Ready(Err(e.take().unwrap())),
|
|
|
|
}
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use bytes::Bytes;
|
2021-01-09 13:17:19 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2019-03-17 05:04:09 +00:00
|
|
|
|
|
|
|
use super::*;
|
2021-01-09 13:17:19 +00:00
|
|
|
use crate::{
|
2021-12-15 01:44:51 +00:00
|
|
|
body,
|
2021-01-09 13:17:19 +00:00
|
|
|
error::InternalError,
|
|
|
|
http::{
|
2021-01-15 02:11:10 +00:00
|
|
|
header::{self, CONTENT_LENGTH, CONTENT_TYPE},
|
2021-01-09 13:17:19 +00:00
|
|
|
StatusCode,
|
|
|
|
},
|
2021-12-15 01:44:51 +00:00
|
|
|
test::{assert_body_eq, TestRequest},
|
2021-01-09 13:17:19 +00:00
|
|
|
};
|
2019-03-17 05:04:09 +00:00
|
|
|
|
2019-03-17 16:52:41 +00:00
|
|
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
|
|
|
struct MyObject {
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
2019-03-17 05:04:09 +00:00
|
|
|
fn json_eq(err: JsonPayloadError, other: JsonPayloadError) -> bool {
|
|
|
|
match err {
|
2021-06-16 14:52:49 +00:00
|
|
|
JsonPayloadError::Overflow { .. } => {
|
|
|
|
matches!(other, JsonPayloadError::Overflow { .. })
|
|
|
|
}
|
|
|
|
JsonPayloadError::OverflowKnownLength { .. } => {
|
|
|
|
matches!(other, JsonPayloadError::OverflowKnownLength { .. })
|
|
|
|
}
|
2021-02-28 18:17:08 +00:00
|
|
|
JsonPayloadError::ContentType => matches!(other, JsonPayloadError::ContentType),
|
2019-03-17 05:04:09 +00:00
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_responder() {
|
|
|
|
let req = TestRequest::default().to_http_request();
|
|
|
|
|
|
|
|
let j = Json(MyObject {
|
|
|
|
name: "test".to_string(),
|
|
|
|
});
|
2021-12-04 19:40:47 +00:00
|
|
|
let res = j.respond_to(&req);
|
|
|
|
assert_eq!(res.status(), StatusCode::OK);
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(
|
2021-12-04 19:40:47 +00:00
|
|
|
res.headers().get(header::CONTENT_TYPE).unwrap(),
|
2019-11-26 05:25:50 +00:00
|
|
|
header::HeaderValue::from_static("application/json")
|
|
|
|
);
|
2021-12-04 19:40:47 +00:00
|
|
|
assert_body_eq!(res, b"{\"name\":\"test\"}");
|
2019-04-10 19:43:31 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_custom_error_responder() {
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-11-26 05:25:50 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2019-12-20 11:13:09 +00:00
|
|
|
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
2019-11-26 05:25:50 +00:00
|
|
|
let msg = MyObject {
|
|
|
|
name: "invalid request".to_string(),
|
|
|
|
};
|
2021-02-11 23:03:17 +00:00
|
|
|
let resp =
|
|
|
|
HttpResponse::BadRequest().body(serde_json::to_string(&msg).unwrap());
|
2021-06-17 16:57:58 +00:00
|
|
|
InternalError::from_response(err, resp).into()
|
2019-11-26 05:25:50 +00:00
|
|
|
}))
|
|
|
|
.to_http_parts();
|
2019-03-17 16:52:41 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
2021-05-09 19:12:48 +00:00
|
|
|
let resp = HttpResponse::from_error(s.err().unwrap());
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
|
|
|
|
2021-12-15 01:44:51 +00:00
|
|
|
let body = body::to_bytes(resp.into_body()).await.unwrap();
|
2019-11-26 05:25:50 +00:00
|
|
|
let msg: MyObject = serde_json::from_slice(&body).unwrap();
|
|
|
|
assert_eq!(msg.name, "invalid request");
|
2019-11-20 17:33:22 +00:00
|
|
|
}
|
2019-03-17 16:52:41 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_extract() {
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-03-17 16:52:41 +00:00
|
|
|
header::CONTENT_TYPE,
|
2019-11-26 05:25:50 +00:00
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-03-17 16:52:41 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-03-17 16:52:41 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2019-04-07 21:43:07 +00:00
|
|
|
.to_http_parts();
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await.unwrap();
|
|
|
|
assert_eq!(s.name, "test");
|
|
|
|
assert_eq!(
|
|
|
|
s.into_inner(),
|
|
|
|
MyObject {
|
|
|
|
name: "test".to_string()
|
|
|
|
}
|
|
|
|
);
|
2019-03-17 16:52:41 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-03-17 16:52:41 +00:00
|
|
|
header::CONTENT_TYPE,
|
2019-11-26 05:25:50 +00:00
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-03-17 16:52:41 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-03-17 16:52:41 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2019-12-20 11:13:09 +00:00
|
|
|
.app_data(JsonConfig::default().limit(10))
|
2019-04-07 21:43:07 +00:00
|
|
|
.to_http_parts();
|
2019-11-20 17:33:22 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(format!("{}", s.err().unwrap())
|
2021-06-16 14:52:49 +00:00
|
|
|
.contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes)."));
|
2019-11-26 05:25:50 +00:00
|
|
|
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-11-26 05:25:50 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2019-12-20 11:13:09 +00:00
|
|
|
.app_data(
|
2019-11-26 05:25:50 +00:00
|
|
|
JsonConfig::default()
|
|
|
|
.limit(10)
|
|
|
|
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
|
|
|
)
|
|
|
|
.to_http_parts();
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(format!("{}", s.err().unwrap()).contains("Content type error"));
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_json_body() {
|
|
|
|
let (req, mut pl) = TestRequest::default().to_http_parts();
|
2021-09-11 16:27:50 +00:00
|
|
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
|
|
|
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-03-17 05:04:09 +00:00
|
|
|
header::CONTENT_TYPE,
|
2019-11-26 05:25:50 +00:00
|
|
|
header::HeaderValue::from_static("application/text"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-11-26 05:25:50 +00:00
|
|
|
.to_http_parts();
|
2021-09-11 16:27:50 +00:00
|
|
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
|
|
|
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("10000"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-11-26 05:25:50 +00:00
|
|
|
.to_http_parts();
|
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true)
|
2019-11-26 05:25:50 +00:00
|
|
|
.limit(100)
|
|
|
|
.await;
|
2021-06-16 14:52:49 +00:00
|
|
|
assert!(json_eq(
|
|
|
|
json.err().unwrap(),
|
|
|
|
JsonPayloadError::OverflowKnownLength {
|
|
|
|
length: 10000,
|
|
|
|
limit: 100
|
|
|
|
}
|
|
|
|
));
|
|
|
|
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
|
|
|
))
|
|
|
|
.set_payload(Bytes::from_static(&[0u8; 1000]))
|
|
|
|
.to_http_parts();
|
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true)
|
2021-06-16 14:52:49 +00:00
|
|
|
.limit(100)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
assert!(json_eq(
|
|
|
|
json.err().unwrap(),
|
|
|
|
JsonPayloadError::Overflow { limit: 100 }
|
|
|
|
));
|
2019-11-26 05:25:50 +00:00
|
|
|
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((
|
2019-11-26 05:25:50 +00:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
|
|
|
.insert_header((
|
2019-03-17 05:04:09 +00:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2021-01-15 02:11:10 +00:00
|
|
|
))
|
2019-03-17 05:04:09 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2019-04-07 21:43:07 +00:00
|
|
|
.to_http_parts();
|
2019-03-17 05:04:09 +00:00
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(
|
|
|
|
json.ok().unwrap(),
|
|
|
|
MyObject {
|
|
|
|
name: "test".to_owned()
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_with_json_and_bad_content_type() {
|
2021-01-15 02:11:10 +00:00
|
|
|
let (req, mut pl) = TestRequest::default()
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("text/plain"),
|
|
|
|
))
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
|
|
|
))
|
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
|
|
|
.app_data(JsonConfig::default().limit(4096))
|
|
|
|
.to_http_parts();
|
2019-11-26 05:25:50 +00:00
|
|
|
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(s.is_err())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_with_json_and_good_custom_content_type() {
|
2021-01-15 02:11:10 +00:00
|
|
|
let (req, mut pl) = TestRequest::default()
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("text/plain"),
|
|
|
|
))
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
|
|
|
))
|
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
|
|
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
|
|
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
|
|
|
}))
|
|
|
|
.to_http_parts();
|
2019-11-26 05:25:50 +00:00
|
|
|
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(s.is_ok())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_with_json_and_bad_custom_content_type() {
|
2021-01-15 02:11:10 +00:00
|
|
|
let (req, mut pl) = TestRequest::default()
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("text/html"),
|
|
|
|
))
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
|
|
|
))
|
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
|
|
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
|
|
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
|
|
|
}))
|
|
|
|
.to_http_parts();
|
2019-11-26 05:25:50 +00:00
|
|
|
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(s.is_err())
|
2019-06-12 10:45:05 +00:00
|
|
|
}
|
2020-09-02 21:12:07 +00:00
|
|
|
|
2021-09-11 16:27:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_json_with_no_content_type() {
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
|
|
|
.insert_header((
|
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
|
|
|
))
|
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
|
|
|
.app_data(JsonConfig::default().content_type_required(false))
|
|
|
|
.to_http_parts();
|
|
|
|
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(s.is_ok())
|
|
|
|
}
|
|
|
|
|
2020-09-02 21:12:07 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_with_config_in_data_wrapper() {
|
|
|
|
let (req, mut pl) = TestRequest::default()
|
2021-01-15 02:11:10 +00:00
|
|
|
.insert_header((CONTENT_TYPE, mime::APPLICATION_JSON))
|
|
|
|
.insert_header((CONTENT_LENGTH, 16))
|
2020-09-02 21:12:07 +00:00
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
|
|
|
.app_data(web::Data::new(JsonConfig::default().limit(10)))
|
|
|
|
.to_http_parts();
|
|
|
|
|
|
|
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
|
|
|
assert!(s.is_err());
|
|
|
|
|
|
|
|
let err_str = s.err().unwrap().to_string();
|
2021-06-16 14:52:49 +00:00
|
|
|
assert!(err_str
|
|
|
|
.contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes)."));
|
2020-09-02 21:12:07 +00:00
|
|
|
}
|
2019-03-17 05:04:09 +00:00
|
|
|
}
|