pub use axum_problem_derive::AxumProblem;
use axum::response::{IntoResponse, Response};
use http::{header, StatusCode};
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Problem {
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub problem_type: Option<String>,
pub title: String,
pub status: u16,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
}
impl Problem {
pub fn new(status: u16) -> Self {
Self {
problem_type: None,
title: status_title(status).to_owned(),
status,
detail: None,
instance: None,
}
}
pub fn problem_type(mut self, t: impl Into<String>) -> Self {
self.problem_type = Some(t.into());
self
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into());
self
}
pub fn bad_request() -> Self { Self::new(400) }
pub fn unauthorized() -> Self { Self::new(401) }
pub fn forbidden() -> Self { Self::new(403) }
pub fn not_found() -> Self { Self::new(404) }
pub fn method_not_allowed() -> Self { Self::new(405) }
pub fn conflict() -> Self { Self::new(409) }
pub fn unprocessable_entity() -> Self { Self::new(422) }
pub fn too_many_requests() -> Self { Self::new(429) }
pub fn internal_server_error() -> Self { Self::new(500) }
pub fn not_implemented() -> Self { Self::new(501) }
pub fn service_unavailable() -> Self { Self::new(503) }
}
impl IntoResponse for Problem {
fn into_response(self) -> Response {
let status = StatusCode::from_u16(self.status)
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let mut serializable = self;
serializable.status = status.as_u16();
let body = serde_json::to_string(&serializable)
.unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
(
status,
[(header::CONTENT_TYPE, "application/problem+json")],
body,
)
.into_response()
}
}
pub fn status_title(status: u16) -> &'static str {
match status {
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
415 => "Unsupported Media Type",
422 => "Unprocessable Entity",
429 => "Too Many Requests",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
_ => "Error",
}
}
#[derive(Clone, Copy, Default)]
pub struct ProblemLayer;
impl<S> tower_layer::Layer<S> for ProblemLayer {
type Service = ProblemService<S>;
fn layer(&self, inner: S) -> Self::Service {
ProblemService { inner }
}
}
#[derive(Clone)]
pub struct ProblemService<S> {
inner: S,
}
impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
where
S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
+ Clone
+ Send
+ 'static,
S::Future: Send + 'static,
ReqBody: Send + 'static,
{
type Response = axum::response::Response;
type Error = S::Error;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
>;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
use axum::response::IntoResponse;
let future = self.inner.call(req);
Box::pin(async move {
let resp = future.await?;
let status = resp.status();
if status.is_client_error() || status.is_server_error() {
let already_problem = resp
.headers()
.get(http::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|ct| ct.contains("application/problem+json"))
.unwrap_or(false);
if !already_problem {
return Ok(Problem::new(status.as_u16()).into_response());
}
}
Ok(resp)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::to_bytes;
async fn body_string(resp: Response) -> String {
let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn problem_serializes_to_correct_json() {
let p = Problem::not_found().detail("order 1001 not found");
let resp = p.into_response();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
"application/problem+json"
);
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["status"], 404);
assert_eq!(json["title"], "Not Found");
assert_eq!(json["detail"], "order 1001 not found");
}
#[tokio::test]
async fn problem_omits_optional_fields() {
let p = Problem::new(400);
let resp = p.into_response();
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert!(json.get("detail").is_none());
assert!(json.get("instance").is_none());
assert!(json.get("type").is_none());
}
#[tokio::test]
async fn problem_with_type_uri() {
let p = Problem::new(422)
.problem_type("https://errors.example.com/validation-failed")
.detail("email is required");
let resp = p.into_response();
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["type"], "https://errors.example.com/validation-failed");
}
#[tokio::test]
async fn status_title_coverage() {
assert_eq!(status_title(404), "Not Found");
assert_eq!(status_title(500), "Internal Server Error");
assert_eq!(status_title(999), "Error");
}
use axum::{Router, routing::get, body::Body};
use tower::ServiceExt;
async fn handler_404() -> impl axum::response::IntoResponse {
(http::StatusCode::NOT_FOUND, "plain text 404")
}
async fn handler_200() -> impl axum::response::IntoResponse {
"ok"
}
async fn handler_problem() -> impl axum::response::IntoResponse {
Problem::not_found().detail("already a problem")
}
fn layered_app() -> Router {
Router::new()
.route("/notfound", get(handler_404))
.route("/ok", get(handler_200))
.route("/problem", get(handler_problem))
.layer(ProblemLayer)
}
async fn call(app: &Router, uri: &str) -> axum::response::Response {
app.clone()
.oneshot(
http::Request::builder()
.uri(uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn problem_layer_converts_plain_404_to_problem_json() {
let app = layered_app();
let resp = call(&app, "/notfound").await;
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
"application/problem+json"
);
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["status"], 404);
assert_eq!(json["title"], "Not Found");
}
#[tokio::test]
async fn problem_layer_passes_through_2xx() {
let app = layered_app();
let resp = call(&app, "/ok").await;
assert_eq!(resp.status(), http::StatusCode::OK);
let ct = resp.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert!(!ct.contains("application/problem+json"));
}
#[tokio::test]
async fn problem_layer_passes_through_existing_problem_json() {
let app = layered_app();
let resp = call(&app, "/problem").await;
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
"application/problem+json"
);
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["detail"], "already a problem");
}
#[tokio::test]
async fn problem_layer_converts_axum_json_extractor_error() {
use axum::extract::Json;
async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
let app = Router::new()
.route("/json", axum::routing::post(needs_json))
.layer(ProblemLayer);
let resp = app
.oneshot(
http::Request::builder()
.method("POST")
.uri("/json")
.header("content-type", "application/json")
.body(Body::from("not valid json {{"))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status().is_client_error());
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
"application/problem+json",
"axum extractor error must be converted to problem+json by ProblemLayer"
);
let body = body_string(resp).await;
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert!(json["status"].as_u64().unwrap() >= 400);
assert!(json["title"].is_string());
}
}