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 response::ResponseBuilder,
246 content::ContentBuilder,
247 };
248
249 impl<'__s> utoipa::ToSchema<'__s> for Problem {
250 fn schema() -> (&'__s str, RefOr<Schema>) {
251 (
252 "Problem",
253 RefOr::T(Schema::Object(
254 ObjectBuilder::new()
255 .description(Some("RFC 9457 problem details (application/problem+json)"))
256 .property(
257 "type",
258 ObjectBuilder::new()
259 .schema_type(SchemaType::String)
260 .description(Some("URI reference identifying the problem type"))
261 .build(),
262 )
263 .property(
264 "title",
265 ObjectBuilder::new()
266 .schema_type(SchemaType::String)
267 .description(Some("Short human-readable summary of the problem type"))
268 .build(),
269 )
270 .required("title")
271 .property(
272 "status",
273 ObjectBuilder::new()
274 .schema_type(SchemaType::Integer)
275 .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int32)))
276 .description(Some("HTTP status code"))
277 .build(),
278 )
279 .required("status")
280 .property(
281 "detail",
282 ObjectBuilder::new()
283 .schema_type(SchemaType::String)
284 .description(Some("Human-readable explanation specific to this occurrence"))
285 .build(),
286 )
287 .property(
288 "instance",
289 ObjectBuilder::new()
290 .schema_type(SchemaType::String)
291 .description(Some("URI identifying the specific occurrence of this problem"))
292 .build(),
293 )
294 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
296 .build(),
297 )),
298 )
299 }
300 }
301}
302
303#[derive(Clone, Copy, Default)]
326pub struct ProblemLayer;
327
328impl<S> tower_layer::Layer<S> for ProblemLayer {
329 type Service = ProblemService<S>;
330 fn layer(&self, inner: S) -> Self::Service {
331 ProblemService { inner }
332 }
333}
334
335#[derive(Clone)]
337pub struct ProblemService<S> {
338 inner: S,
339}
340
341impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
342where
343 S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
344 + Clone
345 + Send
346 + 'static,
347 S::Future: Send + 'static,
348 ReqBody: Send + 'static,
349{
350 type Response = axum::response::Response;
351 type Error = S::Error;
352 type Future = std::pin::Pin<
353 Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
354 >;
355
356 fn poll_ready(
357 &mut self,
358 cx: &mut std::task::Context<'_>,
359 ) -> std::task::Poll<Result<(), Self::Error>> {
360 self.inner.poll_ready(cx)
361 }
362
363 fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
364 use axum::response::IntoResponse;
365 let future = self.inner.call(req);
366 Box::pin(async move {
367 let resp = future.await?;
368 let status = resp.status();
369
370 if status.is_client_error() || status.is_server_error() {
371 let already_problem = resp
372 .headers()
373 .get(http::header::CONTENT_TYPE)
374 .and_then(|v| v.to_str().ok())
375 .map(|ct| ct.contains("application/problem+json"))
376 .unwrap_or(false);
377
378 if !already_problem {
379 let status_u16 = status.as_u16();
380 let body_bytes = axum::body::to_bytes(resp.into_body(), 4096)
386 .await
387 .unwrap_or_default();
388 let detail = std::str::from_utf8(&body_bytes)
389 .map(|s| s.trim())
390 .unwrap_or("")
391 .to_owned();
392 let problem = if detail.is_empty() {
393 Problem::new(status_u16)
394 } else {
395 Problem::new(status_u16).detail(detail)
396 };
397 return Ok(problem.into_response());
398 }
399 }
400
401 Ok(resp)
402 })
403 }
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409 use axum::body::to_bytes;
410
411 async fn body_string(resp: Response) -> String {
412 let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
413 String::from_utf8(bytes.to_vec()).unwrap()
414 }
415
416 #[tokio::test]
417 async fn problem_serializes_to_correct_json() {
418 let p = Problem::not_found().detail("order 1001 not found");
419 let resp = p.into_response();
420
421 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
422 assert_eq!(
423 resp.headers().get(header::CONTENT_TYPE).unwrap(),
424 "application/problem+json"
425 );
426
427 let body = body_string(resp).await;
428 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
429 assert_eq!(json["status"], 404);
430 assert_eq!(json["title"], "Not Found");
431 assert_eq!(json["detail"], "order 1001 not found");
432 }
433
434 #[tokio::test]
435 async fn problem_omits_optional_fields() {
436 let p = Problem::new(400);
437 let resp = p.into_response();
438 let body = body_string(resp).await;
439 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
440 assert!(json.get("detail").is_none());
441 assert!(json.get("instance").is_none());
442 assert!(json.get("type").is_none());
443 }
444
445 #[tokio::test]
446 async fn problem_with_type_uri() {
447 let p = Problem::new(422)
448 .problem_type("https://errors.example.com/validation-failed")
449 .detail("email is required");
450 let resp = p.into_response();
451 let body = body_string(resp).await;
452 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
453 assert_eq!(json["type"], "https://errors.example.com/validation-failed");
454 }
455
456 #[tokio::test]
457 async fn status_title_coverage() {
458 assert_eq!(status_title(404), "Not Found");
459 assert_eq!(status_title(500), "Internal Server Error");
460 assert_eq!(status_title(999), "Error");
461 }
462
463 #[tokio::test]
466 async fn extension_field_serialized_at_top_level() {
467 let p = Problem::new(422)
468 .detail("validation failed")
469 .extension("violations", serde_json::json!([
470 {"field": "email", "message": "invalid"}
471 ]));
472
473 let resp = p.into_response();
474 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
475 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
476
477 assert!(json.get("violations").is_some(), "violations must be a top-level field");
479 assert!(json.get("extensions").is_none(), "must not have a nested 'extensions' key");
480 assert_eq!(json["violations"][0]["field"], "email");
481 assert_eq!(json["status"], 422);
482 assert_eq!(json["detail"], "validation failed");
483 }
484
485 #[tokio::test]
486 async fn multiple_extensions_all_at_top_level() {
487 let p = Problem::new(400)
488 .extension("request_id", serde_json::json!("req-abc-123"))
489 .extension("correlation_id", serde_json::json!("corr-xyz"))
490 .extension("retry_after", serde_json::json!(30));
491
492 let resp = p.into_response();
493 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
494 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
495
496 assert_eq!(json["request_id"], "req-abc-123");
497 assert_eq!(json["correlation_id"], "corr-xyz");
498 assert_eq!(json["retry_after"], 30);
499 }
500
501 #[tokio::test]
502 async fn no_extensions_means_no_extra_fields() {
503 let p = Problem::new(404).detail("not found");
504 let resp = p.into_response();
505 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
506 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
507
508 let keys: Vec<&str> = json.as_object().unwrap().keys().map(|k| k.as_str()).collect();
510 for key in &keys {
511 assert!(
512 ["title", "status", "detail", "instance", "type"].contains(key),
513 "unexpected extra key in response: {key}"
514 );
515 }
516 }
517
518 #[tokio::test]
519 async fn extension_is_valid_rfc9457_json() {
520 let p = Problem::new(400)
521 .extension("errors", serde_json::json!({"count": 3}));
522 let resp = p.into_response();
523 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
524 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
525
526 assert!(json["title"].is_string());
528 assert_eq!(json["status"], 400);
529 assert_eq!(json["errors"]["count"], 3);
531 }
532
533 use axum::{Router, routing::get, body::Body};
536 use tower::ServiceExt;
537
538 async fn handler_404() -> impl axum::response::IntoResponse {
539 (http::StatusCode::NOT_FOUND, "plain text 404")
540 }
541
542 async fn handler_200() -> impl axum::response::IntoResponse {
543 "ok"
544 }
545
546 async fn handler_problem() -> impl axum::response::IntoResponse {
547 Problem::not_found().detail("already a problem")
548 }
549
550 fn layered_app() -> Router {
551 Router::new()
552 .route("/notfound", get(handler_404))
553 .route("/ok", get(handler_200))
554 .route("/problem", get(handler_problem))
555 .layer(ProblemLayer)
556 }
557
558 async fn call(app: &Router, uri: &str) -> axum::response::Response {
559 app.clone()
560 .oneshot(
561 http::Request::builder()
562 .uri(uri)
563 .body(Body::empty())
564 .unwrap(),
565 )
566 .await
567 .unwrap()
568 }
569
570 #[tokio::test]
571 async fn problem_layer_converts_plain_404_to_problem_json() {
572 let app = layered_app();
573 let resp = call(&app, "/notfound").await;
574
575 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
576 assert_eq!(
577 resp.headers().get(header::CONTENT_TYPE).unwrap(),
578 "application/problem+json"
579 );
580
581 let body = body_string(resp).await;
582 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
583 assert_eq!(json["status"], 404);
584 assert_eq!(json["title"], "Not Found");
585 assert_eq!(json["detail"], "plain text 404");
587 }
588
589 #[tokio::test]
590 async fn problem_layer_preserves_empty_body_without_detail() {
591 async fn handler_empty_404() -> impl axum::response::IntoResponse {
592 http::StatusCode::NOT_FOUND
593 }
594
595 let app = Router::new()
596 .route("/empty", get(handler_empty_404))
597 .layer(ProblemLayer);
598
599 let resp = call(&app, "/empty").await;
600 let body = body_string(resp).await;
601 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
602 assert_eq!(json["status"], 404);
603 assert!(json.get("detail").is_none(), "empty body must not produce a detail field");
605 }
606
607 #[tokio::test]
608 async fn problem_layer_passes_through_2xx() {
609 let app = layered_app();
610 let resp = call(&app, "/ok").await;
611 assert_eq!(resp.status(), http::StatusCode::OK);
612 let ct = resp.headers()
614 .get(header::CONTENT_TYPE)
615 .and_then(|v| v.to_str().ok())
616 .unwrap_or("");
617 assert!(!ct.contains("application/problem+json"));
618 }
619
620 #[tokio::test]
621 async fn problem_layer_passes_through_existing_problem_json() {
622 let app = layered_app();
623 let resp = call(&app, "/problem").await;
624
625 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
626 assert_eq!(
627 resp.headers().get(header::CONTENT_TYPE).unwrap(),
628 "application/problem+json"
629 );
630
631 let body = body_string(resp).await;
633 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
634 assert_eq!(json["detail"], "already a problem");
635 }
636
637 #[tokio::test]
638 async fn problem_layer_converts_axum_json_extractor_error() {
639 use axum::extract::Json;
642
643 async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
644
645 let app = Router::new()
646 .route("/json", axum::routing::post(needs_json))
647 .layer(ProblemLayer);
648
649 let resp = app
650 .oneshot(
651 http::Request::builder()
652 .method("POST")
653 .uri("/json")
654 .header("content-type", "application/json")
655 .body(Body::from("not valid json {{"))
656 .unwrap(),
657 )
658 .await
659 .unwrap();
660
661 assert!(resp.status().is_client_error());
662 assert_eq!(
663 resp.headers().get(header::CONTENT_TYPE).unwrap(),
664 "application/problem+json",
665 "axum extractor error must be converted to problem+json by ProblemLayer"
666 );
667
668 let body = body_string(resp).await;
669 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
670 assert!(json["status"].as_u64().unwrap() >= 400);
671 assert!(json["title"].is_string());
672 }
673}