vld_web/axum.rs
1//! # `vld_web::axum` — Axum integration for the `vld` validation library
2//!
3//! Provides extractors that validate request data using `vld` schemas:
4//!
5//! | Extractor | Replaces | Source |
6//! |---|---|---|
7//! | [`VldJson<T>`] | `axum::Json<T>` | JSON request body |
8//! | [`VldQuery<T>`] | `axum::extract::Query<T>` | URL query parameters |
9//! | [`VldPath<T>`] | `axum::extract::Path<T>` | URL path parameters |
10//! | [`VldForm<T>`] | `axum::extract::Form<T>` | URL-encoded form body |
11//! | [`VldHeaders<T>`] | manual header extraction | HTTP headers |
12//! | [`VldCookie<T>`] | manual cookie parsing | Cookie values |
13//!
14//! All extractors return **422 Unprocessable Entity** on validation failure
15//! or malformed input, and **413 Payload Too Large** when the body exceeds
16//! axum's `DefaultBodyLimit` (2 MiB unless configured with
17//! `.layer(DefaultBodyLimit::max(n))`). [`VldJson`] requires a JSON
18//! `Content-Type` (`application/json` or `application/*+json`) and
19//! [`VldForm`] `application/x-www-form-urlencoded`; anything else is
20//! **415 Unsupported Media Type**. See the
21//! [error body format](crate::common#error-bodies).
22//!
23//! Guide: <https://s00d.github.io/vld/integrations/web/axum> (shared rules
24//! for all adapters: <https://s00d.github.io/vld/integrations/web/overview>).
25//!
26//! # Example
27//!
28//! ```
29//! use axum::{routing::post, Router};
30//! use vld_web::axum::{VldHeaders, VldJson, VldPath};
31//!
32//! vld::schema! {
33//! #[derive(Debug)]
34//! pub struct PathParams {
35//! pub id: i64 => vld::number().int().min(1),
36//! }
37//! }
38//!
39//! vld::schema! {
40//! #[derive(Debug)]
41//! pub struct Auth {
42//! pub authorization: String => vld::string().min(1),
43//! }
44//! }
45//!
46//! vld::schema! {
47//! #[derive(Debug)]
48//! pub struct Body {
49//! pub name: String => vld::string().min(2),
50//! }
51//! }
52//!
53//! async fn handler(
54//! VldPath(path): VldPath<PathParams>,
55//! VldHeaders(headers): VldHeaders<Auth>,
56//! VldJson(body): VldJson<Body>, // body extractors go last
57//! ) -> String {
58//! format!("id={} auth={} name={}", path.id, headers.authorization, body.name)
59//! }
60//!
61//! let app: Router = Router::new().route("/users/{id}", post(handler));
62//! ```
63use crate::common::{
64 VldHttpError, cookie_headers_to_json, headers_to_json, parse_form_body, parse_json_body,
65 path_params_to_json, percent_decode, query_string_to_json, require_form_content_type,
66 require_json_content_type,
67};
68use axum::extract::rejection::RawPathParamsRejection;
69use axum::extract::{
70 FromRequest, FromRequestParts, MatchedPath, OriginalUri, RawPathParams, Request,
71};
72use axum::response::{IntoResponse, Response};
73use http::request::Parts;
74use http::{StatusCode, header};
75use vld::schema::VldParse;
76
77// ============================= Rejection =====================================
78
79/// Rejection type returned when validation or body reading fails.
80///
81/// Used by all `Vld*` extractors in this crate.
82pub struct VldJsonRejection(VldHttpError);
83
84impl VldJsonRejection {
85 /// Get a reference to the underlying `VldError`.
86 pub fn error(&self) -> &vld::error::VldError {
87 self.0.error()
88 }
89
90 /// HTTP status of this rejection (422, 413 or 415).
91 pub fn status(&self) -> StatusCode {
92 StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
93 }
94
95 /// JSON response body.
96 pub fn body(&self) -> serde_json::Value {
97 self.0.body()
98 }
99}
100
101impl From<VldHttpError> for VldJsonRejection {
102 fn from(e: VldHttpError) -> Self {
103 Self(e)
104 }
105}
106
107impl From<vld::error::VldError> for VldJsonRejection {
108 fn from(e: vld::error::VldError) -> Self {
109 Self(e.into())
110 }
111}
112
113impl IntoResponse for VldJsonRejection {
114 fn into_response(self) -> Response {
115 (
116 self.status(),
117 [(http::header::CONTENT_TYPE, "application/json")],
118 self.0.body().to_string(),
119 )
120 .into_response()
121 }
122}
123
124impl std::fmt::Display for VldJsonRejection {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 self.0.fmt(f)
127 }
128}
129
130impl std::fmt::Debug for VldJsonRejection {
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 f.debug_struct("VldJsonRejection")
133 .field("error", self.error())
134 .field("status", &self.status())
135 .finish()
136 }
137}
138
139impl std::error::Error for VldJsonRejection {}
140
141/// Read the body via axum's `Bytes` extractor (respects `DefaultBodyLimit`).
142async fn read_body<S: Send + Sync>(req: Request, state: &S) -> Result<bytes::Bytes, VldHttpError> {
143 <bytes::Bytes as FromRequest<S>>::from_request(req, state)
144 .await
145 .map_err(|rejection| {
146 if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE {
147 VldHttpError::payload_too_large()
148 } else {
149 VldHttpError::parse(format!("Failed to read request body: {rejection}"))
150 }
151 })
152}
153
154/// Validate a value coerced from text (query, path, form, headers, cookies).
155fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, VldJsonRejection> {
156 crate::common::parse_coerced(value).map_err(VldJsonRejection::from)
157}
158
159fn content_type(headers: &http::HeaderMap) -> Option<&str> {
160 headers
161 .get(header::CONTENT_TYPE)
162 .and_then(|v| v.to_str().ok())
163}
164
165/// Path params decoded lossily (`%FF` → `U+FFFD`), for when axum refuses
166/// them as invalid UTF-8: match the raw path against the route template.
167fn lossy_path_params(parts: &Parts) -> serde_json::Value {
168 let Some(matched) = parts.extensions.get::<MatchedPath>() else {
169 return serde_json::json!({});
170 };
171 // Nested routers see a stripped URI; the template is the full path.
172 let uri = parts
173 .extensions
174 .get::<OriginalUri>()
175 .map_or(&parts.uri, |o| &o.0);
176 let mut values = uri.path().split('/');
177 let mut params = Vec::new();
178 for pattern in matched.as_str().split('/') {
179 let value = values.next();
180 let Some(name) = pattern.strip_prefix('{').and_then(|p| p.strip_suffix('}')) else {
181 continue;
182 };
183 if let Some(name) = name.strip_prefix('*') {
184 let rest: Vec<&str> = value.into_iter().chain(values.by_ref()).collect();
185 params.push((name, percent_decode(&rest.join("/"))));
186 break;
187 }
188 if let Some(value) = value {
189 params.push((name, percent_decode(value)));
190 }
191 }
192 path_params_to_json(params.iter().map(|(k, v)| (*k, v.as_str())))
193}
194
195// ============================= VldJson =======================================
196
197/// Axum extractor that validates **JSON request bodies**.
198///
199/// Drop-in replacement for `axum::Json<T>`.
200pub struct VldJson<T>(pub T);
201
202impl<S, T> FromRequest<S> for VldJson<T>
203where
204 S: Send + Sync,
205 T: VldParse,
206{
207 type Rejection = VldJsonRejection;
208
209 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
210 require_json_content_type(content_type(req.headers()))?;
211 let body = read_body(req, state).await?;
212 T::vld_parse_value(&parse_json_body(&body)?)
213 .map(VldJson)
214 .map_err(VldJsonRejection::from)
215 }
216}
217
218// ============================= VldQuery ======================================
219
220/// Axum extractor that validates **URL query parameters**.
221///
222/// Drop-in replacement for `axum::extract::Query<T>`.
223///
224/// See [`crate::common::parse_query_string`] for coercion and array rules
225/// (`a=1&a=2` / `a[]=1` → arrays; non-canonical numbers stay strings).
226pub struct VldQuery<T>(pub T);
227
228impl<S, T> FromRequestParts<S> for VldQuery<T>
229where
230 S: Send + Sync,
231 T: VldParse,
232{
233 type Rejection = VldJsonRejection;
234
235 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
236 validate(&query_string_to_json(parts.uri.query().unwrap_or(""))).map(VldQuery)
237 }
238}
239
240// ============================= VldPath =======================================
241
242/// Axum extractor that validates **URL path parameters**.
243///
244/// Drop-in replacement for `axum::extract::Path<T>`.
245///
246/// Path segment values are percent-decoded (invalid UTF-8 becomes `U+FFFD`)
247/// and coerced the same way as query parameters. On a route without
248/// parameters the input is an empty object.
249///
250/// # Example
251///
252/// ```ignore
253/// // Route: /users/{id}/posts/{post_id}
254/// vld::schema! {
255/// #[derive(Debug)]
256/// pub struct PostPath {
257/// pub id: i64 => vld::number().int().min(1),
258/// pub post_id: i64 => vld::number().int().min(1),
259/// }
260/// }
261///
262/// async fn get_post(VldPath(p): VldPath<PostPath>) -> String {
263/// format!("user {} post {}", p.id, p.post_id)
264/// }
265/// ```
266pub struct VldPath<T>(pub T);
267
268impl<S, T> FromRequestParts<S> for VldPath<T>
269where
270 S: Send + Sync,
271 T: VldParse,
272{
273 type Rejection = VldJsonRejection;
274
275 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
276 let value = match RawPathParams::from_request_parts(parts, state).await {
277 Ok(params) => path_params_to_json(¶ms),
278 Err(RawPathParamsRejection::InvalidUtf8InPathParam(_)) => lossy_path_params(parts),
279 Err(_) => serde_json::json!({}),
280 };
281 validate(&value).map(VldPath)
282 }
283}
284
285// ============================= VldForm =======================================
286
287/// Axum extractor that validates **URL-encoded form bodies**
288/// (`application/x-www-form-urlencoded`).
289///
290/// Drop-in replacement for `axum::extract::Form<T>`.
291///
292/// Values are parsed the same way as query parameters.
293///
294/// # Example
295///
296/// ```ignore
297/// vld::schema! {
298/// #[derive(Debug)]
299/// pub struct LoginForm {
300/// pub username: String => vld::string().min(3).max(50),
301/// pub password: String => vld::string().min(8),
302/// }
303/// }
304///
305/// async fn login(VldForm(form): VldForm<LoginForm>) -> String {
306/// format!("Welcome, {}!", form.username)
307/// }
308/// ```
309pub struct VldForm<T>(pub T);
310
311impl<S, T> FromRequest<S> for VldForm<T>
312where
313 S: Send + Sync,
314 T: VldParse,
315{
316 type Rejection = VldJsonRejection;
317
318 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
319 require_form_content_type(content_type(req.headers()))?;
320 let body = read_body(req, state).await?;
321 validate(&parse_form_body(&body)?).map(VldForm)
322 }
323}
324
325// ============================= VldHeaders ====================================
326
327/// Axum extractor that validates **HTTP headers**.
328///
329/// See [`crate::common::headers_to_json`]: names become snake_case
330/// (`X-Request-Id` → `x_request_id`), names containing `_` are ignored,
331/// repeated headers are joined with `", "`, non-UTF-8 bytes are replaced
332/// with `U+FFFD`.
333///
334/// # Example
335///
336/// ```ignore
337/// vld::schema! {
338/// #[derive(Debug)]
339/// pub struct RequiredHeaders {
340/// pub authorization: String => vld::string().min(1),
341/// pub x_request_id: Option<String> => vld::string().uuid().optional(),
342/// }
343/// }
344///
345/// async fn handler(VldHeaders(h): VldHeaders<RequiredHeaders>) -> String {
346/// format!("auth={}", h.authorization)
347/// }
348/// ```
349pub struct VldHeaders<T>(pub T);
350
351impl<S, T> FromRequestParts<S> for VldHeaders<T>
352where
353 S: Send + Sync,
354 T: VldParse,
355{
356 type Rejection = VldJsonRejection;
357
358 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
359 let value = headers_to_json(
360 parts
361 .headers
362 .iter()
363 .map(|(n, v)| (n.as_str(), v.as_bytes())),
364 );
365 validate(&value).map(VldHeaders)
366 }
367}
368
369// ============================= VldCookie =====================================
370
371/// Axum extractor that validates **cookie values** from the `Cookie`
372/// headers (all of them; the first occurrence of a name wins).
373///
374/// Cookie names are used as-is for schema field matching.
375/// Values are unquoted, percent-decoded and coerced.
376///
377/// # Example
378///
379/// ```ignore
380/// vld::schema! {
381/// #[derive(Debug)]
382/// pub struct SessionCookies {
383/// pub session_id: String => vld::string().min(1),
384/// pub theme: Option<String> => vld::string().optional(),
385/// }
386/// }
387///
388/// async fn dashboard(VldCookie(c): VldCookie<SessionCookies>) -> String {
389/// format!("session={}", c.session_id)
390/// }
391/// ```
392pub struct VldCookie<T>(pub T);
393
394impl<S, T> FromRequestParts<S> for VldCookie<T>
395where
396 S: Send + Sync,
397 T: VldParse,
398{
399 type Rejection = VldJsonRejection;
400
401 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
402 let value = cookie_headers_to_json(
403 parts
404 .headers
405 .get_all(header::COOKIE)
406 .iter()
407 .map(|v| v.as_bytes()),
408 );
409 validate(&value).map(VldCookie)
410 }
411}
412
413crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
414
415#[cfg(feature = "axum-ws")]
416pub mod ws;
417
418/// Prelude — import everything you need.
419pub mod prelude {
420 pub use super::{VldCookie, VldForm, VldHeaders, VldJson, VldJsonRejection, VldPath, VldQuery};
421 pub use vld::prelude::*;
422}