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)]
22//!     Database(String),
23//! }
24//!
25//! async fn get_order(Path(id): Path<i64>) -> Result<String, ApiError> {
26//!     Err(ApiError::NotFound { id })
27//! }
28//!
29//! // Apply ProblemLayer to catch axum's own extractor errors
30//! // (bad JSON body, wrong content-type, etc.) and convert them to RFC 9457.
31//! let app: Router = Router::new()
32//!     .route("/orders/:id", get(get_order))
33//!     .layer(ProblemLayer);
34//! ```
35//!
36//! The `mask` attribute hides the error detail from the HTTP response (preventing
37//! internal details leaking to clients) and logs the full error via `tracing::error!`.
38//!
39//! # ProblemLayer
40//!
41//! [`ProblemLayer`] is a Tower middleware that ensures **every** error response
42//! from your API uses `application/problem+json`. It intercepts any 4xx/5xx
43//! response that isn't already a problem response and wraps it:
44//!
45//! ```rust,no_run
46//! use axum::Router;
47//! use axum_problem::ProblemLayer;
48//!
49//! let app: Router = Router::new()
50//!     /* ... routes ... */
51//!     .layer(ProblemLayer);
52//! ```
53//!
54//! Responses already in `application/problem+json` format pass through unchanged.
55
56pub use axum_problem_derive::AxumProblem;
57
58use axum::response::{IntoResponse, Response};
59use http::{header, StatusCode};
60use serde::Serialize;
61
62/// An RFC 9457 problem details response.
63///
64/// Serializes to `application/problem+json` with the correct HTTP status code.
65/// Extension members (RFC 9457 §3.5) are serialized as top-level JSON fields
66/// alongside the standard members.
67///
68/// # Manual construction
69///
70/// ```rust
71/// use axum_problem::Problem;
72/// use serde_json::json;
73///
74/// let p = Problem::new(422)
75///     .title("Validation Failed")
76///     .detail("One or more fields are invalid")
77///     .extension("violations", json!([
78///         {"field": "email", "message": "must be a valid email"},
79///         {"field": "age",   "message": "must be at least 18"},
80///     ]));
81/// ```
82///
83/// Produces:
84/// ```json
85/// {
86///   "title": "Validation Failed",
87///   "status": 422,
88///   "detail": "One or more fields are invalid",
89///   "violations": [...]
90/// }
91/// ```
92#[derive(Debug, Clone, Serialize)]
93pub struct Problem {
94    /// URI reference identifying the problem type. Defaults to `"about:blank"`.
95    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
96    pub problem_type: Option<String>,
97
98    /// Short human-readable summary of the problem type.
99    pub title: String,
100
101    /// HTTP status code.
102    pub status: u16,
103
104    /// Human-readable explanation specific to this occurrence.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub detail: Option<String>,
107
108    /// URI identifying the specific occurrence of this problem.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub instance: Option<String>,
111
112    /// RFC 9457 extension members — serialized as top-level JSON fields.
113    ///
114    /// Use [`Problem::extension`] to add fields fluently.
115    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
116    pub extensions: serde_json::Map<String, serde_json::Value>,
117}
118
119impl Problem {
120    /// Create a new problem for the given HTTP status code.
121    /// The title is set automatically from the status code.
122    pub fn new(status: u16) -> Self {
123        Self {
124            problem_type: None,
125            title: status_title(status).to_owned(),
126            status,
127            detail: None,
128            instance: None,
129            extensions: serde_json::Map::new(),
130        }
131    }
132
133    /// Add an RFC 9457 extension member as a top-level JSON field.
134    ///
135    /// ```rust
136    /// use axum_problem::Problem;
137    /// use serde_json::json;
138    ///
139    /// let p = Problem::new(422)
140    ///     .extension("violations", json!([{"field":"email","message":"invalid"}]))
141    ///     .extension("request_id", json!("req-abc-123"));
142    /// ```
143    pub fn extension(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
144        self.extensions.insert(key.into(), value.into());
145        self
146    }
147
148    /// Set the problem type URI (defaults to `"about:blank"` in the response).
149    pub fn problem_type(mut self, t: impl Into<String>) -> Self {
150        self.problem_type = Some(t.into());
151        self
152    }
153
154    /// Override the title.
155    pub fn title(mut self, title: impl Into<String>) -> Self {
156        self.title = title.into();
157        self
158    }
159
160    /// Add a human-readable explanation for this specific occurrence.
161    pub fn detail(mut self, detail: impl Into<String>) -> Self {
162        self.detail = Some(detail.into());
163        self
164    }
165
166    /// Add a URI identifying this specific occurrence.
167    pub fn instance(mut self, instance: impl Into<String>) -> Self {
168        self.instance = Some(instance.into());
169        self
170    }
171
172    // ── Convenience constructors ──────────────────────────────────────────────
173
174    pub fn bad_request() -> Self { Self::new(400) }
175    pub fn unauthorized() -> Self { Self::new(401) }
176    pub fn forbidden() -> Self { Self::new(403) }
177    pub fn not_found() -> Self { Self::new(404) }
178    pub fn method_not_allowed() -> Self { Self::new(405) }
179    pub fn conflict() -> Self { Self::new(409) }
180    pub fn unprocessable_entity() -> Self { Self::new(422) }
181    pub fn too_many_requests() -> Self { Self::new(429) }
182    pub fn internal_server_error() -> Self { Self::new(500) }
183    pub fn not_implemented() -> Self { Self::new(501) }
184    pub fn service_unavailable() -> Self { Self::new(503) }
185}
186
187impl IntoResponse for Problem {
188    fn into_response(self) -> Response {
189        let status = StatusCode::from_u16(self.status)
190            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
191
192        // Sync the JSON `status` field with the actual HTTP status line.
193        // If the caller passed an invalid code (e.g. 0), both the HTTP status
194        // and the JSON body must agree — returning 500 in both.
195        let mut serializable = self;
196        serializable.status = status.as_u16();
197
198        let body = serde_json::to_string(&serializable)
199            .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
200
201        (
202            status,
203            [(header::CONTENT_TYPE, "application/problem+json")],
204            body,
205        )
206            .into_response()
207    }
208}
209
210/// Returns a short title for common HTTP status codes.
211pub fn status_title(status: u16) -> &'static str {
212    match status {
213        400 => "Bad Request",
214        401 => "Unauthorized",
215        403 => "Forbidden",
216        404 => "Not Found",
217        405 => "Method Not Allowed",
218        408 => "Request Timeout",
219        409 => "Conflict",
220        410 => "Gone",
221        415 => "Unsupported Media Type",
222        422 => "Unprocessable Entity",
223        429 => "Too Many Requests",
224        500 => "Internal Server Error",
225        501 => "Not Implemented",
226        502 => "Bad Gateway",
227        503 => "Service Unavailable",
228        504 => "Gateway Timeout",
229        _ => "Error",
230    }
231}
232
233// ── ProblemLayer ──────────────────────────────────────────────────────────────
234
235/// Tower middleware layer that converts non-problem error responses to RFC 9457.
236///
237/// Any 4xx or 5xx response that doesn't have `Content-Type: application/problem+json`
238/// is replaced with a [`Problem`] response using the same HTTP status code.
239/// 2xx and 3xx responses pass through unchanged.
240/// Responses already in problem+json format also pass through unchanged.
241///
242/// Apply it **last** (outermost layer) in your axum router so it catches errors
243/// from all other middleware and extractors:
244///
245/// ```rust,no_run
246/// use axum::Router;
247/// use axum_problem::ProblemLayer;
248///
249/// let app: Router = Router::new()
250///     /* ... routes and other layers ... */
251///     .layer(ProblemLayer);
252/// ```
253#[derive(Clone, Copy, Default)]
254pub struct ProblemLayer;
255
256impl<S> tower_layer::Layer<S> for ProblemLayer {
257    type Service = ProblemService<S>;
258    fn layer(&self, inner: S) -> Self::Service {
259        ProblemService { inner }
260    }
261}
262
263/// Tower service produced by [`ProblemLayer`].
264#[derive(Clone)]
265pub struct ProblemService<S> {
266    inner: S,
267}
268
269impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
270where
271    S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
272        + Clone
273        + Send
274        + 'static,
275    S::Future: Send + 'static,
276    ReqBody: Send + 'static,
277{
278    type Response = axum::response::Response;
279    type Error = S::Error;
280    type Future = std::pin::Pin<
281        Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
282    >;
283
284    fn poll_ready(
285        &mut self,
286        cx: &mut std::task::Context<'_>,
287    ) -> std::task::Poll<Result<(), Self::Error>> {
288        self.inner.poll_ready(cx)
289    }
290
291    fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
292        use axum::response::IntoResponse;
293        let future = self.inner.call(req);
294        Box::pin(async move {
295            let resp = future.await?;
296            let status = resp.status();
297
298            if status.is_client_error() || status.is_server_error() {
299                let already_problem = resp
300                    .headers()
301                    .get(http::header::CONTENT_TYPE)
302                    .and_then(|v| v.to_str().ok())
303                    .map(|ct| ct.contains("application/problem+json"))
304                    .unwrap_or(false);
305
306                if !already_problem {
307                    return Ok(Problem::new(status.as_u16()).into_response());
308                }
309            }
310
311            Ok(resp)
312        })
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use axum::body::to_bytes;
320
321    async fn body_string(resp: Response) -> String {
322        let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
323        String::from_utf8(bytes.to_vec()).unwrap()
324    }
325
326    #[tokio::test]
327    async fn problem_serializes_to_correct_json() {
328        let p = Problem::not_found().detail("order 1001 not found");
329        let resp = p.into_response();
330
331        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
332        assert_eq!(
333            resp.headers().get(header::CONTENT_TYPE).unwrap(),
334            "application/problem+json"
335        );
336
337        let body = body_string(resp).await;
338        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
339        assert_eq!(json["status"], 404);
340        assert_eq!(json["title"], "Not Found");
341        assert_eq!(json["detail"], "order 1001 not found");
342    }
343
344    #[tokio::test]
345    async fn problem_omits_optional_fields() {
346        let p = Problem::new(400);
347        let resp = p.into_response();
348        let body = body_string(resp).await;
349        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
350        assert!(json.get("detail").is_none());
351        assert!(json.get("instance").is_none());
352        assert!(json.get("type").is_none());
353    }
354
355    #[tokio::test]
356    async fn problem_with_type_uri() {
357        let p = Problem::new(422)
358            .problem_type("https://errors.example.com/validation-failed")
359            .detail("email is required");
360        let resp = p.into_response();
361        let body = body_string(resp).await;
362        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
363        assert_eq!(json["type"], "https://errors.example.com/validation-failed");
364    }
365
366    #[tokio::test]
367    async fn status_title_coverage() {
368        assert_eq!(status_title(404), "Not Found");
369        assert_eq!(status_title(500), "Internal Server Error");
370        assert_eq!(status_title(999), "Error");
371    }
372
373    // ── extensions field tests ────────────────────────────────────────────────
374
375    #[tokio::test]
376    async fn extension_field_serialized_at_top_level() {
377        let p = Problem::new(422)
378            .detail("validation failed")
379            .extension("violations", serde_json::json!([
380                {"field": "email", "message": "invalid"}
381            ]));
382
383        let resp = p.into_response();
384        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
385        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
386
387        // Extension must be a TOP-LEVEL field, not nested under "extensions"
388        assert!(json.get("violations").is_some(), "violations must be a top-level field");
389        assert!(json.get("extensions").is_none(), "must not have a nested 'extensions' key");
390        assert_eq!(json["violations"][0]["field"], "email");
391        assert_eq!(json["status"], 422);
392        assert_eq!(json["detail"], "validation failed");
393    }
394
395    #[tokio::test]
396    async fn multiple_extensions_all_at_top_level() {
397        let p = Problem::new(400)
398            .extension("request_id", serde_json::json!("req-abc-123"))
399            .extension("correlation_id", serde_json::json!("corr-xyz"))
400            .extension("retry_after", serde_json::json!(30));
401
402        let resp = p.into_response();
403        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
404        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
405
406        assert_eq!(json["request_id"], "req-abc-123");
407        assert_eq!(json["correlation_id"], "corr-xyz");
408        assert_eq!(json["retry_after"], 30);
409    }
410
411    #[tokio::test]
412    async fn no_extensions_means_no_extra_fields() {
413        let p = Problem::new(404).detail("not found");
414        let resp = p.into_response();
415        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
416        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
417
418        // Only standard RFC 9457 fields present
419        let keys: Vec<&str> = json.as_object().unwrap().keys().map(|k| k.as_str()).collect();
420        for key in &keys {
421            assert!(
422                ["title", "status", "detail", "instance", "type"].contains(key),
423                "unexpected extra key in response: {key}"
424            );
425        }
426    }
427
428    #[tokio::test]
429    async fn extension_is_valid_rfc9457_json() {
430        let p = Problem::new(400)
431            .extension("errors", serde_json::json!({"count": 3}));
432        let resp = p.into_response();
433        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
434        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
435
436        // Standard fields still present
437        assert!(json["title"].is_string());
438        assert_eq!(json["status"], 400);
439        // Extension present
440        assert_eq!(json["errors"]["count"], 3);
441    }
442
443    // ── ProblemLayer tests ────────────────────────────────────────────────────
444
445    use axum::{Router, routing::get, body::Body};
446    use tower::ServiceExt;
447
448    async fn handler_404() -> impl axum::response::IntoResponse {
449        (http::StatusCode::NOT_FOUND, "plain text 404")
450    }
451
452    async fn handler_200() -> impl axum::response::IntoResponse {
453        "ok"
454    }
455
456    async fn handler_problem() -> impl axum::response::IntoResponse {
457        Problem::not_found().detail("already a problem")
458    }
459
460    fn layered_app() -> Router {
461        Router::new()
462            .route("/notfound", get(handler_404))
463            .route("/ok", get(handler_200))
464            .route("/problem", get(handler_problem))
465            .layer(ProblemLayer)
466    }
467
468    async fn call(app: &Router, uri: &str) -> axum::response::Response {
469        app.clone()
470            .oneshot(
471                http::Request::builder()
472                    .uri(uri)
473                    .body(Body::empty())
474                    .unwrap(),
475            )
476            .await
477            .unwrap()
478    }
479
480    #[tokio::test]
481    async fn problem_layer_converts_plain_404_to_problem_json() {
482        let app = layered_app();
483        let resp = call(&app, "/notfound").await;
484
485        assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
486        assert_eq!(
487            resp.headers().get(header::CONTENT_TYPE).unwrap(),
488            "application/problem+json"
489        );
490
491        let body = body_string(resp).await;
492        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
493        assert_eq!(json["status"], 404);
494        assert_eq!(json["title"], "Not Found");
495    }
496
497    #[tokio::test]
498    async fn problem_layer_passes_through_2xx() {
499        let app = layered_app();
500        let resp = call(&app, "/ok").await;
501        assert_eq!(resp.status(), http::StatusCode::OK);
502        // Content-Type must NOT be problem+json for a 200
503        let ct = resp.headers()
504            .get(header::CONTENT_TYPE)
505            .and_then(|v| v.to_str().ok())
506            .unwrap_or("");
507        assert!(!ct.contains("application/problem+json"));
508    }
509
510    #[tokio::test]
511    async fn problem_layer_passes_through_existing_problem_json() {
512        let app = layered_app();
513        let resp = call(&app, "/problem").await;
514
515        assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
516        assert_eq!(
517            resp.headers().get(header::CONTENT_TYPE).unwrap(),
518            "application/problem+json"
519        );
520
521        // Detail must still be present — not overwritten by the layer
522        let body = body_string(resp).await;
523        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
524        assert_eq!(json["detail"], "already a problem");
525    }
526
527    #[tokio::test]
528    async fn problem_layer_converts_axum_json_extractor_error() {
529        // When axum's JSON extractor fails (bad body), it returns 422 with
530        // plain text. ProblemLayer must convert it to problem+json.
531        use axum::extract::Json;
532
533        async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
534
535        let app = Router::new()
536            .route("/json", axum::routing::post(needs_json))
537            .layer(ProblemLayer);
538
539        let resp = app
540            .oneshot(
541                http::Request::builder()
542                    .method("POST")
543                    .uri("/json")
544                    .header("content-type", "application/json")
545                    .body(Body::from("not valid json {{"))
546                    .unwrap(),
547            )
548            .await
549            .unwrap();
550
551        assert!(resp.status().is_client_error());
552        assert_eq!(
553            resp.headers().get(header::CONTENT_TYPE).unwrap(),
554            "application/problem+json",
555            "axum extractor error must be converted to problem+json by ProblemLayer"
556        );
557
558        let body = body_string(resp).await;
559        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
560        assert!(json["status"].as_u64().unwrap() >= 400);
561        assert!(json["title"].is_string());
562    }
563}