footing 0.6.6

Feature-gated foundations for Rust backend services
Documentation
//! JSON request bodies with client-safe Problem Details responses.

use std::{fmt, ops::Deref};

use axum::{Json, body::Body, extract::FromRequest, http::Request};
use serde::de::DeserializeOwned;

use crate::http::{ApiProblem, RequestContext};

/// Deserializes JSON without requiring application validation.
///
/// Accepts `application/json` and `application/*+json`, and honors Axum's
/// [`axum::extract::DefaultBodyLimit`]. Rejections use [`ApiProblem`], preserving
/// `400` for malformed JSON, `422` for a mismatched data shape, `415` for an
/// unsupported content type, and `413` for a body that exceeds the limit.
/// Parser diagnostics and custom deserializer errors are never included in the
/// response; existing request and trace identifiers are preserved.
///
/// Use [`super::ValidatedJson`] when the input also implements application
/// validation. This extractor's `Debug` output redacts its contents; accessing
/// or logging the inner value is the application's responsibility.
/// For OpenAPI, declare `request_body = T` on the handler, using the input DTO's
/// schema rather than the extractor type.
///
/// ```
/// use axum::{Router, routing::post};
/// use footing::http::JsonBody;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Input {
///     message: String,
/// }
///
/// async fn echo(body: JsonBody<Input>) -> String {
///     body.into_inner().message
/// }
///
/// let app: Router = Router::new().route("/echo", post(echo));
/// ```
#[derive(Clone)]
pub struct JsonBody<T>(T);

impl<T> JsonBody<T> {
    /// Returns the deserialized value.
    #[must_use]
    pub const fn get(&self) -> &T {
        &self.0
    }

    /// Consumes the extractor and returns its value.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> fmt::Debug for JsonBody<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("JsonBody")
            .field(&"[REDACTED]")
            .finish()
    }
}

impl<T> AsRef<T> for JsonBody<T> {
    fn as_ref(&self) -> &T {
        self.get()
    }
}

impl<T> Deref for JsonBody<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl<S, T> FromRequest<S> for JsonBody<T>
where
    S: Send + Sync,
    T: DeserializeOwned,
{
    type Rejection = ApiProblem;

    async fn from_request(request: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
        extract_json(request, state)
            .await
            .map(|(value, _)| Self(value))
    }
}

// Keep the consumed request's context for a subsequent application-validation
// rejection without cloning it or parsing the request a second time.
pub(super) async fn extract_json<S, T>(
    mut request: Request<Body>,
    state: &S,
) -> Result<(T, RequestContext), ApiProblem>
where
    S: Send + Sync,
    T: DeserializeOwned,
{
    let context = request
        .extensions_mut()
        .remove::<RequestContext>()
        .unwrap_or_else(|| RequestContext::from_headers(request.headers()));
    let Json(value) = Json::<T>::from_request(request, state)
        .await
        .map_err(|rejection| ApiProblem::from(rejection).with_request_context(&context))?;
    Ok((value, context))
}

#[cfg(test)]
mod tests {
    use axum::{
        Router,
        body::{Body, to_bytes},
        extract::DefaultBodyLimit,
        http::{Request, StatusCode, header::CONTENT_TYPE},
        routing::post,
    };
    use serde::{Deserialize, Deserializer};
    use tower::ServiceExt;

    use super::JsonBody;
    use crate::http::{RequestContext, RequestId, TraceParent};

    #[derive(Deserialize)]
    struct Input {
        value: String,
    }

    #[tokio::test]
    async fn plain_json_needs_no_validate_impl_and_accepts_json_media_types() {
        let app = Router::new().route(
            "/",
            post(|body: JsonBody<Input>| async move {
                assert_eq!(body.get().value, "private-value");
                assert_eq!(body.as_ref().value, "private-value");
                assert_eq!(body.value, "private-value");
                assert!(!format!("{body:?}").contains("private-value"));
                body.into_inner().value
            }),
        );
        for content_type in ["application/json", "application/vnd.example+json"] {
            let response = app
                .clone()
                .oneshot(
                    Request::post("/")
                        .header(CONTENT_TYPE, content_type)
                        .body(Body::from(r#"{"value":"private-value"}"#))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
            assert_eq!(
                to_bytes(response.into_body(), 4096).await.unwrap(),
                "private-value"
            );
        }
    }

    #[tokio::test]
    async fn plain_json_rejections_preserve_status_and_installed_context() {
        let app = Router::new()
            .route(
                "/",
                post(|_: JsonBody<Input>| async { StatusCode::NO_CONTENT }),
            )
            .layer(DefaultBodyLimit::max(64));
        let context = RequestContext::new(RequestId::new("installed-request").unwrap())
            .with_traceparent(
                TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
                    .unwrap(),
            );
        let json = Some("application/json");
        for (body, content_type, status, code) in [
            ("{}", None, 415, "unsupported_media_type"),
            (r#"{"value":"#, json, 400, "invalid_json"),
            ("null", json, 422, "invalid_json"),
            (r#"{"value":123}"#, json, 422, "invalid_json"),
            (&"x".repeat(65), json, 413, "payload_too_large"),
        ] {
            let mut request = Request::post("/")
                .header("x-request-id", "untrusted-header")
                .extension(context.clone());
            if let Some(content_type) = content_type {
                request = request.header(CONTENT_TYPE, content_type);
            }
            let response = app
                .clone()
                .oneshot(request.body(Body::from(body.to_owned())).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status().as_u16(), status);
            assert_eq!(response.headers()[CONTENT_TYPE], "application/problem+json");
            let body = to_bytes(response.into_body(), 4096).await.unwrap();
            let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(problem["status"], status);
            assert_eq!(problem["code"], code);
            assert_eq!(problem["request_id"], "installed-request");
            assert_eq!(problem["trace_id"], "4bf92f3577b34da6a3ce929d0e0e4736");
            assert!(problem.get("details").is_none());
            assert!(!String::from_utf8_lossy(&body).contains("struct Input"));
        }
    }

    #[tokio::test]
    async fn plain_json_hides_custom_deserializer_diagnostics() {
        struct PrivateInput;

        impl<'de> Deserialize<'de> for PrivateInput {
            fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
                Err(serde::de::Error::custom("private parser diagnostic"))
            }
        }

        let app = Router::new().route(
            "/",
            post(|_: JsonBody<PrivateInput>| async { StatusCode::NO_CONTENT }),
        );
        let response = app
            .oneshot(
                Request::post("/")
                    .header(CONTENT_TYPE, "application/json")
                    .header("x-request-id", "json-request")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(response.into_body(), 4096).await.unwrap();
        let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(problem["code"], "invalid_json");
        assert_eq!(problem["request_id"], "json-request");
        assert_eq!(
            problem["detail"],
            "JSON body does not match the expected format"
        );
        assert!(problem.get("details").is_none());
        assert!(!String::from_utf8_lossy(&body).contains("private parser diagnostic"));
    }
}