use std::convert::Infallible;
use super::{HttpRequest, State, WebResponseError};
use crate::http::Payload;
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be used as a handler argument",
label = "not a request extractor",
note = "handler arguments must implement `FromRequest`, for example `HttpRequest`, `web::types::Path<T>`, `Query<T>`, `Json<T>`, `Form<T>`, or `Payload`",
note = "implement `FromRequest<St>` for `{Self}` to extract it from the request"
)]
pub trait FromRequest<St>: Sized {
type Error;
async fn from_request(
st: &St,
req: &HttpRequest,
payload: &mut Payload,
) -> Result<Self, Self::Error>;
}
impl<St, T> FromRequest<St> for Option<T>
where
St: State,
T: FromRequest<St>,
<T as FromRequest<St>>::Error: WebResponseError<St, St::Error>,
{
type Error = Infallible;
#[inline]
async fn from_request(
st: &St,
req: &HttpRequest,
payload: &mut Payload,
) -> Result<Option<T>, Self::Error> {
match T::from_request(st, req, payload).await {
Ok(v) => Ok(Some(v)),
Err(e) => {
log::debug!("Error for Option<T> extractor: {e}");
Ok(None)
}
}
}
}
impl<St, T> FromRequest<St> for Result<T, T::Error>
where
St: State,
T: FromRequest<St>,
{
type Error = T::Error;
#[inline]
async fn from_request(
st: &St,
req: &HttpRequest,
payload: &mut Payload,
) -> Result<Self, Self::Error> {
match T::from_request(st, req, payload).await {
Ok(v) => Ok(Ok(v)),
Err(e) => Ok(Err(e)),
}
}
}
#[doc(hidden)]
impl<St: State> FromRequest<St> for () {
type Error = Infallible;
#[inline]
async fn from_request(_: &St, _: &HttpRequest, _: &mut Payload) -> Result<(), Self::Error> {
Ok(())
}
}
macro_rules! tuple_from_req {
($(#[$meta:meta])* $(($T:ident, $t:ident)),*) => {
$(#[$meta])*
impl<St, $($T,)+> FromRequest<St> for ($($T,)+)
where
St: State,
$($T: FromRequest<St> + 'static,)+
$(<$T as $crate::web::FromRequest<St>>::Error: WebResponseError<St, St::Error>),+
{
type Error = $crate::web::InternalError<&'static str>;
async fn from_request(st: &St, req: &HttpRequest, payload: &mut Payload) -> Result<($($T,)+), Self::Error> {
Ok((
$($T::from_request(st, req, payload).await.map_err(
|e|
$crate::web::InternalError::from_response("Error", e.error_response(st)))?,)+
))
}
}
}
}
#[allow(non_snake_case, clippy::wildcard_imports)]
#[rustfmt::skip]
mod m {
use super::*;
use variadics_please::all_tuples;
all_tuples!(#[doc(fake_variadic)] tuple_from_req, 1, 12, T, t);
}
#[cfg(test)]
mod tests {
use crate::http::header;
use crate::util::Bytes;
use crate::web::error::{PayloadError, UrlencodedError};
use crate::web::test::{TestRequest, from_request};
use crate::web::types::{Form, FormConfig, Json, PayloadConfig};
#[derive(serde::Deserialize, Debug, PartialEq)]
struct Info {
hello: String,
}
#[crate::rt_test]
async fn test_option() {
let (req, mut pl, ()) =
TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.app_value(FormConfig::default().limit(4096))
.to_http_parts();
let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
.await
.unwrap();
assert_eq!(r, None);
let (req, mut pl, ()) =
TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(header::CONTENT_LENGTH, "9")
.payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
.await
.unwrap();
assert_eq!(
r,
Some(Form(Info {
hello: "world".into()
}))
);
let (req, mut pl, ()) =
TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(header::CONTENT_LENGTH, "9")
.payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = from_request::<_, Option<Form<Info>>>(&(), &req, &mut pl)
.await
.unwrap();
assert_eq!(r, None);
}
#[crate::rt_test]
async fn test_result() {
let (req, mut pl, ()) =
TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(header::CONTENT_LENGTH, "11")
.payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = from_request::<_, Result<Form<Info>, UrlencodedError>>(&(), &req, &mut pl)
.await
.unwrap();
assert_eq!(
r.unwrap(),
Form(Info {
hello: "world".into()
})
);
let (req, mut pl, ()) =
TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(header::CONTENT_LENGTH, "9")
.payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = from_request::<_, Result<Form<Info>, UrlencodedError>>(&(), &req, &mut pl)
.await
.unwrap();
assert!(r.is_err());
}
#[crate::rt_test]
async fn test_optional_json_suppresses_validation() {
use crate::http::{Method, StatusCode};
use crate::web::error::JsonPayloadError;
use crate::web::test::{call_service, init_service, read_body};
use crate::web::types::JsonConfig;
use crate::web::{self, App, WebAppConfig};
use std::{cell::Cell, rc::Rc};
type Value = Json<serde_json::Value>;
let calls = Rc::new([Cell::new(0), Cell::new(0), Cell::new(0)]);
let (c1, c2, c3) = (calls.clone(), calls.clone(), calls.clone());
let srv = init_service(
App::new()
.with_config(WebAppConfig::new().set_value(JsonConfig::default().limit(8)))
.route(
"/required",
web::post().to(async move |v: Value| {
c1[0].set(c1[0].get() + 1);
v.into_inner().to_string()
}),
)
.route(
"/option",
web::post().to(async move |v: Option<Value>| {
c2[1].set(c2[1].get() + 1);
v.map_or_else(|| "none".to_owned(), |v| v.into_inner().to_string())
}),
)
.route(
"/result",
web::post().to(async move |v: Result<Value, JsonPayloadError>| {
c3[2].set(c3[2].get() + 1);
match v {
Ok(v) => v.into_inner().to_string(),
Err(JsonPayloadError::ContentType) => "content-type".to_owned(),
Err(JsonPayloadError::Deserialize(_)) => "deserialize".to_owned(),
Err(JsonPayloadError::Overflow) => "overflow".to_owned(),
Err(JsonPayloadError::Payload(_)) => "payload".to_owned(),
}
}),
),
)
.await;
let cases: [(&str, Option<&'static [u8]>, StatusCode, &str, &str); 4] = [
(
"absent",
None,
StatusCode::BAD_REQUEST,
"none",
"content-type",
),
(
"valid",
Some(b"{\"a\":1}"),
StatusCode::OK,
"{\"a\":1}",
"{\"a\":1}",
),
(
"malformed",
Some(b"{\"a\":"),
StatusCode::BAD_REQUEST,
"none",
"deserialize",
),
(
"oversized",
Some(b"{\"a\":1234567}"),
StatusCode::PAYLOAD_TOO_LARGE,
"none",
"overflow",
),
];
let request = |path: &str, body: Option<&'static [u8]>| {
let req = TestRequest::with_uri(path).method(Method::POST);
match body {
None => req.to_request(),
Some(body) => req
.header(header::CONTENT_TYPE, "application/json")
.header(header::CONTENT_LENGTH, body.len().to_string())
.payload(Bytes::from_static(body))
.to_request(),
}
};
let mut required_calls = 0;
for (n, (input, body, status, option, result)) in cases.into_iter().enumerate() {
let resp = call_service(&srv, request("/required", body)).await;
assert_eq!(resp.status(), status, "required {input}");
required_calls += usize::from(status == StatusCode::OK);
assert_eq!(calls[0].get(), required_calls, "required {input}");
for (path, idx, expected) in [("/option", 1, option), ("/result", 2, result)] {
let resp = call_service(&srv, request(path, body)).await;
assert_eq!(resp.status(), StatusCode::OK, "{path} {input}");
assert_eq!(read_body(resp).await, expected.as_bytes(), "{path} {input}");
assert_eq!(calls[idx].get(), n + 1, "{path} {input}");
}
}
}
fn body_parts(
ctype: &'static str,
body: &'static [u8],
) -> (crate::web::HttpRequest, crate::http::Payload, ()) {
TestRequest::with_header(header::CONTENT_TYPE, ctype)
.header(header::CONTENT_LENGTH, body.len().to_string())
.payload(Bytes::from_static(body))
.to_http_parts()
}
#[crate::rt_test]
async fn test_optional_body_fallback_depends_on_failure_phase() {
type Args = (Option<Json<serde_json::Value>>, Bytes);
let (req, mut pl, ()) = body_parts("text/plain", b"{\"a\":1}");
let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
assert!(json.is_none());
assert_eq!(rest, Bytes::from_static(b"{\"a\":1}"));
let (req, mut pl, ()) = body_parts("application/json", b"{\"a\":");
let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
assert!(json.is_none());
assert!(rest.is_empty());
let (req, mut pl, ()) = body_parts("application/json", b"{\"a\":1}");
let (json, rest) = from_request::<_, Args>(&(), &req, &mut pl).await.unwrap();
assert_eq!(json.unwrap().into_inner(), serde_json::json!({"a": 1}));
assert!(rest.is_empty());
}
#[crate::rt_test]
async fn test_single_read_body_fallback() {
for (ctype, body, parsed) in [
("application/json", &b"{\"a\":1}"[..], true),
("application/json", &b"{\"a\":"[..], false),
("text/plain", &b"{\"a\":1}"[..], true),
] {
let (req, mut pl, ()) = body_parts(ctype, body);
let raw = from_request::<_, Bytes>(&(), &req, &mut pl).await.unwrap();
assert_eq!(raw, Bytes::copy_from_slice(body));
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&raw).is_ok(),
parsed,
"{ctype} {body:?}"
);
}
let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
.header(header::CONTENT_LENGTH, "7")
.payload(Bytes::from_static(b"{\"a\":1}"))
.app_value(PayloadConfig::new(4))
.to_http_parts();
let err = from_request::<_, Bytes>(&(), &req, &mut pl)
.await
.unwrap_err();
assert!(
matches!(
err,
PayloadError::Payload(crate::http::error::PayloadError::Overflow)
),
"{err:?}"
);
}
}