use super::ClientError;
use axum::http::{HeaderMap, HeaderName, HeaderValue};
pub(super) fn origin(value: &str) -> Result<url::Url, ClientError> {
if value.len() > 2048 || value.trim() != value || value.chars().any(char::is_control) {
return Err(ClientError::Configuration);
}
let url = url::Url::parse(value).map_err(|_| ClientError::Configuration)?;
if !matches!(url.scheme(), "http" | "https")
|| !url.has_host()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.path() != "/"
|| url.query().is_some()
|| url.fragment().is_some()
|| url.port_or_known_default().is_none_or(|port| port == 0)
{
return Err(ClientError::Configuration);
}
Ok(url)
}
pub(super) fn resolve(origin: &url::Url, path: &str) -> Result<url::Url, ClientError> {
if path.len() > 8192
|| !path.starts_with('/')
|| path.starts_with("//")
|| path.contains(['\\', '#'])
|| path.chars().any(char::is_control)
{
return Err(ClientError::Destination);
}
let target = origin.join(path).map_err(|_| ClientError::Destination)?;
if origin.origin() != target.origin()
|| !target.username().is_empty()
|| target.password().is_some()
{
return Err(ClientError::Destination);
}
Ok(target)
}
pub(super) fn header(headers: &mut HeaderMap, name: &str, value: &str) -> Result<(), ClientError> {
if name.len() > 128 {
return Err(ClientError::Configuration);
}
let name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| ClientError::Configuration)?;
if matches!(
name.as_str(),
"host"
| "content-length"
| "transfer-encoding"
| "connection"
| "upgrade"
| "proxy-authorization"
| "traceparent"
| "tracestate"
| "baggage"
) || value.len() > 4096
{
return Err(ClientError::Configuration);
}
let mut value = HeaderValue::from_str(value).map_err(|_| ClientError::Configuration)?;
value.set_sensitive(true);
let mut updated = headers.clone();
updated.insert(name, value);
validate_headers(&updated)?;
*headers = updated;
Ok(())
}
pub(super) fn validate_headers(headers: &HeaderMap) -> Result<(), ClientError> {
if headers.len() > 32
|| headers
.iter()
.map(|(name, value)| name.as_str().len() + value.as_bytes().len())
.sum::<usize>()
> 16384
{
return Err(ClientError::Configuration);
}
Ok(())
}
#[cfg(test)]
#[path = "target_test.rs"]
mod target_test;