Skip to main content

asimov_proxy/
proxy_config.rs

1// This is free and unencumbered software released into the public domain.
2
3//! Upstream connection establishment, optionally through a proxy.
4//!
5//! Discovery, endpoint validation, and bypass decisions use `asimov-http`.
6//! Uppercase environment values, including empty values, precede lowercase
7//! values. Per-scheme endpoints precede native settings, then ALL_PROXY.
8//!
9//! Supported proxy URL schemes:
10//!
11//! - `http://` — HTTP proxy (tunneled with `CONNECT`)
12//! - `https://` — HTTPS proxy (TLS to the proxy itself, then `CONNECT`)
13//! - `socks5://` — SOCKS5 proxy (target DNS resolved locally)
14//! - `socks5h://` — SOCKS5 proxy (target DNS resolved by the proxy)
15
16use crate::Error;
17use alloc::{
18    format,
19    string::{String, ToString},
20};
21use base64::Engine as _;
22
23/// How to reach the upstream server.
24#[derive(Clone, Default)]
25pub enum ProxyConfig {
26    /// Resolve shared environment/native policy for the destination at setup.
27    #[default]
28    Automatic,
29
30    /// Connect directly to the target.
31    Direct,
32
33    /// Tunnel through an HTTP(S) proxy using `CONNECT`.
34    HttpConnect {
35        /// Proxy hostname or unbracketed IP address.
36        host: String,
37        /// Proxy TCP port.
38        port: u16,
39        /// Whether to speak TLS to the proxy itself (an `https://` proxy).
40        tls: bool,
41        /// Pre-encoded `Proxy-Authorization: Basic` credentials.
42        basic_auth: Option<String>,
43    },
44
45    /// Tunnel through a SOCKS5 proxy.
46    Socks5 {
47        /// Proxy hostname or unbracketed IP address.
48        host: String,
49        /// Proxy TCP port.
50        port: u16,
51        /// Optional username and password.
52        auth: Option<(String, String)>,
53        /// Whether to resolve target DNS through the proxy (`socks5h://`).
54        remote_dns: bool,
55    },
56}
57
58impl core::fmt::Debug for ProxyConfig {
59    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60        match self {
61            Self::Automatic => f.write_str("Automatic"),
62            Self::Direct => f.write_str("Direct"),
63            Self::HttpConnect {
64                host,
65                port,
66                tls,
67                basic_auth,
68            } => f
69                .debug_struct("HttpConnect")
70                .field("host", host)
71                .field("port", port)
72                .field("tls", tls)
73                .field("basic_auth", &basic_auth.as_ref().map(|_| "[REDACTED]"))
74                .finish(),
75            Self::Socks5 {
76                host,
77                port,
78                auth,
79                remote_dns,
80            } => f
81                .debug_struct("Socks5")
82                .field("host", host)
83                .field("port", port)
84                .field("auth", &auth.as_ref().map(|_| "[REDACTED]"))
85                .field("remote_dns", remote_dns)
86                .finish(),
87        }
88    }
89}
90
91impl ProxyConfig {
92    #[cfg(feature = "std")]
93    pub(crate) fn for_target(self, target: &url::Url) -> Result<Self, Error> {
94        match self {
95            Self::Automatic => Self::from_options(target, &crate::UpstreamProxyOptions::default()),
96            config => Ok(config),
97        }
98    }
99
100    /// Resolves shared environment/native proxy policy for an HTTPS host.
101    ///
102    /// Uppercase variables take precedence, including empty values. Honors
103    /// native exclusions, NO_PROXY domains/IPs/CIDRs/`*`, and CGI protection.
104    /// The returned route is scoped to this host on port 443. For a URL with
105    /// a different scheme/port or local overrides, use [`Self::from_options`].
106    #[cfg(feature = "std")]
107    pub fn from_env(target_host: &str) -> Result<Self, Error> {
108        let host = match target_host.parse::<core::net::Ipv6Addr>() {
109            Ok(address) => format!("[{address}]"),
110            Err(_) => target_host.into(),
111        };
112        let mut url = url::Url::parse("https://localhost/").expect("valid HTTPS base URL");
113        url.set_host(Some(&host))?;
114        Self::from_options(&url, &crate::UpstreamProxyOptions::default())
115    }
116
117    /// Resolves a route for one origin using shared proxy selection and bypass
118    /// options. Use the returned configuration only for this origin.
119    ///
120    /// Discovery/validation errors propagate. A selected protocol unsupported
121    /// by this connector (currently SOCKS4/4a) returns an explicit error.
122    #[cfg(feature = "std")]
123    pub fn from_options(
124        target: &url::Url,
125        options: &crate::UpstreamProxyOptions,
126    ) -> Result<Self, Error> {
127        let policy = asimov_http::proxy::OriginProxy::resolve(target, options)?;
128        match policy.proxy_for_hyper()? {
129            Some(endpoint) => Self::from_endpoint(endpoint),
130            None => Ok(Self::Direct),
131        }
132    }
133
134    /// Parses a proxy URL such as `http://user:pass@host:port` or
135    /// `socks5h://host:port`.
136    ///
137    /// Produces an explicit route with no inherited bypass rules. URL syntax
138    /// uses shared validation; paths, queries, fragments, and port zero fail.
139    /// Use [`Self::Automatic`] or, with `std`, `from_options` for bypass policy.
140    pub fn parse(input: &str) -> Result<Self, Error> {
141        Self::from_endpoint(&asimov_http::proxy::parse_endpoint(input)?)
142    }
143
144    fn from_endpoint(url: &url::Url) -> Result<Self, Error> {
145        // Socket address tuples and TLS server names need an unbracketed IP.
146        let host = match url.host().ok_or(Error::MissingProxyHost)? {
147            url::Host::Domain(host) => host.to_string(),
148            url::Host::Ipv4(ip) => ip.to_string(),
149            url::Host::Ipv6(ip) => ip.to_string(),
150        };
151
152        let username = percent_encoding::percent_decode_str(url.username())
153            .decode_utf8()
154            .map_err(|_| Error::InvalidProxyUsername)?;
155        let password = url
156            .password()
157            .map(|password| percent_encoding::percent_decode_str(password).decode_utf8())
158            .transpose()
159            .map_err(|_| Error::InvalidProxyPassword)?;
160
161        match url.scheme() {
162            "http" | "https" => {
163                let tls = url.scheme() == "https";
164                let port = url.port().unwrap_or(if tls { 443 } else { 80 });
165                let basic_auth = if !username.is_empty() || password.is_some() {
166                    let credentials =
167                        format!("{}:{}", username, password.as_deref().unwrap_or_default());
168                    Some(base64::engine::general_purpose::STANDARD.encode(credentials))
169                } else {
170                    None
171                };
172                Ok(Self::HttpConnect {
173                    host,
174                    port,
175                    tls,
176                    basic_auth,
177                })
178            },
179
180            "socks5" | "socks5h" => {
181                let port = url.port().unwrap_or(1080);
182                let auth = if !username.is_empty() || password.is_some() {
183                    Some((
184                        username.to_string(),
185                        password.as_deref().unwrap_or_default().to_string(),
186                    ))
187                } else {
188                    None
189                };
190                Ok(Self::Socks5 {
191                    host,
192                    port,
193                    auth,
194                    remote_dns: url.scheme() == "socks5h",
195                })
196            },
197
198            scheme => Err(Error::UnsupportedProxyScheme(scheme.into())),
199        }
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn proxy_credentials_are_percent_decoded() {
209        for scheme in ["http", "https", "socks5", "socks5h"] {
210            let config = ProxyConfig::parse(&format!(
211                "{scheme}://user%40domain:p%3Aa%25ss+@proxy.example"
212            ))
213            .unwrap();
214            match config {
215                ProxyConfig::HttpConnect { basic_auth, .. } => {
216                    let decoded = base64::engine::general_purpose::STANDARD
217                        .decode(basic_auth.unwrap())
218                        .unwrap();
219                    assert_eq!(decoded, b"user@domain:p:a%ss+");
220                },
221                ProxyConfig::Socks5 { auth, .. } => {
222                    assert_eq!(auth, Some(("user@domain".into(), "p:a%ss+".into())));
223                },
224                ProxyConfig::Automatic | ProxyConfig::Direct => {
225                    panic!("expected proxy credentials")
226                },
227            }
228            let error = ProxyConfig::parse(&format!("{scheme}://user:secret%FF@proxy.example"))
229                .unwrap_err()
230                .to_string();
231            assert!(error.contains("UTF-8"));
232            assert!(!error.contains("secret"));
233        }
234    }
235
236    #[cfg(feature = "std")]
237    #[test]
238    fn ipv6_proxy_hosts_resolve_without_url_brackets() {
239        use alloc::vec::Vec;
240        use std::net::ToSocketAddrs;
241
242        for input in [
243            "http://[::1]:8080",
244            "https://[::1]:8080",
245            "socks5://[::1]:8080",
246            "socks5h://[::1]:8080",
247            "[::1]:8080",
248        ] {
249            let config = ProxyConfig::parse(input).unwrap();
250            let (host, port) = match config {
251                ProxyConfig::HttpConnect { host, port, .. }
252                | ProxyConfig::Socks5 { host, port, .. } => (host, port),
253                ProxyConfig::Automatic | ProxyConfig::Direct => panic!("expected a proxy"),
254            };
255            assert_eq!(host, "::1", "{input}");
256            let addresses: Vec<_> = (host.as_str(), port).to_socket_addrs().unwrap().collect();
257            assert_eq!(
258                addresses,
259                ["[::1]:8080".parse::<core::net::SocketAddr>().unwrap()]
260            );
261        }
262    }
263
264    #[test]
265    fn diagnostics_redact_proxy_credentials() {
266        let encoded = base64::engine::general_purpose::STANDARD.encode("private-user:private-pass");
267        for scheme in ["http", "https", "socks5", "socks5h"] {
268            let config = ProxyConfig::parse(&format!(
269                "{scheme}://private-user:private-pass@proxy.example:8080"
270            ))
271            .unwrap();
272            let debug = format!("{config:?}");
273            assert!(debug.contains("proxy.example"));
274            assert!(debug.contains("REDACTED"));
275            for secret in ["private-user", "private-pass", &encoded] {
276                assert!(!debug.contains(secret));
277            }
278            let error = ProxyConfig::parse(&format!(
279                "{scheme}://private-user:private-pass@proxy.example:invalid"
280            ))
281            .unwrap_err()
282            .to_string();
283            assert!(!error.contains("private-user"));
284            assert!(!error.contains("private-pass"));
285        }
286    }
287
288    #[test]
289    fn parse_http_proxy() {
290        let config = ProxyConfig::parse("http://proxy.example:3128").unwrap();
291        let ProxyConfig::HttpConnect {
292            host,
293            port,
294            tls,
295            basic_auth,
296        } = config
297        else {
298            panic!("expected HttpConnect, got: {:?}", config)
299        };
300        assert_eq!(host, "proxy.example");
301        assert_eq!(port, 3128);
302        assert!(!tls);
303        assert!(basic_auth.is_none());
304    }
305
306    #[test]
307    fn parse_bare_host_port_as_http_proxy() {
308        let config = ProxyConfig::parse("proxy.example:8080").unwrap();
309        assert!(matches!(
310            config,
311            ProxyConfig::HttpConnect {
312                tls: false,
313                port: 8080,
314                ..
315            }
316        ));
317    }
318
319    #[test]
320    fn parse_https_proxy_with_auth() {
321        let config = ProxyConfig::parse("https://user:pass@proxy.example").unwrap();
322        let ProxyConfig::HttpConnect {
323            host,
324            port,
325            tls,
326            basic_auth,
327        } = config
328        else {
329            panic!("expected HttpConnect, got: {:?}", config)
330        };
331        assert_eq!(host, "proxy.example");
332        assert_eq!(port, 443);
333        assert!(tls);
334        assert_eq!(basic_auth.as_deref(), Some("dXNlcjpwYXNz")); // "user:pass"
335    }
336
337    #[test]
338    fn parse_socks5_proxy() {
339        let config = ProxyConfig::parse("socks5://127.0.0.1").unwrap();
340        assert!(matches!(
341            config,
342            ProxyConfig::Socks5 {
343                port: 1080,
344                remote_dns: false,
345                auth: None,
346                ..
347            }
348        ));
349
350        let config = ProxyConfig::parse("socks5h://user:pass@127.0.0.1:9050").unwrap();
351        let ProxyConfig::Socks5 {
352            port,
353            remote_dns,
354            auth,
355            ..
356        } = config
357        else {
358            panic!("expected Socks5, got: {:?}", config)
359        };
360        assert_eq!(port, 9050);
361        assert!(remote_dns);
362        assert_eq!(auth, Some(("user".to_string(), "pass".to_string())));
363    }
364
365    #[test]
366    fn parse_unsupported_scheme() {
367        assert!(ProxyConfig::parse("ftp://proxy.example").is_err());
368    }
369
370    #[test]
371    fn explicit_endpoints_use_shared_validation() {
372        for endpoint in [
373            "http://proxy.example/path",
374            "http://proxy.example?query",
375            "http://proxy.example#fragment",
376            "http://proxy.example:0",
377            " proxy.example",
378        ] {
379            assert!(matches!(ProxyConfig::parse(endpoint), Err(Error::Proxy(_))));
380        }
381    }
382}