asimov_http/proxy.rs
1// This is free and unencumbered software released into the public domain.
2
3//! Shared HTTP proxy options and endpoint validation (`proxy` feature).
4//!
5//! `system-proxy` adds `OriginProxy` for construction-time environment/native
6//! discovery. `reqwest` adds its `client_builder` and `configure_reqwest`
7//! adapters, with `ClientOptions` for client limits. A resolved policy
8//! belongs to one HTTP(S) origin; it must not configure a multi-origin client.
9//! `hyper` adds `proxy_for_hyper`, including the effective bypass decision.
10//! Native bypass grammars remain separate from `NO_PROXY` syntax.
11
12use alloc::{format, string::String};
13use core::fmt;
14use url::Url;
15
16#[cfg(feature = "system-proxy")]
17mod system;
18#[cfg(feature = "system-proxy")]
19pub use system::OriginProxy;
20#[cfg(feature = "hyper")]
21mod hyper;
22#[cfg(feature = "reqwest")]
23mod reqwest;
24#[cfg(feature = "reqwest")]
25pub use self::reqwest::ClientOptions;
26#[cfg(all(test, feature = "reqwest"))]
27mod test_support;
28
29/// How an HTTP client selects its proxy endpoint.
30///
31/// With `system-proxy`, resolve once with `OriginProxy::resolve` before building
32/// an origin-scoped client. This type itself needs only alloc.
33#[derive(Clone, Default, Eq, PartialEq)]
34pub enum ProxyMode {
35 /// Read environment and native static settings. Per-scheme environment
36 /// endpoints override native settings, followed by ALL_PROXY. This is the
37 /// default. See `OriginProxy` for discovery and bypass semantics.
38 #[default]
39 Automatic,
40 /// Connect directly, without reading proxy environment or native settings.
41 /// Ignores [`ProxyOptions::no_proxy`].
42 Direct,
43 /// Use this endpoint instead of environment or native proxy endpoints.
44 ///
45 /// Accepts `http://`, `https://`, `socks4://`, `socks4a://`, `socks5://`, and
46 /// `socks5h://` URLs, or a bare `host[:port]` for HTTP. Ports default to 80,
47 /// 443, or 1080 respectively. IPv6 addresses require brackets. URL userinfo
48 /// supports existing HTTP Basic/SOCKS5 authentication; percent-encode
49 /// reserved characters. Debug output omits the URL, including credentials.
50 ///
51 /// Invalid endpoints return [`Error::InvalidProxyUrl`] at construction,
52 /// even when a bypass rule matches. Paths other than `/`, queries, fragments,
53 /// whitespace, and port zero are rejected. SOCKS hostnames must be ASCII or
54 /// punycode. A failed connection never falls back to another proxy or direct
55 /// access. This explicit choice also applies when `REQUEST_METHOD` is set.
56 Explicit(String),
57}
58
59impl fmt::Debug for ProxyMode {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 Self::Automatic => f.write_str("Automatic"),
63 Self::Direct => f.write_str("Direct"),
64 Self::Explicit(_) => f.write_str("Explicit([REDACTED])"),
65 }
66 }
67}
68
69/// Client-local proxy selection and bypass policy.
70#[derive(Clone, Debug, Default, Eq, PartialEq)]
71pub struct ProxyOptions {
72 /// Endpoint selection. Defaults to [`ProxyMode::Automatic`].
73 pub mode: ProxyMode,
74 /// Bypass list in `NO_PROXY` syntax: comma-separated domains/subdomains,
75 /// IP literals/CIDRs, or `*` for every host, including IP literals.
76 /// Matching does not resolve DNS names to test CIDRs. Port-qualified rules
77 /// and native-only syntax such as `<local>` are not supported here.
78 ///
79 /// - `None` inherits `NO_PROXY`/`no_proxy`. In automatic mode, an empty
80 /// environment list permits native exclusions when a native proxy wins.
81 /// Explicit mode never reads native exclusions.
82 /// - `Some(list)` replaces both environment and native exclusions.
83 /// - `Some(String::new())` disables all bypass rules.
84 /// - `Some("*".into())` selects direct access for every host.
85 ///
86 /// Direct mode ignores this field. Automatic mode retains CGI protection
87 /// regardless of the override. Configuration never changes the environment.
88 pub no_proxy: Option<String>,
89}
90
91#[cfg(feature = "system-proxy")]
92fn bypasses_all(list: &str) -> bool {
93 list.split(',').any(|rule| rule.trim() == "*")
94}
95
96/// Proxy configuration failures, separate from HTTP integrity failures.
97/// Diagnostics name settings or fixed reasons, never endpoint contents.
98#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
99pub enum Error {
100 /// Native settings could not be read/decoded, or an enabled endpoint is invalid.
101 #[error("invalid native proxy setting: {0}")]
102 InvalidProxy(&'static str),
103 /// Invalid explicit endpoint, including unsupported schemes.
104 #[error("invalid explicit proxy URL: {0}")]
105 InvalidProxyUrl(&'static str),
106 /// The native source requires an unsupported resolver.
107 #[error("unsupported automatic proxy source: {0}; configure an explicit proxy")]
108 UnsupportedProxy(&'static str),
109 /// A target is not HTTP(S), or differs from the resolved origin.
110 #[error("invalid proxy target origin: {0}")]
111 InvalidOrigin(&'static str),
112}
113
114/// Validates an explicit HTTP(S)/SOCKS proxy URL or bare `host[:port]`.
115///
116/// The returned URL retains userinfo; do not log it without redaction. SOCKS
117/// default ports are supplied by transport adapters. No environment or native
118/// settings are read. See [`ProxyMode::Explicit`] for accepted endpoint syntax.
119///
120/// # Errors
121///
122/// Returns [`Error::InvalidProxyUrl`] with a credential-free reason.
123pub fn parse_endpoint(input: &str) -> Result<Url, Error> {
124 if input.is_empty() || input.chars().any(|c| c.is_whitespace() || c.is_control()) {
125 return Err(Error::InvalidProxyUrl(
126 "expected a nonempty URL without whitespace",
127 ));
128 }
129 let url = environment_proxy(input).ok_or(Error::InvalidProxyUrl(
130 "expected an HTTP(S) or SOCKS4/4a/5/5h endpoint with a host",
131 ))?;
132 if url.port() == Some(0) {
133 return Err(Error::InvalidProxyUrl("port must be nonzero"));
134 }
135 if !matches!(url.path(), "" | "/") || url.query().is_some() || url.fragment().is_some() {
136 return Err(Error::InvalidProxyUrl(
137 "paths, queries, and fragments are not supported",
138 ));
139 }
140 // Non-special URL schemes escape Unicode hosts instead of using IDNA.
141 // Require a usable ASCII/punycode name rather than an escaped DNS name.
142 if !url
143 .host_str()
144 .is_some_and(|host| host.is_ascii() && !host.contains('%'))
145 {
146 return Err(Error::InvalidProxyUrl("host must be ASCII or punycode"));
147 }
148 Ok(url)
149}
150
151fn environment_proxy(input: &str) -> Option<Url> {
152 if input.is_empty() {
153 return None;
154 }
155 let url = if input.contains("://") {
156 Url::parse(input)
157 } else {
158 Url::parse(&format!("http://{input}"))
159 }
160 .ok()?;
161 (url.host_str().is_some()
162 && matches!(
163 url.scheme(),
164 "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h"
165 ))
166 .then_some(url)
167}
168
169#[cfg(test)]
170mod tests;