footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
use std::{fmt, ops::Deref};

use axum::{
    extract::{FromRequestParts, Query},
    http::request::Parts,
};
use serde::{
    Deserialize, Deserializer,
    de::{self, DeserializeOwned},
};

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

#[derive(Clone)]
/// Deserialized query parameters with client-safe rejection responses.
///
/// Invalid parameters return `400` with code `invalid_query`. Parser diagnostics
/// and custom deserializer errors are not included in the response.
pub struct QueryParams<T>(T);

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

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

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

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

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

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

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

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let Query(query) = Query::<T>::from_request_parts(parts, state)
            .await
            .map_err(|_| {
                ApiProblem::bad_request(
                    ProblemCode::INVALID_QUERY,
                    "query parameters do not match the expected format",
                )
                .with_request_context(RequestContext::from_parts(parts))
            })?;

        Ok(Self(query))
    }
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum StringOrU32 {
    Number(u32),
    String(String),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum StringOrBool {
    Bool(bool),
    String(String),
}

/// Deserializes an optional `u32` from a URL query scalar.
pub fn deserialize_optional_u32_from_query<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
    D: Deserializer<'de>,
{
    match Option::<StringOrU32>::deserialize(deserializer)? {
        Some(StringOrU32::Number(value)) => Ok(Some(value)),
        Some(StringOrU32::String(value)) => parse_optional_query_u32(&value),
        None => Ok(None),
    }
}

/// Deserializes a boolean from a URL query scalar.
pub fn deserialize_bool_from_query<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    match StringOrBool::deserialize(deserializer)? {
        StringOrBool::Bool(value) => Ok(value),
        StringOrBool::String(value) => parse_query_bool(&value),
    }
}

fn parse_optional_query_u32<E>(value: &str) -> Result<Option<u32>, E>
where
    E: de::Error,
{
    let value = value.trim();
    if value.is_empty() {
        return Ok(None);
    }

    value
        .parse::<u32>()
        .map(Some)
        .map_err(|_| E::custom("expected unsigned integer query parameter"))
}

fn parse_query_bool<E>(value: &str) -> Result<bool, E>
where
    E: de::Error,
{
    match value.trim().to_ascii_lowercase().as_str() {
        "true" | "1" => Ok(true),
        "false" | "0" => Ok(false),
        _ => Err(E::custom("expected boolean query parameter")),
    }
}

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

    use super::QueryParams;

    #[test]
    fn query_params_debug_redacts_inner_values() {
        let value = "private-query-value";
        let query = QueryParams(value.to_owned());
        let debug = format!("{query:?}");

        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains(value));
        assert_eq!(query.get(), value);
    }

    #[tokio::test]
    async fn query_rejections_preserve_context_without_disclosing_diagnostics() {
        #[derive(Deserialize)]
        struct QueryInput {
            count: u32,
        }

        struct PrivateQuery;

        impl<'de> Deserialize<'de> for PrivateQuery {
            fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
                Err(serde::de::Error::custom(
                    "private credential from application deserializer",
                ))
            }
        }

        let app = Router::new()
            .route(
                "/",
                get(|params: QueryParams<QueryInput>| async move { params.count.to_string() }),
            )
            .route(
                "/private",
                get(|_: QueryParams<PrivateQuery>| async { StatusCode::NO_CONTENT }),
            );

        for uri in [
            "/",
            "/?count=private-input",
            "/?count=1&count=2",
            "/private?token=private-input",
        ] {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(uri)
                        .header("x-request-id", "req_query")
                        .header(
                            "traceparent",
                            "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
                        )
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
            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"], 400);
            assert_eq!(problem["code"], "invalid_query");
            assert_eq!(problem["request_id"], "req_query");
            assert_eq!(problem["trace_id"], "4bf92f3577b34da6a3ce929d0e0e4736");
            assert_eq!(
                problem["detail"],
                "query parameters do not match the expected format"
            );
            assert!(problem.get("details").is_none());
            assert!(!String::from_utf8_lossy(&body).contains("private"));
            assert!(!String::from_utf8_lossy(&body).contains("QueryInput"));
        }
    }
}