Skip to main content

aurelin_framework/validation/
http.rs

1//! Safe JSON responses for validated Axum extractors.
2//!
3//! Use `Validated<Json<T>>`, `Validated<Form<T>>`, `Validated<Query<T>>`, or
4//! `Validated<Path<T>>`. Authorization must run in an outer route layer or in
5//! an earlier parts extractor; checks inside the handler run too late.
6//! These extractors always return JSON, irrespective of Accept or X-Inertia.
7//! They do not flash input or implement browser/Inertia redirects. For routes
8//! requiring authorization, apply authorization as an outer Axum route layer;
9//! authorizing in a handler after extraction does not protect validation.
10//!
11//! To customize a rejection, accept `Result<Validated<Json<T>>, ValidationResponse>`
12//! in the handler and call `with_safe_response` on the error. Supply only a
13//! message that is safe to expose publicly.
14
15use axum::{
16    Json,
17    extract::{FromRequest, FromRequestParts, Request},
18    http::{StatusCode, request::Parts},
19    response::{IntoResponse, Response},
20};
21use axum_valid::{HasValidate, Valid, ValidRejection};
22use serde::Serialize;
23use std::collections::BTreeMap;
24use validator::Validate;
25
26use super::{ValidationIssue, issues};
27
28/// An Axum extractor that rejects invalid inputs without invoking the handler.
29pub struct Validated<E>(pub E);
30
31impl<S, E> FromRequest<S> for Validated<E>
32where
33    S: Send + Sync,
34    E: HasValidate + FromRequest<S>,
35    E::Validate: Validate,
36{
37    type Rejection = ValidationResponse;
38
39    async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
40        Valid::<E>::from_request(request, state)
41            .await
42            .map(|valid| Self(valid.0))
43            .map_err(ValidationResponse::from_rejection)
44    }
45}
46
47impl<S, E> FromRequestParts<S> for Validated<E>
48where
49    S: Send + Sync,
50    E: HasValidate + FromRequestParts<S>,
51    E::Validate: Validate,
52{
53    type Rejection = ValidationResponse;
54
55    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
56        Valid::<E>::from_request_parts(parts, state)
57            .await
58            .map(|valid| Self(valid.0))
59            .map_err(ValidationResponse::from_rejection)
60    }
61}
62
63/// A safe validation or extraction failure, customizable at an explicit handler boundary.
64pub struct ValidationResponse {
65    status: StatusCode,
66    code: &'static str,
67    message: String,
68    issues: Vec<ValidationIssue>,
69}
70
71#[derive(Serialize)]
72struct RenderedIssue<'a> {
73    field: &'a str,
74    code: &'a str,
75    message: String,
76    arguments: &'a BTreeMap<String, serde_json::Value>,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    bag: &'a Option<String>,
79}
80
81#[derive(Serialize)]
82struct ErrorBody<'a> {
83    code: &'a str,
84    message: &'a str,
85    issues: Vec<RenderedIssue<'a>>,
86}
87
88impl ValidationResponse {
89    pub(super) fn from_rejection<E: IntoResponse>(rejection: ValidRejection<E>) -> Self {
90        match rejection {
91            ValidRejection::Valid(errors) => Self {
92                status: StatusCode::UNPROCESSABLE_ENTITY,
93                code: "validation_failed",
94                message: "The given data was invalid.".into(),
95                issues: issues(&errors, None),
96            },
97            ValidRejection::Inner(error) => {
98                let status = error.into_response().status();
99                let status = match status {
100                    StatusCode::UNSUPPORTED_MEDIA_TYPE => StatusCode::UNSUPPORTED_MEDIA_TYPE,
101                    StatusCode::PAYLOAD_TOO_LARGE => StatusCode::PAYLOAD_TOO_LARGE,
102                    status if status.is_server_error() => StatusCode::INTERNAL_SERVER_ERROR,
103                    _ => StatusCode::BAD_REQUEST,
104                };
105                Self {
106                    status,
107                    code: if status.is_server_error() { "internal_error" } else { "invalid_request" },
108                    message: if status.is_server_error() { "Server error." } else { "The request could not be read." }
109                        .into(),
110                    issues: Vec::new(),
111                }
112            }
113        }
114    }
115
116    /// Override status and message with application-owned, public-safe values.
117    pub fn with_safe_response(mut self, status: StatusCode, message: impl Into<String>) -> Self {
118        self.status = status;
119        self.message = message.into();
120        self
121    }
122
123    /// Replace issue messages with explicitly public-safe application text.
124    pub fn with_safe_issue_messages(mut self, message: impl Fn(&ValidationIssue) -> Option<String>) -> Self {
125        for issue in &mut self.issues {
126            if let Some(text) = message(issue) {
127                issue.descriptor = super::MessageDescriptor::Custom(text);
128            }
129        }
130        self
131    }
132}
133
134impl IntoResponse for ValidationResponse {
135    fn into_response(self) -> Response {
136        let rendered = self
137            .issues
138            .iter()
139            .map(|issue| RenderedIssue {
140                field: &issue.field,
141                code: &issue.code,
142                message: issue.render_message(),
143                arguments: &issue.arguments,
144                bag: &issue.bag,
145            })
146            .collect();
147        (self.status, Json(ErrorBody { code: self.code, message: &self.message, issues: rendered })).into_response()
148    }
149}