Skip to main content

actix_web/types/
form.rs

1//! For URL-encoded form helper documentation, see [`Form`].
2
3use std::{
4    borrow::Cow,
5    future::Future,
6    pin::Pin,
7    rc::Rc,
8    task::{Context, Poll},
9};
10
11use actix_http::{error::PayloadError, Payload};
12use bytes::BytesMut;
13use encoding_rs::{Encoding, UTF_8};
14use futures_core::{future::LocalBoxFuture, ready};
15use futures_util::{FutureExt as _, StreamExt as _};
16use serde::{de::DeserializeOwned, Serialize};
17
18#[cfg(feature = "__compress")]
19use crate::dev::Decompress;
20use crate::{
21    body::EitherBody, error::UrlencodedError, extract::FromRequest, http::header::CONTENT_LENGTH,
22    web, Error, HttpMessage, HttpRequest, HttpResponse, Responder,
23};
24
25/// URL-encoded payload extractor and responder.
26///
27/// `Form` has two uses: URL-encoded responses, and extracting typed data from URL request payloads.
28///
29/// # Extractor
30/// To extract typed data from a request body, the inner type `T` must implement the
31/// [`DeserializeOwned`] trait.
32///
33/// Use [`FormConfig`] to configure extraction options.
34///
35/// ## Examples
36/// ```
37/// use actix_web::{post, web};
38/// use serde::Deserialize;
39///
40/// #[derive(Deserialize)]
41/// struct Info {
42///     name: String,
43/// }
44///
45/// // This handler is only called if:
46/// // - request headers declare the content type as `application/x-www-form-urlencoded`
47/// // - request payload deserializes into an `Info` struct from the URL-encoded format
48/// #[post("/")]
49/// async fn index(web::Form(form): web::Form<Info>) -> String {
50///     format!("Welcome {}!", form.name)
51/// }
52/// ```
53///
54/// # Responder
55/// The `Form` type also allows you to create URL-encoded responses by returning a value of type
56/// `Form<T>` where `T` is the type to be URL-encoded, as long as `T` implements [`Serialize`].
57///
58/// ## Examples
59/// ```
60/// use actix_web::{get, web};
61/// use serde::Serialize;
62///
63/// #[derive(Serialize)]
64/// struct SomeForm {
65///     name: String,
66///     age: u8
67/// }
68///
69/// // Response will have:
70/// // - status: 200 OK
71/// // - header: `Content-Type: application/x-www-form-urlencoded`
72/// // - body: `name=actix&age=123`
73/// #[get("/")]
74/// async fn index() -> web::Form<SomeForm> {
75///     web::Form(SomeForm {
76///         name: "actix".to_owned(),
77///         age: 123
78///     })
79/// }
80/// ```
81///
82/// # Panics
83/// URL-encoded forms consist of unordered `key=value` pairs, therefore they cannot be decoded into
84/// any type which depends upon data ordering (eg. tuples). Trying to do so will result in a panic.
85#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
86pub struct Form<T>(pub T);
87
88impl_more::impl_deref_and_mut!(<T> in Form<T> => T);
89impl_more::forward_display!(<T> in Form<T>);
90
91impl<T> Form<T> {
92    /// Unwrap into inner `T` value.
93    pub fn into_inner(self) -> T {
94        self.0
95    }
96}
97
98impl<T> Serialize for Form<T>
99where
100    T: Serialize,
101{
102    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
103    where
104        S: serde::Serializer,
105    {
106        self.0.serialize(serializer)
107    }
108}
109
110/// See [here](#extractor) for example of usage as an extractor.
111impl<T> FromRequest for Form<T>
112where
113    T: DeserializeOwned + 'static,
114{
115    type Error = Error;
116    type Future = FormExtractFut<T>;
117
118    #[inline]
119    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
120        let FormConfig { limit, err_handler } = FormConfig::from_req(req).clone();
121
122        FormExtractFut {
123            fut: UrlEncoded::new(req, payload).limit(limit),
124            req: req.clone(),
125            err_handler,
126        }
127    }
128}
129
130type FormErrHandler = Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>;
131
132pub struct FormExtractFut<T> {
133    fut: UrlEncoded<T>,
134    err_handler: FormErrHandler,
135    req: HttpRequest,
136}
137
138impl<T> Future for FormExtractFut<T>
139where
140    T: DeserializeOwned + 'static,
141{
142    type Output = Result<Form<T>, Error>;
143
144    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
145        let this = self.get_mut();
146
147        let res = ready!(Pin::new(&mut this.fut).poll(cx));
148
149        let res = match res {
150            Err(err) => match &this.err_handler {
151                Some(err_handler) => Err((err_handler)(err, &this.req)),
152                None => Err(err.into()),
153            },
154            Ok(item) => Ok(Form(item)),
155        };
156
157        Poll::Ready(res)
158    }
159}
160
161/// See [here](#responder) for example of usage as a handler return type.
162impl<T: Serialize> Responder for Form<T> {
163    type Body = EitherBody<String>;
164
165    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
166        match serde_urlencoded::to_string(&self.0) {
167            Ok(body) => match HttpResponse::Ok()
168                .content_type(mime::APPLICATION_WWW_FORM_URLENCODED)
169                .message_body(body)
170            {
171                Ok(res) => res.map_into_left_body(),
172                Err(err) => HttpResponse::from_error(err).map_into_right_body(),
173            },
174
175            Err(err) => {
176                HttpResponse::from_error(UrlencodedError::Serialize(err)).map_into_right_body()
177            }
178        }
179    }
180}
181
182/// [`Form`] extractor configuration.
183///
184/// ```
185/// use actix_web::{post, web, App, FromRequest, Result};
186/// use serde::Deserialize;
187///
188/// #[derive(Deserialize)]
189/// struct Info {
190///     username: String,
191/// }
192///
193/// // Custom `FormConfig` is applied to App.
194/// // Max payload size for URL-encoded forms is set to 4kB.
195/// #[post("/")]
196/// async fn index(form: web::Form<Info>) -> Result<String> {
197///     Ok(format!("Welcome {}!", form.username))
198/// }
199///
200/// App::new()
201///     .app_data(web::FormConfig::default().limit(4096))
202///     .service(index);
203/// ```
204#[derive(Clone)]
205pub struct FormConfig {
206    limit: usize,
207    err_handler: FormErrHandler,
208}
209
210impl FormConfig {
211    /// Set maximum accepted payload size. By default this limit is 32 KiB.
212    pub fn limit(mut self, limit: usize) -> Self {
213        self.limit = limit;
214        self
215    }
216
217    /// Set custom error handler
218    pub fn error_handler<F>(mut self, f: F) -> Self
219    where
220        F: Fn(UrlencodedError, &HttpRequest) -> Error + 'static,
221    {
222        self.err_handler = Some(Rc::new(f));
223        self
224    }
225
226    /// Extract payload config from app data.
227    ///
228    /// Checks both `T` and `Data<T>`, in that order, and falls back to the default payload config.
229    fn from_req(req: &HttpRequest) -> &Self {
230        req.app_data::<Self>()
231            .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
232            .unwrap_or(&DEFAULT_CONFIG)
233    }
234}
235
236const DEFAULT_LIMIT: usize = 32_768; // 32 KiB
237
238/// Allow shared refs used as default.
239const DEFAULT_CONFIG: FormConfig = FormConfig {
240    limit: DEFAULT_LIMIT,
241    err_handler: None,
242};
243
244impl Default for FormConfig {
245    fn default() -> Self {
246        DEFAULT_CONFIG
247    }
248}
249
250/// Future that resolves to some `T` when parsed from a URL-encoded payload.
251///
252/// Form can be deserialized from any type `T` that implements [`serde::Deserialize`].
253///
254/// Returns error if:
255/// - content type is not `application/x-www-form-urlencoded`
256/// - content length is greater than [limit](UrlEncoded::limit())
257pub struct UrlEncoded<T> {
258    #[cfg(feature = "__compress")]
259    stream: Option<Decompress<Payload>>,
260    #[cfg(not(feature = "__compress"))]
261    stream: Option<Payload>,
262
263    limit: usize,
264    length: Option<usize>,
265    encoding: &'static Encoding,
266    err: Option<UrlencodedError>,
267    fut: Option<LocalBoxFuture<'static, Result<T, UrlencodedError>>>,
268}
269
270#[allow(clippy::borrow_interior_mutable_const)]
271impl<T> UrlEncoded<T> {
272    /// Create a new future to decode a URL-encoded request payload.
273    pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
274        // check content type
275        if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
276            return Self::err(UrlencodedError::ContentType);
277        }
278        let encoding = match req.encoding() {
279            Ok(enc) => enc,
280            Err(_) => return Self::err(UrlencodedError::ContentType),
281        };
282
283        let mut len = None;
284        if let Some(l) = req.headers().get(&CONTENT_LENGTH) {
285            if let Ok(s) = l.to_str() {
286                if let Ok(l) = s.parse::<usize>() {
287                    len = Some(l)
288                } else {
289                    return Self::err(UrlencodedError::UnknownLength);
290                }
291            } else {
292                return Self::err(UrlencodedError::UnknownLength);
293            }
294        };
295
296        let payload = {
297            cfg_if::cfg_if! {
298                if #[cfg(feature = "__compress")] {
299                    Decompress::from_headers(payload.take(), req.headers())
300                        .limit(DEFAULT_LIMIT)
301                } else {
302                    payload.take()
303                }
304            }
305        };
306
307        UrlEncoded {
308            encoding,
309            stream: Some(payload),
310            limit: DEFAULT_LIMIT,
311            length: len,
312            fut: None,
313            err: None,
314        }
315    }
316
317    fn err(err: UrlencodedError) -> Self {
318        UrlEncoded {
319            stream: None,
320            limit: DEFAULT_LIMIT,
321            fut: None,
322            err: Some(err),
323            length: None,
324            encoding: UTF_8,
325        }
326    }
327
328    /// Set maximum accepted payload size. The default limit is 32 KiB.
329    pub fn limit(mut self, limit: usize) -> Self {
330        self.limit = limit;
331
332        #[cfg(feature = "__compress")]
333        {
334            self.stream = self.stream.map(|stream| stream.limit(limit));
335        }
336
337        self
338    }
339}
340
341impl<T> Future for UrlEncoded<T>
342where
343    T: DeserializeOwned + 'static,
344{
345    type Output = Result<T, UrlencodedError>;
346
347    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
348        if let Some(ref mut fut) = self.fut {
349            return Pin::new(fut).poll(cx);
350        }
351
352        if let Some(err) = self.err.take() {
353            return Poll::Ready(Err(err));
354        }
355
356        // payload size
357        let limit = self.limit;
358        if let Some(len) = self.length.take() {
359            if len > limit {
360                return Poll::Ready(Err(UrlencodedError::Overflow { size: len, limit }));
361            }
362        }
363
364        let encoding = self.encoding;
365        let mut stream = self.stream.take().unwrap();
366
367        self.fut = Some(
368            async move {
369                let mut body = BytesMut::with_capacity(8192);
370
371                while let Some(item) = stream.next().await {
372                    let chunk = item.map_err(|err| match err {
373                        PayloadError::Overflow => UrlencodedError::OverflowUnknownLength { limit },
374                        err => UrlencodedError::Payload(err),
375                    })?;
376
377                    if (body.len() + chunk.len()) > limit {
378                        return Err(UrlencodedError::OverflowUnknownLength { limit });
379                    } else {
380                        body.extend_from_slice(&chunk);
381                    }
382                }
383
384                if encoding == UTF_8 {
385                    serde_urlencoded::from_bytes::<T>(&body).map_err(UrlencodedError::Parse)
386                } else {
387                    let body = encoding
388                        .decode_without_bom_handling_and_without_replacement(&body)
389                        .map(Cow::into_owned)
390                        .ok_or(UrlencodedError::Encoding)?;
391
392                    serde_urlencoded::from_str::<T>(&body).map_err(UrlencodedError::Parse)
393                }
394            }
395            .boxed_local(),
396        );
397
398        self.poll(cx)
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use bytes::Bytes;
405    use serde::{Deserialize, Serialize};
406
407    use super::*;
408    use crate::{
409        http::{
410            header::{HeaderValue, CONTENT_TYPE},
411            StatusCode,
412        },
413        test::{assert_body_eq, TestRequest},
414    };
415
416    #[derive(Deserialize, Serialize, Debug, PartialEq)]
417    struct Info {
418        hello: String,
419        counter: i64,
420    }
421
422    #[tokio::test(flavor = "local")]
423    async fn test_form() {
424        let (req, mut pl) = TestRequest::default()
425            .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
426            .insert_header((CONTENT_LENGTH, 11))
427            .set_payload(Bytes::from_static(b"hello=world&counter=123"))
428            .to_http_parts();
429
430        let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap();
431        assert_eq!(
432            s,
433            Info {
434                hello: "world".into(),
435                counter: 123
436            }
437        );
438    }
439
440    fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
441        match err {
442            UrlencodedError::Overflow { .. } => {
443                matches!(other, UrlencodedError::Overflow { .. })
444            }
445            UrlencodedError::UnknownLength => matches!(other, UrlencodedError::UnknownLength),
446            UrlencodedError::ContentType => matches!(other, UrlencodedError::ContentType),
447            _ => false,
448        }
449    }
450
451    #[tokio::test(flavor = "local")]
452    async fn test_urlencoded_error() {
453        let (req, mut pl) = TestRequest::default()
454            .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
455            .insert_header((CONTENT_LENGTH, "xxxx"))
456            .to_http_parts();
457        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
458        assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
459
460        let (req, mut pl) = TestRequest::default()
461            .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
462            .insert_header((CONTENT_LENGTH, "1000000"))
463            .to_http_parts();
464        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
465        assert!(eq(
466            info.err().unwrap(),
467            UrlencodedError::Overflow { size: 0, limit: 0 }
468        ));
469
470        let (req, mut pl) = TestRequest::default()
471            .insert_header((CONTENT_TYPE, "text/plain"))
472            .insert_header((CONTENT_LENGTH, 10))
473            .to_http_parts();
474        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
475        assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
476    }
477
478    #[tokio::test(flavor = "local")]
479    async fn test_urlencoded() {
480        let (req, mut pl) = TestRequest::default()
481            .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
482            .insert_header((CONTENT_LENGTH, 11))
483            .set_payload(Bytes::from_static(b"hello=world&counter=123"))
484            .to_http_parts();
485
486        let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
487        assert_eq!(
488            info,
489            Info {
490                hello: "world".to_owned(),
491                counter: 123
492            }
493        );
494
495        let (req, mut pl) = TestRequest::default()
496            .insert_header((
497                CONTENT_TYPE,
498                "application/x-www-form-urlencoded; charset=utf-8",
499            ))
500            .insert_header((CONTENT_LENGTH, 11))
501            .set_payload(Bytes::from_static(b"hello=world&counter=123"))
502            .to_http_parts();
503
504        let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
505        assert_eq!(
506            info,
507            Info {
508                hello: "world".to_owned(),
509                counter: 123
510            }
511        );
512    }
513
514    #[tokio::test(flavor = "local")]
515    async fn test_responder() {
516        let req = TestRequest::default().to_http_request();
517
518        let form = Form(Info {
519            hello: "world".to_string(),
520            counter: 123,
521        });
522        let res = form.respond_to(&req);
523        assert_eq!(res.status(), StatusCode::OK);
524        assert_eq!(
525            res.headers().get(CONTENT_TYPE).unwrap(),
526            HeaderValue::from_static("application/x-www-form-urlencoded")
527        );
528        assert_body_eq!(res, b"hello=world&counter=123");
529    }
530
531    #[tokio::test(flavor = "local")]
532    async fn test_with_config_in_data_wrapper() {
533        let ctype = HeaderValue::from_static("application/x-www-form-urlencoded");
534
535        let (req, mut pl) = TestRequest::default()
536            .insert_header((CONTENT_TYPE, ctype))
537            .insert_header((CONTENT_LENGTH, HeaderValue::from_static("20")))
538            .set_payload(Bytes::from_static(b"hello=test&counter=4"))
539            .app_data(web::Data::new(FormConfig::default().limit(10)))
540            .to_http_parts();
541
542        let s = Form::<Info>::from_request(&req, &mut pl).await;
543        assert!(s.is_err());
544
545        let err_str = s.err().unwrap().to_string();
546        assert!(err_str.starts_with("URL-encoded payload is larger"));
547    }
548}