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