tower-proxy 0.8.0

Tower service for reverse proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#![cfg_attr(docsrs, feature(doc_cfg))]

//! `tower-proxy` is tower [`Service`s](tower_service::Service) that performs "reverse
//! proxy" with various rewriting rules.
//!
//! Internally these services use [`hyper_util::client::legacy::Client`] to send an incoming request to another
//! server. The [`connector`](hyper_util::client::legacy::connect::Connect) for a client can be
#![cfg_attr(
    not(any(feature = "https", feature = "nativetls", feature = "__rustls")),
    doc = "[`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector),"
)]
#![cfg_attr(
    all(
        any(feature = "https", feature = "nativetls"),
        not(feature = "__rustls")
    ),
    doc = "[`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector), [`HttpsConnector`](hyper_tls::HttpsConnector),"
)]
#![cfg_attr(
    all(
        not(any(feature = "https", feature = "nativetls")),
        feature = "__rustls"
    ),
    doc = "[`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector), [`client::RustlsConnector`],"
)]
#![cfg_attr(
    all(any(feature = "https", feature = "nativetls"), feature = "__rustls"),
    doc = "[`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector), [`HttpsConnector`](hyper_tls::HttpsConnector), [`client::RustlsConnector`],"
)]
//! or any ones whichever you want.
//!
//! # Examples
//!
//! There are two types of services, [`OneshotService`] and [`ReusedService`]. The
//! [`OneshotService`] *owns* the `Client`, while the [`ReusedService`] *shares* the `Client`
//! via [`Arc`](std::sync::Arc).
//!
//!
//! ## General usage
//!
//! ```
//! # async fn run_test() {
//! use tower_proxy::ReusedServiceBuilder;
//! use tower_proxy::{ReplaceAll, ReplaceN};
//!
//! use hyper::body::Bytes;
//! use http_body_util::Full;
//! use http::Request;
//! use tower_service::Service as _;
//!
//! let svc_builder = tower_proxy::builder_http("example.com:1234").unwrap();
//!
//! let req1 = Request::builder()
//!     .method("GET")
//!     .uri("https://myserver.com/foo/bar/foo")
//!     .body(Full::new(Bytes::new()))
//!     .unwrap();
//!
//! // Clones Arc<Client>
//! let mut svc1 = svc_builder.build(ReplaceAll("foo", "baz"));
//! // http://example.com:1234/baz/bar/baz
//! let _res = svc1.call(req1).await.unwrap();
//!
//! let req2 = Request::builder()
//!     .method("POST")
//!     .uri("https://myserver.com/foo/bar/foo")
//!     .header("Content-Type", "application/x-www-form-urlencoded")
//!     .body(Full::new(Bytes::from("key=value")))
//!     .unwrap();
//!
//! let mut svc2 = svc_builder.build(ReplaceN("foo", "baz", 1));
//! // http://example.com:1234/baz/bar/foo
//! let _res = svc2.call(req2).await.unwrap();
//! # }
//! ```
//!
//! In this example, the `svc1` and `svc2` shares the same `Client`, holding the `Arc<Client>`s
//! inside them.
//!
//! For more information of rewriting rules (`ReplaceAll`, `ReplaceN` *etc.*), see the
//! documentations of [`rewrite`].
//!
//!
//! ## With axum
//!
//! ```
//! # #[cfg(feature = "axum")] {
//! use tower_proxy::ReusedServiceBuilder;
//! use tower_proxy::{TrimPrefix, AppendSuffix, Static};
//!
//! use axum::Router;
//!
//! #[tokio::main]
//! async fn main() {
//!     let host1 = tower_proxy::builder_http("example.com").unwrap();
//!     let host2 = tower_proxy::builder_http("example.net:1234").unwrap();
//!
//!     let app = Router::new()
//!         .route_service("/healthcheck", host1.build(Static("/")))
//!         .route_service("/users/{*path}", host1.build(TrimPrefix("/users")))
//!         .route_service("/posts", host2.build(AppendSuffix("/")));
//!
//!     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
//!        .await
//!        .unwrap();
//!
//!    axum::serve(listener, app).await.unwrap();
//! }
//! # }
//! ```
//!
//!
//! # Return Types
//!
//! The return type ([`std::future::Future::Output`]) of [`ReusedService`] and
//! [`OneshotService`] is `Result<Result<Response<Incoming>, ProxyError>, Infallible>`.
#![cfg_attr(
    feature = "axum",
    doc = "This is because axum's [`Router`](axum::Router) accepts only such `Service`s."
)]
//!
#![cfg_attr(
    feature = "axum",
    doc = "The [`ProxyError`] type implements [`IntoResponse`](axum::response::IntoResponse) if you enable the \
    `axum` feature. \
    It returns an empty body, with the status code `INTERNAL_SERVER_ERROR`. The description of this \
    error will be logged out with [`tracing::event!`] at the [`tracing::Level::ERROR`] level in the \
    [`IntoResponse::into_response`](axum::response::IntoResponse::into_response) method. \
"
)]
//!
//! # Features
//!
//! By default only `http1` is enabled.
//!
//! - `http1`: uses `hyper/http1`
//! - `http2`: uses `hyper/http2`
//! - `https`: alias to `nativetls`
//! - `nativetls`: uses the `hyper-tls` crate
//! - `rustls`: alias to `rustls-webpki-roots`
//! - `rustls-webpki-roots`: uses the `hyper-rustls` crate, with the feature `webpki-roots`
//! - `rustls-native-roots`: uses the `hyper-rustls` crate, with the feature `rustls-native-certs`
//! - `rustls-http2`: `http2` plus `rustls`, and `rustls/http2` is enabled

#![cfg_attr(
    feature = "axum",
    doc = " - `axum`: implements [`IntoResponse`](axum::response::IntoResponse) for [`ProxyError`]"
)]
//! You must turn on either `http1`or `http2`. You cannot use the services if, for example, only
//! the `https` feature is on.
//!
//! Through this document, we use `rustls` to mean *any* of `rustls*` features unless otherwise
//! specified.

mod error;
pub use error::ProxyError;

#[cfg(any(feature = "http1", feature = "http2"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
pub mod client;

pub mod rewrite;
pub use rewrite::*;

mod future;
pub use future::RevProxyFuture;

#[cfg(any(feature = "http1", feature = "http2"))]
mod oneshot;
#[cfg(any(feature = "http1", feature = "http2"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
pub use oneshot::OneshotService;

#[cfg(any(feature = "http1", feature = "http2"))]
mod reused;
#[cfg(any(feature = "http1", feature = "http2"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
pub use reused::Builder as ReusedServiceBuilder;
#[cfg(any(feature = "http1", feature = "http2"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
pub use reused::ReusedService;
#[cfg(all(
    any(feature = "http1", feature = "http2"),
    any(feature = "https", feature = "nativetls")
))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(
        any(feature = "http1", feature = "http2"),
        any(feature = "https", feature = "nativetls")
    )))
)]
pub use reused::builder_https;
#[cfg(all(any(feature = "http1", feature = "http2"), feature = "nativetls"))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(any(feature = "http1", feature = "http2"), feature = "nativetls")))
)]
pub use reused::builder_nativetls;
#[cfg(all(any(feature = "http1", feature = "http2"), feature = "__rustls"))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(any(feature = "http1", feature = "http2"), feature = "rustls")))
)]
pub use reused::builder_rustls;
#[cfg(any(feature = "http1", feature = "http2"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
pub use reused::{builder, builder_http};

#[cfg(not(feature = "http1"))]
compile_error!("http1 is a mandatory feature");

#[cfg(all(
    any(feature = "rustls-ring", feature = "rustls-aws-lc"),
    not(any(feature = "rustls-webpki-roots", feature = "rustls-native-roots"))
))]
compile_error!(
    "When enabling rustls-ring and/or rustls-aws-lc, you must enable rustls-webpki-roots and/or rustls-native-roots"
);

#[cfg(test)]
mod test_helper {
    use std::convert::Infallible;

    use http::{Request, Response, StatusCode};
    use http_body_util::BodyExt as _;
    use hyper::body::Incoming;
    use mockito::{Matcher, ServerGuard};
    use pretty_assertions::assert_eq;
    use tower_service::Service;

    use super::{ProxyError, RevProxyFuture};

    async fn call<S, B>(
        service: &mut S,
        (method, suffix, content_type, body): (&str, &str, Option<&str>, B),
        expected: (StatusCode, &str),
    ) where
        S: Service<
                Request<String>,
                Response = Result<Response<Incoming>, ProxyError>,
                Error = Infallible,
                Future = RevProxyFuture,
            >,
        B: Into<String>,
    {
        let mut builder = Request::builder()
            .method(method)
            .uri(format!("https://test.com{}", suffix));

        if let Some(content_type) = content_type {
            builder = builder.header("Content-Type", content_type);
        }

        let request = builder.body(body.into()).unwrap();

        let result = service.call(request).await.unwrap();
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.status(), expected.0);

        let body = response.into_body().collect().await;
        assert!(body.is_ok());

        assert_eq!(body.unwrap().to_bytes(), expected.1);
    }

    pub async fn match_path<S>(server: &mut ServerGuard, svc: &mut S)
    where
        S: Service<
                Request<String>,
                Response = Result<Response<Incoming>, ProxyError>,
                Error = Infallible,
                Future = RevProxyFuture,
            >,
    {
        let _mk = server
            .mock("GET", "/goo/bar/goo/baz/goo")
            .with_body("ok")
            .create_async()
            .await;

        call(
            svc,
            ("GET", "/foo/bar/foo/baz/foo", None, ""),
            (StatusCode::OK, "ok"),
        )
        .await;

        call(
            svc,
            ("GET", "/foo/bar/foo/baz", None, ""),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;
    }

    pub async fn match_query<S>(server: &mut ServerGuard, svc: &mut S)
    where
        S: Service<
                Request<String>,
                Response = Result<Response<Incoming>, ProxyError>,
                Error = Infallible,
                Future = RevProxyFuture,
            >,
    {
        let _mk = server
            .mock("GET", "/goo")
            .match_query(Matcher::UrlEncoded("greeting".into(), "good day".into()))
            .with_body("ok")
            .create_async()
            .await;

        call(
            svc,
            ("GET", "/foo?greeting=good%20day", None, ""),
            (StatusCode::OK, "ok"),
        )
        .await;

        call(
            svc,
            ("GET", "/foo", None, ""),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;
    }

    pub async fn match_post<S>(server: &mut ServerGuard, svc: &mut S)
    where
        S: Service<
                Request<String>,
                Response = Result<Response<Incoming>, ProxyError>,
                Error = Infallible,
                Future = RevProxyFuture,
            >,
    {
        let _mk = server
            .mock("POST", "/goo")
            .match_body("test")
            .with_body("ok")
            .create_async()
            .await;

        call(svc, ("POST", "/foo", None, "test"), (StatusCode::OK, "ok")).await;

        call(
            svc,
            ("PUT", "/foo", None, "test"),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;

        call(
            svc,
            ("POST", "/foo", None, "tests"),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;
    }

    pub async fn match_header<S>(server: &mut ServerGuard, svc: &mut S)
    where
        S: Service<
                Request<String>,
                Response = Result<Response<Incoming>, ProxyError>,
                Error = Infallible,
                Future = RevProxyFuture,
            >,
    {
        let _mk = server
            .mock("POST", "/goo")
            .match_header("content-type", "application/json")
            .match_body(r#"{"key":"value"}"#)
            .with_body("ok")
            .create_async()
            .await;

        call(
            svc,
            (
                "POST",
                "/foo",
                Some("application/json"),
                r#"{"key":"value"}"#,
            ),
            (StatusCode::OK, "ok"),
        )
        .await;

        call(
            svc,
            ("POST", "/foo", None, r#"{"key":"value"}"#),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;

        call(
            svc,
            (
                "POST",
                "/foo",
                Some("application/json"),
                r#"{"key":"values"}"#,
            ),
            (StatusCode::NOT_IMPLEMENTED, ""),
        )
        .await;
    }
}