use std::net::SocketAddr;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum HttpScheme {
Http,
Https,
}
impl HttpScheme {
#[must_use]
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Http => "http",
Self::Https => "https",
}
}
#[must_use]
pub(crate) fn default_port(self) -> u16 {
match self {
Self::Http => 80,
Self::Https => 443,
}
}
#[must_use]
pub(crate) fn is_https(self) -> bool {
matches!(self, Self::Https)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct HttpOrigin {
scheme: HttpScheme,
host: String,
port: u16,
}
impl HttpOrigin {
pub(crate) fn from_uri(uri: &http::Uri) -> Result<Self> {
let scheme_str = uri.scheme_str().ok_or_else(|| {
Error::InvalidUrl(
"native request URI must be absolute with http or https scheme".into(),
)
})?;
let scheme = if scheme_str.eq_ignore_ascii_case("http") {
HttpScheme::Http
} else if scheme_str.eq_ignore_ascii_case("https") {
HttpScheme::Https
} else {
return Err(Error::Unsupported(
"native request URI must use http or https and include an authority".into(),
));
};
let authority = uri.authority().ok_or_else(|| {
Error::Unsupported(
"native request URI must use http or https and include an authority".into(),
)
})?;
let authority_str = authority.as_str();
if authority_str.contains('@') {
return Err(Error::InvalidUrl(
"URL userinfo is not supported; configure authentication explicitly".into(),
));
}
let host = uri.host().ok_or_else(|| {
Error::Unsupported(
"native request URI must use http or https and include an authority".into(),
)
})?;
if host.is_empty() {
return Err(Error::Unsupported(
"native request URI must use http or https and include an authority".into(),
));
}
let canonical_host = if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
host[1..host.len() - 1].to_ascii_lowercase()
} else {
host.to_ascii_lowercase()
};
if canonical_host.is_empty() {
return Err(Error::Unsupported(
"native request URI must use http or https and include an authority".into(),
));
}
let has_explicit_port = if authority_str.starts_with('[') {
match authority_str.find(']') {
Some(end) => authority_str[end + 1..].starts_with(':'),
None => {
return Err(Error::InvalidUrl(
"native request URI has an invalid authority".into(),
));
}
}
} else {
authority_str.contains(':')
};
let port = if let Some(port) = uri.port_u16() {
port
} else {
if has_explicit_port || uri.port().is_some() {
return Err(Error::InvalidUrl(
"native request URI has an invalid port".into(),
));
}
scheme.default_port()
};
Ok(Self {
scheme,
host: canonical_host,
port,
})
}
#[cfg(feature = "high-level-url")]
pub(crate) fn from_url(url: &url::Url) -> Option<Self> {
let scheme = if url.scheme().eq_ignore_ascii_case("http") {
HttpScheme::Http
} else if url.scheme().eq_ignore_ascii_case("https") {
HttpScheme::Https
} else {
return None;
};
let host = url.host_str()?;
if host.is_empty() {
return None;
}
let port = url.port_or_known_default()?;
Some(Self {
scheme,
host: host.to_ascii_lowercase(),
port,
})
}
#[must_use]
pub(crate) fn scheme_str(&self) -> &'static str {
self.scheme.as_str()
}
#[must_use]
pub(crate) fn host(&self) -> &str {
&self.host
}
#[must_use]
pub(crate) fn port_ref(&self) -> u16 {
self.port
}
#[must_use]
pub(crate) fn is_https(&self) -> bool {
self.scheme.is_https()
}
#[must_use]
pub(crate) fn origin_string(&self) -> String {
format!("{}://{}:{}", self.scheme.as_str(), self.host, self.port)
}
}
impl std::fmt::Display for HttpOrigin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}://{}:{}", self.scheme.as_str(), self.host, self.port)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EffectivePortSubject {
ResolvedDestination,
ProxiedDestination,
#[cfg_attr(
not(feature = "proxy"),
allow(
dead_code,
reason = "the proxy-peer subject only exists in the proxy profile"
)
)]
ResolvedProxyPeer,
}
impl EffectivePortSubject {
pub(crate) fn requires_http_url(self) -> Error {
match self {
Self::ResolvedDestination => Error::InvalidResolvedTarget(
"resolved destinations require an HTTP or HTTPS URL".into(),
),
Self::ProxiedDestination => Error::InvalidResolvedTarget(
"proxied destinations require an HTTP or HTTPS URL".into(),
),
Self::ResolvedProxyPeer => Error::InvalidProxyUrl(
"resolved proxy peers require the proxy URL's effective port".into(),
),
}
}
pub(crate) fn port_mismatch(self, expected_port: u16) -> Error {
match self {
Self::ResolvedDestination => Error::InvalidResolvedTarget(format!(
"all resolved destinations must use the URL's effective port {expected_port}"
)),
Self::ProxiedDestination => Error::InvalidResolvedTarget(format!(
"all proxied destinations must use the URL's effective port {expected_port}"
)),
Self::ResolvedProxyPeer => Error::InvalidProxyUrl(format!(
"all resolved proxy peers must use the proxy URL's effective port {expected_port}"
)),
}
}
}
pub(crate) fn validate_effective_port(
subject: EffectivePortSubject,
addresses: &[SocketAddr],
expected_port: u16,
) -> Result<()> {
if addresses
.iter()
.any(|address| address.port() != expected_port)
{
return Err(subject.port_mismatch(expected_port));
}
Ok(())
}
#[cfg(feature = "high-level-url")]
pub(crate) fn validate_url_effective_port(
subject: EffectivePortSubject,
url: &url::Url,
addresses: &[SocketAddr],
) -> Result<()> {
let expected_port = url
.port_or_known_default()
.ok_or_else(|| subject.requires_http_url())?;
validate_effective_port(subject, addresses, expected_port)
}
#[cfg(test)]
mod tests {
use super::*;
fn origin(uri: &str) -> HttpOrigin {
let parsed: http::Uri = uri.parse().expect("valid test URI");
HttpOrigin::from_uri(&parsed).expect("origin parses")
}
#[test]
fn http_default_port() {
let o = origin("http://example.com/");
assert_eq!(o.scheme_str(), "http");
assert_eq!(o.host(), "example.com");
assert_eq!(o.port_ref(), 80);
}
#[test]
fn https_default_port() {
let o = origin("https://example.com/");
assert_eq!(o.scheme_str(), "https");
assert_eq!(o.host(), "example.com");
assert_eq!(o.port_ref(), 443);
}
#[test]
fn explicit_non_default_port_preserved() {
let o = origin("http://example.com:8080/path?q=1");
assert_eq!(o.port_ref(), 8080);
assert_eq!(o.host(), "example.com");
}
#[test]
fn explicit_default_port_preserved() {
let o = origin("http://example.com:80/");
assert_eq!(o.port_ref(), 80);
let implicit = origin("http://example.com/");
assert_eq!(o, implicit);
}
#[test]
fn ipv4_authority() {
let o = origin("http://127.0.0.1:8080/");
assert_eq!(o.host(), "127.0.0.1");
assert_eq!(o.port_ref(), 8080);
}
#[test]
fn ipv6_without_port() {
let o = origin("http://[::1]/");
assert_eq!(o.host(), "::1");
assert_eq!(o.port_ref(), 80);
}
#[test]
fn ipv6_with_port() {
let o = origin("https://[2001:db8::1]:8443/path");
assert_eq!(o.host(), "2001:db8::1");
assert_eq!(o.port_ref(), 8443);
}
#[test]
fn missing_scheme_rejected() {
let uri: http::Uri = "/just/a/path".parse().expect("path-only URI");
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(matches!(err, Error::InvalidUrl(_)), "got {err:?}");
}
#[test]
fn missing_authority_rejected() {
match "http:/only-path".parse::<http::Uri>() {
Err(_) => {}
Ok(uri) => {
assert!(uri.authority().is_none());
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(
matches!(err, Error::Unsupported(_)),
"expected unsupported, got {err:?}"
);
}
}
}
#[test]
fn unsupported_scheme_rejected() {
let uri: http::Uri = "ftp://example.com/file".parse().expect("ftp URI");
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "got {err:?}");
}
#[test]
fn userinfo_rejected() {
let uri: http::Uri = "http://user:pass@example.com/"
.parse()
.expect("userinfo URI parses in http crate");
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(
matches!(err, Error::InvalidUrl(_)),
"expected userinfo rejection, got {err:?}"
);
}
#[test]
fn user_without_password_rejected() {
let uri: http::Uri = "http://user@example.com/"
.parse()
.expect("userinfo URI parses in http crate");
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(matches!(err, Error::InvalidUrl(_)), "got {err:?}");
}
#[test]
fn empty_host_rejected() {
match "http:///path".parse::<http::Uri>() {
Err(_) => {}
Ok(uri) => {
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(
matches!(err, Error::Unsupported(_) | Error::InvalidUrl(_)),
"got {err:?}"
);
}
}
}
#[test]
fn malformed_port_rejected() {
for candidate in ["http://example.com:notaport/", "http://example.com:99999/"] {
match candidate.parse::<http::Uri>() {
Err(_) => {}
Ok(uri) => {
let err = HttpOrigin::from_uri(&uri).unwrap_err();
assert!(
matches!(err, Error::InvalidUrl(_)),
"expected invalid port for {candidate}, got {err:?}"
);
}
}
}
}
#[test]
fn path_query_ignored_for_identity() {
let a = origin("https://example.com/a?b=1");
let b = origin("https://example.com/other");
assert_eq!(a, b);
}
#[test]
fn host_lowercased_for_identity() {
let lower = origin("http://example.com/");
let upper = origin("http://EXAMPLE.COM/");
assert_eq!(lower, upper);
}
}