Skip to main content

vld_web/
salvo.rs

1//! # `vld_web::salvo` — Salvo integration for `vld`
2//!
3//! Validation extractors for [Salvo](https://salvo.rs) 1.x. Every extractor
4//! implements [`Extractible`], so it is a plain `#[handler]` parameter, like
5//! Salvo's own `JsonBody` or `PathParam`.
6//!
7//! | Extractor | Source |
8//! |-----------|--------|
9//! | [`VldJson<T>`] | JSON request body |
10//! | [`VldQuery<T>`] | URL query parameters |
11//! | [`VldForm<T>`] | URL-encoded form body |
12//! | [`VldPath<T>`] | Path parameters |
13//! | [`VldHeaders<T>`] | HTTP headers |
14//! | [`VldCookie<T>`] | Cookie values |
15//!
16//! A failed extraction is written as JSON by [`VldSalvoError`] (see the
17//! [error body format](crate::common#error-bodies)): **422** for invalid or
18//! malformed input, **413** for a body over the limit, **415** when
19//! [`VldJson`] gets no JSON `Content-Type` (`application/json` or
20//! `application/*+json`) or [`VldForm`] no
21//! `application/x-www-form-urlencoded`.
22//!
23//! # Example
24//!
25//! ```no_run
26//! use salvo::prelude::*;
27//! use vld_web::salvo::prelude::*;
28//!
29//! vld::schema! {
30//!     #[derive(Debug, Clone)]
31//!     pub struct CreateUser {
32//!         pub name: String  => vld::string().min(2),
33//!         pub email: String => vld::string().email(),
34//!     }
35//! }
36//!
37//! #[handler]
38//! async fn create(body: VldJson<CreateUser>, res: &mut Response) {
39//!     res.render(Json(serde_json::json!({ "name": body.name })));
40//! }
41//!
42//! # #[tokio::main]
43//! # async fn main() {
44//! let router = Router::with_path("users").post(create);
45//! let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
46//! Server::new(acceptor).serve(router).await;
47//! # }
48//! ```
49//!
50//! # Body limits
51//!
52//! Bodies are read up to Salvo's [`Request::secure_max_size`], set with the
53//! `SecureMaxSize` middleware, `Request::set_secure_max_size` or
54//! `salvo::http::request::set_global_secure_max_size`. While it is Salvo's
55//! built-in 64 KiB default, [`DEFAULT_BODY_LIMIT`] (2 MiB) applies instead,
56//! like in every other `vld` adapter — so setting exactly 64 KiB counts as
57//! unset.
58//!
59//! Requires Rust **1.94+** (Salvo 1.x).
60//!
61//! Guide: <https://s00d.github.io/vld/integrations/web/salvo>
62use crate::common::{
63    DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced,
64    parse_form_body, parse_json_body, path_params_to_json, query_string_to_json,
65    require_form_content_type, require_json_content_type,
66};
67use salvo::extract::Extractible;
68use salvo::extract::metadata::{Metadata, Source, SourceFrom, SourceParser};
69use salvo::http::StatusCode;
70use salvo::prelude::*;
71use std::sync::OnceLock;
72use vld::schema::VldParse;
73
74// ---------------------------------------------------------------------------
75// Error type
76// ---------------------------------------------------------------------------
77
78/// Error type for vld validation failures in Salvo handlers.
79///
80/// Implements [`Writer`] so it can be returned from `#[handler]` functions
81/// via `Result<T, VldSalvoError>`.
82///
83/// On write, renders the [`VldHttpError`] it wraps as a JSON response
84/// (`422` for validation/parse, `415` for a wrong `Content-Type`, `413` for
85/// payload too large).
86#[derive(Debug)]
87pub struct VldSalvoError(VldHttpError);
88
89impl VldSalvoError {
90    /// Create a new `VldSalvoError` from a [`VldError`](vld::error::VldError).
91    pub fn new(error: vld::error::VldError) -> Self {
92        VldHttpError::validation(error).into()
93    }
94
95    /// The underlying validation error.
96    pub fn error(&self) -> &vld::error::VldError {
97        self.0.error()
98    }
99
100    /// HTTP status (422, 413 or 415).
101    pub fn status(&self) -> StatusCode {
102        StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
103    }
104
105    /// JSON response body.
106    pub fn body(&self) -> serde_json::Value {
107        self.0.body()
108    }
109}
110
111impl From<VldHttpError> for VldSalvoError {
112    fn from(e: VldHttpError) -> Self {
113        Self(e)
114    }
115}
116
117impl std::fmt::Display for VldSalvoError {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        self.0.fmt(f)
120    }
121}
122
123impl std::error::Error for VldSalvoError {}
124
125impl From<vld::error::VldError> for VldSalvoError {
126    fn from(error: vld::error::VldError) -> Self {
127        Self::new(error)
128    }
129}
130
131#[async_trait]
132impl Writer for VldSalvoError {
133    async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
134        res.status_code(self.status());
135        res.render(Json(self.body()));
136    }
137}
138
139/// Salvo's built-in `secure_max_size` (64 KiB).
140const SALVO_DEFAULT_MAX_SIZE: usize = 64 * 1024;
141
142/// Read the body up to `secure_max_size`, or [`DEFAULT_BODY_LIMIT`] while
143/// that is Salvo's built-in default.
144async fn read_body(req: &mut Request) -> Result<&[u8], VldSalvoError> {
145    let limit = match req.secure_max_size() {
146        SALVO_DEFAULT_MAX_SIZE => DEFAULT_BODY_LIMIT,
147        limit => limit,
148    };
149    req.payload_with_max_size(limit)
150        .await
151        .map(|b| &b[..])
152        .map_err(map_parse_error)
153}
154
155fn content_type(req: &Request) -> Option<&str> {
156    req.headers()
157        .get(salvo::http::header::CONTENT_TYPE)
158        .and_then(|v| v.to_str().ok())
159}
160
161fn map_parse_error(e: salvo::http::ParseError) -> VldSalvoError {
162    match e {
163        salvo::http::ParseError::PayloadTooLarge => VldHttpError::payload_too_large().into(),
164        other => VldHttpError::parse(other.to_string()).into(),
165    }
166}
167
168/// Validate a value coerced from text (query, path, form, headers, cookies).
169fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, VldSalvoError> {
170    parse_coerced(value).map_err(VldSalvoError::from)
171}
172
173fn metadata(name: &'static str, from: SourceFrom, parser: SourceParser) -> Metadata {
174    Metadata::new(name).add_default_source(Source::new(from, parser))
175}
176
177// ============================= VldJson =======================================
178
179/// Salvo extractor that validates **JSON request bodies**.
180///
181/// Use as a `#[handler]` parameter:
182///
183/// ```rust,ignore
184/// #[handler]
185/// async fn create(body: VldJson<CreateUser>, res: &mut Response) {
186///     // body.0 is the validated CreateUser
187///     res.render(Json(body.0));
188/// }
189/// ```
190pub struct VldJson<T>(pub T);
191
192impl<'ex, T: VldParse + Send> Extractible<'ex> for VldJson<T> {
193    fn metadata() -> &'static Metadata {
194        static META: OnceLock<Metadata> = OnceLock::new();
195        META.get_or_init(|| metadata("VldJson", SourceFrom::Body, SourceParser::Json))
196    }
197
198    async fn extract(
199        req: &'ex mut Request,
200        _depot: &'ex mut Depot,
201    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
202        // Read the raw body: salvo's `parse_json` rejects `application/*+json`.
203        require_json_content_type(content_type(req)).map_err(VldSalvoError::from)?;
204        let value = parse_json_body(read_body(req).await?).map_err(VldSalvoError::from)?;
205        T::vld_parse_value(&value)
206            .map(VldJson)
207            .map_err(VldSalvoError::from)
208    }
209}
210
211// ============================= VldQuery ======================================
212
213/// Salvo extractor that validates **URL query parameters**.
214///
215/// See [`crate::common::parse_query_string`] for coercion and array rules
216/// (`a=1&a=2` / `a[]=1` → arrays).
217///
218/// ```rust,ignore
219/// #[handler]
220/// async fn search(q: VldQuery<SearchParams>, res: &mut Response) {
221///     // q.page, q.limit, ...
222/// }
223/// ```
224pub struct VldQuery<T>(pub T);
225
226impl<'ex, T: VldParse + Send> Extractible<'ex> for VldQuery<T> {
227    fn metadata() -> &'static Metadata {
228        static META: OnceLock<Metadata> = OnceLock::new();
229        META.get_or_init(|| metadata("VldQuery", SourceFrom::Query, SourceParser::MultiMap))
230    }
231
232    async fn extract(
233        req: &'ex mut Request,
234        _depot: &'ex mut Depot,
235    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
236        validate(&query_string_to_json(req.uri().query().unwrap_or(""))).map(VldQuery)
237    }
238}
239
240// ============================= VldForm =======================================
241
242/// Salvo extractor that validates **URL-encoded form bodies**.
243///
244/// ```rust,ignore
245/// #[handler]
246/// async fn login(form: VldForm<LoginForm>, res: &mut Response) {
247///     // form.username, form.password
248/// }
249/// ```
250pub struct VldForm<T>(pub T);
251
252impl<'ex, T: VldParse + Send> Extractible<'ex> for VldForm<T> {
253    fn metadata() -> &'static Metadata {
254        static META: OnceLock<Metadata> = OnceLock::new();
255        META.get_or_init(|| metadata("VldForm", SourceFrom::Body, SourceParser::MultiMap))
256    }
257
258    async fn extract(
259        req: &'ex mut Request,
260        _depot: &'ex mut Depot,
261    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
262        require_form_content_type(content_type(req)).map_err(VldSalvoError::from)?;
263        let value = parse_form_body(read_body(req).await?).map_err(VldSalvoError::from)?;
264        validate(&value).map(VldForm)
265    }
266}
267
268// ============================= VldPath =======================================
269
270/// Salvo extractor that validates **path parameters**.
271///
272/// Path segment values are coerced the same way as query parameters.
273///
274/// ```rust,ignore
275/// // Route: /users/{id}
276/// vld::schema! {
277///     #[derive(Debug, Clone)]
278///     pub struct UserId {
279///         pub id: i64 => vld::number().int().min(1),
280///     }
281/// }
282///
283/// #[handler]
284/// async fn get_user(p: VldPath<UserId>, res: &mut Response) {
285///     // p.id
286/// }
287/// ```
288pub struct VldPath<T>(pub T);
289
290impl<'ex, T: VldParse + Send> Extractible<'ex> for VldPath<T> {
291    fn metadata() -> &'static Metadata {
292        static META: OnceLock<Metadata> = OnceLock::new();
293        META.get_or_init(|| metadata("VldPath", SourceFrom::Param, SourceParser::MultiMap))
294    }
295
296    async fn extract(
297        req: &'ex mut Request,
298        _depot: &'ex mut Depot,
299    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
300        let value = path_params_to_json(req.params().iter().map(|(k, v)| (k.as_str(), v.as_str())));
301        validate(&value).map(VldPath)
302    }
303}
304
305// ============================= VldHeaders ====================================
306
307/// Salvo extractor that validates **HTTP headers**.
308///
309/// See [`crate::common::headers_to_json`]: names become snake_case
310/// (`Content-Type` → `content_type`), names containing `_` are ignored,
311/// repeated headers are joined with `", "`.
312///
313/// ```rust,ignore
314/// #[handler]
315/// async fn handler(h: VldHeaders<AuthHeaders>, res: &mut Response) {
316///     // h.authorization
317/// }
318/// ```
319pub struct VldHeaders<T>(pub T);
320
321impl<'ex, T: VldParse + Send> Extractible<'ex> for VldHeaders<T> {
322    fn metadata() -> &'static Metadata {
323        static META: OnceLock<Metadata> = OnceLock::new();
324        META.get_or_init(|| metadata("VldHeaders", SourceFrom::Header, SourceParser::MultiMap))
325    }
326
327    async fn extract(
328        req: &'ex mut Request,
329        _depot: &'ex mut Depot,
330    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
331        let value = headers_to_json(
332            req.headers()
333                .iter()
334                .map(|(n, v)| (n.as_str(), v.as_bytes())),
335        );
336        validate(&value).map(VldHeaders)
337    }
338}
339
340// ============================= VldCookie =====================================
341
342/// Salvo extractor that validates **cookie values** from the `Cookie`
343/// headers (all of them; the first occurrence of a name wins).
344///
345/// Values are unquoted, percent-decoded and coerced.
346///
347/// ```rust,ignore
348/// #[handler]
349/// async fn dashboard(c: VldCookie<SessionCookies>, res: &mut Response) {
350///     // c.session_id
351/// }
352/// ```
353pub struct VldCookie<T>(pub T);
354
355impl<'ex, T: VldParse + Send> Extractible<'ex> for VldCookie<T> {
356    fn metadata() -> &'static Metadata {
357        static META: OnceLock<Metadata> = OnceLock::new();
358        META.get_or_init(|| metadata("VldCookie", SourceFrom::Cookie, SourceParser::MultiMap))
359    }
360
361    async fn extract(
362        req: &'ex mut Request,
363        _depot: &'ex mut Depot,
364    ) -> Result<Self, impl Writer + Send + std::fmt::Debug + 'static> {
365        let value = cookie_headers_to_json(
366            req.headers()
367                .get_all(salvo::http::header::COOKIE)
368                .iter()
369                .map(|v| v.as_bytes()),
370        );
371        validate(&value).map(VldCookie)
372    }
373}
374
375crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
376
377// ---------------------------------------------------------------------------
378// Prelude
379// ---------------------------------------------------------------------------
380
381/// Prelude — import everything you need.
382pub mod prelude {
383    pub use super::{VldCookie, VldForm, VldHeaders, VldJson, VldPath, VldQuery, VldSalvoError};
384    pub use vld::prelude::*;
385}