Skip to main content

vld_web/ntex/
shared.rs

1//! The ntex adapter, written once against `super::ntex` and compiled by
2//! `ntex3.rs` / `ntex4.rs`; what differs between the majors is in their
3//! `compat` modules.
4
5use super::ntex;
6pub use crate::common::VldBodyLimit;
7use crate::common::{
8    DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced,
9    parse_form_body, parse_json_body, path_params_to_json, query_string_to_json,
10    require_form_content_type, require_json_content_type,
11};
12use ntex::http::{Payload, StatusCode, header};
13use ntex::web::{HttpRequest, HttpResponse, HttpResponseBuilder};
14use std::fmt;
15use vld::schema::VldParse;
16
17// ============================= Error / Rejection =============================
18
19/// Error type returned when validation or body reading fails.
20///
21/// Used by all `Vld*` extractors in this crate; wraps [`VldHttpError`].
22#[derive(Debug)]
23pub struct VldNtexError(VldHttpError);
24
25impl VldNtexError {
26    /// The underlying validation error.
27    pub fn error(&self) -> &vld::error::VldError {
28        self.0.error()
29    }
30
31    /// HTTP status (422, 413 or 415).
32    pub fn status(&self) -> StatusCode {
33        StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
34    }
35
36    /// JSON response body.
37    pub fn body(&self) -> serde_json::Value {
38        self.0.body()
39    }
40}
41
42impl From<VldHttpError> for VldNtexError {
43    fn from(e: VldHttpError) -> Self {
44        Self(e)
45    }
46}
47
48impl From<vld::error::VldError> for VldNtexError {
49    fn from(e: vld::error::VldError) -> Self {
50        Self(e.into())
51    }
52}
53
54impl fmt::Display for VldNtexError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        self.0.fmt(f)
57    }
58}
59
60impl std::error::Error for VldNtexError {}
61
62impl VldNtexError {
63    pub(super) fn render(&self) -> HttpResponse {
64        HttpResponseBuilder::new(self.status())
65            .header("content-type", "application/json")
66            .body(self.0.body().to_string())
67    }
68}
69
70/// Read the body up to the [`VldBodyLimit`] app state, or
71/// [`DEFAULT_BODY_LIMIT`].
72async fn read_body(req: &HttpRequest, payload: &mut Payload) -> Result<Vec<u8>, VldHttpError> {
73    let limit = super::compat::app_value::<VldBodyLimit>(req).map_or(DEFAULT_BODY_LIMIT, |l| l.0);
74    // With `ntex-compress`, decode `Content-Encoding` like ntex's own body
75    // extractors; the limit applies to the decoded size.
76    #[cfg(feature = "ntex-compress")]
77    let mut stream = ntex::http::encoding::Decoder::from_headers(payload.take(), req.headers());
78    #[cfg(not(feature = "ntex-compress"))]
79    let mut stream = payload.take();
80    let mut body = Vec::new();
81    while let Some(chunk) = ntex::util::stream_recv(&mut stream).await {
82        let chunk =
83            chunk.map_err(|e| VldHttpError::parse(format!("Failed to read request body: {e}")))?;
84        if body.len() + chunk.len() > limit {
85            return Err(VldHttpError::payload_too_large());
86        }
87        body.extend_from_slice(&chunk);
88    }
89    Ok(body)
90}
91
92fn content_type(req: &HttpRequest) -> Option<&str> {
93    req.headers()
94        .get(header::CONTENT_TYPE)
95        .and_then(|v| v.to_str().ok())
96}
97
98/// Validate a value coerced from text (query, path, form, headers, cookies).
99fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, VldNtexError> {
100    parse_coerced(value).map_err(VldNtexError::from)
101}
102
103// ============================= VldJson =======================================
104
105/// ntex extractor that validates **JSON request bodies**.
106///
107/// Drop-in replacement for `ntex::web::types::Json<T>`.
108pub struct VldJson<T>(pub T);
109
110impl<T: VldParse> VldJson<T> {
111    pub(super) async fn extract(
112        req: &HttpRequest,
113        payload: &mut Payload,
114    ) -> Result<Self, VldNtexError> {
115        require_json_content_type(content_type(req))?;
116        let body = read_body(req, payload).await?;
117        T::vld_parse_value(&parse_json_body(&body)?)
118            .map(VldJson)
119            .map_err(VldNtexError::from)
120    }
121}
122
123// ============================= VldQuery ======================================
124
125/// ntex extractor that validates **URL query parameters**.
126///
127/// Drop-in replacement for `ntex::web::types::Query<T>`.
128///
129/// See [`crate::common::parse_query_string`] for coercion and array rules.
130pub struct VldQuery<T>(pub T);
131
132impl<T: VldParse> VldQuery<T> {
133    pub(super) async fn extract(
134        req: &HttpRequest,
135        _payload: &mut Payload,
136    ) -> Result<Self, VldNtexError> {
137        validate(&query_string_to_json(req.query_string())).map(VldQuery)
138    }
139}
140
141// ============================= VldPath =======================================
142
143/// ntex extractor that validates **URL path parameters**.
144///
145/// Drop-in replacement for `ntex::web::types::Path<T>`.
146///
147/// Path segment values come percent-decoded from ntex's router (`%2F`,
148/// `%25`, `%2B` included) and are coerced the same way as query parameters.
149pub struct VldPath<T>(pub T);
150
151impl<T: VldParse> VldPath<T> {
152    pub(super) async fn extract(
153        req: &HttpRequest,
154        _payload: &mut Payload,
155    ) -> Result<Self, VldNtexError> {
156        validate(&path_params_to_json(req.match_info().iter())).map(VldPath)
157    }
158}
159
160// ============================= VldForm =======================================
161
162/// ntex extractor that validates **URL-encoded form bodies**
163/// (`application/x-www-form-urlencoded`).
164///
165/// Drop-in replacement for `ntex::web::types::Form<T>`.
166///
167/// Values are parsed the same way as query parameters.
168pub struct VldForm<T>(pub T);
169
170impl<T: VldParse> VldForm<T> {
171    pub(super) async fn extract(
172        req: &HttpRequest,
173        payload: &mut Payload,
174    ) -> Result<Self, VldNtexError> {
175        require_form_content_type(content_type(req))?;
176        let body = read_body(req, payload).await?;
177        validate(&parse_form_body(&body)?).map(VldForm)
178    }
179}
180
181// ============================= VldHeaders ====================================
182
183/// ntex extractor that validates **HTTP headers**.
184///
185/// See [`crate::common::headers_to_json`]: names become snake_case
186/// (`X-Request-Id` → `x_request_id`), names containing `_` are ignored,
187/// repeated headers are joined with `", "`.
188pub struct VldHeaders<T>(pub T);
189
190impl<T: VldParse> VldHeaders<T> {
191    pub(super) async fn extract(
192        req: &HttpRequest,
193        _payload: &mut Payload,
194    ) -> Result<Self, VldNtexError> {
195        let value = headers_to_json(
196            req.headers()
197                .iter()
198                .map(|(n, v)| (n.as_str(), v.as_bytes())),
199        );
200        validate(&value).map(VldHeaders)
201    }
202}
203
204// ============================= VldCookie =====================================
205
206/// ntex extractor that validates **cookie values** from the `Cookie`
207/// headers (all of them; the first occurrence of a name wins).
208///
209/// Cookie names are used as-is for schema field matching.
210/// Values are unquoted, percent-decoded and coerced.
211pub struct VldCookie<T>(pub T);
212
213impl<T: VldParse> VldCookie<T> {
214    pub(super) async fn extract(
215        req: &HttpRequest,
216        _payload: &mut Payload,
217    ) -> Result<Self, VldNtexError> {
218        let value =
219            cookie_headers_to_json(req.headers().get_all(header::COOKIE).map(|v| v.as_bytes()));
220        validate(&value).map(VldCookie)
221    }
222}
223
224crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
225
226/// Prelude — import everything you need.
227pub mod prelude {
228    pub use super::{
229        VldBodyLimit, VldCookie, VldForm, VldHeaders, VldJson, VldNtexError, VldPath, VldQuery,
230    };
231    pub use vld::prelude::*;
232}