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, FormValue>);
impl FormData {
pub fn new(map: HashMap<String, FormValue>) -> Self {
Self(map)
}
pub fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).map(FormValue::as_string)
}
pub fn get_all(&self, key: &str) -> Vec<&str> {
self.0.get(key).map(FormValue::as_array).unwrap_or_default()
}
pub fn get_value(&self, key: &str) -> Option<&FormValue> {
self.0.get(key)
}
pub fn contains_key(&self, key: &str) -> bool {
self.0.contains_key(key)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.0.keys().map(|k| k.as_str())
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &FormValue)> {
self.0.iter().map(|(k, v)| (k.as_str(), v))
}
pub fn into_inner(self) -> HashMap<String, FormValue> {
self.0
}
pub fn get_str(&self, key: &str) -> Result<String> {
self.get(key)
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.ok_or_else(|| Error::InvalidInput(format!("Field '{}' is required", key)))
}
pub fn get_int(&self, key: &str) -> Result<i32> {
self.get_as(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_as<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
let value = self.get_str(key)?;
value.trim().parse::<T>().map_err(|_| {
Error::InvalidInput(format!(
"Field '{}' must be a valid {}",
key,
short_type_name::<T>()
))
})
}
pub fn get_str_or(&self, key: &str, default: &str) -> String {
self.get_str(key).unwrap_or_else(|_| default.to_string())
}
pub fn get_int_or(&self, key: &str, default: i32) -> i32 {
self.get_int(key).unwrap_or(default)
}
pub fn get_bool_or(&self, key: &str, default: bool) -> bool {
self.get_bool(key).unwrap_or(default)
}
pub fn get_as_or<T: std::str::FromStr>(&self, key: &str, default: T) -> T {
self.get_as(key).unwrap_or(default)
}
pub fn get_all_as<T: std::str::FromStr>(&self, key: &str) -> Result<Vec<T>> {
self.get_all(key)
.into_iter()
.map(|value| {
value.trim().parse::<T>().map_err(|_| {
Error::InvalidInput(format!(
"Field '{}' must contain only valid {} values",
key,
short_type_name::<T>()
))
})
})
.collect()
}
}
pub(crate) fn short_type_name<T: ?Sized>() -> &'static str {
let full = std::any::type_name::<T>();
full.rsplit("::").next().unwrap_or(full)
}
fn is_websocket_upgrade_headers(method: &str, headers: &HashMap<String, String>) -> bool {
if !method.eq_ignore_ascii_case("GET") {
return false;
}
let has_token = |name: &str, token: &str| {
headers
.get(name)
.map(|value| {
value
.split(',')
.any(|part| part.trim().eq_ignore_ascii_case(token))
})
.unwrap_or(false)
};
has_token("upgrade", "websocket") && has_token("connection", "upgrade")
}
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>>,
upgrade: Option<hyper::upgrade::OnUpgrade>,
duplicate_handshake_header: bool,
}
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()),
upgrade: None,
duplicate_handshake_header: false,
}
}
}
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()),
upgrade: None,
duplicate_handshake_header: false,
}
}
#[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>(
mut 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();
const SINGLETON_HANDSHAKE_HEADERS: [&str; 3] =
["origin", "sec-websocket-key", "sec-websocket-version"];
const LIST_HANDSHAKE_HEADERS: [&str; 3] = [
"connection",
"sec-websocket-protocol",
"sec-websocket-extensions",
];
let mut headers = HashMap::new();
let mut duplicate_handshake_header = false;
for (name, value) in req.headers() {
if let Ok(value_str) = value.to_str() {
let name = name.to_string();
if LIST_HANDSHAKE_HEADERS.contains(&name.as_str()) {
headers
.entry(name)
.and_modify(|existing: &mut String| {
existing.push_str(", ");
existing.push_str(value_str);
})
.or_insert_with(|| value_str.to_string());
continue;
}
let previous = headers.insert(name.clone(), value_str.to_string());
if previous.is_some() && SINGLETON_HANDSHAKE_HEADERS.contains(&name.as_str()) {
duplicate_handshake_header = true;
}
}
}
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 upgrade = if is_websocket_upgrade_headers(&method, &headers)
&& req
.extensions()
.get::<hyper::upgrade::OnUpgrade>()
.is_some()
{
Some(hyper::upgrade::on(&mut req))
} else {
None
};
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,
upgrade,
duplicate_handshake_header,
})
}
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| {
log::debug!("Rejected JSON body: {}", e);
Error::InvalidInput("Invalid JSON body".to_string())
})
}
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_websocket_upgrade(&self) -> bool {
is_websocket_upgrade_headers(&self.method, &self.headers)
}
pub fn has_duplicate_handshake_header(&self) -> bool {
self.duplicate_handshake_header
}
pub(crate) fn take_upgrade(&mut self) -> Option<hyper::upgrade::OnUpgrade> {
self.upgrade.take()
}
#[cfg(test)]
pub(crate) fn has_upgrade(&self) -> bool {
self.upgrade.is_some()
}
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 wants_json(&self) -> bool {
let htmx = self
.headers
.get("hx-request")
.is_some_and(|value| value.eq_ignore_ascii_case("true"));
let classic_xhr = !htmx
&& self
.headers
.get("x-requested-with")
.is_some_and(|value| value.eq_ignore_ascii_case("xmlhttprequest"));
let Some(accept) = self.headers.get("accept") else {
return classic_xhr;
};
let mut json_q = 0.0f32;
let mut html_q = 0.0f32;
let mut named_json_or_html = false;
for entry in accept.split(',') {
let mut fields = entry.split(';');
let Some(media) = fields.next() else {
continue;
};
let media = media.trim().to_ascii_lowercase();
let mut quality = 1.0f32;
for param in fields {
let param = param.trim().to_ascii_lowercase();
if let Some(value) = param.strip_prefix("q=") {
if let Ok(parsed) = value.trim().parse::<f32>() {
if (0.0..=1.0).contains(&parsed) {
quality = parsed;
}
}
}
}
let is_json = media == "application/json" || media.ends_with("+json");
if is_json {
json_q = json_q.max(quality);
named_json_or_html = true;
} else if media == "text/html" || media == "application/xhtml+xml" {
html_q = html_q.max(quality);
named_json_or_html = true;
}
}
if !named_json_or_html {
return classic_xhr;
}
json_q > 0.0 && json_q >= html_q
}
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(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;
fn with_header(name: &str, value: &str) -> Request {
let mut request = Request::new("GET", "/", "HTTP/1.1");
request.headers.insert(name.to_string(), value.to_string());
request
}
#[test]
fn test_wants_json_ranks_json_against_html() {
assert!(!Request::new("GET", "/", "HTTP/1.1").wants_json());
assert!(!with_header("accept", "*/*").wants_json());
assert!(with_header("accept", "application/json").wants_json());
assert!(with_header("accept", "APPLICATION/JSON").wants_json());
assert!(!with_header(
"accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
)
.wants_json());
assert!(with_header("accept", "text/html;q=0.8, application/json;q=0.9").wants_json());
assert!(!with_header("accept", "text/html;q=0.9, application/json;q=0.8").wants_json());
assert!(with_header("accept", "text/html, application/json").wants_json());
assert!(with_header("accept", "application/json;q=banana, text/html;q=0.9").wants_json());
assert!(with_header("accept", "application/json;q=7, text/html;q=0.9").wants_json());
assert!(with_header("accept", "application/json, text/plain, */*").wants_json());
assert!(!with_header("accept", "*/*").wants_json());
assert!(with_header("accept", "application/problem+json").wants_json());
assert!(with_header("accept", "application/x-made-up+json").wants_json());
assert!(with_header("accept", "model/gltf+json").wants_json());
assert!(with_header("accept", "application/vnd.api+json, text/html;q=0.5").wants_json());
assert!(
with_header("x-requested-with", "XMLHttpRequest").wants_json(),
"an XHR asks for JSON even without an Accept header"
);
let mut xhr_wildcard = with_header("x-requested-with", "XMLHttpRequest");
xhr_wildcard
.headers
.insert("accept".to_string(), "*/*".to_string());
assert!(xhr_wildcard.wants_json());
let mut xhr_html = with_header("x-requested-with", "XMLHttpRequest");
xhr_html
.headers
.insert("accept".to_string(), "text/html".to_string());
assert!(!xhr_html.wants_json());
assert!(!with_header("hx-request", "true").wants_json());
let mut htmx_html = with_header("hx-request", "true");
htmx_html
.headers
.insert("accept".to_string(), "text/html".to_string());
assert!(!htmx_html.wants_json());
let mut htmx_json = with_header("hx-request", "true");
htmx_json
.headers
.insert("accept".to_string(), "application/json".to_string());
assert!(
htmx_json.wants_json(),
"an explicit Accept still wins for htmx"
);
let mut htmx_xhr = with_header("hx-request", "true");
htmx_xhr
.headers
.insert("x-requested-with".to_string(), "XMLHttpRequest".to_string());
htmx_xhr
.headers
.insert("accept".to_string(), "*/*".to_string());
assert!(!htmx_xhr.wants_json());
}
#[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(), FormValue::Single("Alice".to_string()));
map.insert("age".to_string(), FormValue::Single("30".to_string()));
map.insert("active".to_string(), FormValue::Single("true".to_string()));
map.insert("empty".to_string(), FormValue::Single("".to_string()));
map.insert("price".to_string(), FormValue::Single("19.99".to_string()));
map.insert(
"tags".to_string(),
FormValue::Multiple(vec!["rust".to_string(), "web".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_eq!(form.get_as::<f64>("price").unwrap(), 19.99);
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!(form.get_bool_or("active", false));
assert!(form.get_bool_or("missing", true));
assert_eq!(form.get_as_or::<f64>("missing", 1.5), 1.5);
}
#[test]
fn test_form_data_keeps_every_value_of_a_multi_value_field() {
let mut map = HashMap::new();
map.insert("k".to_string(), FormValue::Single("v".to_string()));
map.insert(
"tags".to_string(),
FormValue::Multiple(vec!["rust".to_string(), "web".to_string()]),
);
map.insert(
"ids".to_string(),
FormValue::Multiple(vec!["1".to_string(), "2".to_string()]),
);
let form = FormData::new(map);
assert_eq!(form.get("k"), Some("v"));
assert_eq!(form.get_all("k"), vec!["v"]);
assert_eq!(form.get_all("tags"), vec!["rust", "web"]);
assert_eq!(form.get("tags"), Some("rust"));
assert_eq!(form.get_all_as::<i32>("ids").unwrap(), vec![1, 2]);
assert!(form.get_all_as::<i32>("tags").is_err());
assert_eq!(form.get_all("missing"), Vec::<&str>::new());
assert!(form.contains_key("k"));
assert!(!form.contains_key("missing"));
assert_eq!(form.len(), 3);
}
#[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_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, "");
}
}
#[cfg(test)]
mod websocket_upgrade_tests {
use super::*;
use http_body_util::Full;
use hyper::body::Bytes;
use std::sync::Arc;
fn handshake_headers() -> HashMap<String, String> {
let mut headers = HashMap::new();
headers.insert("upgrade".into(), "websocket".into());
headers.insert("connection".into(), "Upgrade".into());
headers
}
#[test]
fn detects_a_plain_handshake() {
assert!(is_websocket_upgrade_headers("GET", &handshake_headers()));
}
#[test]
fn header_tokens_are_case_insensitive() {
let mut headers = HashMap::new();
headers.insert("upgrade".into(), "WebSocket".into());
headers.insert("connection".into(), "UPGRADE".into());
assert!(is_websocket_upgrade_headers("get", &headers));
}
#[test]
fn connection_token_is_found_inside_a_list() {
let mut headers = handshake_headers();
headers.insert("connection".into(), "keep-alive, Upgrade".into());
assert!(is_websocket_upgrade_headers("GET", &headers));
headers.insert("upgrade".into(), "h2c, websocket".into());
assert!(is_websocket_upgrade_headers("GET", &headers));
}
#[test]
fn a_substring_is_not_a_token() {
let mut headers = handshake_headers();
headers.insert("connection".into(), "upgrade-insecure-requests".into());
assert!(!is_websocket_upgrade_headers("GET", &headers));
}
#[test]
fn rejects_non_get_and_missing_headers() {
assert!(
!is_websocket_upgrade_headers("POST", &handshake_headers()),
"a handshake is a GET"
);
let mut only_upgrade = HashMap::new();
only_upgrade.insert("upgrade".into(), "websocket".into());
assert!(!is_websocket_upgrade_headers("GET", &only_upgrade));
let mut only_connection = HashMap::new();
only_connection.insert("connection".into(), "Upgrade".into());
assert!(!is_websocket_upgrade_headers("GET", &only_connection));
let mut other_protocol = handshake_headers();
other_protocol.insert("upgrade".into(), "h2c".into());
assert!(!is_websocket_upgrade_headers("GET", &other_protocol));
assert!(!is_websocket_upgrade_headers("GET", &HashMap::new()));
}
#[tokio::test]
async fn is_websocket_upgrade_reads_the_built_request() {
let hyper_req = hyper::Request::builder()
.method("GET")
.uri("/chat")
.header("upgrade", "websocket")
.header("connection", "Upgrade")
.header("sec-websocket-version", "13")
.body(Full::new(Bytes::new()))
.unwrap();
let request = Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
.await
.unwrap();
assert!(request.is_websocket_upgrade());
}
#[tokio::test]
async fn no_upgrade_handle_without_a_real_connection() {
let hyper_req = hyper::Request::builder()
.method("GET")
.uri("/chat")
.header("upgrade", "websocket")
.header("connection", "Upgrade")
.body(Full::new(Bytes::new()))
.unwrap();
let mut request =
Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
.await
.unwrap();
assert!(request.is_websocket_upgrade());
assert!(!request.has_upgrade());
assert!(request.take_upgrade().is_none());
}
#[tokio::test]
async fn ordinary_requests_carry_no_upgrade_handle() {
let hyper_req = hyper::Request::builder()
.method("GET")
.uri("/chat")
.body(Full::new(Bytes::new()))
.unwrap();
let request = Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
.await
.unwrap();
assert!(!request.is_websocket_upgrade());
assert!(!request.has_upgrade());
}
#[test]
fn hand_built_requests_default_to_no_upgrade() {
let request = Request::new("GET", "/chat", "HTTP/1.1");
assert!(!request.has_upgrade());
assert!(!Request::default().has_upgrade());
}
}