Skip to main content

agentmux_srv_core/muxbus/
ws_connect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Opens a WebSocket like `connect_async_tls_with_config`, but through the
5//! HTTP proxy named by `HTTPS_PROXY` (`HTTP_PROXY` for `ws://`, then
6//! `ALL_PROXY`) when there is one, honouring `NO_PROXY`. The proxy only
7//! carries bytes: we send `CONNECT host:port`, and the TLS handshake then runs
8//! over the tunnel against the real host, so the server name and the
9//! certificate checks are the host's, never the proxy's. srv's HTTP clients
10//! read the same variables (reqwest); this makes the live MuxBus connection
11//! behave the same, and lets the fault proxy of `scripts/net-fault` take it
12//! down (SPEC_OFFLINE_RESILIENCE_2026_10_20.md ยง7.1).
13//!
14//! Fail closed: when a proxy is configured and cannot be used (its address is
15//! not `http://`, it refuses the CONNECT, it does not answer) the connect
16//! fails, as a connect that cannot reach the network does; it never goes
17//! direct. Credentials in the proxy address (`user:pass@`) are sent as
18//! `Proxy-Authorization` and never logged or put in an error.
19
20use std::io;
21use std::net::IpAddr;
22use std::time::Duration;
23
24use base64::Engine;
25use tokio::io::{AsyncReadExt, AsyncWriteExt};
26use tokio::net::TcpStream;
27use tokio_tungstenite::tungstenite::client::IntoClientRequest;
28use tokio_tungstenite::tungstenite::error::UrlError;
29use tokio_tungstenite::tungstenite::handshake::client::Response;
30use tokio_tungstenite::tungstenite::Error;
31use tokio_tungstenite::{client_async_tls_with_config, connect_async_tls_with_config, MaybeTlsStream, WebSocketStream};
32
33/// How long the proxy may take to answer the CONNECT.
34const PROXY_TIMEOUT: Duration = Duration::from_secs(15);
35/// The longest reply head accepted from a proxy.
36const MAX_REPLY_HEAD: usize = 16 * 1024;
37
38pub(crate) type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
39
40/// An `http://` proxy: where it listens and the `Proxy-Authorization` value, if its address held credentials.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct Proxy {
43    host: String,
44    port: u16,
45    authorization: Option<String>,
46}
47
48/// Parses a proxy address. Only `http://` is supported; the error never repeats the address, which may hold a password.
49pub(crate) fn parse_proxy(address: &str) -> Result<Proxy, String> {
50    const BAD: &str = "the proxy address must look like http://host:port";
51    let rest = address.trim();
52    let rest = match rest.get(..7) {
53        Some(scheme) if scheme.eq_ignore_ascii_case("http://") => &rest[7..],
54        _ => return Err("only http:// proxies are supported".to_string()),
55    };
56    let rest = rest.split(['/', '?', '#']).next().unwrap_or("");
57    let (userinfo, hostport) = match rest.rsplit_once('@') {
58        Some((u, h)) => (Some(u), h),
59        None => (None, rest),
60    };
61    let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
62        let (h, tail) = v6.split_once(']').ok_or(BAD)?;
63        (h, tail.strip_prefix(':'))
64    } else {
65        match hostport.rsplit_once(':') {
66            Some((h, p)) => (h, Some(p)),
67            None => (hostport, None),
68        }
69    };
70    if host.is_empty() {
71        return Err(BAD.to_string());
72    }
73    let port = match port {
74        Some(p) if !p.is_empty() => p.parse::<u16>().map_err(|_| BAD.to_string())?,
75        _ => 80,
76    };
77    let authorization = userinfo.map(|u| {
78        // Basic is `user:password`, with the colon even when the password is empty.
79        let mut pair = percent_decode(u);
80        if !pair.contains(&b':') {
81            pair.push(b':');
82        }
83        format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(pair))
84    });
85    Ok(Proxy { host: host.to_string(), port, authorization })
86}
87
88/// `s` with its `%XX` escapes decoded, as curl and reqwest read the credentials of a proxy address; a `%` not
89/// followed by two hex digits stays as it is.
90fn percent_decode(s: &str) -> Vec<u8> {
91    let bytes = s.as_bytes();
92    let mut out = Vec::with_capacity(bytes.len());
93    let mut i = 0;
94    while i < bytes.len() {
95        let hex = |b: u8| (b as char).to_digit(16);
96        match (bytes[i], bytes.get(i + 1).copied().and_then(hex), bytes.get(i + 2).copied().and_then(hex)) {
97            (b'%', Some(hi), Some(lo)) => {
98                out.push((hi * 16 + lo) as u8);
99                i += 3;
100            }
101            (b, _, _) => {
102                out.push(b);
103                i += 1;
104            }
105        }
106    }
107    out
108}
109
110/// Whether `NO_PROXY` (a comma list) exempts `host:port`: `*`; a name, matching itself and its subdomains (a leading
111/// `.` or `*.` is the same); an address; a CIDR range; each optionally with `:port`.
112pub(crate) fn no_proxy_matches(list: &str, host: &str, port: u16) -> bool {
113    let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
114    let ip = host.parse::<IpAddr>().ok();
115    list.split(',').map(str::trim).filter(|e| !e.is_empty()).any(|entry| {
116        if entry == "*" {
117            return true;
118        }
119        let entry = entry.to_ascii_lowercase();
120        let (name, wanted_port) = split_entry_port(&entry);
121        if wanted_port.is_some_and(|p| p != port) {
122            return false;
123        }
124        if let (Some(ip), Some((net, bits))) = (ip, name.split_once('/')) {
125            return net.trim_matches(['[', ']']).parse::<IpAddr>().ok().zip(bits.parse::<u8>().ok()).is_some_and(|(net, bits)| in_range(ip, net, bits));
126        }
127        let name = name.trim_matches(['[', ']']);
128        // An address entry is the same address however either side writes it (`::1`, `0:0:0:0:0:0:0:1`).
129        if let (Some(ip), Ok(listed)) = (ip, name.parse::<IpAddr>()) {
130            return ip == listed;
131        }
132        let name = name.strip_prefix("*.").or_else(|| name.strip_prefix('.')).unwrap_or(name);
133        !name.is_empty() && (host == name || host.ends_with(&format!(".{name}")))
134    })
135}
136
137/// `name` and `:port` of a NO_PROXY entry; a bare IPv6 address has no port.
138fn split_entry_port(entry: &str) -> (&str, Option<u16>) {
139    if entry.matches(':').count() > 1 && !entry.starts_with('[') {
140        return (entry, None);
141    }
142    match entry.rsplit_once(':') {
143        Some((name, port)) if !name.ends_with(']') || entry.starts_with('[') => match port.parse::<u16>() {
144            Ok(p) => (name, Some(p)),
145            Err(_) => (entry, None),
146        },
147        _ => (entry, None),
148    }
149}
150
151fn in_range(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
152    match (ip, net) {
153        (IpAddr::V4(a), IpAddr::V4(b)) if bits <= 32 => mask_eq(u128::from(u32::from(a)), u128::from(u32::from(b)), 32, bits),
154        (IpAddr::V6(a), IpAddr::V6(b)) if bits <= 128 => mask_eq(u128::from(a), u128::from(b), 128, bits),
155        _ => false,
156    }
157}
158
159fn mask_eq(a: u128, b: u128, width: u32, bits: u8) -> bool {
160    let shift = width - u32::from(bits);
161    shift >= 128 || (a >> shift) == (b >> shift)
162}
163
164/// The proxy for `host:port`, from the environment `get` reads: `Ok(None)` when none is configured or `NO_PROXY` exempts
165/// the host, an error (fail closed) when one is configured but cannot be used.
166pub(crate) fn proxy_for(get: impl Fn(&str) -> Option<String>, host: &str, port: u16, tls: bool) -> Result<Option<Proxy>, String> {
167    let first = |names: &[&str]| names.iter().find_map(|n| get(n).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()));
168    let configured = if tls {
169        first(&["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"])
170    } else {
171        first(&["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"])
172    };
173    let Some(address) = configured else { return Ok(None) };
174    if first(&["NO_PROXY", "no_proxy"]).is_some_and(|list| no_proxy_matches(&list, host, port)) {
175        return Ok(None);
176    }
177    parse_proxy(&address).map(Some)
178}
179
180/// Opens a tunnel to `host:port` through the proxy: the CONNECT and its `200`, nothing more. The stream is then the
181/// server's own.
182async fn tunnel(proxy: &Proxy, host: &str, port: u16) -> io::Result<TcpStream> {
183    let authority = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
184    let attempt = async {
185        let mut stream = TcpStream::connect((proxy.host.as_str(), proxy.port)).await?;
186        let mut head = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n");
187        if let Some(auth) = &proxy.authorization {
188            head.push_str(&format!("Proxy-Authorization: {auth}\r\n"));
189        }
190        head.push_str("\r\n");
191        stream.write_all(head.as_bytes()).await?;
192        // One byte at a time: nothing past the reply head may be consumed, it is the server's.
193        let mut reply = Vec::new();
194        while !reply.ends_with(b"\r\n\r\n") {
195            if reply.len() >= MAX_REPLY_HEAD {
196                return Err(io::Error::other("the proxy's reply was too long"));
197            }
198            reply.push(stream.read_u8().await?);
199        }
200        let status = String::from_utf8_lossy(&reply);
201        let status_line = status.lines().next().unwrap_or("").trim();
202        if status_line.split_whitespace().nth(1) == Some("200") {
203            Ok(stream)
204        } else {
205            Err(io::Error::other(format!("the proxy refused CONNECT {authority}: {status_line}")))
206        }
207    };
208    match tokio::time::timeout(PROXY_TIMEOUT, attempt).await {
209        Ok(result) => result,
210        Err(_) => Err(io::Error::new(io::ErrorKind::TimedOut, format!("the proxy did not answer CONNECT {authority}"))),
211    }
212}
213
214/// Connects the WebSocket for `request`, through the environment's proxy when it names one for the request's host.
215pub async fn connect(request: impl IntoClientRequest + Unpin) -> Result<(Socket, Response), Error> {
216    connect_with_env(request, |name| std::env::var(name).ok()).await
217}
218
219/// [`connect`], failing as a connect that cannot reach the network does when it takes longer than `limit`.
220pub(crate) async fn connect_within(request: impl IntoClientRequest + Unpin, limit: std::time::Duration) -> Result<(Socket, Response), Error> {
221    tokio::time::timeout(limit, connect(request))
222        .await
223        .unwrap_or_else(|_| Err(Error::Io(io::Error::new(io::ErrorKind::TimedOut, "the WebSocket handshake took too long"))))
224}
225
226async fn connect_with_env(request: impl IntoClientRequest + Unpin, get: impl Fn(&str) -> Option<String>) -> Result<(Socket, Response), Error> {
227    let request = request.into_client_request()?;
228    let uri = request.uri();
229    // `Uri::host` keeps the brackets of an IPv6 literal; `tunnel` adds them back.
230    let host = uri.host().ok_or(Error::Url(UrlError::NoHostName))?.trim_matches(['[', ']']).to_string();
231    let tls = uri.scheme_str() == Some("wss");
232    let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
233    match proxy_for(get, &host, port, tls) {
234        Ok(None) => connect_async_tls_with_config(request, None, false, None).await,
235        Ok(Some(proxy)) => {
236            tracing::debug!(host = %host, port, proxy_host = %proxy.host, proxy_port = proxy.port, "ws: connecting through the proxy");
237            let stream = tunnel(&proxy, &host, port).await.map_err(Error::Io)?;
238            client_async_tls_with_config(request, stream, None, None).await
239        }
240        Err(why) => {
241            tracing::warn!("ws: a proxy is configured but cannot be used ({why}); not connecting direct");
242            Err(Error::Io(io::Error::other(format!("proxy not usable: {why}"))))
243        }
244    }
245}
246
247#[cfg(test)]
248#[path = "ws_connect_tests.rs"]
249mod tests;