Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix: pin proxy endpoint resolution
ldm0ad0599b6a94d
diff --git a/Cargo.lock b/Cargo.lockindex a94737256..1406d1ee2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3422,7 +3422,6 @@ dependencies = ["http","moli-crypto","moli-curl",- "moli-dns-resolver","moli-url","openssl","rcgen",diff --git a/moli-curl/src/host_resolve.rs b/moli-curl/src/host_resolve.rsnew file mode 100644index 000000000..c952ca5fe--- /dev/null+++ b/moli-curl/src/host_resolve.rs@@ -0,0 +1,191 @@+use std::net::IpAddr;++use anyhow::{Context, Result, bail};++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct HostResolveOverrides {+ entries: Vec<HostResolveEntry>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct HostResolveEntry {+ host: String,+ port: u16,+ addresses: Vec<IpAddr>,+}++impl HostResolveOverrides {+ pub fn parse(entries: &[String]) -> Result<Self> {+ entries+ .iter()+ .map(|entry| parse_entry(entry))+ .collect::<Result<Vec<_>>>()+ .map(|entries| Self { entries })+ }++ pub fn normalized_entries(&self) -> Vec<String> {+ self.entries+ .iter()+ .map(HostResolveEntry::curl_entry)+ .collect()+ }++ pub fn addresses_for(&self, host: &str, port: u16) -> Option<&[IpAddr]> {+ let mut exact_match = None;+ let mut wildcard_match = None;+ for entry in &self.entries {+ if entry.port != port {+ continue;+ }+ if entry.host == "*" {+ wildcard_match = Some(entry.addresses.as_slice());+ } else if entry.host.eq_ignore_ascii_case(host) {+ exact_match = Some(entry.addresses.as_slice());+ }+ }+ exact_match.or(wildcard_match)+ }+}++pub fn validate_http_host_resolve_entries(entries: &[String]) -> Result<()> {+ HostResolveOverrides::parse(entries).map(|_| ())+}++impl HostResolveEntry {+ fn curl_entry(&self) -> String {+ let addresses = self+ .addresses+ .iter()+ .map(format_ip)+ .collect::<Vec<_>>()+ .join(",");+ format!("{}:{}:{addresses}", format_host(&self.host), self.port)+ }+}++fn parse_entry(entry: &str) -> Result<HostResolveEntry> {+ let entry = entry.trim();+ if entry.starts_with('+') || entry.starts_with('-') {+ bail!("--http-host-resolve does not support `+` or `-` prefixes; use HOST:PORT:ADDR");+ }++ let (host, port, address) = split_entry(entry)?;+ let port = port+ .parse::<u16>()+ .with_context(|| format!("invalid --http-host-resolve port in `{entry}`"))?;+ let mut addresses = Vec::new();+ for address in address.split(',').map(str::trim) {+ if address.is_empty() {+ bail!("--http-host-resolve entries must not contain empty addresses");+ }+ let address = address.trim_matches(['[', ']']);+ let address = address+ .parse::<IpAddr>()+ .with_context(|| format!("invalid --http-host-resolve address in `{entry}`"))?;+ if !addresses.contains(&address) {+ addresses.push(address);+ }+ }++ Ok(HostResolveEntry {+ host: host.trim_matches(['[', ']']).to_owned(),+ port,+ addresses,+ })+}++fn split_entry(entry: &str) -> Result<(&str, &str, &str)> {+ if let Some(entry) = entry.strip_prefix('[') {+ let Some(host_end) = entry.find(']') else {+ bail!("--http-host-resolve must be in HOST:PORT:ADDR form");+ };+ let host = &entry[..host_end];+ let remainder = &entry[host_end + 1..];+ let Some(remainder) = remainder.strip_prefix(':') else {+ bail!("--http-host-resolve must be in HOST:PORT:ADDR form");+ };+ let Some((port, address)) = remainder.split_once(':') else {+ bail!("--http-host-resolve must be in HOST:PORT:ADDR form");+ };+ if host.trim().is_empty() || port.trim().is_empty() || address.trim().is_empty() {+ bail!("--http-host-resolve must be in HOST:PORT:ADDR form");+ }+ return Ok((host.trim(), port.trim(), address.trim()));+ }++ let mut parts = entry.splitn(3, ':');+ let host = parts.next().unwrap_or_default().trim();+ let port = parts.next().unwrap_or_default().trim();+ let address = parts.next().unwrap_or_default().trim();+ if host.is_empty() || port.is_empty() || address.is_empty() {+ bail!("--http-host-resolve must be in HOST:PORT:ADDR form");+ }+ Ok((host, port, address))+}++fn format_host(host: &str) -> String {+ if host != "*" && host.contains(':') {+ format!("[{host}]")+ } else {+ host.to_owned()+ }+}++fn format_ip(ip: &IpAddr) -> String {+ match ip {+ IpAddr::V4(ip) => ip.to_string(),+ IpAddr::V6(ip) => format!("[{ip}]"),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn entries_are_normalized_and_exact_matches_beat_wildcards() {+ let overrides = HostResolveOverrides::parse(&[+ " *:443:192.0.2.1 ".to_owned(),+ " example.test:443: 198.51.100.1, [2001:db8::1] ".to_owned(),+ " [2001:db8::2]:80: 203.0.113.1 ".to_owned(),+ ])+ .unwrap();++ assert_eq!(+ overrides.normalized_entries(),+ [+ "*:443:192.0.2.1",+ "example.test:443:198.51.100.1,[2001:db8::1]",+ "[2001:db8::2]:80:203.0.113.1",+ ]+ );+ assert_eq!(+ overrides.addresses_for("EXAMPLE.TEST", 443).unwrap(),+ [+ "198.51.100.1".parse::<IpAddr>().unwrap(),+ "2001:db8::1".parse::<IpAddr>().unwrap(),+ ]+ );+ assert_eq!(+ overrides.addresses_for("other.test", 443).unwrap(),+ ["192.0.2.1".parse::<IpAddr>().unwrap()]+ );+ }++ #[test]+ fn curl_prefix_syntax_is_rejected() {+ for entry in [+ "+example.test:443:93.184.216.34",+ "-example.test:443",+ "-example.test:443:93.184.216.34",+ ] {+ let error = HostResolveOverrides::parse(&[entry.to_owned()]).unwrap_err();+ assert!(+ error+ .to_string()+ .contains("does not support `+` or `-` prefixes"),+ "{error:#}"+ );+ }+ }+}diff --git a/moli-curl/src/lib.rs b/moli-curl/src/lib.rsindex b2a246eaa..e7c540e4f 100644--- a/moli-curl/src/lib.rs+++ b/moli-curl/src/lib.rs@@ -1,6 +1,7 @@//! Shared libcurl multi scheduler for Moli network requests.mod dns_adapter;+mod host_resolve;mod http;mod network_policy;mod proxy;@@ -9,11 +10,12 @@ mod tls;pub mod websocket;pub use dns_adapter::CurlDnsResolution;+pub use host_resolve::{HostResolveOverrides, validate_http_host_resolve_entries};pub use http::{CurlHttpSender, CurlMultiCompletion, CurlMultiJob, CurlOriginKey, CurlSubmitError};pub use network_policy::NetworkAddressPolicy;pub use proxy::{- ProxyRoute, ProxyScheme, ProxyTargetResolution, SelectedProxy, select_proxy_route,- select_proxy_route_with_env,+ ConnectionDnsEndpoint, ConnectionEndpointRole, ProxyRoute, ProxyScheme, ProxyTargetResolution,+ SelectedProxy, select_proxy_route, select_proxy_route_with_env,};pub use runtime::{CurlMultiRuntime, CurlMultiRuntimeConfig, CurlTransferId};pub use tls::CurlTlsConfig;diff --git a/moli-curl/src/proxy.rs b/moli-curl/src/proxy.rsindex 22045b575..196382cdf 100644--- a/moli-curl/src/proxy.rs+++ b/moli-curl/src/proxy.rs@@ -2,8 +2,11 @@ use std::net::IpAddr;use anyhow::{Context, Result, bail};use cidr::AnyIpCidr;+use moli_dns_resolver::DnsTarget;use url::{Host, Url};+use crate::HostResolveOverrides;+/// How an accepted proxy resolves the request target hostname.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ProxyTargetResolution {@@ -11,6 +14,28 @@ pub enum ProxyTargetResolution {Proxy,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ConnectionEndpointRole {+ RequestTarget,+ Proxy,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ConnectionDnsEndpoint {+ target: DnsTarget,+ role: ConnectionEndpointRole,+}++impl ConnectionDnsEndpoint {+ pub fn target(&self) -> &DnsTarget {+ &self.target+ }++ pub fn role(&self) -> ConnectionEndpointRole {+ self.role+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ProxyScheme {Http,@@ -131,6 +156,68 @@ impl ProxyRoute {Self::Proxy(proxy) => Some(proxy),}}++ /// Returns the one hostname Moli must resolve locally for this route.+ ///+ /// IP literals and fixed host-resolve entries need no lookup. A direct+ /// route resolves the request target; a remote-DNS proxy route resolves+ /// only the proxy endpoint.+ pub fn connection_dns_endpoint(+ &self,+ request_url: &Url,+ host_resolve: &HostResolveOverrides,+ ) -> Result<Option<ConnectionDnsEndpoint>> {+ let request_host = request_url+ .host_str()+ .with_context(|| format!("request URL `{request_url}` is missing a host"))?;+ let request_port = request_url+ .port_or_known_default()+ .with_context(|| format!("request URL `{request_url}` has no port"))?;++ match self {+ Self::Direct => {+ if request_url+ .host()+ .is_some_and(|host| matches!(host, Host::Domain(_)))+ && host_resolve+ .addresses_for(request_host, request_port)+ .is_none()+ {+ return Ok(Some(ConnectionDnsEndpoint {+ target: DnsTarget::new(request_host, request_port),+ role: ConnectionEndpointRole::RequestTarget,+ }));+ }+ Ok(None)+ }+ Self::Proxy(proxy) => {+ let proxy_is_request_endpoint =+ proxy.endpoint_host().eq_ignore_ascii_case(request_host)+ && proxy.endpoint_port() == request_port;+ if !proxy_is_request_endpoint+ && host_resolve+ .addresses_for(request_host, request_port)+ .is_some()+ {+ bail!(+ "--http-host-resolve entry for proxied target `{request_host}:{request_port}` would be ignored; remote-DNS proxy `{}` resolves request target hostnames",+ proxy.url()+ );+ }+ if proxy.endpoint_ip().is_none()+ && host_resolve+ .addresses_for(proxy.endpoint_host(), proxy.endpoint_port())+ .is_none()+ {+ return Ok(Some(ConnectionDnsEndpoint {+ target: DnsTarget::new(proxy.endpoint_host(), proxy.endpoint_port()),+ role: ConnectionEndpointRole::Proxy,+ }));+ }+ Ok(None)+ }+ }+ }}pub fn select_proxy_route(@@ -415,4 +502,64 @@ mod tests {assert!(error.to_string().contains("remote-DNS proxy scheme"));}}++ #[test]+ fn route_selects_only_the_locally_connected_dns_endpoint() {+ let empty = HostResolveOverrides::default();+ let direct = ProxyRoute::Direct;+ let direct_endpoint = direct+ .connection_dns_endpoint(&Url::parse("https://origin.test/path").unwrap(), &empty)+ .unwrap()+ .unwrap();+ assert_eq!(+ direct_endpoint.role(),+ ConnectionEndpointRole::RequestTarget+ );+ assert_eq!(+ direct_endpoint.target(),+ &DnsTarget::new("origin.test", 443)+ );++ let proxy = ProxyRoute::from_proxy_url("http://proxy.test:8080").unwrap();+ let proxy_endpoint = proxy+ .connection_dns_endpoint(&Url::parse("https://origin.test/path").unwrap(), &empty)+ .unwrap()+ .unwrap();+ assert_eq!(proxy_endpoint.role(), ConnectionEndpointRole::Proxy);+ assert_eq!(proxy_endpoint.target(), &DnsTarget::new("proxy.test", 8080));++ let ip_proxy = ProxyRoute::from_proxy_url("http://192.0.2.1:8080").unwrap();+ assert!(+ ip_proxy+ .connection_dns_endpoint(&Url::parse("https://origin.test/path").unwrap(), &empty,)+ .unwrap()+ .is_none()+ );+ }++ #[test]+ fn proxy_endpoint_override_avoids_dns_and_target_override_is_rejected() {+ let proxy = ProxyRoute::from_proxy_url("http://proxy.test:8080").unwrap();+ let proxy_override =+ HostResolveOverrides::parse(&["proxy.test:8080:192.0.2.1".to_owned()]).unwrap();+ assert!(+ proxy+ .connection_dns_endpoint(+ &Url::parse("https://origin.test/path").unwrap(),+ &proxy_override,+ )+ .unwrap()+ .is_none()+ );++ let target_override =+ HostResolveOverrides::parse(&["origin.test:443:198.51.100.1".to_owned()]).unwrap();+ let error = proxy+ .connection_dns_endpoint(+ &Url::parse("https://origin.test/path").unwrap(),+ &target_override,+ )+ .unwrap_err();+ assert!(error.to_string().contains("would be ignored"), "{error:#}");+ }}diff --git a/moli-curl/src/websocket.rs b/moli-curl/src/websocket.rsindex 37fe5d56e..79ac56bb4 100644--- a/moli-curl/src/websocket.rs+++ b/moli-curl/src/websocket.rs@@ -46,6 +46,8 @@ pub struct CurlWebSocketRequest {pub proxy: Option<String>,pub proxy_headers: Vec<(String, String)>,pub tls: CurlTlsConfig,+ /// Permanent `CURLOPT_RESOLVE` entries selected by the high-level route.+ pub resolve_entries: Vec<String>,pub dns_resolution: CurlDnsResolution,pub handshake_timeout: Duration,}@@ -58,6 +60,7 @@ impl CurlWebSocketRequest {proxy: None,proxy_headers: Vec::new(),tls: CurlTlsConfig::default(),+ resolve_entries: Vec::new(),dns_resolution: CurlDnsResolution::no_shared_resolution(),handshake_timeout: Duration::from_secs(30),}diff --git a/moli-curl/src/websocket/connector.rs b/moli-curl/src/websocket/connector.rsindex adc331e18..298a56bb4 100644--- a/moli-curl/src/websocket/connector.rs+++ b/moli-curl/src/websocket/connector.rs@@ -3,7 +3,10 @@use super::{CurlWebSocketConnection, CurlWebSocketRequest, SESSION_CAPACITY, connection::SessionIo,};-use crate::{CurlTransferId, NetworkAddressPolicy, runtime::identity::next_transfer_id};+use crate::{+ CurlTransferId, HostResolveOverrides, NetworkAddressPolicy, SelectedProxy,+ runtime::identity::next_transfer_id,+};use anyhow::{Context, Result, bail};use curl::multi::MultiWaker;use std::sync::{@@ -100,20 +103,32 @@ impl CurlWebSocketConnector {let url = Url::parse(&request.url).with_context(|| format!("failed to parse WebSocket URL `{}`", request.url))?;+ // A validated remote-DNS proxy owns request-target admission. An empty+ // proxy string disables proxying in curl, while socks4/socks5 resolve+ // the target locally; neither may bypass direct-target admission.+ if let Some(proxy) = request.proxy.as_deref().filter(|proxy| !proxy.is_empty()) {+ SelectedProxy::parse(proxy).with_context(|| {+ format!(+ "network address policy requires a supported remote-DNS WebSocket proxy, got `{proxy}`"+ )+ })?;+ return Ok(());+ }let host = url.host().ok_or_else(|| anyhow::anyhow!("WebSocket URL `{url}` is missing a host"))?;match host {Host::Domain(host) => {- if request.proxy.is_some() {- bail!(- "cannot enforce network address policy for proxied WebSocket hostname `{host}` in `{url}`; the proxy must not resolve an unchecked target hostname"- );- }let port = url.port_or_known_default().ok_or_else(|| anyhow::anyhow!("WebSocket URL `{url}` has no port"))?;+ let host_resolve = HostResolveOverrides::parse(&request.resolve_entries)?;+ if let Some(addresses) = host_resolve.addresses_for(host, port) {+ return self+ .network_address_policy+ .check_addresses(addresses, url.as_str());+ }let target = request.dns_resolution.target().ok_or_else(|| {anyhow::anyhow!("network address policy requires shared DNS resolution for WebSocket hostname `{host}` in `{url}`"diff --git a/moli-curl/src/websocket/request.rs b/moli-curl/src/websocket/request.rsindex 6b42bb7bb..488974503 100644--- a/moli-curl/src/websocket/request.rs+++ b/moli-curl/src/websocket/request.rs@@ -1,4 +1,4 @@-use anyhow::{Result, bail};+use anyhow::{Context, Result, anyhow, bail};use curl::easy::{Easy2, Handler, HttpVersion, InfoType, List, WsOptions};use super::CurlWebSocketRequest;@@ -86,6 +86,16 @@ pub(super) fn configure(request: &CurlWebSocketRequest) -> Result<Easy2<Handshakeasy.noproxy("")?;easy.http_proxy_tunnel(request.proxy.as_deref().is_some_and(proxy_uses_http_tunnel))?;easy.separate_proxy_headers(true)?;+ if !request.resolve_entries.is_empty() {+ let mut resolve = List::new();+ for entry in &request.resolve_entries {+ resolve+ .append(entry)+ .with_context(|| anyhow!("failed to build curl host resolve entry `{entry}`"))?;+ }+ easy.resolve(resolve)+ .context("failed to configure curl host resolve overrides")?;+ }easy.http_headers(headers(&request.headers)?)?;easy.proxy_headers(headers(&request.proxy_headers)?)?;// Capture HeaderOut through our handler; never print debug or credentials.diff --git a/moli-curl/src/websocket/tests.rs b/moli-curl/src/websocket/tests.rsindex 3fa09da7b..0ca049981 100644--- a/moli-curl/src/websocket/tests.rs+++ b/moli-curl/src/websocket/tests.rs@@ -19,19 +19,74 @@ mod storage;const DEADLINE: Duration = Duration::from_secs(10);#[test]-fn strict_connector_rejects_proxy_resolved_websocket_hostname() {+fn address_policy_leaves_proxy_resolved_websocket_target_to_proxy() {let runtime = CurlWebSocketRuntime::new().unwrap();let connector = runtime.connector().with_network_address_policy(NetworkAddressPolicy::new(true, Vec::new()));let mut request = CurlWebSocketRequest::new("wss://example.test/socket".to_owned());- request.proxy = Some("http://proxy.test:8080".to_owned());+ request.proxy = Some("http://127.0.0.1:1".to_owned());++ let connection = connector+ .connect(request)+ .expect("request-target policy must not reject a proxy-resolved hostname");+ drop(connection);+}++#[test]+fn address_policy_does_not_treat_an_empty_proxy_as_remote_dns() {+ let runtime = CurlWebSocketRuntime::new().unwrap();+ let connector = runtime+ .connector()+ .with_network_address_policy(NetworkAddressPolicy::new(true, Vec::new()));+ let mut request = CurlWebSocketRequest::new("ws://127.0.0.1/socket".to_owned());+ request.proxy = Some(String::new());++ let error = connector+ .connect(request)+ .expect_err("an empty curl proxy setting is still a direct connection");+ assert!(+ error+ .to_string()+ .contains("blocked private network address")+ );+}++#[test]+fn address_policy_rejects_a_local_dns_websocket_proxy() {+ let runtime = CurlWebSocketRuntime::new().unwrap();+ let connector = runtime+ .connector()+ .with_network_address_policy(NetworkAddressPolicy::new(true, Vec::new()));+ let mut request = CurlWebSocketRequest::new("ws://example.test/socket".to_owned());+ request.proxy = Some("socks5://127.0.0.1:1080".to_owned());let error = connector.connect(request)- .expect_err("a strict connector cannot verify proxy-side DNS");+ .expect_err("a local-DNS proxy cannot satisfy request-target admission");+ assert!(+ format!("{error:#}").contains("supported remote-DNS WebSocket proxy"),+ "{error:#}"+ );+}++#[test]+fn strict_connector_checks_fixed_websocket_target_before_connecting() {+ let runtime = CurlWebSocketRuntime::new().unwrap();+ let connector = runtime+ .connector()+ .with_network_address_policy(NetworkAddressPolicy::new(true, Vec::new()));+ let mut request = CurlWebSocketRequest::new("ws://example.test:65534/socket".to_owned());+ request.resolve_entries = vec!["example.test:65534:127.0.0.1".to_owned()];- assert!(error.to_string().contains("proxied WebSocket hostname"));+ let error = connector+ .connect(request)+ .expect_err("a fixed private WebSocket target must be rejected before connecting");+ assert!(+ error+ .to_string()+ .contains("blocked private network address")+ );}#[tokio::test]diff --git a/moli-fetch/src/blocking/mod.rs b/moli-fetch/src/blocking/mod.rsindex 7235084cd..f4f52acd7 100644--- a/moli-fetch/src/blocking/mod.rs+++ b/moli-fetch/src/blocking/mod.rs@@ -14,6 +14,7 @@ use moli_cookie_jar::{NetworkCookieRequestContext, SharedBrowserCookieStore, StoredCookieQueryReport,StoredCookieSetReport, same_site_urls,};+use moli_curl::HostResolveOverrides;use moli_url::is_potentially_trustworthy_url;use moli_url_policy::ensure_http_network_transport_url;use tracing::debug;@@ -164,13 +165,6 @@ pub(crate) fn outgoing_request_headers_for_url() -> Vec<(String, String)> {let mut outgoing = Vec::new();- if let Some(proxy_bearer_token) = config.proxy_bearer_token() {- outgoing.push((- "Proxy-Authorization".to_owned(),- format!("Bearer {proxy_bearer_token}"),- ));- }-if let Some(cookie_header) = cookie_header {outgoing.push(("Cookie".to_owned(), cookie_header.to_owned()));}@@ -238,19 +232,6 @@ pub(crate) fn outgoing_request_headers_for_url());}- if let Some(auth) = request.auth()- && auth.target == RequestAuthTarget::ProxyHeader- && !header_present(&outgoing, "proxy-authorization")- {- outgoing.push((- "Proxy-Authorization".to_owned(),- format!(- "Basic {}",- encode_basic_auth(&auth.username, &auth.password)- ),- ));- }-outgoing}@@ -543,7 +524,12 @@ pub(crate) fn configure_easy<H: Handler>(validation_headers: Option<Vec<(String, String)>>,) -> Result<Vec<(String, String)>> {ensure_http_network_transport_url(request_url)?;- enforce_request_target_policy(config, request_url)?;+ if crate::should_request_be_blocked_due_to_bad_port(request_url) {+ bail!("blocked bad port for `{request_url}`");+ }+ if matches!(proxy_route, HttpProxyRoute::Direct) {+ enforce_request_target_address_policy(config, request_url)?;+ }configure_curl_http_protocol_allowlist(easy)?;// Keep proxy CONNECT handshake headers out of the response callbacks so@@ -638,9 +624,11 @@ pub(crate) fn configure_easy<H: Handler>(HttpProxyRoute::Direct => easy.proxy("").context("failed to disable the HTTP proxy for a direct request")?,- HttpProxyRoute::Proxy(proxy) => easy- .proxy(proxy.url())- .with_context(|| anyhow!("failed to configure HTTP proxy `{}`", proxy.url()))?,+ HttpProxyRoute::Proxy(proxy) => {+ easy.proxy(proxy.url())+ .with_context(|| anyhow!("failed to configure HTTP proxy `{}`", proxy.url()))?;+ configure_proxy_headers(easy, config, request, proxy.scheme().uses_http_headers())?;+ }}// Proxy bypass has already been resolved into `proxy_route`. Keep curl// from re-evaluating environment `no_proxy` after that security decision.@@ -660,6 +648,16 @@ pub(crate) fn configure_easy<H: Handler>(let mut headers = List::new();let mut outgoing_headers =outgoing_request_headers_for_url(config, request, request_url, cookie_header);+ // A 407 can come from a transparent proxy even when no explicit proxy+ // route is configured. In that case the connected endpoint receives the+ // challenge response as a normal request header. Explicit proxies use the+ // separate CURLOPT_PROXYHEADER path configured above.+ if matches!(proxy_route, HttpProxyRoute::Direct)+ && let Some(authorization) = proxy_header_authorization(request)+ && !header_present(&outgoing_headers, "proxy-authorization")+ {+ outgoing_headers.push(("Proxy-Authorization".to_owned(), authorization));+ }if let Some(web_bot_auth) = config.web_bot_auth() {web_bot_auth.append_request_headers(&mut outgoing_headers, &request.method, request_url)@@ -749,11 +747,50 @@ pub(crate) fn configure_easy<H: Handler>(Ok(outgoing_headers)}-fn enforce_request_target_policy(config: &FetchConfig, request_url: &Url) -> Result<()> {- if crate::should_request_be_blocked_due_to_bad_port(request_url) {- bail!("blocked bad port for `{request_url}`");+fn configure_proxy_headers<H: Handler>(+ easy: &mut Easy2<H>,+ config: &FetchConfig,+ request: &Request,+ proxy_uses_http_headers: bool,+) -> Result<()> {+ let explicit_proxy_header_auth = proxy_header_authorization(request);+ if !proxy_uses_http_headers {+ if config.proxy_bearer_token().is_some() || explicit_proxy_header_auth.is_some() {+ bail!("Proxy-Authorization headers require an HTTP(S) proxy");+ }+ return Ok(());+ }++ easy.separate_proxy_headers(true)+ .context("failed to separate proxy headers from origin request headers")?;+ let authorization = config+ .proxy_bearer_token()+ .map(|token| format!("Bearer {token}"))+ .or(explicit_proxy_header_auth);+ if let Some(authorization) = authorization {+ let mut headers = List::new();+ headers+ .append(&format!("Proxy-Authorization: {authorization}"))+ .context("failed to build proxy authorization header")?;+ easy.proxy_headers(headers)+ .context("failed to configure HTTP proxy headers")?;}+ Ok(())+}++fn proxy_header_authorization(request: &Request) -> Option<String> {+ request+ .auth()+ .filter(|auth| auth.target == RequestAuthTarget::ProxyHeader)+ .map(|auth| {+ format!(+ "Basic {}",+ encode_basic_auth(&auth.username, &auth.password)+ )+ })+}+fn enforce_request_target_address_policy(config: &FetchConfig, request_url: &Url) -> Result<()> {if !config.block_private_networks() && config.block_cidrs().is_empty() {return Ok(());}@@ -787,140 +824,13 @@ pub(crate) fn resolve_host_resolve_override_ips(host: &str,port: u16,) -> Result<Option<Vec<IpAddr>>> {- let mut exact_match: Option<Vec<IpAddr>> = None;- let mut wildcard_match: Option<Vec<IpAddr>> = None;- for entry in entries {- let entry = parse_http_host_resolve_entry(entry)?;- if entry.port == port {- if entry.host == "*" {- wildcard_match = Some(entry.addresses);- } else if entry.host.eq_ignore_ascii_case(host) {- exact_match = Some(entry.addresses);- }- }- }-- Ok(exact_match.or(wildcard_match))-}--struct HttpHostResolveEntry {- host: String,- port: u16,- addresses: Vec<IpAddr>,-}--impl HttpHostResolveEntry {- fn curl_entry(&self) -> String {- let addresses = self- .addresses- .iter()- .map(format_http_host_resolve_ip)- .collect::<Vec<_>>()- .join(",");- format!(- "{}:{}:{addresses}",- format_http_host_resolve_host(&self.host),- self.port- )- }+ Ok(HostResolveOverrides::parse(entries)?+ .addresses_for(host, port)+ .map(<[IpAddr]>::to_vec))}pub(crate) fn normalized_http_host_resolve_entries(entries: &[String]) -> Result<Vec<String>> {- entries- .iter()- .map(|entry| parse_http_host_resolve_entry(entry).map(|entry| entry.curl_entry()))- .collect()-}--pub fn validate_http_host_resolve_entries(entries: &[String]) -> Result<()> {- for entry in entries {- parse_http_host_resolve_entry(entry)?;- }- Ok(())-}--fn parse_http_host_resolve_entry(entry: &str) -> Result<HttpHostResolveEntry> {- let entry = entry.trim();- if entry.starts_with('+') || entry.starts_with('-') {- bail!("--http-host-resolve does not support `+` or `-` prefixes; use HOST:PORT:ADDR");- }-- let (host, port, address) = split_http_host_resolve_add_entry(entry)?;- let port = parse_http_host_resolve_port(port, entry)?;- let mut addresses = Vec::new();- for address in address.split(',').map(str::trim) {- if address.is_empty() {- bail!("--http-host-resolve entries must not contain empty addresses");- }- let address = address.trim_matches(['[', ']']);- let address = address- .parse::<IpAddr>()- .with_context(|| format!("invalid --http-host-resolve address in `{entry}`"))?;- if !addresses.contains(&address) {- addresses.push(address);- }- }-- Ok(HttpHostResolveEntry {- host: normalize_http_host_resolve_host(host),- port,- addresses,- })-}--fn split_http_host_resolve_add_entry(entry: &str) -> Result<(&str, &str, &str)> {- if let Some(entry) = entry.strip_prefix('[') {- let Some(host_end) = entry.find(']') else {- bail!("--http-host-resolve must be in HOST:PORT:ADDR form");- };- let host = &entry[..host_end];- let remainder = &entry[host_end + 1..];- let Some(remainder) = remainder.strip_prefix(':') else {- bail!("--http-host-resolve must be in HOST:PORT:ADDR form");- };- let Some((port, address)) = remainder.split_once(':') else {- bail!("--http-host-resolve must be in HOST:PORT:ADDR form");- };- if host.trim().is_empty() || port.trim().is_empty() || address.trim().is_empty() {- bail!("--http-host-resolve must be in HOST:PORT:ADDR form");- }- return Ok((host.trim(), port.trim(), address.trim()));- }-- let mut parts = entry.splitn(3, ':');- let host = parts.next().unwrap_or_default().trim();- let port = parts.next().unwrap_or_default().trim();- let address = parts.next().unwrap_or_default().trim();-- if host.is_empty() || port.is_empty() || address.is_empty() {- bail!("--http-host-resolve must be in HOST:PORT:ADDR form");- }-- Ok((host, port, address))-}--fn parse_http_host_resolve_port(port: &str, entry: &str) -> Result<u16> {- port.parse::<u16>()- .with_context(|| format!("invalid --http-host-resolve port in `{entry}`"))-}--fn normalize_http_host_resolve_host(host: &str) -> String {- host.trim_matches(['[', ']']).to_owned()-}--fn format_http_host_resolve_host(host: &str) -> String {- if host != "*" && host.contains(':') {- format!("[{host}]")- } else {- host.to_owned()- }-}--fn format_http_host_resolve_ip(ip: &IpAddr) -> String {- match ip {- IpAddr::V4(ip) => ip.to_string(),- IpAddr::V6(ip) => format!("[{ip}]"),- }+ Ok(HostResolveOverrides::parse(entries)?.normalized_entries())}fn configure_curl_http_protocol_allowlist<H: Handler>(easy: &mut Easy2<H>) -> Result<()> {@@ -1508,6 +1418,20 @@ mod tests {}}+ #[test]+ fn configured_proxy_bearer_token_is_not_an_origin_header() {+ let mut config = FetchConfig::default();+ config.set_proxy_options(+ Some("http://proxy.test:8080".to_owned()),+ Some("secret".to_owned()),+ );+ let request = Request::get("http://example.test/").unwrap();++ let headers = outgoing_request_headers_for_url(&config, &request, &request.url, None);++ assert!(!header_present(&headers, "proxy-authorization"));+ }+#[test]fn third_party_credentialed_request_reports_active_storage_access() {let config = FetchConfig::default();diff --git a/moli-fetch/src/client.rs b/moli-fetch/src/client.rsindex d6a48e1fa..6324f904f 100644--- a/moli-fetch/src/client.rs+++ b/moli-fetch/src/client.rs@@ -182,6 +182,10 @@ impl FetchClientHandle {self.config.http_proxy()}+ pub fn http_host_resolve(&self) -> &[String] {+ self.config.http_host_resolve()+ }+pub fn http_no_proxy(&self) -> Option<&str> {self.config.http_no_proxy()}diff --git a/moli-fetch/src/dns.rs b/moli-fetch/src/dns.rsindex 6a4d5f7ce..4fa2b645d 100644--- a/moli-fetch/src/dns.rs+++ b/moli-fetch/src/dns.rs@@ -1,26 +1,19 @@-use anyhow::{Result, bail};-use moli_curl::CurlDnsResolution;+use anyhow::Result;+use moli_curl::{ConnectionEndpointRole, CurlDnsResolution, HostResolveOverrides};use moli_dns_resolver::DnsTarget;-use url::{Host, Url};+use url::Url;-use crate::{- FetchConfig,- blocking::{normalized_http_host_resolve_entries, resolve_host_resolve_override_ips},- proxy::HttpProxyRoute,-};+use crate::{FetchConfig, proxy::HttpProxyRoute};/// Fetch-side DNS admission decision.///-/// The shared resolver is used only when Fetch can prove that curl will-/// connect directly to an HTTP(S) origin. Proxy traffic needs no shared origin-/// lookup only when no address policy is active; otherwise a proxy-resolved-/// hostname cannot be verified locally and is rejected. IP literals and-/// matching explicit host-resolve entries already have exact routing and are-/// checked synchronously before this decision.+/// Each request resolves at most the one hostname curl will connect to locally:+/// the origin for a direct route or the proxy endpoint for a proxy route.#[derive(Debug, Clone, PartialEq, Eq)]enum FetchCurlDnsAdmission {NoSharedResolution,- SharedResolver(DnsTarget),+ DirectTarget(DnsTarget),+ ProxyEndpoint(DnsTarget),}pub(crate) fn curl_dns_resolution(@@ -28,47 +21,42 @@ pub(crate) fn curl_dns_resolution(url: &Url,proxy_route: &HttpProxyRoute,) -> Result<CurlDnsResolution> {- match curl_dns_admission(config, url, proxy_route)? {+ let host_resolve = HostResolveOverrides::parse(config.http_host_resolve())?;+ let static_entries = host_resolve.normalized_entries();+ match curl_dns_admission(url, proxy_route, &host_resolve)? {FetchCurlDnsAdmission::NoSharedResolution => Ok(CurlDnsResolution::no_shared_resolution()),- FetchCurlDnsAdmission::SharedResolver(target) => {+ FetchCurlDnsAdmission::DirectTarget(target) => {let policy = config.network_address_policy();- Ok(CurlDnsResolution::resolve_endpoint(- target,- normalized_http_host_resolve_entries(config.http_host_resolve())?,- )- .with_network_address_policy(policy, url.to_string()))+ Ok(CurlDnsResolution::resolve_endpoint(target, static_entries)+ .with_network_address_policy(policy, url.to_string()))+ }+ FetchCurlDnsAdmission::ProxyEndpoint(target) => {+ Ok(CurlDnsResolution::resolve_endpoint(target, static_entries))}}}fn curl_dns_admission(- config: &FetchConfig,url: &Url,proxy_route: &HttpProxyRoute,+ host_resolve: &HostResolveOverrides,) -> Result<FetchCurlDnsAdmission> {if !matches!(url.scheme(), "http" | "https") {return Ok(FetchCurlDnsAdmission::NoSharedResolution);}- let Some(Host::Domain(host)) = url.host() else {- return Ok(FetchCurlDnsAdmission::NoSharedResolution);- };- let Some(port) = url.port_or_known_default() else {- return Ok(FetchCurlDnsAdmission::NoSharedResolution);- };- if proxy_route.is_proxy() {- if config.network_address_policy().is_enforced() {- bail!(- "cannot enforce network address policy for proxied hostname `{host}` in `{url}`; the proxy must not resolve an unchecked target hostname"- );- }- return Ok(FetchCurlDnsAdmission::NoSharedResolution);- }- if resolve_host_resolve_override_ips(config.http_host_resolve(), host, port)?.is_some() {- return Ok(FetchCurlDnsAdmission::NoSharedResolution);- }- Ok(FetchCurlDnsAdmission::SharedResolver(DnsTarget::new(- host, port,- )))+ Ok(+ match proxy_route.connection_dns_endpoint(url, host_resolve)? {+ None => FetchCurlDnsAdmission::NoSharedResolution,+ Some(endpoint) => match endpoint.role() {+ ConnectionEndpointRole::RequestTarget => {+ FetchCurlDnsAdmission::DirectTarget(endpoint.target().clone())+ }+ ConnectionEndpointRole::Proxy => {+ FetchCurlDnsAdmission::ProxyEndpoint(endpoint.target().clone())+ }+ },+ },+ )}#[cfg(test)]@@ -88,15 +76,20 @@ mod tests {raw_url: &str,proxy_route: &HttpProxyRoute,) -> Result<FetchCurlDnsAdmission> {+ let host_resolve = HostResolveOverrides::parse(config.http_host_resolve())?;curl_dns_admission(- config,&Url::parse(raw_url).expect("test URL should parse"),proxy_route,+ &host_resolve,)}- fn shared_target(host: &str, port: u16) -> FetchCurlDnsAdmission {- FetchCurlDnsAdmission::SharedResolver(DnsTarget::new(host, port))+ fn direct_target(host: &str, port: u16) -> FetchCurlDnsAdmission {+ FetchCurlDnsAdmission::DirectTarget(DnsTarget::new(host, port))+ }++ fn proxy_endpoint(host: &str, port: u16) -> FetchCurlDnsAdmission {+ FetchCurlDnsAdmission::ProxyEndpoint(DnsTarget::new(host, port))}fn proxy_route(raw: &str) -> HttpProxyRoute {@@ -109,7 +102,7 @@ mod tests {assert_eq!(admission(&config, "http://example.test/path", &HttpProxyRoute::Direct),- shared_target("example.test", 80)+ direct_target("example.test", 80));assert_eq!(admission(@@ -117,7 +110,7 @@ mod tests {"https://example.test:8443/path",&HttpProxyRoute::Direct,),- shared_target("example.test", 8443)+ direct_target("example.test", 8443));}@@ -140,13 +133,13 @@ mod tests {);assert_eq!(admission(&config, "http://other.test/path", &HttpProxyRoute::Direct,),- shared_target("other.test", 80),+ direct_target("other.test", 80),"an unrelated host-resolve entry must not return DNS ownership to curl");}#[test]- fn selected_proxy_route_needs_no_shared_origin_resolution() {+ fn selected_proxy_domain_uses_shared_endpoint_resolution() {let config = FetchConfig::default();assert_eq!(@@ -155,22 +148,53 @@ mod tests {"https://api.example.test/path",&proxy_route("http://proxy.test:8080"),),- FetchCurlDnsAdmission::NoSharedResolution+ proxy_endpoint("proxy.test", 8080));}#[test]- fn enforced_policy_rejects_proxy_resolved_hostname() {+ fn selected_proxy_ip_needs_no_shared_resolution_even_with_address_policy() {let mut config = FetchConfig::default();config.set_network_blocking(true, Vec::new());- let error = admission_result(- &config,- "https://api.example.test/path",- &proxy_route("http://proxy.test:8080"),- )- .expect_err("a strict policy cannot verify proxy-side DNS");+ assert_eq!(+ admission(+ &config,+ "https://api.example.test/path",+ &proxy_route("http://192.0.2.1:8080"),+ ),+ FetchCurlDnsAdmission::NoSharedResolution+ );+ }++ #[test]+ fn proxy_endpoint_override_needs_no_dns_but_target_override_is_rejected() {+ let route = proxy_route("http://proxy.test:8080");+ let mut config = FetchConfig::default();+ config.set_http_host_resolve(vec!["proxy.test:8080:192.0.2.1".to_owned()]);+ assert_eq!(+ admission(&config, "https://api.example.test/path", &route),+ FetchCurlDnsAdmission::NoSharedResolution+ );++ config.set_http_host_resolve(vec!["api.example.test:443:198.51.100.1".to_owned()]);+ let error = admission_result(&config, "https://api.example.test/path", &route)+ .expect_err("a target override cannot affect remote proxy DNS");+ assert!(error.to_string().contains("would be ignored"), "{error:#}");+ }++ #[test]+ fn address_policy_does_not_reject_proxy_resolved_target() {+ let mut config = FetchConfig::default();+ config.set_network_blocking(true, Vec::new());- assert!(error.to_string().contains("proxied hostname"));+ assert_eq!(+ admission(+ &config,+ "https://api.example.test/path",+ &proxy_route("http://proxy.test:8080"),+ ),+ proxy_endpoint("proxy.test", 8080)+ );}}diff --git a/moli-fetch/src/lib.rs b/moli-fetch/src/lib.rsindex fe12ccb19..b66e97609 100644--- a/moli-fetch/src/lib.rs+++ b/moli-fetch/src/lib.rs@@ -34,7 +34,7 @@ pub use blocking::{pub use blocking::{clear_http_cache, clear_http_cache_for_origin, clear_http_cache_root,clear_http_cache_root_for_origin, cookie_header_for_request, http_cache_stats,- observe_cookie_access_report_for_request, trim_http_cache, validate_http_host_resolve_entries,+ observe_cookie_access_report_for_request, trim_http_cache,};pub use cancellation::FetchCancelHandle;pub use client::{FetchClient, FetchClientHandle};@@ -50,8 +50,8 @@ pub use headers::{is_forbidden_response_header_name, is_no_cors_safelisted_request_header,};pub use moli_cookie_jar::SharedBrowserCookieStore as SharedCookieStore;-pub use moli_curl::CurlTlsConfig;pub use moli_curl::websocket::CurlWebSocketConnector;+pub use moli_curl::{CurlTlsConfig, validate_http_host_resolve_entries};pub use moli_web_bot_auth::{WebBotAuthProfile, WebBotAuthSigner};pub use network_fetch_result::{NetworkExchangeObservation, NetworkFetchFailureContext, NetworkFetchFailureRequestContext,diff --git a/moli-fetch/src/tests/mod.rs b/moli-fetch/src/tests/mod.rsindex 4c4d43c3f..6ceff38ba 100644--- a/moli-fetch/src/tests/mod.rs+++ b/moli-fetch/src/tests/mod.rs@@ -39,7 +39,8 @@ use crate::{use self::support::{EmptyHttpHttpsUpgradeServer, Http2ProtocolFallbackServer, ScriptedH2Server, ScriptedHttpServer,- ScriptedHttps11Server, ScriptedResponse, unique_test_cache_dir, wait_for_runtime_owner_count,+ ScriptedHttps11Server, ScriptedResponse, spawn_socks5h_proxy, unique_test_cache_dir,+ wait_for_runtime_owner_count,};const ENV_PROXY_CHILD_TEST: &str = "MOLI_FETCH_ENV_PROXY_CHILD";@@ -1916,24 +1917,198 @@ fn fetch_client_checks_the_shared_dns_answer_for_domains() {}#[test]-fn fetch_client_rejects_proxy_side_dns_under_address_policy() {+fn fetch_client_allows_proxy_resolved_target_under_address_policy() {+ let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("proxied-private-target")]);+ let proxy_port = Url::parse(&proxy.origin())+ .unwrap()+ .port()+ .expect("proxy URL should include a port");let mut config = FetchConfig::default();- config.set_http_proxy(Some("http://proxy.test:8080".to_owned()));+ config.set_http_proxy(Some(format!("http://localhost:{proxy_port}")));config.set_network_blocking(true, vec![]);+ let response = fetch_with_config_for_test(+ &config,+ Request::get("http://127.0.0.1/proxy-resolved-target").unwrap(),+ )+ .expect("the trusted proxy owns request-target DNS and address admission");++ assert_eq!(response.body_text(), "proxied-private-target");+ assert_eq!(proxy.hits(), 1);+ proxy.shutdown();+}++#[test]+fn fetch_client_uses_host_resolve_for_proxy_endpoint() {+ let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("fixed-proxy")]);+ let proxy_port = Url::parse(&proxy.origin())+ .unwrap()+ .port()+ .expect("proxy URL should include a port");+ let mut config = FetchConfig::default();+ config.set_http_proxy(Some(format!("http://proxy.invalid:{proxy_port}")));+ config.set_http_host_resolve(vec![format!(+ "proxy.invalid:{proxy_port}:127.0.0.2,127.0.0.1"+ )]);++ let response = fetch_with_config_for_test(+ &config,+ Request::get("http://remote-target.invalid/through-fixed-proxy").unwrap(),+ )+ .expect("a fixed proxy endpoint must bypass DNS without fixing the remote target");++ assert_eq!(response.body_text(), "fixed-proxy");+ assert_eq!(proxy.hits(), 1);+ proxy.shutdown();+}++#[test]+fn fetch_client_sends_bearer_auth_only_as_http_proxy_header() {+ let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("authenticated-proxy")]);+ let mut config = FetchConfig::default();+ config.set_proxy_options(Some(proxy.origin()), Some("proxy-token".to_owned()));++ let response = fetch_with_config_for_test(+ &config,+ Request::get("http://proxy-auth-target.invalid/path").unwrap(),+ )+ .expect("HTTP proxy should receive bearer authentication");+ let requests = proxy.requests();++ assert_eq!(response.body_text(), "authenticated-proxy");+ assert_eq!(requests.len(), 1);+ assert!(+ requests[0].contains("\r\nProxy-Authorization: Bearer proxy-token\r\n"),+ "unexpected proxy request: {:?}",+ requests[0]+ );+ proxy.shutdown();+}++#[test]+fn fetch_client_rejects_host_resolve_for_remote_proxy_target() {+ let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("unexpected")]);+ let mut config = FetchConfig::default();+ config.set_http_proxy(Some(proxy.origin()));+ config.set_http_host_resolve(vec!["target.invalid:80:127.0.0.1".to_owned()]);+let error = fetch_with_config_for_test(&config,- Request::get("https://proxy-resolved.example.test/").unwrap(),+ Request::get("http://target.invalid/ignored-override").unwrap(),)- .expect_err("a strict client cannot verify proxy-side DNS");- let error_chain = format!("{error:#}");+ .expect_err("a remote-DNS proxy cannot honor a target host-resolve override");+ assert!(error.to_string().contains("would be ignored"), "{error:#}");+ assert_eq!(proxy.hits(), 0);+ proxy.shutdown();+}++#[test]+fn fetch_client_rejects_http_header_auth_for_socks_proxy() {+ let mut config = FetchConfig::default();+ config.set_proxy_options(+ Some("socks5h://127.0.0.1:1".to_owned()),+ Some("proxy-token".to_owned()),+ );++ let error = fetch_with_config_for_test(+ &config,+ Request::get("http://target.invalid/through-socks").unwrap(),+ )+ .expect_err("SOCKS proxy authentication must not use an HTTP header");++ let error_chain = format!("{error:#}");assert!(- error_chain.contains("cannot enforce network address policy for proxied hostname"),- "unexpected error: {error_chain}"+ error_chain.contains("Proxy-Authorization headers require an HTTP(S) proxy"),+ "{error_chain}");}+#[test]+fn fetch_client_rejects_local_dns_socks_proxy_schemes() {+ for scheme in ["socks5", "socks4"] {+ let mut config = FetchConfig::default();+ config.set_http_proxy(Some(format!("{scheme}://127.0.0.1:1080")));++ let error = fetch_with_config_for_test(+ &config,+ Request::get("http://target.invalid/through-socks").unwrap(),+ )+ .expect_err("high-level fetch must reject local-DNS SOCKS schemes");+ let error_chain = format!("{error:#}");+ assert!(+ error_chain.contains("remote-DNS proxy scheme"),+ "{error_chain}"+ );+ }+}++#[test]+fn fetch_client_socks5h_sends_target_hostname_to_proxy() {+ let upstream = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("through-socks")]);+ let upstream_url = Url::parse(&upstream.origin()).unwrap();+ let upstream_port = upstream_url+ .port()+ .expect("upstream URL should include a port");+ let upstream_addr = format!("127.0.0.1:{upstream_port}")+ .parse()+ .expect("upstream socket address");+ let (proxy_url, request_rx, proxy) = spawn_socks5h_proxy(upstream_addr);+ let mut config = FetchConfig::default();+ config.set_http_proxy(Some(proxy_url));+ config.set_http_no_proxy(Some(String::new()));++ let response = fetch_with_config_for_test(+ &config,+ Request::get(&format!(+ "http://http-target.invalid:{upstream_port}/through-socks"+ ))+ .unwrap(),+ )+ .expect("socks5h proxy should relay the HTTP request");+ let (requested_host, requested_port) = request_rx+ .recv_timeout(Duration::from_secs(3))+ .expect("SOCKS request should arrive");+ proxy.join().expect("fetch SOCKS proxy should finish");++ assert_eq!(response.body_text(), "through-socks");+ assert_eq!(requested_host, "http-target.invalid");+ assert_eq!(requested_port, upstream_port);+ upstream.shutdown();+}++#[test]+fn fetch_redirect_reselects_direct_or_proxy_endpoint_per_hop() {+ let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("redirected-through-proxy")]);+ let proxy_port = Url::parse(&proxy.origin())+ .unwrap()+ .port()+ .expect("proxy URL should include a port");+ let direct = ScriptedHttpServer::spawn(vec![+ ScriptedResponse::status(302, "Found")+ .with_header("Location", "http://redirect-target.invalid/final"),+ ]);+ let direct_url = Url::parse(&direct.url()).unwrap();+ let direct_port = direct_url.port().expect("direct URL should include a port");+ let mut config = FetchConfig::default();+ config.set_http_proxy(Some(format!("http://localhost:{proxy_port}")));+ config.set_http_no_proxy(Some(format!("127.0.0.1:{direct_port}")));++ let response = fetch_with_config_for_test(+ &config,+ Request::get(direct_url.as_str())+ .unwrap()+ .with_follow_redirects(true),+ )+ .expect("redirect should switch from direct origin DNS to proxy endpoint DNS");++ assert_eq!(response.body_text(), "redirected-through-proxy");+ assert_eq!(direct.hits(), 1);+ assert_eq!(proxy.hits(), 1);+ direct.shutdown();+ proxy.shutdown();+}+#[test]fn fetch_client_applies_selected_no_proxy_route_to_curl() {let server = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("direct")]);@@ -1943,13 +2118,15 @@ fn fetch_client_applies_selected_no_proxy_route_to_curl() {.expect("scripted server URL should include a port");let mut config = FetchConfig::default();config.set_http_proxy(Some("http://127.0.0.1:1".to_owned()));- config.set_http_no_proxy(Some(format!("127.0.0.1:{port}")));+ config.set_http_no_proxy(Some(format!("localhost:{port}")));let response = fetch_with_config_for_test(&config,- Request::get(&format!("http://127.0.0.1:{port}/direct")).unwrap(),+ Request::get(&format!("http://localhost:{port}/direct")).unwrap(),)- .expect("the selected direct route must disable curl proxy evaluation");+ .expect(+ "the selected direct route must use shared origin DNS and disable curl proxy evaluation",+ );assert_eq!(response.body_text(), "direct");assert_eq!(server.hits(), 1);@@ -2045,7 +2222,9 @@ fn fetch_client_rejects_http_bad_ports_before_network_io() {#[test]fn fetch_client_preserves_env_proxy_fallback() {let proxy = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("proxied-env")]);- let proxy_origin = proxy.origin();+ let mut proxy_url = Url::parse(&proxy.origin()).unwrap();+ proxy_url.set_host(Some("localhost")).unwrap();+ let proxy_origin = proxy_url.to_string();let output = Command::new(std::env::current_exe().expect("test binary path")).arg("--exact").arg("tests::env_proxy_child_uses_selected_env_proxy_route")diff --git a/moli-fetch/src/tests/support.rs b/moli-fetch/src/tests/support.rsindex 5d3b8f06b..79a00751f 100644--- a/moli-fetch/src/tests/support.rs+++ b/moli-fetch/src/tests/support.rs@@ -1,7 +1,7 @@use std::{collections::VecDeque,io::{Read, Write},- net::TcpListener,+ net::{TcpListener, TcpStream},sync::{Arc,atomic::{AtomicUsize, Ordering},@@ -14,6 +14,75 @@ use std::{use crate::FetchClientHandle;use parking_lot::Mutex;+pub(super) fn spawn_socks5h_proxy(+ upstream_addr: std::net::SocketAddr,+) -> (+ String,+ std_mpsc::Receiver<(String, u16)>,+ thread::JoinHandle<()>,+) {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind fetch SOCKS proxy");+ let addr = listener.local_addr().expect("fetch SOCKS proxy address");+ let (request_tx, request_rx) = std_mpsc::channel();+ let handle = thread::spawn(move || {+ let (mut client, _) = listener.accept().expect("accept fetch SOCKS client");+ let mut greeting = [0u8; 2];+ client+ .read_exact(&mut greeting)+ .expect("read fetch SOCKS greeting");+ assert_eq!(greeting[0], 5);+ let mut methods = vec![0; usize::from(greeting[1])];+ client+ .read_exact(&mut methods)+ .expect("read fetch SOCKS methods");+ assert!(methods.contains(&0), "SOCKS client must offer no-auth");+ client+ .write_all(&[5, 0])+ .expect("write fetch SOCKS method selection");++ let mut request_head = [0u8; 4];+ client+ .read_exact(&mut request_head)+ .expect("read fetch SOCKS request head");+ assert_eq!(&request_head[..3], &[5, 1, 0]);+ let host = match request_head[3] {+ 3 => {+ let mut length = [0u8; 1];+ client+ .read_exact(&mut length)+ .expect("read fetch SOCKS domain length");+ let mut domain = vec![0; usize::from(length[0])];+ client+ .read_exact(&mut domain)+ .expect("read fetch SOCKS domain");+ String::from_utf8(domain).expect("fetch SOCKS domain should be UTF-8")+ }+ atyp => panic!("socks5h must send a domain target, got address type {atyp}"),+ };+ let mut port = [0u8; 2];+ client+ .read_exact(&mut port)+ .expect("read fetch SOCKS target port");+ let port = u16::from_be_bytes(port);+ let _ = request_tx.send((host, port));++ let mut upstream = TcpStream::connect(upstream_addr).expect("connect fetch SOCKS upstream");+ client+ .write_all(&[5, 0, 0, 1, 127, 0, 0, 1, 0, 0])+ .expect("write fetch SOCKS success response");+ let mut client_read = client.try_clone().expect("clone fetch SOCKS client");+ let mut upstream_write = upstream.try_clone().expect("clone fetch SOCKS upstream");+ let upload = thread::spawn(move || {+ let _ = std::io::copy(&mut client_read, &mut upstream_write);+ });+ let _ = std::io::copy(&mut upstream, &mut client);+ let _ = client.shutdown(std::net::Shutdown::Both);+ let _ = upstream.shutdown(std::net::Shutdown::Both);+ let _ = upload.join();+ });+ (format!("socks5h://{addr}"), request_rx, handle)+}+pub(super) struct ScriptedH2Server {addr: std::net::SocketAddr,hits: Arc<AtomicUsize>,diff --git a/moli-fetch/src/tests/websocket_transport.rs b/moli-fetch/src/tests/websocket_transport.rsindex 0968991c5..0b943d13f 100644--- a/moli-fetch/src/tests/websocket_transport.rs+++ b/moli-fetch/src/tests/websocket_transport.rs@@ -52,3 +52,20 @@ fn websocket_connector_inherits_private_network_policy() {.contains("blocked private network address `127.0.0.1`"));}++#[test]+fn websocket_connector_applies_blocked_cidr_to_fixed_direct_target() {+ let mut config = FetchConfig::default();+ config.set_network_blocking(false, vec!["198.18.0.0/15".parse().unwrap()]);+ let client = FetchClient::new(&config, new_shared_browser_cookie_store());+ let mut request = CurlWebSocketRequest::new("ws://example.test/socket".to_owned());+ request.resolve_entries = vec!["example.test:80:198.18.0.1".to_owned()];++ let error = client+ .handle()+ .websocket_connector()+ .connect(request)+ .expect_err("a fixed WebSocket target in a blocked CIDR must be rejected");++ assert!(error.to_string().contains("matches `198.18.0.0/15`"));+}diff --git a/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs b/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rsindex b2b53f717..08af46c9a 100644--- a/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs@@ -59,6 +59,9 @@ impl JsContextHost {extra_headers: self.extra_http_headers.clone(),http_proxy: loader.and_then(|loader| loader.http_proxy().map(ToOwned::to_owned)),http_no_proxy: loader.and_then(|loader| loader.http_no_proxy().map(ToOwned::to_owned)),+ http_host_resolve: loader+ .map(|loader| loader.http_host_resolve().to_vec())+ .unwrap_or_default(),proxy_bearer_token: loader.and_then(|loader| loader.proxy_bearer_token().map(ToOwned::to_owned)),tls: loaderdiff --git a/moli-renderer-v8/src/network/request_client.rs b/moli-renderer-v8/src/network/request_client.rsindex 365954720..68b5d5030 100644--- a/moli-renderer-v8/src/network/request_client.rs+++ b/moli-renderer-v8/src/network/request_client.rs@@ -963,6 +963,10 @@ impl ResourceRequestClient {self.resource_runtime.client().http_proxy()}+ pub fn http_host_resolve(&self) -> &[String] {+ self.resource_runtime.client().http_host_resolve()+ }+pub fn http_no_proxy(&self) -> Option<&str> {self.resource_runtime.client().http_no_proxy()}diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rsindex 5fa97fa24..26e34d42a 100644--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs@@ -1302,6 +1302,7 @@ pub(crate) fn register_worker_websocket<'s>(.request_client().http_no_proxy().map(ToOwned::to_owned),+ http_host_resolve: loader.request_client().http_host_resolve().to_vec(),proxy_bearer_token: loader.request_client().proxy_bearer_token()diff --git a/moli-websocket/Cargo.toml b/moli-websocket/Cargo.tomlindex 70025b910..82542bafe 100644--- a/moli-websocket/Cargo.toml+++ b/moli-websocket/Cargo.toml@@ -11,7 +11,6 @@ test-support = ["dep:rcgen", "dep:openssl", "dep:tokio-tungstenite", "dep:tokio-base64 = "0.22"moli-curl = { path = "../moli-curl" }moli-crypto = { path = "../moli-crypto" }-moli-dns-resolver = { path = "../moli-dns-resolver" }futures-util = { version = "0.3", default-features = false, features = ["sink", "std"], optional = true }http = "1"moli-url = { path = "../moli-url" }diff --git a/moli-websocket/src/test_support.rs b/moli-websocket/src/test_support.rsindex 30eb2d31d..d5b518499 100644--- a/moli-websocket/src/test_support.rs+++ b/moli-websocket/src/test_support.rs@@ -38,6 +38,7 @@ pub fn test_websocket_context() -> ConnectOptions {extra_headers: Vec::new(),http_proxy: None,http_no_proxy: None,+ http_host_resolve: Vec::new(),proxy_bearer_token: None,tls: Default::default(),cookie_header: None,@@ -532,6 +533,79 @@ pub async fn spawn_http_connect_proxy_response((format!("http://{addr}"), request_rx, handle)}+pub async fn spawn_socks5h_proxy(+ upstream_addr: std::net::SocketAddr,+) -> (+ String,+ oneshot::Receiver<(String, u16)>,+ tokio::task::JoinHandle<()>,+) {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind WebSocket SOCKS proxy");+ let addr = listener.local_addr().expect("WebSocket SOCKS proxy addr");+ let (request_tx, request_rx) = oneshot::channel();+ let handle = tokio::spawn(async move {+ let (mut client, _) = listener.accept().await.expect("accept SOCKS client");+ let mut greeting = [0u8; 2];+ client+ .read_exact(&mut greeting)+ .await+ .expect("read SOCKS greeting");+ assert_eq!(greeting[0], 5);+ let mut methods = vec![0; usize::from(greeting[1])];+ client+ .read_exact(&mut methods)+ .await+ .expect("read SOCKS methods");+ assert!(methods.contains(&0), "SOCKS client must offer no-auth");+ client+ .write_all(&[5, 0])+ .await+ .expect("write SOCKS method selection");++ let mut request_head = [0u8; 4];+ client+ .read_exact(&mut request_head)+ .await+ .expect("read SOCKS request head");+ assert_eq!(&request_head[..3], &[5, 1, 0]);+ let host = match request_head[3] {+ 3 => {+ let mut length = [0u8; 1];+ client+ .read_exact(&mut length)+ .await+ .expect("read SOCKS domain length");+ let mut domain = vec![0; usize::from(length[0])];+ client+ .read_exact(&mut domain)+ .await+ .expect("read SOCKS domain");+ String::from_utf8(domain).expect("SOCKS domain should be UTF-8")+ }+ atyp => panic!("socks5h must send a domain target, got address type {atyp}"),+ };+ let mut port = [0u8; 2];+ client+ .read_exact(&mut port)+ .await+ .expect("read SOCKS target port");+ let port = u16::from_be_bytes(port);+ let _ = request_tx.send((host, port));++ let mut upstream = TcpStream::connect(upstream_addr)+ .await+ .expect("connect SOCKS upstream");+ client+ .write_all(&[5, 0, 0, 1, 127, 0, 0, 1, 0, 0])+ .await+ .expect("write SOCKS success response");+ let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;+ });+ (format!("socks5h://{addr}"), request_rx, handle)+}+pub async fn spawn_text_echo_websocket_server() -> (String, tokio::task::JoinHandle<()>) {spawn_text_binary_echo_websocket_server().await}diff --git a/moli-websocket/src/tests.rs b/moli-websocket/src/tests.rsindex 6004befe0..6e9b1c7fc 100644--- a/moli-websocket/src/tests.rs+++ b/moli-websocket/src/tests.rs@@ -924,7 +924,11 @@ async fn websocket_transport_uses_explicit_http_proxy_connect_without_forwardinglet (proxy_url, proxy_request_rx, proxy) = spawn_http_connect_proxy().await;let (event_tx, mut event_rx) = mpsc::channel(32);let mut context = test_websocket_context();- context.http_proxy = Some(proxy_url);+ let mut named_proxy = Url::parse(&proxy_url).expect("proxy URL");+ named_proxy+ .set_host(Some("localhost"))+ .expect("proxy hostname should be replaceable");+ context.http_proxy = Some(named_proxy.to_string());context.http_no_proxy = Some(String::new());context.proxy_bearer_token = Some("proxy-token".to_owned());let user_agent = context.user_agent.clone();@@ -966,14 +970,59 @@ async fn websocket_transport_uses_explicit_http_proxy_connect_without_forwardingassert_eq!(header_value(&headers, "proxy-authorization"), None);}+#[tokio::test]+async fn websocket_transport_socks5h_sends_target_hostname_to_proxy() {+ let (server_url, headers_rx, server) = spawn_header_capture_websocket_server().await;+ let mut target = Url::parse(&server_url).expect("WebSocket target URL");+ let target_port = target+ .port_or_known_default()+ .expect("WebSocket target port");+ let upstream_addr = format!("127.0.0.1:{target_port}")+ .parse()+ .expect("WebSocket upstream address");+ target+ .set_host(Some("websocket-target.invalid"))+ .expect("WebSocket target hostname should be replaceable");+ let (proxy_url, proxy_request_rx, proxy) = spawn_socks5h_proxy(upstream_addr).await;+ let (event_tx, mut event_rx) = mpsc::channel(32);+ let mut context = test_websocket_context();+ context.http_proxy = Some(proxy_url);+ context.http_no_proxy = Some(String::new());++ let command_tx =+ spawn_standalone_connection(5, target.to_string(), Vec::new(), context, event_tx);+ let (requested_host, requested_port) = timeout(Duration::from_secs(3), proxy_request_rx)+ .await+ .expect("SOCKS request should arrive")+ .expect("SOCKS request sender should stay alive");+ let _headers = timeout(Duration::from_secs(3), headers_rx)+ .await+ .expect("WebSocket headers should arrive")+ .expect("WebSocket header sender should stay alive");+ let open = recv_open_event(&mut event_rx).await;+ let _ = command_tx.close(Some(1000), "done".to_owned());+ server.await.expect("WebSocket header server should finish");+ proxy.await.expect("WebSocket SOCKS proxy should finish");++ assert_eq!(open.socket_id, 5);+ assert_eq!(requested_host, "websocket-target.invalid");+ assert_eq!(requested_port, target_port);+}+#[tokio::test]async fn websocket_transport_rejects_non_200_http_proxy_connect() {let (proxy_url, proxy_request_rx, proxy) =spawn_http_connect_proxy_response(b"HTTP/1.1 204 No Content\r\n\r\n").await;let (event_tx, mut event_rx) = mpsc::channel(32);let mut context = test_websocket_context();- context.http_proxy = Some(proxy_url);+ let mut fixed_proxy = Url::parse(&proxy_url).expect("proxy URL");+ let proxy_port = fixed_proxy.port().expect("proxy URL should include a port");+ fixed_proxy+ .set_host(Some("proxy.invalid"))+ .expect("proxy hostname should be replaceable");+ context.http_proxy = Some(fixed_proxy.to_string());context.http_no_proxy = Some(String::new());+ context.http_host_resolve = vec![format!("proxy.invalid:{proxy_port}:127.0.0.1")];let _command_tx = spawn_standalone_connection(3,@@ -999,6 +1048,26 @@ async fn websocket_transport_rejects_non_200_http_proxy_connect() {);}+#[tokio::test]+async fn websocket_transport_rejects_host_resolve_for_remote_proxy_target() {+ let (event_tx, mut event_rx) = mpsc::channel(32);+ let mut context = test_websocket_context();+ context.http_proxy = Some("http://127.0.0.1:1".to_owned());+ context.http_no_proxy = Some(String::new());+ context.http_host_resolve = vec!["target.invalid:80:127.0.0.1".to_owned()];++ let _command_tx = spawn_standalone_connection(+ 4,+ "ws://target.invalid/socket".to_owned(),+ Vec::new(),+ context,+ event_tx,+ );+ let message = recv_handshake_failure_events(&mut event_rx).await;++ assert!(message.contains("would be ignored"), "{message}");+}+#[tokio::test]async fn websocket_transport_respects_disabled_tls_verify_for_self_signed_wss() {let (url, headers_rx, server) = spawn_tls_header_capture_websocket_server().await;diff --git a/moli-websocket/src/transport.rs b/moli-websocket/src/transport.rsindex 3ba4339bb..4919e46f3 100644--- a/moli-websocket/src/transport.rs+++ b/moli-websocket/src/transport.rs@@ -6,12 +6,11 @@ use crate::{request::PreparedWebSocketRequest,};use moli_curl::{- CurlDnsResolution,+ CurlDnsResolution, HostResolveOverrides,websocket::{CurlWebSocketConnection, CurlWebSocketConnector, CurlWebSocketEvent, CurlWebSocketRequest,},};-use moli_dns_resolver::DnsTarget;pub(crate) struct HandshakeInfo {pub request_headers: http::HeaderMap,@@ -29,9 +28,16 @@ pub(crate) async fn open_websocket_connection(context: &ConnectOptions,) -> Result<OpenedConnection, String> {let proxy_route = websocket_proxy_route(&request.url, context)?;+ let host_resolve = HostResolveOverrides::parse(&context.http_host_resolve)+ .map_err(|error| error.to_string())?;+ let dns_endpoint = proxy_route+ .connection_dns_endpoint(&request.url, &host_resolve)+ .map_err(|error| error.to_string())?;+ let resolve_entries = host_resolve.normalized_entries();let mut native = CurlWebSocketRequest::new(request.url.to_string());native.headers = header_map_entries(&request.headers);native.proxy = proxy_route.proxy().map(|proxy| proxy.url().to_owned());+ native.resolve_entries = resolve_entries.clone();// WebSocket opening handshakes use credentials=include, including across// origins: https://websockets.spec.whatwg.org/#opening-handshakenative.tls = context.tls.clone();@@ -48,18 +54,10 @@ pub(crate) async fn open_websocket_connection(} else if context.proxy_bearer_token.is_some() {return Err("proxy bearer authentication requires an HTTP(S) proxy".to_owned());}- } else {- let url = &request.url;- if let Some(url::Host::Domain(host)) = url.host() {- native.dns_resolution = CurlDnsResolution::resolve_endpoint(- DnsTarget::new(- host,- url.port_or_known_default()- .ok_or("WebSocket URL has no port")?,- ),- Vec::new(),- );- }+ }+ if let Some(endpoint) = dns_endpoint {+ native.dns_resolution =+ CurlDnsResolution::resolve_endpoint(endpoint.target().clone(), resolve_entries);}let mut connection = connector.connect(native)diff --git a/moli-websocket/src/types.rs b/moli-websocket/src/types.rsindex 584ac80b6..641e15a9e 100644--- a/moli-websocket/src/types.rs+++ b/moli-websocket/src/types.rs@@ -5,6 +5,7 @@ pub struct ConnectOptions {pub extra_headers: Vec<(String, String)>,pub http_proxy: Option<String>,pub http_no_proxy: Option<String>,+ pub http_host_resolve: Vec<String>,pub proxy_bearer_token: Option<String>,pub tls: moli_curl::CurlTlsConfig,pub cookie_header: Option<String>,diff --git a/moli/src/cli.rs b/moli/src/cli.rsindex b0b0c1990..7550dc7fc 100644--- a/moli/src/cli.rs+++ b/moli/src/cli.rs@@ -484,12 +484,17 @@ pub struct CommonArgs {#[arg(long)]pub obey_robots: bool,- #[arg(long)]+ /// Route HTTP(S) and WebSocket traffic through an HTTP, HTTPS, socks5h, or+ /// socks4a proxy. Moli resolves and pins the proxy endpoint; the proxy is+ /// responsible for resolving and filtering request target hostnames.+ #[arg(long, value_name = "URL")]pub http_proxy: Option<String>,#[arg(long)]pub http_no_proxy: Option<String>,+ /// Permanently map a directly connected origin or proxy endpoint to an IP.+ /// Target mappings are rejected when a remote-DNS proxy would ignore them.#[arg(long = "http-host-resolve", value_name = "HOST:PORT:ADDR")]pub http_host_resolve: Vec<String>,@@ -594,6 +599,8 @@ pub struct CommonArgs {#[arg(long)]pub document_start_script_file: Vec<String>,+ /// Block private addresses for directly connected request targets.+ /// Proxy-resolved targets are outside this client-side policy.#[arg(long,env = "MOLI_BLOCK_PRIVATE_NETWORKS",@@ -601,6 +608,8 @@ pub struct CommonArgs {)]pub block_private_networks: bool,+ /// Block CIDRs for directly connected request targets. Proxy-resolved+ /// targets must be filtered by the configured proxy.#[arg(long)]pub block_cidrs: Option<String>,