vld-web 0.8.0

Web framework integrations for the vld validation library: axum, actix-web, ntex, poem, Rocket, salvo, warp, rama, Tower, tonic
Documentation
#![allow(clippy::result_large_err)]
//! # `vld_web::tonic` — tonic gRPC integration for `vld`
//!
//! Validate protobuf messages and gRPC metadata with `vld` schemas. Works
//! with tonic 0.12 – 0.14 (the dependency is `>=0.12, <0.15`) and only uses
//! `tonic::{Request, Status}`, so it needs no transport features.
//!
//! | Function | Use case |
//! |---|---|
//! | [`validate`] / [`validate_ref`] | Validate a message that implements [`VldMessage`] (via [`impl_validate!`]) |
//! | [`validate_with`] / [`validate_with_ref`] | Validate a `serde::Serialize` message against a separate `vld::schema!` struct |
//! | [`validate_metadata`] | Validate gRPC request metadata |
//! | [`metadata_interceptor`] | Tonic interceptor: validates metadata, stores [`Validated<T>`] |
//!
//! Failures become `Status::invalid_argument` (or a code of your choice via
//! [`vld_status_with_code`]) whose message is a JSON object with the issues.
//!
//! # Example
//!
//! ```
//! use tonic::{Code, Request};
//!
//! // A prost-generated message (here written by hand).
//! #[derive(Debug, Clone)]
//! pub struct CreateUserRequest {
//!     pub name: String,
//!     pub email: String,
//! }
//!
//! vld_web::tonic::impl_validate!(CreateUserRequest {
//!     name  => vld::string().min(2).max(100),
//!     email => vld::string().email(),
//! });
//!
//! let ok = vld_web::tonic::validate(Request::new(CreateUserRequest {
//!     name: "Alice".into(),
//!     email: "alice@example.com".into(),
//! }));
//! assert!(ok.is_ok());
//!
//! let status = vld_web::tonic::validate(Request::new(CreateUserRequest {
//!     name: "A".into(),
//!     email: "bad".into(),
//! }))
//! .unwrap_err();
//! assert_eq!(status.code(), Code::InvalidArgument);
//! ```
//!
//! Guide: <https://s00d.github.io/vld/integrations/web/tonic>
use tonic::{Code, Request, Status};
use vld::error::VldError;
use vld::schema::VldParse;

// ========================= Error conversion ==================================

/// Convert a [`VldError`] into a [`tonic::Status`] with `INVALID_ARGUMENT` code.
///
/// The status message contains a JSON object with structured error details:
/// `{"error": "VALIDATION_ERROR", "message": "...", "details": [{"path":
/// ".user.name", "message": "...", "code": "too_small"}]}` — `path` uses the
/// same format as the HTTP adapters, `code` is
/// [`IssueCode::key()`](vld::error::IssueCode::key).
pub fn vld_status(error: &VldError) -> Status {
    vld_status_with_code(error, Code::InvalidArgument)
}

/// Convert a [`VldError`] into a [`tonic::Status`] with a custom gRPC code.
pub fn vld_status_with_code(error: &VldError, code: Code) -> Status {
    let body = serde_json::json!({
        "error": "VALIDATION_ERROR",
        "message": "Request validation failed",
        "details": crate::common::format_issues(error),
    });

    Status::new(code, body.to_string())
}

// ========================= VldMessage trait ===================================

/// Trait for message types that can be validated with vld.
///
/// Implement via the [`impl_validate!`] macro, or manually.
pub trait VldMessage {
    /// Validate this message against its rules.
    fn vld_validate(&self) -> Result<(), VldError>;
}

// ========================= Message validation ================================

/// Validate a gRPC request message that implements [`VldMessage`].
///
/// Consumes the request and returns the validated message,
/// or `Status::INVALID_ARGUMENT` on failure.
///
/// # Example
///
/// ```ignore
/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
///     let msg = vld_web::tonic::validate(request)?;
///     // use msg...
///     Ok(Response::new(()))
/// }
/// ```
pub fn validate<T: VldMessage>(request: Request<T>) -> Result<T, Status> {
    let message = request.into_inner();
    message.vld_validate().map_err(|e| vld_status(&e))?;
    Ok(message)
}

/// Validate a message reference without consuming the request.
pub fn validate_ref<T: VldMessage>(message: &T) -> Result<(), Status> {
    message.vld_validate().map_err(|e| vld_status(&e))
}

// ========================= Schema-based validation ===========================

/// Validate a gRPC request message against a separate vld schema type.
///
/// The message is serialized to JSON via serde, then validated using
/// `S::vld_parse_value()`. Useful when you have a `vld::schema!` struct
/// that mirrors the protobuf message fields.
///
/// # Example
///
/// ```ignore
/// vld::schema! {
///     struct UserSchema {
///         name: String => vld::string().min(2),
///         email: String => vld::string().email(),
///     }
/// }
///
/// async fn handler(request: Request<CreateUserRequest>) -> Result<Response<()>, Status> {
///     let msg = vld_web::tonic::validate_with::<UserSchema, _>(request)?;
///     Ok(Response::new(()))
/// }
/// ```
pub fn validate_with<S, T>(request: Request<T>) -> Result<T, Status>
where
    S: VldParse,
    T: serde::Serialize,
{
    let message = request.into_inner();
    validate_with_ref::<S, T>(&message)?;
    Ok(message)
}

/// Validate a message reference against a separate vld schema type.
pub fn validate_with_ref<S, T>(message: &T) -> Result<(), Status>
where
    S: VldParse,
    T: serde::Serialize,
{
    let json = serde_json::to_value(message)
        .map_err(|e| Status::internal(format!("Serialization error: {}", e)))?;
    S::vld_parse_value(&json).map_err(|e| vld_status(&e))?;
    Ok(())
}

// ========================= Metadata validation ===============================

/// Validate gRPC request metadata against a vld schema.
///
/// Metadata keys are converted from `kebab-case` to `snake_case`
/// (e.g. `x-request-id` → `x_request_id`); keys containing `_` are ignored
/// (see [`crate::common::headers_to_json`]) and binary (`-bin`) keys are
/// skipped.
/// Values are coerced with [`crate::common::coerce_value`] (lossless:
/// `"42"` → number, `"true"` → boolean, `"01234"` stays a string) and
/// validated with [`crate::common::parse_coerced`], so a string field still
/// accepts `"42"`.
///
/// # Example
///
/// ```ignore
/// vld::schema! {
///     #[derive(Debug, Clone)]
///     struct AuthMeta {
///         authorization: String => vld::string().min(1),
///     }
/// }
///
/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
///     let auth: AuthMeta = vld_web::tonic::validate_metadata(&request)?;
///     println!("auth: {}", auth.authorization);
///     Ok(Response::new(()))
/// }
/// ```
pub fn validate_metadata<T, M>(request: &Request<M>) -> Result<T, Status>
where
    T: VldParse,
{
    let json =
        crate::common::headers_to_json(request.metadata().iter().filter_map(|kv| match kv {
            tonic::metadata::KeyAndValueRef::Ascii(key, value) => {
                Some((key.as_str(), value.as_encoded_bytes()))
            }
            tonic::metadata::KeyAndValueRef::Binary(_, _) => None,
        }));
    crate::common::parse_coerced::<T>(&json).map_err(|e| vld_status(&e))
}

/// The validated metadata, stored in the request extensions by
/// [`metadata_interceptor`] (a wrapper, so it never collides with other
/// extensions of type `T`).
#[derive(Debug, Clone)]
pub struct Validated<T>(pub T);

impl<T> std::ops::Deref for Validated<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

/// Retrieve a validated metadata struct from request extensions.
///
/// Use after [`metadata_interceptor`] has stored the [`Validated<T>`].
///
/// # Example
///
/// ```ignore
/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
///     let auth = vld_web::tonic::validated_metadata::<AuthMeta, _>(&request)
///         .ok_or_else(|| Status::unauthenticated("Missing auth"))?;
///     Ok(Response::new(()))
/// }
/// ```
pub fn validated_metadata<T, M>(request: &Request<M>) -> Option<T>
where
    T: Clone + Send + Sync + 'static,
{
    request
        .extensions()
        .get::<Validated<T>>()
        .map(|v| v.0.clone())
}

// ========================= Interceptor =======================================

/// A tonic interceptor function that validates request metadata.
///
/// The validated struct is stored in request extensions as
/// [`Validated<T>`] and can be retrieved in handlers via
/// [`validated_metadata`] or `request.extensions().get::<Validated<T>>()`.
///
/// # Example
///
/// ```ignore
/// use tonic::transport::Server;
///
/// vld::schema! {
///     #[derive(Debug, Clone)]
///     struct AuthMeta {
///         authorization: String => vld::string().min(1),
///     }
/// }
///
/// Server::builder()
///     .add_service(MyServiceServer::with_interceptor(
///         my_service,
///         vld_web::tonic::metadata_interceptor::<AuthMeta>,
///     ))
///     .serve(addr)
///     .await?;
/// ```
pub fn metadata_interceptor<T>(mut request: Request<()>) -> Result<Request<()>, Status>
where
    T: VldParse + Clone + Send + Sync + 'static,
{
    let validated: T = validate_metadata(&request)?;
    request.extensions_mut().insert(Validated(validated));
    Ok(request)
}

// ========================= Macro =============================================

/// Attach vld validation rules to a protobuf message type.
///
/// Generates `validate()` and `is_valid()` inherent methods (via
/// [`vld::impl_rules!`]) and implements the [`VldMessage`] trait.
///
/// # Example
///
/// ```ignore
/// // Protobuf message generated by prost (with serde support)
/// #[derive(Clone, PartialEq, prost::Message, serde::Serialize)]
/// pub struct CreateUserRequest {
///     #[prost(string, tag = "1")]
///     pub name: String,
///     #[prost(string, tag = "2")]
///     pub email: String,
///     #[prost(int32, tag = "3")]
///     pub age: i32,
/// }
///
/// vld_web::tonic::impl_validate!(CreateUserRequest {
///     name  => vld::string().min(2).max(50),
///     email => vld::string().email(),
///     age   => vld::number().int().min(0).max(150),
/// });
///
/// // Now you can use:
/// //   msg.validate()?;          — inherent method
/// //   msg.is_valid()            — inherent method
/// //   vld_web::tonic::validate(req)  — request helper
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! __tonic_impl_validate {
    ($name:ident { $($field:ident => $schema:expr),* $(,)? }) => {
        ::vld::impl_rules!($name { $($field => $schema),* });

        impl $crate::tonic::VldMessage for $name {
            fn vld_validate(&self) -> ::std::result::Result<(), ::vld::error::VldError> {
                self.validate()
            }
        }
    };
}

#[doc(inline)]
pub use crate::__tonic_impl_validate as impl_validate;

/// Prelude — import everything you need.
pub mod prelude {
    pub use super::{
        Validated, VldMessage, impl_validate, metadata_interceptor, validate, validate_metadata,
        validate_ref, validate_with, validate_with_ref, validated_metadata, vld_status,
        vld_status_with_code,
    };
    pub use vld::prelude::*;
}