use std::fmt;
use std::net::SocketAddr;
use std::sync::Arc;
use crate::error::{Error, Result};
mod environment;
mod identity;
mod no_proxy;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoProxyRule {
Wildcard,
Host(String),
HostExact(String),
DomainSuffix(String),
HostPort(String, u16),
HostPortExact(String, u16),
HostPortHttpx(String, u16),
IpNetwork(std::net::IpAddr, u8),
Localhost,
LocalhostExact,
SchemeHostPort {
scheme: String,
host: String,
port: Option<u16>,
},
}
#[derive(Debug, Clone)]
pub struct NoProxy {
rules: Vec<NoProxyRule>,
}
impl NoProxy {
pub fn parse(s: &str) -> Result<Self> {
Self::parse_with_localhost_mode(s, false)
}
pub fn parse_httpx(s: &str) -> Result<Self> {
Self::parse_with_localhost_mode(s, true)
}
fn parse_with_localhost_mode(s: &str, exact_localhost: bool) -> Result<Self> {
Ok(Self {
rules: no_proxy::parse_rules(s, exact_localhost)?,
})
}
#[must_use]
pub fn should_bypass(&self, url: &url::Url) -> bool {
self.should_bypass_components(url.scheme(), url.host_str().unwrap_or(""), url.port())
}
#[must_use]
pub(crate) fn should_bypass_components(
&self,
scheme: &str,
host: &str,
port: Option<u16>,
) -> bool {
no_proxy::should_bypass_components(&self.rules, scheme, host, port)
}
}
#[derive(Clone)]
pub enum ProxyAuth {
Basic {
username: String,
password: String,
},
}
impl ProxyAuth {
pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Result<Self> {
let username = username.into();
let password = password.into();
if username.contains(':') {
return Err(Error::InvalidProxyUrl(
"proxy auth username must not contain ':'".into(),
));
}
if username.contains('\r') || username.contains('\n') {
return Err(Error::InvalidProxyUrl(
"proxy auth username must not contain CR/LF".into(),
));
}
if password.contains('\r') || password.contains('\n') {
return Err(Error::InvalidProxyUrl(
"proxy auth password must not contain CR/LF".into(),
));
}
if username.contains('\0') || password.contains('\0') {
return Err(Error::InvalidProxyUrl(
"proxy auth credentials must not contain NUL".into(),
));
}
Ok(Self::Basic { username, password })
}
pub(crate) fn header_value(&self) -> String {
match self {
Self::Basic { username, password } => {
use base64::Engine;
let credential = format!("{username}:{password}");
let encoded =
base64::engine::general_purpose::STANDARD.encode(credential.as_bytes());
format!("Basic {encoded}")
}
}
}
}
impl fmt::Debug for ProxyAuth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Basic { .. } => f
.debug_struct("ProxyAuth::Basic")
.field("username", &"<redacted>")
.field("password", &"<redacted>")
.finish(),
}
}
}
impl fmt::Display for ProxyAuth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Basic { .. } => f.write_str("Basic(<redacted>)"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProxyRule {
All,
Http,
Https,
}
#[derive(Debug, Clone)]
#[allow(
clippy::large_enum_variant,
reason = "ProxyConfig is transient and cloning it is cheap; boxing adds unnecessary allocation"
)]
pub enum ProxyDecision {
Direct,
Proxy(ProxyConfig),
}
#[derive(Clone)]
pub struct ProxyConfig {
pub(crate) uri: url::Url,
pub(crate) auth: Option<ProxyAuth>,
pub(crate) proxy_headers: crate::headers::Headers,
pub(crate) proxy_tls_config: Option<crate::tls::TlsConfig>,
pub(crate) resolved_addresses: Option<Arc<[SocketAddr]>>,
}
impl fmt::Debug for ProxyConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut uri = self.uri.clone();
let _ = uri.set_username("");
let _ = uri.set_password(None);
f.debug_struct("ProxyConfig")
.field("uri", &uri)
.field("auth", &self.auth)
.field("proxy_headers", &self.proxy_headers)
.field(
"proxy_tls_config",
&self.proxy_tls_config.as_ref().map(|_| "<redacted>"),
)
.field(
"resolved_addresses",
&self
.resolved_addresses
.as_ref()
.map(|addresses| addresses.len()),
)
.finish()
}
}
impl ProxyConfig {
#[cfg(feature = "proxy")]
pub(crate) fn connection_identity(&self) -> Vec<u8> {
identity::connection_identity(self)
}
#[must_use]
pub fn uri(&self) -> &url::Url {
&self.uri
}
#[must_use]
pub fn auth(&self) -> Option<&ProxyAuth> {
self.auth.as_ref()
}
#[must_use]
pub fn host(&self) -> Option<&str> {
self.uri.host_str()
}
pub fn port(&self) -> Result<u16> {
match self.uri.port_or_known_default() {
Some(port) => Ok(port),
None => match self.uri.scheme() {
"socks5" | "socks5h" => Ok(1080),
_ => Err(Error::InvalidProxyUrl(format!(
"proxy scheme {:?} has no known default port",
self.uri.scheme()
))),
},
}
}
#[must_use]
pub fn scheme(&self) -> &str {
self.uri.scheme()
}
#[must_use]
pub fn is_socks(&self) -> bool {
matches!(self.uri.scheme(), "socks5" | "socks5h")
}
#[must_use]
pub fn socks_remote_dns(&self) -> bool {
self.uri.scheme() == "socks5h"
}
#[must_use]
pub fn proxy_headers(&self) -> &crate::headers::Headers {
&self.proxy_headers
}
#[must_use]
pub fn proxy_tls_config(&self) -> Option<&crate::tls::TlsConfig> {
self.proxy_tls_config.as_ref()
}
#[must_use]
pub fn resolved_addresses(&self) -> Option<&[SocketAddr]> {
self.resolved_addresses.as_deref()
}
}
#[derive(Clone)]
pub struct Proxy {
uri: url::Url,
auth: Option<ProxyAuth>,
rule: ProxyRule,
bypass: Option<NoProxy>,
#[allow(
clippy::struct_field_names,
reason = "Proxy is already in the proxy context; 'proxy_headers' and 'proxy_tls_config' are unambiguous within this scope"
)]
proxy_headers: crate::headers::Headers,
#[allow(
clippy::struct_field_names,
reason = "Proxy is already in the proxy context; 'proxy_tls_config' is unambiguous within this scope"
)]
proxy_tls_config: Option<crate::tls::TlsConfig>,
resolved_addresses: Option<Arc<[SocketAddr]>>,
}
impl Proxy {
pub fn all(url: &str) -> Result<Self> {
let uri = parse_proxy_url(url)?;
Ok(Self {
uri,
auth: None,
rule: ProxyRule::All,
bypass: None,
proxy_headers: crate::headers::Headers::new(),
proxy_tls_config: None,
resolved_addresses: None,
})
}
pub fn all_compat(url: &str) -> Result<Self> {
let parsed = url::Url::parse(url)
.map_err(|e| Error::InvalidProxyUrl(format!("invalid proxy URL: {e}")))?;
let username = percent_encoding::percent_decode_str(parsed.username())
.decode_utf8_lossy()
.into_owned();
let password = percent_encoding::percent_decode_str(parsed.password().unwrap_or(""))
.decode_utf8_lossy()
.into_owned();
let has_auth = !username.is_empty() || parsed.password().is_some();
let mut without_userinfo = parsed;
let _ = without_userinfo.set_username("");
let _ = without_userinfo.set_password(None);
let mut proxy = Self::all(without_userinfo.as_str())?;
if has_auth {
proxy = proxy.auth(ProxyAuth::basic(username, password)?);
}
Ok(proxy)
}
pub fn http(url: &str) -> Result<Self> {
let uri = parse_proxy_url(url)?;
Ok(Self {
uri,
auth: None,
rule: ProxyRule::Http,
bypass: None,
proxy_headers: crate::headers::Headers::new(),
proxy_tls_config: None,
resolved_addresses: None,
})
}
pub fn http_compat(url: &str) -> Result<Self> {
let mut proxy = Self::all_compat(url)?;
proxy.rule = ProxyRule::Http;
Ok(proxy)
}
pub fn https(url: &str) -> Result<Self> {
let uri = parse_proxy_url(url)?;
Ok(Self {
uri,
auth: None,
rule: ProxyRule::Https,
bypass: None,
proxy_headers: crate::headers::Headers::new(),
proxy_tls_config: None,
resolved_addresses: None,
})
}
pub fn https_compat(url: &str) -> Result<Self> {
let mut proxy = Self::all_compat(url)?;
proxy.rule = ProxyRule::Https;
Ok(proxy)
}
#[must_use]
pub fn auth(mut self, auth: ProxyAuth) -> Self {
self.auth = Some(auth);
self
}
#[must_use]
pub fn no_proxy(mut self, no_proxy: NoProxy) -> Self {
self.bypass = Some(no_proxy);
self
}
#[must_use]
pub fn proxy_headers(mut self, headers: crate::headers::Headers) -> Self {
self.proxy_headers = headers;
self
}
#[must_use]
pub fn proxy_headers_ref(&self) -> &crate::headers::Headers {
&self.proxy_headers
}
#[must_use]
pub fn with_proxy_tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
self.proxy_tls_config = Some(config);
self
}
pub fn resolved_addresses<I>(mut self, addresses: I) -> Result<Self>
where
I: IntoIterator<Item = SocketAddr>,
{
let target = crate::transport_hints::ResolvedTarget::new(addresses).map_err(|error| {
Error::InvalidProxyUrl(format!("invalid resolved proxy peers: {error}"))
})?;
let expected_port = self.config().port()?;
crate::http_origin::validate_effective_port(
crate::http_origin::EffectivePortSubject::ResolvedProxyPeer,
target.addresses(),
expected_port,
)?;
self.resolved_addresses = Some(target.addresses().to_vec().into());
Ok(self)
}
#[must_use]
pub fn no_proxy_rules(&self) -> Option<&NoProxy> {
self.bypass.as_ref()
}
#[must_use]
pub fn should_use_for_scheme(&self, scheme: &str) -> bool {
match self.rule {
ProxyRule::All => true,
ProxyRule::Http => scheme == "http",
ProxyRule::Https => scheme == "https",
}
}
pub(crate) fn config(&self) -> ProxyConfig {
let auth = match self.auth {
Some(ref a) => Some(a.clone()),
None => {
if self.is_socks_url() {
let username = percent_encoding::percent_decode_str(self.uri.username())
.decode_utf8_lossy()
.into_owned();
let password =
percent_encoding::percent_decode_str(self.uri.password().unwrap_or(""))
.decode_utf8_lossy()
.into_owned();
if !username.is_empty() || !password.is_empty() {
Some(ProxyAuth::Basic { username, password })
} else {
None
}
} else {
None
}
}
};
let mut uri = self.uri.clone();
if !uri.username().is_empty() || uri.password().is_some() {
let _ = uri.set_username("");
let _ = uri.set_password(None);
}
ProxyConfig {
uri,
auth,
proxy_headers: self.proxy_headers.clone(),
proxy_tls_config: self.proxy_tls_config.clone(),
resolved_addresses: self.resolved_addresses.clone(),
}
}
fn is_socks_url(&self) -> bool {
matches!(self.uri.scheme(), "socks5" | "socks5h")
}
#[must_use]
pub fn uri(&self) -> &url::Url {
&self.uri
}
#[must_use]
pub fn rule(&self) -> ProxyRule {
self.rule
}
}
impl fmt::Debug for Proxy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut url = self.uri.clone();
let _ = url.set_username("");
let _ = url.set_password(None);
f.debug_struct("Proxy")
.field("uri", &url)
.field("auth", &self.auth)
.field("rule", &self.rule)
.field("bypass", &self.bypass)
.field("proxy_headers", &self.proxy_headers)
.field(
"proxy_tls_config",
&self.proxy_tls_config.as_ref().map(|_| "<redacted>"),
)
.field(
"resolved_addresses",
&self
.resolved_addresses
.as_ref()
.map(|addresses| addresses.len()),
)
.finish()
}
}
impl fmt::Display for Proxy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut url = self.uri.clone();
let _ = url.set_username("");
let _ = url.set_password(None);
write!(f, "Proxy({url})")
}
}
#[derive(Clone, Default)]
#[allow(
clippy::struct_field_names,
reason = "fields name the four conventional proxy environment variables; the shared `proxy` suffix is the domain vocabulary"
)]
pub struct ProxyEnvironment {
http_proxy: Option<String>,
https_proxy: Option<String>,
all_proxy: Option<String>,
no_proxy: Option<String>,
}
impl fmt::Debug for ProxyEnvironment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProxyEnvironment")
.field("http_proxy", &self.http_proxy.as_ref().map(|_| "<set>"))
.field("https_proxy", &self.https_proxy.as_ref().map(|_| "<set>"))
.field("all_proxy", &self.all_proxy.as_ref().map(|_| "<set>"))
.field("no_proxy", &self.no_proxy.as_ref().map(|_| "<set>"))
.finish()
}
}
impl ProxyEnvironment {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_map<I, K, V>(vars: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let mut lower_http: Option<String> = None;
let mut upper_http: Option<String> = None;
let mut lower_https: Option<String> = None;
let mut upper_https: Option<String> = None;
let mut lower_all: Option<String> = None;
let mut upper_all: Option<String> = None;
let mut lower_no: Option<String> = None;
let mut upper_no: Option<String> = None;
for (key, value) in vars {
let value = value.as_ref().trim().to_owned();
if value.is_empty() {
continue;
}
match key.as_ref() {
"http_proxy" => lower_http = Some(value),
"HTTP_PROXY" => upper_http = Some(value),
"https_proxy" => lower_https = Some(value),
"HTTPS_PROXY" => upper_https = Some(value),
"all_proxy" => lower_all = Some(value),
"ALL_PROXY" => upper_all = Some(value),
"no_proxy" => lower_no = Some(value),
"NO_PROXY" => upper_no = Some(value),
_ => {}
}
}
Self {
http_proxy: environment::prefer_lowercase(lower_http, upper_http),
https_proxy: environment::prefer_lowercase(lower_https, upper_https),
all_proxy: environment::prefer_lowercase(lower_all, upper_all),
no_proxy: environment::prefer_lowercase(lower_no, upper_no),
}
}
#[must_use]
pub fn from_env() -> Self {
Self::from_map(std::env::vars())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.http_proxy.is_none() && self.https_proxy.is_none() && self.all_proxy.is_none()
}
fn no_proxy_rules(&self) -> Result<Option<NoProxy>> {
environment::parse_no_proxy(self.no_proxy.as_deref())
}
pub fn resolve(&self, url: &url::Url) -> Result<Option<Proxy>> {
let no_proxy = self.no_proxy_rules()?;
if let Some(ref rules) = no_proxy {
if rules.should_bypass(url) {
return Ok(None);
}
}
let Some((raw, rule, from_all)) = environment::select_proxy(
url.scheme(),
self.http_proxy.as_deref(),
self.https_proxy.as_deref(),
self.all_proxy.as_deref(),
) else {
return Ok(None);
};
let normalized = environment::normalize_proxy_url(raw);
let mut proxy = match (rule, from_all) {
(_, true) | (ProxyRule::All, false) => Proxy::all_compat(&normalized)?,
(ProxyRule::Http, false) => Proxy::http_compat(&normalized)?,
(ProxyRule::Https, false) => Proxy::https_compat(&normalized)?,
};
if let Some(rules) = no_proxy {
proxy = proxy.no_proxy(rules);
}
Ok(Some(proxy))
}
pub fn client_proxies(&self) -> Result<Vec<Proxy>> {
let no_proxy = self.no_proxy_rules()?;
let mut proxies = Vec::new();
if let Some(ref raw) = self.http_proxy {
let normalized = environment::normalize_proxy_url(raw);
let mut proxy = Proxy::http_compat(&normalized)?;
if let Some(ref rules) = no_proxy {
proxy = proxy.no_proxy(rules.clone());
}
proxies.push(proxy);
}
if let Some(ref raw) = self.https_proxy {
let normalized = environment::normalize_proxy_url(raw);
let mut proxy = Proxy::https_compat(&normalized)?;
if let Some(ref rules) = no_proxy {
proxy = proxy.no_proxy(rules.clone());
}
proxies.push(proxy);
}
if let Some(ref raw) = self.all_proxy {
let normalized = environment::normalize_proxy_url(raw);
let mut proxy = Proxy::all_compat(&normalized)?;
if let Some(ref rules) = no_proxy {
proxy = proxy.no_proxy(rules.clone());
}
proxies.push(proxy);
}
Ok(proxies)
}
}
fn parse_proxy_url(url_str: &str) -> Result<url::Url> {
let url = url::Url::parse(url_str)
.map_err(|e| Error::InvalidProxyUrl(format!("invalid proxy URL: {e}")))?;
match url.scheme() {
"http" | "https" => {
if !url.username().is_empty() || url.password().is_some() {
return Err(Error::InvalidProxyUrl(
"proxy URL must not contain credentials; use .auth() instead".into(),
));
}
}
"socks5" | "socks5h" => {
let username = percent_encoding::percent_decode_str(url.username()).decode_utf8_lossy();
let password = percent_encoding::percent_decode_str(url.password().unwrap_or(""))
.decode_utf8_lossy();
if username.contains('\r')
|| username.contains('\n')
|| password.contains('\r')
|| password.contains('\n')
|| username.contains('\0')
|| password.contains('\0')
{
return Err(Error::InvalidProxyUrl(
"proxy auth credentials must not contain CR/LF or NUL".into(),
));
}
}
other => {
return Err(Error::InvalidProxyUrl(format!(
"unsupported proxy scheme '{other}'; supported: http, https, socks5, socks5h"
)));
}
}
if url.host_str().is_none() || url.host_str() == Some("") {
return Err(Error::InvalidProxyUrl("proxy URL must have a host".into()));
}
if url.fragment().is_some() {
return Err(Error::InvalidProxyUrl(
"proxy URL must not contain a fragment".into(),
));
}
if url.query().is_some() {
return Err(Error::InvalidProxyUrl(
"proxy URL must not contain a query string".into(),
));
}
Ok(url)
}
#[cfg(test)]
#[allow(
clippy::items_after_test_module,
reason = "the public proxy response parser is declared after this module in the file's existing layout, and moving it would churn the module for no behavioural gain"
)]
mod tests {
use super::*;
#[test]
fn parse_valid_proxy_url() {
let proxy = Proxy::all("http://proxy.example:8080").unwrap();
assert_eq!(proxy.uri().host_str(), Some("proxy.example"));
assert_eq!(proxy.uri().port(), Some(8080));
}
#[test]
fn unparseable_proxy_url_error_redacts_credentials() {
let err = Proxy::all("http://user:proxy-secret-1@[::1").unwrap_err();
let msg = err.to_string();
assert!(
!msg.contains("proxy-secret-1"),
"proxy parse error must not leak credentials: {msg}"
);
}
#[test]
fn unparseable_compat_proxy_url_error_redacts_credentials() {
let err = Proxy::all_compat("http://user:proxy-secret-2@[::1").unwrap_err();
let msg = err.to_string();
assert!(
!msg.contains("proxy-secret-2"),
"compat proxy parse error must not leak credentials: {msg}"
);
}
#[test]
fn compat_constructors_extract_inline_credentials() {
let proxy = Proxy::https_compat("http://user:pass@proxy.example:8080").unwrap();
assert_eq!(proxy.rule(), ProxyRule::Https);
assert!(proxy.config().auth().is_some());
let proxy = Proxy::http_compat("http://user:pass@proxy.example:8080").unwrap();
assert_eq!(proxy.rule(), ProxyRule::Http);
assert!(proxy.config().auth().is_some());
}
fn https_url() -> url::Url {
url::Url::parse("https://example.com/resource").unwrap()
}
fn http_url() -> url::Url {
url::Url::parse("http://example.com/resource").unwrap()
}
#[test]
fn proxy_environment_https_proxy_selected() {
let env = ProxyEnvironment::from_map([("HTTPS_PROXY", "http://proxy.example:8080")]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("https proxy selected");
assert_eq!(proxy.uri().host_str(), Some("proxy.example"));
assert_eq!(proxy.rule(), ProxyRule::Https);
}
#[test]
fn proxy_environment_lowercase_precedence() {
let env = ProxyEnvironment::from_map([
("HTTPS_PROXY", "http://upper.example:8080"),
("https_proxy", "http://lower.example:8080"),
]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("proxy selected");
assert_eq!(proxy.uri().host_str(), Some("lower.example"));
}
#[test]
fn proxy_environment_all_proxy_fallback() {
let env = ProxyEnvironment::from_map([("ALL_PROXY", "http://fallback.example:8080")]);
let https = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("all_proxy fallback for https");
assert_eq!(https.uri().host_str(), Some("fallback.example"));
let http = env
.resolve(&http_url())
.expect("resolve succeeds")
.expect("all_proxy fallback for http");
assert_eq!(http.uri().host_str(), Some("fallback.example"));
}
#[test]
fn proxy_environment_scheme_specific_beats_fallback() {
let env = ProxyEnvironment::from_map([
("HTTPS_PROXY", "http://specific.example:8080"),
("ALL_PROXY", "http://fallback.example:8080"),
]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("proxy selected");
assert_eq!(proxy.uri().host_str(), Some("specific.example"));
}
#[test]
fn proxy_environment_no_proxy_bypass_exact_and_domain() {
let env = ProxyEnvironment::from_map([
("HTTPS_PROXY", "http://proxy.example:8080"),
("NO_PROXY", "example.com, .internal.example"),
]);
assert!(env
.resolve(&https_url())
.expect("resolve succeeds")
.is_none());
let sub = url::Url::parse("https://api.internal.example/data").unwrap();
assert!(env.resolve(&sub).expect("resolve succeeds").is_none());
let other = url::Url::parse("https://other.example/data").unwrap();
assert!(env.resolve(&other).expect("resolve succeeds").is_some());
}
#[test]
fn proxy_environment_http_proxy_connect_for_https() {
let env =
ProxyEnvironment::from_map([("HTTPS_PROXY", "http://connect-proxy.example:3128")]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("CONNECT proxy selected");
assert_eq!(proxy.uri().scheme(), "http");
assert_eq!(proxy.uri().host_str(), Some("connect-proxy.example"));
}
#[test]
fn proxy_environment_socks_falls_out_of_parser() {
let env = ProxyEnvironment::from_map([("HTTPS_PROXY", "socks5h://socks.example:1080")]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("SOCKS proxy selected");
assert!(proxy.config().is_socks());
}
#[test]
fn proxy_environment_bare_host_gets_http_scheme() {
let env = ProxyEnvironment::from_map([("HTTPS_PROXY", "proxy.example:8080")]);
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("bare host normalized");
assert_eq!(proxy.uri().scheme(), "http");
assert_eq!(proxy.uri().host_str(), Some("proxy.example"));
}
#[test]
fn proxy_environment_invalid_proxy_fails_closed_redacted() {
let env = ProxyEnvironment::from_map([("HTTPS_PROXY", "http://user:env-secret-9@[::1")]);
let err = env.resolve(&https_url()).unwrap_err();
assert!(matches!(err, Error::InvalidProxyUrl(_)));
let msg = err.to_string();
assert!(
!msg.contains("env-secret-9"),
"environment proxy error must not leak credentials: {msg}"
);
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn proxy_environment_no_resolver_means_direct() {
let env = ProxyEnvironment::new();
assert!(env.is_empty());
assert!(env
.resolve(&https_url())
.expect("resolve succeeds")
.is_none());
assert!(env
.resolve(&http_url())
.expect("resolve succeeds")
.is_none());
assert!(env.client_proxies().expect("proxies succeed").is_empty());
}
#[test]
fn proxy_environment_snapshot_stable_after_source_changes() {
let mut source = vec![(
"HTTPS_PROXY".to_owned(),
"http://first.example:8080".to_owned(),
)];
let env = ProxyEnvironment::from_map(source.clone());
source[0].1 = "http://second.example:8080".to_owned();
let proxy = env
.resolve(&https_url())
.expect("resolve succeeds")
.expect("proxy selected");
assert_eq!(proxy.uri().host_str(), Some("first.example"));
}
#[test]
fn proxy_environment_debug_redacts_values() {
let env = ProxyEnvironment::from_map([
(
"HTTPS_PROXY",
"http://user:debug-secret-7@proxy.example:8080",
),
("NO_PROXY", "example.com"),
]);
let rendered = format!("{env:?}");
assert!(
!rendered.contains("debug-secret-7"),
"Debug must not leak proxy credentials: {rendered}"
);
assert!(
!rendered.contains("proxy.example"),
"Debug must not echo proxy host: {rendered}"
);
}
#[test]
fn proxy_environment_client_proxies_specific_before_fallback() {
let env = ProxyEnvironment::from_map([
("HTTP_PROXY", "http://http-proxy.example:8080"),
("HTTPS_PROXY", "http://https-proxy.example:8080"),
("ALL_PROXY", "http://fallback.example:8080"),
]);
let proxies = env.client_proxies().expect("proxies succeed");
assert_eq!(proxies.len(), 3);
assert_eq!(proxies[0].rule(), ProxyRule::Http);
assert_eq!(proxies[1].rule(), ProxyRule::Https);
assert_eq!(proxies[2].rule(), ProxyRule::All);
}
#[test]
fn parse_proxy_url_default_port() {
let proxy = Proxy::all("http://proxy.example").unwrap();
assert_eq!(proxy.uri().port_or_known_default(), Some(80));
}
#[test]
fn parse_proxy_url_accepts_https_scheme() {
let proxy = Proxy::all("https://proxy.example:8443").unwrap();
assert_eq!(proxy.uri().scheme(), "https");
assert_eq!(proxy.config().port().unwrap(), 8443);
}
#[test]
fn parse_proxy_url_https_default_port() {
let proxy = Proxy::all("https://proxy.example").unwrap();
assert_eq!(proxy.config().port().unwrap(), 443);
}
#[test]
fn parse_proxy_url_accepts_socks5() {
let proxy = Proxy::all("socks5://proxy.example:1080").unwrap();
assert_eq!(proxy.uri().host_str(), Some("proxy.example"));
assert_eq!(proxy.uri().port(), Some(1080));
assert_eq!(proxy.uri().scheme(), "socks5");
}
#[test]
fn parse_proxy_url_accepts_socks5h() {
let proxy = Proxy::all("socks5h://proxy.example:1080").unwrap();
assert_eq!(proxy.uri().scheme(), "socks5h");
}
#[test]
fn parse_proxy_url_socks5_default_port() {
let proxy = Proxy::all("socks5://proxy.example").unwrap();
let config = proxy.config();
assert_eq!(config.port().unwrap(), 1080);
}
#[test]
fn parse_proxy_url_socks5_with_credentials() {
let proxy = Proxy::all("socks5://user:pass@proxy.example:1080").unwrap();
let config = proxy.config();
assert!(config.auth().is_some());
if let Some(auth) = config.auth() {
let debug = format!("{auth:?}");
assert!(debug.contains("user"));
assert!(!debug.contains("pass@"), "password should be redacted");
assert!(debug.contains("<redacted>"));
}
}
#[test]
fn parse_proxy_url_socks5_decodes_credentials() {
let proxy = Proxy::all("socks5://user%40name:p%40ss@proxy.example:1080").unwrap();
let config = proxy.config();
match config.auth().unwrap() {
ProxyAuth::Basic { username, password } => {
assert_eq!(username, "user@name");
assert_eq!(password, "p@ss");
}
}
}
#[test]
fn parse_proxy_url_socks5_rejects_crlf_credentials() {
assert!(Proxy::all("socks5://user%0D%0Ax:pass@proxy.example:1080").is_err());
assert!(Proxy::all("socks5://user:p%0Aass@proxy.example:1080").is_err());
assert!(Proxy::all("socks5h://user%0dname:pass@proxy.example:1080").is_err());
}
#[test]
fn parse_proxy_url_socks5_no_userinfo() {
let proxy = Proxy::all("socks5://proxy.example:1080").unwrap();
let config = proxy.config();
assert!(config.auth().is_none());
}
#[test]
fn proxy_config_is_socks() {
let http_proxy = Proxy::all("http://proxy:8080").unwrap();
assert!(!http_proxy.config().is_socks());
let socks_proxy = Proxy::all("socks5://proxy:1080").unwrap();
assert!(socks_proxy.config().is_socks());
let socks5h_proxy = Proxy::all("socks5h://proxy:1080").unwrap();
assert!(socks5h_proxy.config().is_socks());
}
#[test]
fn proxy_config_socks_remote_dns() {
let socks5 = Proxy::all("socks5://proxy:1080").unwrap();
assert!(!socks5.config().socks_remote_dns());
let socks5h = Proxy::all("socks5h://proxy:1080").unwrap();
assert!(socks5h.config().socks_remote_dns());
}
#[test]
fn parse_proxy_url_rejects_no_host() {
let err = Proxy::all("http://").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn compat_proxy_url_extracts_http_userinfo_and_redacts_it() {
let proxy = Proxy::all_compat("http://user:pass@proxy.example:8080").unwrap();
assert!(proxy.config().auth().is_some());
assert!(!proxy.to_string().contains("pass"));
}
#[test]
fn parse_proxy_url_rejects_http_userinfo() {
let err = Proxy::all("http://user:pass@proxy.example:8080").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn parse_proxy_url_rejects_fragment() {
let err = Proxy::all("http://proxy.example:8080#frag").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn parse_proxy_url_rejects_query() {
let err = Proxy::all("http://proxy.example:8080?key=val").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn proxy_rule_all_matches_any_scheme() {
let proxy = Proxy::all("http://proxy:8080").unwrap();
assert!(proxy.should_use_for_scheme("http"));
assert!(proxy.should_use_for_scheme("https"));
}
#[test]
fn proxy_rule_http_only_matches_http() {
let proxy = Proxy::http("http://proxy:8080").unwrap();
assert!(proxy.should_use_for_scheme("http"));
assert!(!proxy.should_use_for_scheme("https"));
}
#[test]
fn proxy_rule_https_only_matches_https() {
let proxy = Proxy::https("http://proxy:8080").unwrap();
assert!(!proxy.should_use_for_scheme("http"));
assert!(proxy.should_use_for_scheme("https"));
}
#[test]
fn proxy_auth_redacted_debug() {
let auth = ProxyAuth::basic("user", "secret123").unwrap();
let debug = format!("{auth:?}");
assert!(!debug.contains("\"user\""));
assert!(debug.contains("<redacted>"));
assert!(!debug.contains("secret123"));
}
#[test]
fn proxy_auth_redacted_display() {
let auth = ProxyAuth::basic("user", "secret123").unwrap();
let display = format!("{auth}");
assert!(!display.contains("user"));
assert!(!display.contains("secret123"));
assert!(display.contains("<redacted>"));
}
#[test]
fn proxy_auth_rejects_cr() {
let err = ProxyAuth::basic("user\r", "pass").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn proxy_auth_rejects_lf() {
let err = ProxyAuth::basic("user", "pass\n").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn proxy_auth_rejects_colon_in_username() {
let err = ProxyAuth::basic("user:name", "pass").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn proxy_auth_header_value() {
use base64::Engine;
let auth = ProxyAuth::basic("user", "pass").unwrap();
let val = auth.header_value();
assert!(val.starts_with("Basic "));
let encoded = val.strip_prefix("Basic ").unwrap();
let decoded = base64::engine::general_purpose::STANDARD
.decode(encoded)
.unwrap();
assert_eq!(String::from_utf8(decoded).unwrap(), "user:pass");
}
#[test]
fn proxy_auth_shared_subset_matches_connect_wire_helper() {
for (username, password) in [("user", "pass"), ("", ""), ("u", "p:ass"), ("é", "päss")] {
let proxy = ProxyAuth::basic(username, password).unwrap();
let wire = eggfetch_http_connect::basic_auth_value(username, password).unwrap();
assert_eq!(proxy.header_value(), wire);
}
}
#[test]
fn proxy_auth_control_domain_remains_intentionally_narrower() {
assert!(ProxyAuth::basic("u\t", "p").is_ok());
assert!(eggfetch_http_connect::basic_auth_value("u\t", "p").is_err());
assert!(ProxyAuth::basic("u\u{7f}", "p").is_ok());
assert!(eggfetch_http_connect::basic_auth_value("u\u{7f}", "p").is_err());
}
#[test]
fn proxy_display_redacts_url() {
let proxy = Proxy::all("http://proxy.example:8080").unwrap();
let display = format!("{proxy}");
assert!(display.contains("proxy.example"));
assert!(display.contains("Proxy("));
}
#[test]
fn proxy_debug_redacts_socks_url_credentials() {
let proxy = Proxy::all("socks5://user:secret123@proxy.example:1080").unwrap();
let debug = format!("{proxy:?}");
assert!(debug.contains("proxy.example"));
assert!(!debug.contains("secret123"));
assert!(!debug.contains("user:"));
}
#[test]
fn proxy_config_host_port() {
let proxy = Proxy::all("http://proxy.example:3128").unwrap();
let config = proxy.config();
assert_eq!(config.host(), Some("proxy.example"));
assert_eq!(config.port().unwrap(), 3128);
assert_eq!(config.scheme(), "http");
}
#[test]
fn proxy_config_default_port() {
let proxy = Proxy::all("http://proxy.example").unwrap();
let config = proxy.config();
assert_eq!(config.port().unwrap(), 80);
}
#[test]
fn proxy_config_socks_default_port() {
let proxy = Proxy::all("socks5://proxy.example").unwrap();
let config = proxy.config();
assert_eq!(config.port().unwrap(), 1080);
}
#[test]
fn proxy_resolved_addresses_validate_and_preserve_order() {
let proxy = Proxy::all("http://proxy.example:3128")
.unwrap()
.resolved_addresses([
"198.51.100.21:3128".parse().unwrap(),
"198.51.100.20:3128".parse().unwrap(),
])
.unwrap();
assert_eq!(
proxy.config().resolved_addresses().unwrap(),
&[
"198.51.100.21:3128".parse().unwrap(),
"198.51.100.20:3128".parse().unwrap(),
]
);
}
#[test]
fn proxy_resolved_addresses_reject_empty_and_wrong_port() {
let proxy = Proxy::all("http://proxy.example:3128").unwrap();
assert!(matches!(
proxy.clone().resolved_addresses(Vec::<SocketAddr>::new()),
Err(Error::InvalidProxyUrl(_))
));
assert!(matches!(
proxy.resolved_addresses(["198.51.100.20:8080".parse().unwrap()]),
Err(Error::InvalidProxyUrl(_))
));
}
#[test]
fn proxy_debug_reports_peer_count_without_topology() {
let proxy = Proxy::all("http://proxy.example:3128")
.unwrap()
.resolved_addresses(["198.51.100.20:3128".parse().unwrap()])
.unwrap();
let debug = format!("{proxy:?}");
assert!(debug.contains("resolved_addresses: Some(1)"));
assert!(!debug.contains("198.51.100.20"));
}
#[test]
fn proxy_config_unknown_scheme_has_no_panic_port() {
let config = ProxyConfig {
uri: url::Url::parse("unknown://proxy.example").unwrap(),
auth: None,
proxy_headers: crate::headers::Headers::new(),
proxy_tls_config: None,
resolved_addresses: None,
};
assert!(matches!(config.port(), Err(Error::InvalidProxyUrl(_))));
}
#[test]
fn proxy_with_auth() {
let auth = ProxyAuth::basic("user", "pass").unwrap();
let proxy = Proxy::all("http://proxy:8080").unwrap().auth(auth);
let config = proxy.config();
assert!(config.auth().is_some());
}
#[test]
fn proxy_with_no_proxy() {
let np = NoProxy::parse("localhost").unwrap();
let proxy = Proxy::all("http://proxy:8080").unwrap().no_proxy(np);
assert!(proxy.no_proxy_rules().is_some());
}
#[test]
fn noparse_empty_string() {
let np = NoProxy::parse("").unwrap();
assert_eq!(np.rules, []);
}
#[test]
fn noparse_whitespace_only() {
let np = NoProxy::parse(" , , ").unwrap();
assert_eq!(np.rules, []);
}
#[test]
fn noparse_single_host() {
let np = NoProxy::parse("example.com").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(np.rules[0], NoProxyRule::Host("example.com".into()));
}
#[test]
fn noparse_domain_suffix() {
let np = NoProxy::parse(".example.com").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(
np.rules[0],
NoProxyRule::DomainSuffix(".example.com".into())
);
}
#[test]
fn noparse_host_port() {
let np = NoProxy::parse("example.com:8080").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(
np.rules[0],
NoProxyRule::HostPort("example.com".into(), 8080)
);
}
#[test]
fn noparse_localhost() {
let np = NoProxy::parse("localhost").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(np.rules[0], NoProxyRule::Localhost);
}
#[test]
fn noparse_wildcard() {
let np = NoProxy::parse("*").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(np.rules[0], NoProxyRule::Wildcard);
}
#[test]
fn noparse_mixed() {
let np = NoProxy::parse("localhost, .example.com, 10.0.0.1:8080").unwrap();
assert_eq!(np.rules.len(), 3);
assert_eq!(np.rules[0], NoProxyRule::Localhost);
assert_eq!(
np.rules[1],
NoProxyRule::DomainSuffix(".example.com".into())
);
assert_eq!(np.rules[2], NoProxyRule::HostPort("10.0.0.1".into(), 8080));
}
#[test]
fn noparse_ipv6_literal() {
let np = NoProxy::parse("[::1]").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(np.rules[0], NoProxyRule::Host("[::1]".into()));
}
#[test]
fn noparse_ipv6_with_port() {
let np = NoProxy::parse("[::1]:8080").unwrap();
assert_eq!(np.rules.len(), 1);
assert_eq!(np.rules[0], NoProxyRule::HostPort("[::1]".into(), 8080));
}
#[test]
fn noparse_invalid_port_rejected() {
let err = NoProxy::parse("example.com:notaport").unwrap_err();
assert!(matches!(err, Error::InvalidProxyUrl(_)));
}
#[test]
fn noparse_dot_only() {
let err = NoProxy::parse(".").unwrap_err();
assert_eq!(err.kind(), "invalid_proxy_url");
}
#[test]
fn nobypass_empty_rules() {
let np = NoProxy::parse("").unwrap();
let url = url::Url::parse("http://example.com").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_exact_host() {
let np = NoProxy::parse("example.com").unwrap();
let url = url::Url::parse("http://example.com/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_exact_host_no_match() {
let np = NoProxy::parse("example.com").unwrap();
let url = url::Url::parse("http://other.com/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_exact_host_case_insensitive() {
let np = NoProxy::parse("Example.Com").unwrap();
let url = url::Url::parse("http://example.com/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_domain_suffix_match() {
let np = NoProxy::parse(".example.com").unwrap();
let url = url::Url::parse("http://foo.example.com/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_domain_suffix_excludes_bare_domain() {
let np = NoProxy::parse(".example.com").unwrap();
let url = url::Url::parse("http://example.com/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_domain_suffix_no_match() {
let np = NoProxy::parse(".example.com").unwrap();
let url = url::Url::parse("http://notexample.com/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_bare_domain_includes_subdomains() {
let np = NoProxy::parse("example.com").unwrap();
for url in ["http://example.com/path", "http://api.example.com/path"] {
assert!(np.should_bypass(&url::Url::parse(url).unwrap()));
}
assert!(!np.should_bypass(&url::Url::parse("http://badexample.com").unwrap()));
}
#[test]
fn parse_httpx_bare_domain_includes_subdomains_at_label_boundary() {
let np = NoProxy::parse_httpx("example.test").unwrap();
for url in [
"http://example.test/",
"http://www.example.test/",
"http://deep.www.example.test/",
] {
assert!(np.should_bypass(&url::Url::parse(url).unwrap()), "{url}");
}
for url in [
"http://wwwexample.test/",
"http://notexample.test/",
"http://example.test.evil/",
] {
assert!(!np.should_bypass(&url::Url::parse(url).unwrap()), "{url}");
}
}
#[test]
fn parse_httpx_leading_dot_excludes_bare_domain() {
let np = NoProxy::parse_httpx(".example.test").unwrap();
assert!(!np.should_bypass(&url::Url::parse("http://example.test/").unwrap()));
assert!(np.should_bypass(&url::Url::parse("http://www.example.test/").unwrap()));
}
#[test]
fn parse_httpx_host_port_requires_explicit_normalized_port() {
let np = NoProxy::parse_httpx("example.test:80").unwrap();
assert!(!np.should_bypass(&url::Url::parse("http://example.test/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://example.test:80/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://example.test:8080/").unwrap()));
assert!(np.should_bypass(&url::Url::parse("https://example.test:80/").unwrap()));
let non_default = NoProxy::parse_httpx("example.test:8080").unwrap();
assert!(non_default.should_bypass(&url::Url::parse("http://example.test:8080/").unwrap()));
assert!(
non_default.should_bypass(&url::Url::parse("http://www.example.test:8080/").unwrap())
);
assert!(!non_default.should_bypass(&url::Url::parse("http://example.test:8081/").unwrap()));
}
#[test]
fn nobypass_cidr_matches_ip_address() {
let np = NoProxy::parse("10.0.0.0/8").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://10.42.1.9").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://11.42.1.9").unwrap()));
}
#[test]
fn nobypass_host_port_match() {
let np = NoProxy::parse("example.com:8080").unwrap();
let url = url::Url::parse("http://example.com:8080/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_host_port_no_match_port() {
let np = NoProxy::parse("example.com:8080").unwrap();
let url = url::Url::parse("http://example.com:9090/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_host_port_no_match_host() {
let np = NoProxy::parse("example.com:8080").unwrap();
let url = url::Url::parse("http://other.com:8080/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn nobypass_host_port_default_port_https() {
let np = NoProxy::parse("example.com:443").unwrap();
let url = url::Url::parse("https://example.com/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_host_port_default_port_http() {
let np = NoProxy::parse("example.com:80").unwrap();
let url = url::Url::parse("http://example.com/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_localhost_name() {
let np = NoProxy::parse("localhost").unwrap();
let url = url::Url::parse("http://localhost/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_localhost_127() {
let np = NoProxy::parse("localhost").unwrap();
let url = url::Url::parse("http://127.0.0.1/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_localhost_ipv6() {
let np = NoProxy::parse("localhost").unwrap();
let url = url::Url::parse("http://[::1]/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_localhost_not_matching() {
let np = NoProxy::parse("localhost").unwrap();
let url = url::Url::parse("http://example.com/path").unwrap();
assert!(!np.should_bypass(&url));
}
#[test]
fn httpx_localhost_does_not_match_loopback_literals() {
let np = NoProxy::parse_httpx("localhost").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://localhost/path").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://127.0.0.1/path").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://[::1]/path").unwrap()));
}
#[test]
fn nobypass_wildcard_matches_everything() {
let np = NoProxy::parse("*").unwrap();
let urls = [
"http://example.com",
"https://other.org",
"http://10.0.0.1:8080",
"http://localhost",
];
for url_str in &urls {
let url = url::Url::parse(url_str).unwrap();
assert!(np.should_bypass(&url), "should bypass {url_str}");
}
}
#[test]
fn nobypass_ipv6_literal() {
let np = NoProxy::parse("[::1]").unwrap();
let url = url::Url::parse("http://[::1]/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn nobypass_ipv4_literal() {
let np = NoProxy::parse("10.0.0.1").unwrap();
let url = url::Url::parse("http://10.0.0.1/path").unwrap();
assert!(np.should_bypass(&url));
}
#[test]
fn httpx_scheme_qualified_no_proxy_is_scheme_specific() {
let np = NoProxy::parse_httpx("http://example.test:8080").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://example.test:8080/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("https://example.test:8080/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://example.test:8081/").unwrap()));
}
#[test]
fn httpx_bare_ipv6_no_proxy_is_not_host_port() {
let np = NoProxy::parse_httpx("::1").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://[::1]/").unwrap()));
}
#[test]
fn httpx_rejects_bracketed_and_prefix_looking_ipv6_entries() {
for entry in ["[::1]", "[::1]:8080", "::1/128", "[::1]/128"] {
assert!(NoProxy::parse_httpx(entry).is_err(), "{entry}");
}
}
#[test]
fn httpx_invalid_ipv6_entry_error_is_bounded() {
let entry = format!("[{}]", ":".repeat(1000));
let error = NoProxy::parse_httpx(&entry).unwrap_err().to_string();
assert!(error.len() < 320);
assert!(!error.contains(&entry));
}
#[test]
fn native_ipv6_cidr_behavior_remains_available() {
let np = NoProxy::parse("2001:db8::/32").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://[2001:db8::1]/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://[2001:db9::1]/").unwrap()));
}
#[test]
fn bare_ipv6_no_proxy_matches() {
let np = NoProxy::parse("::1").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://[::1]/").unwrap()));
}
#[test]
fn httpx_cidr_looking_no_proxy_is_exact_host_text() {
let np = NoProxy::parse_httpx("10.0.0.0/8").unwrap();
assert!(np.should_bypass(&url::Url::parse("http://10.0.0.0/").unwrap()));
assert!(!np.should_bypass(&url::Url::parse("http://10.42.1.9/").unwrap()));
}
#[test]
fn nobypass_multiple_rules_first_match() {
let np = NoProxy::parse("localhost, .example.com").unwrap();
let url1 = url::Url::parse("http://localhost/path").unwrap();
let url2 = url::Url::parse("http://foo.example.com/path").unwrap();
let url3 = url::Url::parse("http://other.com/path").unwrap();
assert!(np.should_bypass(&url1));
assert!(np.should_bypass(&url2));
assert!(!np.should_bypass(&url3));
}
#[cfg(feature = "proxy")]
#[test]
fn proxy_tls_weak_and_strict_identities_do_not_alias() {
use crate::tls::TlsConfig;
let base = TlsConfig::builder().build();
let strict_tls = base.clone();
let weak_tls = base.clone().danger_accept_invalid_certs(true);
let strict = Proxy::all("https://proxy.example:8443")
.unwrap()
.with_proxy_tls_config(strict_tls)
.config()
.clone();
let weak = Proxy::all("https://proxy.example:8443")
.unwrap()
.with_proxy_tls_config(weak_tls)
.config()
.clone();
assert_ne!(
strict.connection_identity(),
weak.connection_identity(),
"proxy TLS verification change must fragment route identity"
);
let strict_again = strict.clone();
assert_eq!(
strict.connection_identity(),
strict_again.connection_identity(),
"unchanged proxy clones must remain reusable"
);
}
#[cfg(feature = "proxy")]
#[test]
fn proxy_identity_is_opaque_and_non_renderable() {
let proxy = Proxy::all("http://proxy.example:8080")
.unwrap()
.auth(ProxyAuth::basic("user", "secret-pass").unwrap());
let config = proxy.config();
let identity = config.connection_identity();
assert_ne!(identity, [] as [u8; 0]);
let debug = format!("{config:?}");
assert!(
!debug.contains("secret-pass"),
"proxy identity diagnostics must not leak credentials: {debug}"
);
}
}
#[doc(hidden)]
pub fn parse_proxy_response_bytes(
data: &[u8],
) -> crate::error::Result<(u16, Vec<(String, String)>)> {
fn read_line(data: &[u8], max_len: usize) -> crate::error::Result<(&[u8], &[u8])> {
let newline = data.iter().position(|&byte| byte == b'\n').ok_or_else(|| {
Error::MalformedProxyResponse("proxy closed connection before end of line".into())
})?;
let (line, remaining) = data.split_at(newline + 1);
let mut line = &line[..newline];
if line.last() == Some(&b'\r') {
line = &line[..line.len() - 1];
}
if line.len() > max_len {
return Err(Error::MalformedProxyResponse(format!(
"proxy response line exceeded maximum length of {max_len} bytes"
)));
}
Ok((line, remaining))
}
let limits = eggfetch_http_connect::ConnectResponseLimits::default();
let (status_line, mut remaining) = read_line(data, limits.max_status_line)?;
let status_line = std::str::from_utf8(status_line).map_err(|_| {
Error::MalformedProxyResponse("proxy response contains invalid UTF-8".into())
})?;
if status_line.is_empty() {
return Err(Error::MalformedProxyResponse(
"proxy closed connection before response".into(),
));
}
let mut parts = status_line.splitn(3, ' ');
let _version = parts.next();
let status_code = parts
.next()
.and_then(|part| part.parse::<u16>().ok())
.ok_or_else(|| {
Error::MalformedProxyResponse(format!("invalid status line: {status_line}"))
})?;
let mut headers = Vec::new();
let mut total_header_bytes = 0usize;
loop {
let (line, rest) = read_line(remaining, limits.max_header_line)?;
remaining = rest;
if line.is_empty() {
break;
}
total_header_bytes += line.len();
if total_header_bytes > limits.max_headers_bytes {
return Err(Error::MalformedProxyResponse(format!(
"proxy response headers exceeded maximum total size of {} bytes",
limits.max_headers_bytes
)));
}
if headers.len() >= limits.max_header_count {
return Err(Error::MalformedProxyResponse(format!(
"proxy response exceeded maximum header count of {}",
limits.max_header_count
)));
}
let line = std::str::from_utf8(line).map_err(|_| {
Error::MalformedProxyResponse("proxy response contains invalid UTF-8".into())
})?;
headers.push(
line.split_once(':')
.map(|(name, value)| (name.trim().to_owned(), value.trim().to_owned()))
.ok_or_else(|| {
Error::MalformedProxyResponse(format!("invalid header line: {line}"))
})?,
);
}
Ok((status_code, headers))
}