footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
//! Path parameters with client-safe Problem Details responses.

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

use axum::{
    extract::{FromRequestParts, Path},
    http::request::Parts,
};
use serde::de::DeserializeOwned;

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

/// Deserializes route captures without disclosing input or parser diagnostics.
///
/// Delegates percent decoding and deserialization to [`Path`]. Invalid values
/// or UTF-8 return `400` with code `invalid_path`. Missing routing metadata,
/// mismatched capture counts, and unsupported target types retain Axum's `500`
/// classification and return a generic internal error. Both responses include
/// the existing request and trace identifiers.
///
/// One extractor reads all captures: use a scalar for one capture, a tuple for
/// positional captures, or a struct whose fields match capture names. `Debug`
/// redacts the contents; the application owns any logging of the inner value.
/// When `openapi` is enabled, this wrapper implements `IntoParams` whenever its
/// inner type does, selecting path parameters.
///
/// ```
/// use axum::{Router, routing::get};
/// use footing::http::PathParams;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct UserPath {
///     user_id: u64,
/// }
///
/// async fn user(path: PathParams<UserPath>) -> String {
///     path.user_id.to_string()
/// }
///
/// let app: Router = Router::new().route("/users/{user_id}", get(user));
/// ```
#[derive(Clone)]
pub struct PathParams<T>(T);

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

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

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

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

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

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

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

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let Path(value) =
            Path::<T>::from_request_parts(parts, state)
                .await
                .map_err(|rejection| {
                    ApiProblem::from(rejection)
                        .with_request_context(RequestContext::from_parts(parts))
                })?;
        Ok(Self(value))
    }
}

#[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::PathParams;
    use crate::http::{RequestContext, RequestId, TraceParent};

    #[tokio::test]
    async fn path_params_decode_named_captures_and_redact_debug() {
        #[derive(Deserialize)]
        struct UserPath {
            id: u64,
            name: String,
        }
        let app = Router::new().route(
            "/users/{id}/{name}",
            get(|path: PathParams<UserPath>| async move {
                assert_eq!(path.id, 42);
                assert_eq!(path.get().name, "private value");
                assert_eq!(path.as_ref().id, 42);
                assert!(!format!("{path:?}").contains("private value"));
                path.into_inner().name
            }),
        );
        let response = app
            .oneshot(
                Request::get("/users/42/private%20value")
                    .body(Body::empty())
                    .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 path_params_distinguish_client_input_from_route_errors() {
        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(
                "/number/{id}",
                get(|_: PathParams<u64>| async { StatusCode::NO_CONTENT }),
            )
            .route(
                "/tuple/{id}",
                get(|_: PathParams<(u64, u64)>| async { StatusCode::NO_CONTENT }),
            )
            .route(
                "/unsupported/{id}",
                get(|_: PathParams<Option<String>>| async { StatusCode::NO_CONTENT }),
            )
            .route(
                "/private/{id}",
                get(|_: PathParams<PrivateInput>| async { StatusCode::NO_CONTENT }),
            )
            .route(
                "/missing",
                get(|_: PathParams<u64>| async { StatusCode::NO_CONTENT }),
            );
        let context = RequestContext::new(RequestId::new("installed-path-request").unwrap())
            .with_traceparent(
                TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
                    .unwrap(),
            );

        for (uri, status) in [
            ("/number/private-input", 400),
            ("/number/%FF", 400),
            ("/private/secret", 400),
            ("/tuple/1", 500),
            ("/unsupported/1", 500),
            ("/missing", 500),
        ] {
            let response = app
                .clone()
                .oneshot(
                    Request::get(uri)
                        .header("x-request-id", "untrusted-header")
                        .extension(context.clone())
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status().as_u16(), status, "{uri}");
            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["request_id"], "installed-path-request");
            assert_eq!(problem["trace_id"], "4bf92f3577b34da6a3ce929d0e0e4736");
            assert!(problem.get("details").is_none());
            if status == 400 {
                assert_eq!(problem["code"], "invalid_path");
                assert_eq!(
                    problem["detail"],
                    "path parameters do not match the expected format"
                );
            } else {
                assert_eq!(problem["code"], "internal_error");
                assert_eq!(problem["detail"], "internal server error");
            }
            for sensitive in [
                "private-input",
                "private parser diagnostic",
                "secret",
                "untrusted-header",
            ] {
                assert!(!String::from_utf8_lossy(&body).contains(sensitive));
            }
        }
    }
}