use crate::common::{
VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced, parse_form_body,
parse_json_body, path_params_to_json, percent_decode, query_string_to_json,
require_form_content_type, require_json_content_type,
};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use futures_util::{Stream, StreamExt};
use std::convert::Infallible;
use vld::schema::VldParse;
use warp::http::{HeaderValue, StatusCode, header};
use warp::reject::Reject;
use warp::{Filter, Rejection, Reply};
#[derive(Debug)]
pub struct VldRejection(VldHttpError);
impl VldRejection {
pub fn error(&self) -> &vld::error::VldError {
self.0.error()
}
pub fn status(&self) -> StatusCode {
StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
}
pub fn body(&self) -> serde_json::Value {
self.0.body()
}
}
impl From<VldHttpError> for VldRejection {
fn from(e: VldHttpError) -> Self {
Self(e)
}
}
impl Reject for VldRejection {}
fn reject(e: impl Into<VldHttpError>) -> Rejection {
warp::reject::custom(VldRejection(e.into()))
}
fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, Rejection> {
parse_coerced(value).map_err(reject)
}
fn raw_header(
name: &'static str,
) -> impl Filter<Extract = (Option<HeaderValue>,), Error = Infallible> + Clone {
warp::header::value(name)
.map(Some)
.or(warp::any().map(|| None))
.unify()
}
fn header_str(value: &Option<HeaderValue>) -> Option<&str> {
value.as_ref().and_then(|v| v.to_str().ok())
}
fn limited_body(limit: u64) -> impl Filter<Extract = (Bytes,), Error = Rejection> + Clone {
warp::body::stream().and_then(move |stream| collect_limited(stream, limit))
}
async fn collect_limited<S, B>(stream: S, limit: u64) -> Result<Bytes, Rejection>
where
S: Stream<Item = Result<B, warp::Error>>,
B: Buf,
{
let limit = usize::try_from(limit).unwrap_or(usize::MAX);
let mut stream = std::pin::pin!(stream);
let mut buf = BytesMut::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| {
reject(VldHttpError::parse(format!(
"Failed to read request body: {e}"
)))
})?;
if buf.len().saturating_add(chunk.remaining()) > limit {
return Err(reject(VldHttpError::payload_too_large()));
}
buf.put(chunk);
}
Ok(buf.freeze())
}
pub fn vld_json<T: VldParse + Send + 'static>()
-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
vld_json_limit(crate::common::DEFAULT_BODY_LIMIT as u64)
}
pub fn vld_json_limit<T: VldParse + Send + 'static>(
limit: u64,
) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
raw_header("content-type")
.and_then(|ct: Option<HeaderValue>| async move {
require_json_content_type(header_str(&ct)).map_err(reject)
})
.untuple_one()
.and(limited_body(limit))
.and_then(|bytes: Bytes| async move {
let value = parse_json_body(&bytes).map_err(reject)?;
T::vld_parse_value(&value).map_err(reject)
})
}
pub fn vld_query<T: VldParse + Send + 'static>()
-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
warp::query::raw()
.or(warp::any().map(String::new))
.unify()
.and_then(|qs: String| async move { validate(&query_string_to_json(&qs)) })
}
pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
use warp::reject as r;
let (status, body) = if let Some(e) = err.find::<VldRejection>() {
(e.status(), e.body())
} else if err.find::<r::PayloadTooLarge>().is_some() {
(
StatusCode::PAYLOAD_TOO_LARGE,
crate::common::format_payload_too_large(),
)
} else if err.is_not_found() {
(
StatusCode::NOT_FOUND,
crate::common::format_generic_error("Not Found"),
)
} else {
let known = |status: StatusCode, msg: String| (status, msg);
let (status, msg) = if let Some(e) = err.find::<r::UnsupportedMediaType>() {
known(StatusCode::UNSUPPORTED_MEDIA_TYPE, e.to_string())
} else if let Some(e) = err.find::<r::LengthRequired>() {
known(StatusCode::LENGTH_REQUIRED, e.to_string())
} else if let Some(e) = err.find::<r::MissingHeader>() {
known(StatusCode::BAD_REQUEST, e.to_string())
} else if let Some(e) = err.find::<r::InvalidHeader>() {
known(StatusCode::BAD_REQUEST, e.to_string())
} else if let Some(e) = err.find::<r::MissingCookie>() {
known(StatusCode::BAD_REQUEST, e.to_string())
} else if let Some(e) = err.find::<r::InvalidQuery>() {
known(StatusCode::BAD_REQUEST, e.to_string())
} else if let Some(e) = err.find::<r::MethodNotAllowed>() {
known(StatusCode::METHOD_NOT_ALLOWED, e.to_string())
} else {
known(
StatusCode::INTERNAL_SERVER_ERROR,
"Internal Server Error".to_string(),
)
};
(status, crate::common::format_generic_error(&msg))
};
Ok(warp::reply::with_status(warp::reply::json(&body), status))
}
pub fn vld_form<T: VldParse + Send + 'static>()
-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
vld_form_limit(crate::common::DEFAULT_BODY_LIMIT as u64)
}
pub fn vld_form_limit<T: VldParse + Send + 'static>(
limit: u64,
) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
raw_header("content-type")
.and_then(|ct: Option<HeaderValue>| async move {
require_form_content_type(header_str(&ct)).map_err(reject)
})
.untuple_one()
.and(limited_body(limit))
.and_then(|bytes: Bytes| async move { validate(&parse_form_body(&bytes).map_err(reject)?) })
}
pub fn vld_param<T: VldParse + Send + 'static>(
name: &'static str,
) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
warp::path::param::<String>().and_then(move |raw: String| async move {
validate(&path_params_to_json([(
name,
percent_decode(&raw).as_str(),
)]))
})
}
pub fn vld_path<T: VldParse + Send + 'static>(
param_names: &'static [&'static str],
) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
warp::path::tail().and_then(move |tail: warp::path::Tail| async move {
let segments: Vec<String> = tail
.as_str()
.split('/')
.filter(|s| !s.is_empty())
.map(percent_decode)
.collect();
if segments.len() != param_names.len() {
return Err(warp::reject::not_found());
}
validate(&path_params_to_json(
param_names
.iter()
.copied()
.zip(segments.iter().map(String::as_str)),
))
})
}
pub fn validate_path_params<T: VldParse>(params: &[(&str, &str)]) -> Result<T, Rejection> {
let decoded: Vec<(&str, String)> = params
.iter()
.map(|(k, v)| (*k, percent_decode(v)))
.collect();
validate(&path_params_to_json(
decoded.iter().map(|(k, v)| (*k, v.as_str())),
))
}
pub fn vld_headers<T: VldParse + Send + 'static>()
-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
warp::header::headers_cloned().and_then(|headers: warp::http::HeaderMap| async move {
validate(&headers_to_json(
headers.iter().map(|(n, v)| (n.as_str(), v.as_bytes())),
))
})
}
pub fn vld_cookie<T: VldParse + Send + 'static>()
-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
warp::header::headers_cloned().and_then(|headers: warp::http::HeaderMap| async move {
validate(&cookie_headers_to_json(
headers.get_all(header::COOKIE).iter().map(|v| v.as_bytes()),
))
})
}
pub mod prelude {
pub use super::{
VldRejection, handle_rejection, validate_path_params, vld_cookie, vld_form, vld_form_limit,
vld_headers, vld_json, vld_json_limit, vld_param, vld_path, vld_query,
};
pub use vld::prelude::*;
}