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