Files
axum/src/extract.rs
T

482 lines
12 KiB
Rust
Raw Normal View History

2021-05-31 22:54:21 +02:00
use crate::{
body::Body,
response::{BoxIntoResponse, IntoResponse},
};
2021-05-31 12:55:39 +02:00
use async_trait::async_trait;
2021-05-30 14:33:20 +02:00
use bytes::Bytes;
2021-05-31 22:54:21 +02:00
use http::{header, Request};
2021-05-30 13:24:03 +02:00
use serde::de::DeserializeOwned;
2021-05-31 22:54:21 +02:00
use std::{collections::HashMap, convert::Infallible, str::FromStr};
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
pub trait FromRequest<B>: Sized {
type Rejection: IntoResponse<B>;
2021-05-31 14:04:05 +02:00
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection>;
2021-05-31 14:04:05 +02:00
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<T, B> FromRequest<B> for Option<T>
2021-05-30 13:24:03 +02:00
where
2021-05-31 22:54:21 +02:00
T: FromRequest<B>,
2021-05-30 13:24:03 +02:00
{
2021-05-31 22:54:21 +02:00
type Rejection = Infallible;
async fn from_request(req: &mut Request<Body>) -> Result<Option<T>, Self::Rejection> {
2021-05-31 12:55:39 +02:00
Ok(T::from_request(req).await.ok())
2021-05-30 13:24:03 +02:00
}
}
2021-05-31 22:54:21 +02:00
macro_rules! define_rejection {
(
#[status = $status:ident]
#[body = $body:expr]
pub struct $name:ident (());
) => {
#[derive(Debug)]
pub struct $name(());
impl IntoResponse<Body> for $name {
fn into_response(self) -> http::Response<Body> {
let mut res = http::Response::new(Body::from($body));
*res.status_mut() = http::StatusCode::$status;
res
}
}
};
(
#[status = $status:ident]
#[body = $body:expr]
pub struct $name:ident (BoxError);
) => {
#[derive(Debug)]
pub struct $name(tower::BoxError);
impl $name {
fn from_err<E>(err: E) -> Self
where
E: Into<tower::BoxError>,
{
Self(err.into())
}
}
impl IntoResponse<Body> for $name {
fn into_response(self) -> http::Response<Body> {
let mut res =
http::Response::new(Body::from(format!(concat!($body, ": {}"), self.0)));
*res.status_mut() = http::StatusCode::$status;
res
}
}
};
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Query string was invalid or missing"]
pub struct QueryStringMissing(());
}
2021-05-30 13:24:03 +02:00
#[derive(Debug, Clone, Copy)]
pub struct Query<T>(T);
impl<T> Query<T> {
pub fn into_inner(self) -> T {
self.0
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<T> FromRequest<Body> for Query<T>
2021-05-30 13:24:03 +02:00
where
2021-05-31 12:55:39 +02:00
T: DeserializeOwned,
2021-05-30 13:24:03 +02:00
{
2021-05-31 22:54:21 +02:00
type Rejection = QueryStringMissing;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
let query = req.uri().query().ok_or(QueryStringMissing(()))?;
let value = serde_urlencoded::from_str(query).map_err(|_| QueryStringMissing(()))?;
2021-05-31 12:55:39 +02:00
Ok(Query(value))
2021-05-30 13:24:03 +02:00
}
}
#[derive(Debug, Clone, Copy)]
pub struct Json<T>(T);
impl<T> Json<T> {
pub fn into_inner(self) -> T {
self.0
}
}
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to parse the response body as JSON"]
pub struct InvalidJsonBody(BoxError);
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Expected request with `Content-Type: application/json`"]
pub struct MissingJsonContentType(());
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<T> FromRequest<Body> for Json<T>
2021-05-30 13:24:03 +02:00
where
T: DeserializeOwned,
{
2021-05-31 22:54:21 +02:00
type Rejection = BoxIntoResponse<Body>;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-31 12:22:16 +02:00
if has_content_type(&req, "application/json") {
2021-05-31 22:54:21 +02:00
let body = take_body(req).map_err(IntoResponse::boxed)?;
2021-05-31 12:22:16 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-05-31 22:54:21 +02:00
.map_err(InvalidJsonBody::from_err)
.map_err(IntoResponse::boxed)?;
let value = serde_json::from_slice(&bytes)
.map_err(InvalidJsonBody::from_err)
.map_err(IntoResponse::boxed)?;
2021-05-31 12:55:39 +02:00
Ok(Json(value))
2021-05-31 12:22:16 +02:00
} else {
2021-05-31 22:54:21 +02:00
Err(MissingJsonContentType(()).boxed())
2021-05-31 12:22:16 +02:00
}
}
}
2021-05-30 13:24:03 +02:00
2021-05-31 12:22:16 +02:00
fn has_content_type<B>(req: &Request<B>, expected_content_type: &str) -> bool {
let content_type = if let Some(content_type) = req.headers().get(header::CONTENT_TYPE) {
content_type
} else {
return false;
};
2021-05-30 13:24:03 +02:00
2021-05-31 12:22:16 +02:00
let content_type = if let Ok(content_type) = content_type.to_str() {
content_type
} else {
return false;
};
content_type.starts_with(expected_content_type)
2021-05-30 13:24:03 +02:00
}
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Missing request extension"]
pub struct MissingExtension(());
}
2021-05-30 13:24:03 +02:00
#[derive(Debug, Clone, Copy)]
pub struct Extension<T>(T);
impl<T> Extension<T> {
pub fn into_inner(self) -> T {
self.0
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<T> FromRequest<Body> for Extension<T>
2021-05-30 13:24:03 +02:00
where
T: Clone + Send + Sync + 'static,
{
2021-05-31 22:54:21 +02:00
type Rejection = MissingExtension;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-31 12:55:39 +02:00
let value = req
.extensions()
.get::<T>()
2021-05-31 22:54:21 +02:00
.ok_or(MissingExtension(()))
2021-05-31 12:55:39 +02:00
.map(|x| x.clone())?;
Ok(Extension(value))
2021-05-30 13:24:03 +02:00
}
}
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to buffer the request body"]
pub struct FailedToBufferBody(BoxError);
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl FromRequest<Body> for Bytes {
type Rejection = BoxIntoResponse<Body>;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
let body = take_body(req).map_err(IntoResponse::boxed)?;
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-05-31 22:54:21 +02:00
.map_err(FailedToBufferBody::from_err)
.map_err(IntoResponse::boxed)?;
2021-05-31 12:55:39 +02:00
Ok(bytes)
2021-05-30 14:33:20 +02:00
}
}
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Response body didn't contain valid UTF-8"]
pub struct InvalidUtf8(BoxError);
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl FromRequest<Body> for String {
type Rejection = BoxIntoResponse<Body>;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
let body = take_body(req).map_err(IntoResponse::boxed)?;
2021-05-31 12:22:16 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-05-31 22:54:21 +02:00
.map_err(FailedToBufferBody::from_err)
.map_err(IntoResponse::boxed)?
2021-05-31 12:55:39 +02:00
.to_vec();
2021-05-31 22:54:21 +02:00
let string = String::from_utf8(bytes)
.map_err(InvalidUtf8::from_err)
.map_err(IntoResponse::boxed)?;
2021-05-31 12:55:39 +02:00
Ok(string)
2021-05-31 12:22:16 +02:00
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl FromRequest<Body> for Body {
type Rejection = BodyAlreadyTaken;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
take_body(req)
2021-05-31 12:22:16 +02:00
}
}
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = PAYLOAD_TOO_LARGE]
#[body = "Request payload is too large"]
pub struct PayloadTooLarge(());
}
define_rejection! {
#[status = LENGTH_REQUIRED]
#[body = "Content length header is required"]
pub struct LengthRequired(());
}
2021-05-30 13:24:03 +02:00
#[derive(Debug, Clone)]
2021-05-30 14:33:20 +02:00
pub struct BytesMaxLength<const N: u64>(Bytes);
2021-05-30 13:24:03 +02:00
2021-05-30 14:33:20 +02:00
impl<const N: u64> BytesMaxLength<N> {
pub fn into_inner(self) -> Bytes {
2021-05-30 13:24:03 +02:00
self.0
}
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<const N: u64> FromRequest<Body> for BytesMaxLength<N> {
type Rejection = BoxIntoResponse<Body>;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 14:33:20 +02:00
let content_length = req.headers().get(http::header::CONTENT_LENGTH).cloned();
2021-05-31 22:54:21 +02:00
let body = take_body(req).map_err(|reject| reject.boxed())?;
2021-05-30 13:24:03 +02:00
2021-05-31 12:55:39 +02:00
let content_length =
content_length.and_then(|value| value.to_str().ok()?.parse::<u64>().ok());
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
if let Some(length) = content_length {
if length > N {
2021-05-31 22:54:21 +02:00
return Err(PayloadTooLarge(()).boxed());
2021-05-31 12:55:39 +02:00
}
} else {
2021-05-31 22:54:21 +02:00
return Err(LengthRequired(()).boxed());
2021-05-31 12:55:39 +02:00
};
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
let bytes = hyper::body::to_bytes(body)
.await
2021-05-31 22:54:21 +02:00
.map_err(|e| FailedToBufferBody::from_err(e).boxed())?;
2021-05-30 14:33:20 +02:00
2021-05-31 12:55:39 +02:00
Ok(BytesMaxLength(bytes))
2021-05-30 13:24:03 +02:00
}
}
2021-05-30 15:44:26 +02:00
2021-05-31 22:54:21 +02:00
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "No url params found for matched route. This is a bug in tower-web. Please open an issue"]
pub struct MissingRouteParams(());
}
2021-05-30 16:37:27 +02:00
pub struct UrlParamsMap(HashMap<String, String>);
2021-05-30 15:44:26 +02:00
2021-05-30 16:37:27 +02:00
impl UrlParamsMap {
2021-06-01 00:34:09 +02:00
pub fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).map(|s| &**s)
2021-05-30 15:44:26 +02:00
}
2021-05-30 16:37:27 +02:00
2021-06-01 00:34:09 +02:00
pub fn get_typed<T>(&self, key: &str) -> Option<T>
2021-05-30 16:37:27 +02:00
where
2021-05-30 16:53:27 +02:00
T: FromStr,
2021-05-30 16:37:27 +02:00
{
2021-06-01 00:34:09 +02:00
self.get(key)?.parse().ok()
2021-05-30 16:37:27 +02:00
}
2021-05-30 15:44:26 +02:00
}
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl FromRequest<Body> for UrlParamsMap {
type Rejection = MissingRouteParams;
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 15:44:26 +02:00
if let Some(params) = req
.extensions_mut()
.get_mut::<Option<crate::routing::UrlParams>>()
{
let params = params.take().expect("params already taken").0;
2021-05-31 12:55:39 +02:00
Ok(Self(params.into_iter().collect()))
2021-05-30 15:44:26 +02:00
} else {
2021-05-31 22:54:21 +02:00
Err(MissingRouteParams(()))
2021-05-30 15:44:26 +02:00
}
}
}
2021-05-30 16:53:27 +02:00
2021-05-31 22:54:21 +02:00
#[derive(Debug)]
pub struct InvalidUrlParam {
type_name: &'static str,
}
2021-05-30 16:53:27 +02:00
2021-05-31 22:54:21 +02:00
impl InvalidUrlParam {
fn new<T>() -> Self {
InvalidUrlParam {
type_name: std::any::type_name::<T>(),
}
}
}
impl IntoResponse<Body> for InvalidUrlParam {
fn into_response(self) -> http::Response<Body> {
let mut res = http::Response::new(Body::from(format!(
"Invalid URL param. Expected something of type `{}`",
self.type_name
)));
*res.status_mut() = http::StatusCode::BAD_REQUEST;
res
2021-05-30 16:53:27 +02:00
}
}
2021-05-31 22:54:21 +02:00
pub struct UrlParams<T>(T);
2021-05-30 16:53:27 +02:00
macro_rules! impl_parse_url {
() => {};
( $head:ident, $($tail:ident),* $(,)? ) => {
2021-05-31 12:55:39 +02:00
#[async_trait]
2021-05-31 22:54:21 +02:00
impl<$head, $($tail,)*> FromRequest<Body> for UrlParams<($head, $($tail,)*)>
2021-05-30 16:53:27 +02:00
where
$head: FromStr + Send,
$( $tail: FromStr + Send, )*
{
2021-05-31 22:54:21 +02:00
type Rejection = BoxIntoResponse<Body>;
2021-05-30 16:53:27 +02:00
#[allow(non_snake_case)]
2021-05-31 22:54:21 +02:00
async fn from_request(req: &mut Request<Body>) -> Result<Self, Self::Rejection> {
2021-05-30 16:53:27 +02:00
let params = if let Some(params) = req
.extensions_mut()
.get_mut::<Option<crate::routing::UrlParams>>()
{
params.take().expect("params already taken").0
} else {
2021-05-31 22:54:21 +02:00
return Err(MissingRouteParams(()).boxed())
2021-05-30 16:53:27 +02:00
};
if let [(_, $head), $((_, $tail),)*] = &*params {
let $head = if let Ok(x) = $head.parse::<$head>() {
x
} else {
2021-05-31 22:54:21 +02:00
return Err(InvalidUrlParam::new::<$head>().boxed());
2021-05-30 16:53:27 +02:00
};
$(
let $tail = if let Ok(x) = $tail.parse::<$tail>() {
x
} else {
2021-05-31 22:54:21 +02:00
return Err(InvalidUrlParam::new::<$tail>().boxed());
2021-05-30 16:53:27 +02:00
};
)*
2021-05-31 12:55:39 +02:00
Ok(UrlParams(($head, $($tail,)*)))
2021-05-30 16:53:27 +02:00
} else {
2021-05-31 22:54:21 +02:00
return Err(MissingRouteParams(()).boxed())
2021-05-30 16:53:27 +02:00
}
}
}
impl_parse_url!($($tail,)*);
};
}
2021-05-31 22:54:21 +02:00
impl_parse_url!(T1, T2, T3, T4, T5, T6);
impl<T1> UrlParams<(T1,)> {
pub fn into_inner(self) -> T1 {
(self.0).0
}
}
impl<T1, T2> UrlParams<(T1, T2)> {
pub fn into_inner(self) -> (T1, T2) {
((self.0).0, (self.0).1)
}
}
impl<T1, T2, T3> UrlParams<(T1, T2, T3)> {
pub fn into_inner(self) -> (T1, T2, T3) {
((self.0).0, (self.0).1, (self.0).2)
}
}
impl<T1, T2, T3, T4> UrlParams<(T1, T2, T3, T4)> {
pub fn into_inner(self) -> (T1, T2, T3, T4) {
((self.0).0, (self.0).1, (self.0).2, (self.0).3)
}
}
impl<T1, T2, T3, T4, T5> UrlParams<(T1, T2, T3, T4, T5)> {
pub fn into_inner(self) -> (T1, T2, T3, T4, T5) {
((self.0).0, (self.0).1, (self.0).2, (self.0).3, (self.0).4)
}
}
impl<T1, T2, T3, T4, T5, T6> UrlParams<(T1, T2, T3, T4, T5, T6)> {
pub fn into_inner(self) -> (T1, T2, T3, T4, T5, T6) {
(
(self.0).0,
(self.0).1,
(self.0).2,
(self.0).3,
(self.0).4,
(self.0).5,
)
}
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Cannot have two request body extractors for a single handler"]
pub struct BodyAlreadyTaken(());
}
fn take_body(req: &mut Request<Body>) -> Result<Body, BodyAlreadyTaken> {
struct BodyAlreadyTakenExt;
if req.extensions_mut().insert(BodyAlreadyTakenExt).is_some() {
Err(BodyAlreadyTaken(()))
} else {
let body = std::mem::take(req.body_mut());
Ok(body)
}
}