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    };
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                        // RFC 9457 extension members — any additional top-level fields
293                        .additional_properties(Some(AdditionalProperties::FreeForm(true)))
294                        .build(),
295                )),
296            )
297        }
298    }
299}
300
301// ── ProblemLayer ──────────────────────────────────────────────────────────────
302
303/// Tower middleware layer that converts non-problem error responses to RFC 9457.
304///
305/// Any 4xx or 5xx response that doesn't have `Content-Type: application/problem+json`
306/// is replaced with a [`Problem`] response using the same HTTP status code.
307/// The original response body (up to 4 KB) is preserved as the problem `detail`
308/// field — so axum extractor error messages like "missing field `email`" are not
309/// silently discarded. 2xx and 3xx responses pass through unchanged. Responses
310/// already in `application/problem+json` format also pass through unchanged.
311///
312/// Apply it **last** (outermost layer) in your axum router so it catches errors
313/// from all other middleware and extractors:
314///
315/// ```rust,no_run
316/// use axum::Router;
317/// use axum_problem::ProblemLayer;
318///
319/// let app: Router = Router::new()
320///     /* ... routes and other layers ... */
321///     .layer(ProblemLayer);
322/// ```
323#[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/// Tower service produced by [`ProblemLayer`].
334#[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                    // Collect the original error body (capped at 4 KB) and use it
379                    // as the problem detail. This preserves axum extractor error
380                    // messages (e.g. "missing field `email`") rather than discarding
381                    // them. Bodies larger than 4 KB or unreadable bodies fall back
382                    // to no detail — the problem response is always emitted.
383                    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    // ── extensions field tests ────────────────────────────────────────────────
462
463    #[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        // Extension must be a TOP-LEVEL field, not nested under "extensions"
476        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        // Only standard RFC 9457 fields present
507        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        // Standard fields still present
525        assert!(json["title"].is_string());
526        assert_eq!(json["status"], 400);
527        // Extension present
528        assert_eq!(json["errors"]["count"], 3);
529    }
530
531    // ── ProblemLayer tests ────────────────────────────────────────────────────
532
533    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        // The original handler body ("plain text 404") is now preserved as detail.
584        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        // No detail field when original body is empty.
602        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        // Content-Type must NOT be problem+json for a 200
611        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        // Detail must still be present — not overwritten by the layer
630        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        // When axum's JSON extractor fails (bad body), it returns 422 with
638        // plain text. ProblemLayer must convert it to problem+json.
639        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}