use std::fmt;
use axum::{Json, body::Body, extract::FromRequest, http::Request};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use thiserror::Error;
use crate::http::{ApiProblem, 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)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
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(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<Vec<FieldViolation>> for ValidationError {
fn from(violations: Vec<FieldViolation>) -> Self {
Self::new(
ErrorCode::internal(DEFAULT_VALIDATION_CODE),
DEFAULT_VALIDATION_MESSAGE,
)
.with_details(json!({ "fields": violations }))
}
}
impl ClassifyError for ValidationError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
self.code.clone()
}
}
impl From<ValidationError> for ApiProblem {
fn from(error: ValidationError) -> Self {
let mut problem =
Self::unprocessable_entity(ProblemCode::from_error_code(error.code), error.message);
if let Some(details) = error.details {
problem = problem.with_details(details);
}
problem
}
}
#[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(mut request: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
let context = request
.extensions_mut()
.remove::<RequestContext>()
.unwrap_or_else(|| RequestContext::from_headers(request.headers()));
let Json(value) = Json::<T>::from_request(request, state)
.await
.map_err(|rejection| ApiProblem::from(rejection).with_request_context(&context))?;
Self::new(value).map_err(|error| ApiProblem::from(error).with_request_context(&context))
}
}
fn normalize_with_default(value: impl Into<String>, default: &str) -> String {
let value = value.into().trim().to_owned();
if value.is_empty() {
default.to_owned()
} else {
value
}
}
#[cfg(test)]
mod tests {
use axum::{
Router,
body::{Body, to_bytes},
extract::DefaultBodyLimit,
http::{Request, StatusCode, header::CONTENT_TYPE},
routing::post,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tower::ServiceExt;
use super::{FieldViolation, Validate, ValidatedJson, ValidationError};
use crate::result::{ClassifyError, ErrorKind};
#[derive(Debug, Deserialize, 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 = vec![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" }])
);
for fields in [violations, vec![]] {
let expected_details = json!({ "fields": fields });
let error = ValidationError::from(fields);
assert_eq!(error.code().as_str(), "validation_failed");
assert_eq!(error.message(), "request validation failed");
assert_eq!(error.details(), Some(&expected_details));
let problem = crate::http::ApiProblem::from(error);
assert_eq!(problem.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(problem.body().code(), "validation_failed");
assert_eq!(problem.body().detail(), "request validation failed");
assert_eq!(problem.body().details(), Some(&expected_details));
}
}
#[test]
fn validated_json_constructor_runs_validation() {
assert!(
ValidatedJson::new(Payload {
name: "example".into()
})
.is_ok()
);
assert!(ValidatedJson::new(Payload { name: " ".into() }).is_err());
}
#[tokio::test]
async fn validated_json_preserves_rejection_status_and_request_context() {
let app = Router::new()
.route(
"/",
post(|_: ValidatedJson<Payload>| async { StatusCode::NO_CONTENT }),
)
.layer(DefaultBodyLimit::max(64));
let json = Some("application/json");
for (body, content_type, status, code) in [
("{}", None, 415, "unsupported_media_type"),
(r#"{"name":"#, json, 400, "invalid_json"),
(r#"{"name":1}"#, json, 422, "invalid_json"),
(&"x".repeat(65), json, 413, "payload_too_large"),
(r#"{"name":" "}"#, json, 422, "invalid_name"),
] {
let mut request = Request::builder()
.uri("/")
.method("POST")
.header("x-request-id", "req_json");
if let Some(content_type) = content_type {
request = request.header(CONTENT_TYPE, content_type);
}
let response = app
.clone()
.oneshot(request.body(Body::from(body.to_owned())).unwrap())
.await
.unwrap();
assert_eq!(response.status().as_u16(), status);
assert_eq!(response.headers()[CONTENT_TYPE], "application/problem+json");
let body = to_bytes(response.into_body(), 4096).await.unwrap();
let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(problem["status"], status);
assert_eq!(problem["code"], code);
assert_eq!(problem["request_id"], "req_json");
assert!(!problem["detail"].as_str().unwrap().is_empty());
if code != "invalid_name" {
assert!(!problem["details"]["reason"].as_str().unwrap().is_empty());
}
}
}
}