Skip to main content

vld_web/rama/
layer.rs

1//! Rama [`Layer`] that validates JSON request bodies.
2
3use std::convert::Infallible;
4use std::fmt;
5use std::marker::PhantomData;
6
7use crate::common::{DEFAULT_BODY_LIMIT, is_json_content_type, parse_json_body};
8use rama::extensions::{Extension, ExtensionsRef};
9use rama::http::body::util::BodyExt;
10use rama::http::header;
11use rama::http::{Body, Request, Response};
12use rama::{Layer, Service};
13use vld::schema::VldParse;
14
15use crate::rama::rejection::VldRejection;
16
17/// Wrapper stored in Rama [`Extensions`](rama::extensions::Extensions) so
18/// validated values do not require a manual `Extension` impl on `T`.
19#[derive(Clone)]
20pub struct Validated<T>(pub T);
21
22impl<T: fmt::Debug> fmt::Debug for Validated<T> {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.debug_tuple("Validated").field(&self.0).finish()
25    }
26}
27
28impl<T> std::ops::Deref for Validated<T> {
29    type Target = T;
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<T: fmt::Debug + Send + Sync + 'static> Extension for Validated<T> {}
36
37/// A Rama [`Layer`] that validates JSON request bodies with `vld`.
38///
39/// On success inserts [`Validated<T>`] into request extensions and forwards
40/// the original body bytes. On failure returns `422` (`413` when the body
41/// exceeds the limit) without calling the inner service.
42///
43/// Requests whose `Content-Type` is not JSON (`application/json` or
44/// `application/*+json`) are passed through **untouched** — their body is
45/// not read, so use [`validated`] (which returns `Option`) in handlers.
46#[derive(Clone)]
47pub struct ValidateJsonLayer<T> {
48    limit: usize,
49    _marker: PhantomData<fn() -> T>,
50}
51
52impl<T> ValidateJsonLayer<T> {
53    /// Create a new validation layer with the default body limit
54    /// ([`DEFAULT_BODY_LIMIT`], 2 MiB).
55    #[must_use]
56    pub fn new() -> Self {
57        Self::with_limit(DEFAULT_BODY_LIMIT)
58    }
59
60    /// Create a new validation layer with a custom body limit in bytes.
61    #[must_use]
62    pub fn with_limit(limit: usize) -> Self {
63        Self {
64            limit,
65            _marker: PhantomData,
66        }
67    }
68}
69
70impl<T> Default for ValidateJsonLayer<T> {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76impl<S, T> Layer<S> for ValidateJsonLayer<T> {
77    type Service = ValidateJsonService<S, T>;
78
79    fn layer(&self, inner: S) -> Self::Service {
80        ValidateJsonService {
81            inner,
82            limit: self.limit,
83            _marker: PhantomData,
84        }
85    }
86}
87
88/// Service produced by [`ValidateJsonLayer`].
89#[derive(Clone)]
90pub struct ValidateJsonService<S, T> {
91    inner: S,
92    limit: usize,
93    _marker: PhantomData<fn() -> T>,
94}
95
96impl<S, T> Service<Request> for ValidateJsonService<S, T>
97where
98    S: Service<Request, Output = Response, Error = Infallible>,
99    T: VldParse + Clone + fmt::Debug + Send + Sync + 'static,
100{
101    type Output = Response;
102    type Error = Infallible;
103
104    async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
105        use rama::http::service::web::response::IntoResponse;
106
107        let is_json = req
108            .headers()
109            .get(header::CONTENT_TYPE)
110            .and_then(|v| v.to_str().ok())
111            .is_some_and(is_json_content_type);
112
113        if !is_json {
114            return self.inner.serve(req).await;
115        }
116
117        let (parts, body) = req.into_parts();
118        let bytes = match body.limited(self.limit).collect().await {
119            Ok(collected) => collected.to_bytes(),
120            Err(e) => return Ok(VldRejection::from_body_error(&e).into_response()),
121        };
122
123        let result = parse_json_body(&bytes)
124            .map_err(VldRejection::from)
125            .and_then(|v| T::vld_parse_value(&v).map_err(VldRejection::from_vld));
126
127        match result {
128            Ok(validated) => {
129                let new_req = Request::from_parts(parts, Body::from(bytes));
130                new_req.extensions().insert(Validated(validated));
131                self.inner.serve(new_req).await
132            }
133            Err(rejection) => Ok(rejection.into_response()),
134        }
135    }
136}
137
138/// Extract the validated value from request extensions.
139///
140/// Returns `None` when the request was not validated — [`ValidateJsonLayer`]
141/// was not applied, the type does not match, or the request was not JSON.
142#[must_use]
143pub fn validated<T: Clone + fmt::Debug + Send + Sync + 'static>(req: &Request) -> Option<T> {
144    req.extensions()
145        .get_ref::<Validated<T>>()
146        .map(|v| v.0.clone())
147}