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
pub mod errors;
use once_cell::sync::{Lazy, OnceCell};
use reqwest::redirect::Policy;
use unicase::Ascii;
use warp::filters::path::FullPath;
use warp::http;
use warp::http::{HeaderMap, HeaderValue, Method as RequestMethod};
use warp::hyper::body::Bytes;
use warp::hyper::Body;
use warp::{Filter, Rejection};
pub static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
pub type Uri = FullPath;
pub type QueryParameters = Option<String>;
pub type Method = RequestMethod;
pub type Headers = HeaderMap;
pub type Request = (Uri, QueryParameters, Method, Headers, Bytes);
pub fn reverse_proxy_filter(
base_path: String,
proxy_address: String,
) -> impl Filter<Extract = (http::Response<Body>,), Error = Rejection> + Clone {
let proxy_address = warp::any().map(move || proxy_address.clone());
let base_path = warp::any().map(move || base_path.clone());
let data_filter = extract_request_data_filter();
proxy_address
.and(base_path)
.and(data_filter)
.and_then(proxy_to_and_forward_response)
.boxed()
}
pub fn query_params_filter(
) -> impl Filter<Extract = (QueryParameters,), Error = std::convert::Infallible> + Clone {
warp::query::raw()
.map(Some)
.or_else(|_| async { Ok::<(QueryParameters,), std::convert::Infallible>((None,)) })
}
pub fn extract_request_data_filter(
) -> impl Filter<Extract = Request, Error = warp::Rejection> + Clone {
warp::path::full()
.and(query_params_filter())
.and(warp::method())
.and(warp::header::headers_cloned())
.and(warp::body::bytes())
}
pub async fn proxy_to_and_forward_response(
proxy_address: String,
base_path: String,
uri: FullPath,
params: QueryParameters,
method: Method,
headers: HeaderMap,
body: Bytes,
) -> Result<http::Response<Body>, Rejection> {
let proxy_uri = remove_relative_path(&uri, base_path, proxy_address);
let request = filtered_data_to_request(proxy_uri, (uri, params, method, headers, body))
.map_err(warp::reject::custom)?;
let response = proxy_request(request).await.map_err(warp::reject::custom)?;
response_to_reply(response)
.await
.map_err(warp::reject::custom)
}
async fn response_to_reply(
response: reqwest::Response,
) -> Result<http::Response<Body>, errors::Error> {
let mut builder = http::Response::builder();
for (k, v) in remove_hop_headers(response.headers()).iter() {
builder = builder.header(k, v);
}
let status = response.status();
let body = Body::wrap_stream(response.bytes_stream());
builder
.status(status)
.body(body)
.map_err(errors::Error::Http)
}
fn remove_relative_path(uri: &FullPath, base_path: String, proxy_address: String) -> String {
let mut base_path = base_path;
if !base_path.starts_with('/') {
base_path = format!("/{}", base_path);
}
let relative_path = uri
.as_str()
.trim_start_matches(&base_path)
.trim_start_matches('/');
let proxy_address = proxy_address.trim_end_matches('/');
format!("{}/{}", proxy_address, relative_path)
}
fn is_hop_header(header_name: &str) -> bool {
static HOP_HEADERS: Lazy<Vec<Ascii<&'static str>>> = Lazy::new(|| {
vec![
Ascii::new("Connection"),
Ascii::new("Keep-Alive"),
Ascii::new("Proxy-Authenticate"),
Ascii::new("Proxy-Authorization"),
Ascii::new("Te"),
Ascii::new("Trailers"),
Ascii::new("Transfer-Encoding"),
Ascii::new("Upgrade"),
]
});
HOP_HEADERS.iter().any(|h| h == &header_name)
}
fn remove_hop_headers(headers: &HeaderMap<HeaderValue>) -> HeaderMap<HeaderValue> {
headers
.iter()
.filter_map(|(k, v)| {
if !is_hop_header(k.as_str()) {
Some((k.clone(), v.clone()))
} else {
None
}
})
.collect()
}
fn filtered_data_to_request(
proxy_address: String,
request: Request,
) -> Result<reqwest::Request, errors::Error> {
let (_uri, params, method, headers, body) = request;
let proxy_uri = if let Some(params) = params {
format!("{}?{}", proxy_address, params)
} else {
proxy_address
};
let headers = remove_hop_headers(&headers);
CLIENT
.get_or_init(default_reqwest_client)
.request(method, proxy_uri)
.headers(headers)
.body(body)
.build()
.map_err(errors::Error::Request)
}
async fn proxy_request(request: reqwest::Request) -> Result<reqwest::Response, errors::Error> {
CLIENT
.get_or_init(default_reqwest_client)
.execute(request)
.await
.map_err(errors::Error::Request)
}
fn default_reqwest_client() -> reqwest::Client {
reqwest::Client::builder()
.redirect(Policy::none())
.build()
.expect("Default reqwest client couldn't build")
}
#[cfg(test)]
pub mod test {
use crate::{
extract_request_data_filter, filtered_data_to_request, proxy_request, remove_relative_path,
reverse_proxy_filter, Request,
};
use std::net::SocketAddr;
use warp::http::StatusCode;
use warp::Filter;
fn serve_test_response(path: String, address: SocketAddr) {
if path.is_empty() {
tokio::spawn(warp::serve(warp::any().map(warp::reply)).run(address));
} else {
tokio::spawn(warp::serve(warp::path(path).map(warp::reply)).run(address));
}
}
#[tokio::test]
async fn request_data_match() {
let filter = extract_request_data_filter();
let (path, query, method, body, header) =
("/foo/bar", "foo=bar", "POST", b"foo bar", ("foo", "bar"));
let path_with_query = format!("{}?{}", path, query);
let result = warp::test::request()
.path(path_with_query.as_str())
.method(method)
.body(body)
.header(header.0, header.1)
.filter(&filter)
.await;
let (result_path, result_query, result_method, result_headers, result_body): Request =
result.unwrap();
assert_eq!(path, result_path.as_str());
assert_eq!(Some(query.to_string()), result_query);
assert_eq!(method, result_method.as_str());
assert_eq!(bytes::Bytes::from(body.to_vec()), result_body);
assert_eq!(result_headers.get(header.0).unwrap(), header.1);
}
#[tokio::test]
async fn proxy_forward_response() {
let filter = extract_request_data_filter();
let (path_with_params, method, body, header) = (
"http://127.0.0.1:3030/foo/bar?foo=bar",
"GET",
b"foo bar",
("foo", "bar"),
);
let result = warp::test::request()
.path(path_with_params)
.method(method)
.body(body)
.header(header.0, header.1)
.filter(&filter)
.await;
let request: Request = result.unwrap();
let address = ([127, 0, 0, 1], 4040);
serve_test_response("".to_string(), address.into());
tokio::task::yield_now().await;
let request = filtered_data_to_request(
remove_relative_path(
&request.0,
"".to_string(),
"http://127.0.0.1:4040".to_string(),
),
request,
)
.unwrap();
let response = proxy_request(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn full_reverse_proxy_filter_forward_response() {
let address_str = "http://127.0.0.1:3030";
let filter = warp::path!("relative_path" / ..).and(reverse_proxy_filter(
"relative_path".to_string(),
address_str.to_string(),
));
let address = ([127, 0, 0, 1], 3030);
let (path, method, body, header) = (
"https://127.0.0.1:3030/relative_path/foo",
"GET",
b"foo bar",
("foo", "bar"),
);
serve_test_response("foo".to_string(), address.into());
tokio::task::yield_now().await;
let response = warp::test::request()
.path(path)
.method(method)
.body(body)
.header(header.0, header.1)
.reply(&filter)
.await;
assert_eq!(response.status(), StatusCode::OK);
}
}