about summary refs log tree commit diff
path: root/src/json_errors.rs
blob: 458eea939772fc34d0ce4e0bcbc28c69ba3dc428 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//! Make every client error answer in the API's own envelope.
//!
//! Extractor failures never reach a handler, so they never see `ApiError`: axum
//! answers a body it cannot deserialize with `text/plain`, e.g.
//!
//! ```text
//! Failed to deserialize the JSON body into the target type:
//! missing field `trait_name` at line 1 column 1387
//! ```
//!
//! That is the one error class a client cannot parse -- everything else carries
//! `code`, `detail` and `request_id`.  Measured on the release service: a
//! `/compute/rqtl` call without `trait_name` answered 422 `text/plain`.
//!
//! A middleware fixes it in one place instead of adding a custom extractor to
//! every handler: if the response is a 4xx that is not already JSON, its body
//! becomes `{"type": "/errors/invalid_request", "title": ..., "status": ...,
//! "code": "invalid_request", "detail": <the original text>, "error": null,
//! "operation_id": <the matched route>}`.
use axum::body::Body;
use axum::extract::MatchedPath;
use axum::http::{header, Request, StatusCode};
use axum::middleware::Next;
use axum::response::Response;

pub async fn jsonify_client_errors(request: Request<Body>, next: Next) -> Response {
    // The matched route pattern is the closest thing to an operation id
    // available this early; it names /compute/rqtl rather than the path asked.
    let operation = request
        .extensions()
        .get::<MatchedPath>()
        .map(|matched: &MatchedPath| matched.as_str().to_string());
    let mut response = next.run(request).await;
    let status = response.status();
    if !status.is_client_error() {
        return response;
    }
    let is_json = response
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .map(|value| value.starts_with("application/json"))
        .unwrap_or(false);
    if is_json {
        return response;
    }
    // Take the body apart and rebuild it: the original text is the detail.
    let (mut parts, body) = response.into_parts();
    let bytes = axum::body::to_bytes(body, 64 * 1024)
        .await
        .unwrap_or_default();
    let detail = String::from_utf8_lossy(&bytes).trim().to_string();
    let body = serde_json::json!({
        "type": "/errors/invalid_request",
        "title": "Invalid request",
        "status": status.as_u16(),
        "code": match status {
            StatusCode::UNSUPPORTED_MEDIA_TYPE => "unsupported_media_type",
            StatusCode::PAYLOAD_TOO_LARGE => "payload_too_large",
            _ => "invalid_request",
        },
        "detail": if detail.is_empty() { "the request could not be read".to_string() } else { detail },
        "error": null,
        "operation_id": operation,
        "spec_url": "/openapi.json",
        "next": null,
    });
    let text = body.to_string();
    parts.headers.insert(
        header::CONTENT_TYPE,
        header::HeaderValue::from_static("application/json"),
    );
    parts.headers.remove(header::CONTENT_LENGTH);
    Response::from_parts(parts, Body::from(text))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::routing::post;

    async fn boom() -> StatusCode {
        StatusCode::BAD_REQUEST
    }

    /// A 4xx that is not JSON comes back as the envelope; a JSON one is left
    /// alone.
    #[tokio::test]
    async fn a_plain_text_client_error_becomes_the_envelope() {
        use tower::ServiceExt;
        let app = Router::new()
            .route("/boom", post(boom))
            .layer(axum::middleware::from_fn(jsonify_client_errors));
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/boom")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        assert_eq!(
            response
                .headers()
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("application/json")
        );
        let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["code"], "invalid_request");
        assert!(body["operation_id"].is_string());
    }
}