Skip to main content

vld_web/
poem.rs

1//! # `vld_web::poem` — Poem integration for `vld`
2//!
3//! Validation extractors for [Poem](https://docs.rs/poem). Validates request
4//! data against `vld` schemas and returns `422 Unprocessable Entity` with
5//! structured JSON errors on failure (`413 Payload Too Large` when a body
6//! exceeds the limit). `VldJson` requires a JSON `Content-Type`
7//! (`application/json` or `application/*+json`) and `VldForm`
8//! `application/x-www-form-urlencoded`; anything else is
9//! `415 Unsupported Media Type`. See the
10//! [error body format](crate::common#error-bodies).
11//!
12//! Guide: <https://s00d.github.io/vld/integrations/web/poem> (shared rules
13//! for all adapters: <https://s00d.github.io/vld/integrations/web/overview>).
14//!
15//! # Example
16//!
17//! ```no_run
18//! use poem::{get, handler, post, EndpointExt, Route};
19//! use vld_web::poem::prelude::*;
20//!
21//! vld::schema! {
22//!     #[derive(Debug, Clone)]
23//!     pub struct CreateUser {
24//!         pub name: String => vld::string().min(2).max(50),
25//!         pub email: String => vld::string().email(),
26//!     }
27//! }
28//!
29//! vld::schema! {
30//!     #[derive(Debug, Clone)]
31//!     pub struct UserPath {
32//!         pub id: i64 => vld::number().int().min(1),
33//!     }
34//! }
35//!
36//! #[handler]
37//! async fn create_user(user: VldJson<CreateUser>) -> String {
38//!     format!("created {}", user.name)
39//! }
40//!
41//! #[handler]
42//! async fn get_user(p: VldPath<UserPath>) -> String {
43//!     format!("user #{}", p.id)
44//! }
45//!
46//! let app = Route::new()
47//!     .at("/users", post(create_user))
48//!     .at("/users/:id", get(get_user));
49//! ```
50//!
51//! # Body limit
52//!
53//! `VldJson` and `VldForm` read at most [`DEFAULT_BODY_LIMIT`] (2 MiB);
54//! attach [`VldBodyLimit`] as request data to change it:
55//!
56//! ```no_run
57//! use poem::{handler, post, EndpointExt, Route};
58//!
59//! #[handler]
60//! fn upload() -> &'static str { "ok" }
61//!
62//! let app = Route::new().at("/upload", post(upload).data(vld_web::poem::VldBodyLimit(8 << 20)));
63//! ```
64//!
65//! # Extractors
66//!
67//! | Extractor | Source |
68//! |-----------|--------|
69//! | `VldJson<T>` | JSON body |
70//! | `VldQuery<T>` | Query string |
71//! | `VldPath<T>` | Path parameters |
72//! | `VldForm<T>` | Form body |
73//! | `VldHeaders<T>` | HTTP headers |
74//! | `VldCookie<T>` | Cookie values |
75pub use crate::common::VldBodyLimit;
76use crate::common::{
77    DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_form_body,
78    parse_json_body, path_params_to_json, query_string_to_json, require_form_content_type,
79    require_json_content_type,
80};
81use poem::error::{ReadBodyError, ResponseError};
82use poem::http::StatusCode;
83use poem::{FromRequest, Request, RequestBody, Result};
84use std::fmt;
85use vld::schema::VldParse;
86
87// ---------------------------------------------------------------------------
88// Error type
89// ---------------------------------------------------------------------------
90
91/// Validation / parse error returned by vld-poem extractors; wraps
92/// [`VldHttpError`].
93#[derive(Debug)]
94pub struct VldPoemError {
95    inner: VldHttpError,
96}
97
98impl VldPoemError {
99    /// The underlying validation error.
100    pub fn error(&self) -> &vld::error::VldError {
101        self.inner.error()
102    }
103
104    /// HTTP status (422, 413 or 415).
105    pub fn status(&self) -> StatusCode {
106        StatusCode::from_u16(self.inner.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
107    }
108
109    /// JSON response body.
110    pub fn body(&self) -> serde_json::Value {
111        self.inner.body()
112    }
113}
114
115impl From<VldHttpError> for VldPoemError {
116    fn from(inner: VldHttpError) -> Self {
117        Self { inner }
118    }
119}
120
121impl From<vld::error::VldError> for VldPoemError {
122    fn from(e: vld::error::VldError) -> Self {
123        VldHttpError::from(e).into()
124    }
125}
126
127impl fmt::Display for VldPoemError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        self.inner.fmt(f)
130    }
131}
132
133impl std::error::Error for VldPoemError {}
134
135impl ResponseError for VldPoemError {
136    fn status(&self) -> StatusCode {
137        VldPoemError::status(self)
138    }
139
140    fn as_response(&self) -> poem::Response {
141        poem::Response::builder()
142            .status(VldPoemError::status(self))
143            .content_type("application/json")
144            .body(self.body().to_string())
145    }
146}
147
148fn reject(e: VldHttpError) -> poem::Error {
149    VldPoemError::from(e).into()
150}
151
152/// Validate a value coerced from text (query, path, form, headers, cookies).
153fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T> {
154    crate::common::parse_coerced(value).map_err(|e| VldPoemError::from(e).into())
155}
156
157/// Read the body up to the [`VldBodyLimit`] request data, or
158/// [`DEFAULT_BODY_LIMIT`].
159async fn read_limited_body(
160    req: &Request,
161    body: &mut RequestBody,
162) -> Result<impl AsRef<[u8]> + use<>> {
163    let limit = req
164        .data::<VldBodyLimit>()
165        .map_or(DEFAULT_BODY_LIMIT, |l| l.0);
166    let body = body
167        .take()
168        .map_err(|e| reject(VldHttpError::parse(format!("Failed to read body: {e}"))))?;
169    body.into_bytes_limit(limit).await.map_err(|e| match e {
170        ReadBodyError::PayloadTooLarge => reject(VldHttpError::payload_too_large()),
171        other => reject(VldHttpError::parse(format!("Failed to read body: {other}"))),
172    })
173}
174
175// ---------------------------------------------------------------------------
176// VldJson<T>
177// ---------------------------------------------------------------------------
178
179/// Validated JSON body extractor for Poem.
180#[derive(Debug, Clone)]
181pub struct VldJson<T>(pub T);
182
183impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldJson<T> {
184    async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
185        require_json_content_type(req.content_type()).map_err(reject)?;
186        let bytes = read_limited_body(req, body).await?;
187        T::vld_parse_value(&parse_json_body(bytes.as_ref()).map_err(reject)?)
188            .map(VldJson)
189            .map_err(|e| VldPoemError::from(e).into())
190    }
191}
192
193// ---------------------------------------------------------------------------
194// VldQuery<T>
195// ---------------------------------------------------------------------------
196
197/// Validated query string extractor for Poem.
198///
199/// See [`crate::common::parse_query_string`] for coercion and array rules.
200#[derive(Debug, Clone)]
201pub struct VldQuery<T>(pub T);
202
203impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldQuery<T> {
204    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
205        validate(&query_string_to_json(req.uri().query().unwrap_or(""))).map(VldQuery)
206    }
207}
208
209// ---------------------------------------------------------------------------
210// VldForm<T>
211// ---------------------------------------------------------------------------
212
213/// Validated form body extractor for Poem.
214#[derive(Debug, Clone)]
215pub struct VldForm<T>(pub T);
216
217impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldForm<T> {
218    async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
219        require_form_content_type(req.content_type()).map_err(reject)?;
220        let bytes = read_limited_body(req, body).await?;
221        validate(&parse_form_body(bytes.as_ref()).map_err(reject)?).map(VldForm)
222    }
223}
224
225// ---------------------------------------------------------------------------
226// VldPath<T>
227// ---------------------------------------------------------------------------
228
229/// Validated path parameters extractor for Poem.
230///
231/// Path values are coerced the same way as query parameters.
232#[derive(Debug, Clone)]
233pub struct VldPath<T>(pub T);
234
235impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldPath<T> {
236    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
237        // `Request::params` parses the *query string*; route parameters come from
238        // `path_params` (the router's match params).
239        let params = req
240            .path_params::<std::collections::BTreeMap<String, String>>()
241            .unwrap_or_default();
242        validate(&path_params_to_json(
243            params.iter().map(|(k, v)| (k.as_str(), v.as_str())),
244        ))
245        .map(VldPath)
246    }
247}
248
249// ---------------------------------------------------------------------------
250// VldHeaders<T>
251// ---------------------------------------------------------------------------
252
253/// Validated HTTP headers extractor for Poem.
254///
255/// See [`crate::common::headers_to_json`]: names become snake_case
256/// (`Content-Type` → `content_type`), names containing `_` are ignored,
257/// repeated headers are joined with `", "`.
258#[derive(Debug, Clone)]
259pub struct VldHeaders<T>(pub T);
260
261impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldHeaders<T> {
262    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
263        let value = headers_to_json(
264            req.headers()
265                .iter()
266                .map(|(n, v)| (n.as_str(), v.as_bytes())),
267        );
268        validate(&value).map(VldHeaders)
269    }
270}
271
272// ---------------------------------------------------------------------------
273// VldCookie<T>
274// ---------------------------------------------------------------------------
275
276/// Validated cookie extractor for Poem.
277///
278/// Reads cookies from every `Cookie` header (the first occurrence of a name
279/// wins) and validates against the schema. Values are unquoted,
280/// percent-decoded and coerced.
281#[derive(Debug, Clone)]
282pub struct VldCookie<T>(pub T);
283
284impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldCookie<T> {
285    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
286        let value = cookie_headers_to_json(
287            req.headers()
288                .get_all(poem::http::header::COOKIE)
289                .iter()
290                .map(|v| v.as_bytes()),
291        );
292        validate(&value).map(VldCookie)
293    }
294}
295
296crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
297
298/// Prelude — import everything you need.
299pub mod prelude {
300    pub use super::{
301        VldBodyLimit, VldCookie, VldForm, VldHeaders, VldJson, VldPath, VldPoemError, VldQuery,
302    };
303    pub use vld::prelude::*;
304}