Skip to main content

nautilus_network/websocket/
proxy.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! HTTP `CONNECT` tunneling for outbound WebSocket connections.
17//!
18//! HTTP and HTTPS proxy URLs are supported. An HTTPS proxy adds TLS to the proxy hop; a `wss`
19//! target adds a separate TLS session after the tunnel is established. URL user information
20//! becomes Basic proxy authentication, and credential-bearing values are redacted from `Debug`
21//! output.
22//!
23//! The tunnel accepts only a `2xx` response and bounds response headers before parsing. It returns
24//! a stream positioned for the WebSocket handshake rather than performing that handshake itself.
25//!
26//! SOCKS URLs are rejected: the client returns an error and never connects directly.
27//! Both transport backends tunnel through the same [`ProxiedStream`], which implements the IO
28//! traits over every tunnel shape so each backend runs its own handshake over the finished stream.
29
30use std::{
31    fmt::Debug,
32    io,
33    pin::Pin,
34    task::{Context, Poll},
35};
36
37use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
38use nautilus_core::string::secret::REDACTED;
39use rustls::{ClientConfig, RootCertStore, pki_types::ServerName};
40use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
41use tokio_rustls::{TlsConnector, client::TlsStream};
42use url::Url;
43
44use crate::{net::TcpStream, transport::TransportError};
45
46/// Maximum size of a `CONNECT` proxy response we are willing to read.
47///
48/// Bounds the buffer so a malicious or broken proxy cannot make us allocate
49/// indefinitely while we wait for the header terminator.
50const MAX_PROXY_RESPONSE_BYTES: usize = 16 * 1024;
51
52/// Validated HTTP or HTTPS proxy URL.
53///
54/// The underlying URL is intentionally redacted from [`Debug`] output because
55/// URL user-info can contain proxy credentials.
56#[derive(Clone, PartialEq, Eq)]
57pub struct ProxyUrl(String);
58
59impl ProxyUrl {
60    /// Parses and validates an HTTP or HTTPS proxy URL.
61    ///
62    /// # Errors
63    ///
64    /// Returns an error if the URL is malformed, has no host, or uses an unsupported scheme.
65    pub fn parse(value: impl Into<String>) -> Result<Self, TransportError> {
66        let value = value.into();
67        ProxyTarget::parse(&value)?;
68        Ok(Self(value))
69    }
70
71    /// Returns the validated URL for transport configuration.
72    #[must_use]
73    pub fn expose(&self) -> &str {
74        &self.0
75    }
76}
77
78impl Debug for ProxyUrl {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_tuple(stringify!(ProxyUrl))
81            .field(&REDACTED)
82            .finish()
83    }
84}
85
86/// Stream produced by `tunnel_via_proxy` when the upstream is `ws://`
87/// (no upstream TLS, but the proxy hop itself may have been TLS-protected).
88///
89/// The TLS-bearing variants are boxed because [`tokio_rustls::client::TlsStream`]
90/// is large enough that a flat enum trips `clippy::large_enum_variant`. Boxing
91/// keeps the discriminant cheap to move while leaving the rare TLS path on the
92/// heap.
93#[derive(Debug)]
94pub enum ProxiedStream {
95    /// Plain TCP after a plain proxy hop.
96    Plain(TcpStream),
97    /// Plain TCP after a TLS proxy hop.
98    PlainOverTlsProxy(Box<TlsStream<TcpStream>>),
99    /// Upstream TLS over a plain proxy hop.
100    Tls(Box<TlsStream<TcpStream>>),
101    /// Upstream TLS over a TLS proxy hop.
102    TlsOverTlsProxy(Box<TlsStream<TlsStream<TcpStream>>>),
103}
104
105/// Combines the two IO traits so [`ProxiedStream`] resolves its variant in one place.
106trait ProxiedIo: AsyncRead + AsyncWrite + Send + Unpin {}
107
108impl<T: AsyncRead + AsyncWrite + Send + Unpin> ProxiedIo for T {}
109
110impl ProxiedStream {
111    fn inner_mut(&mut self) -> &mut dyn ProxiedIo {
112        match self {
113            Self::Plain(s) => s,
114            Self::PlainOverTlsProxy(s) | Self::Tls(s) => s.as_mut(),
115            Self::TlsOverTlsProxy(s) => s.as_mut(),
116        }
117    }
118}
119
120impl AsyncRead for ProxiedStream {
121    fn poll_read(
122        self: Pin<&mut Self>,
123        cx: &mut Context<'_>,
124        buf: &mut ReadBuf<'_>,
125    ) -> Poll<io::Result<()>> {
126        Pin::new(self.get_mut().inner_mut()).poll_read(cx, buf)
127    }
128}
129
130impl AsyncWrite for ProxiedStream {
131    fn poll_write(
132        self: Pin<&mut Self>,
133        cx: &mut Context<'_>,
134        buf: &[u8],
135    ) -> Poll<io::Result<usize>> {
136        Pin::new(self.get_mut().inner_mut()).poll_write(cx, buf)
137    }
138
139    fn poll_write_vectored(
140        self: Pin<&mut Self>,
141        cx: &mut Context<'_>,
142        bufs: &[io::IoSlice<'_>],
143    ) -> Poll<io::Result<usize>> {
144        Pin::new(self.get_mut().inner_mut()).poll_write_vectored(cx, bufs)
145    }
146
147    fn is_write_vectored(&self) -> bool {
148        match self {
149            Self::Plain(s) => s.is_write_vectored(),
150            Self::PlainOverTlsProxy(s) | Self::Tls(s) => s.is_write_vectored(),
151            Self::TlsOverTlsProxy(s) => s.is_write_vectored(),
152        }
153    }
154
155    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
156        Pin::new(self.get_mut().inner_mut()).poll_flush(cx)
157    }
158
159    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
160        Pin::new(self.get_mut().inner_mut()).poll_shutdown(cx)
161    }
162}
163
164/// Parsed components of a target WebSocket URL needed by the proxy hop.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct WsTarget {
167    /// Host name for DNS / SNI / `CONNECT` request line.
168    pub host: String,
169    /// TCP port of the WebSocket origin.
170    pub port: u16,
171    /// `true` when the WebSocket scheme is `wss://`.
172    pub is_tls: bool,
173}
174
175impl WsTarget {
176    /// Parses a `ws://` or `wss://` URL into the host, port, and TLS components.
177    ///
178    /// # Errors
179    ///
180    /// Returns an error if the URL fails to parse, is missing a hostname, or uses a scheme other
181    /// than `ws`/`wss`.
182    pub fn parse(url: &str) -> Result<Self, TransportError> {
183        let parsed = Url::parse(url)
184            .map_err(|e| TransportError::InvalidUrl(format!("invalid WebSocket URL: {e}")))?;
185
186        let is_tls = match parsed.scheme() {
187            "ws" => false,
188            "wss" => true,
189            other => {
190                return Err(TransportError::InvalidUrl(format!(
191                    "expected ws:// or wss:// scheme, was {other}"
192                )));
193            }
194        };
195
196        let raw_host = parsed
197            .host_str()
198            .ok_or_else(|| TransportError::InvalidUrl("missing hostname".to_string()))?;
199
200        // url::Url stores IPv6 literals in bracketed form (`[::1]`); the
201        // `CONNECT` request line and TLS SNI both want the unbracketed form.
202        let host = if raw_host.starts_with('[') && raw_host.ends_with(']') {
203            raw_host[1..raw_host.len() - 1].to_string()
204        } else {
205            raw_host.to_string()
206        };
207
208        let port = parsed.port().unwrap_or(if is_tls { 443 } else { 80 });
209
210        Ok(Self { host, port, is_tls })
211    }
212}
213
214/// Parsed components of a forward proxy URL.
215#[derive(Clone, PartialEq, Eq)]
216pub struct ProxyTarget {
217    /// Host name of the proxy (used for both DNS and TLS SNI when
218    /// [`ProxyTarget::is_tls`] is `true`).
219    pub host: String,
220    /// TCP port of the proxy.
221    pub port: u16,
222    /// `true` when the proxy URL scheme is `https`.
223    pub is_tls: bool,
224    /// Pre-computed `Proxy-Authorization` header value, if the URL embeds
225    /// `user:pass@`.
226    pub auth_header: Option<String>,
227}
228
229impl Debug for ProxyTarget {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        f.debug_struct(stringify!(ProxyTarget))
232            .field("host", &self.host)
233            .field("port", &self.port)
234            .field("is_tls", &self.is_tls)
235            .field("auth_header", &self.auth_header.as_ref().map(|_| REDACTED))
236            .finish()
237    }
238}
239
240impl ProxyTarget {
241    /// Parses an HTTP or HTTPS proxy URL into the components needed to establish the tunnel.
242    ///
243    /// # Errors
244    ///
245    /// Returns an error if the URL is malformed, the host is missing, or the scheme is neither
246    /// `http` nor `https`.
247    pub fn parse(url: &str) -> Result<Self, TransportError> {
248        let parsed = Url::parse(url)
249            .map_err(|e| TransportError::InvalidUrl(format!("invalid proxy URL: {e}")))?;
250
251        let is_tls = match parsed.scheme() {
252            "http" => false,
253            "https" => true,
254            "socks5" | "socks5h" | "socks4" | "socks4a" => {
255                return Err(TransportError::InvalidUrl(format!(
256                    "SOCKS proxy scheme '{}' is not yet supported for WebSocket connections; \
257                    use an http:// or https:// proxy",
258                    parsed.scheme()
259                )));
260            }
261            other => {
262                return Err(TransportError::InvalidUrl(format!(
263                    "unsupported proxy scheme '{other}'; expected http:// or https://"
264                )));
265            }
266        };
267
268        let raw_host = parsed
269            .host_str()
270            .ok_or_else(|| TransportError::InvalidUrl("proxy URL missing hostname".to_string()))?;
271
272        // url::Url stores IPv6 literals bracketed (`[::1]`); the bracketed
273        // form is only valid in the HTTP `Host:` header, not for DNS or
274        // TLS SNI, so we keep both representations.
275        let host = if raw_host.starts_with('[') && raw_host.ends_with(']') {
276            raw_host[1..raw_host.len() - 1].to_string()
277        } else {
278            raw_host.to_string()
279        };
280
281        let port = parsed.port().unwrap_or(if is_tls { 443 } else { 80 });
282
283        let auth_header = if parsed.username().is_empty() && parsed.password().is_none() {
284            None
285        } else {
286            let username = decode_userinfo(parsed.username());
287            let password = decode_userinfo(parsed.password().unwrap_or(""));
288            let credentials = format!("{username}:{password}");
289            Some(format!("Basic {}", BASE64.encode(credentials)))
290        };
291
292        Ok(Self {
293            host,
294            port,
295            is_tls,
296            auth_header,
297        })
298    }
299}
300
301/// Percent-decode a userinfo field from a proxy URL. `url::Url` keeps the
302/// raw percent-encoded form, so we decode it here before assembling the
303/// `Basic` credentials.
304fn decode_userinfo(value: &str) -> String {
305    let bytes = nautilus_core::string::urlencoding::decode_bytes(value.as_bytes());
306    String::from_utf8_lossy(&bytes).into_owned()
307}
308
309/// Establish a tunneled connection through `proxy` to the WebSocket `target`.
310///
311/// On success the returned stream is positioned right after the proxy's
312/// `200`/`2xx` response, ready for the WebSocket handshake. The function does
313/// not perform the WebSocket handshake itself; callers wrap the stream in
314/// `tokio-tungstenite::client_async`.
315///
316/// # Errors
317///
318/// Returns an error if:
319/// - The TCP connection to the proxy fails.
320/// - The TLS layer to the proxy or upstream cannot be established.
321/// - The proxy returns a non-success status, malformed headers, or closes the
322///   stream before completing the response.
323pub async fn tunnel_via_proxy(
324    target: &WsTarget,
325    proxy: &ProxyTarget,
326) -> Result<ProxiedStream, TransportError> {
327    let tcp = TcpStream::connect((proxy.host.as_str(), proxy.port))
328        .await
329        .map_err(TransportError::Io)?;
330
331    crate::net::apply_socket_options(&tcp);
332    if proxy.is_tls {
333        let proxy_tls = wrap_tls(tcp, &proxy.host).await?;
334        let tunneled = send_connect(proxy_tls, target, proxy).await?;
335        if target.is_tls {
336            let upstream = wrap_tls(tunneled, &target.host).await?;
337            Ok(ProxiedStream::TlsOverTlsProxy(Box::new(upstream)))
338        } else {
339            Ok(ProxiedStream::PlainOverTlsProxy(Box::new(tunneled)))
340        }
341    } else {
342        let tunneled = send_connect(tcp, target, proxy).await?;
343        if target.is_tls {
344            let upstream = wrap_tls(tunneled, &target.host).await?;
345            Ok(ProxiedStream::Tls(Box::new(upstream)))
346        } else {
347            Ok(ProxiedStream::Plain(tunneled))
348        }
349    }
350}
351
352/// Sends a `CONNECT` request and returns the underlying stream once a `2xx`
353/// status is received. The returned stream is positioned after the empty line
354/// terminating the proxy response headers.
355async fn send_connect<S>(
356    mut stream: S,
357    target: &WsTarget,
358    proxy: &ProxyTarget,
359) -> Result<S, TransportError>
360where
361    S: AsyncRead + AsyncWrite + Unpin,
362{
363    let host_header = format_host_header(&target.host, target.port);
364    let mut request = format!(
365        "CONNECT {host_header} HTTP/1.1\r\n\
366         Host: {host_header}\r\n\
367         Proxy-Connection: Keep-Alive\r\n"
368    );
369
370    if let Some(auth) = &proxy.auth_header {
371        request.push_str("Proxy-Authorization: ");
372        request.push_str(auth);
373        request.push_str("\r\n");
374    }
375
376    request.push_str("\r\n");
377
378    stream
379        .write_all(request.as_bytes())
380        .await
381        .map_err(TransportError::Io)?;
382    stream.flush().await.map_err(TransportError::Io)?;
383
384    read_connect_response(&mut stream).await?;
385    Ok(stream)
386}
387
388fn format_host_header(host: &str, port: u16) -> String {
389    if host.contains(':') && !(host.starts_with('[') && host.ends_with(']')) {
390        format!("[{host}]:{port}")
391    } else {
392        format!("{host}:{port}")
393    }
394}
395
396/// Reads the proxy's response up to the empty line that terminates the
397/// headers, validating the status line.
398async fn read_connect_response<S>(stream: &mut S) -> Result<(), TransportError>
399where
400    S: AsyncRead + Unpin,
401{
402    let mut buf = Vec::with_capacity(512);
403    let mut byte = [0u8; 1];
404    loop {
405        let n = stream.read(&mut byte).await.map_err(TransportError::Io)?;
406        if n == 0 {
407            return Err(TransportError::ConnectionClosed);
408        }
409
410        buf.push(byte[0]);
411
412        if buf.ends_with(b"\r\n\r\n") {
413            break;
414        }
415
416        if buf.len() > MAX_PROXY_RESPONSE_BYTES {
417            return Err(TransportError::Handshake(format!(
418                "proxy CONNECT response exceeded {MAX_PROXY_RESPONSE_BYTES} bytes without terminator"
419            )));
420        }
421    }
422
423    let text = std::str::from_utf8(&buf).map_err(|_| {
424        TransportError::Handshake("proxy CONNECT response was not valid UTF-8".to_string())
425    })?;
426
427    let status_line = text.lines().next().ok_or_else(|| {
428        TransportError::Handshake("proxy CONNECT response missing status line".to_string())
429    })?;
430
431    // Expect: `HTTP/1.1 200 Connection established` (or any 2xx).
432    let mut parts = status_line.splitn(3, ' ');
433
434    let version = parts.next().ok_or_else(|| {
435        TransportError::Handshake("proxy CONNECT response has a malformed status line".to_string())
436    })?;
437
438    // The version gates the status branch below: without this check a malformed line such as
439    // `NOT-HTTP 503 ...` would yield a retryable `ProxyConnectRejected` rather than staying a
440    // permanent handshake failure.
441    if !matches!(version, "HTTP/1.0" | "HTTP/1.1") {
442        return Err(TransportError::Handshake(
443            "proxy CONNECT response has a malformed status line".to_string(),
444        ));
445    }
446
447    // Parsed as a `StatusCode` rather than a bare `u16` for the same reason the version is
448    // validated above: the number now selects retry behavior, and `u16` parsing accepts tokens
449    // HTTP does not, normalizing `0503` to `503`.
450    let status_code = parts
451        .next()
452        .ok_or_else(|| {
453            TransportError::Handshake(
454                "proxy CONNECT response has a malformed status line".to_string(),
455            )
456        })?
457        .parse::<http::StatusCode>()
458        .map_err(|_| {
459            TransportError::Handshake(
460                "proxy CONNECT response has a invalid status code".to_string(),
461            )
462        })?
463        .as_u16();
464
465    if !(200..300).contains(&status_code) {
466        return Err(TransportError::ProxyConnectRejected(status_code));
467    }
468
469    Ok(())
470}
471
472/// Wraps a stream in a `rustls`-backed TLS session using `webpki_roots`.
473async fn wrap_tls<S>(stream: S, server_name: &str) -> Result<TlsStream<S>, TransportError>
474where
475    S: AsyncRead + AsyncWrite + Unpin,
476{
477    let mut root_store = RootCertStore::empty();
478    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
479
480    let config = ClientConfig::builder()
481        .with_root_certificates(root_store)
482        .with_no_client_auth();
483
484    let connector = TlsConnector::from(std::sync::Arc::new(config));
485    let domain = ServerName::try_from(server_name.to_string())
486        .map_err(|e| TransportError::Tls(format!("invalid DNS name '{server_name}': {e}")))?;
487
488    connector
489        .connect(domain, stream)
490        .await
491        .map_err(TransportError::Io)
492}
493
494#[cfg(test)]
495#[cfg(not(feature = "turmoil"))] // proxy hop is not modeled under the turmoil simulator
496mod tests {
497    use std::net::SocketAddr;
498
499    use rstest::rstest;
500    use tokio::net::TcpListener;
501
502    use super::*;
503
504    #[rstest]
505    fn ws_target_parses_wss() {
506        let target = WsTarget::parse("wss://stream.binance.com:9443/ws/btcusdt@trade").unwrap();
507        assert_eq!(target.host, "stream.binance.com");
508        assert_eq!(target.port, 9443);
509        assert!(target.is_tls);
510    }
511
512    #[rstest]
513    fn ws_target_default_ports() {
514        let plain = WsTarget::parse("ws://example.com/path").unwrap();
515        assert_eq!(plain.port, 80);
516        assert!(!plain.is_tls);
517
518        let tls = WsTarget::parse("wss://example.com/path").unwrap();
519        assert_eq!(tls.port, 443);
520        assert!(tls.is_tls);
521    }
522
523    #[rstest]
524    fn ws_target_strips_ipv6_brackets() {
525        let target = WsTarget::parse("wss://[::1]:9443/ws").unwrap();
526        assert_eq!(target.host, "::1");
527        assert_eq!(target.port, 9443);
528    }
529
530    #[rstest]
531    fn ws_target_rejects_non_ws_scheme() {
532        let err = WsTarget::parse("https://example.com").unwrap_err();
533        assert!(matches!(err, TransportError::InvalidUrl(_)));
534    }
535
536    #[rstest]
537    fn proxy_target_parses_http() {
538        let proxy = ProxyTarget::parse("http://127.0.0.1:9999").unwrap();
539        assert_eq!(proxy.host, "127.0.0.1");
540        assert_eq!(proxy.port, 9999);
541        assert!(!proxy.is_tls);
542        assert!(proxy.auth_header.is_none());
543    }
544
545    #[rstest]
546    fn proxy_target_default_ports() {
547        let plain = ProxyTarget::parse("http://proxy.example.com").unwrap();
548        assert_eq!(plain.port, 80);
549        let tls = ProxyTarget::parse("https://proxy.example.com").unwrap();
550        assert_eq!(tls.port, 443);
551        assert!(tls.is_tls);
552    }
553
554    #[rstest]
555    fn proxy_target_basic_auth() {
556        let proxy =
557            ProxyTarget::parse("http://proxytest:fixture42@proxy.example.com:8080").unwrap();
558        let expected = format!("Basic {}", BASE64.encode("proxytest:fixture42"));
559        assert_eq!(proxy.auth_header.unwrap(), expected);
560    }
561
562    #[rstest]
563    fn proxy_target_basic_auth_decodes_percent_encoded() {
564        // `p%40ss` should decode to `p@ss` before assembling Basic credentials
565        let proxy = ProxyTarget::parse("http://us%2Fer:p%40ss@proxy.example.com:8080").unwrap();
566        let header = proxy.auth_header.unwrap();
567        let expected = format!("Basic {}", BASE64.encode("us/er:p@ss"));
568        assert_eq!(header, expected);
569    }
570
571    #[rstest]
572    fn proxy_target_basic_auth_with_empty_username() {
573        let proxy = ProxyTarget::parse("http://:fixture42@proxy.example.com:8080").unwrap();
574        let expected = format!("Basic {}", BASE64.encode(":fixture42"));
575
576        assert_eq!(proxy.auth_header.unwrap(), expected);
577    }
578
579    #[rstest]
580    fn proxy_debug_redacts_credentials() {
581        const SECRET: &str = "unique-proxy-secret";
582        let url = format!("http://proxytest:{SECRET}@proxy.example.com:8080");
583        let proxy_url = ProxyUrl::parse(url.clone()).unwrap();
584        let target = ProxyTarget::parse(&url).unwrap();
585        let proxy_url_debug = format!("{proxy_url:?}");
586        let target_debug = format!("{target:?}");
587        let encoded_credentials = BASE64.encode(format!("proxytest:{SECRET}"));
588
589        assert_eq!(proxy_url_debug, "ProxyUrl(\"<redacted>\")");
590        assert!(!proxy_url_debug.contains(SECRET));
591        assert!(!target_debug.contains(SECRET));
592        assert!(!target_debug.contains(&encoded_credentials));
593        assert!(target_debug.contains(REDACTED));
594    }
595
596    #[rstest]
597    fn proxy_parse_error_redacts_credentials() {
598        const SECRET: &str = "unique-proxy-secret";
599        let err = ProxyUrl::parse(format!("http://proxytest:{SECRET}@[::1"))
600            .expect_err("malformed proxy URL should fail");
601
602        assert!(!err.to_string().contains(SECRET));
603    }
604
605    #[tokio::test]
606    async fn send_connect_includes_proxy_authorization() {
607        let (client, mut server) = tokio::io::duplex(1024);
608        let target = WsTarget::parse("ws://example.com:80/path").unwrap();
609        let proxy =
610            ProxyTarget::parse("http://proxytest:fixture42@proxy.example.com:8080").unwrap();
611
612        let server_task = tokio::spawn(async move {
613            let mut request = Vec::new();
614            let mut chunk = [0; 64];
615            loop {
616                let n = server.read(&mut chunk).await.unwrap();
617                request.extend_from_slice(&chunk[..n]);
618                if request.ends_with(b"\r\n\r\n") {
619                    break;
620                }
621            }
622
623            let request = String::from_utf8(request).unwrap();
624            let expected = format!(
625                "CONNECT example.com:80 HTTP/1.1\r\n\
626                 Host: example.com:80\r\n\
627                 Proxy-Connection: Keep-Alive\r\n\
628                 Proxy-Authorization: Basic {}\r\n\r\n",
629                BASE64.encode("proxytest:fixture42")
630            );
631            assert_eq!(request, expected);
632            server
633                .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
634                .await
635        });
636
637        let _stream = send_connect(client, &target, &proxy).await.unwrap();
638        server_task.await.unwrap().unwrap();
639    }
640
641    #[rstest]
642    fn proxy_target_strips_ipv6_brackets() {
643        let proxy = ProxyTarget::parse("http://[::1]:8080").unwrap();
644        assert_eq!(proxy.host, "::1");
645        assert_eq!(proxy.port, 8080);
646    }
647
648    #[rstest]
649    fn proxy_target_rejects_socks() {
650        let err = ProxyTarget::parse("socks5://127.0.0.1:1080").unwrap_err();
651
652        let TransportError::InvalidUrl(msg) = err else {
653            panic!("expected InvalidUrl");
654        };
655
656        assert!(msg.contains("SOCKS"));
657    }
658
659    #[rstest]
660    fn proxy_target_rejects_socks_without_authority() {
661        let err = ProxyTarget::parse("socks5:127.0.0.1:1080").unwrap_err();
662        assert!(matches!(err, TransportError::InvalidUrl(_)));
663    }
664
665    #[rstest]
666    fn proxy_target_rejects_unknown_scheme() {
667        let err = ProxyTarget::parse("ftp://proxy.example.com").unwrap_err();
668        assert!(matches!(err, TransportError::InvalidUrl(_)));
669    }
670
671    #[rstest]
672    fn proxy_target_rejects_empty() {
673        let err = ProxyTarget::parse("").unwrap_err();
674        assert!(matches!(err, TransportError::InvalidUrl(_)));
675    }
676
677    #[rstest]
678    fn host_header_brackets_ipv6() {
679        assert_eq!(format_host_header("example.com", 443), "example.com:443");
680        assert_eq!(format_host_header("::1", 443), "[::1]:443");
681        assert_eq!(format_host_header("[::1]", 443), "[::1]:443");
682    }
683
684    /// Spawn a fake HTTP proxy that returns the configured response after
685    /// reading one CONNECT request line. Returns the bound address.
686    async fn spawn_fake_proxy(response: &'static [u8]) -> SocketAddr {
687        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
688        let addr = listener.local_addr().unwrap();
689        tokio::spawn(async move {
690            let (mut stream, _) = listener.accept().await.unwrap();
691            let mut buf = vec![0u8; 1024];
692
693            // Read until we see the CONNECT terminator.
694            loop {
695                let n = AsyncReadExt::read(&mut stream, &mut buf).await.unwrap();
696                if n == 0 {
697                    break;
698                }
699
700                if buf[..n].windows(4).any(|w| w == b"\r\n\r\n") {
701                    break;
702                }
703            }
704
705            stream.write_all(response).await.unwrap();
706            stream.flush().await.unwrap();
707        });
708
709        addr
710    }
711
712    #[tokio::test]
713    async fn read_connect_response_accepts_2xx() {
714        let addr = spawn_fake_proxy(b"HTTP/1.1 200 Connection established\r\n\r\n").await;
715        let mut stream = TcpStream::connect(addr).await.unwrap();
716        stream
717            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
718            .await
719            .unwrap();
720        stream.flush().await.unwrap();
721        read_connect_response(&mut stream).await.unwrap();
722    }
723
724    #[tokio::test]
725    async fn read_connect_response_rejects_403() {
726        let addr = spawn_fake_proxy(b"HTTP/1.1 403 Forbidden\r\n\r\n").await;
727        let mut stream = TcpStream::connect(addr).await.unwrap();
728        stream
729            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
730            .await
731            .unwrap();
732        stream.flush().await.unwrap();
733        let err = read_connect_response(&mut stream).await.unwrap_err();
734        assert!(matches!(err, TransportError::ProxyConnectRejected(403)));
735    }
736
737    /// 300 sits on the upper boundary of the accepted `200..300` range; if
738    /// the check is ever loosened to `200..=300` this test fails. 407 is the
739    /// classic "Proxy Authentication Required" response. Non-numeric status
740    /// probes the parse path.
741    #[rstest]
742    #[case::status_300(&b"HTTP/1.1 300 Multiple Choices\r\n\r\n"[..], Some(300), None)]
743    #[case::status_407(
744        &b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n"[..],
745        Some(407),
746        None,
747    )]
748    #[case::malformed_status(
749        &b"HTTP/1.1 abc Boom\r\n\r\n"[..],
750        None,
751        Some("invalid status code"),
752    )]
753    #[tokio::test]
754    async fn read_connect_response_rejects_non_2xx(
755        #[case] response: &'static [u8],
756        #[case] expected_status: Option<u16>,
757        #[case] expected_msg_substring: Option<&'static str>,
758    ) {
759        let addr = spawn_fake_proxy(response).await;
760        let mut stream = TcpStream::connect(addr).await.unwrap();
761        stream
762            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
763            .await
764            .unwrap();
765        stream.flush().await.unwrap();
766        let err = read_connect_response(&mut stream).await.unwrap_err();
767
768        match (expected_status, expected_msg_substring) {
769            (Some(status), None) => {
770                assert!(
771                    matches!(err, TransportError::ProxyConnectRejected(actual) if actual == status)
772                );
773            }
774            (None, Some(expected_msg_substring)) => {
775                let TransportError::Handshake(msg) = err else {
776                    panic!("expected Handshake error, was {err:?}");
777                };
778
779                assert!(
780                    msg.contains(expected_msg_substring),
781                    "expected error message to contain {expected_msg_substring:?}, was {msg:?}"
782                );
783            }
784            _ => unreachable!(),
785        }
786    }
787
788    #[tokio::test]
789    async fn read_connect_response_does_not_expose_reason_phrase() {
790        const SECRET: &str = "unique-proxy-secret";
791        let response = format!("HTTP/1.1 407 {SECRET}\r\n\r\n").into_bytes();
792        let response = Box::leak(response.into_boxed_slice());
793        let addr = spawn_fake_proxy(response).await;
794        let mut stream = TcpStream::connect(addr).await.unwrap();
795        stream
796            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
797            .await
798            .unwrap();
799        stream.flush().await.unwrap();
800
801        let err = read_connect_response(&mut stream).await.unwrap_err();
802
803        assert_eq!(err.to_string(), "proxy CONNECT rejected with status 407");
804        assert!(!err.to_string().contains(SECRET));
805    }
806
807    /// Closing the connection mid-response should produce a clear handshake
808    /// error rather than spinning on a zero-byte read.
809    #[tokio::test]
810    async fn read_connect_response_rejects_eof_before_terminator() {
811        // Truncated response: missing the empty line that ends the headers
812        let addr = spawn_fake_proxy(b"HTTP/1.1 200 OK\r\n").await;
813        let mut stream = TcpStream::connect(addr).await.unwrap();
814        stream
815            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
816            .await
817            .unwrap();
818        stream.flush().await.unwrap();
819        let err = read_connect_response(&mut stream).await.unwrap_err();
820        assert!(matches!(err, TransportError::ConnectionClosed));
821    }
822
823    /// A malformed version with an otherwise retryable status must stay a permanent
824    /// `Handshake` failure. The status is 503 deliberately: were the version left
825    /// unvalidated, this would parse as `ProxyConnectRejected(503)` and be retried.
826    #[tokio::test]
827    async fn read_connect_response_rejects_malformed_version_with_retryable_status() {
828        let addr = spawn_fake_proxy(b"NOT-HTTP 503 Service Unavailable\r\n\r\n").await;
829        let mut stream = TcpStream::connect(addr).await.unwrap();
830        stream
831            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
832            .await
833            .unwrap();
834        stream.flush().await.unwrap();
835        let err = read_connect_response(&mut stream).await.unwrap_err();
836
837        let TransportError::Handshake(msg) = err else {
838            panic!("expected Handshake error, was {err:?}");
839        };
840
841        assert!(msg.contains("malformed status line"), "was {msg}");
842    }
843
844    /// `0503` is not a valid status token but parses as `503` under bare `u16`
845    /// parsing, which would make a malformed line retryable. 503 is used because
846    /// a permanent status would pass whether or not the token is validated.
847    #[tokio::test]
848    async fn read_connect_response_rejects_malformed_status_token_with_retryable_value() {
849        let addr = spawn_fake_proxy(b"HTTP/1.1 0503 Service Unavailable\r\n\r\n").await;
850        let mut stream = TcpStream::connect(addr).await.unwrap();
851        stream
852            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
853            .await
854            .unwrap();
855        stream.flush().await.unwrap();
856        let err = read_connect_response(&mut stream).await.unwrap_err();
857
858        let TransportError::Handshake(msg) = err else {
859            panic!("expected Handshake error, was {err:?}");
860        };
861
862        assert!(msg.contains("invalid status code"), "was {msg}");
863    }
864
865    /// A proxy that streams headers without ever emitting `\r\n\r\n` should
866    /// trip the size cap rather than allocating without bound.
867    #[tokio::test]
868    async fn read_connect_response_rejects_oversize_headers() {
869        let mut response = b"HTTP/1.1 200 OK\r\n".to_vec();
870        while response.len() <= MAX_PROXY_RESPONSE_BYTES {
871            response.extend_from_slice(b"X-Pad: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n");
872        }
873
874        let leaked: &'static [u8] = response.leak();
875        let addr = spawn_fake_proxy(leaked).await;
876        let mut stream = TcpStream::connect(addr).await.unwrap();
877        stream
878            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
879            .await
880            .unwrap();
881        stream.flush().await.unwrap();
882        let err = read_connect_response(&mut stream).await.unwrap_err();
883
884        let TransportError::Handshake(msg) = err else {
885            panic!("expected Handshake error, was {err:?}");
886        };
887
888        assert!(
889            msg.contains("exceeded"),
890            "unexpected handshake error: {msg}"
891        );
892    }
893
894    /// After accepting the 2xx response, the stream cursor must sit immediately
895    /// after the terminating `\r\n\r\n` so the WebSocket handshake can read its
896    /// own response. Regression guard against over-reading the terminator.
897    #[tokio::test]
898    async fn read_connect_response_preserves_trailing_bytes() {
899        let addr = spawn_fake_proxy(b"HTTP/1.1 200 Connection established\r\n\r\nLEFTOVER").await;
900        let mut stream = TcpStream::connect(addr).await.unwrap();
901        stream
902            .write_all(b"CONNECT host:443 HTTP/1.1\r\nHost: host:443\r\n\r\n")
903            .await
904            .unwrap();
905        stream.flush().await.unwrap();
906        read_connect_response(&mut stream).await.unwrap();
907
908        let mut tail = [0u8; b"LEFTOVER".len()];
909        AsyncReadExt::read_exact(&mut stream, &mut tail)
910            .await
911            .unwrap();
912        assert_eq!(&tail, b"LEFTOVER");
913    }
914}