use std::fmt;
use axum::{
Json,
body::Body,
extract::{FromRequest, rejection::JsonRejection},
http::Request,
};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use thiserror::Error;
use crate::http::{ApiProblem, IntoApiProblem, ProblemCode, RequestContext};
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
const DEFAULT_VALIDATION_CODE: &str = "validation_failed";
const DEFAULT_VALIDATION_MESSAGE: &str = "request validation failed";
const DEFAULT_VALIDATION_FIELD: &str = "request";
pub trait Validate {
fn validate(&self) -> Result<(), ValidationError>;
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct FieldViolation {
field: String,
code: String,
message: String,
}
impl fmt::Debug for FieldViolation {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("FieldViolation")
.field("field", &self.field)
.field("code", &self.code)
.field("message", &"[REDACTED]")
.finish()
}
}
impl FieldViolation {
#[must_use]
pub fn new(
field: impl Into<String>,
code: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self {
field: normalize_with_default(field, DEFAULT_VALIDATION_FIELD),
code: normalize_with_default(code, DEFAULT_VALIDATION_CODE),
message: normalize_with_default(message, DEFAULT_VALIDATION_MESSAGE),
}
}
#[must_use]
pub fn field(&self) -> &str {
&self.field
}
#[must_use]
pub fn code(&self) -> &str {
&self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct FieldViolations {
violations: Vec<FieldViolation>,
}
impl FieldViolations {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_vec(violations: Vec<FieldViolation>) -> Self {
Self { violations }
}
pub fn push(&mut self, violation: FieldViolation) {
self.violations.push(violation);
}
#[must_use]
pub fn with(mut self, violation: FieldViolation) -> Self {
self.violations.push(violation);
self
}
pub fn add(
&mut self,
field: impl Into<String>,
code: impl Into<String>,
message: impl Into<String>,
) -> &mut Self {
self.violations
.push(FieldViolation::new(field, code, message));
self
}
#[must_use]
pub fn len(&self) -> usize {
self.violations.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.violations.is_empty()
}
#[must_use]
pub fn as_slice(&self) -> &[FieldViolation] {
&self.violations
}
pub fn iter(&self) -> impl Iterator<Item = &FieldViolation> {
self.violations.iter()
}
#[must_use]
pub fn into_vec(self) -> Vec<FieldViolation> {
self.violations
}
#[must_use]
pub fn into_validation_error(self) -> ValidationError {
ValidationError::new(
ErrorCode::internal("validation_failed"),
"request validation failed",
)
.with_details(json!({ "fields": self.violations }))
}
}
impl FromIterator<FieldViolation> for FieldViolations {
fn from_iter<T: IntoIterator<Item = FieldViolation>>(iter: T) -> Self {
Self::from_vec(iter.into_iter().collect())
}
}
impl IntoIterator for FieldViolations {
type Item = FieldViolation;
type IntoIter = std::vec::IntoIter<FieldViolation>;
fn into_iter(self) -> Self::IntoIter {
self.violations.into_iter()
}
}
#[derive(Clone, Error)]
#[error("request validation failed ({code})")]
pub struct ValidationError {
code: ErrorCode,
message: String,
details: Option<Value>,
}
impl fmt::Debug for ValidationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ValidationError")
.field("code", &self.code)
.field("message", &"[REDACTED]")
.field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
impl ValidationError {
#[must_use]
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: normalize_with_default(message, DEFAULT_VALIDATION_MESSAGE),
details: None,
}
}
#[must_use]
pub fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
}
#[must_use]
pub const fn code(&self) -> &ErrorCode {
&self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub const fn details(&self) -> Option<&Value> {
self.details.as_ref()
}
}
impl From<FieldViolations> for ValidationError {
fn from(value: FieldViolations) -> Self {
value.into_validation_error()
}
}
impl ClassifyError for ValidationError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
self.code.clone()
}
}
impl IntoApiProblem for ValidationError {
fn into_api_problem(self) -> ApiProblem {
validation_error_to_problem(self)
}
}
#[derive(Clone)]
pub struct ValidatedJson<T>(T);
impl<T> fmt::Debug for ValidatedJson<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("ValidatedJson")
.field(&"[REDACTED]")
.finish()
}
}
impl<T> ValidatedJson<T> {
pub fn new(value: T) -> Result<Self, ValidationError>
where
T: Validate,
{
value.validate()?;
Ok(Self(value))
}
#[must_use]
pub const fn get(&self) -> &T {
&self.0
}
#[must_use]
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> AsRef<T> for ValidatedJson<T> {
fn as_ref(&self) -> &T {
self.get()
}
}
impl<T> std::ops::Deref for ValidatedJson<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.get()
}
}
impl<S, T> FromRequest<S> for ValidatedJson<T>
where
S: Send + Sync,
T: DeserializeOwned + Validate,
{
type Rejection = ApiProblem;
async fn from_request(request: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
let context = request
.extensions()
.get::<RequestContext>()
.cloned()
.unwrap_or_else(|| RequestContext::from_headers(request.headers()));
let Json(value) = Json::<T>::from_request(request, state)
.await
.map_err(|rejection| {
json_rejection_to_problem(rejection).with_request_context(&context)
})?;
value
.validate()
.map_err(|error| validation_error_to_problem(error).with_request_context(&context))?;
Ok(Self(value))
}
}
fn json_rejection_to_problem(rejection: JsonRejection) -> ApiProblem {
let status = rejection.status();
let code = match status {
axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE => ProblemCode::UNSUPPORTED_MEDIA_TYPE,
axum::http::StatusCode::PAYLOAD_TOO_LARGE => ProblemCode::PAYLOAD_TOO_LARGE,
_ => ProblemCode::INVALID_JSON,
};
let detail = rejection.body_text();
let problem = ApiProblem::try_new(status, code.clone(), detail.clone())
.unwrap_or_else(|_| ApiProblem::bad_request(code, detail));
problem.with_details(json!({
"reason": rejection.to_string(),
}))
}
fn validation_error_to_problem(error: ValidationError) -> ApiProblem {
let mut problem =
ApiProblem::unprocessable_entity(ProblemCode::from_error_code(error.code), error.message);
if let Some(details) = error.details {
problem = problem.with_details(details);
}
problem
}
fn normalize(value: impl Into<String>) -> String {
value.into().trim().to_owned()
}
fn normalize_with_default(value: impl Into<String>, default: &str) -> String {
let value = normalize(value);
if value.is_empty() {
default.to_owned()
} else {
value
}
}
#[cfg(test)]
mod tests {
use serde::Serialize;
use serde_json::json;
use super::{FieldViolation, FieldViolations, Validate, ValidatedJson, ValidationError};
use crate::result::{ClassifyError, ErrorKind};
#[derive(Debug, Serialize)]
struct Payload {
name: String,
}
impl Validate for Payload {
fn validate(&self) -> Result<(), ValidationError> {
if self.name.trim().is_empty() {
Err(ValidationError::new(
crate::result::ErrorCode::internal("invalid_name"),
"name is required",
))
} else {
Ok(())
}
}
}
#[test]
fn normalizes_field_violations() {
let violation = FieldViolation::new(" name ", "", "");
assert_eq!(violation.field(), "name");
assert_eq!(violation.code(), "validation_failed");
assert_eq!(violation.message(), "request validation failed");
}
#[test]
fn field_violation_uses_stable_field_fallback() {
let violation = FieldViolation::new(" ", "required", "is required");
assert_eq!(violation.field(), "request");
assert_eq!(violation.code(), "required");
assert_eq!(violation.message(), "is required");
}
#[test]
fn validation_errors_are_classified() {
let error = ValidationError::new(
crate::result::ErrorCode::internal("invalid_payload"),
"payload is invalid",
);
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "invalid_payload");
}
#[test]
fn validation_debug_redacts_messages_details_and_json_payloads() {
let message = "private-validation-message";
let detail = "private-validation-detail";
let error = ValidationError::new(
crate::result::ErrorCode::internal("invalid_payload"),
message,
)
.with_details(json!({ "credential": detail }));
let validated = ValidatedJson(Payload {
name: "private-json-payload".to_owned(),
});
let violation = FieldViolation::new("credential", "invalid", message);
let output = format!("{error:?} {error} {validated:?} {violation:?}");
assert!(output.contains("invalid_payload"));
assert!(output.contains("[REDACTED]"));
for sensitive in [message, detail, "private-json-payload"] {
assert!(!output.contains(sensitive));
}
assert_eq!(error.message(), message);
assert_eq!(error.details(), Some(&json!({ "credential": detail })));
}
#[test]
fn serializes_private_field_violations() {
let violations = FieldViolations::new().with(FieldViolation::new(
"name",
"required",
"name is required",
));
assert_eq!(
serde_json::to_value(violations).expect("violations should serialize"),
json!([{ "field": "name", "code": "required", "message": "name is required" }])
);
}
#[test]
fn validated_json_constructor_runs_validation() {
assert!(
ValidatedJson::new(Payload {
name: "example".into()
})
.is_ok()
);
assert!(ValidatedJson::new(Payload { name: " ".into() }).is_err());
}
}