// sandhole: Expose HTTP/SSH/TCP services through SSH port forwarding // Copyright (C) 2024-2026 Eric Rodrigues Pires // // This program is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for // more details. // // You should have received a copy of the GNU Affero General Public License along // with this program. If not, see . use std::{ error::Error, fmt::Debug, marker::PhantomData, net::SocketAddr, pin::Pin, str::FromStr, sync::{Arc, LazyLock}, task::{Context, Poll}, time::{Duration, Instant}, }; pub(crate) mod http11; pub(crate) mod http2; use crate::{ config::LogFormat, connection_handler::ConnectionHandler, connections::ConnectionGetByHttpHost, error::ServerError, http::{http2::handle_http2_request, http11::handle_http11_request}, keepalive::KeepaliveAlias, sock_addr_alias::BorrowedSockAddrAlias, ssh::ServerHandlerSender, telemetry::{ TELEMETRY_COUNTER_ALIAS_CONNECTIONS, TELEMETRY_COUNTER_HTTP_REQUESTS, TELEMETRY_HISTOGRAM_HTTP_ELAPSED_TIME, TELEMETRY_KEY_ALIAS, TELEMETRY_KEY_HOSTNAME, }, }; use ahash::RandomState; use axum::{ body::Body as AxumBody, response::{IntoResponse, Redirect}, }; use bon::Builder; use dashmap::DashMap; use http::uri::InvalidUriParts; use http::{HeaderMap, HeaderName, HeaderValue, Version, uri::InvalidUri}; use hyper::{ Request, Response, StatusCode, body::{Body, Incoming}, client::conn::http1::SendRequest as Http11SendRequest, client::conn::http2::SendRequest as Http2SendRequest, header::HOST, }; use metrics::{counter, histogram}; use owo_colors::{OwoColorize, Stream, Style}; use russh::keys::ssh_key::Fingerprint; use tokio::io::{AsyncRead, AsyncWrite}; static X_FORWARDED_FOR: LazyLock = LazyLock::new(|| HeaderName::from_str("X-Forwarded-For").expect("valid header name")); static X_FORWARDED_HOST: LazyLock = LazyLock::new(|| HeaderName::from_str("X-Forwarded-Host").expect("valid header name")); static X_FORWARDED_PROTO: LazyLock = LazyLock::new(|| HeaderName::from_str("X-Forwarded-Proto").expect("valid header name")); static X_FORWARDED_PORT: LazyLock = LazyLock::new(|| HeaderName::from_str("X-Forwarded-Port").expect("valid header name")); pub(crate) enum ProxyResponse { Axum(Response), Proxy(TimedResponse), } pub(crate) struct TimedResponse { response: Response, on_drop: Option>, } struct TimedResponseBody { body: Incoming, on_drop: Option>, } impl IntoResponse for TimedResponse { fn into_response(self) -> axum::response::Response { let (parts, body) = self.response.into_parts(); Response::from_parts( parts, AxumBody::new(TimedResponseBody { body, on_drop: self.on_drop, }), ) } } impl Body for TimedResponseBody { type Data = bytes::Bytes; type Error = hyper::Error; #[inline] fn poll_frame( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll, Self::Error>>> { Pin::new(&mut self.body).poll_frame(cx) } #[inline] fn size_hint(&self) -> hyper::body::SizeHint { self.body.size_hint() } #[inline] fn is_end_stream(&self) -> bool { self.body.is_end_stream() } } impl Drop for TimedResponseBody { fn drop(&mut self) { if let Some(on_drop) = self.on_drop.take() { (on_drop)(); } } } #[derive(Builder)] struct HttpLog { ip: String, status: u16, method: String, host: String, uri: String, elapsed_time: Duration, } // Pretty-print an HTTP log with ANSI fn http_log( data: HttpLog, tx: Option, disable_http_logs: bool, log_format: LogFormat, ) { let HttpLog { ip, status, method, host, uri, elapsed_time, } = data; histogram!( TELEMETRY_HISTOGRAM_HTTP_ELAPSED_TIME, "method" => method.clone(), "host" => host.clone(), "status_code" => status.to_string(), ) .record(elapsed_time.as_secs_f64()); let status_style = match status { 100..=199 => Style::new().white(), 200..=299 => Style::new().blue(), 300..=399 => Style::new().green(), 400..=499 => Style::new().yellow(), 500..=599 => Style::new().red(), _ => unreachable!(), }; let method_style = match method.as_str() { "POST" => Style::new().black().on_green().bold(), "PUT" | "PATCH" => Style::new().black().on_yellow().bold(), "DELETE" => Style::new().black().on_red().bold(), "HEAD" => Style::new().black().on_cyan().bold(), "OPTIONS" | "CONNECT" | "TRACE" => Style::new().black().on_magenta().bold(), // GET or other _ => Style::new().black().on_blue().bold(), }; let duration = pretty_duration::pretty_duration(&elapsed_time, None); match log_format { LogFormat::Default => { let tracing_line = format!( "{} {} {} => {} {}", format!("[{status}]") .if_supports_color(Stream::Stdout, |text| text.style(status_style)), format!(" {method} ") .if_supports_color(Stream::Stdout, |text| text.style(method_style)), host, uri, format!("({ip}) {duration}") .if_supports_color(Stream::Stdout, |text| text.dimmed()) ); #[cfg(not(coverage_nightly))] tracing::info!("{tracing_line}"); } #[cfg(feature = "duper")] LogFormat::Duper => { let duration_nanos = elapsed_time.as_nanos(); let duper_duration = format!( "Duration('PT{}.{:09}S')", duration_nanos / 1_000_000_000, duration_nanos % 1_000_000_000 ); #[cfg(not(coverage_nightly))] tracing::info!(%status, %method, %host, %uri, %ip, "$duper.duration" = duper_duration, "Proxied HTTP request."); } LogFormat::Json => { #[cfg(not(coverage_nightly))] tracing::info!(%status, %method, %host, %uri, %ip, %duration, "Proxied HTTP request."); } } if !disable_http_logs { let _ = tx.map(|tx| { let colored_line = format!( "{} {} {} {} => {} {}\r\n", jiff::Timestamp::now().to_string().dimmed(), format!("[{status}]").style(status_style), format!(" {method} ").style(method_style), host, uri, format!("({ip}) {duration}").dimmed() ); tx.send(colored_line.into_bytes()) }); } } // Append the bytes to the given comma-separated entry of HeaderMap pub(crate) fn append_to_header( headers: &mut HeaderMap, header_name: &HeaderName, new_value: &[u8], ) { match headers.entry(header_name) { http::header::Entry::Vacant(entry) => { entry.insert(HeaderValue::from_bytes(new_value).expect("valid header value")); } http::header::Entry::Occupied(mut entry) => { let existing = entry.get().as_bytes(); let mut combined_bytes = Vec::with_capacity(existing.len() + 2 + new_value.len()); combined_bytes.extend_from_slice(existing); combined_bytes.extend_from_slice(b", "); combined_bytes.extend_from_slice(new_value); if let Ok(new_val) = HeaderValue::from_bytes(&combined_bytes) { entry.insert(new_val); } } } } pub(crate) enum Protocol { Http { port: u16 }, TlsRedirect { from: u16, to: u16 }, Https { port: u16 }, } pub(crate) struct DomainRedirect { pub(crate) from: String, pub(crate) to: String, } pub(crate) enum ProxyType { Tunneling, Aliasing, } #[derive(thiserror::Error, Debug)] pub(crate) enum HttpError { #[error("Pool closed")] PoolClosed, #[error("Hyper error: {0}")] HyperError(#[from] hyper::Error), #[error("Handler not found")] HandlerNotFound, #[error("No handler available")] NoHandlerAvailable, #[error("Channel request denied")] ChannelRequestDenied, #[error("Header to string error: {0}")] HeaderToStrError(#[from] http::header::ToStrError), #[error("Missing URI host")] MissingUriHost, #[error("Missing Host for request")] MissingHost, #[error("Invalid Host header")] InvalidHostHeader, #[error("Invalid HTTP version {0:?}")] InvalidHttpVersion(Version), #[error("Invalid URI: {0:?}")] InvalidUri(#[from] InvalidUri), #[error("Invalid URI parts: {0:?}")] InvalidUriParts(#[from] InvalidUriParts), #[error("Missing Upgrade header")] MissingUpgradeHeader, #[error("Request timeout")] RequestTimeout, #[error("Internal server error: {0:?}")] InternalError(ServerError), } impl From for HttpError { fn from(value: ServerError) -> Self { match value { // If pool or IP connection limit was reached, return 429 (no handler is available) ServerError::PoolLimitReached | ServerError::IpConnectionLimitReached => { HttpError::NoHandlerAvailable } // If there is an allowlist for fingerprints/IP networks, return 404 ServerError::TunnelingNotAllowed | ServerError::AliasingNotAllowed => { HttpError::ChannelRequestDenied } // Otherwise, return 500 _ => HttpError::InternalError(value), } } } impl IntoResponse for HttpError { fn into_response(self) -> axum::response::Response { if matches!(self, HttpError::HyperError(_) | HttpError::InternalError(_)) { #[cfg(not(coverage_nightly))] tracing::error!(error = %self, "HTTP proxy error."); } else { #[cfg(not(coverage_nightly))] tracing::debug!(error = %self, "HTTP proxy error."); } match self { HttpError::HeaderToStrError(_) | HttpError::MissingUriHost | HttpError::MissingHost | HttpError::InvalidHostHeader | HttpError::InvalidHttpVersion(_) | HttpError::InvalidUri(_) | HttpError::InvalidUriParts(_) | HttpError::MissingUpgradeHeader => StatusCode::BAD_REQUEST, HttpError::NoHandlerAvailable => StatusCode::TOO_MANY_REQUESTS, HttpError::RequestTimeout => StatusCode::GATEWAY_TIMEOUT, HttpError::HandlerNotFound | HttpError::ChannelRequestDenied => StatusCode::NOT_FOUND, HttpError::PoolClosed | HttpError::HyperError(_) | HttpError::InternalError(_) => { StatusCode::INTERNAL_SERVER_ERROR } } .into_response() } } // Wrapper for pooled connections with metadata pub(crate) struct PooledConnection { connection: T, log_sender: ServerHandlerSender, last_used: Instant, reuse_count: usize, } impl PooledConnection { fn new(connection: T, log_sender: ServerHandlerSender) -> Self { Self { connection, log_sender, last_used: Instant::now(), reuse_count: 0, } } fn touch(&mut self) { self.last_used = Instant::now(); self.reuse_count += 1; } fn is_expired(&self, max_idle: Duration, max_reuse: usize) -> bool { self.last_used.elapsed() > max_idle || self.reuse_count >= max_reuse } } type KeepalivePool

= deadpool::unmanaged::Pool

; type Http11KeepalivePool = KeepalivePool>>; type Http2KeepalivePool = KeepalivePool>>; // Pooled connections that can report whether another request fits on them. pub(crate) trait PooledConnectionReady { fn is_ready(&self) -> bool; } impl PooledConnectionReady for Http11SendRequest { fn is_ready(&self) -> bool { Http11SendRequest::is_ready(self) } } impl PooledConnectionReady for Http2SendRequest { fn is_ready(&self) -> bool { Http2SendRequest::is_ready(self) } } // Take a pooled connection that can serve a request right now, discarding // expired or unusable ones as it goes. Dropping a discarded connection closes // its channel, so this must never put a stale connection back. pub(crate) fn take_ready_connection( pool: &KeepalivePool>, max_idle_time: Duration, max_reuse: usize, ) -> Option> { while let Ok(object) = pool.try_get() { let mut pooled = deadpool::unmanaged::Object::take(object); if pooled.connection.is_ready() && !pooled.is_expired(max_idle_time, max_reuse) { pooled.touch(); return Some(pooled); } } None } // Drop every idle connection that outlived its pool limits, closing their // channels. Without this, an idle alias keeps its channels open until another // request for the same alias happens to evict them. pub(crate) fn evict_expired_connections( pool: &KeepalivePool>, max_idle_time: Duration, max_reuse: usize, ) { // Drain the pool before re-adding live connections. Re-adding one while // draining makes `try_get` return it again, spinning until it expires. let mut kept = Vec::new(); while let Ok(object) = pool.try_get() { let pooled = deadpool::unmanaged::Object::take(object); if !pooled.is_expired(max_idle_time, max_reuse) { kept.push(pooled); } } for pooled in kept.into_iter().rev() { let _ = pool.try_add(pooled); } } // Data commonly reused between HTTP proxy requests. #[derive(Builder)] pub(crate) struct ProxyData where M: ConnectionGetByHttpHost> + Send + Sync + 'static, H: ConnectionHandler + Send + Sync + 'static, T: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static, B: Body + Debug + Send + Unpin + 'static, ::Data: Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { // Keep-alive pool for opened HTTP/1.1 connections. #[builder(default = Arc::default())] pub(crate) keepalive_http11_pool_map: Arc, RandomState>>, // Keep-alive pool for opened HTTP/2 connections. #[builder(default = Arc::default())] pub(crate) keepalive_http2_pool_map: Arc, RandomState>>, // Timeout when the server has a queue pool for handlers. pool_queue_timeout: Option, // Maximum size for each connection pool. http_pool_size: usize, // Maximum idle time for pooled connections. http_pool_max_idle_time: Duration, // Maximum number of times a connection can be reused. http_pool_max_reuse: usize, // Connection manager to get handlers from. conn_manager: M, // Tuple containing where to redirect requests from the main domain to. domain_redirect: Option>, // The HTTP protocol for the current connection. protocol: Protocol, // Configuration on which type of channel to retrieve from the handler. proxy_type: ProxyType, // Buffer size for bidirectional copying. buffer_size: usize, // Optional duration until an outgoing request is canceled. http_request_timeout: Option, // Optional duration until an established Websocket connection is canceled. websocket_timeout: Option, // If set, disables sending HTTP logs to the handler. disable_http_logs: bool, // The format to output HTTP logs in. log_format: LogFormat, #[builder(skip)] _phantom_data: PhantomData<(H, T)>, } impl ProxyData where M: ConnectionGetByHttpHost> + Send + Sync + 'static, H: ConnectionHandler + Send + Sync + 'static, T: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static, B: Body + Debug + Send + Unpin + 'static, ::Data: Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { pub(crate) fn conn_manager(&self) -> &M { &self.conn_manager } // Evict pooled connections that outlived their limits, then forget the // aliases left with nothing. Evicting here (instead of only on the next // request for the same alias) closes channels that would otherwise stay // open for as long as the alias stays idle. pub(crate) fn cleanup_keepalive_pools(&self) { self.keepalive_http11_pool_map.retain(|_, pool| { evict_expired_connections(pool, self.http_pool_max_idle_time, self.http_pool_max_reuse); pool.status().available > 0 }); self.keepalive_http2_pool_map.retain(|_, pool| { evict_expired_connections(pool, self.http_pool_max_idle_time, self.http_pool_max_reuse); pool.status().available > 0 }); } } pub(crate) struct Http11PoolGuard { pool: deadpool::unmanaged::Pool>>, max_idle_time: Duration, max_reuse: usize, } pub(crate) struct Http2PoolGuard { pool: deadpool::unmanaged::Pool>>, max_idle_time: Duration, max_reuse: usize, } pub(crate) trait ArcProxyData { fn get_http11_pool_guard(&self, key: KeepaliveAlias) -> Http11PoolGuard; fn get_http2_pool_guard(&self, key: KeepaliveAlias) -> Http2PoolGuard; } impl ArcProxyData for Arc> where M: ConnectionGetByHttpHost> + Send + Sync + 'static, H: ConnectionHandler + Send + Sync + 'static, T: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static, B: Body + Debug + Send + Unpin + 'static, ::Data: Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { fn get_http11_pool_guard(&self, key: KeepaliveAlias) -> Http11PoolGuard { let pool_size = self.http_pool_size; let pool = { let map_ref = self .keepalive_http11_pool_map .entry(key.clone()) .or_insert_with(|| deadpool::unmanaged::Pool::new(pool_size)) .downgrade(); map_ref.clone() }; Http11PoolGuard { pool, max_idle_time: self.http_pool_max_idle_time, max_reuse: self.http_pool_max_reuse, } } fn get_http2_pool_guard(&self, key: KeepaliveAlias) -> Http2PoolGuard { let pool_size = self.http_pool_size; let pool = { let map_ref = self .keepalive_http2_pool_map .entry(key.clone()) .or_insert_with(|| deadpool::unmanaged::Pool::new(pool_size)) .downgrade(); map_ref.clone() }; Http2PoolGuard { pool, max_idle_time: self.http_pool_max_idle_time, max_reuse: self.http_pool_max_reuse, } } } // Receive an HTTP request and appropriately proxy it, with a possible upgrade to WebSocket. #[cfg_attr( not(coverage_nightly), tracing::instrument(skip(proxy_data), level = "debug") )] pub(crate) async fn proxy_handler( request: Request, tcp_address: SocketAddr, fingerprint: Option, proxy_data: Arc>, ) -> color_eyre::Result> where M: ConnectionGetByHttpHost> + Send + Sync + 'static, H: ConnectionHandler + Send + Sync + 'static, T: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static, B: Body + Debug + Send + Unpin + 'static, ::Data: Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { match proxy_handler_inner(request, tcp_address, fingerprint, proxy_data).await { Ok(response) => Ok(match response { ProxyResponse::Axum(response) => response, ProxyResponse::Proxy(response) => response.into_response(), }), Err(error) => Ok(error.into_response()), } } #[inline] pub(crate) async fn proxy_handler_inner( mut request: Request, tcp_address: SocketAddr, fingerprint: Option, proxy_data: Arc>, ) -> Result where M: ConnectionGetByHttpHost> + Send + Sync + 'static, H: ConnectionHandler + Send + Sync + 'static, T: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static, B: Body + Debug + Send + Unpin + 'static, ::Data: Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { let conn_manager = &proxy_data.conn_manager; let domain_redirect = &proxy_data.domain_redirect; let protocol = &proxy_data.protocol; let timer = Instant::now(); // Retrieve host from the headers let host = match request.version() { Version::HTTP_2 => request.uri().host().ok_or(HttpError::MissingUriHost)?, Version::HTTP_11 => match request.headers().get(HOST) { Some(header_value) => match header_value.to_str() { Ok(header) => header .split(':') .next() .ok_or(HttpError::InvalidHostHeader)?, Err(_) => return Err(HttpError::InvalidHostHeader), }, None => return Err(HttpError::MissingHost), }, version => return Err(HttpError::InvalidHttpVersion(version)), }; let host = host.to_owned(); let ip = tcp_address.ip().to_canonical(); // Find the HTTP handler for the given host let Some(handler) = conn_manager.get_by_http_host(&host, ip) else { // If no handler was found, check if this is a request to the root domain if let Some(redirect) = domain_redirect && redirect.from == host { // If so, redirect to the configured URL let response = Redirect::to(&redirect.to).into_response(); http_log( HttpLog::builder() .uri(request.uri().path().to_string()) .method(request.method().to_string()) .host(host) .ip(ip.to_string()) .status(response.status().as_u16()) .elapsed_time(timer.elapsed()) .build(), None, proxy_data.disable_http_logs, proxy_data.log_format, ); return Ok(ProxyResponse::Axum(response)); } // No handler was found, return 404 return Err(HttpError::HandlerNotFound); }; let http_data = handler.http_data(); let redirect_http_to_https_port = http_data .as_ref() .and_then(|data: &crate::connection_handler::ConnectionHttpData| { data.redirect_http_to_https_port }); // Read protocol information for X-Forwarded headers let (proto, port) = match ( protocol, redirect_http_to_https_port.as_ref(), &proxy_data.proxy_type, ) { // If force-https is true, redirect this HTTP request to HTTPS (Protocol::Http { .. }, Some(port), ProxyType::Tunneling) | (Protocol::TlsRedirect { to: port, .. }, _, ProxyType::Tunneling) => { let response = Redirect::permanent( format!( "https://{}:{}{}", host, port, request .uri() .path_and_query() .map(|path| path.as_str()) .unwrap_or("/"), ) .as_str(), ) .into_response(); http_log( HttpLog::builder() .uri(request.uri().path().to_string()) .method(request.method().to_string()) .host(host) .ip(ip.to_string()) .status(response.status().as_u16()) .elapsed_time(timer.elapsed()) .build(), None, proxy_data.disable_http_logs, proxy_data.log_format, ); return Ok(ProxyResponse::Axum(response)); } (Protocol::Http { port }, _, _) | (Protocol::TlsRedirect { from: port, .. }, _, ProxyType::Aliasing) => ("http", *port), (Protocol::Https { port }, _, _) => ("https", *port), }; // Add proxied info to the proper headers, but don't overwrite any existing proxy headers let headers = request.headers_mut(); append_to_header(headers, &X_FORWARDED_FOR, ip.to_string().as_bytes()); append_to_header(headers, &X_FORWARDED_HOST, host.as_bytes()); append_to_header(headers, &X_FORWARDED_PROTO, proto.as_bytes()); append_to_header(headers, &X_FORWARDED_PORT, port.to_string().as_bytes()); // Add this request to the telemetry for the host if http_data.as_ref().is_some_and(|data| data.is_aliasing) { counter!(TELEMETRY_COUNTER_ALIAS_CONNECTIONS, TELEMETRY_KEY_ALIAS => BorrowedSockAddrAlias(&host, &port).to_string()) .increment(1); } else { counter!(TELEMETRY_COUNTER_HTTP_REQUESTS, TELEMETRY_KEY_HOSTNAME => host.clone()) .increment(1); } let is_http2 = http_data.as_ref().map(|data| data.http2).unwrap_or(false); let host_clone = host.clone(); let request_host = http_data .as_ref() .and_then(|data| data.host.as_deref()) .unwrap_or(host_clone.as_str()); // Find the appropriate handler for this proxy type let key = KeepaliveAlias(host.clone(), ip, fingerprint); match request.version() { Version::HTTP_2 if is_http2 => { handle_http2_request( request, tcp_address, proxy_data, handler, request_host, key, timer, ) .await } Version::HTTP_2 | Version::HTTP_11 => { handle_http11_request( request, tcp_address, proxy_data, handler, request_host, key, timer, ) .await } version => Err(HttpError::InvalidHttpVersion(version)), } } #[cfg(test)] #[cfg_attr(coverage_nightly, coverage(off))] mod proxy_handler_tests { use axum::{ Router, extract::{WebSocketUpgrade, ws}, http::Uri, routing::{any, delete, get, post, put}, }; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; use http::{ Version, header::{HOST, LOCATION}, }; use http_body_util::{BodyExt, Empty}; use hyper::{HeaderMap, Request, StatusCode, body::Incoming, service::service_fn}; use hyper_util::rt::{TokioExecutor, TokioIo}; use std::{sync::Arc, time::Duration}; use tokio::{io::DuplexStream, sync::mpsc, time::sleep}; use tokio_tungstenite::client_async; use tower::Service; use crate::{ config::{LoadBalancingStrategy, LogFormat}, connection_handler::{ConnectionHttpData, MockConnectionHandler}, connections::ConnectionMap, quota::{DummyQuotaHandler, TokenHolder, UserIdentification}, reactor::MockConnectionMapReactor, ssh::ServerHandlerSender, }; use super::{DomainRedirect, Protocol, ProxyData, ProxyType, proxy_handler}; #[test_log::test(tokio::test)] async fn returns_bad_request_on_missing_host_header() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let request = Request::builder() .method("GET") .uri("/index.html") .body(Empty::::new()) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when missing host header"); assert_eq!(response.status(), hyper::StatusCode::BAD_REQUEST); } #[test_log::test(tokio::test)] async fn returns_not_found_on_missing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let request = Request::builder() .method("GET") .uri("/index.html") .header(HOST, "no.handler") .body(Empty::::new()) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when not found"); assert_eq!(response.status(), hyper::StatusCode::NOT_FOUND); } #[test_log::test(tokio::test)] async fn returns_redirect_for_root_domain_and_missing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let request = Request::builder() .method("GET") .uri("/index.html") .header(HOST, "main.domain") .body(Empty::::new()) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when redirect"); assert_eq!(response.status(), hyper::StatusCode::SEE_OTHER); assert_eq!(response.headers()[LOCATION], "https://example.com"); } #[test_log::test(tokio::test)] async fn returns_redirect_to_https_from_global_config() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel().never(); mock.expect_tunneling_channel().never(); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .body(String::from("Hello world")) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::TlsRedirect { from: 80, to: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when HTTPS redirect"); assert_eq!(response.status(), hyper::StatusCode::PERMANENT_REDIRECT); assert_eq!( response.headers()[LOCATION], "https://with.handler:443/api/endpoint" ); } #[test_log::test(tokio::test)] async fn returns_redirect_to_non_standard_https_port_from_global_config() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel().never(); mock.expect_tunneling_channel().never(); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "non.standard".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/test") .header(HOST, "non.standard") .body(String::from("Hello world")) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::TlsRedirect { from: 80, to: 8443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response whyen HTTPS redirect to non-standard port"); assert_eq!(response.status(), hyper::StatusCode::PERMANENT_REDIRECT); assert_eq!( response.headers()[LOCATION], "https://non.standard:8443/test" ); } #[test_log::test(tokio::test)] async fn returns_redirect_to_https_from_connection_data() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel().never(); mock.expect_tunneling_channel().never(); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: Some(443), is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .body(String::from("Hello world")) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when HTTPS redirect"); assert_eq!(response.status(), hyper::StatusCode::PERMANENT_REDIRECT); assert_eq!( response.headers()[LOCATION], "https://with.handler:443/api/endpoint" ); } #[test_log::test(tokio::test)] async fn returns_redirect_to_non_standard_https_port_from_connection_data() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel().never(); mock.expect_tunneling_channel().never(); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: Some(8443), is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "non.standard".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/test") .header(HOST, "non.standard") .body(String::from("Hello world")) .unwrap(); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response when HTTPS redirect to non-standard port"); assert_eq!(response.status(), hyper::StatusCode::PERMANENT_REDIRECT); assert_eq!( response.headers()[LOCATION], "https://non.standard:8443/test" ); } #[test_log::test(tokio::test)] async fn returns_error_for_outgoing_http11_request_timeout() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "slow.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .version(Version::HTTP_11) .method("GET") .uri("/slow_endpoint") .header(HOST, "slow.handler") .body(Empty::::new()) .unwrap(); let router = Router::new().route( "/slow_endpoint", get(async || { sleep(Duration::from_secs(1)).await; "Slow hello." }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .http_request_timeout(Duration::from_millis(500)) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; assert!( !logging_rx.is_empty(), "should log after timing out request" ); let response = response.expect("should return response after proxy"); assert_eq!(response.status(), hyper::StatusCode::GATEWAY_TIMEOUT); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_error_for_outgoing_websocket_request_timeout() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.websocket".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let (socket, stream) = tokio::io::duplex(1024); let router = Router::new().route( "/ws", any(|ws: WebSocketUpgrade| async move { sleep(Duration::from_secs(1)).await; ws.on_upgrade(|mut socket| async move { let _ = socket.send(ws::Message::Text("Success.".into())).await; let _ = socket.close().await; }) }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!(logging_rx.is_empty(), "shouldn't log before request"); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .http_request_timeout(Duration::from_millis(500)) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh2 = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let error = match client_async("ws://with.websocket/ws", stream).await { Err(error) => error, Ok(res) => panic!("should've errored when establishing Websocket connection: {res:?}"), }; match error { tokio_tungstenite::tungstenite::Error::Http(response) => { assert!( response.status() == StatusCode::GATEWAY_TIMEOUT, "should've timed out Websocket request" ) } _ => panic!(), } assert!( !logging_rx.is_empty(), "should log after upgrade proxying request" ); jh.abort(); jh2.abort(); } #[test_log::test(tokio::test)] async fn returns_error_for_outgoing_http2_request_timeout() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: true, host: None, }) }); conn_manager .insert( "slow.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .version(Version::HTTP_2) .method("GET") .uri("https://slow.handler/slow_endpoint") .body(Empty::::new()) .unwrap(); let router = Router::new().route( "/slow_endpoint", get(async || { sleep(Duration::from_secs(1)).await; "Slow hello." }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .http_request_timeout(Duration::from_millis(500)) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; assert!( !logging_rx.is_empty(), "should log after timing out request" ); let response = response.expect("should return response after proxy"); assert_eq!(response.status(), hyper::StatusCode::GATEWAY_TIMEOUT); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_response_for_existing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .body(String::from("Hello world")) .unwrap(); let router = Router::new().route( "/api/endpoint", post(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "with.handler" && body == "Hello world" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().frame().await.unwrap().unwrap(); assert_eq!(body.data_ref(), Some(&Bytes::copy_from_slice(b"Success."))); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_response_for_existing_handler_with_proxy() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .header("X-Forwarded-For", "10.15.0.1") .header("X-Forwarded-Host", "sand.hole") .body(String::from("Hello world")) .unwrap(); let router = Router::new().route( "/api/endpoint", post(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "10.15.0.1, 127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "sand.hole, with.handler" && body == "Hello world" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().frame().await.unwrap().unwrap(); assert_eq!(body.data_ref(), Some(&Bytes::copy_from_slice(b"Success."))); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_response_for_existing_handler_with_custom_host() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: Some("other.host".into()), }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .body(String::from("Hello world")) .unwrap(); let router = Router::new().route( "/api/endpoint", post(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "with.handler" && headers.get("Host").unwrap() == "other.host" && body == "Hello world" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().frame().await.unwrap().unwrap(); assert_eq!(body.data_ref(), Some(&Bytes::copy_from_slice(b"Success."))); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_response_for_aliasing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_aliasing_channel() .once() .return_once(move |_, _, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: Some(443), is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/api/endpoint") .header(HOST, "with.handler") .body(String::from("Hello world")) .unwrap(); let router = Router::new().route( "/api/endpoint", post(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "with.handler" && body == "Hello world" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Http { port: 80 }) .proxy_type(ProxyType::Aliasing) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body(); let body = axum::body::to_bytes(body, 32).await.unwrap(); assert_eq!(body, bytes::Bytes::from("Success.")); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_response_for_handler_of_root_domain() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "root.domain".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let request = Request::builder() .method("POST") .uri("/test") .header(HOST, "root.domain") .body(String::from("My body")) .unwrap(); let router = Router::new().route( "/test", post(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "192.168.0.1" && headers.get("X-Forwarded-Host").unwrap() == "root.domain" && body == "My body" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let response = proxy_handler( request, "192.168.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "root.domain".into(), to: "https://this.is.ignored".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) .await; let response = response.expect("should return response after proxying request"); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body(); let body = axum::body::to_bytes(body, 32).await.unwrap(); assert_eq!(body, bytes::Bytes::from("Success.")); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); } #[test_log::test(tokio::test)] async fn returns_http11_response_for_existing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "http11.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let (socket, stream) = tokio::io::duplex(1024); let router = Router::new().route( "/http11", delete(|headers: HeaderMap| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "http11.handler" { (StatusCode::FORBIDDEN, "Can't get rid of good ol' HTTP1...") } else { (StatusCode::BAD_REQUEST, "Failure.") } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh2 = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let (mut sender, conn) = hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(stream)) .await .unwrap(); let jh3 = tokio::spawn(conn); let request = Request::builder() .method("DELETE") .uri("https://http11.handler/http11") .body(Empty::::new()) .unwrap(); let response = sender .send_request(request) .await .expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::FORBIDDEN); let body = String::from_utf8( response .into_body() .collect() .await .expect("Error collecting response") .to_bytes() .into(), ) .unwrap(); assert_eq!(body, "Can't get rid of good ol' HTTP1..."); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); jh2.abort(); jh3.abort(); } #[test_log::test(tokio::test)] async fn returns_websocket_upgrade_for_existing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: false, host: None, }) }); conn_manager .insert( "with.websocket".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let (socket, stream) = tokio::io::duplex(1024); let router = Router::new().route( "/ws", any(|ws: WebSocketUpgrade| async move { ws.on_upgrade(|mut socket| async move { let _ = socket.send(ws::Message::Text("Success.".into())).await; let _ = socket.close().await; }) }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!(logging_rx.is_empty(), "shouldn't log before request"); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh2 = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let (mut websocket, response) = client_async("ws://with.websocket/ws", stream) .await .unwrap(); assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS); drop(response); assert!( !logging_rx.is_empty(), "should log after upgrade proxying request" ); assert_eq!( websocket.next().await.unwrap().unwrap().to_text().unwrap(), "Success." ); jh.abort(); jh2.abort(); } #[test_log::test(tokio::test)] async fn returns_http2_response_for_existing_handler() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: true, host: None, }) }); conn_manager .insert( "http2.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let (socket, stream) = tokio::io::duplex(1024); let router = Router::new().route( "/http2", put(|headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "http2.handler" && body == "The future of HTTP!" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh2 = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let (mut sender, conn) = hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(stream)) .await .unwrap(); let jh3 = tokio::spawn(conn); let request = Request::builder() .method("PUT") .uri("https://http2.handler/http2") .body(String::from("The future of HTTP!")) .unwrap(); let response = sender .send_request(request) .await .expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = String::from_utf8( response .into_body() .collect() .await .expect("Error collecting response") .to_bytes() .into(), ) .unwrap(); assert_eq!(body, "Success."); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); jh2.abort(); jh3.abort(); } #[test_log::test(tokio::test)] async fn returns_http2_response_for_existing_handler_with_custom_host() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (server, handler) = tokio::io::duplex(1024); let (logging_tx, logging_rx) = mpsc::unbounded_channel::>(); let mut mock = MockConnectionHandler::new(); mock.expect_log_channel() .once() .return_once(move || ServerHandlerSender(Some(logging_tx))); mock.expect_tunneling_channel() .once() .return_once(move |_, _| Box::pin(async move { Ok(handler) })); mock.expect_http_data().once().return_once(move || { Some(ConnectionHttpData { redirect_http_to_https_port: None, is_aliasing: false, http2: true, host: Some("other.host".into()), }) }); conn_manager .insert( "http2.handler".into(), "127.0.0.1:12345".parse().unwrap(), TokenHolder::User(UserIdentification::Username("a".into())), Arc::new(mock), ) .unwrap(); let (socket, stream) = tokio::io::duplex(1024); let router = Router::new().route( "/http2", put(|uri: Uri, headers: HeaderMap, body: String| async move { if headers.get("X-Forwarded-For").unwrap() == "127.0.0.1" && headers.get("X-Forwarded-Host").unwrap() == "http2.handler" && uri.host().unwrap() == "other.host" && &body == "The future of HTTP!" { "Success." } else { "Failure." } }), ); let router_service = service_fn(move |req: Request| router.clone().call(req)); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection(TokioIo::new(server), router_service) .await .expect("Invalid request"); }); assert!( logging_rx.is_empty(), "shouldn't log before handling request" ); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh2 = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let (mut sender, conn) = hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(stream)) .await .unwrap(); let jh3 = tokio::spawn(conn); let request = Request::builder() .method("PUT") .uri("https://http2.handler/http2") .body(String::from("The future of HTTP!")) .unwrap(); let response = sender .send_request(request) .await .expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::OK); let body = String::from_utf8( response .into_body() .collect() .await .expect("Error collecting response") .to_bytes() .into(), ) .unwrap(); assert_eq!(body, "Success."); drop(body); assert!(!logging_rx.is_empty(), "should log after proxying request"); jh.abort(); jh2.abort(); jh3.abort(); } #[test_log::test(tokio::test)] async fn fails_for_http2_with_missing_host_in_uri() { let conn_manager: Arc< ConnectionMap< String, Arc>, MockConnectionMapReactor, >, > = Arc::new( ConnectionMap::builder() .strategy(LoadBalancingStrategy::Allow) .algorithm(crate::LoadBalancingAlgorithm::RoundRobin) .quota_handler(Arc::new(Box::new(DummyQuotaHandler))) .build(), ); let (socket, stream) = tokio::io::duplex(1024); let proxy_service = service_fn(move |request| { proxy_handler( request, "127.0.0.1:12345".parse().unwrap(), None, Arc::new( ProxyData::builder() .conn_manager(Arc::clone(&conn_manager)) .domain_redirect(Arc::new(DomainRedirect { from: "main.domain".into(), to: "https://example.com".into(), })) .protocol(Protocol::Https { port: 443 }) .proxy_type(ProxyType::Tunneling) .buffer_size(8_000) .disable_http_logs(false) .log_format(LogFormat::Default) .http_pool_size(16) .http_pool_max_idle_time(Duration::from_secs(60)) .http_pool_max_reuse(1_000) .build(), ), ) }); let jh = tokio::spawn(async move { hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) .serve_connection_with_upgrades(TokioIo::new(socket), proxy_service) .await .expect("Invalid request"); }); let (mut sender, conn) = hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(stream)) .await .unwrap(); let jh2 = tokio::spawn(conn); let request = Request::builder() .method("GET") .uri("/no_host") .body(Empty::::new()) .unwrap(); let response = sender .send_request(request) .await .expect("should return response after proxy"); assert_eq!(response.status(), StatusCode::BAD_REQUEST); jh.abort(); jh2.abort(); } }