Skip to main content

vld_http_common/
lib.rs

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