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#[derive(Clone)]
11#[cfg_attr(test, derive(Debug, PartialEq))]
12pub struct ProxyConfiguration {
13 pub http: String,
17
18 pub https: String,
22
23 pub no_proxy: Vec<String>,
40
41 pub no_proxy_nonexact_match: bool,
45
46 pub use_proxy_for_cloud_metadata: bool,
51}
52
53const CLOUD_METADATA_ADDRS: &[&str] = &[
55 "169.254.169.254", "100.100.100.200", ];
58
59impl ProxyConfiguration {
60 pub fn build(&self) -> Result<Vec<Proxy>, GenericError> {
71 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
102fn 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
117enum NoProxyEntry {
119 Wildcard,
121 IpCidr { addr: IpAddr, prefix_len: u8 },
123 IpExact { addr: IpAddr, port: Option<u16> },
125 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 host_lower.ends_with(&format!(".{}", name))
169 } else {
170 host_lower == *name || host_lower.ends_with(&format!(".{}", name))
173 }
174 } else {
175 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
203fn 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 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 let (host_str, port) = split_host_port(entry);
222
223 if let Ok(addr) = host_str.parse::<IpAddr>() {
225 return Some(NoProxyEntry::IpExact { addr, port });
226 }
227
228 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
241fn split_host_port(s: &str) -> (&str, Option<u16>) {
246 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 if s.chars().filter(|&c| c == ':').count() > 1 {
259 return (s, None);
260 }
261 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
270fn 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 _ => 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 #[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 #[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 #[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 #[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 #[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 #[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 let m = matcher(&[".example.com"], false);
471 assert!(!m.matches("sub.example.com", None));
472 assert!(!m.matches("example.com", None));
473 }
474
475 #[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 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 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 assert_eq!(proxies.len(), 1);
524 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 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 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 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 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 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 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 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 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 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 let _ = client.send(req).await;
681
682 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 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 let _ = client.send(req).await;
720
721 assert!(
723 rx.try_recv().is_err(),
724 "proxy should not have been contacted for a no_proxy host"
725 );
726 }
727}