use std::{net::IpAddr, str::FromStr};
use ipnet::IpNet;
use thiserror::Error;
use crate::util::nonempty;
#[derive(Debug, Error)]
pub enum Error {
#[error("unexpected empty input")]
EmptyInput,
#[error("comma-separated value is empty")]
EmptyValue,
#[error("failed to parse {input:?} as matcher. supported matchers are: cidr, ip address, and host")]
ParseMatcher {
input: String,
},
#[error("failed to find valid host in parsed uri \"{uri}\"")]
NoHost {
uri: Box<http::Uri>,
},
}
#[derive(Debug)]
pub enum NoProxy {
Wildcard,
Matchers(Vec<NoProxyMatcher>),
}
impl FromStr for NoProxy {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
if s.is_empty() {
return Err(Error::EmptyInput);
}
if s == "*" {
return Ok(Self::Wildcard);
}
let parts: Vec<&str> = s.split(',').collect();
let mut matchers = Vec::new();
for part in parts {
let matcher = NoProxyMatcher::from_str(part.trim())?;
matchers.push(matcher);
}
Ok(Self::Matchers(matchers))
}
}
impl NoProxy {
pub fn from_env() -> Result<Option<Self>, Error> {
if let Some(raw) =
nonempty(std::env::var("NO_PROXY").ok()).or_else(|| nonempty(std::env::var("no_proxy").ok()))
{
Ok(Some(Self::from_str(&raw)?))
} else {
Ok(None)
}
}
pub fn matches(&self, target: &http::Uri) -> Result<bool, Error> {
match self {
NoProxy::Wildcard => Ok(true),
NoProxy::Matchers(matchers) => {
let host = Host::try_from(target)?;
let target_port = port_via_scheme(target);
for matcher in matchers {
if host.matches(target_port, matcher) {
return Ok(true);
} else {
continue;
}
}
Ok(false)
}
}
}
}
#[derive(Debug)]
pub enum NoProxyMatcher {
IpAddr(IpAddr),
IpNet(IpNet),
Host {
name: String,
port: Option<u16>,
exact: bool,
},
}
impl FromStr for NoProxyMatcher {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Err(Error::EmptyValue);
}
if let Ok(ip_net) = IpNet::from_str(s) {
return Ok(NoProxyMatcher::IpNet(ip_net));
}
if let Ok(ip_addr) = IpAddr::from_str(s) {
return Ok(NoProxyMatcher::IpAddr(ip_addr));
}
if let Ok(uri) = http::Uri::from_str(s) {
let Some(mut host) = uri.host() else {
return Err(Error::NoHost { uri: Box::new(uri) });
};
let port = port_via_scheme(&uri);
if host.starts_with("*.") {
host = &host[1..];
}
if host.starts_with('.') {
return Ok(NoProxyMatcher::Host {
name: host.to_owned(),
port,
exact: false,
});
}
return Ok(NoProxyMatcher::Host {
name: host.to_owned(),
port,
exact: true,
});
}
Err(Error::ParseMatcher { input: s.to_owned() })
}
}
enum Host {
IpAddr(IpAddr),
Name(String),
}
impl TryFrom<&http::Uri> for Host {
type Error = Error;
fn try_from(uri: &http::Uri) -> Result<Self, Self::Error> {
match uri.host() {
Some(value) => {
if let Ok(ip_addr) = IpAddr::from_str(value) {
return Ok(Self::IpAddr(ip_addr));
}
Ok(Self::Name(value.to_owned()))
}
None => Err(Error::NoHost {
uri: Box::new(uri.clone()),
}),
}
}
}
impl Host {
fn matches(&self, target_port: Option<u16>, matcher: &NoProxyMatcher) -> bool {
match &self {
Host::IpAddr(target_ip_addr) => match matcher {
NoProxyMatcher::IpAddr(ip_addr) => ip_addr == target_ip_addr,
NoProxyMatcher::IpNet(ip_net) => ip_net.contains(target_ip_addr),
_ => false,
},
Host::Name(target_name) => match matcher {
NoProxyMatcher::Host { name, port, exact } => {
if *exact {
target_name == name && target_port == *port
} else {
target_name.ends_with(name) && target_port == *port
}
}
_ => false,
},
}
}
}
fn port_via_scheme(uri: &http::Uri) -> Option<u16> {
uri.port_u16().or_else(|| match uri.scheme_str() {
Some("https") => Some(443),
Some("http") => Some(80),
_ => None,
})
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
fn assert_match(no_proxy: &str, target: &str, matches: bool) {
let no_proxy = NoProxy::from_str(no_proxy).expect("static input must parse");
let target_uri = http::Uri::from_str(target).expect("static input must parse");
assert_eq!(
no_proxy.matches(&target_uri).expect("target uri is valid"),
matches
);
}
#[rstest]
#[case("example.org,")]
#[case("no/host")]
#[case(" ")]
#[case(",,")]
#[case(",")]
#[case("")]
fn invalid(#[case] input: &str) {
let result = NoProxy::from_str(input);
assert!(result.is_err());
}
#[rstest]
#[case(" * ")]
#[case("* ")]
#[case(" *")]
#[case("*")]
fn wildcard_parse(#[case] input: &str) {
let no_proxy = NoProxy::from_str(input).expect("static input must parse");
assert!(matches!(no_proxy, NoProxy::Wildcard));
}
#[rstest]
#[case("10.255.255.255")]
#[case("10.100.100.100")]
#[case("10.10.10.10")]
#[case("10.0.0.1")]
#[case("1.2.3.255")]
#[case("1.2.3.4")]
#[case("my.nested.exception.example.org")]
#[case("my.nested.exception.example.com")]
#[case("example.org")]
#[case("example.com")]
#[case("kube.rs")]
#[case("localhost")]
fn wildcard_match(#[case] input: &str) {
assert_match("*", input, true);
}
#[rstest]
#[case("10.255.255.255", true)]
#[case("10.100.100.100", true)]
#[case("10.10.10.10", true)]
#[case("10.0.0.1", true)]
#[case("1.2.3.255", true)]
#[case("1.2.3.4", true)]
#[case("192.168.0.1", false)]
#[case("127.0.0.1", false)]
#[case("1.2.4.255", false)]
#[case("1.2.4.3", false)]
#[case("my.nested.exception.example.org", false)]
#[case("my.nested.exception.example.com", false)]
#[case("example.org", false)]
#[case("example.com", false)]
#[case("example.net", false)]
#[case("localhost", false)]
fn cidr(#[case] input: &str, #[case] matches: bool) {
assert_match("10.0.0.0/8, 1.2.3.0/24", input, matches);
}
#[rstest]
#[case("10.255.255.255", true)]
#[case("10.0.0.1", true)]
#[case("1.2.3.4", true)]
#[case("10.100.100.100", false)]
#[case("192.168.0.1", false)]
#[case("10.10.10.10", false)]
#[case("127.0.0.1", false)]
#[case("1.2.4.255", false)]
#[case("1.2.3.255", false)]
#[case("1.2.4.3", false)]
#[case("my.nested.exception.example.org", false)]
#[case("my.nested.exception.example.com", false)]
#[case("example.org", false)]
#[case("example.com", false)]
#[case("example.net", false)]
#[case("localhost", false)]
fn ip_addr(#[case] input: &str, #[case] matches: bool) {
assert_match("10.255.255.255, 10.0.0.1, 1.2.3.4", input, matches);
}
#[rstest]
#[case("my.nested.exception.example.org", true)]
#[case("my.nested.exception.example.com", true)]
#[case("exception.example.org", true)]
#[case("exception.example.com", true)]
#[case("kube.rs", true)]
#[case("localhost", true)]
#[case("exception.kube.rs", false)]
#[case("example.org", false)]
#[case("example.com", false)]
#[case("example.net", false)]
#[case("local", false)]
#[case("10.255.255.255", false)]
#[case("10.100.100.100", false)]
#[case("10.10.10.10", false)]
#[case("10.0.0.1", false)]
#[case("1.2.3.255", false)]
#[case("1.2.3.4", false)]
fn host(#[case] input: &str, #[case] matches: bool) {
assert_match("*.example.org, .example.com, kube.rs, localhost", input, matches);
}
}