返回 CodeWhale
proxy.rs
根目录 / crates / net / src / proxy.rs
1 use anyhow::Result;
2 use std::io::ErrorKind;
3 use std::net::{TcpStream, ToSocketAddrs};
4 use std::sync::Arc;
5 use std::sync::OnceLock;
6 use std::sync::atomic::{AtomicBool, Ordering};
7 use std::time::Duration;
8
9 /// How long the probe waits between checks once one finishes.
10 const LOOPBACK_PROXY_PROBE_INTERVAL: Duration = Duration::from_secs(2);
11 /// Upper bound for one loopback TCP probe. Windows only reports a refused
12 /// loopback connection after roughly two seconds, so a shorter bound would
13 /// turn every closed port into an inconclusive timeout and the fallback would
14 /// never engage.
15 const LOOPBACK_PROXY_PROBE_TIMEOUT: Duration = Duration::from_secs(4);
16 /// Keeps reqwest's snapshot behaviour when set to `0`.
17 const LOOPBACK_PROXY_FALLBACK_ENV: &str = "CODEWHALE_LOCAL_PROXY_FALLBACK";
18
19 /// Redact userinfo and omit paths, queries, and fragments from proxy log labels.
20 fn redact_proxy_userinfo(proxy_url: &str) -> String {
21 let Some(scheme_end) = proxy_url.find("://") else {
22 return "<invalid proxy URL>".to_string();
23 };
24 let after_scheme = scheme_end + 3;
25 let rest = &proxy_url[after_scheme..];
26 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
27 if let Some((_, host)) = authority.rsplit_once('@') {
28 format!("{}***@{host}", &proxy_url[..after_scheme])
29 } else {
30 format!("{}{authority}", &proxy_url[..after_scheme])
31 }
32 }
33
34 /// Install the loopback proxy fallback on a client builder.
35 ///
36 /// `no_proxy()` clears every proxy registered before it, so it must come first:
37 /// afterwards the fallback route is the only proxy source, and a request the
38 /// callback declines cannot fall back to the dead address reqwest reads when the
39 /// client is built.
40 pub fn install_loopback_proxy(builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
41 install_proxy_route(builder, loopback_proxy_fallback())
42 }
43
44 /// `no_proxy()` clears every proxy registered before it, so the route must be
45 /// installed after it. Getting this backwards leaves a builder with no proxies
46 /// at all, which looks like the fix works until the proxy is up again.
47 fn install_proxy_route(
48 builder: reqwest::ClientBuilder,
49 proxy: Option<reqwest::Proxy>,
50 ) -> reqwest::ClientBuilder {
51 let Some(proxy) = proxy else {
52 return builder;
53 };
54 builder.no_proxy().proxy(proxy)
55 }
56
57 /// Route through the ambient loopback proxy while it answers and go direct
58 /// while its port refuses connections.
59 ///
60 /// A long-lived session builds its reqwest clients once, and reqwest snapshots
61 /// `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` when the client is built. A local
62 /// proxy process (Clash, v2rayN, sing-box) that closes after startup would then
63 /// keep every request dialing a dead loopback port until the process restarts —
64 /// including providers that need no proxy at all. Return a proxy that is
65 /// re-probed in the background and bypasses the proxy while it is down.
66 ///
67 /// The proxy environment is read once, on the first client this process builds;
68 /// changing `HTTPS_PROXY` afterwards needs a restart. That matches how reqwest
69 /// already snapshots the environment at build time, and it keeps one probe
70 /// thread for the process instead of one per client.
71 ///
72 /// Each configured proxy is watched on its own port, so a live `HTTP_PROXY` does
73 /// not keep a dead `HTTPS_PROXY` in the path.
74 ///
75 /// Only a definite `ECONNREFUSED` moves routing to direct. A probe that times
76 /// out, hits an fd limit or cannot resolve says nothing about the proxy, so the
77 /// previous state stands: routing the session direct on that evidence would put
78 /// traffic on a network path the operator deliberately avoided.
79 ///
80 /// Known limitations: only loopback proxies are watched, and reachability is a
81 /// TCP connect rather than a proxy handshake, so a process that accepts the
82 /// port without forwarding traffic still counts as up. An unreachable remote
83 /// proxy is a network outage to report, not a boundary to route around, so
84 /// those keep reqwest's own behaviour.
85 ///
86 /// Set `CODEWHALE_LOCAL_PROXY_FALLBACK=0` to keep reqwest's snapshot behaviour.
87 ///
88 /// Returns `None` when no ambient proxy is configured, when none of them is
89 /// loopback, when no configured proxy is parseable, or when the fallback is
90 /// disabled; callers then leave the client builder untouched. An unparseable
91 /// variable next to a usable one is ignored rather than fatal. `new()` also
92 /// declines a request whose CGI environment marks the variables as request data,
93 /// and declines any configuration `NO_PROXY` disables outright.
94 pub fn loopback_proxy_fallback() -> Option<reqwest::Proxy> {
95 let watch = ambient_loopback_proxy()?;
96 Some(reqwest::Proxy::custom(move |url| watch.route(url)))
97 }
98
99 /// One probe thread per process, shared by every client built afterwards, so a
100 /// client rebuilt on a route change does not add another thread or another
101 /// connect every two seconds. The environment is consequently read once.
102 fn ambient_loopback_proxy() -> Option<Arc<LoopbackProxy>> {
103 static WATCH: OnceLock<Option<Arc<LoopbackProxy>>> = OnceLock::new();
104 WATCH
105 .get_or_init(|| {
106 let watch = LoopbackProxy::from_environment()?;
107 spawn_probe(&watch);
108 Some(watch)
109 })
110 .clone()
111 }
112
113 /// Ambient proxy routing plus the reachability of every loopback proxy target
114 /// it can select.
115 struct LoopbackProxy {
116 matcher: hyper_util::client::proxy::matcher::Matcher,
117 all: Option<reqwest::Url>,
118 http: Option<reqwest::Url>,
119 https: Option<reqwest::Url>,
120 targets: Vec<LoopbackTarget>,
121 }
122
123 struct LoopbackTarget {
124 host: String,
125 port: u16,
126 /// The configured URL that selects this target, kept for the one warning
127 /// that names the proxy that stopped answering.
128 configured: String,
129 /// Starts false: no probe has said this port is gone yet, so requests keep
130 /// reqwest's behaviour. Only a definite refusal sets it.
131 refused: AtomicBool,
132 }
133
134 enum Reachability {
135 /// At least one address accepted the connection.
136 Open,
137 /// Every address actively refused it: nothing is listening.
138 Refused,
139 /// Timeout, fd or resolver trouble. Not evidence about the proxy.
140 Unknown,
141 }
142
143 impl LoopbackProxy {
144 fn from_environment() -> Option<Arc<Self>> {
145 // A CGI request's HTTP_PROXY is request data, not proxy configuration.
146 if std::env::var_os("REQUEST_METHOD").is_some() {
147 return None;
148 }
149 if std::env::var(LOOPBACK_PROXY_FALLBACK_ENV).is_ok_and(|value| value.trim() == "0") {
150 return None;
151 }
152 let all = ambient_proxy_url(&["ALL_PROXY", "all_proxy"]);
153 let http = ambient_proxy_url(&["HTTP_PROXY", "http_proxy"]);
154 let https = ambient_proxy_url(&["HTTPS_PROXY", "https_proxy"]);
155 Self::new(all, http, https, &read_no_proxy())
156 }
157
158 /// Build the router for an explicit proxy configuration. `None` when there
159 /// is nothing to watch, when none of the configured proxies is loopback,
160 /// when a loopback proxy's port cannot be determined, or when `NO_PROXY`
161 /// disables proxying altogether. A remote proxy next to a loopback one is
162 /// simply never watched.
163 fn new(
164 all: Option<reqwest::Url>,
165 http: Option<reqwest::Url>,
166 https: Option<reqwest::Url>,
167 no_proxy: &str,
168 ) -> Option<Arc<Self>> {
169 let configured: Vec<&reqwest::Url> = [all.as_ref(), http.as_ref(), https.as_ref()]
170 .into_iter()
171 .flatten()
172 .collect();
173 if configured.is_empty() {
174 return None;
175 }
176 // Watch only the loopback proxies. A remote proxy in the same
177 // configuration keeps reqwest's behaviour: it is never marked down, so
178 // traffic to it never diverts, and a local proxy next to it is still
179 // watched on its own.
180 let mut targets: Vec<LoopbackTarget> = Vec::new();
181 for url in configured {
182 let Some((host, port)) = loopback_target(url) else {
183 // A loopback proxy whose port cannot be determined is a
184 // misconfiguration, not a reason to quietly stop watching it.
185 if is_loopback_url(url) {
186 tracing::warn!(
187 target: "net",
188 proxy = %redact_proxy_userinfo(url.as_str()),
189 "cannot determine this local proxy's port; leaving proxy routing to reqwest"
190 );
191 return None;
192 }
193 continue;
194 };
195 let known = targets
196 .iter()
197 .any(|target| target.host == host && target.port == port);
198 if !known {
199 targets.push(LoopbackTarget {
200 host,
201 port,
202 configured: url.to_string(),
203 refused: AtomicBool::new(false),
204 });
205 }
206 }
207 if targets.is_empty() {
208 return None;
209 }
210 if no_proxy_disables_all(no_proxy) {
211 return None;
212 }
213 let mut builder = hyper_util::client::proxy::matcher::Matcher::builder();
214 if let Some(url) = &all {
215 builder = builder.all(url.as_str());
216 }
217 if let Some(url) = &http {
218 builder = builder.http(url.as_str());
219 }
220 if let Some(url) = &https {
221 builder = builder.https(url.as_str());
222 }
223 let matcher = builder.no(normalize_no_proxy(no_proxy)).build();
224
225 Some(Arc::new(Self {
226 matcher,
227 all,
228 http,
229 https,
230 targets,
231 }))
232 }
233
234 fn route(&self, url: &reqwest::Url) -> Option<reqwest::Url> {
235 // Only ask the matcher whether this destination is proxied (scheme plus
236 // NO_PROXY). The route itself comes from the configured URL so proxy
237 // credentials survive; the matcher strips userinfo into an auth header.
238 let port = url
239 .port()
240 .map(|port| format!(":{port}"))
241 .unwrap_or_default();
242 let destination: http::Uri = format!("{}://{}{}", url.scheme(), url.host_str()?, port)
243 .parse()
244 .ok()?;
245 self.matcher.intercept(&destination)?;
246 let source = match url.scheme() {
247 "http" => self.http.as_ref().or(self.all.as_ref()),
248 "https" => self.https.as_ref().or(self.all.as_ref()),
249 _ => None,
250 }?;
251 // Reachability is per proxy, not per watcher: with HTTP_PROXY up and
252 // HTTPS_PROXY down, only the https route may go direct. Every watched
253 // target is registered from the same URL the matcher selects, so an
254 // unregistered source is a remote proxy, which is never watched.
255 match self.target_for(source) {
256 Some(target) if target.refused.load(Ordering::Relaxed) => return None,
257 Some(_) | None => {}
258 }
259 let mut target = source.clone();
260 // Remote DNS stays with the proxy, exactly as configured_mcp_proxy
261 // keeps it for the same proxy URL.
262 let scheme = match target.scheme() {
263 "socks5" => Some("socks5h"),
264 "socks4" => Some("socks4a"),
265 _ => None,
266 };
267 if let Some(scheme) = scheme {
268 target.set_scheme(scheme).ok()?;
269 }
270 Some(target)
271 }
272
273 /// The watched target behind a configured proxy URL, matched on the same
274 /// host and port the probe uses.
275 fn target_for(&self, source: &reqwest::Url) -> Option<&LoopbackTarget> {
276 let (host, port) = loopback_target(source)?;
277 self.targets
278 .iter()
279 .find(|target| target.host == host && target.port == port)
280 }
281
282 fn refresh(&self) {
283 for target in &self.targets {
284 let reachability = probe_target(target);
285 let was_refused = target.refused.load(Ordering::Relaxed);
286 let refused = match reachability {
287 // A timeout or an fd limit says nothing about the proxy, so the
288 // last definite answer stands.
289 Reachability::Unknown => was_refused,
290 Reachability::Open => false,
291 Reachability::Refused => true,
292 };
293 if was_refused == refused {
294 continue;
295 }
296 target.refused.store(refused, Ordering::Relaxed);
297 if refused {
298 tracing::warn!(
299 target: "net",
300 proxy = %redact_proxy_userinfo(&target.configured),
301 "local proxy refused connections; requests go direct until it returns"
302 );
303 } else {
304 tracing::info!(
305 target: "net",
306 proxy = %redact_proxy_userinfo(&target.configured),
307 "local proxy is reachable again; resuming proxy routing"
308 );
309 }
310 }
311 }
312 }
313
314 fn spawn_probe(watch: &Arc<LoopbackProxy>) {
315 // A Weak probe handle keeps the thread from owning the router. The process
316 // keeps one watch in a static, so this normally never expires; a probe that
317 // stops instead of pinning a watcher is the safer default if that changes.
318 let weak = Arc::downgrade(watch);
319 let spawned = std::thread::Builder::new()
320 .name("codewhale-proxy-probe".to_string())
321 .spawn(move || {
322 loop {
323 // Probe first, then rest: one check may take seconds, and
324 // sleeping between checks would put two probes back to back.
325 let Some(watch) = weak.upgrade() else {
326 return;
327 };
328 watch.refresh();
329 drop(watch);
330 std::thread::sleep(LOOPBACK_PROXY_PROBE_INTERVAL);
331 }
332 });
333 if let Err(error) = spawned {
334 tracing::warn!(
335 target: "net",
336 %error,
337 "could not start the local proxy probe thread"
338 );
339 }
340 }
341
342 fn probe_target(target: &LoopbackTarget) -> Reachability {
343 let Ok(addresses) = (target.host.as_str(), target.port).to_socket_addrs() else {
344 return Reachability::Unknown;
345 };
346 // Only a refusal from every resolved address is evidence the port is gone.
347 // `localhost` resolving to `::1` (refused) and `127.0.0.1` (dropped) is the
348 // shape of "cannot tell", not the shape of "nothing is listening".
349 let mut resolved = 0_u32;
350 let mut refusals = 0_u32;
351 for address in addresses {
352 resolved += 1;
353 match TcpStream::connect_timeout(&address, LOOPBACK_PROXY_PROBE_TIMEOUT) {
354 Ok(_) => return Reachability::Open,
355 Err(error) if error.kind() == ErrorKind::ConnectionRefused => refusals += 1,
356 Err(_) => {}
357 }
358 }
359 if resolved > 0 && refusals == resolved {
360 Reachability::Refused
361 } else {
362 Reachability::Unknown
363 }
364 }
365
366 /// `NO_PROXY` entries separated by whitespace mean the same as comma-separated
367 /// ones, and every Rust proxy path in this process reads the list this way so a
368 /// value cannot mean "direct" to one subsystem and "proxied" to another. Child
369 /// processes still inherit the variable verbatim.
370 fn normalize_no_proxy(raw: &str) -> String {
371 raw.replace(char::is_whitespace, ",")
372 }
373
374 fn no_proxy_disables_all(no_proxy: &str) -> bool {
375 normalize_no_proxy(no_proxy)
376 .split(',')
377 .any(|entry| entry == "*")
378 }
379
380 fn read_no_proxy() -> String {
381 std::env::var("NO_PROXY")
382 .or_else(|_| std::env::var("no_proxy"))
383 .unwrap_or_default()
384 }
385
386 fn ambient_proxy_url(names: &[&str]) -> Option<reqwest::Url> {
387 let raw = names.iter().find_map(|name| {
388 std::env::var(name)
389 .ok()
390 .filter(|value| !value.trim().is_empty())
391 })?;
392 reqwest::Url::parse(&raw)
393 .ok()
394 .filter(|url| url.has_host())
395 .or_else(|| {
396 reqwest::Url::parse(&format!("http://{raw}"))
397 .ok()
398 .filter(|url| url.has_host())
399 })
400 }
401
402 /// The bare loopback address behind a proxy URL's host, or `None` when it is
403 /// not loopback. `Url::host_str` returns an IPv6 literal with its brackets
404 /// (`[::1]`), so the brackets come off before the address is parsed and before
405 /// the host is stored for a probe.
406 fn loopback_host(url: &reqwest::Url) -> Option<String> {
407 let host = url.host_str()?;
408 let unbracketed = host
409 .strip_prefix('[')
410 .and_then(|rest| rest.strip_suffix(']'))
411 .unwrap_or(host);
412 if unbracketed.eq_ignore_ascii_case("localhost") {
413 return Some(unbracketed.to_string());
414 }
415 unbracketed
416 .parse::<std::net::IpAddr>()
417 .ok()
418 .filter(is_loopback_address)
419 .map(|address| address.to_string())
420 }
421
422 /// `Ipv6Addr::is_loopback` only accepts `::1`, so an IPv4-mapped local proxy
423 /// (`[::ffff:127.0.0.1]`) is unwrapped before the check. It is the same host
424 /// with a different spelling, and a proxy bound that way is still local.
425 fn is_loopback_address(address: &std::net::IpAddr) -> bool {
426 match address {
427 std::net::IpAddr::V4(v4) => v4.is_loopback(),
428 std::net::IpAddr::V6(v6) => {
429 v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
430 }
431 }
432 }
433
434 fn is_loopback_url(url: &reqwest::Url) -> bool {
435 loopback_host(url).is_some()
436 }
437
438 fn loopback_target(url: &reqwest::Url) -> Option<(String, u16)> {
439 let host = loopback_host(url)?;
440 // reqwest defaults a portless socks proxy to 1080; matching that here keeps
441 // `ALL_PROXY=socks5://127.0.0.1` watched instead of silently unwatched.
442 let port = url.port_or_known_default().or(match url.scheme() {
443 "socks4" | "socks4a" | "socks5" | "socks5h" => Some(1080),
444 _ => None,
445 })?;
446 Some((host, port))
447 }
448
449 /// Resolve the operator's proxy route for this exact request using the same
450 /// matcher as reqwest. A NO_PROXY match returns None: direct requests must keep
451 /// their public DNS validation and pins. Model and reviewed-plugin requests
452 /// return before even reading proxy credentials.
453 pub fn configured_mcp_proxy<F>(
454 url: &reqwest::Url,
455 disallow_ambient_proxy: bool,
456 mut read_environment: F,
457 ) -> Result<Option<reqwest::Proxy>>
458 where
459 F: FnMut(&str) -> std::result::Result<String, std::env::VarError>,
460 {
461 if disallow_ambient_proxy {
462 return Ok(None);
463 }
464 let env_keys: &[&str] = match url.scheme() {
465 "https" => &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
466 "http" => &["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"],
467 _ => &["ALL_PROXY", "all_proxy"],
468 };
469 let proxy_url = env_keys.iter().find_map(|key| {
470 read_environment(key)
471 .ok()
472 .filter(|value| !value.trim().is_empty())
473 });
474 let Some(proxy_url) = proxy_url else {
475 return Ok(None);
476 };
477 // Normalize userinfo and Unicode with the URL parser before passing the
478 // URL to reqwest's own underlying matcher. Keep its missing-scheme support.
479 let normalized = reqwest::Url::parse(&proxy_url)
480 .ok()
481 .filter(|url| url.has_host())
482 .or_else(|| reqwest::Url::parse(&format!("http://{proxy_url}")).ok());
483 let Some(normalized) = normalized else {
484 tracing::warn!(target: "mcp", "ignoring malformed HTTP(S)_PROXY URL");
485 return Ok(None);
486 };
487 let no_proxy = normalize_no_proxy(
488 &read_environment("NO_PROXY")
489 .or_else(|_| read_environment("no_proxy"))
490 .unwrap_or_default(),
491 );
492 if no_proxy_disables_all(&no_proxy) {
493 return Ok(None);
494 }
495 let matcher = hyper_util::client::proxy::matcher::Matcher::builder()
496 .all(normalized.as_str())
497 .no(no_proxy)
498 .build();
499 let Some(host) = url.host_str() else {
500 return Ok(None);
501 };
502 let port = url
503 .port()
504 .map(|port| format!(":{port}"))
505 .unwrap_or_default();
506 let destination: http::Uri = format!("{}://{}{}", url.scheme(), host, port).parse()?;
507 let Some(route) = matcher.intercept(&destination) else {
508 return Ok(None);
509 };
510 // Build the actual proxy from the matched route itself so the decision
511 // that grants delegated DNS authority cannot diverge from the transport.
512 let route_uri = route.uri().to_string();
513 let route_uri = match route.uri().scheme_str() {
514 Some("socks5") => route_uri.replacen("socks5://", "socks5h://", 1),
515 Some("socks4") => route_uri.replacen("socks4://", "socks4a://", 1),
516 _ => route_uri,
517 };
518 let mut proxy = reqwest::Proxy::all(route_uri)?;
519 if let Some(auth) = route.basic_auth() {
520 proxy = proxy.custom_http_auth(auth.clone());
521 }
522 if let Some((user, password)) = route.raw_auth() {
523 proxy = proxy.basic_auth(user, password);
524 }
525 Ok(Some(proxy))
526 }
527
528 #[cfg(test)]
529 mod tests {
530 use super::*;
531 use std::io::{Read, Write};
532 use std::net::TcpListener;
533
534 fn loopback_listener() -> TcpListener {
535 TcpListener::bind("127.0.0.1:0").expect("bind loopback proxy")
536 }
537
538 fn port_of(listener: &TcpListener) -> u16 {
539 listener.local_addr().expect("loopback address").port()
540 }
541
542 /// A port that was bound and released, so nothing answers it. The window
543 /// before the OS reuses the port only has to outlast one probe.
544 fn closed_port() -> u16 {
545 let listener = loopback_listener();
546 let port = port_of(&listener);
547 drop(listener);
548 port
549 }
550
551 fn proxy_url(port: u16) -> reqwest::Url {
552 reqwest::Url::parse(&format!("http://127.0.0.1:{port}")).expect("proxy url")
553 }
554
555 fn engine_target() -> reqwest::Url {
556 reqwest::Url::parse("https://api.deepseek.com/v1/chat/completions").unwrap()
557 }
558
559 fn watch(https_port: u16) -> Arc<LoopbackProxy> {
560 LoopbackProxy::new(None, None, Some(proxy_url(https_port)), "")
561 .expect("loopback proxy is watched")
562 }
563
564 /// A byte-for-byte HTTP server that answers every request with `200 ok`.
565 fn spawn_target_server() -> (u16, std::thread::JoinHandle<()>) {
566 let listener = loopback_listener();
567 let port = port_of(&listener);
568 let handle = std::thread::spawn(move || {
569 for stream in listener.incoming() {
570 let Ok(mut stream) = stream else { return };
571 let mut buffer = [0u8; 2048];
572 let _ = stream.read(&mut buffer);
573 let _ = stream.write_all(
574 b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
575 );
576 }
577 });
578 (port, handle)
579 }
580
581 /// A server that answers like a proxy refusing to forward: `502`.
582 fn spawn_refusing_proxy() -> (u16, std::thread::JoinHandle<()>) {
583 let listener = loopback_listener();
584 let port = port_of(&listener);
585 let handle = std::thread::spawn(move || {
586 for stream in listener.incoming() {
587 let Ok(mut stream) = stream else { return };
588 let mut buffer = [0u8; 2048];
589 let _ = stream.read(&mut buffer);
590 let _ = stream.write_all(
591 b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
592 );
593 }
594 });
595 (port, handle)
596 }
597
598 #[test]
599 fn a_portless_socks_proxy_defaults_to_1080() {
600 let socks = reqwest::Url::parse("socks5://127.0.0.1").unwrap();
601
602 let watch = LoopbackProxy::new(Some(socks), None, None, "").expect("watched");
603
604 assert_eq!(watch.targets[0].port, 1080);
605 }
606
607 /// A socks5 route keeps remote DNS: building the matcher for that scheme
608 /// must not panic, and the returned route must name socks5h so the proxy
609 /// resolves the hostname rather than the client.
610 #[test]
611 fn a_socks5_proxy_route_keeps_remote_dns() {
612 let listener = loopback_listener();
613 let port = port_of(&listener);
614 let socks = reqwest::Url::parse(&format!("socks5://127.0.0.1:{port}")).unwrap();
615 let watch = LoopbackProxy::new(Some(socks), None, None, "").expect("watched");
616
617 let route = watch.route(&engine_target()).expect("socks route");
618
619 assert_eq!(route.scheme(), "socks5h");
620 assert_eq!(route.port(), Some(port));
621 drop(listener);
622 }
623
624 #[test]
625 fn each_proxy_is_watched_separately() {
626 let http_listener = loopback_listener();
627 let http_port = port_of(&http_listener);
628 let dead_https = closed_port();
629 let watch = LoopbackProxy::new(
630 None,
631 Some(proxy_url(http_port)),
632 Some(proxy_url(dead_https)),
633 "",
634 )
635 .expect("watched");
636
637 watch.refresh();
638
639 let http_target = reqwest::Url::parse("http://example.com/").unwrap();
640 let https_target = reqwest::Url::parse("https://example.com/").unwrap();
641 assert!(
642 watch.route(&http_target).is_some(),
643 "a live http proxy must keep routing"
644 );
645 assert!(
646 watch.route(&https_target).is_none(),
647 "a dead https proxy must not swallow https traffic"
648 );
649 drop(http_listener);
650 }
651
652 /// Proves the install order: with a live proxy the request must reach the
653 /// proxy (502), not the target (200). Installing `no_proxy()` after
654 /// `proxy()` would clear the route and let the request go direct.
655 ///
656 /// Coverage boundary: this pins the order, not the presence of
657 /// `no_proxy()`. Dropping that call would leave reqwest's ambient matcher in
658 /// place, which is only observable when the process environment carries a
659 /// proxy — and mutating the process environment from a test is what this
660 /// suite stopped doing.
661 #[tokio::test]
662 async fn the_route_is_installed_after_the_proxy_list_is_cleared() {
663 let (target_port, target) = spawn_target_server();
664 let (proxy_port, refusing) = spawn_refusing_proxy();
665 let watch =
666 LoopbackProxy::new(Some(proxy_url(proxy_port)), None, None, "").expect("watched");
667 let route = reqwest::Proxy::custom({
668 let watch = Arc::clone(&watch);
669 move |url| watch.route(url)
670 });
671 let client = install_proxy_route(
672 codewhale_release::tls::reqwest_client_builder(),
673 Some(route),
674 )
675 .timeout(Duration::from_secs(5))
676 .build()
677 .expect("client");
678
679 let response = client
680 .get(format!("http://127.0.0.1:{target_port}/"))
681 .send()
682 .await
683 .expect("request");
684
685 assert_eq!(
686 response.status(),
687 502,
688 "the request must reach the proxy, not the target"
689 );
690 drop(target);
691 drop(refusing);
692 }
693
694 #[test]
695 fn no_configured_proxy_is_not_watched() {
696 assert!(LoopbackProxy::new(None, None, None, "").is_none());
697 }
698
699 #[test]
700 fn remote_proxy_is_not_watched() {
701 let remote = reqwest::Url::parse("http://proxy.example.test:8080").unwrap();
702
703 assert!(
704 LoopbackProxy::new(None, None, Some(remote), "").is_none(),
705 "a remote proxy's outage is a network outage, not a routing decision"
706 );
707 }
708
709 #[test]
710 fn a_remote_proxy_in_a_mixed_configuration_leaves_the_local_one_watched() {
711 let local_listener = loopback_listener();
712 let local_port = port_of(&local_listener);
713 let remote = reqwest::Url::parse("http://proxy.example.test:8080").unwrap();
714
715 let watch = LoopbackProxy::new(None, Some(proxy_url(local_port)), Some(remote), "")
716 .expect("the local proxy is still watched");
717
718 watch.refresh();
719
720 assert_eq!(watch.targets.len(), 1, "only loopback proxies are probed");
721 let http_target = reqwest::Url::parse("http://example.com/").unwrap();
722 let https_target = reqwest::Url::parse("https://example.com/").unwrap();
723 assert!(
724 watch.route(&http_target).is_some(),
725 "the live local http proxy keeps routing"
726 );
727 assert_eq!(
728 watch.route(&https_target).map(|url| url.to_string()),
729 Some("http://proxy.example.test:8080/".to_string()),
730 "a remote proxy is routed through, never watched"
731 );
732 drop(local_listener);
733 }
734
735 #[test]
736 fn ipv6_loopback_is_watched() {
737 // Skipped rather than failed on a host with IPv6 disabled: the feature
738 // under test needs a local IPv6 listener to probe.
739 let listener = match TcpListener::bind("[::1]:0") {
740 Ok(listener) => listener,
741 Err(_) => return,
742 };
743 let port = port_of(&listener);
744 let url = reqwest::Url::parse(&format!("http://[::1]:{port}")).expect("ipv6 url");
745
746 let watch = LoopbackProxy::new(None, None, Some(url), "").expect("watched");
747
748 assert_eq!(watch.targets[0].host, "::1");
749 assert_eq!(watch.targets[0].port, port);
750 let route = watch.route(&engine_target()).expect("proxy route");
751 assert_eq!(
752 route.host_str(),
753 Some("[::1]"),
754 "reqwest needs the brackets"
755 );
756 drop(listener);
757 }
758
759 /// The route a request takes must agree with the matcher's decision and with
760 /// the documented variable precedence. With `ALL_PROXY`, `HTTP_PROXY` and
761 /// `HTTPS_PROXY` on three live ports, each scheme follows its own variable
762 /// and `ALL_PROXY` is only the fallback.
763 #[test]
764 fn the_route_follows_the_same_precedence_as_the_matcher() {
765 let all_listener = loopback_listener();
766 let all_port = port_of(&all_listener);
767 let http_listener = loopback_listener();
768 let http_port = port_of(&http_listener);
769 let https_listener = loopback_listener();
770 let https_port = port_of(&https_listener);
771 let watch = LoopbackProxy::new(
772 Some(proxy_url(all_port)),
773 Some(proxy_url(http_port)),
774 Some(proxy_url(https_port)),
775 "",
776 )
777 .expect("watched");
778
779 let http_route = watch
780 .route(&reqwest::Url::parse("http://example.com/").unwrap())
781 .expect("http route");
782 let https_route = watch
783 .route(&reqwest::Url::parse("https://example.com/").unwrap())
784 .expect("https route");
785
786 assert_eq!(
787 http_route.port(),
788 Some(http_port),
789 "HTTP_PROXY outranks ALL_PROXY"
790 );
791 assert_eq!(
792 https_route.port(),
793 Some(https_port),
794 "HTTPS_PROXY outranks ALL_PROXY"
795 );
796 drop(all_listener);
797 drop(http_listener);
798 drop(https_listener);
799 }
800
801 /// `ALL_PROXY` alone still covers both schemes.
802 #[test]
803 fn all_proxy_alone_covers_both_schemes() {
804 let all_listener = loopback_listener();
805 let all_port = port_of(&all_listener);
806 let watch = LoopbackProxy::new(Some(proxy_url(all_port)), None, None, "").expect("watched");
807
808 for target in ["http://example.com/", "https://example.com/"] {
809 let route = watch
810 .route(&reqwest::Url::parse(target).unwrap())
811 .expect("route from ALL_PROXY");
812 assert_eq!(route.port(), Some(all_port));
813 }
814 drop(all_listener);
815 }
816
817 /// With an https proxy configured and no http one, a plain-http target must
818 /// go direct: `HTTPS_PROXY` does not proxy http destinations, and nothing
819 /// else may quietly stand in for it.
820 #[test]
821 fn an_https_only_proxy_leaves_http_targets_direct() {
822 let https_listener = loopback_listener();
823 let https_port = port_of(&https_listener);
824 let watch =
825 LoopbackProxy::new(None, None, Some(proxy_url(https_port)), "").expect("watched");
826
827 assert!(
828 watch
829 .route(&reqwest::Url::parse("http://example.com/").unwrap())
830 .is_none(),
831 "HTTPS_PROXY must not intercept http destinations"
832 );
833 assert_eq!(
834 watch
835 .route(&reqwest::Url::parse("https://example.com/").unwrap())
836 .expect("https route")
837 .port(),
838 Some(https_port)
839 );
840 drop(https_listener);
841 }
842
843 /// `[::ffff:127.0.0.1]` is the same local host spelled as IPv6, and
844 /// `Ipv6Addr::is_loopback` alone would call it remote.
845 #[test]
846 fn an_ipv4_mapped_ipv6_loopback_is_watched() {
847 let url = reqwest::Url::parse("http://[::ffff:127.0.0.1]:7890").expect("url");
848
849 let watch = LoopbackProxy::new(None, None, Some(url), "").expect("watched");
850
851 assert_eq!(watch.targets[0].port, 7890);
852 }
853
854 #[test]
855 fn no_proxy_star_disables_the_watcher() {
856 let local = proxy_url(closed_port());
857
858 assert!(LoopbackProxy::new(None, None, Some(local), "*").is_none());
859 }
860
861 #[test]
862 fn whitespace_separated_no_proxy_entries_match_commas() {
863 assert_eq!(
864 normalize_no_proxy("api.deepseek.com other.example"),
865 "api.deepseek.com,other.example"
866 );
867 assert_eq!(
868 normalize_no_proxy(" a.example,\n b.example "),
869 ",a.example,,,b.example,"
870 );
871 assert!(no_proxy_disables_all("a.example *"));
872 assert!(!no_proxy_disables_all("a.example"));
873 }
874
875 #[test]
876 fn answering_loopback_port_keeps_proxy_routing() {
877 let listener = loopback_listener();
878 let port = port_of(&listener);
879 let watch = watch(port);
880
881 let route = watch.route(&engine_target()).expect("proxy route");
882
883 assert_eq!(route.host_str(), Some("127.0.0.1"));
884 assert_eq!(route.port(), Some(port));
885 drop(listener);
886 }
887
888 #[test]
889 fn loopback_proxy_credentials_survive_the_route() {
890 let listener = loopback_listener();
891 let port = port_of(&listener);
892 let url = reqwest::Url::parse(&format!(
893 "http://placeholder-user:placeholder-pass@127.0.0.1:{port}"
894 ))
895 .unwrap();
896 let watch = LoopbackProxy::new(None, None, Some(url), "").expect("watched");
897
898 let route = watch.route(&engine_target()).expect("proxy route");
899
900 assert_eq!(route.username(), "placeholder-user");
901 assert_eq!(route.password(), Some("placeholder-pass"));
902 drop(listener);
903 }
904
905 #[test]
906 fn no_proxy_hosts_bypass_the_watched_proxy() {
907 let listener = loopback_listener();
908 let port = port_of(&listener);
909 let url = proxy_url(port);
910 let watch = LoopbackProxy::new(None, None, Some(url), "api.deepseek.com").expect("watched");
911
912 assert!(
913 watch.route(&engine_target()).is_none(),
914 "NO_PROXY must keep winning while the proxy is up"
915 );
916 drop(listener);
917 }
918
919 #[test]
920 fn a_refused_port_moves_routing_to_direct() {
921 let watch = watch(closed_port());
922 assert!(
923 watch.route(&engine_target()).is_some(),
924 "an unprobed proxy keeps reqwest's behaviour"
925 );
926
927 watch.refresh();
928
929 assert!(
930 watch.route(&engine_target()).is_none(),
931 "a refused port must stop intercepting requests"
932 );
933 }
934
935 #[test]
936 fn a_returning_port_moves_routing_back_to_the_proxy() {
937 let listener = loopback_listener();
938 let port = port_of(&listener);
939 let watch = watch(port);
940 drop(listener);
941 watch.refresh();
942 assert!(watch.route(&engine_target()).is_none(), "proxy is gone");
943
944 let listener = TcpListener::bind(("127.0.0.1", port)).expect("rebind proxy port");
945 watch.refresh();
946
947 assert!(
948 watch.route(&engine_target()).is_some(),
949 "a answering port must restore proxy routing"
950 );
951 drop(listener);
952 }
953
954 /// End to end over a real client: while the configured proxy refuses
955 /// connections the request must reach the target directly, and while it
956 /// answers the request must go to the proxy instead.
957 #[tokio::test]
958 async fn a_closed_proxy_no_longer_blocks_the_request() {
959 let (target_port, target) = spawn_target_server();
960 let target_url = format!("http://127.0.0.1:{target_port}/");
961 // ALL_PROXY so the plain-http target is proxied too; an HTTPS_PROXY
962 // entry deliberately does not intercept http destinations.
963 let watch = LoopbackProxy::new(Some(proxy_url(closed_port())), None, None, "")
964 .expect("watched loopback proxy");
965 let client = codewhale_release::tls::reqwest_client_builder()
966 .no_proxy()
967 .proxy(reqwest::Proxy::custom({
968 let watch = Arc::clone(&watch);
969 move |url| watch.route(url)
970 }))
971 .timeout(Duration::from_secs(5))
972 .build()
973 .expect("client");
974
975 assert!(
976 client.get(&target_url).send().await.is_err(),
977 "before a probe the dead proxy is still selected"
978 );
979
980 watch.refresh();
981 let response = client
982 .get(&target_url)
983 .send()
984 .await
985 .expect("direct request");
986
987 assert_eq!(response.status(), 200);
988 drop(target);
989 }
990
991 #[test]
992 fn reviewed_plugin_remote_proxy_policy_never_reads_ambient_environment() {
993 let reads = std::cell::Cell::new(0_u32);
994 let proxy = configured_mcp_proxy(
995 &reqwest::Url::parse("https://example.com/mcp").unwrap(),
996 true,
997 |_| {
998 reads.set(reads.get() + 1);
999 Ok("http://127.0.0.1:9999".to_string())
1000 },
1001 );
1002
1003 assert_eq!(
1004 reads.get(),
1005 0,
1006 "reviewed remotes must not read proxy values"
1007 );
1008 assert!(proxy.unwrap().is_none());
1009 }
1010
1011 #[test]
1012 fn user_authored_mcp_proxy_policy_keeps_environment_support() {
1013 let requested = std::cell::RefCell::new(Vec::new());
1014 let proxy = configured_mcp_proxy(
1015 &reqwest::Url::parse("https://example.com/mcp").unwrap(),
1016 false,
1017 |name| {
1018 requested.borrow_mut().push(name.to_string());
1019 match name {
1020 "HTTPS_PROXY" => Ok("http://127.0.0.1:8080".to_string()),
1021 _ => Err(std::env::VarError::NotPresent),
1022 }
1023 },
1024 );
1025
1026 assert_eq!(
1027 requested.into_inner(),
1028 vec![
1029 "HTTPS_PROXY".to_string(),
1030 "NO_PROXY".to_string(),
1031 "no_proxy".to_string(),
1032 ]
1033 );
1034 assert!(proxy.unwrap().is_some());
1035 }
1036
1037 #[test]
1038 fn redact_proxy_userinfo_strips_password() {
1039 // Corporate-style proxy URL with embedded creds — the
1040 // password must never reach the on-disk log file. URL strings
1041 // are assembled from placeholder constants via `format!` so the
1042 // literal source never contains a scheme-prefixed username +
1043 // password pair (colon-separated, `@`-terminated) that
1044 // GitGuardian's "Basic Auth String" detector would flag as a
1045 // committed credential.
1046 let (placeholder_user, placeholder_pass) = ("PLACEHOLDER_USER", "PLACEHOLDER_PASS");
1047 let with_creds = format!("http://{placeholder_user}:{placeholder_pass}@proxy.example/");
1048 let redacted = redact_proxy_userinfo(&with_creds);
1049 assert_eq!(redacted, "http://***@proxy.example");
1050 assert!(!redacted.contains(placeholder_pass));
1051 assert!(!redacted.contains(placeholder_user));
1052
1053 // User only (no password) — still redacted.
1054 let with_user_only = format!("https://{placeholder_user}@proxy.example:8080");
1055 let redacted = redact_proxy_userinfo(&with_user_only);
1056 assert_eq!(redacted, "https://***@proxy.example:8080");
1057
1058 let redacted = redact_proxy_userinfo("http://proxy.example:3128/");
1059 assert_eq!(redacted, "http://proxy.example:3128");
1060
1061 let redacted =
1062 redact_proxy_userinfo("http://proxy.example/path@thing?token=PLACEHOLDER#fragment");
1063 assert_eq!(redacted, "http://proxy.example");
1064
1065 assert_eq!(redact_proxy_userinfo("not-a-url"), "<invalid proxy URL>");
1066
1067 for host in [
1068 "ho st:8080",
1069 "proxy.example:port-not-a-number",
1070 "[::1:8080",
1071 "",
1072 ] {
1073 let malformed = format!("{placeholder_user}:{placeholder_pass}@{host}");
1074 let redacted = redact_proxy_userinfo(&malformed);
1075 assert_eq!(redacted, "<invalid proxy URL>", "{host:?}");
1076 assert!(!redacted.contains(placeholder_pass));
1077 }
1078 }
1079
1080 #[test]
1081 fn configured_mcp_proxy_respects_scheme_and_handles_url_fragments() {
1082 let https_with_fragment =
1083 reqwest::Url::parse("https://example.com/docs/page#section-1").unwrap();
1084 let proxy = configured_mcp_proxy(&https_with_fragment, false, |name| match name {
1085 "HTTPS_PROXY" => Ok("http://127.0.0.1:8443".to_string()),
1086 _ => Err(std::env::VarError::NotPresent),
1087 })
1088 .expect("fragment url must not fail uri parsing");
1089 assert!(proxy.is_some());
1090
1091 let http_target = reqwest::Url::parse("http://example.com/plain#top").unwrap();
1092 let https_only = configured_mcp_proxy(&http_target, false, |name| match name {
1093 "HTTPS_PROXY" => Ok("http://127.0.0.1:8443".to_string()),
1094 _ => Err(std::env::VarError::NotPresent),
1095 })
1096 .expect("http target with only HTTPS_PROXY");
1097 assert!(
1098 https_only.is_none(),
1099 "HTTPS_PROXY must not intercept plain http requests"
1100 );
1101
1102 let all_proxy = configured_mcp_proxy(&http_target, false, |name| match name {
1103 "ALL_PROXY" => Ok("socks5://127.0.0.1:1080".to_string()),
1104 _ => Err(std::env::VarError::NotPresent),
1105 })
1106 .expect("ALL_PROXY fallback");
1107 assert!(all_proxy.is_some());
1108 }
1109 }
1110
1110 lines RUST