1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00
actix-web/src/types/form.rs

509 lines
15 KiB
Rust
Raw Normal View History

//! For URL encoded form helper documentation, see [`Form`].
use std::{
fmt,
future::Future,
ops,
pin::Pin,
rc::Rc,
task::{Context, Poll},
};
use actix_http::Payload;
use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8};
use futures_util::{
future::{FutureExt, LocalBoxFuture},
StreamExt,
};
use serde::{de::DeserializeOwned, Serialize};
2019-12-15 07:28:54 +00:00
#[cfg(feature = "compress")]
use crate::dev::Decompress;
use crate::{
2021-02-11 23:03:17 +00:00
error::UrlencodedError, extract::FromRequest, http::header::CONTENT_LENGTH, web, Error,
HttpMessage, HttpRequest, HttpResponse, Responder,
2019-07-20 11:55:52 +00:00
};
/// URL encoded payload extractor and responder.
2019-07-20 11:55:52 +00:00
///
/// `Form` has two uses: URL encoded responses, and extracting typed data from URL request payloads.
2019-07-20 11:55:52 +00:00
///
/// # Extractor
/// To extract typed data from a request body, the inner type `T` must implement the
/// [`serde::Deserialize`] trait.
///
/// Use [`FormConfig`] to configure extraction process.
///
/// ```
/// use actix_web::{post, web};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Info {
/// name: String,
/// }
///
/// // This handler is only called if:
/// // - request headers declare the content type as `application/x-www-form-urlencoded`
/// // - request payload is deserialized into a `Info` struct from the URL encoded format
/// #[post("/")]
/// async fn index(form: web::Form<Info>) -> String {
/// format!("Welcome {}!", form.name)
/// }
/// ```
2019-07-20 11:55:52 +00:00
///
/// # Responder
/// The `Form` type also allows you to create URL encoded responses:
/// simply return a value of type Form<T> where T is the type to be URL encoded.
/// The type must implement [`serde::Serialize`].
2019-07-20 11:55:52 +00:00
///
/// Responses use
2019-07-20 11:55:52 +00:00
///
/// ```
/// use actix_web::{get, web};
/// use serde::Serialize;
///
2019-07-20 11:55:52 +00:00
/// #[derive(Serialize)]
/// struct SomeForm {
/// name: String,
/// age: u8
/// }
///
/// // Response will have:
/// // - status: 200 OK
/// // - header: `Content-Type: application/x-www-form-urlencoded`
/// // - body: `name=actix&age=123`
/// #[get("/")]
/// async fn index() -> web::Form<SomeForm> {
2019-07-20 11:55:52 +00:00
/// web::Form(SomeForm {
/// name: "actix".into(),
/// age: 123
/// })
/// }
/// ```
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Form<T>(pub T);
impl<T> Form<T> {
/// Unwrap into inner `T` value.
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> ops::Deref for Form<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> ops::DerefMut for Form<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
/// See [here](#extractor) for example of usage as an extractor.
impl<T> FromRequest for Form<T>
where
T: DeserializeOwned + 'static,
{
2019-04-13 23:35:25 +00:00
type Config = FormConfig;
type Error = Error;
2019-11-20 17:33:22 +00:00
type Future = LocalBoxFuture<'static, Result<Self, Error>>;
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
2019-04-07 21:43:07 +00:00
let req2 = req.clone();
let (limit, err_handler) = req
.app_data::<Self::Config>()
.or_else(|| {
req.app_data::<web::Data<Self::Config>>()
.map(|d| d.as_ref())
})
.map(|c| (c.limit, c.err_handler.clone()))
.unwrap_or((16384, None));
2019-11-20 17:33:22 +00:00
UrlEncoded::new(req, payload)
.limit(limit)
.map(move |res| match res {
Err(err) => match err_handler {
Some(err_handler) => Err((err_handler)(err, &req2)),
None => Err(err.into()),
},
2019-11-20 17:33:22 +00:00
Ok(item) => Ok(Form(item)),
})
.boxed_local()
}
}
impl<T: fmt::Debug> fmt::Debug for Form<T> {
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T: fmt::Display> fmt::Display for Form<T> {
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
/// See [here](#responder) for example of usage as a handler return type.
2019-07-20 11:55:52 +00:00
impl<T: Serialize> Responder for Form<T> {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
match serde_urlencoded::to_string(&self.0) {
Ok(body) => HttpResponse::Ok()
.content_type(mime::APPLICATION_WWW_FORM_URLENCODED)
.body(body),
Err(err) => HttpResponse::from_error(err.into()),
}
2019-07-20 11:55:52 +00:00
}
}
/// [`Form`] extractor configuration.
///
/// ```
/// use actix_web::{post, web, App, FromRequest, Result};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Info {
/// username: String,
/// }
///
/// // Custom `FormConfig` is applied to App.
/// // Max payload size for URL encoded forms is set to 4kB.
/// #[post("/")]
/// async fn index(form: web::Form<Info>) -> Result<String> {
/// Ok(format!("Welcome {}!", form.username))
/// }
///
/// App::new()
/// .app_data(web::FormConfig::default().limit(4096))
/// .service(index);
/// ```
#[derive(Clone)]
pub struct FormConfig {
limit: usize,
err_handler: Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>,
}
impl FormConfig {
/// Set maximum accepted payload size. By default this limit is 16kB.
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
/// Set custom error handler
pub fn error_handler<F>(mut self, f: F) -> Self
where
F: Fn(UrlencodedError, &HttpRequest) -> Error + 'static,
{
self.err_handler = Some(Rc::new(f));
self
}
}
impl Default for FormConfig {
fn default() -> Self {
FormConfig {
limit: 16_384, // 2^14 bytes (~16kB)
err_handler: None,
}
}
}
/// Future that resolves to some `T` when parsed from a URL encoded payload.
2019-03-17 07:48:40 +00:00
///
/// Form can be deserialized from any type `T` that implements [`serde::Deserialize`].
2019-03-17 07:48:40 +00:00
///
/// Returns error if:
/// - content type is not `application/x-www-form-urlencoded`
/// - content length is greater than [limit](UrlEncoded::limit())
pub struct UrlEncoded<T> {
2019-12-15 07:28:54 +00:00
#[cfg(feature = "compress")]
stream: Option<Decompress<Payload>>,
2019-12-15 07:28:54 +00:00
#[cfg(not(feature = "compress"))]
stream: Option<Payload>,
2019-03-17 07:48:40 +00:00
limit: usize,
length: Option<usize>,
encoding: &'static Encoding,
2019-03-17 07:48:40 +00:00
err: Option<UrlencodedError>,
fut: Option<LocalBoxFuture<'static, Result<T, UrlencodedError>>>,
2019-03-17 07:48:40 +00:00
}
#[allow(clippy::borrow_interior_mutable_const)]
impl<T> UrlEncoded<T> {
/// Create a new future to decode a URL encoded request payload.
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
2019-03-17 07:48:40 +00:00
// check content type
if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
return Self::err(UrlencodedError::ContentType);
}
let encoding = match req.encoding() {
Ok(enc) => enc,
Err(_) => return Self::err(UrlencodedError::ContentType),
};
let mut len = None;
if let Some(l) = req.headers().get(&CONTENT_LENGTH) {
2019-03-17 07:48:40 +00:00
if let Ok(s) = l.to_str() {
if let Ok(l) = s.parse::<usize>() {
len = Some(l)
} else {
return Self::err(UrlencodedError::UnknownLength);
}
} else {
return Self::err(UrlencodedError::UnknownLength);
}
};
2019-12-15 07:28:54 +00:00
#[cfg(feature = "compress")]
let payload = Decompress::from_headers(payload.take(), req.headers());
2019-12-15 07:28:54 +00:00
#[cfg(not(feature = "compress"))]
let payload = payload.take();
2019-03-17 07:48:40 +00:00
UrlEncoded {
encoding,
stream: Some(payload),
2019-03-17 07:48:40 +00:00
limit: 32_768,
length: len,
fut: None,
err: None,
}
}
fn err(err: UrlencodedError) -> Self {
2019-03-17 07:48:40 +00:00
UrlEncoded {
stream: None,
2019-03-17 07:48:40 +00:00
limit: 32_768,
fut: None,
err: Some(err),
2019-03-17 07:48:40 +00:00
length: None,
encoding: UTF_8,
}
}
/// Set maximum accepted payload size. The default limit is 256kB.
2019-03-17 07:48:40 +00:00
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
}
impl<T> Future for UrlEncoded<T>
2019-03-17 07:48:40 +00:00
where
T: DeserializeOwned + 'static,
2019-03-17 07:48:40 +00:00
{
type Output = Result<T, UrlencodedError>;
2019-03-17 07:48:40 +00:00
2019-12-07 18:46:51 +00:00
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2019-03-17 07:48:40 +00:00
if let Some(ref mut fut) = self.fut {
2019-11-20 17:33:22 +00:00
return Pin::new(fut).poll(cx);
2019-03-17 07:48:40 +00:00
}
if let Some(err) = self.err.take() {
2019-11-20 17:33:22 +00:00
return Poll::Ready(Err(err));
2019-03-17 07:48:40 +00:00
}
// payload size
let limit = self.limit;
if let Some(len) = self.length.take() {
if len > limit {
2019-11-20 17:33:22 +00:00
return Poll::Ready(Err(UrlencodedError::Overflow { size: len, limit }));
2019-03-17 07:48:40 +00:00
}
}
// future
let encoding = self.encoding;
2019-11-20 17:33:22 +00:00
let mut stream = self.stream.take().unwrap();
self.fut = Some(
async move {
let mut body = BytesMut::with_capacity(8192);
while let Some(item) = stream.next().await {
let chunk = item?;
2019-11-20 17:33:22 +00:00
if (body.len() + chunk.len()) > limit {
return Err(UrlencodedError::Overflow {
size: body.len() + chunk.len(),
limit,
});
} else {
body.extend_from_slice(&chunk);
}
2019-03-17 07:48:40 +00:00
}
2019-11-20 17:33:22 +00:00
if encoding == UTF_8 {
2021-02-11 23:03:17 +00:00
serde_urlencoded::from_bytes::<T>(&body).map_err(|_| UrlencodedError::Parse)
2019-03-17 07:48:40 +00:00
} else {
let body = encoding
.decode_without_bom_handling_and_without_replacement(&body)
.map(|s| s.into_owned())
.ok_or(UrlencodedError::Parse)?;
2021-02-11 23:03:17 +00:00
serde_urlencoded::from_str::<T>(&body).map_err(|_| UrlencodedError::Parse)
2019-03-17 07:48:40 +00:00
}
2019-11-20 17:33:22 +00:00
}
.boxed_local(),
2019-11-20 17:33:22 +00:00
);
2019-11-20 17:33:22 +00:00
self.poll(cx)
2019-03-17 07:48:40 +00:00
}
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
2019-07-20 11:55:52 +00:00
use serde::{Deserialize, Serialize};
use super::*;
use crate::http::{
header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
StatusCode,
};
2019-11-26 05:25:50 +00:00
use crate::test::TestRequest;
2019-07-20 11:55:52 +00:00
#[derive(Deserialize, Serialize, Debug, PartialEq)]
struct Info {
hello: String,
2019-07-20 11:55:52 +00:00
counter: i64,
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_form() {
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
2019-03-17 07:48:40 +00:00
2019-11-26 05:25:50 +00:00
let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap();
assert_eq!(
s,
Info {
hello: "world".into(),
counter: 123
}
);
2019-03-17 07:48:40 +00:00
}
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
match err {
UrlencodedError::Overflow { .. } => {
matches!(other, UrlencodedError::Overflow { .. })
}
2021-02-28 18:17:08 +00:00
UrlencodedError::UnknownLength => matches!(other, UrlencodedError::UnknownLength),
UrlencodedError::ContentType => matches!(other, UrlencodedError::ContentType),
2019-03-17 07:48:40 +00:00
_ => false,
}
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_urlencoded_error() {
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, "xxxx"))
.to_http_parts();
2019-11-26 05:25:50 +00:00
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
2019-03-17 07:48:40 +00:00
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, "1000000"))
.to_http_parts();
2019-11-26 05:25:50 +00:00
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(
info.err().unwrap(),
UrlencodedError::Overflow { size: 0, limit: 0 }
));
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "text/plain"))
.insert_header((CONTENT_LENGTH, 10))
2019-11-20 17:33:22 +00:00
.to_http_parts();
2019-11-26 05:25:50 +00:00
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
}
2019-03-17 07:48:40 +00:00
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_urlencoded() {
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
2019-03-17 07:48:40 +00:00
2019-11-26 05:25:50 +00:00
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
assert_eq!(
info,
Info {
hello: "world".to_owned(),
counter: 123
}
);
2021-01-15 02:11:10 +00:00
let (req, mut pl) = TestRequest::default()
.insert_header((
CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8",
))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
2019-11-26 05:25:50 +00:00
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
assert_eq!(
info,
Info {
hello: "world".to_owned(),
counter: 123
}
);
}
2019-07-20 11:55:52 +00:00
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_responder() {
let req = TestRequest::default().to_http_request();
let form = Form(Info {
hello: "world".to_string(),
counter: 123,
});
let resp = form.respond_to(&req);
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/x-www-form-urlencoded")
);
use crate::responder::tests::BodyTest;
assert_eq!(resp.body().bin_ref(), b"hello=world&counter=123");
2019-07-20 11:55:52 +00:00
}
#[actix_rt::test]
async fn test_with_config_in_data_wrapper() {
let ctype = HeaderValue::from_static("application/x-www-form-urlencoded");
let (req, mut pl) = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((CONTENT_TYPE, ctype))
.insert_header((CONTENT_LENGTH, HeaderValue::from_static("20")))
.set_payload(Bytes::from_static(b"hello=test&counter=4"))
.app_data(web::Data::new(FormConfig::default().limit(10)))
.to_http_parts();
let s = Form::<Info>::from_request(&req, &mut pl).await;
assert!(s.is_err());
let err_str = s.err().unwrap().to_string();
assert!(err_str.starts_with("URL encoded payload is larger"));
}
}