Skip to main content

ntex/web/types/
form.rs

1//! Form extractor
2use std::task::{Context, Poll, ready};
3use std::{borrow::Cow, fmt, future::Future, future::poll_fn, marker::PhantomData, mem, ops};
4use std::{pin::Pin, str};
5
6use encoding_rs::{Encoding, UTF_8};
7use serde::{Serialize, de::DeserializeOwned};
8
9use crate::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
10use crate::http::{HttpMessage, Payload, Response, StatusCode};
11use crate::web::error::{UrlencodedError, WebResponseError};
12use crate::web::{FromRequest, HttpRequest, Responder, State};
13
14/// Form data helper (`application/x-www-form-urlencoded`)
15///
16/// Can be used to extract url-encoded data from the request body,
17/// or send url-encoded data as the response.
18///
19/// ## Extract
20///
21/// To extract typed information from request's body, the type `T` must
22/// implement the `Deserialize` trait from *serde*.
23///
24/// [`FormConfig`] allows to configure extraction
25/// process.
26///
27/// Field names and values are decoded with the `charset` parameter of the
28/// `Content-Type` header, UTF-8 by default: with `charset=windows-1252`,
29/// `caf%E9` yields `café`. Raw or percent-encoded bytes that are invalid in
30/// that charset fail with `UrlencodedError::Parse` rather than being replaced.
31///
32/// ### Example
33/// ```rust
34/// use ntex::web;
35///
36/// #[derive(serde::Deserialize)]
37/// struct FormData {
38///     username: String,
39/// }
40///
41/// /// Extract form data using serde.
42/// ///
43/// /// If the content type is not *x-www-form-urlencoded* or the body cannot be
44/// /// deserialized to a `FormData` struct, the extractor fails with
45/// /// `UrlencodedError` and the handler is not called.
46/// async fn index(form: web::types::Form<FormData>) -> String {
47///     format!("Welcome {}!", form.username)
48/// }
49/// # fn main() {}
50/// ```
51///
52/// ## Respond
53///
54/// The `Form` type also allows you to respond with well-formed url-encoded data:
55/// simply return a value of type `Form<T>` where T is the type to be url-encoded.
56/// The type  must implement `serde::Serialize`;
57///
58/// ### Example
59/// ```rust
60/// use ntex::web;
61///
62/// #[derive(serde::Serialize)]
63/// struct SomeForm {
64///     name: String,
65///     age: u8
66/// }
67///
68/// // Will return a 200 response with header
69/// // `Content-Type: application/x-www-form-urlencoded`
70/// // and body "name=ntex&age=123"
71/// async fn index() -> web::types::Form<SomeForm> {
72///     web::types::Form(SomeForm {
73///         name: "ntex".into(),
74///         age: 123
75///     })
76/// }
77/// # fn main() {}
78/// ```
79#[derive(PartialEq, Eq, PartialOrd, Ord)]
80pub struct Form<T>(pub T);
81
82impl<T> Form<T> {
83    /// Deconstruct to an inner value
84    pub fn into_inner(self) -> T {
85        self.0
86    }
87}
88
89impl<T> ops::Deref for Form<T> {
90    type Target = T;
91
92    fn deref(&self) -> &T {
93        &self.0
94    }
95}
96
97impl<T> ops::DerefMut for Form<T> {
98    fn deref_mut(&mut self) -> &mut T {
99        &mut self.0
100    }
101}
102
103impl<St, T> FromRequest<St> for Form<T>
104where
105    St: State,
106    T: DeserializeOwned + 'static,
107{
108    type Error = UrlencodedError;
109
110    // Checks run when the future is created, so it holds only the body reader
111    fn from_request(
112        _: &St,
113        req: &HttpRequest,
114        payload: &mut Payload,
115    ) -> impl Future<Output = Result<Self, Self::Error>> {
116        let limit = req.app_value::<FormConfig>().map_or(16384, |c| c.limit);
117
118        let mut body = UrlEncoded::new(req, payload).limit(limit);
119        poll_fn(move |cx| Pin::new(&mut body).poll(cx).map_ok(Form))
120    }
121}
122
123impl<T: fmt::Debug> fmt::Debug for Form<T> {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.debug_tuple("Form").field(&self.0).finish()
126    }
127}
128
129impl<T: fmt::Display> fmt::Display for Form<T> {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        self.0.fmt(f)
132    }
133}
134
135impl<St, T: Serialize> Responder<St> for Form<T>
136where
137    St: State,
138    serde_urlencoded::ser::Error: WebResponseError<St, St::Error>,
139{
140    async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
141        let body = match serde_urlencoded::to_string(&self.0) {
142            Ok(body) => body,
143            Err(e) => return e.error_response(st),
144        };
145
146        Response::builder(StatusCode::OK)
147            .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
148            .body(body)
149    }
150}
151
152/// Form extractor configuration
153///
154/// Register it with [`WebAppConfig::set_value()`](crate::web::WebAppConfig::set_value)
155/// and [`App::with_config()`](crate::web::App::with_config). The extractor
156/// does not read the application state, so a config stored in
157/// [`AppState`](crate::web::AppState) has no effect.
158///
159/// ```rust
160/// use std::convert::Infallible;
161/// use ntex::web::{self, App, WebError, FromRequest, WebAppConfig};
162///
163/// #[derive(serde::Deserialize)]
164/// struct FormData {
165///     username: String,
166/// }
167///
168/// /// Extract form data using serde.
169/// /// Custom configuration is used for this handler, max payload size is 4k
170/// async fn index(form: web::types::Form<FormData>) -> Result<String, Infallible> {
171///     Ok(format!("Welcome {}!", form.username))
172/// }
173///
174/// fn main() {
175///     let cfg = WebAppConfig::new()
176///         // change `Form` extractor configuration
177///         .set_value(web::types::FormConfig::default().limit(4097));
178///
179///     let app = App::default()
180///         .with_config(cfg)
181///         .service(web::resource("/index.html").route(web::get().to(index)));
182/// }
183/// ```
184#[derive(Clone, Debug)]
185pub struct FormConfig {
186    limit: usize,
187}
188
189impl FormConfig {
190    #[must_use]
191    /// Change max size of payload.
192    ///
193    /// By default max size is 16Kb
194    pub fn limit(mut self, limit: usize) -> Self {
195        self.limit = limit;
196        self
197    }
198}
199
200impl Default for FormConfig {
201    fn default() -> Self {
202        FormConfig { limit: 16384 }
203    }
204}
205
206/// Future that resolves to a parsed urlencoded values.
207///
208/// Parse `application/x-www-form-urlencoded` encoded request's body.
209/// Return `UrlEncoded` future. Form can be deserialized to any type that
210/// implements `Deserialize` trait from *serde*.
211///
212/// Returns error:
213///
214/// * content type is not `application/x-www-form-urlencoded`
215/// * content-length is greater than the limit (32k by default; the `Form`
216///   extractor sets it from [`FormConfig`], 16k by default)
217///
218enum UrlEncoded<U> {
219    Body(
220        super::ReadBody<super::BodyStream>,
221        &'static Encoding,
222        PhantomData<fn() -> U>,
223    ),
224    Err(UrlencodedError),
225    Done,
226}
227
228impl<U> UrlEncoded<U> {
229    /// Create a new future to URL encode a request
230    fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded<U> {
231        // check content type
232        if !req
233            .content_type()
234            .eq_ignore_ascii_case("application/x-www-form-urlencoded")
235        {
236            return Self::err(UrlencodedError::ContentType);
237        }
238        let Ok(encoding) = req.encoding() else {
239            return Self::err(UrlencodedError::ContentType);
240        };
241
242        let mut len = None;
243        if let Some(l) = req.headers().get(&CONTENT_LENGTH) {
244            if let Ok(s) = l.to_str() {
245                if let Ok(l) = s.parse::<usize>() {
246                    len = Some(l);
247                } else {
248                    return Self::err(UrlencodedError::UnknownLength);
249                }
250            } else {
251                return Self::err(UrlencodedError::UnknownLength);
252            }
253        }
254
255        UrlEncoded::Body(
256            super::ReadBody::from_request(req, payload, 32_768).length(len),
257            encoding,
258            PhantomData,
259        )
260    }
261
262    fn err(e: UrlencodedError) -> Self {
263        UrlEncoded::Err(e)
264    }
265
266    /// Change max size of payload. By default max size is 32Kb
267    fn limit(mut self, limit: usize) -> Self {
268        if let UrlEncoded::Body(body, _, _) = &mut self {
269            body.limit = limit;
270        }
271        self
272    }
273}
274
275impl<U> Future for UrlEncoded<U>
276where
277    U: DeserializeOwned + 'static,
278{
279    type Output = Result<U, UrlencodedError>;
280
281    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
282        let this = self.get_mut();
283        let (body, encoding) = match this {
284            UrlEncoded::Body(body, encoding, _) => (body, *encoding),
285            UrlEncoded::Err(_) => {
286                let UrlEncoded::Err(err) = mem::replace(this, UrlEncoded::Done) else {
287                    unreachable!()
288                };
289                return Poll::Ready(Err(err));
290            }
291            UrlEncoded::Done => panic!("polled after completion"),
292        };
293
294        // payload size
295        let limit = body.limit;
296        if let Some(len) = body.length
297            && len > limit
298        {
299            return Poll::Ready(Err(UrlencodedError::Overflow { size: len, limit }));
300        }
301
302        let body = match ready!(Pin::new(body).poll(cx)) {
303            Ok(body) => body,
304            Err(super::ReadBodyError::Overflow(size)) => {
305                return Poll::Ready(Err(UrlencodedError::Overflow { size, limit }));
306            }
307            Err(super::ReadBodyError::Payload(err)) => {
308                return Poll::Ready(Err(UrlencodedError::Payload(err)));
309            }
310        };
311
312        Poll::Ready(
313            to_utf8_form(&body, encoding)
314                .ok_or(UrlencodedError::Parse)
315                .and_then(|body| {
316                    serde_urlencoded::from_bytes::<U>(&body).map_err(|_| UrlencodedError::Parse)
317                }),
318        )
319    }
320}
321
322/// Converts a form body to an equivalent UTF-8 form body.
323///
324/// Raw and percent-decoded bytes are decoded with `encoding`, so `caf%E9`
325/// with `windows-1252` yields `café`. Returns `None` if the bytes are not
326/// valid in that encoding.
327fn to_utf8_form<'a>(body: &'a [u8], encoding: &'static Encoding) -> Option<Cow<'a, [u8]>> {
328    let (body, encoding): (Cow<'a, [u8]>, _) = if encoding.is_ascii_compatible() {
329        (Cow::Borrowed(body), encoding)
330    } else {
331        // delimiters and escapes are only recognizable after decoding the text
332        let text = encoding.decode_without_bom_handling_and_without_replacement(body)?;
333        (Cow::Owned(text.into_owned().into_bytes()), UTF_8)
334    };
335
336    if encoding == UTF_8 {
337        // delimiters are ASCII, so the whole body is valid iff every field is
338        str::from_utf8(&percent_decode(&body)).ok()?;
339        return Some(body);
340    }
341
342    let decode = |part: &[u8]| {
343        encoding
344            .decode_without_bom_handling_and_without_replacement(&percent_decode(part))
345            .map(Cow::into_owned)
346    };
347    let mut fields = Vec::new();
348    for field in body.split(|b| *b == b'&').filter(|f| !f.is_empty()) {
349        let (name, value) = match field.iter().position(|b| *b == b'=') {
350            Some(pos) => (&field[..pos], &field[pos + 1..]),
351            None => (field, &b""[..]),
352        };
353        fields.push((decode(name)?, decode(value)?));
354    }
355    serde_urlencoded::to_string(fields)
356        .ok()
357        .map(|body| Cow::Owned(body.into_bytes()))
358}
359
360/// Decodes `+` and `%XX` escapes, keeping malformed escapes as-is.
361fn percent_decode(input: &[u8]) -> Vec<u8> {
362    fn hex(b: u8) -> Option<u8> {
363        char::from(b)
364            .to_digit(16)
365            .and_then(|d| u8::try_from(d).ok())
366    }
367
368    let mut out = Vec::with_capacity(input.len());
369    let mut i = 0;
370    while i < input.len() {
371        match input[i] {
372            b'+' => out.push(b' '),
373            b'%' if let (Some(hi), Some(lo)) = (
374                input.get(i + 1).copied().and_then(hex),
375                input.get(i + 2).copied().and_then(hex),
376            ) =>
377            {
378                out.push(hi << 4 | lo);
379                i += 2;
380            }
381            b => out.push(b),
382        }
383        i += 1;
384    }
385    out
386}
387
388#[cfg(test)]
389mod tests {
390    use serde::{Deserialize, Serialize};
391
392    use super::*;
393    use crate::http::header::HeaderValue;
394    use crate::util::Bytes;
395    use crate::web::test::{TestRequest, from_request, respond_to};
396
397    #[derive(Deserialize, Serialize, Debug, PartialEq, thiserror::Error)]
398    #[error("Info({hello})")]
399    struct Info {
400        hello: String,
401        counter: i64,
402    }
403
404    fn eq(err: &UrlencodedError, other: &UrlencodedError) -> bool {
405        if let UrlencodedError::Overflow { .. } = err
406            && let UrlencodedError::Overflow { .. } = other
407        {
408            return true;
409        } else if let UrlencodedError::UnknownLength = err
410            && let UrlencodedError::UnknownLength = other
411        {
412            return true;
413        } else if let UrlencodedError::ContentType = err
414            && let UrlencodedError::ContentType = other
415        {
416            return true;
417        }
418        false
419    }
420
421    /// STATEMENT: `Form` exposes mutable inner fields and delegates useful formatting.
422    ///
423    /// HOW:
424    /// - Wrap an `Info` value, read and change its `hello` field, and assert both values.
425    /// - Assert debug output identifies `Form` and display output includes the changed text.
426    #[test]
427    fn test_basic() {
428        let mut f = Form(Info {
429            hello: "world".into(),
430            counter: 123,
431        });
432        assert_eq!(f.hello, "world");
433        f.hello = "test".to_string();
434        assert_eq!(f.hello, "test");
435        assert!(format!("{f:?}").contains("Form"));
436        assert!(format!("{f}").contains("test"));
437    }
438
439    /// STATEMENT: Form extraction deserializes fields and rejects an invalid content length.
440    ///
441    /// HOW:
442    /// - Extract `Form<Info>` from a URL-encoded body and assert both fields.
443    /// - Repeat with a nonnumeric `Content-Length` and assert `UnknownLength`.
444    #[crate::rt_test]
445    async fn test_form() {
446        let (req, mut pl, ()) =
447            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
448                .header(CONTENT_LENGTH, "11")
449                .payload(Bytes::from_static(b"hello=world&counter=123"))
450                .to_http_parts();
451
452        let Form(s) = from_request::<_, Form<Info>>(&(), &req, &mut pl)
453            .await
454            .unwrap();
455        assert_eq!(
456            s,
457            Info {
458                hello: "world".into(),
459                counter: 123
460            }
461        );
462
463        let (req, mut pl, ()) =
464            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
465                .header(CONTENT_LENGTH, "xx")
466                .payload(Bytes::from_static(b"hello=world&counter=123"))
467                .to_http_parts();
468        let res = from_request::<_, Form<Info>>(&(), &req, &mut pl).await;
469        assert!(eq(&res.err().unwrap(), &UrlencodedError::UnknownLength));
470    }
471
472    /// STATEMENT: URL-encoded reading rejects unknown lengths, oversized declarations, and wrong types.
473    ///
474    /// HOW:
475    /// - Construct bodies with a malformed length, a very large length, and `text/plain`.
476    /// - Assert `UnknownLength`, `Overflow`, and `ContentType` error variants, respectively.
477    #[crate::rt_test]
478    async fn test_urlencoded_error() {
479        let (req, mut pl, ()) =
480            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
481                .header(CONTENT_LENGTH, "xxxx")
482                .to_http_parts();
483        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
484        assert!(eq(&info.err().unwrap(), &UrlencodedError::UnknownLength));
485
486        let (req, mut pl, ()) =
487            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
488                .header(CONTENT_LENGTH, "1000000")
489                .to_http_parts();
490        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
491        assert!(eq(
492            &info.err().unwrap(),
493            &UrlencodedError::Overflow { size: 0, limit: 0 }
494        ));
495
496        let (req, mut pl, ()) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
497            .header(CONTENT_LENGTH, "10")
498            .to_http_parts();
499        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
500        assert!(eq(&info.err().unwrap(), &UrlencodedError::ContentType));
501    }
502
503    /// STATEMENT: URL-encoded reading accepts mixed-case media types and supported charset parameters.
504    ///
505    /// HOW:
506    /// - Deserialize the same form with ordinary and mixed-case media types and UTF-8/CP1251 charsets.
507    /// - Assert the expected fields for the ordinary and charset cases and success for mixed case.
508    #[crate::rt_test]
509    async fn test_urlencoded() {
510        let (req, mut pl, ()) =
511            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
512                .header(CONTENT_LENGTH, "11")
513                .payload(Bytes::from_static(b"hello=world&counter=123"))
514                .to_http_parts();
515
516        let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
517        assert_eq!(
518            info,
519            Info {
520                hello: "world".to_owned(),
521                counter: 123
522            }
523        );
524
525        let (req, mut pl, ()) =
526            TestRequest::with_header(CONTENT_TYPE, "Application/X-WWW-Form-URLEncoded")
527                .header(CONTENT_LENGTH, "11")
528                .payload(Bytes::from_static(b"hello=world&counter=123"))
529                .to_http_parts();
530        assert!(UrlEncoded::<Info>::new(&req, &mut pl).await.is_ok());
531
532        let (req, mut pl, ()) = TestRequest::with_header(
533            CONTENT_TYPE,
534            "application/x-www-form-urlencoded; charset=utf-8",
535        )
536        .header(CONTENT_LENGTH, "11")
537        .payload(Bytes::from_static(b"hello=world&counter=123"))
538        .to_http_parts();
539
540        let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
541        assert_eq!(
542            info,
543            Info {
544                hello: "world".to_owned(),
545                counter: 123
546            }
547        );
548
549        let (req, mut pl, ()) = TestRequest::with_header(
550            CONTENT_TYPE,
551            "application/x-www-form-urlencoded; charset=cp1251",
552        )
553        .header(CONTENT_LENGTH, "11")
554        .payload(Bytes::from_static(b"hello=world&counter=123"))
555        .to_http_parts();
556
557        let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
558        assert_eq!(
559            info,
560            Info {
561                hello: "world".to_owned(),
562                counter: 123
563            }
564        );
565    }
566
567    /// STATEMENT: Form fields are decoded with the declared charset and rejected if invalid.
568    ///
569    /// HOW:
570    /// - Deserialize bodies using raw bytes, `+`, `%XX`, escaped delimiters, malformed escapes,
571    ///   empty fields and fields without `=` under UTF-8, `windows-1252`, `shift_jis` and
572    ///   `utf-16le` charsets.
573    /// - Assert the decoded `hello` value, or `Parse` for bytes invalid in the charset.
574    /// - Assert empty fields add no map entries, and a missing charset rejects invalid UTF-8.
575    #[crate::rt_test]
576    async fn test_urlencoded_charset() {
577        let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(u16::to_le_bytes).collect() };
578        let cases: Vec<(&str, Vec<u8>, Option<&str>)> = vec![
579            (
580                "windows-1252",
581                b"hello=caf%E9&counter=1".to_vec(),
582                Some("caf\u{e9}"),
583            ),
584            (
585                "windows-1252",
586                b"hello=caf\xe9&counter=1".to_vec(),
587                Some("caf\u{e9}"),
588            ),
589            (
590                "windows-1252",
591                b"hello=a%26b%3Dc+d&&counter=1&".to_vec(),
592                Some("a&b=c d"),
593            ),
594            (
595                "windows-1252",
596                b"hello=100%25%zz%4&counter=1".to_vec(),
597                Some("100%%zz%4"),
598            ),
599            ("windows-1252", b"counter=1&hello".to_vec(), Some("")),
600            ("windows-1252", b"h%65llo=x&counter=1".to_vec(), Some("x")),
601            (
602                "shift_jis",
603                b"hello=%82%A0&counter=1".to_vec(),
604                Some("\u{3042}"),
605            ),
606            ("shift_jis", b"hello=%82&counter=1".to_vec(), None),
607            ("shift_jis", b"h%82=x&counter=1".to_vec(), None),
608            (
609                "utf-8",
610                b"hello=caf%C3%A9+x&counter=1".to_vec(),
611                Some("caf\u{e9} x"),
612            ),
613            ("utf-8", b"hello=caf%E9&counter=1".to_vec(), None),
614            ("utf-8", b"hello=caf\xff&counter=1".to_vec(), None),
615            (
616                "utf-16le",
617                utf16("hello=caf%C3%A9&counter=1"),
618                Some("caf\u{e9}"),
619            ),
620            ("utf-16le", utf16("hello=caf%E9&counter=1"), None),
621            ("utf-16le", b"hello=x&counter=1".to_vec(), None),
622        ];
623        for (charset, body, expected) in cases {
624            let (req, mut pl, ()) = TestRequest::with_header(
625                CONTENT_TYPE,
626                format!("application/x-www-form-urlencoded; charset={charset}"),
627            )
628            .payload(Bytes::from(body.clone()))
629            .to_http_parts();
630            let res = UrlEncoded::<Info>::new(&req, &mut pl).await;
631            match expected {
632                Some(hello) => assert_eq!(res.unwrap().hello, hello, "{charset} {body:?}"),
633                None => assert!(
634                    matches!(res, Err(UrlencodedError::Parse)),
635                    "{charset} {body:?}"
636                ),
637            }
638        }
639
640        // empty fields are skipped, not decoded as an empty name
641        let (req, mut pl, ()) = TestRequest::with_header(
642            CONTENT_TYPE,
643            "application/x-www-form-urlencoded; charset=windows-1252",
644        )
645        .payload(Bytes::from_static(b"&a=1&&b=2&"))
646        .to_http_parts();
647        let res = UrlEncoded::<std::collections::HashMap<String, String>>::new(&req, &mut pl)
648            .await
649            .unwrap();
650        assert_eq!(res.len(), 2, "{res:?}");
651
652        // a missing charset means UTF-8
653        let (req, mut pl, ()) =
654            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
655                .payload(Bytes::from_static(b"hello=caf%FF&counter=1"))
656                .to_http_parts();
657        let res = UrlEncoded::<Info>::new(&req, &mut pl).await;
658        assert!(matches!(res, Err(UrlencodedError::Parse)));
659    }
660
661    /// STATEMENT: Form responders serialize fields with the URL-encoded media type.
662    ///
663    /// HOW:
664    /// - Respond with `Form<Info>` containing a string and counter.
665    /// - Assert OK, `application/x-www-form-urlencoded`, and the exact encoded body.
666    #[crate::rt_test]
667    async fn test_responder() {
668        let req = TestRequest::default().to_http_request();
669
670        let form = Form(Info {
671            hello: "world".to_string(),
672            counter: 123,
673        });
674        let resp = respond_to(form, &req).await;
675        assert_eq!(resp.status(), StatusCode::OK);
676        assert_eq!(
677            resp.headers().get(CONTENT_TYPE).unwrap(),
678            HeaderValue::from_static("application/x-www-form-urlencoded")
679        );
680
681        assert_eq!(resp.get_body_ref(), b"hello=world&counter=123");
682    }
683
684    /// STATEMENT: URL-encoded reading validates charset, header encoding, and streamed size limits.
685    ///
686    /// HOW:
687    /// - Supply an unknown charset and a non-UTF-8 length header and assert their respective errors.
688    /// - Omit content length, read a body beyond a five-byte limit, and assert `Overflow`.
689    #[crate::rt_test]
690    async fn test_urlencoded_errors2() {
691        let (req, mut pl, ()) = TestRequest::with_header(
692            CONTENT_TYPE,
693            "application/x-www-form-urlencoded; charset=unknown",
694        )
695        .to_http_parts();
696        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
697        assert!(eq(&info.err().unwrap(), &UrlencodedError::ContentType));
698
699        let (req, mut pl, ()) =
700            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
701                .header(CONTENT_LENGTH, HeaderValue::from_bytes(b"1\xff").unwrap())
702                .to_http_parts();
703        let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
704        assert!(eq(&info.err().unwrap(), &UrlencodedError::UnknownLength));
705
706        // no content-length, payload is larger than limit
707        let (req, mut pl, ()) =
708            TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
709                .payload(Bytes::from_static(b"hello=world&counter=123"))
710                .to_http_parts();
711        let info = UrlEncoded::<Info>::new(&req, &mut pl).limit(5).await;
712        assert!(eq(
713            &info.err().unwrap(),
714            &UrlencodedError::Overflow { size: 0, limit: 0 }
715        ));
716    }
717
718    /// STATEMENT: An unserializable form value produces an internal-server-error response.
719    ///
720    /// HOW:
721    /// - Respond with `Form(1)`, which cannot be encoded as form fields.
722    /// - Assert status `INTERNAL_SERVER_ERROR`.
723    #[crate::rt_test]
724    async fn test_responder_error() {
725        let req = TestRequest::default().to_http_request();
726        let resp = respond_to(Form(1), &req).await;
727        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
728    }
729}