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