vld_web/tonic.rs
1#![allow(clippy::result_large_err)]
2//! # `vld_web::tonic` — tonic gRPC integration for `vld`
3//!
4//! Validate protobuf messages and gRPC metadata with `vld` schemas. Works
5//! with tonic 0.12 – 0.14 (the dependency is `>=0.12, <0.15`) and only uses
6//! `tonic::{Request, Status}`, so it needs no transport features.
7//!
8//! | Function | Use case |
9//! |---|---|
10//! | [`validate`] / [`validate_ref`] | Validate a message that implements [`VldMessage`] (via [`impl_validate!`]) |
11//! | [`validate_with`] / [`validate_with_ref`] | Validate a `serde::Serialize` message against a separate `vld::schema!` struct |
12//! | [`validate_metadata`] | Validate gRPC request metadata |
13//! | [`metadata_interceptor`] | Tonic interceptor: validates metadata, stores [`Validated<T>`] |
14//!
15//! Failures become `Status::invalid_argument` (or a code of your choice via
16//! [`vld_status_with_code`]) whose message is a JSON object with the issues.
17//!
18//! # Example
19//!
20//! ```
21//! use tonic::{Code, Request};
22//!
23//! // A prost-generated message (here written by hand).
24//! #[derive(Debug, Clone)]
25//! pub struct CreateUserRequest {
26//! pub name: String,
27//! pub email: String,
28//! }
29//!
30//! vld_web::tonic::impl_validate!(CreateUserRequest {
31//! name => vld::string().min(2).max(100),
32//! email => vld::string().email(),
33//! });
34//!
35//! let ok = vld_web::tonic::validate(Request::new(CreateUserRequest {
36//! name: "Alice".into(),
37//! email: "alice@example.com".into(),
38//! }));
39//! assert!(ok.is_ok());
40//!
41//! let status = vld_web::tonic::validate(Request::new(CreateUserRequest {
42//! name: "A".into(),
43//! email: "bad".into(),
44//! }))
45//! .unwrap_err();
46//! assert_eq!(status.code(), Code::InvalidArgument);
47//! ```
48//!
49//! Guide: <https://s00d.github.io/vld/integrations/web/tonic>
50use tonic::{Code, Request, Status};
51use vld::error::VldError;
52use vld::schema::VldParse;
53
54// ========================= Error conversion ==================================
55
56/// Convert a [`VldError`] into a [`tonic::Status`] with `INVALID_ARGUMENT` code.
57///
58/// The status message contains a JSON object with structured error details:
59/// `{"error": "VALIDATION_ERROR", "message": "...", "details": [{"path":
60/// ".user.name", "message": "...", "code": "too_small"}]}` — `path` uses the
61/// same format as the HTTP adapters, `code` is
62/// [`IssueCode::key()`](vld::error::IssueCode::key).
63pub fn vld_status(error: &VldError) -> Status {
64 vld_status_with_code(error, Code::InvalidArgument)
65}
66
67/// Convert a [`VldError`] into a [`tonic::Status`] with a custom gRPC code.
68pub fn vld_status_with_code(error: &VldError, code: Code) -> Status {
69 let body = serde_json::json!({
70 "error": "VALIDATION_ERROR",
71 "message": "Request validation failed",
72 "details": crate::common::format_issues(error),
73 });
74
75 Status::new(code, body.to_string())
76}
77
78// ========================= VldMessage trait ===================================
79
80/// Trait for message types that can be validated with vld.
81///
82/// Implement via the [`impl_validate!`] macro, or manually.
83pub trait VldMessage {
84 /// Validate this message against its rules.
85 fn vld_validate(&self) -> Result<(), VldError>;
86}
87
88// ========================= Message validation ================================
89
90/// Validate a gRPC request message that implements [`VldMessage`].
91///
92/// Consumes the request and returns the validated message,
93/// or `Status::INVALID_ARGUMENT` on failure.
94///
95/// # Example
96///
97/// ```ignore
98/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
99/// let msg = vld_web::tonic::validate(request)?;
100/// // use msg...
101/// Ok(Response::new(()))
102/// }
103/// ```
104pub fn validate<T: VldMessage>(request: Request<T>) -> Result<T, Status> {
105 let message = request.into_inner();
106 message.vld_validate().map_err(|e| vld_status(&e))?;
107 Ok(message)
108}
109
110/// Validate a message reference without consuming the request.
111pub fn validate_ref<T: VldMessage>(message: &T) -> Result<(), Status> {
112 message.vld_validate().map_err(|e| vld_status(&e))
113}
114
115// ========================= Schema-based validation ===========================
116
117/// Validate a gRPC request message against a separate vld schema type.
118///
119/// The message is serialized to JSON via serde, then validated using
120/// `S::vld_parse_value()`. Useful when you have a `vld::schema!` struct
121/// that mirrors the protobuf message fields.
122///
123/// # Example
124///
125/// ```ignore
126/// vld::schema! {
127/// struct UserSchema {
128/// name: String => vld::string().min(2),
129/// email: String => vld::string().email(),
130/// }
131/// }
132///
133/// async fn handler(request: Request<CreateUserRequest>) -> Result<Response<()>, Status> {
134/// let msg = vld_web::tonic::validate_with::<UserSchema, _>(request)?;
135/// Ok(Response::new(()))
136/// }
137/// ```
138pub fn validate_with<S, T>(request: Request<T>) -> Result<T, Status>
139where
140 S: VldParse,
141 T: serde::Serialize,
142{
143 let message = request.into_inner();
144 validate_with_ref::<S, T>(&message)?;
145 Ok(message)
146}
147
148/// Validate a message reference against a separate vld schema type.
149pub fn validate_with_ref<S, T>(message: &T) -> Result<(), Status>
150where
151 S: VldParse,
152 T: serde::Serialize,
153{
154 let json = serde_json::to_value(message)
155 .map_err(|e| Status::internal(format!("Serialization error: {}", e)))?;
156 S::vld_parse_value(&json).map_err(|e| vld_status(&e))?;
157 Ok(())
158}
159
160// ========================= Metadata validation ===============================
161
162/// Validate gRPC request metadata against a vld schema.
163///
164/// Metadata keys are converted from `kebab-case` to `snake_case`
165/// (e.g. `x-request-id` → `x_request_id`); keys containing `_` are ignored
166/// (see [`crate::common::headers_to_json`]) and binary (`-bin`) keys are
167/// skipped.
168/// Values are coerced with [`crate::common::coerce_value`] (lossless:
169/// `"42"` → number, `"true"` → boolean, `"01234"` stays a string) and
170/// validated with [`crate::common::parse_coerced`], so a string field still
171/// accepts `"42"`.
172///
173/// # Example
174///
175/// ```ignore
176/// vld::schema! {
177/// #[derive(Debug, Clone)]
178/// struct AuthMeta {
179/// authorization: String => vld::string().min(1),
180/// }
181/// }
182///
183/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
184/// let auth: AuthMeta = vld_web::tonic::validate_metadata(&request)?;
185/// println!("auth: {}", auth.authorization);
186/// Ok(Response::new(()))
187/// }
188/// ```
189pub fn validate_metadata<T, M>(request: &Request<M>) -> Result<T, Status>
190where
191 T: VldParse,
192{
193 let json =
194 crate::common::headers_to_json(request.metadata().iter().filter_map(|kv| match kv {
195 tonic::metadata::KeyAndValueRef::Ascii(key, value) => {
196 Some((key.as_str(), value.as_encoded_bytes()))
197 }
198 tonic::metadata::KeyAndValueRef::Binary(_, _) => None,
199 }));
200 crate::common::parse_coerced::<T>(&json).map_err(|e| vld_status(&e))
201}
202
203/// The validated metadata, stored in the request extensions by
204/// [`metadata_interceptor`] (a wrapper, so it never collides with other
205/// extensions of type `T`).
206#[derive(Debug, Clone)]
207pub struct Validated<T>(pub T);
208
209impl<T> std::ops::Deref for Validated<T> {
210 type Target = T;
211 fn deref(&self) -> &T {
212 &self.0
213 }
214}
215
216/// Retrieve a validated metadata struct from request extensions.
217///
218/// Use after [`metadata_interceptor`] has stored the [`Validated<T>`].
219///
220/// # Example
221///
222/// ```ignore
223/// async fn handler(request: Request<MyMessage>) -> Result<Response<()>, Status> {
224/// let auth = vld_web::tonic::validated_metadata::<AuthMeta, _>(&request)
225/// .ok_or_else(|| Status::unauthenticated("Missing auth"))?;
226/// Ok(Response::new(()))
227/// }
228/// ```
229pub fn validated_metadata<T, M>(request: &Request<M>) -> Option<T>
230where
231 T: Clone + Send + Sync + 'static,
232{
233 request
234 .extensions()
235 .get::<Validated<T>>()
236 .map(|v| v.0.clone())
237}
238
239// ========================= Interceptor =======================================
240
241/// A tonic interceptor function that validates request metadata.
242///
243/// The validated struct is stored in request extensions as
244/// [`Validated<T>`] and can be retrieved in handlers via
245/// [`validated_metadata`] or `request.extensions().get::<Validated<T>>()`.
246///
247/// # Example
248///
249/// ```ignore
250/// use tonic::transport::Server;
251///
252/// vld::schema! {
253/// #[derive(Debug, Clone)]
254/// struct AuthMeta {
255/// authorization: String => vld::string().min(1),
256/// }
257/// }
258///
259/// Server::builder()
260/// .add_service(MyServiceServer::with_interceptor(
261/// my_service,
262/// vld_web::tonic::metadata_interceptor::<AuthMeta>,
263/// ))
264/// .serve(addr)
265/// .await?;
266/// ```
267pub fn metadata_interceptor<T>(mut request: Request<()>) -> Result<Request<()>, Status>
268where
269 T: VldParse + Clone + Send + Sync + 'static,
270{
271 let validated: T = validate_metadata(&request)?;
272 request.extensions_mut().insert(Validated(validated));
273 Ok(request)
274}
275
276// ========================= Macro =============================================
277
278/// Attach vld validation rules to a protobuf message type.
279///
280/// Generates `validate()` and `is_valid()` inherent methods (via
281/// [`vld::impl_rules!`]) and implements the [`VldMessage`] trait.
282///
283/// # Example
284///
285/// ```ignore
286/// // Protobuf message generated by prost (with serde support)
287/// #[derive(Clone, PartialEq, prost::Message, serde::Serialize)]
288/// pub struct CreateUserRequest {
289/// #[prost(string, tag = "1")]
290/// pub name: String,
291/// #[prost(string, tag = "2")]
292/// pub email: String,
293/// #[prost(int32, tag = "3")]
294/// pub age: i32,
295/// }
296///
297/// vld_web::tonic::impl_validate!(CreateUserRequest {
298/// name => vld::string().min(2).max(50),
299/// email => vld::string().email(),
300/// age => vld::number().int().min(0).max(150),
301/// });
302///
303/// // Now you can use:
304/// // msg.validate()?; — inherent method
305/// // msg.is_valid() — inherent method
306/// // vld_web::tonic::validate(req) — request helper
307/// ```
308#[doc(hidden)]
309#[macro_export]
310macro_rules! __tonic_impl_validate {
311 ($name:ident { $($field:ident => $schema:expr),* $(,)? }) => {
312 ::vld::impl_rules!($name { $($field => $schema),* });
313
314 impl $crate::tonic::VldMessage for $name {
315 fn vld_validate(&self) -> ::std::result::Result<(), ::vld::error::VldError> {
316 self.validate()
317 }
318 }
319 };
320}
321
322#[doc(inline)]
323pub use crate::__tonic_impl_validate as impl_validate;
324
325/// Prelude — import everything you need.
326pub mod prelude {
327 pub use super::{
328 Validated, VldMessage, impl_validate, metadata_interceptor, validate, validate_metadata,
329 validate_ref, validate_with, validate_with_ref, validated_metadata, vld_status,
330 vld_status_with_code,
331 };
332 pub use vld::prelude::*;
333}