Skip to main content

vld_web/
common.rs

1//! Shared HTTP helpers for the `vld` web integrations.
2//!
3//! The common parsing helpers and the shared [`VldHttpError`] type used by
4//! every framework module of this crate.
5//!
6//! Applications normally use it through a framework module. Use it
7//! directly to write an adapter for another framework or to build the same
8//! error body by hand. It is framework-agnostic: no HTTP framework or `http`
9//! crate dependency.
10//!
11//! Guide: <https://s00d.github.io/vld/integrations/web/common>
12//! (the rules below, per framework:
13//! <https://s00d.github.io/vld/integrations/web/overview>).
14//!
15//! # Example
16//!
17//! ```
18//! use vld_web::common::{parse_json_body, require_json_content_type, VldHttpError};
19//!
20//! vld::schema! {
21//!     #[derive(Debug)]
22//!     pub struct User {
23//!         pub name: String => vld::string().min(2),
24//!     }
25//! }
26//!
27//! fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
28//!     require_json_content_type(content_type)?; // 415
29//!     let value = parse_json_body(body)?;       // 422 on malformed JSON
30//!     Ok(User::parse_value(&value)?)            // 422 on validation errors
31//! }
32//!
33//! let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
34//! assert_eq!(err.status(), 422);
35//! assert_eq!(err.body()["issues"][0]["code"], "too_small");
36//! assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);
37//!
38//! // Text sources (query, form, path, headers, cookies) use `parse_coerced`.
39//! vld::schema! {
40//!     #[derive(Debug)]
41//!     pub struct Search {
42//!         pub q: String => vld::string(),
43//!         pub page: i64 => vld::number().int().min(1),
44//!         pub tags: Vec<String> => vld::array(vld::string()),
45//!     }
46//! }
47//!
48//! let value = vld_web::common::query_string_to_json("q=123&page=2&tags=a");
49//! let s: Search = vld_web::common::parse_coerced(&value).unwrap();
50//! assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));
51//! ```
52//!
53//! # Value semantics (all adapters)
54//!
55//! - Query strings and form bodies: repeated keys (`a=1&a=2`) and `a[]=1`
56//!   become arrays; `?flag` and `?x=` become `""`.
57//! - Values are coerced with [`coerce_value`], which never loses information.
58//! - Coerced sources are validated with [`parse_coerced`]: a coerced number /
59//!   boolean is turned back into text where the schema expects a string
60//!   (`?q=123` into `vld::string()` is `"123"`), and a single value is
61//!   wrapped into an array where the schema expects one (`?tags=a`).
62//! - JSON body extractors require a JSON `Content-Type` (`application/json`
63//!   or `application/*+json`, see [`is_json_content_type`]) and form
64//!   extractors `application/x-www-form-urlencoded`
65//!   ([`require_form_content_type`]); a missing or different type is **415**
66//!   `{"error": "Unsupported Media Type", "message": ...}`.
67//! - Malformed bodies (JSON, non-UTF-8 forms, more than [`MAX_FORM_FIELDS`]
68//!   form fields) → **422** with the [`ValidationErrorBody`] shape; oversized
69//!   bodies → **413** `{"error": "Payload too large"}`.
70//! - Header names containing `_` are ignored (see [`headers_to_json`]); all
71//!   `Cookie` headers are read and the first occurrence of a cookie name wins
72//!   (see [`cookie_headers_to_json`]).
73//!
74//! # Error bodies
75//!
76//! | Status | Body |
77//! |---|---|
78//! | 422 | `{"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}` |
79//! | 413 | `{"error": "Payload too large"}` |
80//! | 415 | `{"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."}` |
81//!
82//! `path` is `""` for the root (e.g. malformed JSON), `.field` for fields and
83//! `[0]` for array items (`.items[0].name`); `code` is
84//! [`IssueCode::key()`](vld::error::IssueCode::key).
85/// Coerce a raw string value (query, form, path, header, cookie) into JSON:
86/// the core [`vld::schema::coerce_text`] (same rules, one implementation).
87pub use vld::schema::coerce_text as coerce_value;
88pub use vld::schema::parse_coerced;
89
90/// Default max request body size (2 MiB — same as axum `DefaultBodyLimit`).
91///
92/// Every adapter applies it to JSON and form bodies unless a limit is
93/// configured ([`VldBodyLimit`], the framework's own setting, or a
94/// constructor argument; per adapter:
95/// <https://s00d.github.io/vld/integrations/web/overview#body-limits>).
96pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
97
98/// Max number of `&`-separated fields in a form body ([`parse_form_body`]).
99///
100/// Caps the memory a small body can expand into (`a&a&a&…` turns every two
101/// bytes into a JSON value); more fields are a 422 parse error.
102pub const MAX_FORM_FIELDS: usize = 1000;
103
104/// Body size limit in bytes, registered as request/app data for the adapters
105/// without a framework-native body limit setting (`vld-actix` `app_data`,
106/// `vld-ntex` app state, `vld-poem` `.data(..)`; `vld-rama` has its own
107/// extension type).
108///
109/// Without it those adapters use [`DEFAULT_BODY_LIMIT`].
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct VldBodyLimit(pub usize);
112
113/// Parse a URL query string (or `application/x-www-form-urlencoded` body)
114/// into a `serde_json::Map`.
115///
116/// - keys and values are form-decoded ([`url_decode`]) and values coerced via
117///   [`coerce_value`];
118/// - a key without `=` (`?flag`) yields `""`, like `URLSearchParams`;
119/// - a repeated key (`a=1&a=2`) yields an array `[1, 2]`;
120/// - a key ending in `[]` (`a[]=1`) always yields an array under `a`.
121pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
122    use serde_json::Value;
123    let mut map = serde_json::Map::new();
124
125    for pair in query.split('&').filter(|p| !p.is_empty()) {
126        let (key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
127        let mut key = url_decode(key);
128        let value = coerce_value(&url_decode(raw_value));
129
130        let force_array = key.ends_with("[]");
131        if force_array {
132            key.truncate(key.len() - 2);
133        }
134
135        match map.get_mut(&key) {
136            Some(Value::Array(items)) => items.push(value),
137            Some(existing) => {
138                let first = existing.take();
139                *existing = Value::Array(vec![first, value]);
140            }
141            None if force_array => {
142                map.insert(key, Value::Array(vec![value]));
143            }
144            None => {
145                map.insert(key, value);
146            }
147        }
148    }
149
150    map
151}
152
153/// Parse a URL query string into a `serde_json::Value::Object`.
154///
155/// Convenience wrapper around [`parse_query_string`].
156pub fn query_string_to_json(query: &str) -> serde_json::Value {
157    serde_json::Value::Object(parse_query_string(query))
158}
159
160/// Build a JSON object from a `Cookie` header value.
161///
162/// Cookie names are used as-is. Values are unquoted (`"abc"` → `abc`),
163/// percent-decoded (`+` is kept) and coerced via [`coerce_value`].
164///
165/// When a name repeats (`sid=legit; sid=evil`) the **first** occurrence
166/// wins, as in most cookie parsers (browsers send the most specific path
167/// first); letting a later one win enables cookie tossing from a sibling
168/// subdomain.
169pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
170    let mut map = serde_json::Map::new();
171
172    for cookie in cookie_header.split(';') {
173        let cookie = cookie.trim();
174        if cookie.is_empty() {
175            continue;
176        }
177        let (name, value) = cookie.split_once('=').unwrap_or((cookie, ""));
178        let value = value.trim();
179        let value = value
180            .strip_prefix('"')
181            .and_then(|v| v.strip_suffix('"'))
182            .unwrap_or(value);
183        map.entry(name.trim())
184            .or_insert_with(|| coerce_value(&percent_decode(value)));
185    }
186
187    serde_json::Value::Object(map)
188}
189
190/// Build a JSON object from **all** `Cookie` header values of a request.
191///
192/// HTTP/2 clients may send one `Cookie` header per cookie, so the values are
193/// joined with `"; "` before [`cookies_to_json`] (the first occurrence of a
194/// name wins). Non-UTF-8 bytes become `U+FFFD`.
195pub fn cookie_headers_to_json<'a, I>(values: I) -> serde_json::Value
196where
197    I: IntoIterator<Item = &'a [u8]>,
198{
199    let values: Vec<_> = values.into_iter().map(String::from_utf8_lossy).collect();
200    cookies_to_json(&values.join("; "))
201}
202
203/// Build a JSON object from HTTP header name/value pairs.
204///
205/// - names are lowercased and `-` becomes `_` (`X-Request-Id` → `x_request_id`);
206/// - names that already contain `_` (`x_user`) are **skipped**: a client
207///   could otherwise fill the `x_user` field past a proxy that strips only
208///   `X-User` (nginx, for one, also drops such names by default);
209/// - non-UTF-8 bytes become `U+FFFD` instead of silently dropping the header;
210/// - repeated headers are joined with `", "` (RFC 9110 §5.3);
211/// - the joined value is coerced via [`coerce_value`].
212pub fn headers_to_json<'a, I>(headers: I) -> serde_json::Value
213where
214    I: IntoIterator<Item = (&'a str, &'a [u8])>,
215{
216    let mut map = serde_json::Map::new();
217    let mut raw: Vec<(String, String)> = Vec::new();
218    for (name, value) in headers {
219        if name.contains('_') {
220            continue;
221        }
222        let key = name.to_ascii_lowercase().replace('-', "_");
223        let value = String::from_utf8_lossy(value);
224        match raw.iter_mut().find(|(k, _)| *k == key) {
225            Some((_, v)) => {
226                v.push_str(", ");
227                v.push_str(&value);
228            }
229            None => raw.push((key, value.into_owned())),
230        }
231    }
232    for (k, v) in raw {
233        map.insert(k, coerce_value(&v));
234    }
235    serde_json::Value::Object(map)
236}
237
238/// Build a JSON object from already-decoded path parameters, coercing each
239/// value via [`coerce_value`].
240pub fn path_params_to_json<'a, I>(params: I) -> serde_json::Value
241where
242    I: IntoIterator<Item = (&'a str, &'a str)>,
243{
244    serde_json::Value::Object(
245        params
246            .into_iter()
247            .map(|(k, v)| (k.to_string(), coerce_value(v)))
248            .collect(),
249    )
250}
251
252/// Parse an `application/x-www-form-urlencoded` body.
253///
254/// Fails with a 422 parse error when the body is not valid UTF-8 or has more
255/// than [`MAX_FORM_FIELDS`] fields.
256pub fn parse_form_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
257    let s = std::str::from_utf8(body)
258        .map_err(|_| VldHttpError::parse("Form body is not valid UTF-8"))?;
259    if s.split('&').filter(|p| !p.is_empty()).count() > MAX_FORM_FIELDS {
260        return Err(VldHttpError::parse(format!(
261            "Too many form fields (max {MAX_FORM_FIELDS})"
262        )));
263    }
264    Ok(query_string_to_json(s))
265}
266
267/// Parse a JSON body; malformed JSON is a 422 parse error.
268pub fn parse_json_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
269    serde_json::from_slice(body).map_err(|e| VldHttpError::parse(format!("Invalid JSON: {e}")))
270}
271
272/// The media type without parameters, trimmed and lowercased
273/// (`Application/JSON; charset=utf-8` → `application/json`).
274fn media_type_essence(content_type: &str) -> String {
275    content_type
276        .split(';')
277        .next()
278        .unwrap_or("")
279        .trim()
280        .to_ascii_lowercase()
281}
282
283/// `true` for `application/json` and any `application/<x>+json` media type
284/// with a non-empty `<x>` (case-insensitive; parameters such as
285/// `; charset=utf-8` are ignored, even malformed ones).
286pub fn is_json_content_type(content_type: &str) -> bool {
287    let essence = media_type_essence(content_type);
288    essence == "application/json"
289        || essence
290            .strip_prefix("application/")
291            .and_then(|s| s.strip_suffix("+json"))
292            .is_some_and(|prefix| !prefix.is_empty())
293}
294
295/// Check the `Content-Type` of a JSON body: `Ok` for JSON media types
296/// ([`is_json_content_type`]), otherwise a **415** error (also when the
297/// header is missing or not valid UTF-8).
298pub fn require_json_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
299    match content_type {
300        Some(ct) if is_json_content_type(ct) => Ok(()),
301        _ => Err(VldHttpError::unsupported_media_type()),
302    }
303}
304
305/// Check the `Content-Type` of a form body: `Ok` for
306/// `application/x-www-form-urlencoded` (case-insensitive, parameters
307/// allowed), otherwise a **415** error (also when the header is missing or
308/// not valid UTF-8).
309pub fn require_form_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
310    match content_type.map(media_type_essence) {
311        Some(ct) if ct == "application/x-www-form-urlencoded" => Ok(()),
312        _ => Err(VldHttpError::unsupported_form_media_type()),
313    }
314}
315
316// ---------------------------------------------------------------------------
317// Shared error type
318// ---------------------------------------------------------------------------
319
320/// Framework-independent error produced by all `vld` HTTP adapters.
321///
322/// | Constructor | Status | Body |
323/// |---|---|---|
324/// | [`validation`](Self::validation) / [`parse`](Self::parse) | 422 | [`ValidationErrorBody`] |
325/// | [`payload_too_large`](Self::payload_too_large) | 413 | [`ErrorBody`] |
326/// | [`unsupported_media_type`](Self::unsupported_media_type) / [`unsupported_form_media_type`](Self::unsupported_form_media_type) | 415 | [`ErrorWithMessage`] |
327///
328/// Adapters only convert [`status`](Self::status) and [`body`](Self::body)
329/// into their framework's response type.
330#[derive(Debug, Clone)]
331pub struct VldHttpError {
332    status: u16,
333    error: vld::error::VldError,
334}
335
336impl VldHttpError {
337    /// 422 — schema validation failed.
338    pub fn validation(error: vld::error::VldError) -> Self {
339        Self { status: 422, error }
340    }
341
342    /// 422 — the input could not be parsed (malformed JSON, bad UTF-8, ...).
343    pub fn parse(message: impl Into<String>) -> Self {
344        Self::validation(vld::error::VldError::single(
345            vld::error::IssueCode::ParseError,
346            message.into(),
347        ))
348    }
349
350    /// 413 — the body exceeds the size limit.
351    ///
352    /// [`error`](Self::error) holds a single `ParseError` issue
353    /// `"Payload too large"` (also what `Display` prints).
354    pub fn payload_too_large() -> Self {
355        Self {
356            status: 413,
357            error: vld::error::VldError::single(
358                vld::error::IssueCode::ParseError,
359                "Payload too large",
360            ),
361        }
362    }
363
364    /// 415 — a JSON body was sent without a JSON `Content-Type`.
365    ///
366    /// [`error`](Self::error) holds a single `ParseError` issue with
367    /// [`UNSUPPORTED_MEDIA_TYPE_MESSAGE`].
368    pub fn unsupported_media_type() -> Self {
369        Self::unsupported(UNSUPPORTED_MEDIA_TYPE_MESSAGE)
370    }
371
372    /// 415 — a form body was sent without
373    /// `Content-Type: application/x-www-form-urlencoded`.
374    ///
375    /// [`error`](Self::error) holds a single `ParseError` issue with
376    /// [`UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE`].
377    pub fn unsupported_form_media_type() -> Self {
378        Self::unsupported(UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE)
379    }
380
381    fn unsupported(message: &str) -> Self {
382        Self {
383            status: 415,
384            error: vld::error::VldError::single(vld::error::IssueCode::ParseError, message),
385        }
386    }
387
388    /// HTTP status code (422, 413 or 415).
389    #[must_use]
390    pub fn status(&self) -> u16 {
391        self.status
392    }
393
394    /// The underlying validation error.
395    pub fn error(&self) -> &vld::error::VldError {
396        &self.error
397    }
398
399    /// Consume and return the underlying validation error.
400    pub fn into_error(self) -> vld::error::VldError {
401        self.error
402    }
403
404    /// JSON response body for this error.
405    pub fn body(&self) -> serde_json::Value {
406        match self.status {
407            413 => format_payload_too_large(),
408            415 => serde_json::to_value(ErrorWithMessage {
409                error: "Unsupported Media Type".into(),
410                message: self
411                    .error
412                    .issues
413                    .first()
414                    .map_or(UNSUPPORTED_MEDIA_TYPE_MESSAGE, |i| i.message.as_str())
415                    .into(),
416            })
417            .expect("ErrorWithMessage serialization cannot fail"),
418            _ => format_vld_error(&self.error),
419        }
420    }
421}
422
423impl From<vld::error::VldError> for VldHttpError {
424    fn from(error: vld::error::VldError) -> Self {
425        Self::validation(error)
426    }
427}
428
429impl std::fmt::Display for VldHttpError {
430    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
431        match self.status {
432            413 => f.write_str("Payload too large"),
433            415 => f.write_str("Unsupported Media Type"),
434            _ => write!(f, "Validation failed: {}", self.error),
435        }
436    }
437}
438
439impl std::error::Error for VldHttpError {}
440
441// ---------------------------------------------------------------------------
442// Error response schemas (defined via vld::schema!)
443// ---------------------------------------------------------------------------
444
445use serde::Serialize;
446
447vld::schema! {
448    /// Simple error body: `{ "error": "..." }`.
449    ///
450    /// Used for generic HTTP errors such as "Payload too large",
451    /// "Not Found", "Method Not Allowed", etc.
452    #[derive(Debug, Clone, Serialize)]
453    pub struct ErrorBody {
454        /// Short error title.
455        pub error: String => vld::string(),
456    }
457}
458
459vld::schema! {
460    /// Error body with a message: `{ "error": "...", "message": "..." }`.
461    ///
462    /// The **415** body ([`VldHttpError::unsupported_media_type`],
463    /// [`VldHttpError::unsupported_form_media_type`]).
464    #[derive(Debug, Clone, Serialize)]
465    pub struct ErrorWithMessage {
466        /// Short error title.
467        pub error: String   => vld::string(),
468        /// Details.
469        pub message: String => vld::string(),
470    }
471}
472
473vld::schema! {
474    /// A single validation issue:
475    /// `{ "path": "...", "message": "...", "code": "..." }` (`code` is
476    /// [`IssueCode::key()`](vld::error::IssueCode::key)).
477    #[derive(Debug, Clone, Serialize)]
478    pub struct ValidationIssue {
479        /// Path of the invalid value (`.user.email`, `[0]`).
480        pub path: String    => vld::string(),
481        /// Human-readable message.
482        pub message: String => vld::string(),
483        /// Issue code key (`too_small`, `invalid_string`, …).
484        pub code: String    => vld::string(),
485    }
486}
487
488vld::schema! {
489    /// Validation error response body:
490    /// `{ "error": "Validation failed", "issues": [...] }`.
491    #[derive(Debug, Clone, Serialize)]
492    pub struct ValidationErrorBody {
493        /// Always `"Validation failed"`.
494        pub error: String => vld::string(),
495        /// Every issue found.
496        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
497    }
498}
499
500// ---------------------------------------------------------------------------
501// Formatting helpers
502// ---------------------------------------------------------------------------
503
504/// `.user.name`, `.items[0]` — spelled out instead of relying on
505/// `PathSegment`'s `Display` so the wire format stays stable.
506fn format_path(path: &[vld::error::PathSegment]) -> String {
507    use std::fmt::Write;
508    use vld::error::PathSegment;
509    let mut out = String::new();
510    for seg in path {
511        let _ = match seg {
512            PathSegment::Field(name) => write!(out, ".{name}"),
513            PathSegment::Index(idx) => write!(out, "[{idx}]"),
514        };
515    }
516    out
517}
518
519/// Format a [`VldError`](vld::error::VldError) into a list of
520/// [`ValidationIssue`] structs.
521pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
522    err.issues
523        .iter()
524        .map(|i| ValidationIssue {
525            path: format_path(&i.path),
526            message: i.message.clone(),
527            code: i.code.key().to_string(),
528        })
529        .collect()
530}
531
532/// Format a [`VldError`](vld::error::VldError) into a JSON object with
533/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
534///
535/// Internally constructs a [`ValidationErrorBody`] and serializes it.
536pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
537    let body = ValidationErrorBody {
538        error: "Validation failed".into(),
539        issues: format_issues(err),
540    };
541    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
542}
543
544/// Decode a form/query component: `+` → space, then [`percent_decode`].
545pub fn url_decode(input: &str) -> String {
546    percent_decode(&input.replace('+', " "))
547}
548
549/// Percent-decode a URL component (path segment, cookie value); `+` is kept.
550///
551/// Only `%` followed by exactly two hex digits is decoded; anything else is
552/// kept literally. Decoded bytes are read as UTF-8 (`%C3%A9` → `é`); invalid
553/// sequences become `U+FFFD`.
554pub fn percent_decode(input: &str) -> String {
555    let bytes = input.as_bytes();
556    let hex = |i: usize| bytes.get(i).and_then(|&b| (b as char).to_digit(16));
557    let mut out = Vec::with_capacity(bytes.len());
558    let mut i = 0;
559    while i < bytes.len() {
560        if bytes[i] == b'%'
561            && let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2))
562        {
563            out.push((h * 16 + l) as u8);
564            i += 3;
565            continue;
566        }
567        out.push(bytes[i]);
568        i += 1;
569    }
570    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
571}
572
573// ---------------------------------------------------------------------------
574// Standard HTTP error response helpers
575// ---------------------------------------------------------------------------
576
577/// Build a JSON error body for payloads that exceed the size limit.
578///
579/// Returns `{ "error": "Payload too large" }`.
580///
581/// Internally constructs an [`ErrorBody`] and serializes it.
582pub fn format_payload_too_large() -> serde_json::Value {
583    format_generic_error("Payload too large")
584}
585
586/// Message of the 415 body and error for JSON extractors.
587pub const UNSUPPORTED_MEDIA_TYPE_MESSAGE: &str =
588    "Expected Content-Type: application/json (or application/*+json)";
589
590/// Message of the 415 body and error for form extractors.
591pub const UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE: &str =
592    "Expected Content-Type: application/x-www-form-urlencoded";
593
594/// Build the JSON error body for a non-JSON `Content-Type`.
595///
596/// Returns `{ "error": "Unsupported Media Type", "message": "Expected Content-Type: ..." }`.
597pub fn format_unsupported_media_type() -> serde_json::Value {
598    VldHttpError::unsupported_media_type().body()
599}
600
601/// Build a generic JSON error body with a custom error string.
602///
603/// Returns `{ "error": "<error>" }`.
604///
605/// Internally constructs an [`ErrorBody`] and serializes it.
606pub fn format_generic_error(error: &str) -> serde_json::Value {
607    serde_json::to_value(ErrorBody {
608        error: error.into(),
609    })
610    .expect("ErrorBody serialization cannot fail")
611}