vld_web/tower.rs
1//! # `vld_web::tower` — Tower middleware for `vld`
2//!
3//! A [`tower::Layer`](tower_layer::Layer) that validates JSON request bodies
4//! against a `vld` schema, for any Tower service over the [`http`] types: an
5//! Axum `Router` (see `examples/tower_axum.rs`), a hyper service via
6//! `hyper-util`'s `TowerToHyperService`, or a plain `service_fn`. It depends
7//! only on `tower-layer` / `tower-service` / `http`, not on a web framework.
8//!
9//! On **success** the validated value is stored in the request extensions as
10//! [`Validated<T>`] and the body bytes are forwarded. On **failure** a JSON
11//! error response is returned and the inner service is not called (see the
12//! [error body format](crate::common#error-bodies)):
13//!
14//! | Situation | Status |
15//! |---|---|
16//! | schema validation failed / malformed JSON / body read error | 422 |
17//! | body larger than the limit ([`ValidateJsonLayer::with_limit`], default 2 MiB) | 413 |
18//!
19//! Requests whose `Content-Type` is not JSON (`application/json` or
20//! `application/*+json`, case-insensitive) are passed through **untouched**
21//! (body not read), so [`validated`] returns `Option<T>`.
22//!
23//! The inner service receives `Request<`[`ValidatedBody<B>`]`>`: the buffered
24//! bytes for validated JSON requests, the original body otherwise. Responses
25//! are `Response<ValidatedBody<ResBody>>`: the error body or the inner
26//! service's. The layer never fails itself; its error type is the inner
27//! service's.
28//!
29//! # Example
30//!
31//! ```
32//! use bytes::Bytes;
33//! use http::{Request, Response, StatusCode};
34//! use http_body_util::Full;
35//! use tower::{ServiceBuilder, ServiceExt};
36//! use vld_web::tower::{validated, ValidateJsonLayer, ValidatedBody};
37//!
38//! vld::schema! {
39//! #[derive(Debug, Clone)]
40//! pub struct CreateUser {
41//! pub name: String => vld::string().min(2),
42//! pub email: String => vld::string().email(),
43//! }
44//! }
45//!
46//! async fn handler(
47//! req: Request<ValidatedBody<Full<Bytes>>>,
48//! ) -> Result<Response<Full<Bytes>>, std::convert::Infallible> {
49//! let name = validated::<CreateUser>(&req).map_or("not JSON".into(), |u| u.name);
50//! Ok(Response::new(Full::new(Bytes::from(name))))
51//! }
52//!
53//! # #[tokio::main]
54//! # async fn main() {
55//! let svc = ServiceBuilder::new()
56//! .layer(ValidateJsonLayer::<CreateUser>::new())
57//! .service_fn(handler);
58//!
59//! let req = Request::post("/users")
60//! .header("content-type", "application/json")
61//! .body(Full::new(Bytes::from(r#"{"name":"A","email":"bad"}"#)))
62//! .unwrap();
63//! let resp = svc.oneshot(req).await.unwrap();
64//! assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
65//! # }
66//! ```
67//!
68//! Guide: <https://s00d.github.io/vld/integrations/web/tower>
69use crate::common::{DEFAULT_BODY_LIMIT, VldHttpError, is_json_content_type, parse_json_body};
70use bytes::Bytes;
71use http::{Request, Response, StatusCode};
72use http_body::Body;
73use http_body_util::{BodyExt, Either, Full, LengthLimitError, Limited};
74use std::future::Future;
75use std::marker::PhantomData;
76use std::pin::Pin;
77use std::task::{Context, Poll};
78use vld::schema::VldParse;
79
80/// Body type seen by the inner service (`Left`: the buffered bytes of a
81/// validated JSON request, `Right`: the untouched original body of a
82/// non-JSON request) and returned by the layer (`Left`: a JSON error body,
83/// `Right`: the inner service's body).
84pub type ValidatedBody<B> = Either<Full<Bytes>, B>;
85
86/// The validated value, stored in the request extensions by
87/// [`ValidateJsonLayer`] (a wrapper, so it never collides with other
88/// extensions of type `T`).
89#[derive(Debug, Clone)]
90pub struct Validated<T>(pub T);
91
92impl<T> std::ops::Deref for Validated<T> {
93 type Target = T;
94 fn deref(&self) -> &T {
95 &self.0
96 }
97}
98
99// ---------------------------------------------------------------------------
100// Layer
101// ---------------------------------------------------------------------------
102
103/// A [`tower_layer::Layer`] that validates JSON request bodies with `vld`.
104///
105/// The type parameter `T` is the validated struct (must implement
106/// [`VldParse`] + [`Clone`] + [`Send`] + [`Sync`] + `'static`).
107///
108/// # Behaviour
109///
110/// 1. Non-JSON requests are forwarded untouched (body not read).
111/// 2. JSON bodies are read up to the limit (413 beyond it, 422 on a read
112/// error), parsed and validated via `T::vld_parse_value()`.
113/// 3. **Valid** — inserts [`Validated<T>`] into request extensions,
114/// re-attaches the body bytes, and calls the inner service.
115/// 4. **Invalid** — returns `422 Unprocessable Entity` (`413` when the body
116/// is over the limit) with a JSON error body. The inner service is **not**
117/// called.
118#[derive(Clone)]
119pub struct ValidateJsonLayer<T> {
120 limit: usize,
121 _marker: PhantomData<fn() -> T>,
122}
123
124impl<T> ValidateJsonLayer<T> {
125 /// Create a new validation layer with the default body limit
126 /// ([`DEFAULT_BODY_LIMIT`], 2 MiB).
127 pub fn new() -> Self {
128 Self::with_limit(DEFAULT_BODY_LIMIT)
129 }
130
131 /// Create a new validation layer with a custom body limit in bytes.
132 pub fn with_limit(limit: usize) -> Self {
133 Self {
134 limit,
135 _marker: PhantomData,
136 }
137 }
138}
139
140impl<T> Default for ValidateJsonLayer<T> {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl<S, T> tower_layer::Layer<S> for ValidateJsonLayer<T> {
147 type Service = ValidateJsonService<S, T>;
148
149 fn layer(&self, inner: S) -> Self::Service {
150 ValidateJsonService {
151 inner,
152 limit: self.limit,
153 _marker: PhantomData,
154 }
155 }
156}
157
158// ---------------------------------------------------------------------------
159// Service
160// ---------------------------------------------------------------------------
161
162/// The middleware [`Service`](tower_service::Service) created by
163/// [`ValidateJsonLayer`].
164#[derive(Clone)]
165pub struct ValidateJsonService<S, T> {
166 inner: S,
167 limit: usize,
168 _marker: PhantomData<fn() -> T>,
169}
170
171fn error_response<B>(err: VldHttpError) -> Response<ValidatedBody<B>> {
172 let mut resp = Response::new(Either::Left(Full::new(Bytes::from(err.body().to_string()))));
173 *resp.status_mut() =
174 StatusCode::from_u16(err.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY);
175 resp.headers_mut().insert(
176 http::header::CONTENT_TYPE,
177 http::HeaderValue::from_static("application/json"),
178 );
179 resp
180}
181
182/// 413 when the length limit was hit (anywhere in the source chain), else a
183/// 422 parse error.
184fn body_error(e: &(dyn std::error::Error + 'static)) -> VldHttpError {
185 if std::iter::successors(Some(e), |e| e.source()).any(|e| e.is::<LengthLimitError>()) {
186 VldHttpError::payload_too_large()
187 } else {
188 VldHttpError::parse(format!("Failed to read request body: {e}"))
189 }
190}
191
192impl<S, T, ReqBody, ResBody> tower_service::Service<Request<ReqBody>> for ValidateJsonService<S, T>
193where
194 S: tower_service::Service<Request<ValidatedBody<ReqBody>>, Response = Response<ResBody>>
195 + Clone
196 + Send
197 + 'static,
198 S::Future: Send + 'static,
199 S::Error: Send + 'static,
200 ReqBody: Body<Data = Bytes> + Send + 'static,
201 ReqBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
202 ResBody: Send + 'static,
203 T: VldParse + Clone + Send + Sync + 'static,
204{
205 type Response = Response<ValidatedBody<ResBody>>;
206 type Error = S::Error;
207 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
208
209 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
210 self.inner.poll_ready(cx)
211 }
212
213 fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
214 let mut inner = self.inner.clone();
215 // Swap so `self` is ready for next call (standard Tower pattern)
216 std::mem::swap(&mut self.inner, &mut inner);
217 let limit = self.limit;
218
219 Box::pin(async move {
220 let is_json = req
221 .headers()
222 .get(http::header::CONTENT_TYPE)
223 .and_then(|v| v.to_str().ok())
224 .is_some_and(is_json_content_type);
225
226 let (parts, body) = req.into_parts();
227
228 if !is_json {
229 let req = Request::from_parts(parts, Either::Right(body));
230 return Ok(inner.call(req).await?.map(Either::Right));
231 }
232
233 let bytes = match Limited::new(body, limit).collect().await {
234 Ok(collected) => collected.to_bytes(),
235 Err(e) => return Ok(error_response(body_error(&*e))),
236 };
237
238 let validated = match parse_json_body(&bytes)
239 .and_then(|v| T::vld_parse_value(&v).map_err(VldHttpError::validation))
240 {
241 Ok(v) => v,
242 Err(e) => return Ok(error_response(e)),
243 };
244
245 let mut req = Request::from_parts(parts, Either::Left(Full::new(bytes)));
246 req.extensions_mut().insert(Validated(validated));
247 Ok(inner.call(req).await?.map(Either::Right))
248 })
249 }
250}
251
252// ---------------------------------------------------------------------------
253// Helper: extract validated value from request extensions
254// ---------------------------------------------------------------------------
255
256/// Extract the validated value from request extensions.
257///
258/// Returns `None` when the request was not validated — the layer was not
259/// applied, the type does not match, or the request was not JSON (non-JSON
260/// requests are passed through without validation).
261pub fn validated<T: Clone + Send + Sync + 'static>(req: &Request<impl Body>) -> Option<T> {
262 req.extensions().get::<Validated<T>>().map(|v| v.0.clone())
263}
264
265/// Prelude — import everything you need.
266pub mod prelude {
267 pub use super::{ValidateJsonLayer, ValidateJsonService, Validated, ValidatedBody, validated};
268 pub use vld::prelude::*;
269}