Skip to main content

saluki_components/common/proxy/
destination.rs

1//! Where a proxy forwards requests to, and the check that it doesn't forward them to itself.
2
3use std::net::{IpAddr, SocketAddr};
4#[cfg(unix)]
5use std::path::PathBuf;
6use std::time::Duration;
7
8use http::{uri::Authority, Uri};
9use saluki_error::{generic_error, ErrorContext as _, GenericError};
10use saluki_io::net::{client::http::HttpClientBuilder, ListenAddress};
11
12/// Where a proxy forwards requests to.
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub enum Destination {
15    /// A TCP host and port.
16    Tcp {
17        /// Host name or IP address, without brackets for IPv6.
18        ///
19        /// Valid hosts include `localhost`, `agent.internal`, `127.0.0.1`, and `::1`. `[::1]` isn't valid, because the
20        /// proxy adds the brackets to the request URI itself.
21        host: String,
22
23        /// Port.
24        port: u16,
25    },
26
27    /// A Unix domain socket path.
28    #[cfg(unix)]
29    Unix(PathBuf),
30}
31
32impl Destination {
33    /// Creates a TCP destination from a `host:port` address, such as `127.0.0.1:4319` or `[::1]:4319`.
34    ///
35    /// # Errors
36    ///
37    /// If `address` isn't a host and a port, an error is returned.
38    pub fn from_tcp_address(address: &str) -> Result<Self, GenericError> {
39        if address.contains('@') {
40            return Err(generic_error!(
41                "Invalid address `{address}`: expected a host and a port, without credentials."
42            ));
43        }
44        let authority = address
45            .parse::<Authority>()
46            .with_error_context(|| format!("Invalid address `{address}`: expected a host and a port."))?;
47        let port = authority
48            .port_u16()
49            .ok_or_else(|| generic_error!("Invalid address `{address}`: expected a host and a port."))?;
50        // An authority keeps an IPv6 host bracketed, which address lookups don't accept.
51        let host = authority
52            .host()
53            .trim_start_matches('[')
54            .trim_end_matches(']')
55            .to_string();
56        Ok(Self::Tcp { host, port })
57    }
58
59    /// Returns the URI with the scheme and authority of each request to this destination, and a root path.
60    ///
61    /// The client connects a Unix domain socket destination to its socket and ignores the authority, but a request URI
62    /// still needs one, so it gets `localhost`.
63    ///
64    /// # Errors
65    ///
66    /// If the host and port don't make a valid authority, an error is returned.
67    pub(crate) fn base_uri(&self) -> Result<Uri, http::Error> {
68        match self {
69            Self::Tcp { host, port } => {
70                // An IPv6 host needs brackets in a URI.
71                let authority = if host.contains(':') {
72                    format!("[{host}]:{port}")
73                } else {
74                    format!("{host}:{port}")
75                };
76                Uri::builder()
77                    .scheme("http")
78                    .authority(authority)
79                    .path_and_query("/")
80                    .build()
81            }
82            #[cfg(unix)]
83            Self::Unix(_) => Ok(Uri::from_static("http://localhost/")),
84        }
85    }
86
87    /// Makes the client that `builder` builds connect to this destination.
88    pub(crate) fn configure_client(&self, builder: HttpClientBuilder) -> HttpClientBuilder {
89        match self {
90            // The client connects to the host and port of each request URI.
91            Self::Tcp { .. } => builder,
92            #[cfg(unix)]
93            Self::Unix(path) => builder.with_unix_socket_path(path.clone()),
94        }
95    }
96}
97
98/// How long [`listener_reached_by`] waits for a destination's host name to resolve.
99///
100/// The value is arbitrary. Neither ADP nor the Agent has a lookup timeout to match, and the system resolver can retry for
101/// much longer.
102const LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);
103
104/// Returns the listener in `listeners` that `destination` reaches, if any.
105///
106/// A TCP destination reaches a TCP listener, and a Unix domain socket destination reaches a Unix domain socket listener
107/// on the same path. This catches the obvious misconfigurations, such as the same port used for both, not every route
108/// back to the proxy: a listener on every interface is also reached through the host's other addresses, for example.
109pub async fn listener_reached_by<'a, I>(destination: &Destination, listeners: I) -> Option<&'a ListenAddress>
110where
111    I: IntoIterator<Item = &'a ListenAddress>,
112{
113    match destination {
114        Destination::Tcp { host, port } => {
115            let tcp_listeners = listeners
116                .into_iter()
117                .filter_map(|endpoint| match endpoint {
118                    ListenAddress::Tcp(listener) => Some((endpoint, *listener)),
119                    _ => None,
120                })
121                .collect::<Vec<_>>();
122            if tcp_listeners.is_empty() {
123                return None;
124            }
125
126            // A destination that doesn't resolve yet can't be told apart from the listener, so it is let through. A
127            // slow resolver mustn't hold up startup, so a lookup that times out counts the same.
128            let destinations = tokio::time::timeout(LOOKUP_TIMEOUT, tokio::net::lookup_host((host.as_str(), *port)))
129                .await
130                .ok()?
131                .ok()?
132                .collect::<Vec<_>>();
133            tcp_listeners
134                .into_iter()
135                .find(|(_, listener)| {
136                    destinations
137                        .iter()
138                        .any(|destination| tcp_reaches(*destination, *listener))
139                })
140                .map(|(endpoint, _)| endpoint)
141        }
142        #[cfg(unix)]
143        Destination::Unix(path) => listeners
144            .into_iter()
145            .find(|endpoint| matches!(endpoint, ListenAddress::Unix(listener) if listener == path)),
146    }
147}
148
149/// Returns whether connecting to `destination` reaches a TCP listener bound to `listener`.
150///
151/// A listener on the unspecified address accepts connections to any local address, and connecting to the unspecified
152/// address connects to the local host, so either side being unspecified matches a loopback address of the same family.
153fn tcp_reaches(destination: SocketAddr, listener: SocketAddr) -> bool {
154    let is_local = |ip: IpAddr| ip.is_loopback() || ip.is_unspecified();
155    let (destination_ip, listener_ip) = (destination.ip(), listener.ip());
156
157    destination.port() == listener.port()
158        && (destination_ip == listener_ip
159            || ((destination_ip.is_unspecified() || listener_ip.is_unspecified())
160                && destination_ip.is_ipv4() == listener_ip.is_ipv4()
161                && is_local(destination_ip)
162                && is_local(listener_ip)))
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn base_uri_brackets_an_ipv6_host() {
171        let uri = |host: &str| {
172            Destination::Tcp {
173                host: host.to_string(),
174                port: 8126,
175            }
176            .base_uri()
177            .unwrap()
178            .to_string()
179        };
180
181        assert_eq!(uri("127.0.0.1"), "http://127.0.0.1:8126/");
182        assert_eq!(uri("localhost"), "http://localhost:8126/");
183        assert_eq!(uri("::1"), "http://[::1]:8126/");
184    }
185
186    #[test]
187    fn from_tcp_address_splits_the_host_and_port() {
188        let tcp = |host: &str, port| Destination::Tcp {
189            host: host.to_string(),
190            port,
191        };
192
193        assert_eq!(
194            Destination::from_tcp_address("127.0.0.1:4319").unwrap(),
195            tcp("127.0.0.1", 4319)
196        );
197        assert_eq!(
198            Destination::from_tcp_address("localhost:4320").unwrap(),
199            tcp("localhost", 4320)
200        );
201        assert_eq!(Destination::from_tcp_address("[::1]:4319").unwrap(), tcp("::1", 4319));
202
203        for address in [
204            "127.0.0.1",
205            "localhost:",
206            "http://127.0.0.1:4319",
207            "user@127.0.0.1:4319",
208            "",
209        ] {
210            assert!(Destination::from_tcp_address(address).is_err(), "{address:?}");
211        }
212    }
213
214    #[tokio::test]
215    async fn listener_reached_by_matches_a_listener_of_the_same_transport() {
216        let tcp = |host: &str, port| Destination::Tcp {
217            host: host.to_string(),
218            port,
219        };
220        let listen = |address: &str| ListenAddress::try_from(address).unwrap();
221        let wildcard = listen("tcp://0.0.0.0:4319");
222        let loopback = listen("tcp://127.0.0.1:4320");
223        let listeners = [&wildcard, &loopback];
224
225        assert_eq!(
226            listener_reached_by(&tcp("127.0.0.1", 4319), listeners).await,
227            Some(&wildcard)
228        );
229        assert_eq!(
230            listener_reached_by(&tcp("localhost", 4320), listeners).await,
231            Some(&loopback)
232        );
233        assert_eq!(listener_reached_by(&tcp("127.0.0.1", 4321), listeners).await, None);
234    }
235
236    #[cfg(unix)]
237    #[tokio::test]
238    async fn listener_reached_by_matches_a_unix_socket_listener_only_by_path() {
239        let tcp = |host: &str, port| Destination::Tcp {
240            host: host.to_string(),
241            port,
242        };
243        let unix = |path: &str| Destination::Unix(PathBuf::from(path));
244        let listen = |address: &str| ListenAddress::try_from(address).unwrap();
245        let loopback = listen("tcp://127.0.0.1:4320");
246        let socket = listen("unix:///tmp/otlp.sock");
247        let listeners = [&loopback, &socket];
248
249        assert_eq!(
250            listener_reached_by(&unix("/tmp/otlp.sock"), listeners).await,
251            Some(&socket)
252        );
253        assert_eq!(listener_reached_by(&unix("/tmp/other.sock"), listeners).await, None);
254        // A TCP destination never reaches a Unix domain socket listener, wherever it is in the list.
255        assert_eq!(listener_reached_by(&tcp("127.0.0.1", 4320), [&socket]).await, None);
256        assert_eq!(
257            listener_reached_by(&tcp("127.0.0.1", 4320), [&socket, &loopback]).await,
258            Some(&loopback)
259        );
260    }
261
262    #[test]
263    fn tcp_reaches_only_a_listener_on_the_same_port_and_address() {
264        let addr = |s: &str| s.parse::<SocketAddr>().unwrap();
265
266        assert!(tcp_reaches(addr("127.0.0.1:8126"), addr("127.0.0.1:8126")));
267        assert!(tcp_reaches(addr("127.0.0.1:8126"), addr("0.0.0.0:8126")));
268        assert!(tcp_reaches(addr("0.0.0.0:8126"), addr("127.0.0.1:8126")));
269        assert!(tcp_reaches(addr("[::1]:8126"), addr("[::]:8126")));
270
271        assert!(!tcp_reaches(addr("127.0.0.1:8127"), addr("127.0.0.1:8126")));
272        assert!(!tcp_reaches(addr("10.0.0.2:8126"), addr("10.0.0.1:8126")));
273        assert!(!tcp_reaches(addr("[::1]:8126"), addr("0.0.0.0:8126")));
274        assert!(!tcp_reaches(addr("127.0.0.1:8126"), addr("10.0.0.1:8126")));
275    }
276}