use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;
use http::Uri;
use http::header::HeaderValue;
use hyper_util::client::proxy::matcher::{Intercept, Matcher};
#[derive(Clone, Default)]
pub(crate) enum ProxyMode {
#[default]
Env,
Explicit(String),
Disabled,
}
impl fmt::Debug for ProxyMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProxyMode::Env => f.write_str("Env"),
ProxyMode::Explicit(_) => f.write_str("Explicit(<redacted>)"),
ProxyMode::Disabled => f.write_str("Disabled"),
}
}
}
pub(crate) enum ProxySetup {
Direct,
Tunnel {
uri: Uri,
auth: Option<HeaderValue>,
display: Box<str>,
},
Invalid(ProxyConfigError),
}
#[derive(Debug, Clone)]
pub(crate) struct ProxyConfigError {
detail: Cow<'static, str>,
}
impl ProxyConfigError {
fn new(detail: impl Into<Cow<'static, str>>) -> Self {
Self {
detail: detail.into(),
}
}
}
impl fmt::Display for ProxyConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid proxy configuration: {}", self.detail)
}
}
impl StdError for ProxyConfigError {}
#[derive(Debug, Default, Clone)]
pub(crate) struct EnvProxy {
pub all: String,
pub http: String,
pub https: String,
pub no: String,
pub is_cgi: bool,
}
impl EnvProxy {
fn from_env() -> Self {
Self {
all: first_env(&["ALL_PROXY", "all_proxy"]),
http: first_env(&["HTTP_PROXY", "http_proxy"]),
https: first_env(&["HTTPS_PROXY", "https_proxy"]),
no: first_env(&["NO_PROXY", "no_proxy"]),
is_cgi: std::env::var_os("REQUEST_METHOD").is_some(),
}
}
fn configured_for(&self, scheme: Option<&str>) -> bool {
let specific = match scheme {
Some("https") => &self.https,
Some("http") => &self.http,
_ => return false,
};
!specific.is_empty() || !self.all.is_empty()
}
}
fn first_env(names: &[&str]) -> String {
for name in names {
if let Ok(val) = std::env::var(name) {
return val;
}
}
String::new()
}
pub(crate) fn resolve(mode: &ProxyMode, base_url: &str) -> ProxySetup {
match mode {
ProxyMode::Disabled => ProxySetup::Direct,
ProxyMode::Explicit(url) => resolve_explicit(url, base_url),
ProxyMode::Env => resolve_env(&EnvProxy::from_env(), base_url),
}
}
fn resolve_explicit(proxy_url: &str, base_url: &str) -> ProxySetup {
let Some(dst) = destination(base_url) else {
return ProxySetup::Invalid(ProxyConfigError::new(
"a proxy was requested but the API base URL is not an absolute \
http:// or https:// URL, so no connection can be made through it",
));
};
match Matcher::builder().all(proxy_url).build().intercept(&dst) {
Some(intercept) => from_intercept(&intercept),
None => ProxySetup::Invalid(ProxyConfigError::new(
"the proxy URL could not be parsed; expected something like \
http://host:port or http://user:pass@host:port",
)),
}
}
fn resolve_env(env: &EnvProxy, base_url: &str) -> ProxySetup {
if env.is_cgi {
return ProxySetup::Direct;
}
let Some(dst) = destination(base_url) else {
return ProxySetup::Direct;
};
let excluded = Matcher::builder()
.all("http://placeholder.invalid:1")
.no(env.no.as_str())
.build()
.intercept(&dst)
.is_none();
if excluded {
return ProxySetup::Direct;
}
let matcher = Matcher::builder()
.all(env.all.as_str())
.http(env.http.as_str())
.https(env.https.as_str())
.no(env.no.as_str())
.build();
if let Some(intercept) = matcher.intercept(&dst) {
return from_intercept(&intercept);
}
if !env.configured_for(dst.scheme_str()) {
return ProxySetup::Direct;
}
let without_exclusions = Matcher::builder()
.all(env.all.as_str())
.http(env.http.as_str())
.https(env.https.as_str())
.build();
if without_exclusions.intercept(&dst).is_some() {
ProxySetup::Direct
} else {
ProxySetup::Invalid(ProxyConfigError::new(
"a proxy environment variable is set but could not be parsed; \
expected something like http://host:port",
))
}
}
fn destination(base_url: &str) -> Option<Uri> {
let uri: Uri = base_url.parse().ok()?;
uri.host()?;
uri.scheme_str()?;
Some(uri)
}
fn from_intercept(intercept: &Intercept) -> ProxySetup {
let uri = intercept.uri();
match uri.scheme_str() {
Some("http") => {}
Some(other) => {
return ProxySetup::Invalid(ProxyConfigError::new(format!(
"proxy scheme `{other}` is not supported; only http:// proxies \
(HTTP CONNECT tunnelling) are"
)));
}
None => {
return ProxySetup::Invalid(ProxyConfigError::new(
"the proxy URL has no scheme; expected http://host:port",
));
}
}
ProxySetup::Tunnel {
uri: uri.clone(),
auth: intercept.basic_auth().cloned(),
display: sanitized_authority(uri),
}
}
fn sanitized_authority(uri: &Uri) -> Box<str> {
match uri.authority() {
Some(authority) => {
let s = authority.as_str();
match s.split_once('@') {
Some((_userinfo, host_port)) => host_port.into(),
None => s.into(),
}
}
None => "<unknown>".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
const HTTPS_DST: &str = "https://api.delopay.net";
const HTTP_DST: &str = "http://api.delopay.net";
fn proxy_of(setup: &ProxySetup) -> Option<&str> {
match setup {
ProxySetup::Direct => None,
ProxySetup::Tunnel { display, .. } => Some(display),
ProxySetup::Invalid(e) => panic!("expected a decision, got {e}"),
}
}
fn env(https: &str, no: &str) -> EnvProxy {
EnvProxy {
https: https.to_string(),
no: no.to_string(),
..EnvProxy::default()
}
}
#[test]
fn no_proxy_wins_over_an_unparseable_proxy_variable() {
let setup = resolve_env(
&env(" http://corp-egress:3128\n", "api.delopay.net"),
HTTPS_DST,
);
assert!(
matches!(setup, ProxySetup::Direct),
"NO_PROXY must bypass before the proxy value is validated"
);
}
#[test]
fn an_unparseable_proxy_variable_still_fails_when_the_host_is_not_excluded() {
let setup = resolve_env(
&env(" http://corp-egress:3128\n", "other.example"),
HTTPS_DST,
);
assert!(
matches!(setup, ProxySetup::Invalid(_)),
"a garbage proxy value must fail closed, never fall back to direct"
);
}
#[test]
fn env_https_proxy_is_used_for_an_https_base_url() {
let setup = resolve_env(&env("http://corp-egress:3128", ""), HTTPS_DST);
assert_eq!(proxy_of(&setup), Some("corp-egress:3128"));
}
#[test]
fn env_all_proxy_covers_both_schemes() {
let e = EnvProxy {
all: "http://corp-egress:3128".into(),
..EnvProxy::default()
};
assert_eq!(
proxy_of(&resolve_env(&e, HTTPS_DST)),
Some("corp-egress:3128")
);
assert_eq!(
proxy_of(&resolve_env(&e, HTTP_DST)),
Some("corp-egress:3128")
);
}
#[test]
fn env_http_proxy_does_not_capture_https_traffic() {
let e = EnvProxy {
http: "http://corp-egress:3128".into(),
..EnvProxy::default()
};
assert_eq!(proxy_of(&resolve_env(&e, HTTPS_DST)), None);
assert_eq!(
proxy_of(&resolve_env(&e, HTTP_DST)),
Some("corp-egress:3128")
);
}
#[test]
fn no_proxy_exclusion_bypasses_the_proxy_for_a_matching_host() {
let setup = resolve_env(&env("http://corp-egress:3128", "delopay.net"), HTTPS_DST);
assert_eq!(
proxy_of(&setup),
None,
"NO_PROXY listed the destination's domain, so it must go direct"
);
}
#[test]
fn no_proxy_exclusion_does_not_bypass_a_non_matching_host() {
let setup = resolve_env(&env("http://corp-egress:3128", "example.com"), HTTPS_DST);
assert_eq!(proxy_of(&setup), Some("corp-egress:3128"));
}
#[test]
fn no_environment_at_all_means_direct() {
assert_eq!(
proxy_of(&resolve_env(&EnvProxy::default(), HTTPS_DST)),
None
);
}
#[test]
fn cgi_environment_disables_proxying() {
let e = EnvProxy {
https: "http://corp-egress:3128".into(),
is_cgi: true,
..EnvProxy::default()
};
assert_eq!(proxy_of(&resolve_env(&e, HTTPS_DST)), None);
}
#[test]
fn an_unparseable_env_proxy_is_an_error_not_a_direct_connection() {
let setup = resolve_env(&env("::not a proxy::", ""), HTTPS_DST);
assert!(
matches!(setup, ProxySetup::Invalid(_)),
"a set-but-broken proxy variable must not degrade to a direct connection"
);
}
#[test]
fn explicit_proxy_overrides_the_environment() {
let setup = resolve(
&ProxyMode::Explicit("http://explicit-proxy:8080".into()),
HTTPS_DST,
);
assert_eq!(proxy_of(&setup), Some("explicit-proxy:8080"));
}
#[test]
fn explicit_proxy_ignores_no_proxy() {
let setup = resolve_explicit("http://explicit-proxy:8080", HTTPS_DST);
assert_eq!(proxy_of(&setup), Some("explicit-proxy:8080"));
}
#[test]
fn no_proxy_mode_overrides_the_environment() {
assert_eq!(proxy_of(&resolve(&ProxyMode::Disabled, HTTPS_DST)), None);
}
#[test]
fn an_explicit_but_malformed_proxy_url_is_an_error_not_a_direct_connection() {
let setup = resolve_explicit("not a url at all", HTTPS_DST);
assert!(
matches!(setup, ProxySetup::Invalid(_)),
"an explicit proxy that cannot be used must never fall back to direct"
);
}
#[test]
fn a_socks_proxy_is_refused_rather_than_tunnelled_over() {
let setup = resolve_explicit("socks5://corp-egress:1080", HTTPS_DST);
match setup {
ProxySetup::Invalid(e) => assert!(e.to_string().contains("socks5")),
_ => panic!("a socks proxy must be refused"),
}
}
#[test]
fn an_https_proxy_is_refused_rather_than_connected_to_in_cleartext() {
let setup = resolve_explicit("https://corp-egress:3128", HTTPS_DST);
assert!(matches!(setup, ProxySetup::Invalid(_)));
}
#[test]
fn an_unusable_base_url_with_an_explicit_proxy_is_an_error() {
let setup = resolve_explicit("http://corp-egress:3128", "not a url");
assert!(matches!(setup, ProxySetup::Invalid(_)));
}
#[test]
fn proxy_credentials_survive_as_auth_but_never_as_text() {
let setup = resolve_explicit("http://alice:hunter2@corp-egress:3128", HTTPS_DST);
match setup {
ProxySetup::Tunnel { uri, auth, display } => {
assert!(
auth.is_some(),
"credentials in the URL must become a Proxy-Authorization value"
);
assert_eq!(&*display, "corp-egress:3128");
assert!(!uri.to_string().contains("hunter2"));
assert!(!format!("{uri:?}").contains("alice"));
}
_ => panic!("expected a tunnel"),
}
}
#[test]
fn a_credential_free_proxy_carries_no_auth() {
let setup = resolve_explicit("http://corp-egress:3128", HTTPS_DST);
match setup {
ProxySetup::Tunnel { auth, .. } => assert!(auth.is_none()),
_ => panic!("expected a tunnel"),
}
}
#[test]
fn proxy_mode_debug_redacts_the_url() {
let mode = ProxyMode::Explicit("http://alice:hunter2@corp-egress:3128".into());
let formatted = format!("{mode:?}");
assert!(
!formatted.contains("hunter2") && !formatted.contains("alice"),
"ProxyMode's Debug output must not contain proxy credentials: {formatted}"
);
}
#[test]
fn sanitized_authority_strips_userinfo() {
let uri: Uri = "http://alice:hunter2@corp-egress:3128/".parse().unwrap();
assert_eq!(&*sanitized_authority(&uri), "corp-egress:3128");
}
#[test]
fn config_error_text_carries_no_credentials() {
let setup = resolve_explicit("ftp://alice:hunter2@corp-egress:21", HTTPS_DST);
match setup {
ProxySetup::Invalid(e) => {
let text = format!("{e} {e:?}");
assert!(
!text.contains("hunter2") && !text.contains("alice"),
"a proxy error must not echo the URL back: {text}"
);
}
_ => panic!("an ftp proxy must be refused"),
}
}
}