1pub use axum_problem_derive::AxumProblem;
61
62use axum::response::{IntoResponse, Response};
63use http::{header, StatusCode};
64use serde::Serialize;
65
66#[derive(Debug, Clone, Serialize)]
97pub struct Problem {
98 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
100 pub problem_type: Option<String>,
101
102 pub title: String,
104
105 pub status: u16,
107
108 #[serde(skip_serializing_if = "Option::is_none")]
110 pub detail: Option<String>,
111
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub instance: Option<String>,
115
116 #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
120 pub extensions: serde_json::Map<String, serde_json::Value>,
121}
122
123impl Problem {
124 pub fn new(status: u16) -> Self {
127 Self {
128 problem_type: None,
129 title: status_title(status).to_owned(),
130 status,
131 detail: None,
132 instance: None,
133 extensions: serde_json::Map::new(),
134 }
135 }
136
137 pub fn extension(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
148 self.extensions.insert(key.into(), value.into());
149 self
150 }
151
152 pub fn problem_type(mut self, t: impl Into<String>) -> Self {
154 self.problem_type = Some(t.into());
155 self
156 }
157
158 pub fn title(mut self, title: impl Into<String>) -> Self {
160 self.title = title.into();
161 self
162 }
163
164 pub fn detail(mut self, detail: impl Into<String>) -> Self {
166 self.detail = Some(detail.into());
167 self
168 }
169
170 pub fn instance(mut self, instance: impl Into<String>) -> Self {
172 self.instance = Some(instance.into());
173 self
174 }
175
176 pub fn bad_request() -> Self { Self::new(400) }
179 pub fn unauthorized() -> Self { Self::new(401) }
180 pub fn forbidden() -> Self { Self::new(403) }
181 pub fn not_found() -> Self { Self::new(404) }
182 pub fn method_not_allowed() -> Self { Self::new(405) }
183 pub fn conflict() -> Self { Self::new(409) }
184 pub fn unprocessable_entity() -> Self { Self::new(422) }
185 pub fn too_many_requests() -> Self { Self::new(429) }
186 pub fn internal_server_error() -> Self { Self::new(500) }
187 pub fn not_implemented() -> Self { Self::new(501) }
188 pub fn service_unavailable() -> Self { Self::new(503) }
189}
190
191impl IntoResponse for Problem {
192 fn into_response(self) -> Response {
193 let status = StatusCode::from_u16(self.status)
194 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
195
196 let mut serializable = self;
200 serializable.status = status.as_u16();
201
202 let body = serde_json::to_string(&serializable)
203 .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
204
205 (
206 status,
207 [(header::CONTENT_TYPE, "application/problem+json")],
208 body,
209 )
210 .into_response()
211 }
212}
213
214pub fn status_title(status: u16) -> &'static str {
216 match status {
217 400 => "Bad Request",
218 401 => "Unauthorized",
219 403 => "Forbidden",
220 404 => "Not Found",
221 405 => "Method Not Allowed",
222 408 => "Request Timeout",
223 409 => "Conflict",
224 410 => "Gone",
225 415 => "Unsupported Media Type",
226 422 => "Unprocessable Entity",
227 429 => "Too Many Requests",
228 500 => "Internal Server Error",
229 501 => "Not Implemented",
230 502 => "Bad Gateway",
231 503 => "Service Unavailable",
232 504 => "Gateway Timeout",
233 _ => "Error",
234 }
235}
236
237#[cfg(feature = "utoipa")]
240mod utoipa_impl {
241 use super::Problem;
242 use utoipa::openapi::{
243 ObjectBuilder, RefOr, Schema,
244 schema::{SchemaType, SchemaFormat, KnownFormat, AdditionalProperties},
245 };
246
247 impl<'__s> utoipa::ToSchema<'__s> for Problem {
248 fn schema() -> (&'__s str, RefOr<Schema>) {
249 (
250 "Problem",
251 RefOr::T(Schema::Object(
252 ObjectBuilder::new()
253 .description(Some("RFC 9457 problem details (application/problem+json)"))
254 .property(
255 "type",
256 ObjectBuilder::new()
257 .schema_type(SchemaType::String)
258 .description(Some("URI reference identifying the problem type"))
259 .build(),
260 )
261 .property(
262 "title",
263 ObjectBuilder::new()
264 .schema_type(SchemaType::String)
265 .description(Some("Short human-readable summary of the problem type"))
266 .build(),
267 )
268 .required("title")
269 .property(
270 "status",
271 ObjectBuilder::new()
272 .schema_type(SchemaType::Integer)
273 .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int32)))
274 .description(Some("HTTP status code"))
275 .build(),
276 )
277 .required("status")
278 .property(
279 "detail",
280 ObjectBuilder::new()
281 .schema_type(SchemaType::String)
282 .description(Some("Human-readable explanation specific to this occurrence"))
283 .build(),
284 )
285 .property(
286 "instance",
287 ObjectBuilder::new()
288 .schema_type(SchemaType::String)
289 .description(Some("URI identifying the specific occurrence of this problem"))
290 .build(),
291 )
292 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
294 .build(),
295 )),
296 )
297 }
298 }
299}
300
301#[derive(Clone, Copy, Default)]
324pub struct ProblemLayer;
325
326impl<S> tower_layer::Layer<S> for ProblemLayer {
327 type Service = ProblemService<S>;
328 fn layer(&self, inner: S) -> Self::Service {
329 ProblemService { inner }
330 }
331}
332
333#[derive(Clone)]
335pub struct ProblemService<S> {
336 inner: S,
337}
338
339impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
340where
341 S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
342 + Clone
343 + Send
344 + 'static,
345 S::Future: Send + 'static,
346 ReqBody: Send + 'static,
347{
348 type Response = axum::response::Response;
349 type Error = S::Error;
350 type Future = std::pin::Pin<
351 Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
352 >;
353
354 fn poll_ready(
355 &mut self,
356 cx: &mut std::task::Context<'_>,
357 ) -> std::task::Poll<Result<(), Self::Error>> {
358 self.inner.poll_ready(cx)
359 }
360
361 fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
362 use axum::response::IntoResponse;
363 let future = self.inner.call(req);
364 Box::pin(async move {
365 let resp = future.await?;
366 let status = resp.status();
367
368 if status.is_client_error() || status.is_server_error() {
369 let already_problem = resp
370 .headers()
371 .get(http::header::CONTENT_TYPE)
372 .and_then(|v| v.to_str().ok())
373 .map(|ct| ct.contains("application/problem+json"))
374 .unwrap_or(false);
375
376 if !already_problem {
377 let status_u16 = status.as_u16();
378 let body_bytes = axum::body::to_bytes(resp.into_body(), 4096)
384 .await
385 .unwrap_or_default();
386 let detail = std::str::from_utf8(&body_bytes)
387 .map(|s| s.trim())
388 .unwrap_or("")
389 .to_owned();
390 let problem = if detail.is_empty() {
391 Problem::new(status_u16)
392 } else {
393 Problem::new(status_u16).detail(detail)
394 };
395 return Ok(problem.into_response());
396 }
397 }
398
399 Ok(resp)
400 })
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use axum::body::to_bytes;
408
409 async fn body_string(resp: Response) -> String {
410 let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
411 String::from_utf8(bytes.to_vec()).unwrap()
412 }
413
414 #[tokio::test]
415 async fn problem_serializes_to_correct_json() {
416 let p = Problem::not_found().detail("order 1001 not found");
417 let resp = p.into_response();
418
419 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
420 assert_eq!(
421 resp.headers().get(header::CONTENT_TYPE).unwrap(),
422 "application/problem+json"
423 );
424
425 let body = body_string(resp).await;
426 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
427 assert_eq!(json["status"], 404);
428 assert_eq!(json["title"], "Not Found");
429 assert_eq!(json["detail"], "order 1001 not found");
430 }
431
432 #[tokio::test]
433 async fn problem_omits_optional_fields() {
434 let p = Problem::new(400);
435 let resp = p.into_response();
436 let body = body_string(resp).await;
437 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
438 assert!(json.get("detail").is_none());
439 assert!(json.get("instance").is_none());
440 assert!(json.get("type").is_none());
441 }
442
443 #[tokio::test]
444 async fn problem_with_type_uri() {
445 let p = Problem::new(422)
446 .problem_type("https://errors.example.com/validation-failed")
447 .detail("email is required");
448 let resp = p.into_response();
449 let body = body_string(resp).await;
450 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
451 assert_eq!(json["type"], "https://errors.example.com/validation-failed");
452 }
453
454 #[tokio::test]
455 async fn status_title_coverage() {
456 assert_eq!(status_title(404), "Not Found");
457 assert_eq!(status_title(500), "Internal Server Error");
458 assert_eq!(status_title(999), "Error");
459 }
460
461 #[tokio::test]
464 async fn extension_field_serialized_at_top_level() {
465 let p = Problem::new(422)
466 .detail("validation failed")
467 .extension("violations", serde_json::json!([
468 {"field": "email", "message": "invalid"}
469 ]));
470
471 let resp = p.into_response();
472 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
473 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
474
475 assert!(json.get("violations").is_some(), "violations must be a top-level field");
477 assert!(json.get("extensions").is_none(), "must not have a nested 'extensions' key");
478 assert_eq!(json["violations"][0]["field"], "email");
479 assert_eq!(json["status"], 422);
480 assert_eq!(json["detail"], "validation failed");
481 }
482
483 #[tokio::test]
484 async fn multiple_extensions_all_at_top_level() {
485 let p = Problem::new(400)
486 .extension("request_id", serde_json::json!("req-abc-123"))
487 .extension("correlation_id", serde_json::json!("corr-xyz"))
488 .extension("retry_after", serde_json::json!(30));
489
490 let resp = p.into_response();
491 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
492 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
493
494 assert_eq!(json["request_id"], "req-abc-123");
495 assert_eq!(json["correlation_id"], "corr-xyz");
496 assert_eq!(json["retry_after"], 30);
497 }
498
499 #[tokio::test]
500 async fn no_extensions_means_no_extra_fields() {
501 let p = Problem::new(404).detail("not found");
502 let resp = p.into_response();
503 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
504 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
505
506 let keys: Vec<&str> = json.as_object().unwrap().keys().map(|k| k.as_str()).collect();
508 for key in &keys {
509 assert!(
510 ["title", "status", "detail", "instance", "type"].contains(key),
511 "unexpected extra key in response: {key}"
512 );
513 }
514 }
515
516 #[tokio::test]
517 async fn extension_is_valid_rfc9457_json() {
518 let p = Problem::new(400)
519 .extension("errors", serde_json::json!({"count": 3}));
520 let resp = p.into_response();
521 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
522 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
523
524 assert!(json["title"].is_string());
526 assert_eq!(json["status"], 400);
527 assert_eq!(json["errors"]["count"], 3);
529 }
530
531 use axum::{Router, routing::get, body::Body};
534 use tower::ServiceExt;
535
536 async fn handler_404() -> impl axum::response::IntoResponse {
537 (http::StatusCode::NOT_FOUND, "plain text 404")
538 }
539
540 async fn handler_200() -> impl axum::response::IntoResponse {
541 "ok"
542 }
543
544 async fn handler_problem() -> impl axum::response::IntoResponse {
545 Problem::not_found().detail("already a problem")
546 }
547
548 fn layered_app() -> Router {
549 Router::new()
550 .route("/notfound", get(handler_404))
551 .route("/ok", get(handler_200))
552 .route("/problem", get(handler_problem))
553 .layer(ProblemLayer)
554 }
555
556 async fn call(app: &Router, uri: &str) -> axum::response::Response {
557 app.clone()
558 .oneshot(
559 http::Request::builder()
560 .uri(uri)
561 .body(Body::empty())
562 .unwrap(),
563 )
564 .await
565 .unwrap()
566 }
567
568 #[tokio::test]
569 async fn problem_layer_converts_plain_404_to_problem_json() {
570 let app = layered_app();
571 let resp = call(&app, "/notfound").await;
572
573 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
574 assert_eq!(
575 resp.headers().get(header::CONTENT_TYPE).unwrap(),
576 "application/problem+json"
577 );
578
579 let body = body_string(resp).await;
580 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
581 assert_eq!(json["status"], 404);
582 assert_eq!(json["title"], "Not Found");
583 assert_eq!(json["detail"], "plain text 404");
585 }
586
587 #[tokio::test]
588 async fn problem_layer_preserves_empty_body_without_detail() {
589 async fn handler_empty_404() -> impl axum::response::IntoResponse {
590 http::StatusCode::NOT_FOUND
591 }
592
593 let app = Router::new()
594 .route("/empty", get(handler_empty_404))
595 .layer(ProblemLayer);
596
597 let resp = call(&app, "/empty").await;
598 let body = body_string(resp).await;
599 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
600 assert_eq!(json["status"], 404);
601 assert!(json.get("detail").is_none(), "empty body must not produce a detail field");
603 }
604
605 #[tokio::test]
606 async fn problem_layer_passes_through_2xx() {
607 let app = layered_app();
608 let resp = call(&app, "/ok").await;
609 assert_eq!(resp.status(), http::StatusCode::OK);
610 let ct = resp.headers()
612 .get(header::CONTENT_TYPE)
613 .and_then(|v| v.to_str().ok())
614 .unwrap_or("");
615 assert!(!ct.contains("application/problem+json"));
616 }
617
618 #[tokio::test]
619 async fn problem_layer_passes_through_existing_problem_json() {
620 let app = layered_app();
621 let resp = call(&app, "/problem").await;
622
623 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
624 assert_eq!(
625 resp.headers().get(header::CONTENT_TYPE).unwrap(),
626 "application/problem+json"
627 );
628
629 let body = body_string(resp).await;
631 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
632 assert_eq!(json["detail"], "already a problem");
633 }
634
635 #[tokio::test]
636 async fn problem_layer_converts_axum_json_extractor_error() {
637 use axum::extract::Json;
640
641 async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
642
643 let app = Router::new()
644 .route("/json", axum::routing::post(needs_json))
645 .layer(ProblemLayer);
646
647 let resp = app
648 .oneshot(
649 http::Request::builder()
650 .method("POST")
651 .uri("/json")
652 .header("content-type", "application/json")
653 .body(Body::from("not valid json {{"))
654 .unwrap(),
655 )
656 .await
657 .unwrap();
658
659 assert!(resp.status().is_client_error());
660 assert_eq!(
661 resp.headers().get(header::CONTENT_TYPE).unwrap(),
662 "application/problem+json",
663 "axum extractor error must be converted to problem+json by ProblemLayer"
664 );
665
666 let body = body_string(resp).await;
667 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
668 assert!(json["status"].as_u64().unwrap() >= 400);
669 assert!(json["title"].is_string());
670 }
671}