use bytes::{Bytes, BytesMut};
use crate::body::{BoxBytesStream, RequestBody, ResponseBody};
use crate::error::{Error, Result};
use crate::headers::Headers;
use crate::proxy::{ProxyAuth, ProxyConfig};
use crate::response::Response;
use crate::timeout::TimeoutPhase;
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct ForwardRouteKey {
identity: Vec<u8>,
origin: String,
connect_timeout: Option<std::time::Duration>,
proxy_tls_timeout: Option<std::time::Duration>,
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl ForwardRouteKey {
pub(crate) fn new(
proxy: &ProxyConfig,
origin: &url::Url,
connect_timeout: Option<std::time::Duration>,
proxy_tls_timeout: Option<std::time::Duration>,
) -> Self {
Self {
identity: proxy.connection_identity(),
origin: origin_origin(origin),
connect_timeout,
proxy_tls_timeout,
}
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
fn origin_origin(url: &url::Url) -> String {
match (url.host_str(), url.port_or_known_default()) {
(Some(host), Some(port)) => format!("{}://{host}:{port}", url.scheme()),
_ => url.as_str().to_owned(),
}
}
pub(crate) fn effective_timeout(
deadline: Option<std::time::Instant>,
configured: Option<std::time::Duration>,
) -> Result<Option<std::time::Duration>> {
let now = std::time::Instant::now();
let total = match deadline {
Some(deadline) if deadline > now => Some(deadline.duration_since(now)),
Some(deadline) => {
return Err(Error::Timeout {
phase: TimeoutPhase::Total,
elapsed: now.saturating_duration_since(deadline),
});
}
None => None,
};
Ok(match (configured, total) {
(Some(phase), Some(total)) => Some(phase.min(total)),
(Some(phase), None) => Some(phase),
(None, Some(total)) => Some(total),
(None, None) => None,
})
}
pub(crate) struct ProxyRequestContext<'a> {
pub(crate) remaining_total: Option<std::time::Duration>,
pub(crate) deadline: Option<std::time::Instant>,
pub(crate) connect_timeout: Option<std::time::Duration>,
pub(crate) proxy_connect_timeout: Option<std::time::Duration>,
pub(crate) proxy_tls_timeout: Option<std::time::Duration>,
pub(crate) write_timeout: Option<std::time::Duration>,
pub(crate) read_timeout: Option<std::time::Duration>,
pub(crate) http_version_policy: crate::http_version::HttpVersionPolicy,
pub(crate) origin_tls_config: Option<&'a crate::tls::TlsConfig>,
pub(crate) proxy_tls_config: Option<&'a crate::tls::TlsConfig>,
pub(crate) proxied_target: Option<&'a crate::transport_hints::ResolvedTarget>,
pub(crate) socks_client: Option<crate::transport::TimeoutSocksClient>,
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
pub(crate) forward_client: Option<crate::transport::TimeoutForwardClient>,
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
pub(crate) connect_client: Option<crate::transport::TimeoutConnectClient>,
pub(crate) failure_context: Option<&'a crate::error::RequestFailureContext>,
pub(crate) transport_metrics:
Option<std::sync::Arc<crate::transport::metrics::TransportMetrics>>,
}
pub(crate) enum ProxyIo {
Tcp(tokio::net::TcpStream),
Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
pub(crate) struct ForwardProxyConnection {
inner: tokio::io::BufReader<ProxyIo>,
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl ForwardProxyConnection {
fn new(inner: tokio::io::BufReader<ProxyIo>) -> Self {
Self { inner }
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl tokio::io::AsyncRead for ForwardProxyConnection {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::pin::Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl tokio::io::AsyncWrite for ForwardProxyConnection {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bytes: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
std::pin::Pin::new(&mut self.inner).poll_write(cx, bytes)
}
fn poll_flush(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::pin::Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::pin::Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl hyper_util::client::legacy::connect::Connection for ForwardProxyConnection {
fn connected(&self) -> hyper_util::client::legacy::connect::Connected {
hyper_util::client::legacy::connect::Connected::new().proxy(true)
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[derive(Clone)]
pub(crate) struct ForwardProxyConnector {
proxy: ProxyConfig,
proxy_connect_timeout: Option<std::time::Duration>,
proxy_tls_timeout: Option<std::time::Duration>,
proxy_tls_config: Option<crate::tls::TlsConfig>,
metrics: std::sync::Arc<crate::transport::metrics::TransportMetrics>,
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl ForwardProxyConnector {
pub(crate) fn new(
proxy: ProxyConfig,
proxy_connect_timeout: Option<std::time::Duration>,
proxy_tls_timeout: Option<std::time::Duration>,
metrics: std::sync::Arc<crate::transport::metrics::TransportMetrics>,
) -> Self {
let proxy_tls_config = proxy.proxy_tls_config.clone();
Self {
proxy,
proxy_connect_timeout,
proxy_tls_timeout,
proxy_tls_config,
metrics,
}
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
impl tower_service::Service<http::Uri> for ForwardProxyConnector {
type Response = hyper_util::rt::TokioIo<ForwardProxyConnection>;
type Error = Box<dyn std::error::Error + Send + Sync>;
type Future = std::pin::Pin<
Box<
dyn std::future::Future<Output = std::result::Result<Self::Response, Self::Error>>
+ Send,
>,
>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::result::Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&mut self, _dst: http::Uri) -> Self::Future {
let proxy = self.proxy.clone();
let proxy_connect_timeout = self.proxy_connect_timeout;
let proxy_tls_timeout = self.proxy_tls_timeout;
let proxy_tls_config = self.proxy_tls_config.clone();
let metrics = self.metrics.clone();
Box::pin(async move {
let stream = connect_to_proxy(
&proxy,
proxy_connect_timeout,
proxy_tls_timeout,
None,
proxy_tls_config.as_ref(),
Some(&metrics),
)
.await
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
Ok(hyper_util::rt::TokioIo::new(ForwardProxyConnection::new(
stream,
)))
})
}
}
impl tokio::io::AsyncRead for ProxyIo {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
match &mut *self {
Self::Tcp(stream) => std::pin::Pin::new(stream).poll_read(cx, buf),
Self::Tls(stream) => std::pin::Pin::new(stream.as_mut()).poll_read(cx, buf),
}
}
}
impl tokio::io::AsyncWrite for ProxyIo {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bytes: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
match &mut *self {
Self::Tcp(stream) => std::pin::Pin::new(stream).poll_write(cx, bytes),
Self::Tls(stream) => std::pin::Pin::new(stream.as_mut()).poll_write(cx, bytes),
}
}
fn poll_flush(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
match &mut *self {
Self::Tcp(stream) => std::pin::Pin::new(stream).poll_flush(cx),
Self::Tls(stream) => std::pin::Pin::new(stream.as_mut()).poll_flush(cx),
}
}
fn poll_shutdown(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
match &mut *self {
Self::Tcp(stream) => std::pin::Pin::new(stream).poll_shutdown(cx),
Self::Tls(stream) => std::pin::Pin::new(stream.as_mut()).poll_shutdown(cx),
}
}
}
#[allow(
clippy::too_many_arguments,
reason = "the destination, request line, body, proxy config and transport hints are forwarded unchanged to the SOCKS5, HTTP-forward and CONNECT arms"
)] pub(crate) async fn send_proxy_request(
dest_url: &url::Url,
method: &http::Method,
headers: Headers,
body: RequestBody,
version: http::Version,
proxy_config: &ProxyConfig,
transport_hints: &crate::transport_hints::TransportHints,
ctx: &ProxyRequestContext<'_>,
) -> Result<Response> {
if proxy_config.is_socks() {
return send_socks_request(
dest_url,
method,
headers,
body,
version,
transport_hints,
ctx,
)
.await;
}
match dest_url.scheme() {
"http" => {
send_http_proxy_request(
dest_url,
method,
&headers,
body,
version,
proxy_config,
transport_hints,
ctx,
)
.await
}
"https" => {
super::connect::send_https_connect_request(
dest_url,
method,
&headers,
body,
version,
proxy_config,
transport_hints,
ctx,
)
.await
}
other => Err(Error::Unsupported(format!(
"unsupported destination scheme '{other}' through proxy"
))),
}
}
#[allow(
clippy::too_many_lines,
reason = "proxy connect sequences TCP/DNS/TLS phases with metrics; splitting would obscure the ordered handshake"
)]
pub(crate) async fn connect_to_proxy(
proxy_config: &ProxyConfig,
proxy_connect_timeout: Option<std::time::Duration>,
proxy_tls_timeout: Option<std::time::Duration>,
deadline: Option<std::time::Instant>,
proxy_tls_config: Option<&crate::tls::TlsConfig>,
metrics: Option<&std::sync::Arc<crate::transport::metrics::TransportMetrics>>,
) -> Result<tokio::io::BufReader<ProxyIo>> {
if let Some(m) = metrics {
m.record_proxy_attempt();
}
let proxy_host = proxy_config
.host()
.ok_or_else(|| Error::ProxyConnect("proxy URI has no host".into()))?
.to_owned();
let proxy_port = proxy_config.port()?;
let connect_future = async {
let addrs: Vec<std::net::SocketAddr> =
if let Some(addresses) = proxy_config.resolved_addresses() {
addresses.to_vec()
} else {
tokio::net::lookup_host(format!("{proxy_host}:{proxy_port}"))
.await
.map_err(|e| {
Error::ProxyConnect(format!(
"DNS resolution failed for proxy {proxy_host}:{proxy_port}: {e}"
))
})?
.collect()
};
let mut last_error: Option<String> = None;
let mut connected: Option<tokio::net::TcpStream> = None;
for addr in addrs {
match tokio::net::TcpStream::connect(addr).await {
Ok(stream) => {
stream
.set_nodelay(true)
.map_err(|e| Error::ProxyConnect(format!("failed to set nodelay: {e}")))?;
connected = Some(stream);
break;
}
Err(e) => last_error = Some(e.to_string()),
}
}
connected.ok_or_else(|| {
Error::ProxyConnect(format!(
"TCP connect to proxy {proxy_host}:{proxy_port} failed: {}",
last_error.unwrap_or_else(|| "no addresses resolved".into())
))
})
};
let connect_timeout = effective_timeout(deadline, proxy_connect_timeout)?;
let stream = match connect_timeout {
Some(dur) => {
let start = std::time::Instant::now();
match tokio::time::timeout(dur, connect_future).await {
Ok(Ok(s)) => s,
Ok(Err(e)) => {
if let Some(m) = metrics {
m.record_proxy_failure();
}
return Err(e);
}
Err(_) => {
if let Some(m) = metrics {
m.record_proxy_failure();
}
return Err(Error::Timeout {
phase: TimeoutPhase::ProxyConnect,
elapsed: start.elapsed(),
});
}
}
}
None => match connect_future.await {
Ok(s) => s,
Err(e) => {
if let Some(m) = metrics {
m.record_proxy_failure();
}
return Err(e);
}
},
};
let stream = if proxy_config.scheme() == "https" {
if let Some(m) = metrics {
m.record_proxy_tls_attempt();
}
let rustls_config = build_proxy_tls_config(proxy_tls_config)?;
let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(rustls_config));
let domain = proxy_server_name(&proxy_host)?;
let handshake = connector.connect(domain, stream);
let tls_timeout = effective_timeout(deadline, proxy_tls_timeout)?;
let tls_stream = match tls_timeout {
Some(dur) => {
let start = std::time::Instant::now();
match tokio::time::timeout(dur, handshake).await {
Ok(Ok(stream)) => stream,
Ok(Err(e)) => {
if let Some(m) = metrics {
m.record_proxy_tls_failure();
}
return Err(Error::Tls(format!("proxy TLS handshake failed: {e}")));
}
Err(_) => {
if let Some(m) = metrics {
m.record_proxy_tls_failure();
}
return Err(Error::Timeout {
phase: TimeoutPhase::ProxyTls,
elapsed: start.elapsed(),
});
}
}
}
None => match handshake.await {
Ok(s) => s,
Err(e) => {
if let Some(m) = metrics {
m.record_proxy_tls_failure();
}
return Err(Error::Tls(format!("proxy TLS handshake failed: {e}")));
}
},
};
ProxyIo::Tls(Box::new(tls_stream))
} else {
ProxyIo::Tcp(stream)
};
Ok(tokio::io::BufReader::new(stream))
}
pub(crate) fn build_proxy_tls_config(
proxy_tls_config: Option<&crate::tls::TlsConfig>,
) -> Result<rustls::ClientConfig> {
let http1_only = crate::http_version::HttpVersionPolicyEnabler::from_policy(
crate::http_version::HttpVersionPolicy::Http1Only,
);
if let Some(tc) = proxy_tls_config {
let rc = tc
.build_rustls_config()
.map_err(|e| Error::Tls(format!("failed to build proxy TLS config: {e}")))?;
Ok(crate::client::configure_tls_alpn(rc, http1_only))
} else {
let fallback = crate::tls::TlsConfig::default()
.build_rustls_config()
.map_err(|e| Error::Tls(format!("failed to build proxy TLS config: {e}")))?;
Ok(crate::client::configure_tls_alpn(fallback, http1_only))
}
}
fn proxy_server_name(proxy_host: &str) -> Result<rustls::pki_types::ServerName<'static>> {
crate::transport::direct_connector::tls_server_name(proxy_host)
.map_err(|e| Error::Tls(format!("invalid proxy TLS server name: {e}")))
}
#[allow(
clippy::too_many_lines,
reason = "the legacy fallback remains a bounded compatibility path for unsupported Hyper targets"
)]
#[allow(
clippy::too_many_arguments,
reason = "the forward-proxy path needs the destination, the request line, the body, the proxy config, the transport hints and the phase context together"
)] async fn send_http_proxy_request(
dest_url: &url::Url,
method: &http::Method,
headers: &Headers,
body: RequestBody,
version: http::Version,
proxy_config: &ProxyConfig,
transport_hints: &crate::transport_hints::TransportHints,
ctx: &ProxyRequestContext<'_>,
) -> Result<Response> {
if matches!(
ctx.http_version_policy,
crate::http_version::HttpVersionPolicy::Http2Only
) {
return Err(Error::Unsupported(
"HTTP/2-only policy is not supported through an HTTP forward proxy".into(),
));
}
if let Some(ref target) = transport_hints.target {
crate::pipeline::validate_target(target)?;
let uri = crate::transport_hints::target_extension_str(target)?;
if !(uri.starts_with("http://") || uri.starts_with("https://")) {
return Err(Error::RequestBuild(
"target extension must be absolute-form (http:// or https://) for forward-proxy requests".into(),
));
}
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
if let Some(forward_client) = ctx.forward_client.as_ref() {
return send_http_proxy_request_hyper(
dest_url,
method,
headers,
body,
version,
proxy_config,
transport_hints,
forward_client,
ctx.failure_context,
ctx.read_timeout,
ctx.remaining_total,
)
.await;
}
let mut stream = connect_to_proxy(
proxy_config,
ctx.proxy_connect_timeout,
ctx.proxy_tls_timeout,
ctx.deadline,
ctx.proxy_tls_config,
ctx.transport_metrics.as_ref(),
)
.await?;
let absolute_uri = if let Some(ref target) = transport_hints.target {
crate::transport_hints::target_extension_str(target)?
} else {
dest_url.as_str()
};
let write = write_proxy_request(
&mut stream,
method,
absolute_uri,
version,
headers,
proxy_config.auth(),
proxy_config.proxy_headers(),
body,
);
match effective_timeout(ctx.deadline, ctx.write_timeout)? {
Some(duration) => {
tokio::time::timeout(duration, write)
.await
.map_err(|_| Error::Timeout {
phase: TimeoutPhase::Write,
elapsed: duration,
})??;
}
None => write.await?,
}
let read = read_proxy_response(&mut stream);
let (status, resp_headers, initial_buf, reason_phrase) =
match effective_timeout(ctx.deadline, ctx.read_timeout)? {
Some(duration) => {
tokio::time::timeout(duration, read)
.await
.map_err(|_| Error::Timeout {
phase: TimeoutPhase::Read,
elapsed: duration,
})??
}
None => read.await?,
};
let url = dest_url.clone();
let status = http::StatusCode::from_u16(status)
.map_err(|e| Error::MalformedProxyResponse(format!("invalid status code: {e}")))?;
let mut resp_headers_map = http::HeaderMap::new();
for (name, value) in &resp_headers {
let name = http::HeaderName::from_bytes(name.as_bytes())
.map_err(|e| Error::MalformedProxyResponse(format!("invalid header name: {e}")))?;
let value = http::HeaderValue::from_bytes(value)
.map_err(|e| Error::MalformedProxyResponse(format!("invalid header value: {e}")))?;
resp_headers_map.append(name, value);
}
let stream_reader = stream.into_inner();
let expected_len = response_content_length(&resp_headers);
let body_stream = ProxyResponseStream::new(initial_buf, stream_reader, expected_len);
let body_stream = Box::pin(body_stream) as BoxBytesStream;
let body = ResponseBody::streaming(body_stream);
let mut response = Response::new(status, version, resp_headers_map, url, body);
response.set_wire_reason_phrase(reason_phrase);
Ok(response)
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[allow(
clippy::too_many_arguments,
reason = "the reusable forward client needs the absolute-form destination, the request line, the body, the proxy auth and headers, the transport hints and the failure context"
)]
async fn send_http_proxy_request_hyper(
dest_url: &url::Url,
method: &http::Method,
headers: &Headers,
body: RequestBody,
version: http::Version,
proxy_config: &ProxyConfig,
transport_hints: &crate::transport_hints::TransportHints,
client: &crate::transport::TimeoutForwardClient,
failure_context: Option<&crate::error::RequestFailureContext>,
read_timeout: Option<std::time::Duration>,
remaining_total: Option<std::time::Duration>,
) -> Result<Response> {
let absolute_uri = transport_hints
.target
.as_deref()
.map(|target| crate::transport_hints::target_extension_str(target).map(str::to_owned))
.transpose()?
.unwrap_or_else(|| dest_url.as_str().to_owned());
let uri = absolute_uri
.parse::<http::Uri>()
.map_err(|error| Error::RequestBuild(format!("invalid forward-proxy target: {error}")))?;
let mut request = http::Request::builder()
.method(method)
.uri(uri)
.version(version);
for (name, value) in headers.iter() {
request = request.header(name, value);
}
if let Some(auth) = proxy_config.auth() {
request = request.header("proxy-authorization", auth.header_value());
}
for (name, value) in proxy_config.proxy_headers().iter() {
if name.as_str().eq_ignore_ascii_case("proxy-authorization")
&& proxy_config.auth().is_some()
{
continue;
}
request = request.header(name, value);
}
let request = request
.body(crate::transport::HyperRequestBody::new(
body.into_http_body(),
))
.map_err(|error| Error::RequestBuild(error.to_string()))?;
crate::transport::direct::send_proxy_request(
client,
request,
dest_url.clone(),
transport_hints.trace.as_deref(),
failure_context,
read_timeout,
remaining_total,
)
.await
}
fn push_header_line(out: &mut Vec<u8>, name: &str, value: &[u8]) {
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(b": ");
out.extend_from_slice(value);
out.extend_from_slice(b"\r\n");
}
#[allow(
clippy::too_many_arguments,
reason = "the request line, the body, the origin headers and the proxy-only auth and header channel are all needed to assemble the forward-proxy request head"
)] pub(crate) async fn write_proxy_request<S: tokio::io::AsyncWrite + Unpin>(
stream: &mut S,
method: &http::Method,
uri: &str,
version: http::Version,
headers: &Headers,
proxy_auth: Option<&ProxyAuth>,
proxy_headers: &Headers,
body: RequestBody,
) -> Result<()> {
use tokio::io::AsyncWriteExt;
let chunked_body = matches!(&body, RequestBody::Stream { length: None, .. });
if chunked_body && version != http::Version::HTTP_11 {
return Err(Error::RequestBuild(
"unknown-length proxy request bodies require HTTP/1.1".into(),
));
}
let version_str = match version {
http::Version::HTTP_10 => "HTTP/1.0",
_ => "HTTP/1.1",
};
let mut request = Vec::new();
request.extend_from_slice(format!("{method} {uri} {version_str}\r\n").as_bytes());
if !headers.contains("host") {
if let Ok(parsed) = url::Url::parse(uri) {
let host = if let Some(port) = parsed.port() {
format!("{}:{port}", parsed.host_str().unwrap_or(""))
} else {
parsed.host_str().unwrap_or("").to_string()
};
request.extend_from_slice(format!("Host: {host}\r\n").as_bytes());
}
}
for (name, value) in headers.iter() {
if name.as_str().eq_ignore_ascii_case("proxy-authorization") {
continue;
}
push_header_line(&mut request, name.as_str(), value.as_bytes());
}
for (name, value) in proxy_headers.iter() {
if name.as_str().eq_ignore_ascii_case("proxy-authorization") {
continue;
}
if headers.contains(name.as_str()) {
continue;
}
push_header_line(&mut request, name.as_str(), value.as_bytes());
}
if chunked_body {
let transfer_encoding = headers
.get("transfer-encoding")
.or_else(|| proxy_headers.get("transfer-encoding"));
if let Some(value) = transfer_encoding {
if !value.as_bytes().eq_ignore_ascii_case(b"chunked") {
return Err(Error::RequestBuild(
"unknown-length proxy request bodies require chunked transfer encoding".into(),
));
}
} else {
request.extend_from_slice(b"Transfer-Encoding: chunked\r\n");
}
}
if let Some(auth) = proxy_auth {
request.extend_from_slice(
format!("Proxy-Authorization: {}\r\n", auth.header_value()).as_bytes(),
);
}
request.extend_from_slice(b"\r\n");
if request.len() > crate::headers::MAX_REQUEST_HEADER_BYTES {
return Err(Error::RequestBuild(format!(
"request headers exceed maximum size of {} bytes",
crate::headers::MAX_REQUEST_HEADER_BYTES
)));
}
stream
.write_all(&request)
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write request: {e}")))?;
write_proxy_body(stream, body, chunked_body).await?;
stream
.flush()
.await
.map_err(|e| Error::ProxyConnect(format!("failed to flush: {e}")))?;
Ok(())
}
async fn write_proxy_body<S: tokio::io::AsyncWrite + Unpin>(
stream: &mut S,
body: RequestBody,
chunked: bool,
) -> Result<()> {
use futures_util::StreamExt;
use tokio::io::AsyncWriteExt;
match body {
RequestBody::Empty => {}
RequestBody::Bytes(bytes) => {
stream
.write_all(&bytes)
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
}
RequestBody::Stream {
stream: mut body_stream,
..
} => {
while let Some(chunk) = body_stream.next().await {
let chunk = chunk.map_err(|e| Error::Body(e.to_string()))?;
if chunked {
if chunk.is_empty() {
continue;
}
stream
.write_all(format!("{:X}\r\n", chunk.len()).as_bytes())
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
stream
.write_all(&chunk)
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
stream
.write_all(b"\r\n")
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
} else {
stream
.write_all(&chunk)
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
}
}
if chunked {
stream
.write_all(b"0\r\n\r\n")
.await
.map_err(|e| Error::ProxyConnect(format!("failed to write body: {e}")))?;
}
}
}
Ok(())
}
async fn read_bounded_line<S: tokio::io::AsyncRead + Unpin>(
stream: &mut tokio::io::BufReader<S>,
max_len: usize,
) -> Result<Vec<u8>> {
use tokio::io::AsyncReadExt;
let mut buf = Vec::with_capacity(256);
let mut byte = [0u8; 1];
loop {
let n = stream
.read(&mut byte)
.await
.map_err(|e| Error::ProxyConnect(format!("failed to read proxy response: {e}")))?;
if n == 0 {
return Err(Error::MalformedProxyResponse(
"proxy closed connection before end of line".into(),
));
}
if byte[0] == b'\n' {
break;
}
buf.push(byte[0]);
if buf.len() > max_len {
return Err(Error::MalformedProxyResponse(format!(
"proxy response line exceeded maximum length of {max_len} bytes"
)));
}
}
if buf.last() == Some(&b'\r') {
buf.pop();
}
Ok(buf)
}
fn trim_ows(value: &[u8]) -> &[u8] {
let start = value
.iter()
.position(|byte| !matches!(byte, b' ' | b'\t'))
.unwrap_or(value.len());
let end = value
.iter()
.rposition(|byte| !matches!(byte, b' ' | b'\t'))
.map_or(start, |index| index + 1);
&value[start..end]
}
fn truncate_preview(bytes: &[u8]) -> String {
const MAX_PREVIEW_CHARS: usize = 200;
let preview = String::from_utf8_lossy(bytes);
let mut truncated: String = preview.chars().take(MAX_PREVIEW_CHARS).collect();
if preview.chars().count() > MAX_PREVIEW_CHARS {
truncated.push('…');
}
truncated
}
pub(crate) async fn read_proxy_response<S: tokio::io::AsyncRead + Unpin>(
stream: &mut tokio::io::BufReader<S>,
) -> Result<(u16, Vec<(String, Vec<u8>)>, Vec<u8>, Option<String>)> {
use tokio::io::AsyncBufReadExt;
const MAX_STATUS_LINE_LEN: usize = 4096;
const MAX_HEADER_COUNT: usize = 100;
const MAX_HEADER_LINE_LEN: usize = 8192;
const MAX_TOTAL_HEADER_BYTES: usize = 65536;
let status_line = read_bounded_line(stream, MAX_STATUS_LINE_LEN).await?;
if status_line.is_empty() {
return Err(Error::MalformedProxyResponse(
"proxy closed connection before response".into(),
));
}
let mut parts = status_line.splitn(3, |byte| *byte == b' ');
let _version = parts.next();
let status_code = parts
.next()
.and_then(|s| std::str::from_utf8(s).ok())
.and_then(|s| s.parse::<u16>().ok())
.ok_or_else(|| {
Error::MalformedProxyResponse(format!(
"invalid status line: {}",
truncate_preview(&status_line)
))
})?;
let reason_phrase = parts
.next()
.map(|phrase| String::from_utf8_lossy(phrase).into_owned());
let mut headers = Vec::new();
let mut total_header_bytes: usize = 0;
loop {
let line = read_bounded_line(stream, MAX_HEADER_LINE_LEN).await?;
if line.is_empty() {
break;
}
total_header_bytes = total_header_bytes.checked_add(line.len()).ok_or_else(|| {
Error::MalformedProxyResponse(format!(
"proxy response headers exceeded maximum total size of {MAX_TOTAL_HEADER_BYTES} bytes"
))
})?;
if total_header_bytes > MAX_TOTAL_HEADER_BYTES {
return Err(Error::MalformedProxyResponse(format!(
"proxy response headers exceeded maximum total size of {MAX_TOTAL_HEADER_BYTES} bytes"
)));
}
if headers.len() >= MAX_HEADER_COUNT {
return Err(Error::MalformedProxyResponse(format!(
"proxy response exceeded maximum header count of {MAX_HEADER_COUNT}"
)));
}
let colon = line.iter().position(|byte| *byte == b':').ok_or_else(|| {
Error::MalformedProxyResponse(format!(
"invalid header line: {}",
truncate_preview(&line)
))
})?;
let name = std::str::from_utf8(trim_ows(&line[..colon])).map_err(|_| {
Error::MalformedProxyResponse("proxy response header name is not ASCII".into())
})?;
headers.push((name.to_owned(), trim_ows(&line[colon + 1..]).to_vec()));
}
let mut initial_buf = Vec::new();
let buf_ref = stream.buffer();
if !buf_ref.is_empty() {
initial_buf.extend_from_slice(buf_ref);
let consumed = buf_ref.len();
stream.consume(consumed);
}
Ok((status_code, headers, initial_buf, reason_phrase))
}
struct ProxyResponseStream<S> {
initial_buf: std::io::Cursor<Vec<u8>>,
inner: S,
chunk: BytesMut,
expected_len: Option<u64>,
delivered: u64,
}
impl<S> ProxyResponseStream<S> {
fn body_is_complete(&self) -> bool {
self.expected_len.is_some_and(|n| self.delivered >= n)
}
}
fn map_socks_send_error(err: hyper_util::client::legacy::Error) -> Error {
let mapped = super::direct::map_send_error(err);
if mapped.kind() == "hyper_client" {
Error::ProxyConnect("proxy connection failed".into())
} else {
mapped
}
}
async fn send_socks_request(
dest_url: &url::Url,
method: &http::Method,
headers: Headers,
body: RequestBody,
version: http::Version,
transport_hints: &crate::transport_hints::TransportHints,
ctx: &ProxyRequestContext<'_>,
) -> Result<Response> {
let client = ctx
.socks_client
.as_ref()
.ok_or_else(|| Error::ProxyConnect("persistent SOCKS client was not initialized".into()))?;
let uri: http::Uri = if let Some(ref target) = transport_hints.target {
crate::pipeline::validate_target(target)?;
crate::transport_hints::target_extension_str(target)?
.parse()
.map_err(|e| Error::InvalidUrl(format!("failed to convert target to URI: {e}")))?
} else {
dest_url
.as_str()
.parse()
.map_err(|e| Error::InvalidUrl(format!("failed to convert url to URI: {e}")))?
};
let request = http::Request::builder()
.method(method)
.uri(uri)
.version(version);
let request = request
.body(crate::transport::HyperRequestBody::new(
body.into_http_body(),
))
.map_err(|e| Error::RequestBuild(e.to_string()))?;
let mut request = request;
*request.headers_mut() = headers.into_inner();
let completion = request.body_mut().take_completion_receiver();
let send = async { client.request(request).await.map_err(map_socks_send_error) };
let send = super::direct::send_with_read_timeout(
send,
completion,
ctx.read_timeout,
ctx.remaining_total,
);
let response = match ctx.remaining_total {
Some(duration) => {
tokio::time::timeout(duration, send)
.await
.map_err(|_| Error::Timeout {
phase: TimeoutPhase::Total,
elapsed: duration,
})??
}
None => send.await?,
};
let (response_parts, incoming) = response.into_parts();
let trailers = crate::body::SharedTrailers::new();
let stream = super::direct::wrap_incoming(incoming, trailers.clone());
let mut core_response = Response::new(
response_parts.status,
response_parts.version,
response_parts.headers,
dest_url.clone(),
ResponseBody::streaming(stream),
);
core_response.set_trailers(trailers);
Ok(core_response)
}
impl<S> ProxyResponseStream<S> {
fn new(initial_buf: Vec<u8>, inner: S, expected_len: Option<u64>) -> Self {
Self {
initial_buf: std::io::Cursor::new(initial_buf),
inner,
chunk: BytesMut::with_capacity(8192),
expected_len,
delivered: 0,
}
}
}
impl<S: tokio::io::AsyncRead + Unpin> futures_core::Stream for ProxyResponseStream<S> {
type Item = Result<Bytes>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::io::Read as _;
let this = self.as_mut().get_mut();
if this.initial_buf.position() < this.initial_buf.get_ref().len() as u64 {
this.chunk.clear();
this.chunk.resize(8192, 0);
let n = match this.initial_buf.read(&mut this.chunk) {
Ok(n) => n,
Err(e) => {
return std::task::Poll::Ready(Some(Err(Error::Body(format!(
"failed to read initial buffer: {e}"
)))));
}
};
if n > 0 {
this.delivered = this.delivered.saturating_add(n as u64);
return std::task::Poll::Ready(Some(Ok(this.chunk.split_to(n).freeze())));
}
}
this.chunk.clear();
this.chunk.resize(8192, 0);
let mut read_buf = tokio::io::ReadBuf::new(&mut this.chunk);
match tokio::io::AsyncRead::poll_read(
std::pin::Pin::new(&mut this.inner),
cx,
&mut read_buf,
) {
std::task::Poll::Ready(Ok(())) => {
let n = read_buf.filled().len();
if n > 0 {
this.delivered = this.delivered.saturating_add(n as u64);
std::task::Poll::Ready(Some(Ok(this.chunk.split_to(n).freeze())))
} else {
std::task::Poll::Ready(None)
}
}
std::task::Poll::Ready(Err(e)) => {
if e.kind() == std::io::ErrorKind::UnexpectedEof {
if this.expected_len.is_some() && !this.body_is_complete() {
return std::task::Poll::Ready(Some(Err(Error::MalformedProxyResponse(
format!("proxy closed connection unexpectedly: {e}"),
))));
}
return std::task::Poll::Ready(None);
}
std::task::Poll::Ready(Some(Err(Error::Body(format!(
"proxy stream read error: {e}"
)))))
}
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
pub(crate) fn response_content_length(headers: &[(String, Vec<u8>)]) -> Option<u64> {
let mut content_length: Option<u64> = None;
let mut chunked = false;
for (name, value) in headers {
if name.eq_ignore_ascii_case("transfer-encoding")
&& std::str::from_utf8(value)
.unwrap_or_default()
.split(',')
.any(|token| token.trim().eq_ignore_ascii_case("chunked"))
{
chunked = true;
}
if name.eq_ignore_ascii_case("content-length") {
let parsed: Option<u64> = std::str::from_utf8(value).ok()?.trim().parse().ok();
match (content_length, parsed) {
(None, parsed) => content_length = parsed,
(Some(existing), Some(current)) if existing == current => {}
_ => return None,
}
}
}
if chunked {
None
} else {
content_length
}
}
#[cfg(test)]
mod tests {
use super::{
build_proxy_tls_config, effective_timeout, proxy_server_name, read_proxy_response,
response_content_length, write_proxy_request, ProxyResponseStream,
};
use crate::error::Error;
use crate::timeout::TimeoutPhase;
use std::time::{Duration, Instant};
struct AbruptReader {
data: std::io::Cursor<Vec<u8>>,
}
impl AbruptReader {
fn new(data: &[u8]) -> Self {
Self {
data: std::io::Cursor::new(data.to_vec()),
}
}
}
impl tokio::io::AsyncRead for AbruptReader {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
use std::io::Read as _;
let mut tmp = [0u8; 1024];
match self.data.read(&mut tmp) {
Ok(0) => std::task::Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"peer closed connection without sending TLS close_notify",
))),
Ok(n) => {
buf.put_slice(&tmp[..n]);
std::task::Poll::Ready(Ok(()))
}
Err(e) => std::task::Poll::Ready(Err(e)),
}
}
}
#[test]
fn response_content_length_parses_declared_length() {
let headers = vec![("Content-Length".to_owned(), b"42".to_vec())];
assert_eq!(response_content_length(&headers), Some(42));
}
#[test]
fn response_content_length_prefers_explicit_over_chunked() {
let headers = vec![
("Content-Length".to_owned(), b"42".to_vec()),
("Transfer-Encoding".to_owned(), b"chunked".to_vec()),
];
assert_eq!(response_content_length(&headers), None);
}
#[test]
fn response_content_length_absent_without_length() {
let headers = vec![("Content-Type".to_owned(), b"text/plain".to_vec())];
assert_eq!(response_content_length(&headers), None);
}
#[tokio::test]
async fn proxy_body_stream_complete_body_survives_abrupt_close() {
use futures_util::StreamExt as _;
let mut stream = ProxyResponseStream::new(b"ok".to_vec(), AbruptReader::new(b""), Some(2));
let first = stream.next().await.expect("body chunk").expect("no error");
assert_eq!(first.as_ref(), b"ok");
assert!(stream.next().await.is_none());
}
#[tokio::test]
async fn proxy_body_stream_truncated_body_still_errors() {
use futures_util::StreamExt as _;
let mut stream = ProxyResponseStream::new(Vec::new(), AbruptReader::new(b"o"), Some(2));
let first = stream.next().await.expect("body chunk").expect("no error");
assert_eq!(first.as_ref(), b"o");
let err = stream.next().await.expect("stream item").unwrap_err();
assert!(
matches!(err, Error::MalformedProxyResponse(_)),
"truncation must stay an error, got: {err:?}"
);
}
#[tokio::test]
async fn proxy_body_stream_close_delimited_ends_at_eof() {
use futures_util::StreamExt as _;
let mut stream = ProxyResponseStream::new(Vec::new(), AbruptReader::new(b"data"), None);
let first = stream.next().await.expect("body chunk").expect("no error");
assert_eq!(first.as_ref(), b"data");
assert!(stream.next().await.is_none());
}
#[test]
fn effective_timeout_uses_the_smaller_phase_or_total_budget() {
let deadline = Instant::now() + Duration::from_secs(2);
let timeout = effective_timeout(Some(deadline), Some(Duration::from_secs(5)))
.expect("deadline is in the future");
assert!(timeout.is_some_and(|value| value <= Duration::from_secs(2)));
}
#[test]
fn effective_timeout_uses_phase_budget_without_total() {
assert_eq!(
effective_timeout(None, Some(Duration::from_secs(3))).expect("phase budget is valid"),
Some(Duration::from_secs(3))
);
}
#[test]
fn proxy_tls_server_name_accepts_ip_literals() {
assert!(proxy_server_name("127.0.0.1").is_ok());
assert!(proxy_server_name("proxy.example").is_ok());
}
#[test]
fn expired_total_budget_is_classified_as_total() {
let error = effective_timeout(
Some(
Instant::now()
.checked_sub(Duration::from_millis(1))
.expect("a millisecond is representable before now"),
),
Some(Duration::from_secs(3)),
)
.expect_err("expired total must fail before the phase starts");
assert!(matches!(
error,
Error::Timeout {
phase: TimeoutPhase::Total,
..
}
));
}
#[test]
fn effective_timeout_rejects_deadline_at_now() {
let error =
effective_timeout(Some(Instant::now()), Some(Duration::from_secs(3))).unwrap_err();
assert!(matches!(
error,
Error::Timeout {
phase: TimeoutPhase::Total,
..
}
));
}
#[tokio::test]
async fn read_proxy_response_returns_buffered_body_bytes() {
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(
b"HTTP/1.1 200 OK\r\n\r\nbody".to_vec(),
));
let (_, _, initial, reason) = read_proxy_response(&mut reader).await.unwrap();
assert_eq!(initial, b"body");
assert_eq!(reason.as_deref(), Some("OK"));
}
#[tokio::test]
async fn read_proxy_response_preserves_obs_text_header_values() {
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(
b"HTTP/1.1 200 OK\r\nX-Note: hi\x80\xff\r\n\r\nbody".to_vec(),
));
let (_, headers, initial, _) = read_proxy_response(&mut reader).await.unwrap();
assert_eq!(headers, vec![("X-Note".to_owned(), b"hi\x80\xff".to_vec())]);
assert_eq!(initial, b"body");
}
#[tokio::test]
async fn write_proxy_request_chunks_unknown_length_streams() {
use crate::body::RequestBody;
use crate::headers::Headers;
use bytes::Bytes;
use futures_util::stream;
use tokio::io::AsyncReadExt;
let (mut client_io, mut server_io) = tokio::io::duplex(1024);
write_proxy_request(
&mut client_io,
&http::Method::POST,
"http://origin.example/upload",
http::Version::HTTP_11,
&Headers::new(),
None,
&Headers::new(),
RequestBody::from_stream(
stream::iter(vec![Ok(Bytes::from_static(b"ab")), Ok(Bytes::new())]),
None,
),
)
.await
.unwrap();
drop(client_io);
let mut wire = Vec::new();
server_io.read_to_end(&mut wire).await.unwrap();
assert!(wire
.windows(b"Transfer-Encoding: chunked\r\n".len())
.any(|w| { w == b"Transfer-Encoding: chunked\r\n" }));
assert!(wire.ends_with(b"\r\n\r\n2\r\nab\r\n0\r\n\r\n"));
}
#[tokio::test]
async fn truncated_status_line_is_rejected() {
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(b"HTTP/1.1 200".to_vec()));
let error = read_proxy_response(&mut reader).await.unwrap_err();
assert!(matches!(error, Error::MalformedProxyResponse(_)));
}
#[tokio::test]
async fn truncated_header_section_is_rejected() {
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(
b"HTTP/1.1 200 OK\r\nX-Only: one".to_vec(),
));
let error = read_proxy_response(&mut reader).await.unwrap_err();
assert!(matches!(error, Error::MalformedProxyResponse(_)));
}
#[tokio::test]
async fn header_count_limit_admits_exactly_max() {
use std::fmt::Write as _;
const MAX_HEADER_COUNT: usize = 100;
let mut wire = String::from("HTTP/1.1 200 OK\r\n");
for i in 0..MAX_HEADER_COUNT {
let _ = write!(wire, "X-H{i}: v\r\n");
}
wire.push_str("\r\n");
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(wire.into_bytes()));
let (_, headers, _, _) = read_proxy_response(&mut reader).await.unwrap();
assert_eq!(headers.len(), MAX_HEADER_COUNT);
let mut wire = String::from("HTTP/1.1 200 OK\r\n");
for i in 0..=MAX_HEADER_COUNT {
let _ = write!(wire, "X-H{i}: v\r\n");
}
wire.push_str("\r\n");
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(wire.into_bytes()));
let error = read_proxy_response(&mut reader).await.unwrap_err();
assert!(
matches!(error, Error::MalformedProxyResponse(ref msg) if msg.contains("header count")),
"unexpected error: {error}"
);
}
#[tokio::test]
async fn read_proxy_response_extracts_reason_phrase() {
let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(
b"HTTP/1.1 404 Not Found\r\n\r\n".to_vec(),
));
let (status, _, _, reason) = read_proxy_response(&mut reader).await.unwrap();
assert_eq!(status, 404);
assert_eq!(reason.as_deref(), Some("Not Found"));
}
#[tokio::test]
async fn write_proxy_request_preserves_obs_text_header_values() {
use crate::body::RequestBody;
use crate::headers::Headers;
use tokio::io::AsyncReadExt;
let mut map = http::HeaderMap::new();
map.insert(
http::HeaderName::from_static("x-note"),
http::HeaderValue::from_bytes(&[b'h', b'i', 0x80]).expect("obs-text is a valid value"),
);
let headers = Headers::from(map);
let (mut client_io, mut server_io) = tokio::io::duplex(1024);
super::write_proxy_request(
&mut client_io,
&http::Method::GET,
"http://origin.example/path",
http::Version::HTTP_11,
&headers,
None,
&Headers::new(),
RequestBody::Empty,
)
.await
.unwrap();
drop(client_io);
let mut wire = Vec::new();
server_io.read_to_end(&mut wire).await.unwrap();
let needle: &[u8] = b"x-note: hi\x80\r\n";
assert!(
wire.windows(needle.len()).any(|w| w == needle),
"raw obs-text value must reach the wire, got: {:?}",
String::from_utf8_lossy(&wire)
);
}
#[test]
fn proxy_tls_config_clamps_alpn_to_http1_only() {
let custom = crate::tls::TlsConfig::builder().build();
let with_custom =
build_proxy_tls_config(Some(&custom)).expect("custom proxy TLS config builds");
assert_eq!(with_custom.alpn_protocols, vec![b"http/1.1".to_vec()]);
}
#[test]
fn proxy_tls_fallback_advertises_http1_only_with_roots() {
let fallback = build_proxy_tls_config(None).expect("fallback proxy TLS config builds");
assert_eq!(fallback.alpn_protocols, vec![b"http/1.1".to_vec()]);
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[test]
fn forward_route_key_isolates_tls_policy_and_reuses_compatible() {
use super::ForwardRouteKey;
use crate::proxy::Proxy;
use crate::tls::TlsConfig;
let base = TlsConfig::builder().build();
let strict_proxy = Proxy::all("http://proxy.example:8080")
.unwrap()
.with_proxy_tls_config(base.clone())
.config()
.clone();
let weak_proxy = Proxy::all("http://proxy.example:8080")
.unwrap()
.with_proxy_tls_config(base.clone().danger_accept_invalid_certs(true))
.config()
.clone();
let origin = url::Url::parse("http://origin.example/").unwrap();
let strict_key = ForwardRouteKey::new(&strict_proxy, &origin, None, None);
let strict_again = ForwardRouteKey::new(&strict_proxy, &origin, None, None);
let weak_key = ForwardRouteKey::new(&weak_proxy, &origin, None, None);
assert!(
strict_key == strict_again,
"compatible proxy TLS must reuse"
);
assert!(
strict_key != weak_key,
"weak proxy TLS must not alias strict route"
);
let key_a = ForwardRouteKey::new(&strict_proxy, &origin, None, None);
let key_b = ForwardRouteKey::new(&strict_proxy, &origin, None, None);
assert!(key_a == key_b);
}
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[test]
fn forward_route_key_fragments_on_connection_policy() {
use super::ForwardRouteKey;
use crate::proxy::Proxy;
use std::time::Duration;
let origin = url::Url::parse("http://origin.example/").unwrap();
let base = Proxy::all("http://proxy.example:8080").unwrap();
let base_config = base.config();
let base_key = ForwardRouteKey::new(&base_config, &origin, None, None);
let other_origin = url::Url::parse("http://other.example/").unwrap();
let authed = Proxy::all("http://proxy.example:8080")
.unwrap()
.auth(crate::proxy::ProxyAuth::basic("user", "pass").unwrap());
let authed_config = authed.config();
let other_proxy = Proxy::all("http://proxy2.example:8080").unwrap();
let other_config = other_proxy.config();
let mut headers = crate::headers::Headers::new();
headers.insert("x-proxy-test", "1").unwrap();
let with_headers = Proxy::all("http://proxy.example:8080")
.unwrap()
.proxy_headers(headers);
let headers_config = with_headers.config();
let pinned = Proxy::all("http://proxy.example:8080")
.unwrap()
.resolved_addresses(["127.0.0.1:8080".parse().unwrap()])
.unwrap();
let pinned_config = pinned.config();
assert!(
base_key != ForwardRouteKey::new(&base_config, &other_origin, None, None),
"origin change must fragment forward identity"
);
assert!(
base_key != ForwardRouteKey::new(&authed_config, &origin, None, None),
"proxy auth change must fragment forward identity"
);
assert!(
base_key != ForwardRouteKey::new(&other_config, &origin, None, None),
"proxy endpoint change must fragment forward identity"
);
assert!(
base_key != ForwardRouteKey::new(&headers_config, &origin, None, None),
"proxy-only header change must fragment forward identity"
);
assert!(
base_key != ForwardRouteKey::new(&pinned_config, &origin, None, None),
"pinned proxy peer change must fragment forward identity"
);
assert!(
base_key
!= ForwardRouteKey::new(
&base_config,
&origin,
Some(Duration::from_millis(100)),
None,
),
"connect timeout change must fragment forward identity"
);
assert!(
base_key
!= ForwardRouteKey::new(
&base_config,
&origin,
None,
Some(Duration::from_millis(100)),
),
"proxy TLS timeout change must fragment forward identity"
);
let key_a = ForwardRouteKey::new(&base_config, &origin, None, None);
let key_b = ForwardRouteKey::new(&base_config, &origin, None, None);
assert!(key_a == key_b, "request-only mutations must not fragment");
}
}