use crate::error::{Error, Result};
use crate::http::files::{FileCollection, MultipartParser};
use http_body_util::BodyExt;
use hyper::Request as HyperRequest;
use ipnetwork::IpNetwork;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use simd_json;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::Path;
use std::sync::Arc;
use url::Url;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FormValue {
Single(String),
Multiple(Vec<String>),
}
impl FormValue {
pub fn as_string(&self) -> &str {
match self {
FormValue::Single(s) => s,
FormValue::Multiple(v) => v.first().map(|s| s.as_str()).unwrap_or(""),
}
}
pub fn as_array(&self) -> Vec<&str> {
match self {
FormValue::Single(s) => vec![s.as_str()],
FormValue::Multiple(v) => v.iter().map(|s| s.as_str()).collect(),
}
}
pub fn is_array(&self) -> bool {
matches!(self, FormValue::Multiple(_))
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(transparent)]
pub struct FormData(HashMap<String, String>);
impl std::ops::Deref for FormData {
type Target = HashMap<String, String>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FormData {
pub fn new(map: HashMap<String, String>) -> Self {
Self(map)
}
pub fn get_str(&self, key: &str) -> Result<String> {
self.0
.get(key)
.filter(|s| !s.is_empty())
.cloned()
.ok_or_else(|| Error::InvalidInput(format!("Field '{}' is required", key)))
}
pub fn get_int(&self, key: &str) -> Result<i32> {
self.get_str(key)?
.parse()
.map_err(|_| Error::InvalidInput(format!("Field '{}' must be a valid integer", key)))
}
pub fn get_bool(&self, key: &str) -> Result<bool> {
let value = self.get_str(key)?;
Ok(matches!(
value.as_str(),
"true" | "1" | "yes" | "on" | "checked"
))
}
pub fn get_str_or(&self, key: &str, default: &str) -> String {
self.0
.get(key)
.filter(|s| !s.is_empty())
.cloned()
.unwrap_or_else(|| default.to_string())
}
pub fn get_int_or(&self, key: &str, default: i32) -> i32 {
self.get_str(key)
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(default)
}
pub fn get_bool_or(&self, key: &str, default: bool) -> bool {
self.get_str(key)
.map(|s| matches!(s.as_str(), "true" | "1" | "yes" | "on" | "checked"))
.unwrap_or(default)
}
}
pub struct Request {
pub method: String,
pub uri: String,
pub headers: HashMap<String, String>,
pub params: HashMap<String, String>,
pub query: HashMap<String, String>,
body_bytes: Vec<u8>,
files: Option<FileCollection>,
multipart_form_data: Option<HashMap<String, String>>,
cookies_cache: once_cell::sync::OnceCell<HashMap<String, String>>,
peer_addr: Option<SocketAddr>,
trusted_proxies: Arc<Vec<IpNetwork>>,
}
impl Default for Request {
fn default() -> Self {
Self {
method: String::new(),
uri: String::new(),
headers: HashMap::new(),
params: HashMap::new(),
query: HashMap::new(),
body_bytes: Vec::new(),
files: None,
multipart_form_data: None,
cookies_cache: once_cell::sync::OnceCell::new(),
peer_addr: None,
trusted_proxies: Arc::new(Vec::new()),
}
}
}
impl Request {
#[doc(hidden)]
pub fn new(method: &str, uri: &str, _version: &str) -> Self {
Request {
method: method.to_string(),
uri: uri.to_string(),
headers: HashMap::new(),
params: HashMap::new(),
query: HashMap::new(),
body_bytes: Vec::new(),
files: None,
multipart_form_data: None,
cookies_cache: once_cell::sync::OnceCell::new(),
peer_addr: None,
trusted_proxies: Arc::new(Vec::new()),
}
}
#[doc(hidden)]
#[cfg(test)]
pub fn set_body(&mut self, body: Vec<u8>) {
self.body_bytes = body;
}
pub async fn from_hyper<B>(req: HyperRequest<B>) -> Result<Self>
where
B: hyper::body::Body,
B::Error: std::fmt::Display,
{
Self::from_hyper_with_connection(req, None, Arc::new(Vec::new())).await
}
pub async fn from_hyper_with_connection<B>(
req: HyperRequest<B>,
peer_addr: Option<SocketAddr>,
trusted_proxies: Arc<Vec<IpNetwork>>,
) -> Result<Self>
where
B: hyper::body::Body,
B::Error: std::fmt::Display,
{
let method = req.method().to_string();
let uri = req.uri().to_string();
let mut headers = HashMap::new();
for (name, value) in req.headers() {
if let Ok(value_str) = value.to_str() {
headers.insert(name.to_string(), value_str.to_string());
}
}
let query = Self::parse_query(req.uri().query().unwrap_or(""));
let content_length = req
.headers()
.get("content-length")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok())
.unwrap_or(0);
let has_transfer_encoding = req.headers().contains_key("transfer-encoding");
let body_hint = req.body().size_hint();
let has_body = content_length > 0 || has_transfer_encoding || body_hint.lower() > 0;
let body_bytes = if has_body {
req.into_body()
.collect()
.await
.map_err(|e| Error::Internal(format!("failed to read request body: {e}")))?
.to_bytes()
.to_vec()
} else {
Vec::new()
};
Ok(Request {
method,
uri,
headers,
params: HashMap::new(), query,
body_bytes,
files: None, multipart_form_data: None, cookies_cache: once_cell::sync::OnceCell::new(),
peer_addr,
trusted_proxies,
})
}
pub fn body_as_json<T: DeserializeOwned>(&self) -> Result<T> {
let mut body_bytes = self.body_bytes.clone();
simd_json::from_slice(&mut body_bytes)
.map_err(|e| Error::internal(format!("Failed to parse JSON: {}", e)))
}
pub fn body_as_form(&mut self) -> Result<HashMap<String, String>> {
if let Some(ref form) = self.multipart_form_data {
return Ok(form.clone());
}
if self
.headers
.get("content-type")
.map(|v| v.starts_with("multipart/form-data"))
== Some(true)
{
self.parse_files()?;
if let Some(ref form) = self.multipart_form_data {
return Ok(form.clone());
}
}
let body_str = String::from_utf8_lossy(&self.body_bytes);
Ok(Self::parse_query(&body_str))
}
pub fn body_as_form_data(&mut self) -> Result<HashMap<String, FormValue>> {
if let Some(ref form) = self.multipart_form_data {
return Ok(form
.iter()
.map(|(key, value)| (key.clone(), FormValue::Single(value.clone())))
.collect());
}
if self
.headers
.get("content-type")
.map(|v| v.starts_with("multipart/form-data"))
== Some(true)
{
self.parse_files()?;
if let Some(ref form) = self.multipart_form_data {
return Ok(form
.iter()
.map(|(key, value)| (key.clone(), FormValue::Single(value.clone())))
.collect());
}
}
let body_str = match std::str::from_utf8(&self.body_bytes) {
Ok(s) => s,
Err(_) => {
return Ok(Self::parse_query_with_arrays(&String::from_utf8_lossy(
&self.body_bytes,
)))
}
};
Ok(Self::parse_query_with_arrays(body_str))
}
pub fn body_as_string(&self) -> String {
String::from_utf8_lossy(&self.body_bytes).to_string()
}
fn parse_query(query: &str) -> HashMap<String, String> {
let mut result = HashMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
if key.is_empty() {
continue;
}
if let (Some(decoded_key), Some(decoded_value)) =
(urlencoding::decode(key), urlencoding::decode(value))
{
if !decoded_key.is_empty() {
result.insert(decoded_key.to_string(), decoded_value.to_string());
}
}
}
result
}
fn parse_query_with_arrays(query: &str) -> HashMap<String, FormValue> {
let mut result: HashMap<String, FormValue> = HashMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
if key.is_empty() {
continue;
}
if let (Some(decoded_key), Some(decoded_value)) =
(urlencoding::decode(key), urlencoding::decode(value))
{
if decoded_key.is_empty() {
continue;
}
let (actual_key, is_array) = if decoded_key.ends_with("[]") {
let key_len = decoded_key.len();
(decoded_key[..key_len - 2].to_string(), true)
} else {
(decoded_key.to_string(), false)
};
if actual_key.is_empty() {
continue;
}
let decoded_value_str = decoded_value.to_string();
match result.entry(actual_key) {
std::collections::hash_map::Entry::Vacant(e) => {
if is_array {
e.insert(FormValue::Multiple(vec![decoded_value_str]));
} else {
e.insert(FormValue::Single(decoded_value_str));
}
}
std::collections::hash_map::Entry::Occupied(mut e) => {
match e.get_mut() {
FormValue::Single(existing) => {
let existing_value = std::mem::take(existing);
*e.get_mut() =
FormValue::Multiple(vec![existing_value, decoded_value_str]);
}
FormValue::Multiple(vec) => {
vec.push(decoded_value_str);
}
}
}
}
}
}
result
}
pub fn client_ip(&self) -> String {
if self.should_trust_forwarded_headers() {
if let Some(forwarded) = self.headers.get("x-forwarded-for") {
let forwarded_ips: Vec<IpAddr> = forwarded
.split(',')
.filter_map(|ip| ip.trim().parse::<IpAddr>().ok())
.collect();
if !forwarded_ips.is_empty() {
if let Some(ip) = forwarded_ips
.iter()
.rev()
.find(|ip| !self.is_trusted_proxy_ip(**ip))
{
return ip.to_string();
}
return forwarded_ips[0].to_string();
}
}
if let Some(real_ip) = self.headers.get("x-real-ip") {
if let Ok(real_ip) = real_ip.parse::<IpAddr>() {
return real_ip.to_string();
}
}
}
self.peer_addr
.map(|addr| addr.ip().to_string())
.unwrap_or_else(|| "127.0.0.1".to_string())
}
pub fn user_agent(&self) -> Option<&str> {
self.headers.get("user-agent").map(|s| s.as_str())
}
pub fn is_mobile(&self) -> bool {
if let Some(ua) = self.user_agent() {
let ua_lower = ua.to_lowercase();
ua_lower.contains("mobile")
|| ua_lower.contains("android")
|| ua_lower.contains("iphone")
|| ua_lower.contains("ipad")
|| ua_lower.contains("blackberry")
|| ua_lower.contains("windows phone")
} else {
false
}
}
pub fn is_robot(&self) -> bool {
if let Some(ua) = self.user_agent() {
let ua_lower = ua.to_lowercase();
ua_lower.contains("bot")
|| ua_lower.contains("crawler")
|| ua_lower.contains("spider")
|| ua_lower.contains("scraper")
|| ua_lower.contains("googlebot")
|| ua_lower.contains("bingbot")
|| ua_lower.contains("facebookexternalhit")
|| ua_lower.contains("twitterbot")
} else {
false
}
}
pub fn is_secure(&self) -> bool {
if self.should_trust_forwarded_headers() {
if let Some(proto) = self.headers.get("x-forwarded-proto") {
return proto
.split(',')
.next()
.map(|value| value.trim().eq_ignore_ascii_case("https"))
.unwrap_or(false);
}
}
self.uri.starts_with("https://")
}
pub fn is_xhr(&self) -> bool {
if let Some(xhr_header) = self.headers.get("x-requested-with") {
if xhr_header.to_lowercase() == "xmlhttprequest" {
return true;
}
}
if let Some(hx_request) = self.headers.get("hx-request") {
if hx_request.to_lowercase() == "true" {
return true;
}
}
false
}
pub fn language(&self) -> Option<&str> {
if let Some(accept_lang) = self.headers.get("accept-language") {
accept_lang
.split(',')
.next()
.and_then(|lang| lang.split(';').next())
.map(|lang| lang.trim())
} else {
None
}
}
pub fn referrer(&self) -> Option<&str> {
self.headers.get("referer").map(|s| s.as_str())
}
pub fn files(&mut self) -> Result<&FileCollection> {
if self.files.is_none() {
self.parse_files()?;
}
Ok(self.files.as_ref().unwrap())
}
pub fn file(&mut self, field_name: &str) -> Result<Option<&crate::http::files::UploadedFile>> {
Ok(self.files()?.get(field_name))
}
fn parse_files(&mut self) -> Result<()> {
if let Some(content_type) = self.headers.get("content-type") {
if content_type.starts_with("multipart/form-data") {
if let Some(boundary) = self.extract_boundary(content_type) {
let (files, form_data) = MultipartParser::parse(&self.body_bytes, &boundary)?;
self.multipart_form_data = Some(form_data);
self.files = Some(files);
return Ok(());
}
return Err(Error::InvalidInput(
"Invalid multipart/form-data Content-Type: missing or malformed boundary"
.to_string(),
));
}
}
self.files = Some(FileCollection::new());
self.multipart_form_data = None;
Ok(())
}
fn extract_boundary(&self, content_type: &str) -> Option<String> {
for part in content_type.split(';').skip(1) {
let part = part.trim();
if let Some((name, value)) = part.split_once('=') {
if name.trim().eq_ignore_ascii_case("boundary") {
let boundary = value.trim().trim_matches('"');
if !boundary.is_empty()
&& !boundary
.chars()
.any(|ch| ch.is_control() || ch.is_whitespace())
{
return Some(boundary.to_string());
}
}
}
}
None
}
pub fn cookie(&self, name: &str) -> Option<String> {
self.cookies().get(name).cloned()
}
pub fn cookies(&self) -> &HashMap<String, String> {
self.cookies_cache.get_or_init(|| {
self.headers
.get("cookie")
.map(|h| Self::parse_cookies(h))
.unwrap_or_default()
})
}
pub fn host(&self) -> Option<&str> {
self.headers.get("host").map(|s| s.as_str())
}
pub fn hostname(&self, path: Option<&str>) -> String {
let origin = self
.request_origin()
.or_else(|| self.configured_origin())
.unwrap_or_else(|| "http://localhost".to_string());
if let Some(path) = path {
let path = if path.starts_with('/') {
path
} else {
&format!("/{}", path)
};
format!("{}{}", origin.trim_end_matches('/'), path)
} else {
origin
}
}
fn request_origin(&self) -> Option<String> {
let host = if self.should_trust_forwarded_headers() {
self.headers
.get("x-forwarded-host")
.map(|value| value.split(',').next().unwrap_or(value).trim())
.filter(|value| !value.is_empty())
.or_else(|| {
self.headers.get("forwarded").and_then(|value| {
value.split(';').find_map(|part| {
let part = part.trim();
part.strip_prefix("host=")
.map(|host| host.trim_matches('"').trim())
.filter(|host| !host.is_empty())
})
})
})
.or_else(|| self.host())
} else {
self.host()
}?;
let scheme = if self.is_secure() { "https" } else { "http" };
Some(format!("{}://{}", scheme, host))
}
fn configured_origin(&self) -> Option<String> {
if let Some(public_url) = crate::configuration::CONF::get_string("server.public_url") {
if let Some(origin) = Self::normalize_origin(&public_url) {
return Some(origin);
}
}
let host = crate::configuration::CONF::get_string("server.host")?;
let port = crate::configuration::CONF::get::<u16>("server.port")
.unwrap_or(if self.is_secure() { 443 } else { 80 });
let scheme = if self.is_secure()
|| crate::configuration::CONF::get_bool("server.ssl_enabled").unwrap_or(false)
{
"https"
} else {
"http"
};
let default_port = match scheme {
"https" => 443,
_ => 80,
};
let port_suffix = if port == default_port {
String::new()
} else {
format!(":{}", port)
};
Some(format!("{}://{}{}", scheme, host, port_suffix))
}
pub fn path(&self) -> &str {
if let Some(path_start) = self.uri.find("://") {
let after_scheme = &self.uri[path_start + 3..];
if let Some(path_start) = after_scheme.find('/') {
let path_with_query = &after_scheme[path_start..];
if let Some(query_start) = path_with_query.find('?') {
&path_with_query[..query_start]
} else {
path_with_query
}
} else {
"/"
}
} else {
if let Some(query_start) = self.uri.find('?') {
&self.uri[..query_start]
} else {
&self.uri
}
}
}
pub fn extension(&self) -> Option<&str> {
let path = self.path();
Path::new(path).extension().and_then(|ext| ext.to_str())
}
pub fn is_authorized(&self) -> bool {
self.headers.get("authorization").is_some()
}
pub fn authorization(&self) -> Option<&str> {
self.headers.get("authorization").map(|s| s.as_str())
}
pub fn is_proxy(&self) -> bool {
self.should_trust_forwarded_headers()
&& (self.headers.contains_key("x-forwarded-for")
|| self.headers.contains_key("x-real-ip")
|| self.headers.contains_key("x-forwarded-proto")
|| self.headers.contains_key("x-forwarded-host")
|| self.headers.contains_key("forwarded"))
}
pub fn is_static_file(&self) -> bool {
if let Some(ext) = self.extension() {
matches!(
ext.to_lowercase().as_str(),
"css"
| "js"
| "jpg"
| "jpeg"
| "png"
| "gif"
| "svg"
| "webp"
| "ico"
| "woff"
| "woff2"
| "ttf"
| "eot"
| "pdf"
| "zip"
| "txt"
| "xml"
| "json"
| "csv"
| "mp3"
| "mp4"
| "webm"
| "html"
| "htm"
| "map"
)
} else {
false
}
}
pub fn subdomain(&self) -> Option<String> {
if let Some(host) = self.host() {
let host = if let Some(port_pos) = host.find(':') {
&host[..port_pos]
} else {
host
};
let parts: Vec<&str> = host.split('.').collect();
if parts.len() > 2 {
let subdomain_parts = &parts[..parts.len() - 2];
if !subdomain_parts.is_empty() {
Some(subdomain_parts.join("."))
} else {
None
}
} else {
None
}
} else {
None
}
}
pub fn split(&self) -> Vec<&str> {
self.path()
.trim_start_matches('/')
.trim_end_matches('/')
.split('/')
.filter(|s| !s.is_empty())
.collect()
}
pub fn csrf(&self) -> String {
Self::generate_csrf_token()
}
pub(crate) fn generate_csrf_token() -> String {
use rand::{thread_rng, Rng};
let token_bytes: Vec<u8> = (0..32).map(|_| thread_rng().gen::<u8>()).collect();
Self::base64_encode(&token_bytes)
}
fn parse_cookies(cookie_header: &str) -> HashMap<String, String> {
let mut cookies = HashMap::new();
for cookie_pair in cookie_header.split(';') {
let cookie_pair = cookie_pair.trim();
if let Some((name, value)) = cookie_pair.split_once('=') {
let name = name.trim().to_string();
let value = value.trim().to_string();
cookies.insert(name, value);
}
}
cookies
}
fn should_trust_forwarded_headers(&self) -> bool {
self.peer_addr
.map(|addr| self.is_trusted_proxy_ip(addr.ip()))
.unwrap_or(false)
}
fn is_trusted_proxy_ip(&self, ip: IpAddr) -> bool {
self.trusted_proxies
.iter()
.any(|network| network.contains(ip))
}
fn normalize_origin(input: &str) -> Option<String> {
let parsed = Url::parse(input).ok()?;
let scheme = parsed.scheme();
let host = parsed.host_str()?;
let default_port = match scheme {
"http" => Some(80),
"https" => Some(443),
_ => None,
};
let port_suffix = match parsed.port() {
Some(port) if Some(port) != default_port => format!(":{}", port),
_ => String::new(),
};
Some(format!("{}://{}{}", scheme, host, port_suffix))
}
fn base64_encode(input: &[u8]) -> String {
const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut result = String::new();
for chunk in input.chunks(3) {
let b1 = chunk[0] as u32;
let b2 = chunk.get(1).copied().unwrap_or(0) as u32;
let b3 = chunk.get(2).copied().unwrap_or(0) as u32;
let combined = (b1 << 16) | (b2 << 8) | b3;
result.push(CHARS[((combined >> 18) & 63) as usize] as char);
result.push(CHARS[((combined >> 12) & 63) as usize] as char);
result.push(if chunk.len() > 1 {
CHARS[((combined >> 6) & 63) as usize] as char
} else {
'='
});
result.push(if chunk.len() > 2 {
CHARS[(combined & 63) as usize] as char
} else {
'='
});
}
result
}
pub fn reset(&mut self) {
self.method.clear();
self.uri.clear();
self.headers.clear();
self.params.clear();
self.query.clear();
self.body_bytes.clear();
self.files = None;
self.multipart_form_data = None;
self.cookies_cache = once_cell::sync::OnceCell::new();
const MAX_CAPACITY: usize = 1024;
if self.headers.capacity() > MAX_CAPACITY {
self.headers = HashMap::new();
}
if self.params.capacity() > MAX_CAPACITY {
self.params = HashMap::new();
}
if self.query.capacity() > MAX_CAPACITY {
self.query = HashMap::new();
}
if self.body_bytes.capacity() > MAX_CAPACITY * 1024 {
self.body_bytes = Vec::new();
}
}
}
mod urlencoding {
use std::borrow::Cow;
pub fn decode(s: &str) -> Option<Cow<'_, str>> {
decode_safe(s).ok()
}
pub fn decode_safe(input: &str) -> Result<Cow<'_, str>, UrlDecodeError> {
if input.len() > MAX_URL_LENGTH {
return Err(UrlDecodeError::TooLong);
}
let mut result = Vec::new();
let mut chars = input.char_indices();
while let Some((i, ch)) = chars.next() {
match ch {
'%' => {
if i + 2 >= input.len() {
return Err(UrlDecodeError::InvalidEncoding);
}
let hex_str = &input[i + 1..i + 3];
if !hex_str.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(UrlDecodeError::InvalidHex);
}
let hex_value =
u8::from_str_radix(hex_str, 16).map_err(|_| UrlDecodeError::InvalidHex)?;
result.push(hex_value);
chars.next();
chars.next();
}
'+' => {
result.push(b' ');
}
c if c.is_ascii() && is_safe_url_char(c) => {
result.push(c as u8);
}
_ => {
return Err(UrlDecodeError::InvalidCharacter);
}
}
}
match String::from_utf8(result) {
Ok(decoded) => {
if decoded
.chars()
.any(|c| c == '\0' || (c.is_control() && !matches!(c, '\n' | '\r' | '\t')))
{
Err(UrlDecodeError::UnsafeByte)
} else if decoded == input {
Ok(Cow::Borrowed(input))
} else {
Ok(Cow::Owned(decoded))
}
}
Err(_) => Err(UrlDecodeError::InvalidUtf8),
}
}
const MAX_URL_LENGTH: usize = 8192;
#[derive(Debug)]
pub enum UrlDecodeError {
TooLong,
InvalidEncoding,
InvalidHex,
UnsafeByte,
InvalidCharacter,
InvalidUtf8,
}
fn is_safe_url_char(c: char) -> bool {
match c {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '.' | '_' | '~' => true,
':' | '/' | '?' | '#' | '[' | ']' | '@' => true,
'!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn test_path_normalizes_origin_and_absolute_forms() {
let h1 = Request::new("GET", "/api/status?x=1", "HTTP/1.1");
assert_eq!(h1.path(), "/api/status");
let h2 = Request::new("GET", "http://127.0.0.1:8000/api/status?x=1", "HTTP/2");
assert_eq!(h2.path(), "/api/status");
let root = Request::new("GET", "http://example.com/", "HTTP/2");
assert_eq!(root.path(), "/");
}
#[test]
fn test_secure_url_decoding() {
use super::urlencoding::decode;
assert_eq!(decode("hello%20world").unwrap(), "hello world");
assert_eq!(decode("test+string").unwrap(), "test string");
assert_eq!(decode("normal_string").unwrap(), "normal_string");
assert_eq!(decode("caf%C3%A9").unwrap(), "café");
assert_eq!(decode("../etc/passwd").unwrap(), "../etc/passwd");
assert_eq!(decode("%2e%2e%2fpasswd").unwrap(), "../passwd");
assert_eq!(decode("%3cscript%3e").unwrap(), "<script>");
assert!(decode("%00null").is_none());
let long_string = "a".repeat(10000);
assert!(decode(&long_string).is_none());
assert!(decode("invalid%GG").is_none());
assert!(decode("incomplete%2").is_none());
assert!(decode("%01%02%03").is_none());
}
#[test]
fn test_url_decode_error_types() {
use super::urlencoding::{decode_safe, UrlDecodeError};
let long_input = "a".repeat(10000);
assert!(matches!(
decode_safe(&long_input),
Err(UrlDecodeError::TooLong)
));
assert!(matches!(
decode_safe("caf%C3%A9"),
Ok(value) if value.as_ref() == "café"
));
assert!(matches!(
decode_safe("invalid%GG"),
Err(UrlDecodeError::InvalidHex)
));
assert!(matches!(
decode_safe("incomplete%2"),
Err(UrlDecodeError::InvalidEncoding)
));
assert!(matches!(
decode_safe("%00test"),
Err(UrlDecodeError::UnsafeByte)
));
assert!(matches!(
decode_safe("%01test"),
Err(UrlDecodeError::UnsafeByte)
));
}
#[test]
fn test_safe_query_parsing() {
let malicious_query = "key1=../passwd&key2=%00null&key3=normal";
let parsed = Request::parse_query(malicious_query);
assert_eq!(parsed.get("key1"), Some(&"../passwd".to_string()));
assert_eq!(parsed.get("key3"), Some(&"normal".to_string()));
assert!(!parsed.contains_key("key2"));
}
#[test]
fn test_parse_query_function() {
let query = Request::parse_query("param=value&other=test&flag");
assert_eq!(query.get("param"), Some(&"value".to_string()));
assert_eq!(query.get("other"), Some(&"test".to_string()));
assert_eq!(query.get("flag"), Some(&"".to_string()));
}
#[test]
fn test_parse_query_skips_invalid_or_empty_keys() {
let query = Request::parse_query("=bad&%00evil=value&ok=1");
assert_eq!(query.get("ok"), Some(&"1".to_string()));
assert!(!query.contains_key(""));
assert_eq!(query.len(), 1);
}
#[test]
fn test_form_data_getters() {
let mut map = HashMap::new();
map.insert("name".to_string(), "Alice".to_string());
map.insert("age".to_string(), "30".to_string());
map.insert("active".to_string(), "true".to_string());
map.insert("empty".to_string(), "".to_string());
let form = FormData::new(map);
assert_eq!(form.get_str("name").unwrap(), "Alice");
assert_eq!(form.get_int("age").unwrap(), 30);
assert!(form.get_bool("active").unwrap());
assert!(form.get_str("missing").is_err());
assert!(form.get_str("empty").is_err());
assert!(form.get_int("name").is_err());
assert_eq!(form.get_str_or("name", "default"), "Alice");
assert_eq!(form.get_str_or("missing", "default"), "default");
assert_eq!(form.get_str_or("empty", "default"), "default");
assert_eq!(form.get_int_or("age", 0), 30);
assert_eq!(form.get_int_or("missing", 42), 42);
assert_eq!(form.get_bool_or("active", false), true);
assert_eq!(form.get_bool_or("missing", true), true);
}
#[test]
fn test_form_data_deref() {
let mut map = HashMap::new();
map.insert("k".to_string(), "v".to_string());
let form = FormData::new(map);
assert_eq!(form.get("k"), Some(&"v".to_string()));
}
#[test]
fn test_form_data_default() {
let form = FormData::default();
assert!(form.is_empty());
}
#[test]
fn test_form_arrays() {
let query = Request::parse_query_with_arrays("tags[]=rust&tags[]=web&tags[]=framework");
assert_eq!(query.len(), 1);
let tags_value = query.get("tags").unwrap();
assert!(tags_value.is_array());
assert_eq!(tags_value.as_array(), vec!["rust", "web", "framework"]);
let query =
Request::parse_query_with_arrays("name=John&hobbies[]=coding&hobbies[]=reading&age=30");
assert_eq!(query.len(), 3);
let name = query.get("name").unwrap();
assert!(!name.is_array());
assert_eq!(name.as_string(), "John");
let hobbies = query.get("hobbies").unwrap();
assert!(hobbies.is_array());
assert_eq!(hobbies.as_array(), vec!["coding", "reading"]);
let age = query.get("age").unwrap();
assert!(!age.is_array());
assert_eq!(age.as_string(), "30");
}
#[test]
fn test_form_value_conversions() {
let single = FormValue::Single("test".to_string());
assert_eq!(single.as_string(), "test");
assert_eq!(single.as_array(), vec!["test"]);
assert!(!single.is_array());
let multiple = FormValue::Multiple(vec![
"one".to_string(),
"two".to_string(),
"three".to_string(),
]);
assert_eq!(multiple.as_string(), "one"); assert_eq!(multiple.as_array(), vec!["one", "two", "three"]);
assert!(multiple.is_array());
let empty_multiple = FormValue::Multiple(vec![]);
assert_eq!(empty_multiple.as_string(), "");
assert_eq!(empty_multiple.as_array(), Vec::<&str>::new());
assert!(empty_multiple.is_array());
}
#[test]
fn test_form_parsing_with_encoding() {
let query = Request::parse_query_with_arrays(
"message=Hello%20World&tags[]=rust%2Blang&tags[]=web%20dev",
);
let message = query.get("message").unwrap();
assert_eq!(message.as_string(), "Hello World");
let tags = query.get("tags").unwrap();
assert_eq!(tags.as_array(), vec!["rust+lang", "web dev"]);
}
#[test]
fn test_multipart_form_data_uses_cached_fields() {
let mut request = Request::default();
request.headers.insert(
"content-type".to_string(),
"multipart/form-data; boundary=boundary123".to_string(),
);
request.set_body(
b"--boundary123\r\n\
Content-Disposition: form-data; name=\"title\"\r\n\r\n\
Hello multipart\r\n\
--boundary123\r\n\
Content-Disposition: form-data; name=\"upload\"; filename=\"test.txt\"\r\n\
Content-Type: text/plain\r\n\r\n\
file contents\r\n\
--boundary123--\r\n"
.to_vec(),
);
let form = request.body_as_form_data().unwrap();
assert_eq!(
form.get("title").map(FormValue::as_string),
Some("Hello multipart")
);
assert!(form.get("upload").is_none());
}
#[test]
fn test_extract_boundary_supports_quoted_values() {
let request = Request::default();
let boundary = request.extract_boundary("multipart/form-data; boundary=\"abc123\"");
assert_eq!(boundary.as_deref(), Some("abc123"));
}
#[test]
fn test_parse_files_errors_on_missing_boundary() {
let mut request = Request::default();
request.headers.insert(
"content-type".to_string(),
"multipart/form-data".to_string(),
);
request.set_body(b"--ignored--".to_vec());
let err = request.files().unwrap_err();
assert!(matches!(err, Error::InvalidInput(_)));
}
#[test]
fn test_form_parsing_malicious_input() {
let query = Request::parse_query("safe=value&bad=../etc/passwd&normal=test");
assert_eq!(query.get("safe"), Some(&"value".to_string()));
assert_eq!(query.get("bad"), Some(&"../etc/passwd".to_string()));
assert_eq!(query.get("normal"), Some(&"test".to_string()));
}
#[test]
fn test_form_arrays_edge_cases() {
let query = Request::parse_query_with_arrays("item=first&item=second&item=third");
let items = query.get("item").unwrap();
assert!(items.is_array());
assert_eq!(items.as_array(), vec!["first", "second", "third"]);
let query = Request::parse_query_with_arrays("empty[]=&empty[]=&filled[]=value");
let empty = query.get("empty").unwrap();
assert!(empty.is_array());
assert_eq!(empty.as_array(), vec!["", ""]);
let filled = query.get("filled").unwrap();
assert_eq!(filled.as_string(), "value");
}
#[test]
fn test_cookie_parsing() {
let mut request = Request::default();
request.headers.insert(
"cookie".to_string(),
"session=abc123; user=john; theme=dark".to_string(),
);
assert_eq!(request.cookie("session"), Some("abc123".to_string()));
assert_eq!(request.cookie("user"), Some("john".to_string()));
assert_eq!(request.cookie("theme"), Some("dark".to_string()));
assert_eq!(request.cookie("nonexistent"), None);
let empty_request = Request::default();
assert_eq!(empty_request.cookie("any"), None);
}
#[test]
fn test_cookies_cache_returns_stable_reference() {
let mut request = Request::default();
request
.headers
.insert("cookie".to_string(), "a=1; b=2; c=3".to_string());
let first = request.cookies() as *const _;
let second = request.cookies() as *const _;
assert_eq!(
first, second,
"cookies() must cache — got different HashMap pointers"
);
assert_eq!(request.cookie("a"), Some("1".to_string()));
assert_eq!(request.cookie("b"), Some("2".to_string()));
assert_eq!(request.cookie("c"), Some("3".to_string()));
let third = request.cookies() as *const _;
assert_eq!(first, third);
}
#[test]
fn test_reset_clears_cookie_cache() {
let mut request = Request::default();
request
.headers
.insert("cookie".to_string(), "session=first".to_string());
assert_eq!(request.cookie("session"), Some("first".to_string()));
request.reset();
request
.headers
.insert("cookie".to_string(), "session=second".to_string());
assert_eq!(request.cookie("session"), Some("second".to_string()));
}
#[test]
fn test_host_and_hostname() {
let mut request = Request::default();
request
.headers
.insert("host".to_string(), "example.com:8080".to_string());
assert_eq!(request.host(), Some("example.com:8080"));
assert_eq!(request.hostname(None), "http://example.com:8080");
assert_eq!(
request.hostname(Some("/api/users")),
"http://example.com:8080/api/users"
);
assert_eq!(
request.hostname(Some("api/users")),
"http://example.com:8080/api/users"
);
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request
.headers
.insert("x-forwarded-proto".to_string(), "https".to_string());
assert_eq!(request.hostname(None), "https://example.com:8080");
let empty_request = Request::default();
assert_eq!(empty_request.host(), None);
assert!(
empty_request.hostname(None).starts_with("http://localhost"),
"fallback hostname should default to localhost when no request host is available"
);
}
#[test]
fn test_path_and_extension() {
let mut request = Request::default();
request.uri = "/api/users.json".to_string();
assert_eq!(request.path(), "/api/users.json");
assert_eq!(request.extension(), Some("json"));
request.uri = "/api/users.json?limit=10&offset=0".to_string();
assert_eq!(request.path(), "/api/users.json");
assert_eq!(request.extension(), Some("json"));
request.uri = "https://example.com:8080/api/users.html?param=value".to_string();
assert_eq!(request.path(), "/api/users.html");
assert_eq!(request.extension(), Some("html"));
request.uri = "/".to_string();
assert_eq!(request.path(), "/");
assert_eq!(request.extension(), None);
request.uri = "/api/users".to_string();
assert_eq!(request.path(), "/api/users");
assert_eq!(request.extension(), None);
request.uri = "https://example.com".to_string();
assert_eq!(request.path(), "/");
assert_eq!(request.extension(), None);
}
#[test]
fn test_authorization() {
let mut request = Request::default();
assert!(!request.is_authorized());
assert_eq!(request.authorization(), None);
request
.headers
.insert("authorization".to_string(), "Bearer token123".to_string());
assert!(request.is_authorized());
assert_eq!(request.authorization(), Some("Bearer token123"));
request.headers.insert(
"authorization".to_string(),
"Basic dXNlcjpwYXNz".to_string(),
);
assert!(request.is_authorized());
assert_eq!(request.authorization(), Some("Basic dXNlcjpwYXNz"));
}
#[test]
fn test_proxy_detection() {
let mut request = Request::default();
assert!(!request.is_proxy());
request
.headers
.insert("x-forwarded-for".to_string(), "192.168.1.1".to_string());
assert!(!request.is_proxy());
request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request
.headers
.insert("x-real-ip".to_string(), "10.0.0.1".to_string());
assert!(request.is_proxy());
request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request
.headers
.insert("x-forwarded-proto".to_string(), "https".to_string());
assert!(request.is_proxy());
request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request.headers.insert(
"forwarded".to_string(),
"for=192.0.2.60;proto=http".to_string(),
);
assert!(request.is_proxy());
}
#[test]
fn test_client_ip_ignores_forwarded_headers_from_untrusted_peer() {
let mut request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.headers.insert(
"x-forwarded-for".to_string(),
"203.0.113.10, 10.0.0.5".to_string(),
);
request
.headers
.insert("x-real-ip".to_string(), "203.0.113.20".to_string());
assert_eq!(request.client_ip(), "10.0.0.5");
}
#[test]
fn test_client_ip_uses_forwarded_headers_from_trusted_peer() {
let mut request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request.headers.insert(
"x-forwarded-for".to_string(),
"203.0.113.10, 10.1.1.1".to_string(),
);
assert_eq!(request.client_ip(), "203.0.113.10");
}
#[test]
fn test_is_secure_ignores_forwarded_proto_from_untrusted_peer() {
let mut request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request
.headers
.insert("x-forwarded-proto".to_string(), "https".to_string());
assert!(!request.is_secure());
}
#[test]
fn test_is_secure_uses_forwarded_proto_from_trusted_peer() {
let mut request = Request::default();
request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
request
.headers
.insert("x-forwarded-proto".to_string(), "https".to_string());
assert!(request.is_secure());
}
#[test]
fn test_static_file_detection() {
let mut request = Request::default();
let static_files = [
"/assets/style.css",
"/js/app.js",
"/images/logo.png",
"/favicon.ico",
"/font.woff2",
"/document.pdf",
"/data.json",
"/video.mp4",
"/map.xml",
];
for file_path in static_files {
request.uri = file_path.to_string();
assert!(
request.is_static_file(),
"Should detect {} as static file",
file_path
);
}
let dynamic_paths = ["/api/users", "/", "/users/123", "/admin/login"];
for path in dynamic_paths {
request.uri = path.to_string();
assert!(
!request.is_static_file(),
"Should not detect {} as static file",
path
);
}
}
#[test]
fn test_subdomain_extraction() {
let mut request = Request::default();
request
.headers
.insert("host".to_string(), "api.example.com".to_string());
assert_eq!(request.subdomain(), Some("api".to_string()));
request
.headers
.insert("host".to_string(), "v1.api.example.com".to_string());
assert_eq!(request.subdomain(), Some("v1.api".to_string()));
request
.headers
.insert("host".to_string(), "example.com".to_string());
assert_eq!(request.subdomain(), None);
request
.headers
.insert("host".to_string(), "api.example.com:8080".to_string());
assert_eq!(request.subdomain(), Some("api".to_string()));
request
.headers
.insert("host".to_string(), "www.example.com".to_string());
assert_eq!(request.subdomain(), Some("www".to_string()));
request.headers.clear();
assert_eq!(request.subdomain(), None);
}
#[test]
fn test_path_split() {
let mut request = Request::default();
request.uri = "/api/v1/users/123".to_string();
assert_eq!(request.split(), vec!["api", "v1", "users", "123"]);
request.uri = "/".to_string();
assert_eq!(request.split(), Vec::<&str>::new());
request.uri = "/api/users/".to_string();
assert_eq!(request.split(), vec!["api", "users"]);
request.uri = "/api/users?limit=10".to_string();
assert_eq!(request.split(), vec!["api", "users"]);
request.uri = "/dashboard".to_string();
assert_eq!(request.split(), vec!["dashboard"]);
}
#[test]
fn test_csrf_token() {
let request = Request::default();
let token1 = request.csrf();
let token2 = request.csrf();
assert_ne!(token1, token2);
assert!(token1
.chars()
.all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '='));
assert!(token2
.chars()
.all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '='));
assert!(token1.len() >= 40);
assert!(token2.len() >= 40);
}
#[test]
fn test_base64_encode() {
let input1 = b"hello";
let encoded1 = Request::base64_encode(input1);
assert_eq!(encoded1, "aGVsbG8=");
let input2 = b"hello world";
let encoded2 = Request::base64_encode(input2);
assert_eq!(encoded2, "aGVsbG8gd29ybGQ=");
let input3 = b"";
let encoded3 = Request::base64_encode(input3);
assert_eq!(encoded3, "");
}
}