Skip to main content

vld_rocket/
lib.rs

1//! **Deprecated:** moved to [`vld-web`](https://docs.rs/vld-web) 0.8 (`vld_web::rocket`); see the
2//! [migration guide](https://s00d.github.io/vld/guides/migration#from-07-to-08).
3//!
4//! # vld-rocket — Rocket integration for `vld`
5//!
6//! Validation extractors for [Rocket](https://rocket.rs/). Validates request
7//! data against `vld` schemas and returns `422 Unprocessable Entity` with
8//! structured JSON errors on failure (malformed JSON/form bodies included),
9//! and `413 Payload Too Large` when a body exceeds the limit.
10//! `VldJson` requires a JSON `Content-Type` (`application/json` or
11//! `application/*+json`) and `VldForm` `application/x-www-form-urlencoded`;
12//! anything else is `415 Unsupported Media Type`. See the
13//! [error body format](vld_http_common#error-bodies).
14//!
15//! Guide: <https://s00d.github.io/vld/integrations/web/rocket> (shared rules
16//! for all adapters: <https://s00d.github.io/vld/integrations/web/overview>).
17//!
18//! # Example
19//!
20//! ```no_run
21//! use vld_rocket::prelude::*;
22//!
23//! vld::schema! {
24//!     #[derive(Debug, Clone)]
25//!     pub struct CreateUser {
26//!         pub name: String  => vld::string().min(2).max(50),
27//!         pub email: String => vld::string().email(),
28//!     }
29//! }
30//!
31//! vld::schema! {
32//!     #[derive(Debug, Clone)]
33//!     pub struct UserPath {
34//!         pub id: i64 => vld::number().int().min(1),
35//!     }
36//! }
37//!
38//! #[rocket::post("/users", data = "<user>")]
39//! fn create_user(user: VldJson<CreateUser>) -> String {
40//!     format!("created {}", user.name)
41//! }
42//!
43//! // Rocket needs every `<param>` as an argument too; `VldPath` validates them.
44//! #[rocket::get("/users/<id>")]
45//! fn get_user(id: &str, p: VldPath<UserPath>) -> String {
46//!     let _ = id;
47//!     format!("user #{}", p.id)
48//! }
49//!
50//! fn app() -> rocket::Rocket<rocket::Build> {
51//!     rocket::build()
52//!         .mount("/api", rocket::routes![create_user, get_user])
53//!         .register("/", vld_catchers())
54//! }
55//! # fn main() { let _ = app(); }
56//! ```
57//!
58//! # Extractors
59//!
60//! | Extractor | Source | Rocket equivalent |
61//! |-----------|--------|-------------------|
62//! | `VldJson<T>` | JSON body | `rocket::serde::json::Json<T>` |
63//! | `VldQuery<T>` | Query string | query params |
64//! | `VldPath<T>` | Path segments | `<param>` / `<param..>` segments |
65//! | `VldForm<T>` | Form body | `rocket::form::Form<T>` |
66//! | `VldHeaders<T>` | HTTP headers | manual extraction |
67//! | `VldCookie<T>` | Cookie values | `CookieJar` |
68//!
69//! # Body limits
70//!
71//! `VldJson` reads up to Rocket's `json` limit and `VldForm` up to the
72//! `form` limit, configured via `limits` in `Rocket.toml` (or
73//! `ROCKET_LIMITS`). While a limit is left at Rocket's built-in default
74//! (1 MiB / 32 KiB) [`DEFAULT_BODY_LIMIT`] (2 MiB) applies instead, like in
75//! every other `vld` adapter — so setting exactly the built-in value counts
76//! as unset.
77//!
78//! # Error catchers
79//!
80//! Register [`vld_catchers()`] (as in the example above) to get JSON error
81//! responses instead of Rocket's default HTML pages. A failed guard only sets
82//! the status; the catcher answers with the error body the guard stored.
83#![warn(missing_docs)]
84
85use rocket::data::{ByteUnit, Data, FromData, Limits, Outcome as DataOutcome, ToByteUnit};
86use rocket::http::Status;
87use rocket::request::{FromRequest, Outcome, Request};
88use rocket::serde::json::Json;
89use std::sync::Mutex;
90use vld::schema::VldParse;
91use vld_http_common::{
92    DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced,
93    parse_form_body, parse_json_body, path_params_to_json, query_string_to_json,
94    require_form_content_type, require_json_content_type,
95};
96
97// ---------------------------------------------------------------------------
98// Request-local error storage
99// ---------------------------------------------------------------------------
100
101/// The latest vld failure `(status, body)` of a request, for the catchers.
102#[derive(Default)]
103struct VldErrorCache(Mutex<Option<(Status, serde_json::Value)>>);
104
105/// Store the error body for the catchers and return `(status, body)`.
106fn fail(req: &Request<'_>, err: VldHttpError) -> (Status, serde_json::Value) {
107    let status = Status::new(err.status());
108    let body = err.body();
109    // A later failure overwrites: the catcher answers for the last one.
110    *req.local_cache(VldErrorCache::default)
111        .0
112        .lock()
113        .unwrap_or_else(|e| e.into_inner()) = Some((status, body.clone()));
114    (status, body)
115}
116
117/// Rocket's limit `name`, or [`DEFAULT_BODY_LIMIT`] while it is unset or
118/// left at Rocket's built-in default.
119fn body_limit(req: &Request<'_>, name: &str) -> ByteUnit {
120    match req.limits().get(name) {
121        Some(limit) if Some(limit) != Limits::default().get(name) => limit,
122        _ => DEFAULT_BODY_LIMIT.bytes(),
123    }
124}
125
126/// Read the body up to `limit`: 413 beyond it, 422 on a read error.
127async fn read_body(
128    req: &Request<'_>,
129    data: Data<'_>,
130    limit: ByteUnit,
131) -> Result<Vec<u8>, (Status, serde_json::Value)> {
132    match data.open(limit).into_bytes().await {
133        Ok(b) if b.is_complete() => Ok(b.into_inner()),
134        Ok(_) => Err(fail(req, VldHttpError::payload_too_large())),
135        Err(e) => Err(fail(
136            req,
137            VldHttpError::parse(format!("Failed to read request body: {e}")),
138        )),
139    }
140}
141
142fn validate<T: VldParse>(
143    req: &Request<'_>,
144    value: &serde_json::Value,
145) -> Result<T, (Status, serde_json::Value)> {
146    parse_coerced(value).map_err(|e| fail(req, VldHttpError::validation(e)))
147}
148
149fn to_outcome<S>(r: Result<S, (Status, serde_json::Value)>) -> Outcome<S, serde_json::Value> {
150    match r {
151        Ok(v) => Outcome::Success(v),
152        Err(e) => Outcome::Error(e),
153    }
154}
155
156fn to_data_outcome<'r, S>(
157    r: Result<S, (Status, serde_json::Value)>,
158) -> DataOutcome<'r, S, serde_json::Value> {
159    match r {
160        Ok(v) => DataOutcome::Success(v),
161        Err(e) => DataOutcome::Error(e),
162    }
163}
164
165// ---------------------------------------------------------------------------
166// VldJson<T> — validated JSON body
167// ---------------------------------------------------------------------------
168
169/// Validated JSON body extractor.
170///
171/// Reads the request body as JSON, validates via `T::vld_parse_value()`,
172/// and returns `422` with error details on failure (`413` when the body
173/// exceeds the `json` limit, `415` when the `Content-Type` is missing
174/// or not `application/json` / `application/*+json`).
175#[derive(Debug, Clone)]
176pub struct VldJson<T>(pub T);
177
178#[rocket::async_trait]
179impl<'r, T: VldParse + Send + 'static> FromData<'r> for VldJson<T> {
180    type Error = serde_json::Value;
181
182    async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> DataOutcome<'r, Self> {
183        if let Err(e) = require_json_content_type(req.headers().get_one("Content-Type")) {
184            return DataOutcome::Error(fail(req, e));
185        }
186        let result = match read_body(req, data, body_limit(req, "json")).await {
187            Ok(body) => parse_json_body(&body)
188                .and_then(|v| T::vld_parse_value(&v).map_err(VldHttpError::validation))
189                .map(VldJson)
190                .map_err(|e| fail(req, e)),
191            Err(e) => Err(e),
192        };
193        to_data_outcome(result)
194    }
195}
196
197// ---------------------------------------------------------------------------
198// VldQuery<T> — validated query string
199// ---------------------------------------------------------------------------
200
201/// Validated query string extractor.
202///
203/// See [`vld_http_common::parse_query_string`] for coercion and array rules.
204#[derive(Debug, Clone)]
205pub struct VldQuery<T>(pub T);
206
207#[rocket::async_trait]
208impl<'r, T: VldParse + Send + Sync + 'static> FromRequest<'r> for VldQuery<T> {
209    type Error = serde_json::Value;
210
211    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
212        let qs = req.uri().query().map(|q| q.as_str()).unwrap_or("");
213        to_outcome(validate(req, &query_string_to_json(qs)).map(VldQuery))
214    }
215}
216
217// ---------------------------------------------------------------------------
218// VldForm<T> — validated form body
219// ---------------------------------------------------------------------------
220
221/// Validated form body extractor.
222///
223/// Reads an `application/x-www-form-urlencoded` body (`415` for another
224/// `Content-Type`, `413` above the `form` limit), parses it like a query
225/// string and validates via `T::vld_parse_value()`.
226#[derive(Debug, Clone)]
227pub struct VldForm<T>(pub T);
228
229#[rocket::async_trait]
230impl<'r, T: VldParse + Send + 'static> FromData<'r> for VldForm<T> {
231    type Error = serde_json::Value;
232
233    async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> DataOutcome<'r, Self> {
234        if let Err(e) = require_form_content_type(req.headers().get_one("Content-Type")) {
235            return DataOutcome::Error(fail(req, e));
236        }
237        let result = match read_body(req, data, body_limit(req, "form")).await {
238            Ok(body) => parse_form_body(&body)
239                .map_err(|e| fail(req, e))
240                .and_then(|value| validate(req, &value)),
241            Err(e) => Err(e),
242        };
243        to_data_outcome(result.map(VldForm))
244    }
245}
246
247// ---------------------------------------------------------------------------
248// Error catchers
249// ---------------------------------------------------------------------------
250
251/// The stored vld error body when it is for `status`; otherwise (another
252/// guard failed, e.g. Rocket's own `Json`) a generic `{"error": reason}`.
253fn cached_or(req: &Request<'_>, status: Status) -> (Status, Json<serde_json::Value>) {
254    let cached = req
255        .local_cache(VldErrorCache::default)
256        .0
257        .lock()
258        .unwrap_or_else(|e| e.into_inner())
259        .clone();
260    let body = match cached {
261        Some((s, body)) if s == status => body,
262        _ => vld_http_common::format_generic_error(status.reason_lossy()),
263    };
264    (status, Json(body))
265}
266
267/// All vld catchers: `400`, `413`, `415` and `422`.
268///
269/// ```rust,ignore
270/// rocket::build().register("/", vld_rocket::vld_catchers())
271/// ```
272pub fn vld_catchers() -> Vec<rocket::Catcher> {
273    rocket::catchers![
274        vld_400_catcher,
275        vld_413_catcher,
276        vld_415_catcher,
277        vld_422_catcher
278    ]
279}
280
281/// Catcher for `422 Unprocessable Entity` that returns JSON from the
282/// validation error stored by vld extractors.
283///
284/// Register in your Rocket application:
285///
286/// ```rust,ignore
287/// rocket::build()
288///     .register("/", catchers![vld_rocket::vld_422_catcher])
289/// ```
290#[rocket::catch(422)]
291pub fn vld_422_catcher(req: &Request<'_>) -> (Status, Json<serde_json::Value>) {
292    cached_or(req, Status::UnprocessableEntity)
293}
294
295/// Catcher for `400 Bad Request` that returns JSON.
296#[rocket::catch(400)]
297pub fn vld_400_catcher(req: &Request<'_>) -> (Status, Json<serde_json::Value>) {
298    cached_or(req, Status::BadRequest)
299}
300
301/// Catcher for `413 Payload Too Large` that returns
302/// `{"error": "Payload too large"}`.
303#[rocket::catch(413)]
304pub fn vld_413_catcher(_req: &Request<'_>) -> (Status, Json<serde_json::Value>) {
305    (
306        Status::PayloadTooLarge,
307        Json(vld_http_common::format_payload_too_large()),
308    )
309}
310
311/// Catcher for `415 Unsupported Media Type` that returns JSON.
312#[rocket::catch(415)]
313pub fn vld_415_catcher(req: &Request<'_>) -> (Status, Json<serde_json::Value>) {
314    cached_or(req, Status::UnsupportedMediaType)
315}
316
317// ---------------------------------------------------------------------------
318// VldPath<T> — validated path parameters
319// ---------------------------------------------------------------------------
320
321/// Validated path parameter extractor for Rocket.
322///
323/// Extracts named dynamic segments of the matched route (`<id>`; a trailing
324/// `<path..>` receives the remaining segments joined with `/`) and validates
325/// via `T::vld_parse_value()`. Works with any mount point.
326///
327/// The struct field names must match the parameter names.
328#[derive(Debug, Clone)]
329pub struct VldPath<T>(pub T);
330
331/// Map the route's dynamic segments to the request's routed segments.
332fn path_params(req: &Request<'_>) -> Vec<(String, String)> {
333    let Some(route) = req.route() else {
334        return Vec::new();
335    };
336    // `unmounted_origin` and `routed_segments` both exclude the mount base.
337    let mut values = req.routed_segments(0..);
338    let mut params = Vec::new();
339    for pattern in route.uri.unmounted_origin.path().segments() {
340        let value = values.next();
341        let Some(name) = pattern.strip_prefix('<').and_then(|p| p.strip_suffix('>')) else {
342            continue;
343        };
344        if let Some(name) = name.strip_suffix("..") {
345            let rest: Vec<&str> = value.into_iter().chain(values.by_ref()).collect();
346            params.push((name.to_string(), rest.join("/")));
347            break;
348        }
349        if let Some(value) = value {
350            params.push((name.to_string(), value.to_string()));
351        }
352    }
353    params
354}
355
356#[rocket::async_trait]
357impl<'r, T: VldParse + Send + Sync + 'static> FromRequest<'r> for VldPath<T> {
358    type Error = serde_json::Value;
359
360    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
361        let params = path_params(req);
362        let value = path_params_to_json(params.iter().map(|(k, v)| (k.as_str(), v.as_str())));
363        to_outcome(validate(req, &value).map(VldPath))
364    }
365}
366
367// ---------------------------------------------------------------------------
368// VldHeaders<T> — validated HTTP headers
369// ---------------------------------------------------------------------------
370
371/// Validated HTTP headers extractor for Rocket.
372///
373/// See [`vld_http_common::headers_to_json`]: names become snake_case
374/// (`Content-Type` → `content_type`), names containing `_` are ignored,
375/// repeated headers are joined with `", "`.
376#[derive(Debug, Clone)]
377pub struct VldHeaders<T>(pub T);
378
379#[rocket::async_trait]
380impl<'r, T: VldParse + Send + Sync + 'static> FromRequest<'r> for VldHeaders<T> {
381    type Error = serde_json::Value;
382
383    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
384        // `iter()` yields `Header`s by value; keep them alive while borrowed.
385        let headers: Vec<_> = req.headers().iter().collect();
386        let value = headers_to_json(
387            headers
388                .iter()
389                .map(|h| (h.name().as_str(), h.value().as_bytes())),
390        );
391        to_outcome(validate(req, &value).map(VldHeaders))
392    }
393}
394
395// ---------------------------------------------------------------------------
396// VldCookie<T> — validated cookies
397// ---------------------------------------------------------------------------
398
399/// Validated cookie extractor for Rocket.
400///
401/// Reads cookies from every `Cookie` header (the first occurrence of a name
402/// wins) and validates against the schema. Cookie names are used as-is;
403/// values are unquoted, percent-decoded and coerced.
404#[derive(Debug, Clone)]
405pub struct VldCookie<T>(pub T);
406
407#[rocket::async_trait]
408impl<'r, T: VldParse + Send + Sync + 'static> FromRequest<'r> for VldCookie<T> {
409    type Error = serde_json::Value;
410
411    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
412        let value = cookie_headers_to_json(req.headers().get("Cookie").map(str::as_bytes));
413        to_outcome(validate(req, &value).map(VldCookie))
414    }
415}
416
417vld_http_common::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
418
419/// Prelude — import everything you need.
420pub mod prelude {
421    pub use crate::{
422        VldCookie, VldForm, VldHeaders, VldJson, VldPath, VldQuery, vld_400_catcher,
423        vld_413_catcher, vld_415_catcher, vld_422_catcher, vld_catchers,
424    };
425    pub use vld::prelude::*;
426}