use axum::body::Bytes;
use axum::extract::{FromRequest, Request};
use serde::de::DeserializeOwned;
use crate::problem::{Problem, ProblemResponse};
use crate::request_id::RequestIdExt;
pub use seiva_contract::{Validate, ValidationError};
#[derive(Debug, Clone, Copy)]
pub struct Valid<T>(pub T);
impl<T, S> FromRequest<S> for Valid<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
{
type Rejection = ProblemResponse;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let request_id = request.extensions().request_id();
let instance = request.uri().path().to_owned();
let bytes = Bytes::from_request(request, state).await.map_err(|error| {
let status = error.status();
Problem::new(status, status.canonical_reason().unwrap_or("Bad Request"))
.with_detail(error.body_text())
.with_instance(instance.clone())
.with_request_id_opt(request_id.clone())
})?;
let mut unknown_field: Option<String> = None;
let deserializer = &mut serde_json::Deserializer::from_slice(&bytes);
let value: T = serde_ignored::deserialize(deserializer, |path| {
if unknown_field.is_none() {
unknown_field = Some(path.to_string());
}
})
.map_err(|error| {
Problem::unprocessable_entity(format!("invalid JSON body: {error}"))
.with_instance(instance.clone())
.with_request_id_opt(request_id.clone())
})?;
if let Some(field) = unknown_field {
return Err(Problem::unprocessable_entity(format!(
"unknown field `{field}` is not accepted"
))
.with_instance(instance.clone())
.with_request_id_opt(request_id.clone())
.into());
}
value.validate().map_err(|error| {
Problem::unprocessable_entity(error.to_string())
.with_instance(instance)
.with_request_id_opt(request_id)
})?;
Ok(Valid(value))
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::StatusCode;
#[derive(Debug, serde::Deserialize)]
struct Dto {
name: String,
}
impl Validate for Dto {
fn validate(&self) -> Result<(), ValidationError> {
if self.name.is_empty() {
return Err(ValidationError::new("name must not be empty"));
}
Ok(())
}
}
async fn extract(json: &str) -> Result<Valid<Dto>, ProblemResponse> {
let request = Request::builder()
.uri("/v1/things")
.body(Body::from(json.to_owned()))
.unwrap();
Valid::<Dto>::from_request(request, &()).await
}
#[tokio::test]
async fn accepts_a_body_with_exactly_the_declared_fields() {
let valid = extract(r#"{"name":"widget"}"#)
.await
.expect("should accept");
assert_eq!(valid.0.name, "widget");
}
#[tokio::test]
async fn rejects_an_unknown_field_as_422_mass_assignment_guard() {
let err = extract(r#"{"name":"widget","is_admin":true}"#)
.await
.expect_err("unknown field must be rejected");
assert_eq!(err.0.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(err
.0
.detail
.as_deref()
.unwrap_or_default()
.contains("is_admin"));
}
#[tokio::test]
async fn still_runs_the_validate_check() {
let err = extract(r#"{"name":""}"#)
.await
.expect_err("empty name invalid");
assert_eq!(err.0.status, StatusCode::UNPROCESSABLE_ENTITY);
}
}