Skip to main content

trillium_client/
proxy.rs

1use crate::{HeaderName, HeaderValues, Headers, KnownHeaderName, Url};
2use base64::{Engine as _, engine::general_purpose::STANDARD};
3use std::{borrow::Cow, fmt, io, sync::Arc};
4use trillium_server_common::Destination;
5
6pub(crate) mod connect;
7pub use connect::ProxyConnectError;
8
9mod env;
10
11mod key;
12pub(crate) use key::ProxyKey;
13
14mod no_proxy;
15use no_proxy::NoProxy;
16
17mod router;
18pub(crate) use router::ArcedProxyRouter;
19pub use router::ProxyRouter;
20
21#[cfg(test)]
22mod tests;
23
24/// An outbound HTTP proxy: where to send requests, which origin schemes it carries, and which
25/// origins bypass it.
26///
27/// Install with [`Client::with_proxy`](crate::Client::with_proxy), alone or as part of a
28/// [`ProxyRouter`]. Plain HTTP requests are forwarded to the proxy. HTTPS requests, and HTTP
29/// requests that need the origin's own connection — upgrades such as WebSocket, HTTP/2 prior
30/// knowledge, and CONNECT — go through a CONNECT tunnel instead. A proxied request never falls
31/// back to a direct connection.
32///
33/// A `Proxy-Authorization` CONNECT header, including one derived from the endpoint URL's user
34/// information, is sent with both forwarded requests and tunnels; other CONNECT headers are sent
35/// only with CONNECT. While a router is installed, a `Proxy-Authorization` header set on an
36/// individual request is removed, including on requests sent directly. Installing a proxy does
37/// not change which certificates the TLS connector trusts.
38///
39/// ```
40/// use trillium_client::{Proxy, ProxySchemes};
41///
42/// let proxy = Proxy::new("http://user:pass@proxy.example:8080")?
43///     .with_schemes(ProxySchemes::Https)
44///     .except(["localhost", "127.0.0.0/8", "[::1]", ".internal.example"])?;
45/// # Ok::<(), std::io::Error>(())
46/// ```
47#[derive(Clone)]
48pub struct Proxy(Arc<Config>);
49
50#[derive(Clone)]
51struct Config {
52    endpoint: Url,
53    key: Arc<ProxyKey>,
54    schemes: ProxySchemes,
55    exceptions: NoProxy,
56}
57
58/// Which origin URL schemes a [`Proxy`] carries. Requests for other schemes connect directly.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum ProxySchemes {
62    /// `http://` origins only.
63    Http,
64    /// `https://` origins only.
65    Https,
66    /// Both `http://` and `https://` origins. The default.
67    #[default]
68    Both,
69}
70
71impl ProxySchemes {
72    fn includes(self, scheme: &str) -> bool {
73        match self {
74            Self::Http => scheme == "http",
75            Self::Https => scheme == "https",
76            Self::Both => matches!(scheme, "http" | "https"),
77        }
78    }
79}
80
81impl Proxy {
82    /// A proxy at `endpoint`, carrying both HTTP and HTTPS origins.
83    ///
84    /// `endpoint` is an `http://` or `https://` URL; without a scheme, `http://` is assumed. URL
85    /// user information becomes a Basic `Proxy-Authorization` CONNECT header, percent escapes
86    /// decoded, and is removed from the stored endpoint. The path, query, and fragment don't
87    /// affect connections.
88    ///
89    /// # Errors
90    ///
91    /// Returns [`io::ErrorKind::InvalidInput`] for a malformed URL, an unsupported scheme, a URL
92    /// without a host, or a username containing `:`. The error never includes the credentials.
93    pub fn new(endpoint: impl AsRef<str>) -> io::Result<Self> {
94        let endpoint = endpoint.as_ref();
95        let endpoint: Cow<'_, str> = if endpoint.contains("://") {
96            endpoint.into()
97        } else {
98            format!("http://{endpoint}").into()
99        };
100        let mut endpoint = Url::parse(&endpoint).map_err(|_| invalid("invalid proxy endpoint"))?;
101        let authorization = basic_authorization(&endpoint)?;
102        endpoint
103            .set_username("")
104            .map_err(|()| invalid("invalid proxy endpoint"))?;
105        endpoint
106            .set_password(None)
107            .map_err(|()| invalid("invalid proxy endpoint"))?;
108        Destination::from_url(&endpoint)?;
109
110        let mut connect_headers = Headers::new();
111        if let Some(authorization) = authorization {
112            connect_headers.insert(KnownHeaderName::ProxyAuthorization, authorization);
113        }
114        Ok(Self(Arc::new(Config {
115            key: Arc::new(ProxyKey::new(&endpoint, connect_headers)),
116            endpoint,
117            schemes: ProxySchemes::Both,
118            exceptions: NoProxy::default(),
119        })))
120    }
121
122    /// Carry only origins with these schemes.
123    #[must_use]
124    pub fn with_schemes(mut self, schemes: ProxySchemes) -> Self {
125        Arc::make_mut(&mut self.0).schemes = schemes;
126        self
127    }
128
129    /// Send this header to the proxy with `CONNECT`, replacing any values it already has.
130    ///
131    /// `Proxy-Authorization` is also sent with forwarded requests. Opening a tunnel fails if the
132    /// CONNECT headers include `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, or
133    /// `Upgrade`: the client writes `Host` itself, and a `CONNECT` request has no body and
134    /// upgrades nothing.
135    #[must_use]
136    pub fn with_connect_header(
137        mut self,
138        name: impl Into<HeaderName<'static>>,
139        value: impl Into<HeaderValues>,
140    ) -> Self {
141        let config = Arc::make_mut(&mut self.0);
142        let mut connect_headers = config.key.connect_headers().clone();
143        connect_headers.insert(name, value);
144        config.key = Arc::new(ProxyKey::new(&config.endpoint, connect_headers));
145        self
146    }
147
148    /// Connect directly to origins matching any of these bypass entries, in addition to any
149    /// already added.
150    ///
151    /// Each entry is one domain name, IP address, or CIDR network, written exactly. Entries are
152    /// matched against the URL host without resolving DNS. A domain matches itself and its
153    /// subdomains at label boundaries, so `example.com` matches `a.example.com` but not
154    /// `notexample.com`; a leading `.` or `*.` is optional, and case and trailing dots are ignored.
155    /// An optional `:port` limits an entry to that effective URL port; bracket an IPv6 literal that
156    /// has a port, as in `[::1]:8080`. IP addresses and networks match IP-literal URLs, not
157    /// addresses a domain resolves to.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`io::ErrorKind::InvalidInput`], naming the entry, for one that is malformed,
162    /// empty, has surrounding whitespace, or contains a comma, and for `*`, which would leave the
163    /// proxy carrying nothing.
164    pub fn except<I>(mut self, entries: I) -> io::Result<Self>
165    where
166        I: IntoIterator,
167        I::Item: AsRef<str>,
168    {
169        let exceptions = &mut Arc::make_mut(&mut self.0).exceptions;
170        for entry in entries {
171            exceptions.push(entry.as_ref())?;
172        }
173        Ok(self)
174    }
175
176    /// The proxy's URL, without credentials.
177    #[must_use]
178    pub fn endpoint(&self) -> &Url {
179        &self.0.endpoint
180    }
181
182    /// The origin schemes this proxy carries.
183    #[must_use]
184    pub fn schemes(&self) -> ProxySchemes {
185        self.0.schemes
186    }
187
188    /// The headers sent to the proxy with `CONNECT`.
189    #[must_use]
190    pub fn connect_headers(&self) -> &Headers {
191        self.0.key.connect_headers()
192    }
193
194    /// Whether this proxy carries a request to `url`, by its schemes and bypass entries.
195    fn carries(&self, url: &Url) -> bool {
196        self.0.schemes.includes(url.scheme()) && !self.0.exceptions.contains(url)
197    }
198
199    fn with_exceptions(mut self, exceptions: &NoProxy) -> Self {
200        Arc::make_mut(&mut self.0)
201            .exceptions
202            .extend(exceptions.clone());
203        self
204    }
205
206    pub(crate) fn key(&self) -> &Arc<ProxyKey> {
207        &self.0.key
208    }
209
210    /// The [`Destination`] for dialing the proxy itself.
211    ///
212    /// Talking to an HTTP proxy is a `CONNECT` exchange or a forwarded HTTP/1.1 request,
213    /// so the ALPN is pinned rather than negotiated.
214    pub(crate) fn destination(&self) -> io::Result<Destination> {
215        let mut destination = Destination::from_url(&self.0.endpoint)?;
216        destination.set_alpn([Cow::Borrowed(b"http/1.1".as_slice())]);
217        Ok(destination)
218    }
219}
220
221impl fmt::Debug for Proxy {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        f.debug_struct("Proxy")
224            .field("endpoint", &self.0.endpoint.as_str())
225            .field("schemes", &self.0.schemes)
226            .field("exceptions", &self.0.exceptions)
227            .finish_non_exhaustive()
228    }
229}
230
231fn basic_authorization(endpoint: &Url) -> io::Result<Option<String>> {
232    if endpoint.username().is_empty() && endpoint.password().is_none() {
233        return Ok(None);
234    }
235    let username: Vec<u8> = percent_encoding::percent_decode_str(endpoint.username()).collect();
236    if username.contains(&b':') {
237        return Err(invalid(
238            "Basic proxy authorization username contains a colon",
239        ));
240    }
241    let password: Vec<u8> =
242        percent_encoding::percent_decode_str(endpoint.password().unwrap_or_default()).collect();
243    let mut credentials = username;
244    credentials.push(b':');
245    credentials.extend(password);
246    Ok(Some(format!("Basic {}", STANDARD.encode(credentials))))
247}
248
249fn invalid(message: &str) -> io::Error {
250    io::Error::new(io::ErrorKind::InvalidInput, message)
251}