Skip to main content

saluki_components/common/datadog/
proxy.rs

1use std::net::IpAddr;
2use std::sync::Arc;
3
4use headers::Authorization;
5use hyper_http_proxy::{Intercept, Proxy};
6use saluki_error::GenericError;
7use url::Url;
8
9/// Proxy configuration.
10#[derive(Clone)]
11#[cfg_attr(test, derive(Debug, PartialEq))]
12pub struct ProxyConfiguration {
13    /// The proxy server for HTTP requests.
14    ///
15    /// If empty, HTTP requests are not proxied.
16    pub http: String,
17
18    /// The proxy server for HTTPS requests.
19    ///
20    /// If empty, HTTPS requests are not proxied.
21    pub https: String,
22
23    /// List of hosts that should bypass the proxy.
24    ///
25    /// Each entry can be one of:
26    ///
27    /// - An exact IP address: `192.168.1.1` or `::1`. An optional port suffix (`192.168.1.1:8080`)
28    ///   restricts the match to that port only; without a port, all ports match.
29    /// - A CIDR range: `192.168.0.0/24` or `2001:db8::/32`. Only used when
30    ///   `no_proxy_nonexact_match` is true; ignored in exact mode.
31    /// - A domain name: `example.com`. In exact mode, only the literal hostname matches. In
32    ///   nonexact mode, the domain and all its subdomains match (for example, `example.com` also matches
33    ///   `sub.example.com`). An optional port suffix (`example.com:443`) restricts the match to
34    ///   that port.
35    /// - A leading-dot domain: `.example.com`. Only used in nonexact mode; matches subdomains
36    ///   only, not the domain itself (for example, `.example.com` matches `sub.example.com` but not
37    ///   `example.com`).
38    /// - A wildcard `*`: bypasses the proxy for all destinations. Only used in nonexact mode.
39    pub no_proxy: Vec<String>,
40
41    /// When true, `no_proxy` uses full domain/CIDR/wildcard matching, mirroring the behavior of Go's
42    /// [`golang.org/x/net/http/httpproxy`](https://pkg.go.dev/golang.org/x/net/http/httpproxy) package.
43    /// When false, only exact host matches are applied; suffix and CIDR entries are ignored.
44    pub no_proxy_nonexact_match: bool,
45
46    /// When true, proxy settings apply to requests for cloud provider metadata endpoints.
47    ///
48    /// When false, the well-known cloud metadata addresses are automatically added to the `no_proxy` list so they
49    /// always bypass the proxy.
50    pub use_proxy_for_cloud_metadata: bool,
51}
52
53/// Well-known cloud provider metadata endpoint addresses that bypass the proxy by default.
54const CLOUD_METADATA_ADDRS: &[&str] = &[
55    "169.254.169.254", // Azure, EC2, GCE
56    "100.100.100.200", // Alibaba
57];
58
59impl ProxyConfiguration {
60    /// Builds the configured proxies.
61    ///
62    /// Each proxy uses a custom intercept that forwards only requests matching the proxy's scheme
63    /// (HTTP or HTTPS) and not excluded by `no_proxy`. Cloud metadata addresses are appended to
64    /// the exclusion list unless `use_proxy_for_cloud_metadata` is true. Matching mode (exact vs.
65    /// full domain/CIDR/wildcard) is controlled by `no_proxy_nonexact_match`.
66    ///
67    /// # Errors
68    ///
69    /// If the configured proxy URLs are invalid, an error is returned.
70    pub fn build(&self) -> Result<Vec<Proxy>, GenericError> {
71        // Build the effective no_proxy list, injecting cloud metadata addresses unless the caller
72        // has explicitly opted in to proxying them.
73        let mut effective_no_proxy = self.no_proxy.clone();
74        if !self.use_proxy_for_cloud_metadata {
75            effective_no_proxy.extend(CLOUD_METADATA_ADDRS.iter().map(|s| s.to_string()));
76        }
77
78        let matcher = Arc::new(NoProxyMatcher::new(&effective_no_proxy, self.no_proxy_nonexact_match));
79
80        let mut proxies = Vec::new();
81
82        if let Some(url) = non_empty(&self.http) {
83            let m = Arc::clone(&matcher);
84            let intercept = Intercept::from(move |scheme: Option<&str>, host: Option<&str>, port: Option<u16>| {
85                scheme == Some("http") && !host.is_some_and(|h| m.matches(h, port))
86            });
87            proxies.push(new_proxy(url, intercept)?);
88        }
89
90        if let Some(url) = non_empty(&self.https) {
91            let m = Arc::clone(&matcher);
92            let intercept = Intercept::from(move |scheme: Option<&str>, host: Option<&str>, port: Option<u16>| {
93                scheme == Some("https") && !host.is_some_and(|h| m.matches(h, port))
94            });
95            proxies.push(new_proxy(url, intercept)?);
96        }
97
98        Ok(proxies)
99    }
100}
101
102/// Returns the value unless it is empty, in which case the setting is not configured.
103fn non_empty(value: &str) -> Option<&str> {
104    (!value.is_empty()).then_some(value)
105}
106
107fn new_proxy(proxy_url: &str, intercept: Intercept) -> Result<Proxy, GenericError> {
108    let url = Url::parse(proxy_url)?;
109    let mut proxy = Proxy::new(intercept, url.as_str().parse()?);
110    if let Some(password) = url.password() {
111        let username = url.username();
112        proxy.set_authorization(Authorization::basic(username, password));
113    }
114    Ok(proxy)
115}
116
117/// Parsed representation of a single `no_proxy` entry.
118enum NoProxyEntry {
119    /// `*`—bypass proxy for all destinations. Only used in nonexact mode.
120    Wildcard,
121    /// An IP address in CIDR notation (for example, `192.168.0.0/24`). Only used in nonexact mode.
122    IpCidr { addr: IpAddr, prefix_len: u8 },
123    /// An exact IP address, with an optional port constraint (for example, `192.168.1.1` or `192.168.1.1:80`).
124    IpExact { addr: IpAddr, port: Option<u16> },
125    /// A domain name, with optional port constraint and a flag for suffix-only matching.
126    ///
127    /// When `suffix_only` is true (entry had a leading `.`), only subdomains match, not the domain
128    /// itself. When false, both the domain and its subdomains match (in nonexact mode).
129    Domain {
130        name: String,
131        port: Option<u16>,
132        suffix_only: bool,
133    },
134}
135
136impl NoProxyEntry {
137    fn matches(&self, host: &str, port: Option<u16>, nonexact: bool) -> bool {
138        match self {
139            NoProxyEntry::Wildcard => nonexact,
140
141            NoProxyEntry::IpExact { addr, port: entry_port } => {
142                let host_matches = host.parse::<IpAddr>() == Ok(*addr);
143                let port_matches = entry_port.is_none_or(|ep| port == Some(ep));
144                host_matches && port_matches
145            }
146
147            NoProxyEntry::IpCidr { addr, prefix_len } => {
148                if !nonexact {
149                    return false;
150                }
151                host.parse::<IpAddr>().is_ok_and(|h| ip_in_cidr(*addr, *prefix_len, h))
152            }
153
154            NoProxyEntry::Domain {
155                name,
156                port: entry_port,
157                suffix_only,
158            } => {
159                let port_matches = entry_port.is_none_or(|ep| port == Some(ep));
160                if !port_matches {
161                    return false;
162                }
163                let host_lower = host.to_lowercase();
164                if nonexact {
165                    if *suffix_only {
166                        // Leading-dot entry: only matches subdomains, not the domain itself.
167                        // for example, ".y.com" matches "x.y.com" but not "y.com".
168                        host_lower.ends_with(&format!(".{}", name))
169                    } else {
170                        // Plain domain: matches the domain and all subdomains.
171                        // for example, "foo.com" matches "foo.com" and "bar.foo.com".
172                        host_lower == *name || host_lower.ends_with(&format!(".{}", name))
173                    }
174                } else {
175                    // Exact mode: suffix-only entries are ignored entirely; plain domains match
176                    // only the literal hostname.
177                    if *suffix_only {
178                        return false;
179                    }
180                    host_lower == *name
181                }
182            }
183        }
184    }
185}
186
187struct NoProxyMatcher {
188    entries: Vec<NoProxyEntry>,
189    nonexact: bool,
190}
191
192impl NoProxyMatcher {
193    fn new(no_proxy: &[String], nonexact: bool) -> Self {
194        let entries = no_proxy.iter().filter_map(|s| parse_no_proxy_entry(s)).collect();
195        Self { entries, nonexact }
196    }
197
198    fn matches(&self, host: &str, port: Option<u16>) -> bool {
199        self.entries.iter().any(|e| e.matches(host, port, self.nonexact))
200    }
201}
202
203/// Parses a single `no_proxy` entry string. Returns `None` for empty or malformed entries (best-effort).
204fn parse_no_proxy_entry(entry: &str) -> Option<NoProxyEntry> {
205    let entry = entry.trim();
206    if entry.is_empty() {
207        return None;
208    }
209    if entry == "*" {
210        return Some(NoProxyEntry::Wildcard);
211    }
212
213    // CIDR notation: `1.2.3.4/8`. A CIDR entry does not carry a port.
214    if let Some((ip_str, prefix_str)) = entry.split_once('/') {
215        let addr = ip_str.parse::<IpAddr>().ok()?;
216        let prefix_len = prefix_str.parse::<u8>().ok()?;
217        return Some(NoProxyEntry::IpCidr { addr, prefix_len });
218    }
219
220    // Everything else may carry an optional port suffix.
221    let (host_str, port) = split_host_port(entry);
222
223    // Try parsing as a bare IP address.
224    if let Ok(addr) = host_str.parse::<IpAddr>() {
225        return Some(NoProxyEntry::IpExact { addr, port });
226    }
227
228    // Treat as a domain name.
229    let suffix_only = host_str.starts_with('.');
230    let name = host_str.trim_start_matches('.').to_lowercase();
231    if name.is_empty() {
232        return None;
233    }
234    Some(NoProxyEntry::Domain {
235        name,
236        port,
237        suffix_only,
238    })
239}
240
241/// Splits a host string into a (host, port) pair.
242///
243/// Handles IPv6 addresses in brackets (`[::1]` or `[::1]:80`), bare IPv6 addresses (multiple
244/// colons, treated as having no port), and standard `host:port` or `ip:port` forms.
245fn split_host_port(s: &str) -> (&str, Option<u16>) {
246    // Bracketed IPv6: [::1] or [::1]:80
247    if s.starts_with('[') {
248        if let Some(end) = s.find(']') {
249            let host = &s[1..end];
250            let port = s
251                .get(end + 1..)
252                .and_then(|r| r.strip_prefix(':'))
253                .and_then(|p| p.parse().ok());
254            return (host, port);
255        }
256    }
257    // Bare IPv6 (multiple colons) has no port component.
258    if s.chars().filter(|&c| c == ':').count() > 1 {
259        return (s, None);
260    }
261    // Single colon: try host:port.
262    if let Some(pos) = s.rfind(':') {
263        if let Ok(port) = s[pos + 1..].parse::<u16>() {
264            return (&s[..pos], Some(port));
265        }
266    }
267    (s, None)
268}
269
270/// Returns true if `addr` falls within the CIDR block defined by `network`/`prefix_len`.
271fn ip_in_cidr(network: IpAddr, prefix_len: u8, addr: IpAddr) -> bool {
272    match (network, addr) {
273        (IpAddr::V4(net), IpAddr::V4(tgt)) => {
274            if prefix_len == 0 {
275                return true;
276            }
277            if prefix_len > 32 {
278                return false;
279            }
280            let shift = 32 - prefix_len;
281            (u32::from(net) >> shift) == (u32::from(tgt) >> shift)
282        }
283        (IpAddr::V6(net), IpAddr::V6(tgt)) => {
284            if prefix_len == 0 {
285                return true;
286            }
287            if prefix_len > 128 {
288                return false;
289            }
290            let shift = 128 - prefix_len;
291            (u128::from(net) >> shift) == (u128::from(tgt) >> shift)
292        }
293        // IPv4 vs IPv6 mismatch—never matches.
294        _ => false,
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use crate::common::datadog::test_util::init_tls;
302
303    fn unproxied() -> ProxyConfiguration {
304        ProxyConfiguration {
305            http: String::new(),
306            https: String::new(),
307            no_proxy: Vec::new(),
308            no_proxy_nonexact_match: false,
309            use_proxy_for_cloud_metadata: false,
310        }
311    }
312
313    fn matcher(entries: &[&str], nonexact: bool) -> NoProxyMatcher {
314        NoProxyMatcher::new(&entries.iter().map(|s| s.to_string()).collect::<Vec<_>>(), nonexact)
315    }
316
317    // --- construction ---
318
319    #[test]
320    fn an_empty_proxy_url_is_not_configured() {
321        let config = ProxyConfiguration {
322            https: "http://proxy.example.com:3128".to_string(),
323            ..unproxied()
324        };
325
326        let proxies = config.build().expect("should build");
327        assert_eq!(1, proxies.len());
328        assert!(!proxies[0]
329            .intercept()
330            .matches(&"http://example.com/".parse::<hyper::Uri>().unwrap()));
331        assert!(proxies[0]
332            .intercept()
333            .matches(&"https://example.com/".parse::<hyper::Uri>().unwrap()));
334    }
335
336    // --- wildcard ---
337
338    #[test]
339    fn wildcard_matches_any_host_in_nonexact_mode() {
340        let m = matcher(&["*"], true);
341        assert!(m.matches("anything.example.com", None));
342        assert!(m.matches("192.168.1.1", None));
343    }
344
345    #[test]
346    fn wildcard_ignored_in_exact_mode() {
347        let m = matcher(&["*"], false);
348        assert!(!m.matches("anything.example.com", None));
349        assert!(!m.matches("192.168.1.1", None));
350    }
351
352    // --- exact IP ---
353
354    #[test]
355    fn exact_ip_matches() {
356        let m = matcher(&["192.168.1.1"], true);
357        assert!(m.matches("192.168.1.1", None));
358        assert!(!m.matches("192.168.1.2", None));
359        assert!(!m.matches("example.com", None));
360    }
361
362    #[test]
363    fn exact_ip_with_port_requires_port_match() {
364        let m = matcher(&["192.168.1.1:8080"], true);
365        assert!(m.matches("192.168.1.1", Some(8080)));
366        assert!(!m.matches("192.168.1.1", Some(9090)));
367        assert!(!m.matches("192.168.1.1", None));
368    }
369
370    #[test]
371    fn exact_ip_without_port_matches_any_port() {
372        let m = matcher(&["192.168.1.1"], true);
373        assert!(m.matches("192.168.1.1", Some(80)));
374        assert!(m.matches("192.168.1.1", None));
375    }
376
377    // --- CIDR ---
378
379    #[test]
380    fn cidr_matches_address_in_range() {
381        let m = matcher(&["192.168.0.0/24"], true);
382        assert!(m.matches("192.168.0.1", None));
383        assert!(m.matches("192.168.0.254", None));
384        assert!(!m.matches("192.168.1.1", None));
385    }
386
387    #[test]
388    fn cidr_ignored_in_exact_mode() {
389        let m = matcher(&["192.168.0.0/24"], false);
390        assert!(!m.matches("192.168.0.1", None));
391    }
392
393    #[test]
394    fn cidr_prefix_zero_matches_any_address() {
395        let m = matcher(&["0.0.0.0/0"], true);
396        assert!(m.matches("1.2.3.4", None));
397        assert!(m.matches("192.168.1.1", None));
398    }
399
400    #[test]
401    fn cidr_ipv4_does_not_match_ipv6_address() {
402        let m = matcher(&["192.168.0.0/24"], true);
403        assert!(!m.matches("::1", None));
404    }
405
406    #[test]
407    fn cidr_ipv6_does_not_match_ipv4_address() {
408        let m = matcher(&["2001:db8::/32"], true);
409        assert!(!m.matches("192.168.0.1", None));
410    }
411
412    // --- IPv6 ---
413
414    #[test]
415    fn exact_ipv6_matches() {
416        let m = matcher(&["::1"], true);
417        assert!(m.matches("::1", None));
418        assert!(!m.matches("::2", None));
419        assert!(!m.matches("192.168.1.1", None));
420    }
421
422    #[test]
423    fn exact_ipv6_with_port_requires_port_match() {
424        let m = matcher(&["[::1]:8080"], true);
425        assert!(m.matches("::1", Some(8080)));
426        assert!(!m.matches("::1", Some(9090)));
427        assert!(!m.matches("::1", None));
428    }
429
430    #[test]
431    fn exact_ipv6_without_port_matches_any_port() {
432        let m = matcher(&["::1"], true);
433        assert!(m.matches("::1", Some(80)));
434        assert!(m.matches("::1", None));
435    }
436
437    #[test]
438    fn ipv6_cidr_matches_address_in_range() {
439        let m = matcher(&["2001:db8::/32"], true);
440        assert!(m.matches("2001:db8::1", None));
441        assert!(m.matches("2001:db8:ffff::1", None));
442        assert!(!m.matches("2001:db9::1", None));
443    }
444
445    #[test]
446    fn ipv6_cidr_ignored_in_exact_mode() {
447        let m = matcher(&["2001:db8::/32"], false);
448        assert!(!m.matches("2001:db8::1", None));
449    }
450
451    // --- domain exact mode ---
452
453    #[test]
454    fn domain_exact_mode_matches_literal() {
455        let m = matcher(&["localhost"], false);
456        assert!(m.matches("localhost", None));
457        assert!(!m.matches("other.localhost", None));
458    }
459
460    #[test]
461    fn domain_exact_mode_does_not_match_subdomains() {
462        let m = matcher(&["example.com"], false);
463        assert!(m.matches("example.com", None));
464        assert!(!m.matches("sub.example.com", None));
465    }
466
467    #[test]
468    fn domain_suffix_entry_ignored_in_exact_mode() {
469        // Leading-dot entries are suffix-only and should be ignored in exact mode.
470        let m = matcher(&[".example.com"], false);
471        assert!(!m.matches("sub.example.com", None));
472        assert!(!m.matches("example.com", None));
473    }
474
475    // --- domain nonexact mode ---
476
477    #[test]
478    fn domain_nonexact_matches_domain_and_subdomains() {
479        let m = matcher(&["foo.com"], true);
480        assert!(m.matches("foo.com", None));
481        assert!(m.matches("bar.foo.com", None));
482        assert!(!m.matches("notfoo.com", None));
483    }
484
485    #[test]
486    fn domain_suffix_only_matches_subdomains_not_domain() {
487        // ".y.com" matches "x.y.com" but not "y.com"
488        let m = matcher(&[".y.com"], true);
489        assert!(m.matches("x.y.com", None));
490        assert!(!m.matches("y.com", None));
491    }
492
493    #[test]
494    fn domain_matching_is_case_insensitive() {
495        let m = matcher(&["Example.COM"], true);
496        assert!(m.matches("example.com", None));
497        assert!(m.matches("SUB.EXAMPLE.COM", None));
498    }
499
500    #[test]
501    fn domain_with_port_requires_port_match() {
502        let m = matcher(&["example.com:443"], true);
503        assert!(m.matches("example.com", Some(443)));
504        assert!(!m.matches("example.com", Some(80)));
505        assert!(!m.matches("example.com", None));
506    }
507
508    // --- cloud metadata defaults ---
509
510    fn proxy_config_with_cloud_flag(use_proxy: bool) -> ProxyConfiguration {
511        ProxyConfiguration {
512            http: "http://proxy.example.com:3128".to_string(),
513            use_proxy_for_cloud_metadata: use_proxy,
514            ..unproxied()
515        }
516    }
517
518    #[test]
519    fn cloud_metadata_bypasses_proxy_by_default() {
520        let config = proxy_config_with_cloud_flag(false);
521        let proxies = config.build().expect("should build");
522        // With a custom intercept the proxy list still has one entry.
523        assert_eq!(proxies.len(), 1);
524        // The intercept should not proxy cloud metadata addresses.
525        assert!(!proxies[0]
526            .intercept()
527            .matches(&"http://169.254.169.254/latest/meta-data".parse::<hyper::Uri>().unwrap()));
528        assert!(!proxies[0]
529            .intercept()
530            .matches(&"http://100.100.100.200/".parse::<hyper::Uri>().unwrap()));
531        // Normal hosts should still be proxied.
532        assert!(proxies[0]
533            .intercept()
534            .matches(&"http://example.com/".parse::<hyper::Uri>().unwrap()));
535    }
536
537    #[test]
538    fn cloud_metadata_proxied_when_flag_enabled() {
539        let config = proxy_config_with_cloud_flag(true);
540        let proxies = config.build().expect("should build");
541        assert_eq!(proxies.len(), 1);
542        // With no no_proxy list and the flag enabled, nothing is excluded—proxies everything.
543        assert!(proxies[0]
544            .intercept()
545            .matches(&"http://169.254.169.254/latest/meta-data".parse::<hyper::Uri>().unwrap()));
546        assert!(proxies[0]
547            .intercept()
548            .matches(&"http://100.100.100.200/".parse::<hyper::Uri>().unwrap()));
549    }
550
551    // --- end-to-end routing tests ---
552    //
553    // These tests spin up a mock HTTP server acting as a proxy and verify that the
554    // HttpClient actually routes (or bypasses) traffic correctly based on ProxyConfiguration.
555
556    async fn start_mock_http_server(status: http::StatusCode) -> u16 {
557        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
558        let port = listener.local_addr().unwrap().port();
559        let router = axum::Router::new().fallback(move || async move { status });
560        tokio::spawn(async move {
561            axum::serve(listener, router).await.unwrap();
562        });
563        port
564    }
565
566    fn proxy_config_for_routing(proxy_http: &str, no_proxy: &[&str]) -> ProxyConfiguration {
567        ProxyConfiguration {
568            http: proxy_http.to_string(),
569            no_proxy: no_proxy.iter().map(|entry| entry.to_string()).collect(),
570            ..unproxied()
571        }
572    }
573
574    #[tokio::test]
575    async fn http_request_routed_through_proxy() {
576        init_tls();
577        // The mock proxy returns 418; a direct connection to doesnotexist.example.com would fail.
578        // Getting 418 back confirms the request reached our mock proxy.
579        let proxy_port = start_mock_http_server(http::StatusCode::IM_A_TEAPOT).await;
580        let config = proxy_config_for_routing(&format!("http://127.0.0.1:{proxy_port}"), &[]);
581        let proxies = config.build().unwrap();
582
583        let mut client = saluki_io::net::client::http::HttpClient::builder()
584            .with_proxies(proxies)
585            .build()
586            .unwrap();
587
588        let req = http::Request::builder()
589            .uri("http://doesnotexist.example.com/")
590            .body(http_body_util::Empty::<bytes::Bytes>::new())
591            .unwrap();
592        let resp = client.send(req).await.unwrap();
593        assert_eq!(resp.status(), http::StatusCode::IM_A_TEAPOT);
594    }
595
596    #[tokio::test]
597    async fn no_proxy_host_bypasses_proxy() {
598        init_tls();
599        // The mock proxy returns 418; the direct server returns 200.
600        // Getting 200 back confirms the request bypassed the proxy and went directly.
601        let proxy_port = start_mock_http_server(http::StatusCode::IM_A_TEAPOT).await;
602        let direct_port = start_mock_http_server(http::StatusCode::OK).await;
603        let config = proxy_config_for_routing(
604            &format!("http://127.0.0.1:{proxy_port}"),
605            &[&format!("127.0.0.1:{direct_port}")],
606        );
607        let proxies = config.build().unwrap();
608
609        let mut client = saluki_io::net::client::http::HttpClient::builder()
610            .with_proxies(proxies)
611            .build()
612            .unwrap();
613
614        let req = http::Request::builder()
615            .uri(format!("http://127.0.0.1:{direct_port}/"))
616            .body(http_body_util::Empty::<bytes::Bytes>::new())
617            .unwrap();
618        let resp = client.send(req).await.unwrap();
619        assert_eq!(resp.status(), http::StatusCode::OK);
620    }
621
622    /// Starts a minimal raw TCP server that handles a single HTTP CONNECT request per connection.
623    ///
624    /// Returns the listening port and a channel receiver that yields the `host:port` target from
625    /// each CONNECT request received. The server runs until the tokio test runtime is dropped.
626    async fn start_mock_connect_proxy() -> (u16, tokio::sync::mpsc::Receiver<String>) {
627        use tokio::io::{AsyncReadExt, AsyncWriteExt};
628
629        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
630        let port = listener.local_addr().unwrap().port();
631        let (tx, rx) = tokio::sync::mpsc::channel(10);
632
633        tokio::spawn(async move {
634            while let Ok((mut stream, _)) = listener.accept().await {
635                let tx = tx.clone();
636                tokio::spawn(async move {
637                    let mut buf = vec![0u8; 4096];
638                    if let Ok(n) = stream.read(&mut buf).await {
639                        let req = String::from_utf8_lossy(&buf[..n]);
640                        // "CONNECT host:port HTTP/1.1\r\n..."
641                        if let Some(target) = req.strip_prefix("CONNECT ").and_then(|s| s.split_whitespace().next()) {
642                            let _ = tx.send(target.to_string()).await;
643                        }
644                        let _ = stream.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n").await;
645                    }
646                    // Hold the connection open briefly so the client can read the 200 before
647                    // the stream is dropped and the connection closes.
648                    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
649                });
650            }
651        });
652
653        (port, rx)
654    }
655
656    #[tokio::test]
657    async fn https_request_routed_through_proxy() {
658        init_tls();
659        // The mock CONNECT proxy records the target from each CONNECT request. The TLS
660        // handshake will fail after the tunnel is established (no real server behind it), but
661        // receiving the CONNECT confirms the request was routed through the proxy.
662        let (proxy_port, mut rx) = start_mock_connect_proxy().await;
663        let config = ProxyConfiguration {
664            https: format!("http://127.0.0.1:{proxy_port}"),
665            ..unproxied()
666        };
667        let proxies = config.build().unwrap();
668
669        let mut client = saluki_io::net::client::http::HttpClient::builder()
670            .with_proxies(proxies)
671            .with_tls_config(|b| b.danger_accept_invalid_certs())
672            .build()
673            .unwrap();
674
675        let req = http::Request::builder()
676            .uri("https://doesnotexist.example.com/")
677            .body(http_body_util::Empty::<bytes::Bytes>::new())
678            .unwrap();
679        // TLS will fail after the CONNECT tunnel is established; ignore the error.
680        let _ = client.send(req).await;
681
682        // Verify the proxy received a CONNECT request for our target.
683        let connect_target = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
684            .await
685            .expect("timed out waiting for CONNECT request")
686            .expect("channel closed unexpectedly");
687        assert!(
688            connect_target.starts_with("doesnotexist.example.com:"),
689            "unexpected CONNECT target: {connect_target}"
690        );
691    }
692
693    #[tokio::test]
694    async fn https_no_proxy_host_bypasses_proxy() {
695        init_tls();
696        // For a no_proxy host, the client connects directly rather than sending a CONNECT to
697        // the proxy. We verify this by asserting the proxy receives no CONNECT request.
698        let (proxy_port, mut rx) = start_mock_connect_proxy().await;
699        let direct_port = start_mock_http_server(http::StatusCode::OK).await;
700        let config = ProxyConfiguration {
701            https: format!("http://127.0.0.1:{proxy_port}"),
702            no_proxy: vec![format!("127.0.0.1:{direct_port}")],
703            ..unproxied()
704        };
705        let proxies = config.build().unwrap();
706
707        let mut client = saluki_io::net::client::http::HttpClient::builder()
708            .with_proxies(proxies)
709            .with_tls_config(|b| b.danger_accept_invalid_certs())
710            .build()
711            .unwrap();
712
713        let req = http::Request::builder()
714            .uri(format!("https://127.0.0.1:{direct_port}/"))
715            .body(http_body_util::Empty::<bytes::Bytes>::new())
716            .unwrap();
717        // Direct connection: TLS fails (plain HTTP server), but the proxy should not be
718        // contacted. Ignore the error.
719        let _ = client.send(req).await;
720
721        // Verify the proxy received no CONNECT requests.
722        assert!(
723            rx.try_recv().is_err(),
724            "proxy should not have been contacted for a no_proxy host"
725        );
726    }
727}