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///
66/// # Manual construction
67///
68/// ```rust
69/// use axum_problem::Problem;
70///
71/// let p = Problem::new(404)
72///     .title("Order Not Found")
73///     .detail("Order 1001 does not exist");
74/// ```
75#[derive(Debug, Clone, Serialize)]
76pub struct Problem {
77    /// URI reference identifying the problem type. Defaults to `"about:blank"`.
78    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
79    pub problem_type: Option<String>,
80
81    /// Short human-readable summary of the problem type.
82    pub title: String,
83
84    /// HTTP status code.
85    pub status: u16,
86
87    /// Human-readable explanation specific to this occurrence.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub detail: Option<String>,
90
91    /// URI identifying the specific occurrence of this problem.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub instance: Option<String>,
94}
95
96impl Problem {
97    /// Create a new problem for the given HTTP status code.
98    /// The title is set automatically from the status code.
99    pub fn new(status: u16) -> Self {
100        Self {
101            problem_type: None,
102            title: status_title(status).to_owned(),
103            status,
104            detail: None,
105            instance: None,
106        }
107    }
108
109    /// Set the problem type URI (defaults to `"about:blank"` in the response).
110    pub fn problem_type(mut self, t: impl Into<String>) -> Self {
111        self.problem_type = Some(t.into());
112        self
113    }
114
115    /// Override the title.
116    pub fn title(mut self, title: impl Into<String>) -> Self {
117        self.title = title.into();
118        self
119    }
120
121    /// Add a human-readable explanation for this specific occurrence.
122    pub fn detail(mut self, detail: impl Into<String>) -> Self {
123        self.detail = Some(detail.into());
124        self
125    }
126
127    /// Add a URI identifying this specific occurrence.
128    pub fn instance(mut self, instance: impl Into<String>) -> Self {
129        self.instance = Some(instance.into());
130        self
131    }
132
133    // ── Convenience constructors ──────────────────────────────────────────────
134
135    pub fn bad_request() -> Self { Self::new(400) }
136    pub fn unauthorized() -> Self { Self::new(401) }
137    pub fn forbidden() -> Self { Self::new(403) }
138    pub fn not_found() -> Self { Self::new(404) }
139    pub fn method_not_allowed() -> Self { Self::new(405) }
140    pub fn conflict() -> Self { Self::new(409) }
141    pub fn unprocessable_entity() -> Self { Self::new(422) }
142    pub fn too_many_requests() -> Self { Self::new(429) }
143    pub fn internal_server_error() -> Self { Self::new(500) }
144    pub fn not_implemented() -> Self { Self::new(501) }
145    pub fn service_unavailable() -> Self { Self::new(503) }
146}
147
148impl IntoResponse for Problem {
149    fn into_response(self) -> Response {
150        let status = StatusCode::from_u16(self.status)
151            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
152
153        // Sync the JSON `status` field with the actual HTTP status line.
154        // If the caller passed an invalid code (e.g. 0), both the HTTP status
155        // and the JSON body must agree — returning 500 in both.
156        let mut serializable = self;
157        serializable.status = status.as_u16();
158
159        let body = serde_json::to_string(&serializable)
160            .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
161
162        (
163            status,
164            [(header::CONTENT_TYPE, "application/problem+json")],
165            body,
166        )
167            .into_response()
168    }
169}
170
171/// Returns a short title for common HTTP status codes.
172pub fn status_title(status: u16) -> &'static str {
173    match status {
174        400 => "Bad Request",
175        401 => "Unauthorized",
176        403 => "Forbidden",
177        404 => "Not Found",
178        405 => "Method Not Allowed",
179        408 => "Request Timeout",
180        409 => "Conflict",
181        410 => "Gone",
182        415 => "Unsupported Media Type",
183        422 => "Unprocessable Entity",
184        429 => "Too Many Requests",
185        500 => "Internal Server Error",
186        501 => "Not Implemented",
187        502 => "Bad Gateway",
188        503 => "Service Unavailable",
189        504 => "Gateway Timeout",
190        _ => "Error",
191    }
192}
193
194// ── ProblemLayer ──────────────────────────────────────────────────────────────
195
196/// Tower middleware layer that converts non-problem error responses to RFC 9457.
197///
198/// Any 4xx or 5xx response that doesn't have `Content-Type: application/problem+json`
199/// is replaced with a [`Problem`] response using the same HTTP status code.
200/// 2xx and 3xx responses pass through unchanged.
201/// Responses already in problem+json format also pass through unchanged.
202///
203/// Apply it **last** (outermost layer) in your axum router so it catches errors
204/// from all other middleware and extractors:
205///
206/// ```rust,no_run
207/// use axum::Router;
208/// use axum_problem::ProblemLayer;
209///
210/// let app: Router = Router::new()
211///     /* ... routes and other layers ... */
212///     .layer(ProblemLayer);
213/// ```
214#[derive(Clone, Copy, Default)]
215pub struct ProblemLayer;
216
217impl<S> tower_layer::Layer<S> for ProblemLayer {
218    type Service = ProblemService<S>;
219    fn layer(&self, inner: S) -> Self::Service {
220        ProblemService { inner }
221    }
222}
223
224/// Tower service produced by [`ProblemLayer`].
225#[derive(Clone)]
226pub struct ProblemService<S> {
227    inner: S,
228}
229
230impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
231where
232    S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
233        + Clone
234        + Send
235        + 'static,
236    S::Future: Send + 'static,
237    ReqBody: Send + 'static,
238{
239    type Response = axum::response::Response;
240    type Error = S::Error;
241    type Future = std::pin::Pin<
242        Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
243    >;
244
245    fn poll_ready(
246        &mut self,
247        cx: &mut std::task::Context<'_>,
248    ) -> std::task::Poll<Result<(), Self::Error>> {
249        self.inner.poll_ready(cx)
250    }
251
252    fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
253        use axum::response::IntoResponse;
254        let future = self.inner.call(req);
255        Box::pin(async move {
256            let resp = future.await?;
257            let status = resp.status();
258
259            if status.is_client_error() || status.is_server_error() {
260                let already_problem = resp
261                    .headers()
262                    .get(http::header::CONTENT_TYPE)
263                    .and_then(|v| v.to_str().ok())
264                    .map(|ct| ct.contains("application/problem+json"))
265                    .unwrap_or(false);
266
267                if !already_problem {
268                    return Ok(Problem::new(status.as_u16()).into_response());
269                }
270            }
271
272            Ok(resp)
273        })
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use axum::body::to_bytes;
281
282    async fn body_string(resp: Response) -> String {
283        let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
284        String::from_utf8(bytes.to_vec()).unwrap()
285    }
286
287    #[tokio::test]
288    async fn problem_serializes_to_correct_json() {
289        let p = Problem::not_found().detail("order 1001 not found");
290        let resp = p.into_response();
291
292        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
293        assert_eq!(
294            resp.headers().get(header::CONTENT_TYPE).unwrap(),
295            "application/problem+json"
296        );
297
298        let body = body_string(resp).await;
299        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
300        assert_eq!(json["status"], 404);
301        assert_eq!(json["title"], "Not Found");
302        assert_eq!(json["detail"], "order 1001 not found");
303    }
304
305    #[tokio::test]
306    async fn problem_omits_optional_fields() {
307        let p = Problem::new(400);
308        let resp = p.into_response();
309        let body = body_string(resp).await;
310        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
311        assert!(json.get("detail").is_none());
312        assert!(json.get("instance").is_none());
313        assert!(json.get("type").is_none());
314    }
315
316    #[tokio::test]
317    async fn problem_with_type_uri() {
318        let p = Problem::new(422)
319            .problem_type("https://errors.example.com/validation-failed")
320            .detail("email is required");
321        let resp = p.into_response();
322        let body = body_string(resp).await;
323        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
324        assert_eq!(json["type"], "https://errors.example.com/validation-failed");
325    }
326
327    #[tokio::test]
328    async fn status_title_coverage() {
329        assert_eq!(status_title(404), "Not Found");
330        assert_eq!(status_title(500), "Internal Server Error");
331        assert_eq!(status_title(999), "Error");
332    }
333
334    // ── ProblemLayer tests ────────────────────────────────────────────────────
335
336    use axum::{Router, routing::get, body::Body};
337    use tower::ServiceExt;
338
339    async fn handler_404() -> impl axum::response::IntoResponse {
340        (http::StatusCode::NOT_FOUND, "plain text 404")
341    }
342
343    async fn handler_200() -> impl axum::response::IntoResponse {
344        "ok"
345    }
346
347    async fn handler_problem() -> impl axum::response::IntoResponse {
348        Problem::not_found().detail("already a problem")
349    }
350
351    fn layered_app() -> Router {
352        Router::new()
353            .route("/notfound", get(handler_404))
354            .route("/ok", get(handler_200))
355            .route("/problem", get(handler_problem))
356            .layer(ProblemLayer)
357    }
358
359    async fn call(app: &Router, uri: &str) -> axum::response::Response {
360        app.clone()
361            .oneshot(
362                http::Request::builder()
363                    .uri(uri)
364                    .body(Body::empty())
365                    .unwrap(),
366            )
367            .await
368            .unwrap()
369    }
370
371    #[tokio::test]
372    async fn problem_layer_converts_plain_404_to_problem_json() {
373        let app = layered_app();
374        let resp = call(&app, "/notfound").await;
375
376        assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
377        assert_eq!(
378            resp.headers().get(header::CONTENT_TYPE).unwrap(),
379            "application/problem+json"
380        );
381
382        let body = body_string(resp).await;
383        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
384        assert_eq!(json["status"], 404);
385        assert_eq!(json["title"], "Not Found");
386    }
387
388    #[tokio::test]
389    async fn problem_layer_passes_through_2xx() {
390        let app = layered_app();
391        let resp = call(&app, "/ok").await;
392        assert_eq!(resp.status(), http::StatusCode::OK);
393        // Content-Type must NOT be problem+json for a 200
394        let ct = resp.headers()
395            .get(header::CONTENT_TYPE)
396            .and_then(|v| v.to_str().ok())
397            .unwrap_or("");
398        assert!(!ct.contains("application/problem+json"));
399    }
400
401    #[tokio::test]
402    async fn problem_layer_passes_through_existing_problem_json() {
403        let app = layered_app();
404        let resp = call(&app, "/problem").await;
405
406        assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
407        assert_eq!(
408            resp.headers().get(header::CONTENT_TYPE).unwrap(),
409            "application/problem+json"
410        );
411
412        // Detail must still be present — not overwritten by the layer
413        let body = body_string(resp).await;
414        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
415        assert_eq!(json["detail"], "already a problem");
416    }
417
418    #[tokio::test]
419    async fn problem_layer_converts_axum_json_extractor_error() {
420        // When axum's JSON extractor fails (bad body), it returns 422 with
421        // plain text. ProblemLayer must convert it to problem+json.
422        use axum::extract::Json;
423
424        async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
425
426        let app = Router::new()
427            .route("/json", axum::routing::post(needs_json))
428            .layer(ProblemLayer);
429
430        let resp = app
431            .oneshot(
432                http::Request::builder()
433                    .method("POST")
434                    .uri("/json")
435                    .header("content-type", "application/json")
436                    .body(Body::from("not valid json {{"))
437                    .unwrap(),
438            )
439            .await
440            .unwrap();
441
442        assert!(resp.status().is_client_error());
443        assert_eq!(
444            resp.headers().get(header::CONTENT_TYPE).unwrap(),
445            "application/problem+json",
446            "axum extractor error must be converted to problem+json by ProblemLayer"
447        );
448
449        let body = body_string(resp).await;
450        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
451        assert!(json["status"].as_u64().unwrap() >= 400);
452        assert!(json["title"].is_string());
453    }
454}