Skip to main content

vld_web/
actix.rs

1//! # `vld_web::actix` — Actix-web 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>`] | `actix_web::web::Json<T>` | JSON request body |
8//! | [`VldQuery<T>`] | `actix_web::web::Query<T>` | URL query parameters |
9//! | [`VldPath<T>`] | `actix_web::web::Path<T>` | URL path parameters |
10//! | [`VldForm<T>`] | `actix_web::web::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//! the limit. [`VldJson`] requires a JSON `Content-Type` (`application/json`
17//! or `application/*+json`) and [`VldForm`]
18//! `application/x-www-form-urlencoded`; anything else is **415 Unsupported
19//! Media Type**. See the [error body format](crate::common#error-bodies).
20//!
21//! Guide: <https://s00d.github.io/vld/integrations/web/actix> (shared rules
22//! for all adapters: <https://s00d.github.io/vld/integrations/web/overview>).
23//!
24//! # Body limits
25//!
26//! [`VldJson`] and [`VldForm`] read the body themselves (compressed bodies
27//! are decoded; the limit applies to the decoded size) up to
28//! [`DEFAULT_BODY_LIMIT`] (2 MiB). Register [`VldBodyLimit`] with
29//! `app_data` to change it — actix's `JsonConfig` / `PayloadConfig` do not
30//! apply:
31//!
32//! ```no_run
33//! use actix_web::App;
34//!
35//! let app = App::new().app_data(vld_web::actix::VldBodyLimit(8 * 1024 * 1024));
36//! ```
37//!
38//! # Example
39//!
40//! ```no_run
41//! use actix_web::{web, App, HttpResponse};
42//! use vld_web::actix::{VldHeaders, VldJson, VldPath};
43//!
44//! vld::schema! {
45//!     #[derive(Debug)]
46//!     pub struct PathParams {
47//!         pub id: i64 => vld::number().int().min(1),
48//!     }
49//! }
50//!
51//! vld::schema! {
52//!     #[derive(Debug)]
53//!     pub struct Auth {
54//!         pub authorization: String => vld::string().min(1),
55//!     }
56//! }
57//!
58//! vld::schema! {
59//!     #[derive(Debug)]
60//!     pub struct Body {
61//!         pub name: String => vld::string().min(2),
62//!     }
63//! }
64//!
65//! async fn handler(
66//!     path: VldPath<PathParams>,
67//!     headers: VldHeaders<Auth>,
68//!     body: VldJson<Body>,
69//! ) -> HttpResponse {
70//!     HttpResponse::Ok().body(format!(
71//!         "id={} auth={} name={}",
72//!         path.id, headers.authorization, body.name,
73//!     ))
74//! }
75//!
76//! let app = App::new().route("/users/{id}", web::post().to(handler));
77//! ```
78pub use crate::common::VldBodyLimit;
79use crate::common::{
80    DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced,
81    parse_form_body, parse_json_body, path_params_to_json, percent_decode, query_string_to_json,
82    require_form_content_type, require_json_content_type,
83};
84use actix_web::body::{BodyStream, to_bytes_limited};
85use actix_web::dev::{Decompress, Payload};
86use actix_web::http::{StatusCode, header};
87use actix_web::{FromRequest, HttpRequest, HttpResponse, ResponseError};
88use std::fmt;
89use std::future::Future;
90use std::pin::Pin;
91
92// ============================= Error / Rejection =============================
93
94/// Error type returned when validation or body reading fails.
95///
96/// Used by all `Vld*` extractors in this crate; wraps [`VldHttpError`].
97#[derive(Debug)]
98pub struct VldActixError(VldHttpError);
99
100impl VldActixError {
101    /// The underlying validation error.
102    pub fn error(&self) -> &vld::error::VldError {
103        self.0.error()
104    }
105
106    /// HTTP status (422, 413 or 415).
107    pub fn status(&self) -> StatusCode {
108        StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
109    }
110
111    /// JSON response body.
112    pub fn body(&self) -> serde_json::Value {
113        self.0.body()
114    }
115}
116
117impl From<VldHttpError> for VldActixError {
118    fn from(e: VldHttpError) -> Self {
119        Self(e)
120    }
121}
122
123impl From<vld::error::VldError> for VldActixError {
124    fn from(e: vld::error::VldError) -> Self {
125        Self(e.into())
126    }
127}
128
129impl fmt::Display for VldActixError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        self.0.fmt(f)
132    }
133}
134
135impl ResponseError for VldActixError {
136    fn status_code(&self) -> StatusCode {
137        self.status()
138    }
139
140    fn error_response(&self) -> HttpResponse {
141        HttpResponse::build(self.status_code())
142            .content_type("application/json")
143            .body(self.0.body().to_string())
144    }
145}
146
147/// Read the (decompressed) body up to the [`VldBodyLimit`] app data, or
148/// [`DEFAULT_BODY_LIMIT`].
149fn read_body(
150    req: &HttpRequest,
151    payload: &mut Payload,
152) -> impl Future<Output = Result<actix_web::web::Bytes, VldHttpError>> + 'static + use<> {
153    let limit = req
154        .app_data::<VldBodyLimit>()
155        .map_or(DEFAULT_BODY_LIMIT, |l| l.0);
156    let stream = Decompress::from_headers(payload.take(), req.headers());
157    async move {
158        match to_bytes_limited(BodyStream::new(stream), limit).await {
159            Ok(Ok(bytes)) => Ok(bytes),
160            Ok(Err(e)) => Err(VldHttpError::parse(format!(
161                "Failed to read request body: {e}"
162            ))),
163            Err(_) => Err(VldHttpError::payload_too_large()),
164        }
165    }
166}
167
168fn content_type(req: &HttpRequest) -> Option<&str> {
169    req.headers()
170        .get(header::CONTENT_TYPE)
171        .and_then(|v| v.to_str().ok())
172}
173
174/// Validate a JSON value against `T`.
175fn validate<T: vld::schema::VldParse>(value: &serde_json::Value) -> Result<T, VldActixError> {
176    T::vld_parse_value(value).map_err(VldActixError::from)
177}
178
179/// Validate a value coerced from text (query, path, form, headers, cookies).
180fn validate_coerced<T: vld::schema::VldParse>(
181    value: &serde_json::Value,
182) -> Result<T, VldActixError> {
183    parse_coerced(value).map_err(VldActixError::from)
184}
185
186/// Extractor future type.
187type ExtractFuture<T> = Pin<Box<dyn Future<Output = Result<T, VldActixError>>>>;
188
189// ============================= VldJson =======================================
190
191/// Actix-web extractor that validates **JSON request bodies**.
192///
193/// Drop-in replacement for `actix_web::web::Json<T>`.
194pub struct VldJson<T>(pub T);
195
196impl<T: vld::schema::VldParse> FromRequest for VldJson<T> {
197    type Error = VldActixError;
198    type Future = ExtractFuture<Self>;
199
200    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
201        if let Err(e) = require_json_content_type(content_type(req)) {
202            return Box::pin(async move { Err(e.into()) });
203        }
204        let body = read_body(req, payload);
205        Box::pin(async move { validate(&parse_json_body(&body.await?)?).map(VldJson) })
206    }
207}
208
209// ============================= VldQuery ======================================
210
211/// Actix-web extractor that validates **URL query parameters**.
212///
213/// Drop-in replacement for `actix_web::web::Query<T>`.
214///
215/// See [`crate::common::parse_query_string`] for coercion and array rules.
216pub struct VldQuery<T>(pub T);
217
218impl<T: vld::schema::VldParse> FromRequest for VldQuery<T> {
219    type Error = VldActixError;
220    type Future = ExtractFuture<Self>;
221
222    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
223        let value = query_string_to_json(req.query_string());
224        Box::pin(async move { validate_coerced(&value).map(VldQuery) })
225    }
226}
227
228// ============================= VldPath =======================================
229
230/// Actix-web extractor that validates **URL path parameters**.
231///
232/// Drop-in replacement for `actix_web::web::Path<T>`. Works with custom
233/// segment patterns such as `{id:\d+}`.
234///
235/// Path segment values are percent-decoded (actix keeps `%2F`, `%25` and
236/// `%2B` encoded in `match_info`) and coerced the same way as query
237/// parameters.
238///
239/// # Example
240///
241/// ```ignore
242/// // Route: /users/{id}/posts/{post_id}
243/// vld::schema! {
244///     #[derive(Debug)]
245///     pub struct PostPath {
246///         pub id: i64 => vld::number().int().min(1),
247///         pub post_id: i64 => vld::number().int().min(1),
248///     }
249/// }
250///
251/// async fn get_post(path: VldPath<PostPath>) -> HttpResponse {
252///     HttpResponse::Ok().body(format!("user {} post {}", path.id, path.post_id))
253/// }
254/// ```
255pub struct VldPath<T>(pub T);
256
257impl<T: vld::schema::VldParse> FromRequest for VldPath<T> {
258    type Error = VldActixError;
259    type Future = ExtractFuture<Self>;
260
261    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
262        let params: Vec<_> = req
263            .match_info()
264            .iter()
265            .map(|(k, v)| (k, percent_decode(v)))
266            .collect();
267        let value = path_params_to_json(params.iter().map(|(k, v)| (*k, v.as_str())));
268        Box::pin(async move { validate_coerced(&value).map(VldPath) })
269    }
270}
271
272// ============================= VldForm =======================================
273
274/// Actix-web extractor that validates **URL-encoded form bodies**
275/// (`application/x-www-form-urlencoded`).
276///
277/// Drop-in replacement for `actix_web::web::Form<T>`.
278///
279/// Values are parsed the same way as query parameters.
280///
281/// # Example
282///
283/// ```ignore
284/// vld::schema! {
285///     #[derive(Debug)]
286///     pub struct LoginForm {
287///         pub username: String => vld::string().min(3).max(50),
288///         pub password: String => vld::string().min(8),
289///     }
290/// }
291///
292/// async fn login(form: VldForm<LoginForm>) -> HttpResponse {
293///     HttpResponse::Ok().body(format!("Welcome, {}!", form.username))
294/// }
295/// ```
296pub struct VldForm<T>(pub T);
297
298impl<T: vld::schema::VldParse> FromRequest for VldForm<T> {
299    type Error = VldActixError;
300    type Future = ExtractFuture<Self>;
301
302    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
303        if let Err(e) = require_form_content_type(content_type(req)) {
304            return Box::pin(async move { Err(e.into()) });
305        }
306        let body = read_body(req, payload);
307        Box::pin(async move { validate_coerced(&parse_form_body(&body.await?)?).map(VldForm) })
308    }
309}
310
311// ============================= VldHeaders ====================================
312
313/// Actix-web extractor that validates **HTTP headers**.
314///
315/// See [`crate::common::headers_to_json`]: names become snake_case
316/// (`X-Request-Id` → `x_request_id`), names containing `_` are ignored,
317/// repeated headers are joined with `", "`.
318///
319/// # Example
320///
321/// ```ignore
322/// vld::schema! {
323///     #[derive(Debug)]
324///     pub struct RequiredHeaders {
325///         pub authorization: String => vld::string().min(1),
326///         pub x_request_id: Option<String> => vld::string().uuid().optional(),
327///     }
328/// }
329///
330/// async fn handler(headers: VldHeaders<RequiredHeaders>) -> HttpResponse {
331///     HttpResponse::Ok().body(format!("auth={}", headers.authorization))
332/// }
333/// ```
334pub struct VldHeaders<T>(pub T);
335
336impl<T: vld::schema::VldParse> FromRequest for VldHeaders<T> {
337    type Error = VldActixError;
338    type Future = ExtractFuture<Self>;
339
340    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
341        let value = headers_to_json(
342            req.headers()
343                .iter()
344                .map(|(n, v)| (n.as_str(), v.as_bytes())),
345        );
346        Box::pin(async move { validate_coerced(&value).map(VldHeaders) })
347    }
348}
349
350// ============================= VldCookie =====================================
351
352/// Actix-web extractor that validates **cookie values** from the `Cookie`
353/// headers (all of them; the first occurrence of a name wins).
354///
355/// Cookie names are used as-is for schema field matching.
356/// Values are unquoted, percent-decoded and coerced.
357///
358/// # Example
359///
360/// ```ignore
361/// vld::schema! {
362///     #[derive(Debug)]
363///     pub struct SessionCookies {
364///         pub session_id: String => vld::string().min(1),
365///         pub theme: Option<String> => vld::string().optional(),
366///     }
367/// }
368///
369/// async fn dashboard(cookies: VldCookie<SessionCookies>) -> HttpResponse {
370///     HttpResponse::Ok().body(format!("session={}", cookies.session_id))
371/// }
372/// ```
373pub struct VldCookie<T>(pub T);
374
375impl<T: vld::schema::VldParse> FromRequest for VldCookie<T> {
376    type Error = VldActixError;
377    type Future = ExtractFuture<Self>;
378
379    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
380        let value =
381            cookie_headers_to_json(req.headers().get_all(header::COOKIE).map(|v| v.as_bytes()));
382        Box::pin(async move { validate_coerced(&value).map(VldCookie) })
383    }
384}
385
386crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
387
388/// Prelude — import everything you need.
389pub mod prelude {
390    pub use super::{
391        VldActixError, VldBodyLimit, VldCookie, VldForm, VldHeaders, VldJson, VldPath, VldQuery,
392    };
393    pub use vld::prelude::*;
394}