Skip to main content

vld_web/
warp.rs

1//! # `vld_web::warp` — Warp integration for `vld`
2//!
3//! Validation [filters](warp::Filter) for [Warp](https://docs.rs/warp) 0.3
4//! and 0.4 (the dependency is `>=0.3, <0.5`; there are no version features).
5//!
6//! | Filter / Function | Source |
7//! |-------------------|--------|
8//! | [`vld_json::<T>()`] | JSON body |
9//! | [`vld_query::<T>()`] | Query string |
10//! | [`vld_form::<T>()`] | URL-encoded form body |
11//! | [`vld_param::<T>(name)`](vld_param) | Single path segment |
12//! | [`vld_path::<T>(names)`](vld_path) | All remaining path segments (tail) |
13//! | [`validate_path_params::<T>(pairs)`](validate_path_params) | Pre-extracted path params |
14//! | [`vld_headers::<T>()`] | HTTP headers |
15//! | [`vld_cookie::<T>()`] | Cookie values |
16//!
17//! Every filter rejects with [`VldRejection`] (wrapping [`VldHttpError`]).
18//! Add [`handle_rejection`] with `.recover()` to turn rejections into JSON
19//! (see the [error body format](crate::common#error-bodies)):
20//! validation / malformed body → 422, body over the limit → 413, `vld_json`
21//! without a JSON `Content-Type` (`application/json` or `application/*+json`)
22//! or `vld_form` without `application/x-www-form-urlencoded` → 415, plus
23//! the usual warp rejections (404, 405, 400, 411, 415) and 500 for anything
24//! unknown.
25//!
26//! # Example
27//!
28//! ```no_run
29//! use vld_web::warp::prelude::*;
30//! use warp::Filter;
31//!
32//! vld::schema! {
33//!     #[derive(Debug, Clone)]
34//!     pub struct CreateUser {
35//!         pub name: String  => vld::string().min(2),
36//!         pub email: String => vld::string().email(),
37//!     }
38//! }
39//!
40//! # #[tokio::main]
41//! # async fn main() {
42//! let create = warp::post()
43//!     .and(warp::path("users"))
44//!     .and(vld_json::<CreateUser>())
45//!     .map(|u: CreateUser| warp::reply::json(&serde_json::json!({ "name": u.name })));
46//!
47//! warp::serve(create.recover(handle_rejection))
48//!     .run(([127, 0, 0, 1], 3030))
49//!     .await;
50//! # }
51//! ```
52//!
53//! # Body limit
54//!
55//! `vld_json` / `vld_form` stream the body and stop at
56//! [`DEFAULT_BODY_LIMIT`](crate::common::DEFAULT_BODY_LIMIT) (2 MiB), also
57//! without a `Content-Length` (chunked uploads);
58//! [`vld_json_limit`] / [`vld_form_limit`] take an explicit limit.
59//!
60//! Guide: <https://s00d.github.io/vld/integrations/web/warp>
61use crate::common::{
62    VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced, parse_form_body,
63    parse_json_body, path_params_to_json, percent_decode, query_string_to_json,
64    require_form_content_type, require_json_content_type,
65};
66use bytes::{Buf, BufMut, Bytes, BytesMut};
67use futures_util::{Stream, StreamExt};
68use std::convert::Infallible;
69use vld::schema::VldParse;
70use warp::http::{HeaderValue, StatusCode, header};
71use warp::reject::Reject;
72use warp::{Filter, Rejection, Reply};
73
74// ---------------------------------------------------------------------------
75// Rejection type
76// ---------------------------------------------------------------------------
77
78/// The rejection of every `vld_*` filter: validation / parse failure (422),
79/// body too large (413) or wrong `Content-Type` (415). [`handle_rejection`]
80/// answers it with [`status`](Self::status) and [`body`](Self::body).
81#[derive(Debug)]
82pub struct VldRejection(VldHttpError);
83
84impl VldRejection {
85    /// The underlying validation error.
86    pub fn error(&self) -> &vld::error::VldError {
87        self.0.error()
88    }
89
90    /// HTTP status (422, 413 or 415).
91    pub fn status(&self) -> StatusCode {
92        StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
93    }
94
95    /// JSON response body.
96    pub fn body(&self) -> serde_json::Value {
97        self.0.body()
98    }
99}
100
101impl From<VldHttpError> for VldRejection {
102    fn from(e: VldHttpError) -> Self {
103        Self(e)
104    }
105}
106
107impl Reject for VldRejection {}
108
109fn reject(e: impl Into<VldHttpError>) -> Rejection {
110    warp::reject::custom(VldRejection(e.into()))
111}
112
113/// Validate a value coerced from text (query, path, form, headers, cookies).
114fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, Rejection> {
115    parse_coerced(value).map_err(reject)
116}
117
118/// The raw value of header `name`, if any. Unlike
119/// `warp::header::optional::<String>`, a non-ASCII value is not a 400.
120fn raw_header(
121    name: &'static str,
122) -> impl Filter<Extract = (Option<HeaderValue>,), Error = Infallible> + Clone {
123    warp::header::value(name)
124        .map(Some)
125        .or(warp::any().map(|| None))
126        .unify()
127}
128
129fn header_str(value: &Option<HeaderValue>) -> Option<&str> {
130    value.as_ref().and_then(|v| v.to_str().ok())
131}
132
133/// Read the whole body, streaming, up to `limit` bytes. Works without a
134/// `Content-Length` header (chunked uploads).
135fn limited_body(limit: u64) -> impl Filter<Extract = (Bytes,), Error = Rejection> + Clone {
136    warp::body::stream().and_then(move |stream| collect_limited(stream, limit))
137}
138
139async fn collect_limited<S, B>(stream: S, limit: u64) -> Result<Bytes, Rejection>
140where
141    S: Stream<Item = Result<B, warp::Error>>,
142    B: Buf,
143{
144    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
145    let mut stream = std::pin::pin!(stream);
146    let mut buf = BytesMut::new();
147    while let Some(chunk) = stream.next().await {
148        let chunk = chunk.map_err(|e| {
149            reject(VldHttpError::parse(format!(
150                "Failed to read request body: {e}"
151            )))
152        })?;
153        if buf.len().saturating_add(chunk.remaining()) > limit {
154            return Err(reject(VldHttpError::payload_too_large()));
155        }
156        buf.put(chunk);
157    }
158    Ok(buf.freeze())
159}
160
161// ---------------------------------------------------------------------------
162// vld_json filter
163// ---------------------------------------------------------------------------
164
165/// Warp filter that extracts and validates a JSON body.
166///
167/// Returns the validated `T` or rejects with [`VldRejection`] (422; 413 for
168/// a body over [`DEFAULT_BODY_LIMIT`](crate::common::DEFAULT_BODY_LIMIT);
169/// 415 without a JSON `Content-Type`).
170///
171/// # Example
172///
173/// ```rust,ignore
174/// use vld_web::warp::vld_json;
175///
176/// vld::schema! {
177///     #[derive(Debug, Clone)]
178///     pub struct CreateUser {
179///         pub name: String  => vld::string().min(2),
180///         pub email: String => vld::string().email(),
181///     }
182/// }
183///
184/// let route = warp::post()
185///     .and(warp::path("users"))
186///     .and(vld_json::<CreateUser>())
187///     .map(|user: CreateUser| {
188///         warp::reply::json(&serde_json::json!({"name": user.name}))
189///     });
190/// ```
191pub fn vld_json<T: VldParse + Send + 'static>()
192-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
193    vld_json_limit(crate::common::DEFAULT_BODY_LIMIT as u64)
194}
195
196/// Like [`vld_json`], but with an explicit body size limit (bytes).
197pub fn vld_json_limit<T: VldParse + Send + 'static>(
198    limit: u64,
199) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
200    raw_header("content-type")
201        .and_then(|ct: Option<HeaderValue>| async move {
202            require_json_content_type(header_str(&ct)).map_err(reject)
203        })
204        .untuple_one()
205        .and(limited_body(limit))
206        .and_then(|bytes: Bytes| async move {
207            let value = parse_json_body(&bytes).map_err(reject)?;
208            T::vld_parse_value(&value).map_err(reject)
209        })
210}
211
212// ---------------------------------------------------------------------------
213// vld_query filter
214// ---------------------------------------------------------------------------
215
216/// Warp filter that extracts and validates query parameters.
217///
218/// See [`crate::common::parse_query_string`] for coercion and array rules.
219///
220/// # Example
221///
222/// ```rust,ignore
223/// use vld_web::warp::vld_query;
224///
225/// vld::schema! {
226///     #[derive(Debug, Clone)]
227///     pub struct Pagination {
228///         pub page: i64  => vld::number().int().min(1),
229///         pub limit: i64 => vld::number().int().min(1).max(100),
230///     }
231/// }
232///
233/// let route = warp::get()
234///     .and(warp::path("items"))
235///     .and(vld_query::<Pagination>())
236///     .map(|p: Pagination| {
237///         warp::reply::json(&serde_json::json!({"page": p.page, "limit": p.limit}))
238///     });
239/// ```
240pub fn vld_query<T: VldParse + Send + 'static>()
241-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
242    warp::query::raw()
243        .or(warp::any().map(String::new))
244        .unify()
245        .and_then(|qs: String| async move { validate(&query_string_to_json(&qs)) })
246}
247
248// ---------------------------------------------------------------------------
249// Recovery handler
250// ---------------------------------------------------------------------------
251
252/// Recovery handler that converts rejections into JSON responses.
253///
254/// | Rejection | Status |
255/// |---|---|
256/// | [`VldRejection`] | its [`status`](VldRejection::status) (422 / 413 / 415) and [`body`](VldRejection::body) |
257/// | `PayloadTooLarge` | 413 |
258/// | `MethodNotAllowed` | 405 |
259/// | `UnsupportedMediaType` | 415 |
260/// | `LengthRequired` | 411 |
261/// | `MissingHeader`, `InvalidHeader`, `MissingCookie`, `InvalidQuery` | 400 |
262/// | not found | 404 |
263/// | anything else | 500 |
264///
265/// Use with `warp::Filter::recover()`:
266///
267/// ```rust,ignore
268/// use vld_web::warp::handle_rejection;
269///
270/// let routes = warp::any()
271///     // ...your routes...
272///     .recover(handle_rejection);
273/// ```
274pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
275    use warp::reject as r;
276
277    let (status, body) = if let Some(e) = err.find::<VldRejection>() {
278        (e.status(), e.body())
279    } else if err.find::<r::PayloadTooLarge>().is_some() {
280        (
281            StatusCode::PAYLOAD_TOO_LARGE,
282            crate::common::format_payload_too_large(),
283        )
284    } else if err.is_not_found() {
285        (
286            StatusCode::NOT_FOUND,
287            crate::common::format_generic_error("Not Found"),
288        )
289    } else {
290        let known = |status: StatusCode, msg: String| (status, msg);
291        // Same priority as warp: any specific error beats 405, 405 beats 404.
292        let (status, msg) = if let Some(e) = err.find::<r::UnsupportedMediaType>() {
293            known(StatusCode::UNSUPPORTED_MEDIA_TYPE, e.to_string())
294        } else if let Some(e) = err.find::<r::LengthRequired>() {
295            known(StatusCode::LENGTH_REQUIRED, e.to_string())
296        } else if let Some(e) = err.find::<r::MissingHeader>() {
297            known(StatusCode::BAD_REQUEST, e.to_string())
298        } else if let Some(e) = err.find::<r::InvalidHeader>() {
299            known(StatusCode::BAD_REQUEST, e.to_string())
300        } else if let Some(e) = err.find::<r::MissingCookie>() {
301            known(StatusCode::BAD_REQUEST, e.to_string())
302        } else if let Some(e) = err.find::<r::InvalidQuery>() {
303            known(StatusCode::BAD_REQUEST, e.to_string())
304        } else if let Some(e) = err.find::<r::MethodNotAllowed>() {
305            known(StatusCode::METHOD_NOT_ALLOWED, e.to_string())
306        } else {
307            known(
308                StatusCode::INTERNAL_SERVER_ERROR,
309                "Internal Server Error".to_string(),
310            )
311        };
312        (status, crate::common::format_generic_error(&msg))
313    };
314
315    Ok(warp::reply::with_status(warp::reply::json(&body), status))
316}
317
318// ---------------------------------------------------------------------------
319// vld_form filter
320// ---------------------------------------------------------------------------
321
322/// Warp filter that extracts and validates a URL-encoded form body
323/// (`application/x-www-form-urlencoded`, 415 otherwise).
324///
325/// Values are parsed the same way as query parameters.
326pub fn vld_form<T: VldParse + Send + 'static>()
327-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
328    vld_form_limit(crate::common::DEFAULT_BODY_LIMIT as u64)
329}
330
331/// Like [`vld_form`], but with an explicit body size limit (bytes).
332pub fn vld_form_limit<T: VldParse + Send + 'static>(
333    limit: u64,
334) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
335    raw_header("content-type")
336        .and_then(|ct: Option<HeaderValue>| async move {
337            require_form_content_type(header_str(&ct)).map_err(reject)
338        })
339        .untuple_one()
340        .and(limited_body(limit))
341        .and_then(|bytes: Bytes| async move { validate(&parse_form_body(&bytes).map_err(reject)?) })
342}
343
344// ---------------------------------------------------------------------------
345// vld_param — single path parameter filter
346// ---------------------------------------------------------------------------
347
348/// Warp filter that extracts and validates **a single path segment**.
349///
350/// Works like `warp::path::param::<String>()` but percent-decodes and
351/// coerces the raw value and validates via `T::vld_parse_value()`.
352///
353/// The extracted segment is wrapped into a JSON object `{ "<name>": <coerced> }`
354/// so that the vld schema field name matches.
355///
356/// # Example
357///
358/// ```rust,ignore
359/// use vld_web::warp::vld_param;
360///
361/// vld::schema! {
362///     #[derive(Debug, Clone)]
363///     pub struct UserId {
364///         pub id: i64 => vld::number().int().min(1),
365///     }
366/// }
367///
368/// // GET /users/<id>
369/// let route = warp::path("users")
370///     .and(vld_param::<UserId>("id"))
371///     .and(warp::path::end())
372///     .map(|p: UserId| {
373///         warp::reply::json(&serde_json::json!({"id": p.id}))
374///     });
375/// ```
376pub fn vld_param<T: VldParse + Send + 'static>(
377    name: &'static str,
378) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
379    warp::path::param::<String>().and_then(move |raw: String| async move {
380        validate(&path_params_to_json([(
381            name,
382            percent_decode(&raw).as_str(),
383        )]))
384    })
385}
386
387// ---------------------------------------------------------------------------
388// vld_path — multi-param tail filter
389// ---------------------------------------------------------------------------
390
391/// Warp filter that extracts and validates **all remaining path segments**.
392///
393/// Uses `warp::path::tail()` internally — all segments after the current
394/// position are consumed, percent-decoded and mapped to `param_names` in
395/// order. The number of remaining segments **must equal** the number of
396/// names; otherwise the request is rejected with 404 (not found).
397///
398/// Best suited for routes where all remaining segments are parameters
399/// (no static segments left).
400///
401/// # Example
402///
403/// ```rust,ignore
404/// use vld_web::warp::vld_path;
405///
406/// vld::schema! {
407///     #[derive(Debug, Clone)]
408///     pub struct PostPath {
409///         pub user_id: i64 => vld::number().int().min(1),
410///         pub post_id: i64 => vld::number().int().min(1),
411///     }
412/// }
413///
414/// // GET /posts/<user_id>/<post_id>
415/// let route = warp::path("posts")
416///     .and(vld_path::<PostPath>(&["user_id", "post_id"]))
417///     .map(|p: PostPath| {
418///         warp::reply::json(&serde_json::json!({
419///             "user_id": p.user_id,
420///             "post_id": p.post_id
421///         }))
422///     });
423/// ```
424pub fn vld_path<T: VldParse + Send + 'static>(
425    param_names: &'static [&'static str],
426) -> impl Filter<Extract = (T,), Error = Rejection> + Clone {
427    warp::path::tail().and_then(move |tail: warp::path::Tail| async move {
428        let segments: Vec<String> = tail
429            .as_str()
430            .split('/')
431            .filter(|s| !s.is_empty())
432            .map(percent_decode)
433            .collect();
434
435        if segments.len() != param_names.len() {
436            return Err(warp::reject::not_found());
437        }
438
439        validate(&path_params_to_json(
440            param_names
441                .iter()
442                .copied()
443                .zip(segments.iter().map(String::as_str)),
444        ))
445    })
446}
447
448// ---------------------------------------------------------------------------
449// validate_path_params — standalone validator for pre-extracted params
450// ---------------------------------------------------------------------------
451
452/// Validate pre-extracted path parameter pairs against a vld schema.
453///
454/// Values are percent-decoded (warp's `path::param::<String>()` yields the
455/// raw, still-encoded segment) and coerced.
456///
457/// Useful for complex routes where static and dynamic segments are
458/// interleaved and you extract `String` params with
459/// `warp::path::param::<String>()`, then validate them all at once.
460///
461/// # Example
462///
463/// ```rust,ignore
464/// use vld_web::warp::validate_path_params;
465///
466/// vld::schema! {
467///     #[derive(Debug, Clone)]
468///     pub struct CommentPath {
469///         pub user_id: i64 => vld::number().int().min(1),
470///         pub post_id: i64 => vld::number().int().min(1),
471///         pub comment_id: i64 => vld::number().int().min(1),
472///     }
473/// }
474///
475/// // GET /users/<id>/posts/<pid>/comments/<cid>
476/// let route = warp::path("users")
477///     .and(warp::path::param::<String>())
478///     .and(warp::path("posts"))
479///     .and(warp::path::param::<String>())
480///     .and(warp::path("comments"))
481///     .and(warp::path::param::<String>())
482///     .and(warp::path::end())
483///     .and_then(|uid: String, pid: String, cid: String| async move {
484///         validate_path_params::<CommentPath>(&[
485///             ("user_id", &uid),
486///             ("post_id", &pid),
487///             ("comment_id", &cid),
488///         ])
489///     });
490/// ```
491pub fn validate_path_params<T: VldParse>(params: &[(&str, &str)]) -> Result<T, Rejection> {
492    let decoded: Vec<(&str, String)> = params
493        .iter()
494        .map(|(k, v)| (*k, percent_decode(v)))
495        .collect();
496    validate(&path_params_to_json(
497        decoded.iter().map(|(k, v)| (*k, v.as_str())),
498    ))
499}
500
501// ---------------------------------------------------------------------------
502// vld_headers filter
503// ---------------------------------------------------------------------------
504
505/// Warp filter that extracts and validates HTTP headers.
506///
507/// See [`crate::common::headers_to_json`]: names become snake_case
508/// (`Content-Type` → `content_type`), names containing `_` are ignored,
509/// repeated headers are joined with `", "`.
510pub fn vld_headers<T: VldParse + Send + 'static>()
511-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
512    warp::header::headers_cloned().and_then(|headers: warp::http::HeaderMap| async move {
513        validate(&headers_to_json(
514            headers.iter().map(|(n, v)| (n.as_str(), v.as_bytes())),
515        ))
516    })
517}
518
519// ---------------------------------------------------------------------------
520// vld_cookie filter
521// ---------------------------------------------------------------------------
522
523/// Warp filter that extracts and validates cookies from the `Cookie`
524/// headers (all of them; the first occurrence of a name wins; a non-ASCII
525/// value is not a 400).
526///
527/// Cookie names are used as-is for schema field matching.
528/// Values are unquoted, percent-decoded and coerced.
529pub fn vld_cookie<T: VldParse + Send + 'static>()
530-> impl Filter<Extract = (T,), Error = Rejection> + Clone {
531    warp::header::headers_cloned().and_then(|headers: warp::http::HeaderMap| async move {
532        validate(&cookie_headers_to_json(
533            headers.get_all(header::COOKIE).iter().map(|v| v.as_bytes()),
534        ))
535    })
536}
537
538/// Prelude — import everything you need.
539pub mod prelude {
540    pub use super::{
541        VldRejection, handle_rejection, validate_path_params, vld_cookie, vld_form, vld_form_limit,
542        vld_headers, vld_json, vld_json_limit, vld_param, vld_path, vld_query,
543    };
544    pub use vld::prelude::*;
545}