Add WebSocket fallback for OAuth SSH tunnels (#65212)

## Why

Networks that block HTTP/3 and HTTP/2 `CONNECT` can prevent
`codex tcp-tunnel` from establishing an SSH connection.

## What changed

In the default `auto` mode, keep the TCP attempt available when HTTP/3
`CONNECT` is blocked. If HTTP/2 `CONNECT` returns 405, 501, or a 403 with
a `Server` header starting with `Zscaler/`, retry once over an HTTP/1.1
WebSocket. Use WebSocket directly when TLS negotiates HTTP/1.1. Ordinary
authentication and authorization rejections stop setup. The attempts
share the gateway, proxy route, TLS trust, and setup deadline.

Use `--transport websocket` to force WebSocket or `--transport connect`
to use only HTTP/3 and HTTP/2 `CONNECT`. Legacy JWT tunnels use
`CONNECT`.

Preserve independent EOF in both directions. When the remote side
finishes writing, close the output pipe to OpenSSH so it sees EOF
while upload can continue.

## Testing

Add TLS-backed tests for fallback after blocked `CONNECT` responses,
half-close in both directions, terminal gateway rejection, certificate
verification before credential loading, and redirect rejection.

GitOrigin-RevId: cfbbd81a3836da8d1f12bed61bb03c9dfb3674ce
This commit is contained in:
Anton Panasenko
2026-12-02 09:56:45 +00:00
committed by copyberry
parent aa433cb350
commit 07753325c6
14 changed files with 813 additions and 186 deletions
+3
View File
@@ -2698,6 +2698,7 @@ dependencies = [
"codex-windows-sandbox",
"core_test_support",
"crossterm",
"filedescriptor",
"flate2",
"futures",
"http 1.4.0",
@@ -5265,6 +5266,7 @@ dependencies = [
"anyhow",
"bytes",
"clap",
"futures",
"h2",
"h3",
"h3-quinn",
@@ -5278,6 +5280,7 @@ dependencies = [
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tokio-tungstenite",
"tower-service",
"url",
]
+2
View File
@@ -83,6 +83,7 @@ codex-utils-path-uri = { workspace = true }
codex-utils-redacted-string = { workspace = true }
codex-websocket-auth = { workspace = true }
crossterm = { workspace = true, features = ["event-stream"] }
filedescriptor = "0.8.3"
futures = { workspace = true }
http = { workspace = true }
libc = { workspace = true }
@@ -96,6 +97,7 @@ supports-color = { workspace = true }
sys-locale = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"fs",
"io-std",
"io-util",
"macros",
+14 -2
View File
@@ -1053,6 +1053,18 @@ fn main() -> anyhow::Result<()> {
})
}
// ProxyCommand needs to send EOF to OpenSSH while it can still read stdin.
// Dropping tokio::io::stdout() leaves the process-wide pipe open. Give the
// relay sole ownership of that pipe and send any later stdout to the null device.
fn ssh_stdout() -> anyhow::Result<tokio::fs::File> {
let null = std::fs::File::create(if cfg!(windows) { "NUL" } else { "/dev/null" })?;
let stdout = filedescriptor::FileDescriptor::redirect_stdio(
&null,
filedescriptor::StdioDescriptor::Stdout,
)?;
Ok(tokio::fs::File::from_std(stdout.as_file()?))
}
async fn dispatch_cli(
arg0_paths: Arg0DispatchPaths,
remote_control_disabled: bool,
@@ -1172,7 +1184,7 @@ async fn dispatch_cli(
)));
}
Some(Subcommand::TcpTunnel(args)) if args.token_file.is_some() => {
codex_tcp_tunnel::run_ssh_proxy_from_file(args, tokio::io::stdout()).await?;
codex_tcp_tunnel::run_ssh_proxy_from_file(args, ssh_stdout()?).await?;
}
Some(Subcommand::TcpTunnel(args)) => {
let config =
@@ -1200,7 +1212,7 @@ async fn dispatch_cli(
.run(codex_tcp_tunnel::run_ssh_proxy(
args,
access_token,
tokio::io::stdout(),
ssh_stdout()?,
))
.await??;
}
+2
View File
@@ -11,6 +11,7 @@ doctest = false
anyhow = { workspace = true }
bytes = { workspace = true }
clap = { workspace = true, features = ["derive"] }
futures = { workspace = true, features = ["std"] }
h2 = "0.4.19"
h3 = { git = "https://github.com/hyperium/h3", rev = "e07e69412876f7e26f026bd75a48b2704d8c8283" }
h3-quinn = { git = "https://github.com/hyperium/h3", rev = "e07e69412876f7e26f026bd75a48b2704d8c8283" }
@@ -22,6 +23,7 @@ rustls = { workspace = true, features = ["ring", "std"] }
rustls-native-certs = { workspace = true }
tokio = { workspace = true, features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] }
tokio-rustls = { workspace = true }
tokio-tungstenite = { workspace = true }
tower-service = "0.3"
url = { workspace = true }
+18 -1
View File
@@ -4,6 +4,23 @@ Use `codex tcp-tunnel --environment-id ENV` as an OpenSSH `ProxyCommand`. The he
When standard HTTPS proxy settings select a proxy, the helper uses that route without attempting direct QUIC. It honors `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`, and supported OS proxy configuration, tunnels to the gateway, and verifies the gateway's TLS certificate before sending the admission credential. Direct TCP races resolved addresses through TLS and HTTP/2 readiness.
Desktop uses the same stdio path with a one-use `--token-file` in a private directory. OAuth uses the environment ID and published port; legacy JWT admission additionally uses `--target IP:PORT`. The helper reads and removes the token file only after verifying the gateway. SSH owns each helper process; multiplexing belongs to OpenSSH ControlMaster.
Native OAuth falls back automatically. Leave `--transport` unset (the default
is `auto`). If HTTP/3 CONNECT is blocked, the TCP attempt can still succeed.
If HTTP/2 CONNECT is also blocked, the helper retries once over WebSocket.
A block means 405, 501, or 403 with `Server: Zscaler/...`. An ordinary 401 or
403 stops setup. If TLS selects HTTP/1.1, the helper uses WebSocket directly.
All attempts share the gateway, proxy, TLS trust, credential and ten-second
deadline. An explicit HTTP proxy must still allow the outer tunnel to the gateway.
For diagnostics, `--transport websocket` forces the upgrade and
`--transport connect` restricts the helper to H3/H2.
The upgrade is a GET to `/v1/tcp-tunnel` with the native OAuth headers and
the `portals-tcp-v1` subprotocol. Each binary message carries up to 64 KiB.
An empty binary message signals EOF in that direction. Either side can finish
writing first. Remote EOF closes the pipe to SSH while any remaining upload
continues. The gateway closes the WebSocket after both directions finish.
Desktop uses the same stdio path with a one-use `--token-file` in a private directory. OAuth uses the environment ID and published port. Legacy JWT admission uses `--target IP:PORT` and stays on CONNECT. The helper reads and removes the token file only after verifying the gateway. SSH owns each helper process. Multiplexing belongs to OpenSSH ControlMaster.
On Linux, run `codex-rs/tcp-tunnel/tests/real-ssh.sh` to verify a complete upload and a remote exit with local stdin still open through a real OpenSSH server and HTTP/3 tunnel. It requires OpenSSH, Python, `timeout`, and the normal Rust test tools.
+6 -119
View File
@@ -1,11 +1,7 @@
//! TLS HTTP/2 CONNECT transport for the same trusted proxy origin as HTTP/3.
//! Each connection carries one CONNECT and preserves TCP half-close and bounded buffering.
//! HTTP/2 CONNECT admission and byte relay with bounded buffering and independent half-close.
use std::future::Future;
use std::future::poll_fn;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
use anyhow::Context;
@@ -14,129 +10,21 @@ use anyhow::anyhow;
use anyhow::ensure;
use bytes::Bytes;
use http::Request;
use hyper_util::client::legacy::connect::proxy::Tunnel;
use hyper_util::client::proxy::matcher::Intercept;
use hyper_util::client::proxy::matcher::Matcher;
use hyper_util::rt::TokioIo;
use rustls::pki_types::ServerName;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tower_service::Service;
use crate::MAX_FIELD_SECTION_SIZE;
use crate::ProxyTarget;
use crate::SetupError;
use crate::tcp;
const COPY_BUFFER_SIZE: usize = 64 * 1024;
pub(super) type Sender = h2::client::SendRequest<Bytes>;
pub(super) trait GatewayIo: AsyncRead + AsyncWrite + Send + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin> GatewayIo for T {}
pub(super) type Connection =
h2::client::Connection<tokio_rustls::client::TlsStream<Box<dyn GatewayIo>>, Bytes>;
pub(super) type Connection = h2::client::Connection<tcp::Stream, Bytes>;
pub(super) async fn connect(
target: &ProxyTarget,
tls: Arc<rustls::ClientConfig>,
) -> Result<(Sender, Connection)> {
let addresses: Vec<_> = tokio::net::lookup_host((target.host.as_str(), target.port))
.await?
.collect();
connect_addresses(target, tls, &addresses).await
}
pub(super) fn system_proxy(target: &ProxyTarget) -> Result<Option<(http::Uri, Intercept)>> {
let uri = gateway_uri(target)?;
Ok(Matcher::from_system()
.intercept(&uri)
.map(|proxy| (uri, proxy)))
}
async fn connect_addresses(
target: &ProxyTarget,
tls: Arc<rustls::ClientConfig>,
addresses: &[SocketAddr],
) -> Result<(Sender, Connection)> {
let name = ServerName::try_from(target.host.clone())
.map_err(|_| anyhow!("invalid proxy TLS server name"))?;
let connector = TlsConnector::from(tls);
let mut attempts = tokio::task::JoinSet::new();
for &address in addresses {
let connector = connector.clone();
let name = name.clone();
attempts.spawn(async move {
let socket = TcpStream::connect(address).await?;
socket.set_nodelay(/*nodelay*/ true)?;
handshake(Box::new(socket), connector, name).await
});
}
let mut invalid_certificate = false;
while let Some(result) = attempts.join_next().await {
match result {
Ok(Ok(connection)) => return Ok(connection),
Ok(Err(error)) => {
invalid_certificate |= error.chain().any(|cause| {
matches!(
cause.downcast_ref::<rustls::Error>(),
Some(rustls::Error::InvalidCertificate(_))
)
});
}
_ => {}
}
}
if invalid_certificate {
return Err(anyhow!("HTTP/2 proxy certificate verification failed"));
}
Err(anyhow!("HTTP/2 proxy connection failed"))
}
fn gateway_uri(target: &ProxyTarget) -> Result<http::Uri> {
let host = if target.host.contains(':') {
format!("[{}]", target.host)
} else {
target.host.clone()
};
Ok(format!("https://{host}:{}/", target.port).parse()?)
}
pub(super) async fn connect_through_proxy(
target: &ProxyTarget,
tls: Arc<rustls::ClientConfig>,
uri: http::Uri,
proxy: Intercept,
) -> Result<(Sender, Connection)> {
ensure!(
matches!(proxy.uri().scheme_str(), Some("http" | "https")),
"unsupported HTTPS proxy scheme"
);
let mut proxy_tls = (*tls).clone();
proxy_tls.alpn_protocols.clear();
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(proxy_tls)
.https_or_http()
.enable_http1()
.build();
let mut tunnel = Tunnel::new(proxy.uri().clone(), connector);
if let Some(auth) = proxy.basic_auth() {
tunnel = tunnel.with_auth(auth.clone());
}
let socket = TokioIo::new(tunnel.call(uri).await?);
let name = ServerName::try_from(target.host.clone())
.map_err(|_| anyhow!("invalid proxy TLS server name"))?;
handshake(Box::new(socket), TlsConnector::from(tls), name).await
}
async fn handshake(
socket: Box<dyn GatewayIo>,
connector: TlsConnector,
name: ServerName<'static>,
) -> Result<(Sender, Connection)> {
let stream = connector.connect(name, socket).await?;
pub(super) async fn handshake(stream: tcp::Stream) -> Result<(Sender, Connection)> {
ensure!(
stream.get_ref().1.alpn_protocol() == Some(b"h2"),
"proxy did not negotiate HTTP/2"
@@ -176,10 +64,9 @@ pub(super) async fn admit(
.send_request(request, /*end_of_stream*/ false)
.map_err(|_| stream_error())?;
let response = response.await.map_err(|_| stream_error())?;
let status = response.status();
if !status.is_success() {
if !response.status().is_success() {
send.send_reset(h2::Reason::CANCEL);
return Err(SetupError::Rejected(status).into());
return Err(SetupError::connect_rejection(&response).into());
}
Ok((send, response.into_body()))
}
+25 -5
View File
@@ -20,9 +20,21 @@ use tokio::net::TcpListener;
use tokio::time::timeout;
use tokio_rustls::TlsAcceptor;
use super::connect_addresses as connect;
use super::connect_through_proxy;
use super::gateway_uri;
use crate::tcp::gateway_uri;
async fn connect(
target: &crate::ProxyTarget,
tls: Arc<rustls::ClientConfig>,
addresses: &[std::net::SocketAddr],
) -> Result<(super::Sender, super::Connection)> {
let Connection::Http2(sender, connection) =
crate::tcp::connect_addresses(target, tls, addresses, crate::transport::Mode::Connect)
.await?
else {
anyhow::bail!("expected HTTP/2")
};
Ok((sender, *connection))
}
use crate::ProxyTarget;
use crate::SetupError;
use crate::transport::Connection;
@@ -244,8 +256,16 @@ async fn proxy_only_egress_keeps_gateway_credentials_inside_tls() -> Result<()>
.build()
.intercept(&uri)
.unwrap();
let (sender, mut connection) =
connect_through_proxy(&target, Arc::new(client), uri, intercept).await?;
let Connection::Http2(sender, mut connection) = crate::tcp::connect(
&target,
&client,
Some((uri, intercept)),
crate::transport::Mode::Connect,
)
.await?
else {
anyhow::bail!("expected HTTP/2")
};
let request =
target.request(HeaderMap::new(), HeaderValue::from_static("Bearer fixture"))?;
let result = tokio::select! {
+39 -6
View File
@@ -30,7 +30,9 @@ use url::Url;
mod http2;
mod ssh;
mod tcp;
mod transport;
mod websocket;
pub use ssh::run_ssh_proxy;
pub use ssh::run_ssh_proxy_from_file;
@@ -56,18 +58,50 @@ pub struct Args {
/// One-use bearer in a private file, supplied by Desktop. Never read from SSH stdin.
#[arg(long)]
pub token_file: Option<PathBuf>,
/// Select the tunnel transport. WebSocket requires native OAuth.
#[arg(long, value_enum, default_value_t = transport::Mode::Auto)]
transport: transport::Mode,
}
#[derive(Debug)]
enum SetupError {
Timeout,
Rejected(StatusCode),
ConnectBlocked(StatusCode),
UpgradeRejected(StatusCode),
}
impl SetupError {
fn connect_rejection<B>(response: &http::Response<B>) -> Self {
let status = response.status();
// An ordinary 403 is an admission decision. Only retry an unsupported
// method or the recognizable intermediary block response.
if matches!(
status,
StatusCode::METHOD_NOT_ALLOWED | StatusCode::NOT_IMPLEMENTED
) || (status == StatusCode::FORBIDDEN
&& response
.headers()
.get(header::SERVER)
.is_some_and(|v| v.as_bytes().starts_with(b"Zscaler/")))
{
Self::ConnectBlocked(status)
} else {
Self::Rejected(status)
}
}
}
impl fmt::Display for SetupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Timeout => f.write_str("SSH tunnel setup timed out"),
Self::Rejected(status) => write!(f, "CONNECT rejected with status {}", status.as_u16()),
Self::UpgradeRejected(status) => write!(
f,
"WebSocket upgrade rejected with status {}",
status.as_u16()
),
Self::Rejected(status) | Self::ConnectBlocked(status) => {
write!(f, "CONNECT rejected with status {}", status.as_u16())
}
}
}
}
@@ -188,13 +222,12 @@ impl ProxyConnection {
type H3Stream = h3::client::RequestStream<h3_quinn::BidiStream<Bytes>, Bytes>;
async fn check_h3_response(stream: &mut H3Stream) -> Result<()> {
let status = stream
let response = stream
.recv_response()
.await
.context("receiving CONNECT response")?
.status();
if !status.is_success() {
return Err(SetupError::Rejected(status).into());
.context("receiving CONNECT response")?;
if !response.status().is_success() {
return Err(SetupError::connect_rejection(&response).into());
}
Ok(())
}
+16 -4
View File
@@ -113,10 +113,19 @@ pub async fn run_ssh_proxy(
stdout: impl AsyncWrite + Unpin,
) -> Result<()> {
let (target, headers) = args.ssh_destination()?;
let mode = match (args.target, args.transport) {
(Some(_), super::transport::Mode::Websocket) => {
anyhow::bail!("WebSocket requires native OAuth")
}
(Some(_), _) => super::transport::Mode::Connect,
(None, mode) => mode,
};
let tunnel = TransportConfig::new(super::tls_config()?)?
.open(&target, async {
target.request(headers, oauth_bearer(&access_token.await?)?)
})
.open(
&target,
async { target.request(headers, oauth_bearer(&access_token.await?)?) },
mode,
)
.await
.map_err(safe_tunnel_error)?;
@@ -159,8 +168,11 @@ pub async fn run_ssh_proxy(
fn safe_tunnel_error(err: anyhow::Error) -> anyhow::Error {
match err.downcast_ref::<SetupError>() {
Some(SetupError::Rejected(status)) => SetupError::Rejected(*status).into(),
Some(SetupError::Rejected(status) | SetupError::ConnectBlocked(status)) => {
SetupError::Rejected(*status).into()
}
Some(SetupError::Timeout) => SetupError::Timeout.into(),
Some(SetupError::UpgradeRejected(status)) => SetupError::UpgradeRejected(*status).into(),
_ => anyhow::anyhow!("SSH tunnel stream failed"),
}
}
+135
View File
@@ -0,0 +1,135 @@
//! Dial the verified gateway, respecting the system proxy and racing direct addresses through protocol readiness.
use std::net::SocketAddr;
use std::sync::Arc;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::ensure;
use hyper_util::client::legacy::connect::proxy::Tunnel;
use hyper_util::client::proxy::matcher::Intercept;
use hyper_util::client::proxy::matcher::Matcher;
use hyper_util::rt::TokioIo;
use rustls::pki_types::ServerName;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tower_service::Service;
use crate::ProxyTarget;
use crate::transport::Connection;
use crate::transport::Mode;
/// A direct TCP socket or a stream through the configured HTTPS proxy.
pub(super) trait GatewayIo: AsyncRead + AsyncWrite + Send + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin> GatewayIo for T {}
pub(super) type Stream = tokio_rustls::client::TlsStream<Box<dyn GatewayIo>>;
pub(super) fn system_proxy(target: &ProxyTarget) -> Result<Option<(http::Uri, Intercept)>> {
let uri = gateway_uri(target)?;
Ok(Matcher::from_system()
.intercept(&uri)
.map(|proxy| (uri, proxy)))
}
pub(super) async fn connect(
target: &ProxyTarget,
tls: &rustls::ClientConfig,
proxy: Option<(http::Uri, Intercept)>,
mode: Mode,
) -> Result<Connection> {
let mut tls = tls.clone();
tls.alpn_protocols = match mode {
Mode::Auto => vec![b"h2".to_vec(), b"http/1.1".to_vec()],
Mode::Connect => vec![b"h2".to_vec()],
Mode::Websocket => vec![b"http/1.1".to_vec()],
};
let tls = Arc::new(tls);
if let Some((uri, proxy)) = proxy {
return Connection::ready(connect_through_proxy(target, tls, uri, proxy).await?, mode)
.await;
}
let addresses: Vec<_> = tokio::net::lookup_host((target.host.as_str(), target.port))
.await?
.collect();
connect_addresses(target, tls, &addresses, mode).await
}
pub(super) async fn connect_addresses(
target: &ProxyTarget,
tls: Arc<rustls::ClientConfig>,
addresses: &[SocketAddr],
mode: Mode,
) -> Result<Connection> {
let name = ServerName::try_from(target.host.clone())
.map_err(|_| anyhow!("invalid proxy TLS server name"))?;
let connector = TlsConnector::from(tls);
let mut attempts = tokio::task::JoinSet::new();
for &address in addresses {
let connector = connector.clone();
let name = name.clone();
attempts.spawn(async move {
let socket = TcpStream::connect(address).await?;
socket.set_nodelay(/*nodelay*/ true)?;
let socket: Box<dyn GatewayIo> = Box::new(socket);
let stream = connector.connect(name, socket).await?;
Connection::ready(stream, mode).await
});
}
let mut invalid_certificate = false;
while let Some(result) = attempts.join_next().await {
match result {
Ok(Ok(connection)) => return Ok(connection),
Ok(Err(error)) => {
invalid_certificate |= error.chain().any(|cause| {
matches!(
cause.downcast_ref::<rustls::Error>(),
Some(rustls::Error::InvalidCertificate(_))
)
});
}
_ => {}
}
}
if invalid_certificate {
return Err(anyhow!("proxy certificate verification failed"));
}
Err(anyhow!("proxy connection failed"))
}
pub(super) fn gateway_uri(target: &ProxyTarget) -> Result<http::Uri> {
let host = if target.host.contains(':') {
format!("[{}]", target.host)
} else {
target.host.clone()
};
Ok(format!("https://{host}:{}/", target.port).parse()?)
}
async fn connect_through_proxy(
target: &ProxyTarget,
tls: Arc<rustls::ClientConfig>,
uri: http::Uri,
proxy: Intercept,
) -> Result<Stream> {
ensure!(
matches!(proxy.uri().scheme_str(), Some("http" | "https")),
"unsupported HTTPS proxy scheme"
);
let mut proxy_tls = (*tls).clone();
proxy_tls.alpn_protocols.clear();
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(proxy_tls)
.https_or_http()
.enable_http1()
.build();
let mut tunnel = Tunnel::new(proxy.uri().clone(), connector);
if let Some(auth) = proxy.basic_auth() {
tunnel = tunnel.with_auth(auth.clone());
}
let socket = TokioIo::new(tunnel.call(uri).await?);
let name = ServerName::try_from(target.host.clone())
.map_err(|_| anyhow!("invalid proxy TLS server name"))?;
let socket: Box<dyn GatewayIo> = Box::new(socket);
Ok(TlsConnector::from(tls).connect(name, socket).await?)
}
+81 -30
View File
@@ -1,4 +1,4 @@
//! Select the first authenticated CONNECT, preferring QUIC with a short head start.
//! Select an admitted tunnel before reading SSH bytes. QUIC gets a short head start.
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
@@ -17,13 +17,23 @@ use crate::ProxyConnection;
use crate::ProxyTarget;
use crate::SetupError;
use crate::http2;
use crate::tcp;
use crate::websocket;
#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
pub(super) enum Mode {
#[default]
Auto,
Connect,
Websocket,
}
const QUIC_HEAD_START: Duration = Duration::from_millis(250);
#[derive(Clone)]
pub(super) struct Config {
quic: quinn::ClientConfig,
tls: Arc<rustls::ClientConfig>,
tls: rustls::ClientConfig,
}
impl Config {
@@ -36,11 +46,7 @@ impl Config {
transport.max_idle_timeout(Some(Duration::from_secs(30).try_into()?));
transport.keep_alive_interval(Some(Duration::from_secs(10)));
quic.transport_config(Arc::new(transport));
tls.alpn_protocols = vec![b"h2".to_vec()];
Ok(Self {
quic,
tls: Arc::new(tls),
})
Ok(Self { quic, tls })
}
/// The request future is polled only after a gateway has passed TLS verification.
@@ -48,31 +54,54 @@ impl Config {
&self,
target: &ProxyTarget,
request: impl Future<Output = Result<Request<()>>>,
mode: Mode,
) -> Result<Tunnel> {
tokio::time::timeout(PROXY_CONNECT_TIMEOUT, async {
if let Some((uri, proxy)) = http2::system_proxy(target)? {
let (sender, connection) =
http2::connect_through_proxy(target, self.tls.clone(), uri, proxy).await?;
return Connection::Http2(sender, Box::new(connection))
.admit(request.await?)
.await;
let proxy = tcp::system_proxy(target)?;
let dial = |mode| tcp::connect(target, &self.tls, proxy.clone(), mode);
if matches!(mode, Mode::Websocket) {
return dial(mode).await?.admit(request.await?).await;
}
let admit = async |connection: Connection, request: Request<()>| {
// The TCP attempt owns the sole WebSocket retry. A blocked H3
// CONNECT leaves that attempt in the race.
let retry = (matches!(mode, Mode::Auto)
&& matches!(connection, Connection::Http2(..)))
.then(|| request.clone());
match connection.admit(request).await {
Err(error)
if matches!(
error.downcast_ref::<SetupError>(),
Some(SetupError::ConnectBlocked(_))
) =>
{
let Some(request) = retry else {
return Err(error);
};
dial(Mode::Websocket).await?.admit(request).await
}
result => result,
}
};
let tcp = async {
if proxy.is_none() {
tokio::time::sleep(QUIC_HEAD_START).await;
}
dial(mode).await
};
if proxy.is_some() {
return admit(tcp.await?, request.await?).await;
}
let quic = async {
ProxyConnection::connect(target, &self.quic)
.await
.map(|p| Connection::Http3(Box::new(p)))
};
let tcp = async {
tokio::time::sleep(QUIC_HEAD_START).await;
http2::connect(target, self.tls.clone())
.await
.map(|(sender, connection)| Connection::Http2(sender, Box::new(connection)))
};
tokio::pin!(quic, tcp);
tokio::select! {
biased;
first = &mut quic => finish_setup(first, tcp, request).await,
first = &mut tcp => finish_setup(first, quic, request).await,
first = &mut quic => finish_setup(first, tcp, request, admit, mode).await,
first = &mut tcp => finish_setup(first, quic, request, admit, mode).await,
}
})
.await
@@ -84,32 +113,37 @@ async fn finish_setup(
first: Result<Connection>,
other: impl Future<Output = Result<Connection>>,
request: impl Future<Output = Result<Request<()>>>,
admit: impl AsyncFn(Connection, Request<()>) -> Result<Tunnel>,
mode: Mode,
) -> Result<Tunnel> {
let first = match first {
Ok(connection) => connection,
Err(_) => return other.await?.admit(request.await?).await,
Err(_) => return admit(other.await?, request.await?).await,
};
let request = request.await?;
let preferred = first.admit(request.clone());
let alternate = async { other.await?.admit(request).await };
let preferred = admit(first, request.clone());
let alternate = async { admit(other.await?, request).await };
tokio::pin!(preferred, alternate);
tokio::select! {
biased;
result = &mut preferred => complete_or_try_other(result, alternate).await,
result = &mut alternate => complete_or_try_other(result, preferred).await,
result = &mut preferred => complete_or_try_other(result, alternate, mode).await,
result = &mut alternate => complete_or_try_other(result, preferred, mode).await,
}
}
async fn complete_or_try_other(
result: Result<Tunnel>,
other: impl Future<Output = Result<Tunnel>>,
mode: Mode,
) -> Result<Tunnel> {
match result {
Ok(tunnel) => Ok(tunnel),
Err(error)
if error
.downcast_ref::<SetupError>()
.is_some_and(|c| matches!(c, SetupError::Rejected(_))) =>
if error.downcast_ref::<SetupError>().is_some_and(|c| match c {
SetupError::Rejected(_) | SetupError::UpgradeRejected(_) => true,
SetupError::ConnectBlocked(_) => !matches!(mode, Mode::Auto),
SetupError::Timeout => false,
}) =>
{
Err(error)
}
@@ -120,9 +154,11 @@ async fn complete_or_try_other(
pub(super) enum Connection {
Http3(Box<ProxyConnection>),
Http2(http2::Sender, Box<http2::Connection>),
WebSocket(Box<tcp::Stream>),
}
pub(super) enum Tunnel {
WebSocket(Box<websocket::Socket>),
Http3(Box<(ProxyConnection, crate::H3Stream)>),
Http2 {
connection: Box<http2::Connection>,
@@ -132,8 +168,22 @@ pub(super) enum Tunnel {
}
impl Connection {
pub(super) async fn ready(stream: tcp::Stream, mode: Mode) -> Result<Self> {
match stream.get_ref().1.alpn_protocol() {
Some(b"h2") => {
let (sender, connection) = http2::handshake(stream).await?;
Ok(Self::Http2(sender, Box::new(connection)))
}
Some(b"http/1.1") | None if !matches!(mode, Mode::Connect) => {
Ok(Self::WebSocket(Box::new(stream)))
}
_ => Err(anyhow!("unsupported gateway ALPN")),
}
}
pub(super) async fn admit(self, request: Request<()>) -> Result<Tunnel> {
match self {
Self::WebSocket(stream) => websocket::admit(*stream, request).await,
Self::Http3(mut proxy) => {
let admit = async {
let mut stream = proxy
@@ -172,6 +222,7 @@ impl Tunnel {
output: impl AsyncWrite + Unpin,
) -> Result<()> {
match self {
Self::WebSocket(socket) => websocket::relay(*socket, input, output).await,
Self::Http3(tunnel) => {
let (mut proxy, stream) = *tunnel;
let forward = crate::bridge_h3_stream(input, output, stream);
@@ -208,4 +259,4 @@ impl Tunnel {
#[cfg(test)]
#[path = "transport_tests.rs"]
mod tests;
pub(crate) mod tests;
+48 -19
View File
@@ -20,7 +20,7 @@ use super::Tunnel;
use crate::http2::tests::target;
use crate::http2::tests::tls_configs;
async fn sockets() -> Result<(TcpListener, UdpSocket)> {
pub(crate) async fn sockets() -> Result<(TcpListener, UdpSocket)> {
for _ in 0..32 {
let tcp = TcpListener::bind("127.0.0.1:0").await?;
if let Ok(udp) = UdpSocket::bind(tcp.local_addr()?) {
@@ -72,7 +72,11 @@ async fn prefers_admitted_quic_without_opening_tcp() -> Result<()> {
Ok::<_, anyhow::Error>(())
});
let tunnel = Config::new(client)?
.open(&target(address), async { request(address) })
.open(
&target(address),
async { request(address) },
super::Mode::Auto,
)
.await?;
assert!(matches!(tunnel, Tunnel::Http3(_)));
assert!(
@@ -94,7 +98,11 @@ async fn blocked_udp_uses_admitted_h2() -> Result<()> {
let address = tcp.local_addr()?;
let peer = tokio::spawn(h2_peer(tcp, tls));
let tunnel = Config::new(client)?
.open(&target(address), async { request(address) })
.open(
&target(address),
async { request(address) },
super::Mode::Auto,
)
.await?;
assert!(matches!(tunnel, Tunnel::Http2 { .. }));
drop(tunnel);
@@ -116,7 +124,11 @@ async fn quic_handshake_without_working_http3_does_not_defeat_h2() -> Result<()>
});
let h2 = tokio::spawn(h2_peer(tcp, tls));
let tunnel = Config::new(client)?
.open(&target(address), async { request(address) })
.open(
&target(address),
async { request(address) },
super::Mode::Auto,
)
.await?;
assert!(matches!(tunnel, Tunnel::Http2 { .. }));
drop(tunnel);
@@ -127,25 +139,34 @@ async fn quic_handshake_without_working_http3_does_not_defeat_h2() -> Result<()>
.await?
}
pub(crate) async fn reject_h3(
udp: UdpSocket,
tls: rustls::ServerConfig,
response: Response<()>,
) -> Result<()> {
let endpoint = endpoint(udp, tls)?;
let quic = endpoint.accept().await.unwrap().await?;
let mut http: h3::server::Connection<_, Bytes> =
h3::server::Connection::new(h3_quinn::Connection::new(quic.clone())).await?;
let (_, mut stream) = http.accept().await?.unwrap().resolve_request().await?;
stream.send_response(response).await?;
quic.closed().await;
Ok(())
}
#[tokio::test]
async fn admission_rejection_is_terminal() -> Result<()> {
let (tls, client) = tls_configs()?;
let (tcp, udp) = sockets().await?;
let address = tcp.local_addr()?;
let endpoint = endpoint(udp, tls)?;
let peer = tokio::spawn(async move {
let quic = endpoint.accept().await.unwrap().await?;
let mut http: h3::server::Connection<_, Bytes> =
h3::server::Connection::new(h3_quinn::Connection::new(quic.clone())).await?;
let (_, mut stream) = http.accept().await?.unwrap().resolve_request().await?;
stream
.send_response(Response::builder().status(StatusCode::FORBIDDEN).body(())?)
.await?;
quic.closed().await;
Ok::<_, anyhow::Error>(())
});
let response = Response::builder().status(StatusCode::FORBIDDEN).body(())?;
let peer = tokio::spawn(reject_h3(udp, tls, response));
let error = Config::new(client)?
.open(&target(address), async { request(address) })
.open(
&target(address),
async { request(address) },
super::Mode::Auto,
)
.await
.err()
.unwrap();
@@ -187,7 +208,11 @@ async fn setup_deadline_includes_connect_response() -> Result<()> {
});
let result = timeout(
crate::PROXY_CONNECT_TIMEOUT + Duration::from_secs(2),
Config::new(client)?.open(&target(address), async { request(address) }),
Config::new(client)?.open(
&target(address),
async { request(address) },
super::Mode::Auto,
),
)
.await?;
assert!(matches!(
@@ -313,7 +338,11 @@ async fn real_ssh_case(remote_exits_early: bool) -> Result<()> {
});
let (socket, _) = front.accept().await?;
let tunnel = Config::new(client)?
.open(&target(address), async { request(address) })
.open(
&target(address),
async { request(address) },
super::Mode::Auto,
)
.await?;
assert!(matches!(tunnel, Tunnel::Http3(_)));
let (input, output) = socket.into_split();
+125
View File
@@ -0,0 +1,125 @@
//! Native TCP over an authenticated HTTP/1.1 WebSocket. One binary message
//! carries bytes; an empty binary message half-closes that direction.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use bytes::Bytes;
use futures::SinkExt;
use futures::StreamExt;
use http::Request;
use http::header::SEC_WEBSOCKET_PROTOCOL;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::client_async_with_config;
use tokio_tungstenite::tungstenite::Error;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use crate::SetupError;
use crate::tcp;
use crate::transport::Tunnel;
const PROTOCOL: &str = "portals-tcp-v1";
const CHUNK: usize = 64 * 1024;
pub(super) type Socket = WebSocketStream<tcp::Stream>;
pub(super) fn native(request: &Request<()>) -> bool {
request
.headers()
.get("x-portals-auth-mode")
.is_some_and(|v| v == "oauth")
}
pub(super) async fn admit(stream: tcp::Stream, request: Request<()>) -> Result<Tunnel> {
ensure!(native(&request), "WebSocket requires native OAuth");
let authority = request
.uri()
.authority()
.context("missing gateway authority")?;
let mut upgrade = format!("wss://{authority}/v1/tcp-tunnel").into_client_request()?;
upgrade.headers_mut().extend(request.into_parts().0.headers);
upgrade.headers_mut().insert(
SEC_WEBSOCKET_PROTOCOL,
http::HeaderValue::from_static(PROTOCOL),
);
let config = WebSocketConfig::default()
.max_message_size(Some(CHUNK))
.max_frame_size(Some(CHUNK));
// Handshake on the already verified socket. Never follow redirects or
// let the WebSocket library select a different proxy or trust store.
match client_async_with_config(upgrade, stream, Some(config)).await {
Ok((socket, _)) => Ok(Tunnel::WebSocket(Box::new(socket))),
Err(Error::Http(response)) => Err(SetupError::UpgradeRejected(response.status()).into()),
Err(_) => bail!("WebSocket handshake failed"),
}
}
pub(super) async fn relay(
socket: Socket,
mut input: impl AsyncRead + Unpin,
output: impl AsyncWrite + Unpin,
) -> Result<()> {
let (mut tx, mut rx) = socket.split();
let upload = async {
let mut buf = vec![0; CHUNK];
loop {
let n = input.read(&mut buf).await?;
tx.send(Message::Binary(Bytes::copy_from_slice(&buf[..n])))
.await?;
if n == 0 {
return Ok::<(), anyhow::Error>(());
}
}
};
let download = async {
let mut output = Some(output);
while let Some(message) = rx.next().await {
match message? {
Message::Binary(data) if data.is_empty() => {
// Drop the writer to signal EOF on pipes. Keep servicing ping and
// close frames while the other direction finishes.
let mut writer = output.take().context("duplicate tunnel EOF")?;
writer.shutdown().await?;
}
Message::Binary(data) => {
let output = output.as_mut().context("tunnel data after EOF")?;
output.write_all(&data).await?;
output.flush().await?;
}
// Tungstenite queues the pong and flushes on the next read.
Message::Ping(_) | Message::Pong(_) => {}
Message::Close(frame)
if output.is_none()
&& frame.as_ref().is_none_or(|f| f.code == CloseCode::Normal) =>
{
return Ok(());
}
Message::Text(_) | Message::Frame(_) | Message::Close(_) => {
bail!("unexpected tunnel message")
}
}
}
bail!("tunnel closed without EOF")
};
{
tokio::pin!(upload, download);
tokio::select! {
biased;
result = &mut upload => { result?; download.await?; }
result = &mut download => { result?; bail!("tunnel closed before upload EOF") }
}
}
// Reading the peer's Close queued our reply.
tx.flush().await?;
Ok(())
}
#[cfg(test)]
#[path = "websocket_tests.rs"]
mod tests;
+299
View File
@@ -0,0 +1,299 @@
#![cfg(test)]
//! Exercise fallback and the native wire protocol over real, verified TLS.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use bytes::Bytes;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderMap;
use http::HeaderValue;
use http::Request;
use http::Response;
use http::StatusCode;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::time::timeout;
use tokio_rustls::TlsAcceptor;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server;
use crate::SetupError;
use crate::http2::tests::target;
use crate::http2::tests::tls_configs;
use crate::transport::Config;
use crate::transport::Mode;
use crate::transport::tests::reject_h3;
use crate::transport::tests::sockets;
fn oauth(address: std::net::SocketAddr) -> Result<Request<()>> {
let mut headers = HeaderMap::new();
headers.insert("x-portals-auth-mode", HeaderValue::from_static("oauth"));
headers.insert(
"x-portals-environment-id",
HeaderValue::from_static("ccarenv_a"),
);
headers.insert("x-portals-port", HeaderValue::from_static("22"));
target(address).request(headers, HeaderValue::from_static("Bearer fixture"))
}
async fn reject(tcp: &TcpListener, tls: &TlsAcceptor, server: &'static str) -> Result<()> {
let stream = tls.accept(tcp.accept().await?.0).await?;
assert_eq!(stream.get_ref().1.alpn_protocol(), Some(b"h2".as_slice()));
let mut h2: h2::server::Connection<_, Bytes> = h2::server::handshake(stream).await?;
let (req, mut response) = h2.accept().await.unwrap()?;
assert_eq!(req.method(), http::Method::CONNECT);
response.send_response(
Response::builder()
.status(403)
.header("server", server)
.body(())?,
true,
)?;
let _ = h2.accept().await;
Ok(())
}
#[tokio::test]
async fn blocked_h3_and_h2_fall_back_before_banner_and_preserve_half_close() -> Result<()> {
timeout(Duration::from_secs(5), async {
let (mut tls, client) = tls_configs()?;
tls.alpn_protocols.push(b"http/1.1".to_vec());
let (tcp, udp) = sockets().await?;
let address = tcp.local_addr()?;
let peer = tokio::spawn(async move {
reject_h3(
udp,
tls.clone(),
Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(())?,
)
.await?;
let accept = TlsAcceptor::from(Arc::new(tls));
reject(&tcp, &accept, "Zscaler/6.2").await?;
let stream = accept.accept(tcp.accept().await?.0).await?;
assert_eq!(
stream.get_ref().1.alpn_protocol(),
Some(b"http/1.1".as_slice())
);
let mut ws = accept_hdr_async(
stream,
|req: &server::Request, mut res: server::Response| {
assert_eq!(req.uri().path(), "/v1/tcp-tunnel");
for (name, value) in oauth(address).unwrap().headers() {
assert_eq!(&req.headers()[name], value);
}
assert_eq!(req.headers()["sec-websocket-protocol"], "portals-tcp-v1");
res.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("portals-tcp-v1"),
);
Ok(res)
},
)
.await?;
ws.send(Message::Binary(Bytes::from_static(b"SSH-2.0-test\r\n")))
.await?;
ws.send(Message::Ping(Bytes::from_static(b"alive"))).await?;
let mut data = Vec::new();
let mut pong = false;
while let Some(message) = ws.next().await {
match message? {
Message::Binary(d) if d.is_empty() => break,
Message::Binary(d) => data.extend_from_slice(&d),
Message::Pong(d) => pong = d == b"alive"[..],
_ => anyhow::bail!("unexpected frame"),
}
}
assert!(pong);
assert_eq!(
data,
(0..=255).cycle().take(256 * 1024).collect::<Vec<u8>>()
);
ws.send(Message::Binary(Bytes::from_static(b"after-fin")))
.await?;
ws.send(Message::Binary(Bytes::new())).await?;
ws.close(None).await?;
Ok::<_, anyhow::Error>(())
});
let tunnel = Config::new(client)?
.open(&target(address), async { oauth(address) }, Mode::Auto)
.await?;
let (mut local, other) = tokio::io::duplex(4096);
let (rx, tx) = tokio::io::split(other);
let relay = tokio::spawn(tunnel.relay(rx, tx));
let mut banner = [0; 14];
local.read_exact(&mut banner).await?;
assert_eq!(&banner, b"SSH-2.0-test\r\n");
local
.write_all(&(0..=255).cycle().take(256 * 1024).collect::<Vec<u8>>())
.await?;
local.shutdown().await?;
let mut tail = Vec::new();
local.read_to_end(&mut tail).await?;
assert_eq!(tail, b"after-fin");
relay.await??;
peer.await??;
Ok::<_, anyhow::Error>(())
})
.await?
}
#[tokio::test]
async fn backend_eof_still_allows_upload() -> Result<()> {
timeout(Duration::from_secs(5), async {
let (mut tls, client) = tls_configs()?;
tls.alpn_protocols = vec![b"http/1.1".to_vec()];
let tcp = TcpListener::bind("127.0.0.1:0").await?;
let address = tcp.local_addr()?;
let (pong_sent, pong_received) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let stream = TlsAcceptor::from(Arc::new(tls))
.accept(tcp.accept().await?.0)
.await?;
let mut ws =
accept_hdr_async(stream, |_: &server::Request, mut res: server::Response| {
res.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("portals-tcp-v1"),
);
Ok(res)
})
.await?;
ws.send(Message::Binary(Bytes::new())).await?;
ws.send(Message::Ping(Bytes::from_static(b"alive"))).await?;
assert_eq!(
ws.next().await.unwrap()?,
Message::Pong(Bytes::from_static(b"alive"))
);
pong_sent.send(()).unwrap();
let mut received = Vec::new();
loop {
match ws.next().await.unwrap()? {
Message::Binary(data) if data.is_empty() => break,
Message::Binary(data) => received.extend_from_slice(&data),
_ => anyhow::bail!("unexpected frame"),
}
}
ws.close(None).await?;
assert!(matches!(ws.next().await, Some(Ok(Message::Close(_)))));
Ok::<_, anyhow::Error>(received)
});
let tunnel = Config::new(client)?
.open(&target(address), async { oauth(address) }, Mode::Websocket)
.await?;
let (mut local, other) = tokio::io::duplex(4096);
let (rx, tx) = tokio::io::split(other);
let relay = tokio::spawn(tunnel.relay(rx, tx));
assert_eq!(local.read(&mut [0]).await?, 0);
pong_received.await?;
let payload = (0..=255).cycle().take(256 * 1024).collect::<Vec<u8>>();
local.write_all(&payload).await?;
local.shutdown().await?;
assert_eq!(peer.await??, payload);
relay.await??;
Ok::<_, anyhow::Error>(())
})
.await?
}
#[tokio::test]
async fn gateway_forbidden_does_not_retry() -> Result<()> {
let (mut tls, client) = tls_configs()?;
tls.alpn_protocols.push(b"http/1.1".to_vec());
let accept = TlsAcceptor::from(Arc::new(tls));
let tcp = TcpListener::bind("127.0.0.1:0").await?;
let address = tcp.local_addr()?;
let peer = tokio::spawn(async move {
reject(&tcp, &accept, "envoy").await?;
assert!(
timeout(Duration::from_millis(100), tcp.accept())
.await
.is_err()
);
Ok::<_, anyhow::Error>(())
});
let err = Config::new(client)?
.open(&target(address), async { oauth(address) }, Mode::Auto)
.await
.err()
.unwrap();
assert!(matches!(
err.downcast_ref::<SetupError>(),
Some(SetupError::Rejected(StatusCode::FORBIDDEN))
));
peer.await??;
Ok(())
}
#[tokio::test]
async fn forced_websocket_verifies_tls_before_reading_credentials() -> Result<()> {
let (mut untrusted, _) = tls_configs()?;
let (_, client) = tls_configs()?;
untrusted.alpn_protocols = vec![b"http/1.1".to_vec()];
let tcp = TcpListener::bind("127.0.0.1:0").await?;
let address = tcp.local_addr()?;
let peer = tokio::spawn(async move {
let socket = tcp.accept().await.unwrap().0;
assert!(
TlsAcceptor::from(Arc::new(untrusted))
.accept(socket)
.await
.is_err()
);
});
let result = Config::new(client)?
.open(
&target(address),
async { panic!("credential read before certificate validation") },
Mode::Websocket,
)
.await;
assert!(result.is_err());
peer.await?;
Ok(())
}
#[tokio::test]
async fn http1_only_upgrade_does_not_follow_redirects() -> Result<()> {
let (mut tls, client) = tls_configs()?;
tls.alpn_protocols = vec![b"http/1.1".to_vec()];
let tcp = TcpListener::bind("127.0.0.1:0").await?;
let address = tcp.local_addr()?;
let peer = tokio::spawn(async move {
let mut stream = TlsAcceptor::from(Arc::new(tls))
.accept(tcp.accept().await?.0)
.await?;
let mut head = Vec::new();
while !head.ends_with(b"\r\n\r\n") {
head.push(stream.read_u8().await?);
}
assert!(head.starts_with(b"GET /v1/tcp-tunnel HTTP/1.1\r\n"));
stream.write_all(format!("HTTP/1.1 302 Found\r\nLocation: wss://{address}/redirect\r\nContent-Length: 0\r\n\r\n").as_bytes()).await?;
assert!(
timeout(Duration::from_millis(100), tcp.accept())
.await
.is_err()
);
Ok::<_, anyhow::Error>(())
});
let error = timeout(
Duration::from_secs(4),
Config::new(client)?.open(&target(address), async { oauth(address) }, Mode::Auto),
)
.await?
.err()
.unwrap();
assert!(matches!(
error.downcast_ref::<SetupError>(),
Some(SetupError::UpgradeRejected(StatusCode::FOUND))
));
peer.await??;
Ok(())
}