Skip to main content

vld_web/
lambda.rs

1#![allow(clippy::result_large_err)]
2//! # `vld_web::lambda` — AWS Lambda integration for `vld`
3//!
4//! Validate API Gateway / ALB / Function URL requests of
5//! [`lambda_http`](https://docs.rs/lambda_http) 1.x, and raw
6//! `lambda_runtime` events, with `vld` schemas (`lambda_http` with its
7//! default features: every event source; `lambda_runtime` is used through
8//! its `lambda_http::lambda_runtime` re-export).
9//!
10//! | Function | Source |
11//! |---|---|
12//! | [`validate_json`] | JSON body (requires a JSON `Content-Type`) |
13//! | [`validate_query`] | `queryStringParameters` ([`RequestExt::query_string_parameters`]) |
14//! | [`validate_path`] | `pathParameters` ([`RequestExt::path_parameters`]) |
15//! | [`error_response`] | the 422 / 415 response for a [`VldHttpError`] |
16//! | [`validate_event`] / [`event_error`] | a raw `LambdaEvent<serde_json::Value>` payload; failures are a [`Diagnostic`] |
17//!
18//! Requests answer with the same bodies and parse parameters by the same
19//! rules as every HTTP module ([error bodies](crate::common#error-bodies)).
20//!
21//! # Example
22//!
23//! ```
24//! use lambda_http::{Body, Error, Request, Response};
25//! use vld_web::lambda::{validate_json, validate_path};
26//!
27//! vld::schema! {
28//!     #[derive(Debug)]
29//!     pub struct UserPath {
30//!         pub id: i64 => vld::number().int().min(1),
31//!     }
32//! }
33//!
34//! vld::schema! {
35//!     #[derive(Debug)]
36//!     pub struct UpdateUser {
37//!         pub name: String => vld::string().min(2),
38//!     }
39//! }
40//!
41//! async fn handler(req: Request) -> Result<Response<Body>, Error> {
42//!     let path: UserPath = match validate_path(&req) {
43//!         Ok(p) => p,
44//!         Err(resp) => return Ok(resp), // 422
45//!     };
46//!     let body: UpdateUser = match validate_json(&req) {
47//!         Ok(b) => b,
48//!         Err(resp) => return Ok(resp), // 422 / 415
49//!     };
50//!     Ok(Response::new(format!("{}: {}", path.id, body.name).into()))
51//! }
52//! // lambda_http::run(lambda_http::service_fn(handler)).await
53//! ```
54//!
55//! Guide: <https://s00d.github.io/vld/integrations/web/lambda>
56use lambda_http::http::{StatusCode, header};
57use lambda_http::lambda_runtime::{Context, Diagnostic, LambdaEvent};
58use lambda_http::{Body, Request, RequestExt, Response};
59use vld::error::VldError;
60use vld::schema::VldParse;
61
62use crate::common::{
63    VldHttpError, parse_coerced, parse_json_body, path_params_to_json, query_string_to_json,
64    require_json_content_type,
65};
66
67/// Validate the JSON body. A missing or non-JSON `Content-Type` is **415**,
68/// malformed JSON and schema errors are **422**.
69pub fn validate_json<T: VldParse>(request: &Request) -> Result<T, Response<Body>> {
70    let content_type = request
71        .headers()
72        .get(header::CONTENT_TYPE)
73        .and_then(|v| v.to_str().ok());
74    require_json_content_type(content_type)
75        .and_then(|()| parse_json_body(request.body()))
76        .and_then(|value| T::vld_parse_value(&value).map_err(VldHttpError::from))
77        .map_err(|e| error_response(&e))
78}
79
80/// Validate the query parameters the event carries
81/// ([`RequestExt::query_string_parameters`]). Repeated keys become arrays
82/// and values are coerced as for every HTTP module's query extractor.
83pub fn validate_query<T: VldParse>(request: &Request) -> Result<T, Response<Body>> {
84    let query: Vec<String> = request
85        .query_string_parameters()
86        .iter()
87        .map(|(k, v)| format!("{}={}", encode(k), encode(v)))
88        .collect();
89    validate_coerced(&query_string_to_json(&query.join("&")))
90}
91
92/// Validate the path parameters API Gateway matched
93/// ([`RequestExt::path_parameters`], already decoded); values are coerced
94/// as for every HTTP module's path extractor.
95pub fn validate_path<T: VldParse>(request: &Request) -> Result<T, Response<Body>> {
96    validate_coerced(&path_params_to_json(request.path_parameters().iter()))
97}
98
99/// The JSON error response for `error`: its status (422 / 415 / 413) and
100/// body. For a plain [`VldError`] use `error_response(&err.into())` (422).
101pub fn error_response(error: &VldHttpError) -> Response<Body> {
102    let mut response = Response::new(Body::from(error.body().to_string()));
103    *response.status_mut() =
104        StatusCode::from_u16(error.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY);
105    response.headers_mut().insert(
106        header::CONTENT_TYPE,
107        header::HeaderValue::from_static("application/json"),
108    );
109    response
110}
111
112/// Validate the payload of a raw `lambda_runtime` event (SQS, EventBridge,
113/// a direct invocation, …) and hand back the payload and its context.
114///
115/// ```ignore
116/// async fn handler(event: LambdaEvent<serde_json::Value>) -> Result<String, Diagnostic> {
117///     let (order, _ctx) = vld_web::lambda::validate_event::<Order>(event)?;
118///     Ok(order.id)
119/// }
120/// ```
121pub fn validate_event<T: VldParse>(
122    event: LambdaEvent<serde_json::Value>,
123) -> Result<(T, Context), Diagnostic> {
124    let LambdaEvent { payload, context } = event;
125    T::vld_parse_value(&payload)
126        .map(|value| (value, context))
127        .map_err(|e| event_error(&e))
128}
129
130/// A [`Diagnostic`] for a failed invocation: `errorType`
131/// `"ValidationError"`, `errorMessage` the HTTP 422 body as JSON text.
132pub fn event_error(error: &VldError) -> Diagnostic {
133    Diagnostic {
134        error_type: "ValidationError".into(),
135        error_message: crate::common::format_vld_error(error).to_string(),
136    }
137}
138
139fn validate_coerced<T: VldParse>(value: &serde_json::Value) -> Result<T, Response<Body>> {
140    parse_coerced(value).map_err(|e| error_response(&e.into()))
141}
142
143/// Percent-encode everything but unreserved characters, so the decoded
144/// parameters survive the round trip through [`query_string_to_json`].
145fn encode(s: &str) -> String {
146    s.bytes()
147        .map(|b| match b {
148            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
149                (b as char).to_string()
150            }
151            _ => format!("%{b:02X}"),
152        })
153        .collect()
154}
155
156/// Prelude — import everything you need.
157pub mod prelude {
158    pub use super::{
159        error_response, event_error, validate_event, validate_json, validate_path, validate_query,
160    };
161    pub use vld::prelude::*;
162}