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