├── .gitignore ├── .travis.yml ├── .github └── workflows │ ├── build.yml │ ├── linting.yaml │ └── tests.yml ├── Cargo.toml ├── examples └── simple.rs ├── tests ├── test_websocket.rs └── test_http.rs ├── README.md ├── benches └── internal.rs ├── LICENSE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | /.idea 5 | *.swp 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Cargo Build 4 | 5 | jobs: 6 | build: 7 | name: Build 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | config: 12 | - node: ubuntu-latest 13 | - node: windows-latest 14 | - node: macos-latest 15 | runs-on: ${{ matrix.config.node }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: nightly 22 | override: true 23 | 24 | - uses: actions-rs/cargo@v1 25 | with: 26 | command: install 27 | args: cargo-all-features 28 | - uses: actions-rs/cargo@v1 29 | with: 30 | command: build-all-features 31 | 32 | - uses: actions-rs/cargo@v1 33 | with: 34 | command: build-all-features 35 | 36 | - uses: actions-rs/cargo@v1 37 | with: 38 | command: build 39 | args: --examples 40 | 41 | - uses: actions-rs/cargo@v1 42 | with: 43 | command: build 44 | args: --benches --features __bench -------------------------------------------------------------------------------- /.github/workflows/linting.yaml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Cargo Check & Clippy 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: stable 15 | override: true 16 | - uses: actions-rs/cargo@v1 17 | with: 18 | command: check 19 | fmt: 20 | name: Rustfmt 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v2 24 | - uses: actions-rs/toolchain@v1 25 | with: 26 | profile: minimal 27 | toolchain: stable 28 | override: true 29 | - run: rustup component add rustfmt 30 | - uses: actions-rs/cargo@v1 31 | with: 32 | command: fmt 33 | args: --all -- --check 34 | 35 | clippy: 36 | name: Clippy 37 | runs-on: ubuntu-latest 38 | steps: 39 | - uses: actions/checkout@v2 40 | - uses: actions-rs/toolchain@v1 41 | with: 42 | profile: minimal 43 | toolchain: stable 44 | override: true 45 | - run: rustup component add clippy 46 | - uses: actions-rs/cargo@v1 47 | with: 48 | command: clippy 49 | args: -- -D warnings 50 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hyper-reverse-proxy" 3 | version = "0.5.2-dev" 4 | authors = [ 5 | "Brendan Zabarauskas ", 6 | "Felipe Noronha ", 7 | "Jan Kantert ", 8 | ] 9 | license = "Apache-2.0" 10 | description = "A simple reverse proxy, to be used with Hyper and Tokio." 11 | homepage = "https://github.com/felipenoris/hyper-reverse-proxy" 12 | documentation = "https://docs.rs/hyper-reverse-proxy" 13 | repository = "https://github.com/felipenoris/hyper-reverse-proxy" 14 | keywords = ["http", "hyper"] 15 | categories = ["network-programming", "web-programming"] 16 | readme = "README.md" 17 | edition = "2018" 18 | 19 | include = ["Cargo.toml", "LICENSE", "src/**/*"] 20 | 21 | [[bench]] 22 | name="internal" 23 | harness = false 24 | 25 | [dependencies] 26 | hyper = { version = "0.14.18", features = ["client"] } 27 | lazy_static = "1.4.0" 28 | tokio = { version = "1.17.0", features = ["io-util", "rt"] } 29 | tracing = "0.1.34" 30 | 31 | [dev-dependencies] 32 | hyper = { version = "0.14.18", features = ["server"] } 33 | futures = "0.3.21" 34 | async-trait = "0.1.53" 35 | async-tungstenite = { version = "0.17", features = ["tokio-runtime"] } 36 | tokio-test = "0.4.2" 37 | test-context = "0.1.3" 38 | tokiotest-httpserver = "0.2.1" 39 | hyper-trust-dns = { version = "0.4.2", features = [ 40 | "rustls-http2", 41 | "dnssec-ring", 42 | "dns-over-https-rustls", 43 | "rustls-webpki" 44 | ] } 45 | rand = "0.8.5" 46 | tungstenite = "0.17" 47 | url = "2.2" 48 | criterion = "0.3.5" 49 | 50 | [features] 51 | 52 | __bench=[] -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Cargo Test 4 | 5 | jobs: 6 | test: 7 | name: Test Suite 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | config: 12 | - node: ubuntu-latest 13 | - node: windows-latest 14 | - node: macos-latest 15 | runs-on: ${{ matrix.config.node }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: nightly 22 | override: true 23 | - uses: actions-rs/cargo@v1 24 | with: 25 | command: install 26 | args: cargo-all-features 27 | - uses: actions-rs/cargo@v1 28 | with: 29 | command: test-all-features 30 | - uses: actions-rs/cargo@v1 31 | with: 32 | command: test-all-features 33 | args: --release 34 | 35 | # cargo all-features currently does not support cross 36 | test-cross: 37 | strategy: 38 | fail-fast: false 39 | matrix: 40 | config: 41 | # ubuntu aarch64 42 | - node: ubuntu-latest 43 | arch: aarch64-unknown-linux-gnu 44 | - node: ubuntu-latest 45 | arch: aarch64-unknown-linux-musl 46 | 47 | # ubuntu x86 48 | - node: ubuntu-latest 49 | arch: x86_64-unknown-linux-gnu 50 | - node: ubuntu-latest 51 | arch: x86_64-unknown-linux-musl 52 | 53 | # apple aarch64 54 | - node: macos-latest 55 | arch: aarch64-apple-darwin 56 | 57 | runs-on: ${{ matrix.config.node }} 58 | steps: 59 | - name: Checkout repository 60 | uses: actions/checkout@v2.4.0 61 | 62 | - uses: docker-practice/actions-setup-docker@master 63 | 64 | - name: Set up Docker Buildx 65 | uses: docker/setup-buildx-action@v1 66 | 67 | - uses: actions-rs/cargo@v1 68 | with: 69 | command: install 70 | args: cross 71 | 72 | - uses: actions-rs/toolchain@v1 73 | with: 74 | toolchain: nightly 75 | override: true 76 | 77 | - name: Test Dev 78 | run: cross test --target ${{ matrix.config.arch }} --lib 79 | 80 | - name: Test Release 81 | run: cross test --target ${{ matrix.config.arch }} --release --lib 82 | -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | use hyper::server::conn::AddrStream; 2 | use hyper::service::{make_service_fn, service_fn}; 3 | use hyper::{Body, Request, Response, Server, StatusCode}; 4 | use hyper_reverse_proxy::ReverseProxy; 5 | use hyper_trust_dns::{RustlsHttpsConnector, TrustDnsResolver}; 6 | use std::net::IpAddr; 7 | use std::{convert::Infallible, net::SocketAddr}; 8 | 9 | lazy_static::lazy_static! { 10 | static ref PROXY_CLIENT: ReverseProxy = { 11 | ReverseProxy::new( 12 | hyper::Client::builder().build::<_, hyper::Body>(TrustDnsResolver::default().into_rustls_webpki_https_connector()), 13 | ) 14 | }; 15 | } 16 | 17 | fn debug_request(req: &Request) -> Result, Infallible> { 18 | let body_str = format!("{:?}", req); 19 | Ok(Response::new(Body::from(body_str))) 20 | } 21 | 22 | async fn handle(client_ip: IpAddr, req: Request) -> Result, Infallible> { 23 | if req.uri().path().starts_with("/target/first") { 24 | match PROXY_CLIENT 25 | .call(client_ip, "http://127.0.0.1:13901", req) 26 | .await 27 | { 28 | Ok(response) => Ok(response), 29 | Err(_error) => Ok(Response::builder() 30 | .status(StatusCode::INTERNAL_SERVER_ERROR) 31 | .body(Body::empty()) 32 | .unwrap()), 33 | } 34 | } else if req.uri().path().starts_with("/target/second") { 35 | match PROXY_CLIENT 36 | .call(client_ip, "http://127.0.0.1:13902", req) 37 | .await 38 | { 39 | Ok(response) => Ok(response), 40 | Err(_error) => Ok(Response::builder() 41 | .status(StatusCode::INTERNAL_SERVER_ERROR) 42 | .body(Body::empty()) 43 | .unwrap()), 44 | } 45 | } else { 46 | debug_request(&req) 47 | } 48 | } 49 | 50 | #[tokio::main] 51 | async fn main() { 52 | let bind_addr = "127.0.0.1:8000"; 53 | let addr: SocketAddr = bind_addr.parse().expect("Could not parse ip:port."); 54 | 55 | let make_svc = make_service_fn(|conn: &AddrStream| { 56 | let remote_addr = conn.remote_addr().ip(); 57 | async move { Ok::<_, Infallible>(service_fn(move |req| handle(remote_addr, req))) } 58 | }); 59 | 60 | let server = Server::bind(&addr).serve(make_svc); 61 | 62 | println!("Running server on {:?}", addr); 63 | 64 | if let Err(e) = server.await { 65 | eprintln!("server error: {}", e); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/test_websocket.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | convert::Infallible, 3 | net::{IpAddr, SocketAddr}, 4 | process::exit, 5 | time::Duration, 6 | }; 7 | 8 | use async_tungstenite::tokio::{accept_async, connect_async}; 9 | use futures::{SinkExt, StreamExt}; 10 | use hyper::{ 11 | client::{connect::dns::GaiResolver, HttpConnector}, 12 | server::conn::AddrStream, 13 | service::{make_service_fn, service_fn}, 14 | Body, Request, Response, Server, 15 | }; 16 | use hyper_reverse_proxy::ReverseProxy; 17 | use test_context::{test_context, AsyncTestContext}; 18 | use tokio::{net::TcpListener, sync::oneshot::Sender, task::JoinHandle}; 19 | use tokiotest_httpserver::take_port; 20 | use tungstenite::Message; 21 | use url::Url; 22 | 23 | lazy_static::lazy_static! { 24 | static ref PROXY_CLIENT: ReverseProxy> = { 25 | ReverseProxy::new( 26 | hyper::Client::new(), 27 | ) 28 | }; 29 | } 30 | 31 | struct ProxyTestContext { 32 | sender: Sender<()>, 33 | proxy_handler: JoinHandle>, 34 | ws_handler: JoinHandle<()>, 35 | port: u16, 36 | } 37 | 38 | #[test_context(ProxyTestContext)] 39 | #[tokio::test] 40 | async fn test_websocket(ctx: &mut ProxyTestContext) { 41 | let (mut client, _) = 42 | connect_async(Url::parse(&format!("ws://127.0.0.1:{}", ctx.port)).unwrap()) 43 | .await 44 | .unwrap(); 45 | 46 | client.send(Message::Ping("hello".into())).await.unwrap(); 47 | let msg = client.next().await.unwrap().unwrap(); 48 | 49 | assert!( 50 | matches!(&msg, Message::Pong(inner) if inner == "hello".as_bytes()), 51 | "did not get pong, but {:?}", 52 | msg 53 | ); 54 | 55 | let msg = client.next().await.unwrap().unwrap(); 56 | 57 | assert!( 58 | matches!(&msg, Message::Text(inner) if inner == "All done"), 59 | "did not get text, but {:?}", 60 | msg 61 | ); 62 | } 63 | 64 | async fn handle( 65 | client_ip: IpAddr, 66 | req: Request, 67 | backend_port: u16, 68 | ) -> Result, Infallible> { 69 | match PROXY_CLIENT 70 | .call( 71 | client_ip, 72 | format!("http://127.0.0.1:{}", backend_port).as_str(), 73 | req, 74 | ) 75 | .await 76 | { 77 | Ok(response) => Ok(response), 78 | Err(err) => panic!("did not expect error: {:?}", err), 79 | } 80 | } 81 | 82 | #[async_trait::async_trait] 83 | impl<'a> AsyncTestContext for ProxyTestContext { 84 | async fn setup() -> ProxyTestContext { 85 | tokio::spawn(async { 86 | tokio::time::sleep(Duration::from_secs(5)).await; 87 | println!("Unit test executed too long, perhaps its stuck..."); 88 | exit(1); 89 | }); 90 | 91 | let (sender, receiver) = tokio::sync::oneshot::channel::<()>(); 92 | let ws_port = take_port(); 93 | 94 | let ws_handler = tokio::spawn(async move { 95 | let ws_server = TcpListener::bind(("127.0.0.1", ws_port)).await.unwrap(); 96 | 97 | if let Ok((stream, _)) = ws_server.accept().await { 98 | let mut websocket = accept_async(stream).await.unwrap(); 99 | 100 | let msg = websocket.next().await.unwrap().unwrap(); 101 | assert!( 102 | matches!(&msg, Message::Ping(inner) if inner == "hello".as_bytes()), 103 | "did not get ping, but: {:?}", 104 | msg 105 | ); 106 | // Tungstenite will auto send a Pong as a response to a Ping 107 | 108 | websocket 109 | .send(Message::Text("All done".to_string())) 110 | .await 111 | .unwrap(); 112 | } 113 | }); 114 | 115 | let make_svc = make_service_fn(move |conn: &AddrStream| { 116 | let remote_addr = conn.remote_addr().ip(); 117 | async move { Ok::<_, Infallible>(service_fn(move |req| handle(remote_addr, req, ws_port))) } 118 | }); 119 | 120 | let port = take_port(); 121 | let addr = SocketAddr::new("127.0.0.1".parse().unwrap(), port); 122 | let server = Server::bind(&addr) 123 | .serve(make_svc) 124 | .with_graceful_shutdown(async { 125 | receiver.await.ok(); 126 | }); 127 | let proxy_handler = tokio::spawn(server); 128 | ProxyTestContext { 129 | sender, 130 | proxy_handler, 131 | ws_handler, 132 | port, 133 | } 134 | } 135 | async fn teardown(self) { 136 | let _ = self.sender.send(()).unwrap(); 137 | let _ = tokio::join!(self.proxy_handler, self.ws_handler); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /tests/test_http.rs: -------------------------------------------------------------------------------- 1 | use hyper::client::connect::dns::GaiResolver; 2 | use hyper::client::HttpConnector; 3 | use hyper::header::{CONNECTION, HOST, UPGRADE}; 4 | use hyper::server::conn::AddrStream; 5 | use hyper::service::{make_service_fn, service_fn}; 6 | use hyper::{Body, Client, HeaderMap, Request, Response, Server, StatusCode, Uri}; 7 | use hyper_reverse_proxy::ReverseProxy; 8 | use std::convert::Infallible; 9 | use std::net::{IpAddr, SocketAddr}; 10 | use test_context::test_context; 11 | use test_context::AsyncTestContext; 12 | use tokio::sync::oneshot::Sender; 13 | use tokio::task::JoinHandle; 14 | use tokiotest_httpserver::handler::HandlerBuilder; 15 | use tokiotest_httpserver::{take_port, HttpTestContext}; 16 | 17 | lazy_static::lazy_static! { 18 | static ref PROXY_CLIENT: ReverseProxy> = { 19 | ReverseProxy::new( 20 | hyper::Client::new(), 21 | ) 22 | }; 23 | } 24 | 25 | struct ProxyTestContext { 26 | sender: Sender<()>, 27 | proxy_handler: JoinHandle>, 28 | http_back: HttpTestContext, 29 | port: u16, 30 | } 31 | 32 | #[test_context(ProxyTestContext)] 33 | #[tokio::test] 34 | async fn test_get_error_500(ctx: &mut ProxyTestContext) { 35 | let client = Client::new(); 36 | let resp = client 37 | .request( 38 | Request::builder() 39 | .header("keep-alive", "treu") 40 | .method("GET") 41 | .uri(ctx.uri("/500")) 42 | .body(Body::from("")) 43 | .unwrap(), 44 | ) 45 | .await 46 | .unwrap(); 47 | assert_eq!(500, resp.status()); 48 | } 49 | 50 | #[test_context(ProxyTestContext)] 51 | #[tokio::test] 52 | async fn test_upgrade_mismatch(ctx: &mut ProxyTestContext) { 53 | ctx.http_back.add( 54 | HandlerBuilder::new("/ws") 55 | .status_code(StatusCode::SWITCHING_PROTOCOLS) 56 | .build(), 57 | ); 58 | let resp = Client::new() 59 | .request( 60 | Request::builder() 61 | .header(CONNECTION, "Upgrade") 62 | .header(UPGRADE, "websocket") 63 | .method("GET") 64 | .uri(ctx.uri("/ws")) 65 | .body(Body::from("")) 66 | .unwrap(), 67 | ) 68 | .await 69 | .unwrap(); 70 | assert_eq!(resp.status(), 502); 71 | } 72 | 73 | #[test_context(ProxyTestContext)] 74 | #[tokio::test] 75 | async fn test_upgrade_unrequested(ctx: &mut ProxyTestContext) { 76 | ctx.http_back.add( 77 | HandlerBuilder::new("/wrong_switch") 78 | .status_code(StatusCode::SWITCHING_PROTOCOLS) 79 | .build(), 80 | ); 81 | let resp = Client::new().get(ctx.uri("/wrong_switch")).await.unwrap(); 82 | assert_eq!(resp.status(), 502); 83 | } 84 | 85 | #[test_context(ProxyTestContext)] 86 | #[tokio::test] 87 | async fn test_get(ctx: &mut ProxyTestContext) { 88 | let mut headers = HeaderMap::new(); 89 | headers.insert( 90 | HOST, 91 | format!("127.0.0.1:{}", ctx.http_back.port).parse().unwrap(), 92 | ); 93 | ctx.http_back.add( 94 | HandlerBuilder::new("/foo") 95 | .status_code(StatusCode::OK) 96 | .headers(headers) 97 | .build(), 98 | ); 99 | let resp = Client::new().get(ctx.uri("/foo")).await.unwrap(); 100 | assert_eq!(200, resp.status()); 101 | } 102 | 103 | async fn handle( 104 | client_ip: IpAddr, 105 | req: Request, 106 | backend_port: u16, 107 | ) -> Result, Infallible> { 108 | match PROXY_CLIENT 109 | .call( 110 | client_ip, 111 | format!("http://127.0.0.1:{}", backend_port).as_str(), 112 | req, 113 | ) 114 | .await 115 | { 116 | Ok(response) => Ok(response), 117 | Err(_) => Ok(Response::builder().status(502).body(Body::empty()).unwrap()), 118 | } 119 | } 120 | 121 | #[async_trait::async_trait] 122 | impl<'a> AsyncTestContext for ProxyTestContext { 123 | async fn setup() -> ProxyTestContext { 124 | let http_back: HttpTestContext = AsyncTestContext::setup().await; 125 | let (sender, receiver) = tokio::sync::oneshot::channel::<()>(); 126 | let bp_to_move = http_back.port; 127 | 128 | let make_svc = make_service_fn(move |conn: &AddrStream| { 129 | let remote_addr = conn.remote_addr().ip(); 130 | let back_port = bp_to_move; 131 | async move { 132 | Ok::<_, Infallible>(service_fn(move |req| handle(remote_addr, req, back_port))) 133 | } 134 | }); 135 | let port = take_port(); 136 | let addr = SocketAddr::new("127.0.0.1".parse().unwrap(), port); 137 | let server = Server::bind(&addr) 138 | .serve(make_svc) 139 | .with_graceful_shutdown(async { 140 | receiver.await.ok(); 141 | }); 142 | let proxy_handler = tokio::spawn(server); 143 | ProxyTestContext { 144 | sender, 145 | proxy_handler, 146 | http_back, 147 | port, 148 | } 149 | } 150 | async fn teardown(self) { 151 | let _ = AsyncTestContext::teardown(self.http_back); 152 | let _ = self.sender.send(()).unwrap(); 153 | let _ = tokio::join!(self.proxy_handler); 154 | } 155 | } 156 | impl ProxyTestContext { 157 | pub fn uri(&self, path: &str) -> Uri { 158 | format!("http://{}:{}{}", "localhost", self.port, path) 159 | .parse::() 160 | .unwrap() 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # hyper-reverse-proxy 3 | 4 | [![License][license-img]](LICENSE) 5 | [![CI][ci-img]][ci-url] 6 | [![docs][docs-img]][docs-url] 7 | [![version][version-img]][version-url] 8 | 9 | [license-img]: https://img.shields.io/crates/l/hyper-reverse-proxy.svg 10 | [ci-img]: https://github.com/felipenoris/hyper-reverse-proxy/workflows/CI/badge.svg 11 | [ci-url]: https://github.com/felipenoris/hyper-reverse-proxy/actions/workflows/main.yml 12 | [docs-img]: https://docs.rs/hyper-reverse-proxy/badge.svg 13 | [docs-url]: https://docs.rs/hyper-reverse-proxy 14 | [version-img]: https://img.shields.io/crates/v/hyper-reverse-proxy.svg 15 | [version-url]: https://crates.io/crates/hyper-reverse-proxy 16 | 17 | A simple reverse proxy, to be used with [Hyper]. 18 | 19 | The implementation ensures that [Hop-by-hop headers] are stripped correctly in both directions, 20 | and adds the client's IP address to a comma-space-separated list of forwarding addresses in the 21 | `X-Forwarded-For` header. 22 | 23 | The implementation is based on Go's [`httputil.ReverseProxy`]. 24 | 25 | [Hyper]: http://hyper.rs/ 26 | [Hop-by-hop headers]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html 27 | [`httputil.ReverseProxy`]: https://golang.org/pkg/net/http/httputil/#ReverseProxy 28 | 29 | # Example 30 | 31 | Add these dependencies to your `Cargo.toml` file. 32 | 33 | ```toml 34 | [dependencies] 35 | hyper-reverse-proxy = "?" 36 | hyper = { version = "?", features = ["full"] } 37 | tokio = { version = "?", features = ["full"] } 38 | lazy_static = "?" 39 | hyper-trust-dns = { version = "?", features = [ 40 | "rustls-http2", 41 | "dnssec-ring", 42 | "dns-over-https-rustls", 43 | "rustls-webpki", 44 | "https-only" 45 | ] } 46 | ``` 47 | 48 | The following example will set up a reverse proxy listening on `127.0.0.1:13900`, 49 | and will proxy these calls: 50 | 51 | * `"/target/first"` will be proxied to `http://127.0.0.1:13901` 52 | 53 | * `"/target/second"` will be proxied to `http://127.0.0.1:13902` 54 | 55 | * All other URLs will be handled by `debug_request` function, that will display request information. 56 | 57 | ```rust 58 | use hyper::server::conn::AddrStream; 59 | use hyper::service::{make_service_fn, service_fn}; 60 | use hyper::{Body, Request, Response, Server, StatusCode}; 61 | use hyper_reverse_proxy::ReverseProxy; 62 | use hyper_trust_dns::{RustlsHttpsConnector, TrustDnsResolver}; 63 | use std::net::IpAddr; 64 | use std::{convert::Infallible, net::SocketAddr}; 65 | 66 | lazy_static::lazy_static! { 67 | static ref PROXY_CLIENT: ReverseProxy = { 68 | ReverseProxy::new( 69 | hyper::Client::builder().build::<_, hyper::Body>(TrustDnsResolver::default().into_rustls_webpki_https_connector()), 70 | ) 71 | }; 72 | } 73 | 74 | fn debug_request(req: &Request) -> Result, Infallible> { 75 | let body_str = format!("{:?}", req); 76 | Ok(Response::new(Body::from(body_str))) 77 | } 78 | 79 | async fn handle(client_ip: IpAddr, req: Request) -> Result, Infallible> { 80 | if req.uri().path().starts_with("/target/first") { 81 | match PROXY_CLIENT.call(client_ip, "http://127.0.0.1:13901", req) 82 | .await 83 | { 84 | Ok(response) => { 85 | Ok(response) 86 | }, 87 | Err(_error) => { 88 | Ok(Response::builder() 89 | .status(StatusCode::INTERNAL_SERVER_ERROR) 90 | .body(Body::empty()) 91 | .unwrap())}, 92 | } 93 | } else if req.uri().path().starts_with("/target/second") { 94 | match PROXY_CLIENT.call(client_ip, "http://127.0.0.1:13902", req) 95 | .await 96 | { 97 | Ok(response) => Ok(response), 98 | Err(_error) => Ok(Response::builder() 99 | .status(StatusCode::INTERNAL_SERVER_ERROR) 100 | .body(Body::empty()) 101 | .unwrap()), 102 | } 103 | } else { 104 | debug_request(&req) 105 | } 106 | } 107 | 108 | #[tokio::main] 109 | async fn main() { 110 | let bind_addr = "127.0.0.1:8000"; 111 | let addr: SocketAddr = bind_addr.parse().expect("Could not parse ip:port."); 112 | 113 | let make_svc = make_service_fn(|conn: &AddrStream| { 114 | let remote_addr = conn.remote_addr().ip(); 115 | async move { Ok::<_, Infallible>(service_fn(move |req| handle(remote_addr, req))) } 116 | }); 117 | 118 | let server = Server::bind(&addr).serve(make_svc); 119 | 120 | println!("Running server on {:?}", addr); 121 | 122 | if let Err(e) = server.await { 123 | eprintln!("server error: {}", e); 124 | } 125 | } 126 | ``` 127 | 128 | ### A word about Security 129 | 130 | Handling outgoing requests can be a security nightmare. This crate does not control the client for the outgoing requests, as it needs to be supplied to the proxy call. The following chapters may give you an overview on how you can secure your client using the `hyper-trust-dns` crate. 131 | 132 | > You can see them being used in the example. 133 | 134 | #### HTTPS 135 | 136 | You should use a secure transport in order to know who you are talking to and so you can trust the connection. By default `hyper-trust-dns` enables the feature flag `https-only` which will panic if you supply a transport scheme which isn't `https`. It is a healthy default as it's not only you needing to trust the source but also everyone else seeing the content on unsecure connections. 137 | 138 | > ATTENTION: if you are running on a host with added certificates in your cert store, make sure to audit them in a interval, so neither old certificates nor malicious certificates are considered as valid by your client. 139 | 140 | #### TLS 1.2 141 | 142 | By default `tls 1.2` is disabled in favor of `tls 1.3`, because many parts of `tls 1.2` can be considered as attach friendly. As not yet all services support it `tls 1.2` can be enabled via the `rustls-tls-12` feature. 143 | 144 | > ATTENTION: make sure to audit the services you connect to on an interval 145 | 146 | #### DNSSEC 147 | 148 | As dns queries and entries aren't "trustworthy" by default from a security standpoint. `DNSSEC` adds a new cryptographic layer for verification. To enable it use the `dnssec-ring` feature. 149 | 150 | #### HTTP/2 151 | 152 | By default only rustlss `http1` feature is enabled for dns queries. While `http/3` might be just around the corner. `http/2` support can be enabled using the `rustls-http2` feature. 153 | 154 | #### DoT & DoH 155 | 156 | DoT and DoH provide you with a secure transport between you and your dns. 157 | 158 | By default none of them are enabled. If you would like to enabled them, you can do so using the features `doh` and `dot`. 159 | 160 | Recommendations: 161 | - If you need to monitor network activities in relation to accessed ports, use dot with the `dns-over-rustls` feature flag 162 | - If you are out in the wild and have no need to monitor based on ports, doh with the `dns-over-https-rustls` feature flag as it will blend in with other `https` traffic 163 | 164 | It is highly recommended to use one of them. 165 | 166 | > Currently only includes dns queries as `esni` or `ech` is still in draft by the `ietf` -------------------------------------------------------------------------------- /benches/internal.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, Criterion}; 2 | use hyper::client::connect::dns::GaiResolver; 3 | use hyper::client::HttpConnector; 4 | use hyper::header::HeaderName; 5 | use hyper::Uri; 6 | use hyper::{HeaderMap, Request, Response}; 7 | use hyper_reverse_proxy::benches as internal_benches; 8 | use hyper_reverse_proxy::ReverseProxy; 9 | use rand::distributions::Alphanumeric; 10 | use rand::prelude::*; 11 | use std::net::Ipv4Addr; 12 | use std::str::FromStr; 13 | use test_context::AsyncTestContext; 14 | use tokio::runtime::Runtime; 15 | use tokiotest_httpserver::HttpTestContext; 16 | 17 | lazy_static::lazy_static! { 18 | static ref PROXY_CLIENT: ReverseProxy> = { 19 | ReverseProxy::new( 20 | hyper::Client::new(), 21 | ) 22 | }; 23 | } 24 | 25 | fn create_proxied_response(b: &mut Criterion) { 26 | let headers_map = build_headers(); 27 | 28 | b.bench_function("create proxied response", |t| { 29 | t.iter(|| { 30 | let mut response = Response::builder().status(200); 31 | 32 | *response.headers_mut().unwrap() = headers_map.clone(); 33 | 34 | internal_benches::create_proxied_response(black_box(response.body(()).unwrap())); 35 | }) 36 | }); 37 | } 38 | 39 | fn generate_string() -> String { 40 | let take = rand::thread_rng().gen::().into(); 41 | rand::thread_rng() 42 | .sample_iter(&Alphanumeric) 43 | .take(take) 44 | .map(char::from) 45 | .collect() 46 | } 47 | 48 | fn build_headers() -> HeaderMap { 49 | let mut headers_map: HeaderMap = (&*internal_benches::hop_headers()) 50 | .iter() 51 | .map(|el: &'static HeaderName| (el.clone(), generate_string().parse().unwrap())) 52 | .collect(); 53 | 54 | for _i in 0..20 { 55 | 'inserted: loop { 56 | if let Ok(value) = 57 | hyper::header::HeaderName::from_str(&generate_string().to_lowercase()) 58 | { 59 | headers_map.insert(value, generate_string().parse().unwrap()); 60 | 61 | break 'inserted; 62 | } 63 | } 64 | } 65 | 66 | headers_map 67 | } 68 | 69 | fn proxy_call(b: &mut Criterion) { 70 | let rt = Runtime::new().unwrap(); 71 | 72 | let uri = Uri::from_static("http://0.0.0.0:8080/me?hello=world"); 73 | 74 | let http_context: HttpTestContext = rt.block_on(async { AsyncTestContext::setup().await }); 75 | 76 | let forward_url = &format!("http://0.0.0.0:{}", http_context.port); 77 | 78 | let headers_map = build_headers(); 79 | 80 | let client_ip = std::net::IpAddr::from(Ipv4Addr::from_str("0.0.0.0").unwrap()); 81 | 82 | b.bench_function("proxy call", |c| { 83 | c.iter(|| { 84 | rt.block_on(async { 85 | let mut request = Request::builder().uri(uri.clone()); 86 | 87 | *request.headers_mut().unwrap() = headers_map.clone(); 88 | 89 | black_box(&PROXY_CLIENT) 90 | .call( 91 | black_box(client_ip), 92 | black_box(forward_url), 93 | black_box(request.body(hyper::Body::from("")).unwrap()), 94 | ) 95 | .await 96 | .unwrap(); 97 | }) 98 | }) 99 | }); 100 | } 101 | 102 | fn forward_url_with_str_ending_slash(b: &mut Criterion) { 103 | let uri = Uri::from_static("https://0.0.0.0:8080/me"); 104 | let port = rand::thread_rng().gen::(); 105 | let forward_url = &format!("https://0.0.0.0:{}/", port); 106 | 107 | b.bench_function("forward url with str ending slash", |b| { 108 | b.iter(|| { 109 | let request = Request::builder().uri(uri.clone()).body(()); 110 | 111 | internal_benches::forward_uri(forward_url, &request.unwrap()); 112 | }) 113 | }); 114 | } 115 | 116 | fn forward_url_with_str_ending_slash_and_query(b: &mut Criterion) { 117 | let uri = Uri::from_static("https://0.0.0.0:8080/me?hello=world"); 118 | let port = rand::thread_rng().gen::(); 119 | let forward_url = &format!("https://0.0.0.0:{}/", port); 120 | 121 | b.bench_function("forward url with str ending slash and query", |t| { 122 | t.iter(|| { 123 | let request = Request::builder().uri(uri.clone()).body(()); 124 | 125 | internal_benches::forward_uri(forward_url, &request.unwrap()); 126 | }) 127 | }); 128 | } 129 | 130 | fn forward_url_no_ending_slash(b: &mut Criterion) { 131 | let uri = Uri::from_static("https://0.0.0.0:8080/me"); 132 | let port = rand::thread_rng().gen::(); 133 | let forward_url = &format!("https://0.0.0.0:{}", port); 134 | 135 | b.bench_function("forward url no ending slash", |t| { 136 | t.iter(|| { 137 | let request = Request::builder().uri(uri.clone()).body(()); 138 | 139 | internal_benches::forward_uri(forward_url, &request.unwrap()); 140 | }) 141 | }); 142 | } 143 | 144 | fn forward_url_with_query(b: &mut Criterion) { 145 | let uri = Uri::from_static("https://0.0.0.0:8080/me?hello=world"); 146 | let port = rand::thread_rng().gen::(); 147 | let forward_url = &format!("https://0.0.0.0:{}", port); 148 | 149 | b.bench_function("forward_url_with_query", |t| { 150 | t.iter(|| { 151 | let request = Request::builder().uri(uri.clone()).body(()); 152 | 153 | internal_benches::forward_uri(forward_url, &request.unwrap()); 154 | }) 155 | }); 156 | } 157 | 158 | fn create_proxied_request_forwarded_for_occupied(b: &mut Criterion) { 159 | let uri = Uri::from_static("https://0.0.0.0:8080/me?hello=world"); 160 | let port = rand::thread_rng().gen::(); 161 | let forward_url = &format!("https://0.0.0.0:{}", port); 162 | 163 | let mut headers_map = build_headers(); 164 | 165 | headers_map.insert( 166 | HeaderName::from_static("x-forwarded-for"), 167 | "0.0.0.0".parse().unwrap(), 168 | ); 169 | 170 | let client_ip = std::net::IpAddr::from(Ipv4Addr::from_str("0.0.0.0").unwrap()); 171 | 172 | b.bench_function("create proxied request forwarded for occupied", |t| { 173 | t.iter(|| { 174 | let mut request = Request::builder().uri(uri.clone()); 175 | 176 | *request.headers_mut().unwrap() = headers_map.clone(); 177 | 178 | internal_benches::create_proxied_request( 179 | client_ip, 180 | forward_url, 181 | request.body(()).unwrap(), 182 | None, 183 | ); 184 | }) 185 | }); 186 | } 187 | 188 | fn create_proxied_request_forwarded_for_vacant(b: &mut Criterion) { 189 | let uri = Uri::from_static("https://0.0.0.0:8080/me?hello=world"); 190 | let port = rand::thread_rng().gen::(); 191 | let forward_url = &format!("https://0.0.0.0:{}", port); 192 | 193 | let headers_map = build_headers(); 194 | 195 | let client_ip = std::net::IpAddr::from(Ipv4Addr::from_str("0.0.0.0").unwrap()); 196 | 197 | b.bench_function("create proxied request forwarded for vacant", |t| { 198 | t.iter(|| { 199 | let mut request = Request::builder().uri(uri.clone()); 200 | 201 | *request.headers_mut().unwrap() = headers_map.clone(); 202 | 203 | internal_benches::create_proxied_request( 204 | client_ip, 205 | forward_url, 206 | request.body(()).unwrap(), 207 | None, 208 | ); 209 | }) 210 | }); 211 | } 212 | 213 | criterion_group!(external_api, proxy_call); 214 | criterion_group!(responses, create_proxied_response); 215 | criterion_group!( 216 | url_parsing, 217 | forward_url_with_query, 218 | forward_url_no_ending_slash, 219 | forward_url_with_str_ending_slash_and_query, 220 | forward_url_with_str_ending_slash 221 | ); 222 | criterion_group!( 223 | requests, 224 | create_proxied_request_forwarded_for_vacant, 225 | create_proxied_request_forwarded_for_occupied 226 | ); 227 | criterion_main!(external_api, responses, url_parsing, requests); 228 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | 3 | #[macro_use] 4 | extern crate tracing; 5 | 6 | use hyper::header::{HeaderMap, HeaderName, HeaderValue, HOST}; 7 | use hyper::http::header::{InvalidHeaderValue, ToStrError}; 8 | use hyper::http::uri::InvalidUri; 9 | use hyper::upgrade::OnUpgrade; 10 | use hyper::{Body, Client, Error, Request, Response, StatusCode}; 11 | use lazy_static::lazy_static; 12 | use std::net::IpAddr; 13 | use tokio::io::copy_bidirectional; 14 | 15 | lazy_static! { 16 | static ref TE_HEADER: HeaderName = HeaderName::from_static("te"); 17 | static ref CONNECTION_HEADER: HeaderName = HeaderName::from_static("connection"); 18 | static ref UPGRADE_HEADER: HeaderName = HeaderName::from_static("upgrade"); 19 | static ref TRAILER_HEADER: HeaderName = HeaderName::from_static("trailer"); 20 | static ref TRAILERS_HEADER: HeaderName = HeaderName::from_static("trailers"); 21 | // A list of the headers, using hypers actual HeaderName comparison 22 | static ref HOP_HEADERS: [HeaderName; 9] = [ 23 | CONNECTION_HEADER.clone(), 24 | TE_HEADER.clone(), 25 | TRAILER_HEADER.clone(), 26 | HeaderName::from_static("keep-alive"), 27 | HeaderName::from_static("proxy-connection"), 28 | HeaderName::from_static("proxy-authenticate"), 29 | HeaderName::from_static("proxy-authorization"), 30 | HeaderName::from_static("transfer-encoding"), 31 | HeaderName::from_static("upgrade"), 32 | ]; 33 | 34 | static ref X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for"); 35 | } 36 | 37 | #[derive(Debug)] 38 | pub enum ProxyError { 39 | InvalidUri(InvalidUri), 40 | HyperError(Error), 41 | ForwardHeaderError, 42 | UpgradeError(String), 43 | } 44 | 45 | impl From for ProxyError { 46 | fn from(err: Error) -> ProxyError { 47 | ProxyError::HyperError(err) 48 | } 49 | } 50 | 51 | impl From for ProxyError { 52 | fn from(err: InvalidUri) -> ProxyError { 53 | ProxyError::InvalidUri(err) 54 | } 55 | } 56 | 57 | impl From for ProxyError { 58 | fn from(_err: ToStrError) -> ProxyError { 59 | ProxyError::ForwardHeaderError 60 | } 61 | } 62 | 63 | impl From for ProxyError { 64 | fn from(_err: InvalidHeaderValue) -> ProxyError { 65 | ProxyError::ForwardHeaderError 66 | } 67 | } 68 | 69 | fn remove_hop_headers(headers: &mut HeaderMap) { 70 | debug!("Removing hop headers"); 71 | 72 | for header in &*HOP_HEADERS { 73 | headers.remove(header); 74 | } 75 | } 76 | 77 | fn get_upgrade_type(headers: &HeaderMap) -> Option { 78 | #[allow(clippy::blocks_in_if_conditions)] 79 | if headers 80 | .get(&*CONNECTION_HEADER) 81 | .map(|value| { 82 | value 83 | .to_str() 84 | .unwrap() 85 | .split(',') 86 | .any(|e| e.trim() == *UPGRADE_HEADER) 87 | }) 88 | .unwrap_or(false) 89 | { 90 | if let Some(upgrade_value) = headers.get(&*UPGRADE_HEADER) { 91 | debug!( 92 | "Found upgrade header with value: {}", 93 | upgrade_value.to_str().unwrap().to_owned() 94 | ); 95 | 96 | return Some(upgrade_value.to_str().unwrap().to_owned()); 97 | } 98 | } 99 | 100 | None 101 | } 102 | 103 | fn remove_connection_headers(headers: &mut HeaderMap) { 104 | if headers.get(&*CONNECTION_HEADER).is_some() { 105 | debug!("Removing connection headers"); 106 | 107 | let value = headers.get(&*CONNECTION_HEADER).cloned().unwrap(); 108 | 109 | for name in value.to_str().unwrap().split(',') { 110 | if !name.trim().is_empty() { 111 | headers.remove(name.trim()); 112 | } 113 | } 114 | } 115 | } 116 | 117 | fn create_proxied_response(mut response: Response) -> Response { 118 | info!("Creating proxied response"); 119 | 120 | remove_hop_headers(response.headers_mut()); 121 | remove_connection_headers(response.headers_mut()); 122 | 123 | response 124 | } 125 | 126 | fn forward_uri(forward_url: &str, req: &Request) -> String { 127 | debug!("Building forward uri"); 128 | 129 | let split_url = forward_url.split('?').collect::>(); 130 | 131 | let mut base_url: &str = split_url.get(0).unwrap_or(&""); 132 | let forward_url_query: &str = split_url.get(1).unwrap_or(&""); 133 | 134 | let path2 = req.uri().path(); 135 | 136 | if base_url.ends_with('/') { 137 | let mut path1_chars = base_url.chars(); 138 | path1_chars.next_back(); 139 | 140 | base_url = path1_chars.as_str(); 141 | } 142 | 143 | let total_length = base_url.len() 144 | + path2.len() 145 | + 1 146 | + forward_url_query.len() 147 | + req.uri().query().map(|e| e.len()).unwrap_or(0); 148 | 149 | debug!("Creating url with capacity to {}", total_length); 150 | 151 | let mut url = String::with_capacity(total_length); 152 | 153 | url.push_str(base_url); 154 | url.push_str(path2); 155 | 156 | if !forward_url_query.is_empty() || req.uri().query().map(|e| !e.is_empty()).unwrap_or(false) { 157 | debug!("Adding query parts to url"); 158 | url.push('?'); 159 | url.push_str(forward_url_query); 160 | 161 | if forward_url_query.is_empty() { 162 | debug!("Using request query"); 163 | 164 | url.push_str(req.uri().query().unwrap_or("")); 165 | } else { 166 | debug!("Merging request and forward_url query"); 167 | 168 | let request_query_items = req.uri().query().unwrap_or("").split('&').map(|el| { 169 | let parts = el.split('=').collect::>(); 170 | (parts[0], if parts.len() > 1 { parts[1] } else { "" }) 171 | }); 172 | 173 | let forward_query_items = forward_url_query 174 | .split('&') 175 | .map(|el| { 176 | let parts = el.split('=').collect::>(); 177 | parts[0] 178 | }) 179 | .collect::>(); 180 | 181 | for (key, value) in request_query_items { 182 | if !forward_query_items.iter().any(|e| e == &key) { 183 | url.push('&'); 184 | url.push_str(key); 185 | url.push('='); 186 | url.push_str(value); 187 | } 188 | } 189 | 190 | if url.ends_with('&') { 191 | let mut parts = url.chars(); 192 | parts.next_back(); 193 | 194 | url = parts.as_str().to_string(); 195 | } 196 | } 197 | } 198 | 199 | debug!("Built forwarding url from request: {}", url); 200 | 201 | url.parse().unwrap() 202 | } 203 | 204 | fn create_proxied_request( 205 | client_ip: IpAddr, 206 | forward_url: &str, 207 | mut request: Request, 208 | upgrade_type: Option<&String>, 209 | ) -> Result, ProxyError> { 210 | info!("Creating proxied request"); 211 | 212 | let contains_te_trailers_value = request 213 | .headers() 214 | .get(&*TE_HEADER) 215 | .map(|value| { 216 | value 217 | .to_str() 218 | .unwrap() 219 | .split(',') 220 | .any(|e| e.trim() == *TRAILERS_HEADER) 221 | }) 222 | .unwrap_or(false); 223 | 224 | let uri: hyper::Uri = forward_uri(forward_url, &request).parse()?; 225 | 226 | debug!("Setting headers of proxied request"); 227 | 228 | // remove the original HOST header. It will be set by the client that sends the request 229 | request.headers_mut().remove(HOST); 230 | 231 | *request.uri_mut() = uri; 232 | 233 | remove_hop_headers(request.headers_mut()); 234 | remove_connection_headers(request.headers_mut()); 235 | 236 | if contains_te_trailers_value { 237 | debug!("Setting up trailer headers"); 238 | 239 | request 240 | .headers_mut() 241 | .insert(&*TE_HEADER, HeaderValue::from_static("trailers")); 242 | } 243 | 244 | if let Some(value) = upgrade_type { 245 | debug!("Repopulate upgrade headers"); 246 | 247 | request 248 | .headers_mut() 249 | .insert(&*UPGRADE_HEADER, value.parse().unwrap()); 250 | request 251 | .headers_mut() 252 | .insert(&*CONNECTION_HEADER, HeaderValue::from_static("UPGRADE")); 253 | } 254 | 255 | // Add forwarding information in the headers 256 | match request.headers_mut().entry(&*X_FORWARDED_FOR) { 257 | hyper::header::Entry::Vacant(entry) => { 258 | debug!("X-Fowraded-for header was vacant"); 259 | entry.insert(client_ip.to_string().parse()?); 260 | } 261 | 262 | hyper::header::Entry::Occupied(entry) => { 263 | debug!("X-Fowraded-for header was occupied"); 264 | let client_ip_str = client_ip.to_string(); 265 | let mut addr = 266 | String::with_capacity(entry.get().as_bytes().len() + 2 + client_ip_str.len()); 267 | 268 | addr.push_str(std::str::from_utf8(entry.get().as_bytes()).unwrap()); 269 | addr.push(','); 270 | addr.push(' '); 271 | addr.push_str(&client_ip_str); 272 | } 273 | } 274 | 275 | debug!("Created proxied request"); 276 | 277 | Ok(request) 278 | } 279 | 280 | pub async fn call<'a, T: hyper::client::connect::Connect + Clone + Send + Sync + 'static>( 281 | client_ip: IpAddr, 282 | forward_uri: &str, 283 | mut request: Request, 284 | client: &'a Client, 285 | ) -> Result, ProxyError> { 286 | info!( 287 | "Received proxy call from {} to {}, client: {}", 288 | request.uri().to_string(), 289 | forward_uri, 290 | client_ip 291 | ); 292 | 293 | let request_upgrade_type = get_upgrade_type(request.headers()); 294 | let request_upgraded = request.extensions_mut().remove::(); 295 | 296 | let proxied_request = create_proxied_request( 297 | client_ip, 298 | forward_uri, 299 | request, 300 | request_upgrade_type.as_ref(), 301 | )?; 302 | let mut response = client.request(proxied_request).await?; 303 | 304 | if response.status() == StatusCode::SWITCHING_PROTOCOLS { 305 | let response_upgrade_type = get_upgrade_type(response.headers()); 306 | 307 | if request_upgrade_type == response_upgrade_type { 308 | if let Some(request_upgraded) = request_upgraded { 309 | let mut response_upgraded = response 310 | .extensions_mut() 311 | .remove::() 312 | .expect("response does not have an upgrade extension") 313 | .await?; 314 | 315 | debug!("Responding to a connection upgrade response"); 316 | 317 | tokio::spawn(async move { 318 | let mut request_upgraded = 319 | request_upgraded.await.expect("failed to upgrade request"); 320 | 321 | copy_bidirectional(&mut response_upgraded, &mut request_upgraded) 322 | .await 323 | .expect("coping between upgraded connections failed"); 324 | }); 325 | 326 | Ok(response) 327 | } else { 328 | Err(ProxyError::UpgradeError( 329 | "request does not have an upgrade extension".to_string(), 330 | )) 331 | } 332 | } else { 333 | Err(ProxyError::UpgradeError(format!( 334 | "backend tried to switch to protocol {:?} when {:?} was requested", 335 | response_upgrade_type, request_upgrade_type 336 | ))) 337 | } 338 | } else { 339 | let proxied_response = create_proxied_response(response); 340 | 341 | debug!("Responding to call with response"); 342 | Ok(proxied_response) 343 | } 344 | } 345 | 346 | pub struct ReverseProxy { 347 | client: Client, 348 | } 349 | 350 | impl ReverseProxy { 351 | pub fn new(client: Client) -> Self { 352 | Self { client } 353 | } 354 | 355 | pub async fn call( 356 | &self, 357 | client_ip: IpAddr, 358 | forward_uri: &str, 359 | request: Request, 360 | ) -> Result, ProxyError> { 361 | call::(client_ip, forward_uri, request, &self.client).await 362 | } 363 | } 364 | 365 | #[cfg(feature = "__bench")] 366 | pub mod benches { 367 | pub fn hop_headers() -> &'static [crate::HeaderName] { 368 | &*super::HOP_HEADERS 369 | } 370 | 371 | pub fn create_proxied_response(response: crate::Response) { 372 | super::create_proxied_response(response); 373 | } 374 | 375 | pub fn forward_uri(forward_url: &str, req: &crate::Request) { 376 | super::forward_uri(forward_url, req); 377 | } 378 | 379 | pub fn create_proxied_request( 380 | client_ip: crate::IpAddr, 381 | forward_url: &str, 382 | request: crate::Request, 383 | upgrade_type: Option<&String>, 384 | ) { 385 | super::create_proxied_request(client_ip, forward_url, request, upgrade_type).unwrap(); 386 | } 387 | } 388 | --------------------------------------------------------------------------------