1use axum::body::Bytes;
10use axum::extract::{FromRequest, Request};
11use serde::de::DeserializeOwned;
12
13use crate::problem::{Problem, ProblemResponse};
14use crate::request_id::RequestIdExt;
15
16pub use seiva_contract::{Validate, ValidationError};
21
22#[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 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 let bytes = Bytes::from_request(request, state).await.map_err(|error| {
45 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 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 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}