Skip to main content

axum_problem/
lib.rs

1//! RFC 9457 problem details for axum.
2//!
3//! # Quick start
4//!
5//! ```rust,no_run
6//! use axum::{Router, routing::get, extract::Path};
7//! use axum_problem::{AxumProblem, Problem, ProblemLayer};
8//! use thiserror::Error;
9//!
10//! #[derive(Debug, Error, AxumProblem)]
11//! pub enum ApiError {
12//!     #[error("order {id} not found")]
13//!     #[problem(status = 404)]
14//!     NotFound { id: i64 },
15//!
16//!     #[error("unauthorized")]
17//!     #[problem(status = 401)]
18//!     Unauthorized,
19//!
20//!     #[error("database error: {0}")]
21//!     #[problem(status = 500, mask)]             // logs at error level (default)
22//!     Database(String),
23//!
24//!     #[error("rate limited: {0}")]
25//!     #[problem(status = 429, mask, log = "warn")]  // logs at warn level
26//!     RateLimited(String),
27//! }
28//!
29//! async fn get_order(Path(id): Path<i64>) -> Result<String, ApiError> {
30//!     Err(ApiError::NotFound { id })
31//! }
32//!
33//! // Apply ProblemLayer to catch axum's own extractor errors
34//! // (bad JSON body, wrong content-type, etc.) and convert them to RFC 9457.
35//! let app: Router = Router::new()
36//!     .route("/orders/:id", get(get_order))
37//!     .layer(ProblemLayer);
38//! ```
39//!
40//! The `mask` attribute hides the error detail from the HTTP response (preventing
41//! internal details leaking to clients) and logs the full error via `tracing::error!`.
42//!
43//! # ProblemLayer
44//!
45//! [`ProblemLayer`] is a Tower middleware that ensures **every** error response
46//! from your API uses `application/problem+json`. It intercepts any 4xx/5xx
47//! response that isn't already a problem response and wraps it:
48//!
49//! ```rust,no_run
50//! use axum::Router;
51//! use axum_problem::ProblemLayer;
52//!
53//! let app: Router = Router::new()
54//!     /* ... routes ... */
55//!     .layer(ProblemLayer);
56//! ```
57//!
58//! Responses already in `application/problem+json` format pass through unchanged.
59
60pub use axum_problem_derive::AxumProblem;
61
62use axum::response::{IntoResponse, Response};
63use http::{header, StatusCode};
64use serde::Serialize;
65
66/// An RFC 9457 problem details response.
67///
68/// Serializes to `application/problem+json` with the correct HTTP status code.
69/// Extension members (RFC 9457 §3.5) are serialized as top-level JSON fields
70/// alongside the standard members.
71///
72/// # Manual construction
73///
74/// ```rust
75/// use axum_problem::Problem;
76/// use serde_json::json;
77///
78/// let p = Problem::new(422)
79///     .title("Validation Failed")
80///     .detail("One or more fields are invalid")
81///     .extension("violations", json!([
82///         {"field": "email", "message": "must be a valid email"},
83///         {"field": "age",   "message": "must be at least 18"},
84///     ]));
85/// ```
86///
87/// Produces:
88/// ```json
89/// {
90///   "title": "Validation Failed",
91///   "status": 422,
92///   "detail": "One or more fields are invalid",
93///   "violations": [...]
94/// }
95/// ```
96#[derive(Debug, Clone, Serialize)]
97pub struct Problem {
98    /// URI reference identifying the problem type. Defaults to `"about:blank"`.
99    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
100    pub problem_type: Option<String>,
101
102    /// Short human-readable summary of the problem type.
103    pub title: String,
104
105    /// HTTP status code.
106    pub status: u16,
107
108    /// Human-readable explanation specific to this occurrence.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub detail: Option<String>,
111
112    /// URI identifying the specific occurrence of this problem.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub instance: Option<String>,
115
116    /// RFC 9457 extension members — serialized as top-level JSON fields.
117    ///
118    /// Use [`Problem::extension`] to add fields fluently.
119    #[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    /// Create a new problem for the given HTTP status code.
125    /// The title is set automatically from the status code.
126    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    /// Add an RFC 9457 extension member as a top-level JSON field.
138    ///
139    /// ```rust
140    /// use axum_problem::Problem;
141    /// use serde_json::json;
142    ///
143    /// let p = Problem::new(422)
144    ///     .extension("violations", json!([{"field":"email","message":"invalid"}]))
145    ///     .extension("request_id", json!("req-abc-123"));
146    /// ```
147    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    /// Set the problem type URI (defaults to `"about:blank"` in the response).
153    pub fn problem_type(mut self, t: impl Into<String>) -> Self {
154        self.problem_type = Some(t.into());
155        self
156    }
157
158    /// Override the title.
159    pub fn title(mut self, title: impl Into<String>) -> Self {
160        self.title = title.into();
161        self
162    }
163
164    /// Add a human-readable explanation for this specific occurrence.
165    pub fn detail(mut self, detail: impl Into<String>) -> Self {
166        self.detail = Some(detail.into());
167        self
168    }
169
170    /// Add a URI identifying this specific occurrence.
171    pub fn instance(mut self, instance: impl Into<String>) -> Self {
172        self.instance = Some(instance.into());
173        self
174    }
175
176    // ── Convenience constructors ──────────────────────────────────────────────
177
178    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        // Sync the JSON `status` field with the actual HTTP status line.
197        // If the caller passed an invalid code (e.g. 0), both the HTTP status
198        // and the JSON body must agree — returning 500 in both.
199        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
214/// Returns a short title for common HTTP status codes.
215pub 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// ── utoipa integration (optional feature) ────────────────────────────────────
238
239#[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                        // RFC 9457 extension members — any additional top-level fields
295                        .additional_properties(Some(AdditionalProperties::FreeForm(true)))
296                        .build(),
297                )),
298            )
299        }
300    }
301}
302
303// ── ProblemLayer ──────────────────────────────────────────────────────────────
304
305/// Tower middleware layer that converts non-problem error responses to RFC 9457.
306///
307/// Any 4xx or 5xx response that doesn't have `Content-Type: application/problem+json`
308/// is replaced with a [`Problem`] response using the same HTTP status code.
309/// The original response body (up to 4 KB) is preserved as the problem `detail`
310/// field — so axum extractor error messages like "missing field `email`" are not
311/// silently discarded. 2xx and 3xx responses pass through unchanged. Responses
312/// already in `application/problem+json` format also pass through unchanged.
313///
314/// Apply it **last** (outermost layer) in your axum router so it catches errors
315/// from all other middleware and extractors:
316///
317/// ```rust,no_run
318/// use axum::Router;
319/// use axum_problem::ProblemLayer;
320///
321/// let app: Router = Router::new()
322///     /* ... routes and other layers ... */
323///     .layer(ProblemLayer);
324/// ```
325#[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/// Tower service produced by [`ProblemLayer`].
336#[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                    // Collect the original error body (capped at 4 KB) and use it
381                    // as the problem detail. This preserves axum extractor error
382                    // messages (e.g. "missing field `email`") rather than discarding
383                    // them. Bodies larger than 4 KB or unreadable bodies fall back
384                    // to no detail — the problem response is always emitted.
385                    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    // ── extensions field tests ────────────────────────────────────────────────
464
465    #[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        // Extension must be a TOP-LEVEL field, not nested under "extensions"
478        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        // Only standard RFC 9457 fields present
509        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        // Standard fields still present
527        assert!(json["title"].is_string());
528        assert_eq!(json["status"], 400);
529        // Extension present
530        assert_eq!(json["errors"]["count"], 3);
531    }
532
533    // ── ProblemLayer tests ────────────────────────────────────────────────────
534
535    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        // The original handler body ("plain text 404") is now preserved as detail.
586        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        // No detail field when original body is empty.
604        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        // Content-Type must NOT be problem+json for a 200
613        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        // Detail must still be present — not overwritten by the layer
632        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        // When axum's JSON extractor fails (bad body), it returns 422 with
640        // plain text. ProblemLayer must convert it to problem+json.
641        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}