Skip to main content

seiva_http/
valid.rs

1//! A typed, validated JSON body extractor.
2//!
3//! [`Valid<T>`] is the `Valid<Json<T>>`-style extractor: it reads the request
4//! body as JSON into `T`, then runs `T`'s [`Validate`] check. A parse failure or
5//! a validation failure both become a `422`
6//! [`Problem`]; otherwise the handler receives a value
7//! already known to be well-formed and valid.
8
9use axum::body::Bytes;
10use axum::extract::{FromRequest, Request};
11use serde::de::DeserializeOwned;
12
13use crate::problem::{Problem, ProblemResponse};
14use crate::request_id::RequestIdExt;
15
16// `Validate`/`ValidationError` are transport-neutral contract types: they moved to
17// `seiva-contract` so a module's `facade` validates without depending on this HTTP
18// crate (ADR 0003). Re-exported here, so `seiva_http::{Validate, ValidationError}`
19// and the `Valid<T>` extractor below are unchanged for every existing caller.
20pub use seiva_contract::{Validate, ValidationError};
21
22/// A request body that deserialized into `T` and passed `T`'s [`Validate`]
23/// check. Destructure it as `Valid(value)` in a handler.
24#[derive(Debug, Clone, Copy)]
25pub struct Valid<T>(pub T);
26
27impl<T, S> FromRequest<S> for Valid<T>
28where
29    T: DeserializeOwned + Validate,
30    S: Send + Sync,
31{
32    // The HTTP edge wrapper: a `Problem` built below is rendered through it. The
33    // `?` operator converts `Problem` into it via `From<Problem>`.
34    type Rejection = ProblemResponse;
35
36    async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
37        let request_id = request.extensions().request_id();
38        let instance = request.uri().path().to_owned();
39        // Use axum's `Bytes` extractor rather than `into_body()` + `to_bytes(_,
40        // usize::MAX)`: `Bytes` honours the router's `DefaultBodyLimit`, so an
41        // oversized body is rejected before it is buffered into memory (OWASP
42        // API4 — resource exhaustion). Reading with `usize::MAX` silently
43        // bypassed that limit for every generated write route.
44        let bytes = Bytes::from_request(request, state).await.map_err(|error| {
45            // Keep the rejection's own status (a limit breach is `413 Payload Too
46            // Large`, a read failure `400`); the body text is axum's fixed,
47            // non-sensitive message. The title tracks the status.
48            let status = error.status();
49            Problem::new(status, status.canonical_reason().unwrap_or("Bad Request"))
50                .with_detail(error.body_text())
51                .with_instance(instance.clone())
52                .with_request_id_opt(request_id.clone())
53        })?;
54
55        // Reject unknown fields (OWASP API6 — mass assignment): a body carrying
56        // keys the DTO does not declare is refused instead of silently dropped,
57        // so a client cannot smuggle server-controlled fields (`role`, `tenant`,
58        // `is_admin`) past a DTO that happens to omit `#[serde(deny_unknown_fields)]`.
59        // `serde_ignored` reports each key the DTO ignored; the first one fails
60        // the request. This holds for every DTO without touching the wire shape
61        // of valid requests.
62        let mut unknown_field: Option<String> = None;
63        let deserializer = &mut serde_json::Deserializer::from_slice(&bytes);
64        let value: T = serde_ignored::deserialize(deserializer, |path| {
65            if unknown_field.is_none() {
66                unknown_field = Some(path.to_string());
67            }
68        })
69        .map_err(|error| {
70            Problem::unprocessable_entity(format!("invalid JSON body: {error}"))
71                .with_instance(instance.clone())
72                .with_request_id_opt(request_id.clone())
73        })?;
74
75        if let Some(field) = unknown_field {
76            return Err(Problem::unprocessable_entity(format!(
77                "unknown field `{field}` is not accepted"
78            ))
79            .with_instance(instance.clone())
80            .with_request_id_opt(request_id.clone())
81            .into());
82        }
83
84        value.validate().map_err(|error| {
85            Problem::unprocessable_entity(error.to_string())
86                .with_instance(instance)
87                .with_request_id_opt(request_id)
88        })?;
89
90        Ok(Valid(value))
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use axum::body::Body;
98    use axum::http::StatusCode;
99
100    #[derive(Debug, serde::Deserialize)]
101    struct Dto {
102        name: String,
103    }
104
105    impl Validate for Dto {
106        fn validate(&self) -> Result<(), ValidationError> {
107            if self.name.is_empty() {
108                return Err(ValidationError::new("name must not be empty"));
109            }
110            Ok(())
111        }
112    }
113
114    async fn extract(json: &str) -> Result<Valid<Dto>, ProblemResponse> {
115        let request = Request::builder()
116            .uri("/v1/things")
117            .body(Body::from(json.to_owned()))
118            .unwrap();
119        Valid::<Dto>::from_request(request, &()).await
120    }
121
122    #[tokio::test]
123    async fn accepts_a_body_with_exactly_the_declared_fields() {
124        let valid = extract(r#"{"name":"widget"}"#)
125            .await
126            .expect("should accept");
127        assert_eq!(valid.0.name, "widget");
128    }
129
130    #[tokio::test]
131    async fn rejects_an_unknown_field_as_422_mass_assignment_guard() {
132        // A client smuggling a server-controlled field the DTO does not declare is
133        // refused, not silently dropped (OWASP API6).
134        let err = extract(r#"{"name":"widget","is_admin":true}"#)
135            .await
136            .expect_err("unknown field must be rejected");
137        assert_eq!(err.0.status, StatusCode::UNPROCESSABLE_ENTITY);
138        assert!(err
139            .0
140            .detail
141            .as_deref()
142            .unwrap_or_default()
143            .contains("is_admin"));
144    }
145
146    #[tokio::test]
147    async fn still_runs_the_validate_check() {
148        let err = extract(r#"{"name":""}"#)
149            .await
150            .expect_err("empty name invalid");
151        assert_eq!(err.0.status, StatusCode::UNPROCESSABLE_ENTITY);
152    }
153}