pub use vld::schema::coerce_text as coerce_value;
pub use vld::schema::parse_coerced;
pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
pub const MAX_FORM_FIELDS: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VldBodyLimit(pub usize);
pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
use serde_json::Value;
let mut map = serde_json::Map::new();
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
let mut key = url_decode(key);
let value = coerce_value(&url_decode(raw_value));
let force_array = key.ends_with("[]");
if force_array {
key.truncate(key.len() - 2);
}
match map.get_mut(&key) {
Some(Value::Array(items)) => items.push(value),
Some(existing) => {
let first = existing.take();
*existing = Value::Array(vec![first, value]);
}
None if force_array => {
map.insert(key, Value::Array(vec![value]));
}
None => {
map.insert(key, value);
}
}
}
map
}
pub fn query_string_to_json(query: &str) -> serde_json::Value {
serde_json::Value::Object(parse_query_string(query))
}
pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
let mut map = serde_json::Map::new();
for cookie in cookie_header.split(';') {
let cookie = cookie.trim();
if cookie.is_empty() {
continue;
}
let (name, value) = cookie.split_once('=').unwrap_or((cookie, ""));
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.unwrap_or(value);
map.entry(name.trim())
.or_insert_with(|| coerce_value(&percent_decode(value)));
}
serde_json::Value::Object(map)
}
pub fn cookie_headers_to_json<'a, I>(values: I) -> serde_json::Value
where
I: IntoIterator<Item = &'a [u8]>,
{
let values: Vec<_> = values.into_iter().map(String::from_utf8_lossy).collect();
cookies_to_json(&values.join("; "))
}
pub fn headers_to_json<'a, I>(headers: I) -> serde_json::Value
where
I: IntoIterator<Item = (&'a str, &'a [u8])>,
{
let mut map = serde_json::Map::new();
let mut raw: Vec<(String, String)> = Vec::new();
for (name, value) in headers {
if name.contains('_') {
continue;
}
let key = name.to_ascii_lowercase().replace('-', "_");
let value = String::from_utf8_lossy(value);
match raw.iter_mut().find(|(k, _)| *k == key) {
Some((_, v)) => {
v.push_str(", ");
v.push_str(&value);
}
None => raw.push((key, value.into_owned())),
}
}
for (k, v) in raw {
map.insert(k, coerce_value(&v));
}
serde_json::Value::Object(map)
}
pub fn path_params_to_json<'a, I>(params: I) -> serde_json::Value
where
I: IntoIterator<Item = (&'a str, &'a str)>,
{
serde_json::Value::Object(
params
.into_iter()
.map(|(k, v)| (k.to_string(), coerce_value(v)))
.collect(),
)
}
pub fn parse_form_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
let s = std::str::from_utf8(body)
.map_err(|_| VldHttpError::parse("Form body is not valid UTF-8"))?;
if s.split('&').filter(|p| !p.is_empty()).count() > MAX_FORM_FIELDS {
return Err(VldHttpError::parse(format!(
"Too many form fields (max {MAX_FORM_FIELDS})"
)));
}
Ok(query_string_to_json(s))
}
pub fn parse_json_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
serde_json::from_slice(body).map_err(|e| VldHttpError::parse(format!("Invalid JSON: {e}")))
}
fn media_type_essence(content_type: &str) -> String {
content_type
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
}
pub fn is_json_content_type(content_type: &str) -> bool {
let essence = media_type_essence(content_type);
essence == "application/json"
|| essence
.strip_prefix("application/")
.and_then(|s| s.strip_suffix("+json"))
.is_some_and(|prefix| !prefix.is_empty())
}
pub fn require_json_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
match content_type {
Some(ct) if is_json_content_type(ct) => Ok(()),
_ => Err(VldHttpError::unsupported_media_type()),
}
}
pub fn require_form_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
match content_type.map(media_type_essence) {
Some(ct) if ct == "application/x-www-form-urlencoded" => Ok(()),
_ => Err(VldHttpError::unsupported_form_media_type()),
}
}
#[derive(Debug, Clone)]
pub struct VldHttpError {
status: u16,
error: vld::error::VldError,
}
impl VldHttpError {
pub fn validation(error: vld::error::VldError) -> Self {
Self { status: 422, error }
}
pub fn parse(message: impl Into<String>) -> Self {
Self::validation(vld::error::VldError::single(
vld::error::IssueCode::ParseError,
message.into(),
))
}
pub fn payload_too_large() -> Self {
Self {
status: 413,
error: vld::error::VldError::single(
vld::error::IssueCode::ParseError,
"Payload too large",
),
}
}
pub fn unsupported_media_type() -> Self {
Self::unsupported(UNSUPPORTED_MEDIA_TYPE_MESSAGE)
}
pub fn unsupported_form_media_type() -> Self {
Self::unsupported(UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE)
}
fn unsupported(message: &str) -> Self {
Self {
status: 415,
error: vld::error::VldError::single(vld::error::IssueCode::ParseError, message),
}
}
#[must_use]
pub fn status(&self) -> u16 {
self.status
}
pub fn error(&self) -> &vld::error::VldError {
&self.error
}
pub fn into_error(self) -> vld::error::VldError {
self.error
}
pub fn body(&self) -> serde_json::Value {
match self.status {
413 => format_payload_too_large(),
415 => serde_json::to_value(ErrorWithMessage {
error: "Unsupported Media Type".into(),
message: self
.error
.issues
.first()
.map_or(UNSUPPORTED_MEDIA_TYPE_MESSAGE, |i| i.message.as_str())
.into(),
})
.expect("ErrorWithMessage serialization cannot fail"),
_ => format_vld_error(&self.error),
}
}
}
impl From<vld::error::VldError> for VldHttpError {
fn from(error: vld::error::VldError) -> Self {
Self::validation(error)
}
}
impl std::fmt::Display for VldHttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.status {
413 => f.write_str("Payload too large"),
415 => f.write_str("Unsupported Media Type"),
_ => write!(f, "Validation failed: {}", self.error),
}
}
}
impl std::error::Error for VldHttpError {}
use serde::Serialize;
vld::schema! {
#[derive(Debug, Clone, Serialize)]
pub struct ErrorBody {
pub error: String => vld::string(),
}
}
vld::schema! {
#[derive(Debug, Clone, Serialize)]
pub struct ErrorWithMessage {
pub error: String => vld::string(),
pub message: String => vld::string(),
}
}
vld::schema! {
#[derive(Debug, Clone, Serialize)]
pub struct ValidationIssue {
pub path: String => vld::string(),
pub message: String => vld::string(),
pub code: String => vld::string(),
}
}
vld::schema! {
#[derive(Debug, Clone, Serialize)]
pub struct ValidationErrorBody {
pub error: String => vld::string(),
pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
}
}
fn format_path(path: &[vld::error::PathSegment]) -> String {
use std::fmt::Write;
use vld::error::PathSegment;
let mut out = String::new();
for seg in path {
let _ = match seg {
PathSegment::Field(name) => write!(out, ".{name}"),
PathSegment::Index(idx) => write!(out, "[{idx}]"),
};
}
out
}
pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
err.issues
.iter()
.map(|i| ValidationIssue {
path: format_path(&i.path),
message: i.message.clone(),
code: i.code.key().to_string(),
})
.collect()
}
pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
let body = ValidationErrorBody {
error: "Validation failed".into(),
issues: format_issues(err),
};
serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
}
pub fn url_decode(input: &str) -> String {
percent_decode(&input.replace('+', " "))
}
pub fn percent_decode(input: &str) -> String {
let bytes = input.as_bytes();
let hex = |i: usize| bytes.get(i).and_then(|&b| (b as char).to_digit(16));
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}
pub fn format_payload_too_large() -> serde_json::Value {
format_generic_error("Payload too large")
}
pub const UNSUPPORTED_MEDIA_TYPE_MESSAGE: &str =
"Expected Content-Type: application/json (or application/*+json)";
pub const UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE: &str =
"Expected Content-Type: application/x-www-form-urlencoded";
pub fn format_unsupported_media_type() -> serde_json::Value {
VldHttpError::unsupported_media_type().body()
}
pub fn format_generic_error(error: &str) -> serde_json::Value {
serde_json::to_value(ErrorBody {
error: error.into(),
})
.expect("ErrorBody serialization cannot fail")
}