ntex/web/extract.rs
1//! Request extractors
2use std::{convert::Infallible, future, future::Future};
3
4use super::{HttpRequest, State, WebResponseError};
5use crate::http::Payload;
6
7/// Turns request data into a value that a handler can use.
8///
9/// Each argument accepted by a handler registered with
10/// [`Route::to()`](super::Route::to) is an extractor. Before calling the
11/// handler, ntex asks each argument type to create its value from the incoming
12/// request.
13///
14/// An extractor can look at the application state, request headers, path, and
15/// other request information. It can also read the request body through the
16/// payload. Extractors run in the same order as the handler arguments and
17/// share that payload, so an extractor that reads the body may leave nothing
18/// for the next one. For that reason, a handler should normally have only one
19/// body-reading extractor.
20///
21/// A failed body extractor may also have consumed the body, depending on where
22/// it failed. For example, `Json<T>` rejects an unsupported content type before
23/// reading anything, but it has already read the body when deserialization
24/// fails. Wrapping it in `Option<T>` or `Result<T, E>` therefore does not make
25/// `(Option<Json<T>>, Bytes)` a reliable "JSON or raw body" fallback. To fall
26/// back to the raw body, extract `Bytes` once and parse the retained bytes, for
27/// example with `serde_json::from_slice()`.
28/// [`PayloadConfig`](super::types::PayloadConfig) limits that buffer.
29///
30/// When an extractor returns an error, ntex turns it into an HTTP response and
31/// skips the handler. The error must implement [`WebResponseError`] for the
32/// application. If the handler should still run, use `Option<T>` to receive
33/// `None`, or `Result<T, T::Error>` to receive the original error. Both also
34/// let malformed or oversized input through, so the handler must reject it
35/// itself when that matters.
36///
37/// # Example
38///
39/// A custom extractor can turn a request header into a handler argument:
40///
41/// ```rust
42/// use ntex::http::Payload;
43/// use ntex::web::{self, FromRequest, HttpRequest, InternalError};
44///
45/// struct ClientName(String);
46///
47/// impl<St: web::State> FromRequest<St> for ClientName {
48/// type Error = InternalError<&'static str>;
49///
50/// async fn from_request(_: &St, req: &HttpRequest, _: &mut Payload) -> Result<Self, Self::Error> {
51/// req.headers()
52/// .get("x-client-name")
53/// .and_then(|value| value.to_str().ok())
54/// .map(|value| ClientName(value.to_owned()))
55/// .ok_or_else(|| web::error::ErrorBadRequest("Missing client name"))
56/// }
57/// }
58///
59/// async fn hello(client: ClientName) -> String {
60/// format!("Hello, {}!", client.0)
61/// }
62///
63/// let app = web::App::default().route("/", web::get().to(hello));
64/// ```
65#[diagnostic::on_unimplemented(
66 message = "`{Self}` cannot be used as a handler argument",
67 label = "not a request extractor",
68 note = "handler arguments must implement `FromRequest`, for example `HttpRequest`, `web::types::Path<T>`, `Query<T>`, `Json<T>`, `Form<T>`, or `Payload`",
69 note = "implement `FromRequest<St>` for `{Self}` to extract it from the request"
70)]
71pub trait FromRequest<St>: Sized {
72 /// The error returned when extraction fails.
73 ///
74 /// For a route handler, ntex must be able to turn this error into an HTTP
75 /// response through [`WebResponseError`].
76 type Error;
77
78 /// Creates the extractor value for this request.
79 async fn from_request(
80 st: &St,
81 req: &HttpRequest,
82 payload: &mut Payload,
83 ) -> Result<Self, Self::Error>;
84}
85
86/// Optionally extract a field from the request
87///
88/// If the `FromRequest` for T fails, return None rather than returning an error response
89///
90/// `None` covers every extraction error, not only missing input. Input that is
91/// present but invalid also becomes `None`, and the handler runs. For example,
92/// `Option<Json<T>>` receives `None` for a missing body, a wrong content type,
93/// malformed JSON, and a body over the [`JsonConfig`](super::types::JsonConfig)
94/// limit, where `Json<T>` would reject the last two with 400 and 413. Use
95/// `Option<T>` only when such input may be ignored. To accept missing input
96/// but still reject invalid input, extract `Result<T, T::Error>` and return the
97/// errors that should still fail the request.
98///
99/// The request body is not rewound. If `T` reads the body before failing, later
100/// extractors see only what remains. See [`FromRequest`] for a single-read
101/// fallback pattern.
102///
103/// ## Example
104///
105/// ```rust
106/// use ntex::http;
107/// use ntex::web::{self, error, App, HttpRequest, FromRequest, InternalError};
108/// use rand;
109///
110/// #[derive(Debug, serde::Deserialize)]
111/// struct Thing {
112/// name: String
113/// }
114///
115/// impl<St> FromRequest<St> for Thing {
116/// type Error = InternalError<&'static str>;
117///
118/// async fn from_request(st: &St, req: &HttpRequest, payload: &mut http::Payload) -> Result<Self, Self::Error> {
119/// if rand::random() {
120/// Ok(Thing { name: "thingy".into() })
121/// } else {
122/// Err(error::ErrorBadRequest("no luck"))
123/// }
124/// }
125/// }
126///
127/// /// extract `Thing` from request
128/// async fn index(supplied_thing: Option<Thing>) -> String {
129/// match supplied_thing {
130/// // Puns not intended
131/// Some(thing) => format!("Got something: {:?}", thing),
132/// None => format!("No thing!")
133/// }
134/// }
135///
136/// fn main() {
137/// let app = App::default().service(
138/// web::resource("/users/{first}").route(
139/// web::post().to(index))
140/// );
141/// }
142/// ```
143impl<St, T> FromRequest<St> for Option<T>
144where
145 St: State,
146 T: FromRequest<St>,
147 <T as FromRequest<St>>::Error: WebResponseError<St, St::Error>,
148{
149 type Error = Infallible;
150
151 #[inline]
152 async fn from_request(
153 st: &St,
154 req: &HttpRequest,
155 payload: &mut Payload,
156 ) -> Result<Option<T>, Self::Error> {
157 match T::from_request(st, req, payload).await {
158 Ok(v) => Ok(Some(v)),
159 Err(e) => {
160 log::debug!("Error for Option<T> extractor: {e}");
161 Ok(None)
162 }
163 }
164 }
165}
166
167/// Optionally extract a field from the request or extract the Error if unsuccessful
168///
169/// If the `FromRequest` for T fails, inject Err into handler rather than returning an error response
170///
171/// As with `Option<T>`, the request body is not rewound after a failure.
172///
173/// ## Example
174///
175/// ```rust
176/// use ntex::http;
177/// use ntex::web::{self, error, App, State, HttpRequest, FromRequest, InternalError};
178/// use rand;
179///
180/// #[derive(Debug, serde::Deserialize)]
181/// struct Thing {
182/// name: String
183/// }
184///
185/// impl<St: State> FromRequest<St> for Thing {
186/// type Error = InternalError<&'static str>;
187///
188/// async fn from_request(st: &St, req: &HttpRequest, payload: &mut http::Payload) -> Result<Thing, Self::Error> {
189/// if rand::random() {
190/// Ok(Thing { name: "thingy".into() })
191/// } else {
192/// Err(error::ErrorBadRequest("no luck"))
193/// }
194/// }
195/// }
196///
197/// /// extract `Thing` from request
198/// async fn index(supplied_thing: Result<Thing, InternalError<&'static str>>) -> String {
199/// match supplied_thing {
200/// Ok(thing) => format!("Got thing: {:?}", thing),
201/// Err(e) => format!("Error extracting thing: {}", e)
202/// }
203/// }
204///
205/// fn main() {
206/// let app = App::default().service(
207/// web::resource("/users/{first}").route(web::post().to(index))
208/// );
209/// }
210/// ```
211impl<St, T> FromRequest<St> for Result<T, T::Error>
212where
213 St: State,
214 T: FromRequest<St>,
215{
216 type Error = T::Error;
217
218 #[inline]
219 async fn from_request(
220 st: &St,
221 req: &HttpRequest,
222 payload: &mut Payload,
223 ) -> Result<Self, Self::Error> {
224 match T::from_request(st, req, payload).await {
225 Ok(v) => Ok(Ok(v)),
226 Err(e) => Ok(Err(e)),
227 }
228 }
229}
230
231#[doc(hidden)]
232impl<St: State> FromRequest<St> for () {
233 type Error = Infallible;
234
235 #[inline]
236 fn from_request(
237 _: &St,
238 _: &HttpRequest,
239 _: &mut Payload,
240 ) -> impl Future<Output = Result<(), Self::Error>> {
241 future::ready(Ok(()))
242 }
243}
244
245macro_rules! tuple_from_req {
246 ($(#[$meta:meta])* $(($T:ident, $t:ident)),*) => {
247 $(#[$meta])*
248 impl<St, $($T,)+> FromRequest<St> for ($($T,)+)
249 where
250 St: State,
251 $($T: FromRequest<St> + 'static,)+
252 $(<$T as $crate::web::FromRequest<St>>::Error: WebResponseError<St, St::Error>),+
253 {
254 type Error = $crate::web::InternalError<&'static str>;
255
256 // An `async` block, unlike an `async fn`, does not keep a second copy
257 // of the arguments in the future
258 #[allow(clippy::manual_async_fn)]
259 fn from_request(st: &St, req: &HttpRequest, payload: &mut Payload) -> impl Future<Output = Result<($($T,)+), Self::Error>> {
260 async move {
261 Ok((
262 $($T::from_request(st, req, payload).await.map_err(
263 |e|
264 $crate::web::InternalError::from_response("Error", e.error_response(st)))?,)+
265 ))
266 }
267 }
268 }
269 }
270}
271
272#[allow(non_snake_case, clippy::wildcard_imports)]
273#[rustfmt::skip]
274mod m {
275 use super::*;
276 use variadics_please::all_tuples;
277
278 all_tuples!(#[doc(fake_variadic)] tuple_from_req, 1, 12, T, t);
279}
280
281#[cfg(test)]
282mod tests {
283 use crate::http::header;
284 use crate::util::Bytes;
285 use crate::web::error::{PayloadError, UrlencodedError};
286 use crate::web::test::{TestRequest, from_request};
287 use crate::web::types::{Form, FormConfig, Json, PayloadConfig};
288
289 #[derive(serde::Deserialize, Debug, PartialEq)]
290 struct Info {
291 hello: String,
292 }
293
294 /// STATEMENT: Optional extractors turn extraction failures into `None` and retain valid values.
295 ///
296 /// HOW:
297 /// - Extract `Option<Form<Info>>` from empty, valid, and missing-field URL-encoded bodies.
298 /// - Assert `None`, the expected `hello` value, and `None`, respectively.
299 #[crate::rt_test]
300 async fn test_option() {
301 let (req, mut pl, ()) =
302 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
303 .app_value(FormConfig::default().limit(4096))
304 .to_http_parts();
305
306 let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
307 .await
308 .unwrap();
309 assert_eq!(r, None);
310
311 let (req, mut pl, ()) =
312 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
313 .header(header::CONTENT_LENGTH, "9")
314 .payload(Bytes::from_static(b"hello=world"))
315 .to_http_parts();
316
317 let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
318 .await
319 .unwrap();
320 assert_eq!(
321 r,
322 Some(Form(Info {
323 hello: "world".into()
324 }))
325 );
326
327 let (req, mut pl, ()) =
328 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
329 .header(header::CONTENT_LENGTH, "9")
330 .payload(Bytes::from_static(b"bye=world"))
331 .to_http_parts();
332
333 let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
334 .await
335 .unwrap();
336 assert_eq!(r, None);
337 }
338
339 /// STATEMENT: Result extractors expose inner extraction errors without failing outer extraction.
340 ///
341 /// HOW:
342 /// - Extract `Result<Form<Info>, UrlencodedError>` from valid and missing-field bodies.
343 /// - Assert outer success in both cases, with the expected form value or an inner error.
344 #[crate::rt_test]
345 async fn test_result() {
346 let (req, mut pl, ()) =
347 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
348 .header(header::CONTENT_LENGTH, "11")
349 .payload(Bytes::from_static(b"hello=world"))
350 .to_http_parts();
351
352 let r = from_request::<_, Result<Form<Info>, UrlencodedError>>(&(), &req, &mut pl)
353 .await
354 .unwrap();
355 assert_eq!(
356 r.unwrap(),
357 Form(Info {
358 hello: "world".into()
359 })
360 );
361
362 let (req, mut pl, ()) =
363 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
364 .header(header::CONTENT_LENGTH, "9")
365 .payload(Bytes::from_static(b"bye=world"))
366 .to_http_parts();
367
368 let r = from_request::<_, Result<Form<Info>, UrlencodedError>>(&(), &req, &mut pl)
369 .await
370 .unwrap();
371 assert!(r.is_err());
372 }
373
374 /// STATEMENT: `Option<Json<T>>` turns malformed and oversized bodies into `None` and
375 /// runs the handler, where `Json<T>` rejects them; `Result<Json<T>, _>` keeps the cause.
376 ///
377 /// HOW:
378 /// - Serve `Json<Value>`, `Option<Json<Value>>` and `Result<Json<Value>, JsonPayloadError>`
379 /// routes with `JsonConfig::limit(8)`, counting handler invocations per route.
380 /// - Send an absent body, valid JSON, malformed JSON and a 13-byte body to each route.
381 /// - Assert `Json` returns 200, 400, 400 and 413 and runs only for valid input, while the
382 /// optional routes return 200 and run every time, receiving `None` or the matching
383 /// `ContentType`, `Deserialize` or `Overflow` error for every non-valid input.
384 #[crate::rt_test]
385 async fn test_optional_json_suppresses_validation() {
386 use crate::http::{Method, StatusCode};
387 use crate::web::error::JsonPayloadError;
388 use crate::web::test::{call_service, init_service, read_body};
389 use crate::web::types::JsonConfig;
390 use crate::web::{self, App, WebAppConfig};
391 use std::{cell::Cell, rc::Rc};
392
393 type Value = Json<serde_json::Value>;
394
395 let calls = Rc::new([Cell::new(0), Cell::new(0), Cell::new(0)]);
396 let (c1, c2, c3) = (calls.clone(), calls.clone(), calls.clone());
397 let srv = init_service(
398 App::new()
399 .with_config(WebAppConfig::new().set_value(JsonConfig::default().limit(8)))
400 .route(
401 "/required",
402 web::post().to(async move |v: Value| {
403 c1[0].set(c1[0].get() + 1);
404 v.into_inner().to_string()
405 }),
406 )
407 .route(
408 "/option",
409 web::post().to(async move |v: Option<Value>| {
410 c2[1].set(c2[1].get() + 1);
411 v.map_or_else(|| "none".to_owned(), |v| v.into_inner().to_string())
412 }),
413 )
414 .route(
415 "/result",
416 web::post().to(async move |v: Result<Value, JsonPayloadError>| {
417 c3[2].set(c3[2].get() + 1);
418 match v {
419 Ok(v) => v.into_inner().to_string(),
420 Err(JsonPayloadError::ContentType) => "content-type".to_owned(),
421 Err(JsonPayloadError::Deserialize(_)) => "deserialize".to_owned(),
422 Err(JsonPayloadError::Overflow) => "overflow".to_owned(),
423 Err(JsonPayloadError::Payload(_)) => "payload".to_owned(),
424 }
425 }),
426 ),
427 )
428 .await;
429
430 // (input, body, required status, option body, result body)
431 let cases: [(&str, Option<&'static [u8]>, StatusCode, &str, &str); 4] = [
432 (
433 "absent",
434 None,
435 StatusCode::BAD_REQUEST,
436 "none",
437 "content-type",
438 ),
439 (
440 "valid",
441 Some(b"{\"a\":1}"),
442 StatusCode::OK,
443 "{\"a\":1}",
444 "{\"a\":1}",
445 ),
446 (
447 "malformed",
448 Some(b"{\"a\":"),
449 StatusCode::BAD_REQUEST,
450 "none",
451 "deserialize",
452 ),
453 (
454 "oversized",
455 Some(b"{\"a\":1234567}"),
456 StatusCode::PAYLOAD_TOO_LARGE,
457 "none",
458 "overflow",
459 ),
460 ];
461 let request = |path: &str, body: Option<&'static [u8]>| {
462 let req = TestRequest::with_uri(path).method(Method::POST);
463 match body {
464 None => req.to_request(),
465 Some(body) => req
466 .header(header::CONTENT_TYPE, "application/json")
467 .header(header::CONTENT_LENGTH, body.len().to_string())
468 .payload(Bytes::from_static(body))
469 .to_request(),
470 }
471 };
472
473 let mut required_calls = 0;
474 for (n, (input, body, status, option, result)) in cases.into_iter().enumerate() {
475 let resp = call_service(&srv, request("/required", body)).await;
476 assert_eq!(resp.status(), status, "required {input}");
477 required_calls += usize::from(status == StatusCode::OK);
478 assert_eq!(calls[0].get(), required_calls, "required {input}");
479
480 for (path, idx, expected) in [("/option", 1, option), ("/result", 2, result)] {
481 let resp = call_service(&srv, request(path, body)).await;
482 assert_eq!(resp.status(), StatusCode::OK, "{path} {input}");
483 assert_eq!(read_body(resp).await, expected.as_bytes(), "{path} {input}");
484 assert_eq!(calls[idx].get(), n + 1, "{path} {input}");
485 }
486 }
487 }
488
489 fn body_parts(
490 ctype: &'static str,
491 body: &'static [u8],
492 ) -> (crate::web::HttpRequest, crate::http::Payload, ()) {
493 TestRequest::with_header(header::CONTENT_TYPE, ctype)
494 .header(header::CONTENT_LENGTH, body.len().to_string())
495 .payload(Bytes::from_static(body))
496 .to_http_parts()
497 }
498
499 /// STATEMENT: An optional body extractor followed by `Bytes` is not a reliable fallback;
500 /// what `Bytes` receives depends on where the optional extractor stopped.
501 ///
502 /// HOW:
503 /// - Extract `(Option<Json<Value>>, Bytes)` from a `text/plain` JSON body and assert
504 /// `None` with the whole body left for `Bytes`, because the media-type check fails
505 /// before reading.
506 /// - Repeat with malformed `application/json` and assert `None` with an empty `Bytes`,
507 /// because deserialization fails after reading the body.
508 /// - Repeat with valid `application/json` and assert the parsed value with an empty `Bytes`.
509 #[crate::rt_test]
510 async fn test_optional_body_fallback_depends_on_failure_phase() {
511 type Args = (Option<Json<serde_json::Value>>, Bytes);
512
513 let (req, mut pl, ()) = body_parts("text/plain", b"{\"a\":1}");
514 let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
515 assert!(json.is_none());
516 assert_eq!(rest, Bytes::from_static(b"{\"a\":1}"));
517
518 let (req, mut pl, ()) = body_parts("application/json", b"{\"a\":");
519 let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
520 assert!(json.is_none());
521 assert!(rest.is_empty());
522
523 let (req, mut pl, ()) = body_parts("application/json", b"{\"a\":1}");
524 let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
525 assert_eq!(json.unwrap().into_inner(), serde_json::json!({"a": 1}));
526 assert!(rest.is_empty());
527 }
528
529 /// STATEMENT: Reading the body once as `Bytes` and parsing the retained bytes gives a
530 /// fallback that keeps the whole body, within the `PayloadConfig` limit.
531 ///
532 /// HOW:
533 /// - Extract `Bytes` from valid JSON, malformed JSON, and a non-JSON content type.
534 /// - Assert `serde_json::from_slice()` parses the valid body, fails on the malformed one,
535 /// and the retained `Bytes` equals the full request body in every case.
536 /// - Set `PayloadConfig::new(4)` and assert a 7-byte body fails with
537 /// `PayloadError::Overflow` instead of being buffered.
538 #[crate::rt_test]
539 async fn test_single_read_body_fallback() {
540 for (ctype, body, parsed) in [
541 ("application/json", &b"{\"a\":1}"[..], true),
542 ("application/json", &b"{\"a\":"[..], false),
543 ("text/plain", &b"{\"a\":1}"[..], true),
544 ] {
545 let (req, mut pl, ()) = body_parts(ctype, body);
546 let raw = from_request::<_, Bytes>(&(), &req, &mut pl).await.unwrap();
547 assert_eq!(raw, Bytes::copy_from_slice(body));
548 assert_eq!(
549 serde_json::from_slice::<serde_json::Value>(&raw).is_ok(),
550 parsed,
551 "{ctype} {body:?}"
552 );
553 }
554
555 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
556 .header(header::CONTENT_LENGTH, "7")
557 .payload(Bytes::from_static(b"{\"a\":1}"))
558 .app_value(PayloadConfig::new(4))
559 .to_http_parts();
560 let err = from_request::<_, Bytes>(&(), &req, &mut pl)
561 .await
562 .unwrap_err();
563 assert!(
564 matches!(
565 err,
566 PayloadError::Payload(crate::http::error::PayloadError::Overflow)
567 ),
568 "{err:?}"
569 );
570 }
571}