forked from vectordotdev/vector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.rs
418 lines (372 loc) · 13.9 KB
/
http.rs
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
412
413
414
415
416
417
418
#![allow(missing_docs)]
use std::{
fmt,
task::{Context, Poll},
time::Duration,
};
use futures::future::BoxFuture;
use headers::{Authorization, HeaderMapExt};
use http::{
header::HeaderValue, request::Builder, uri::InvalidUri, HeaderMap, Request, Response, Uri,
};
use hyper::{
body::{Body, HttpBody},
client,
client::{Client, HttpConnector},
};
use hyper_openssl::HttpsConnector;
use hyper_proxy::ProxyConnector;
use snafu::{ResultExt, Snafu};
use tower::Service;
use tower_http::{
classify::{ServerErrorsAsFailures, SharedClassifier},
trace::TraceLayer,
};
use tracing::{Instrument, Span};
use vector_lib::configurable::configurable_component;
use vector_lib::sensitive_string::SensitiveString;
use crate::{
config::ProxyConfig,
internal_events::{http_client, HttpServerRequestReceived, HttpServerResponseSent},
tls::{tls_connector_builder, MaybeTlsSettings, TlsError},
};
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum HttpError {
#[snafu(display("Failed to build TLS connector: {}", source))]
BuildTlsConnector { source: TlsError },
#[snafu(display("Failed to build HTTPS connector: {}", source))]
MakeHttpsConnector { source: openssl::error::ErrorStack },
#[snafu(display("Failed to build Proxy connector: {}", source))]
MakeProxyConnector { source: InvalidUri },
#[snafu(display("Failed to make HTTP(S) request: {}", source))]
CallRequest { source: hyper::Error },
#[snafu(display("Failed to build HTTP request: {}", source))]
BuildRequest { source: http::Error },
}
impl HttpError {
pub const fn is_retriable(&self) -> bool {
match self {
HttpError::BuildRequest { .. } | HttpError::MakeProxyConnector { .. } => false,
HttpError::CallRequest { .. }
| HttpError::BuildTlsConnector { .. }
| HttpError::MakeHttpsConnector { .. } => true,
}
}
}
pub type HttpClientFuture = <HttpClient as Service<http::Request<Body>>>::Future;
type HttpProxyConnector = ProxyConnector<HttpsConnector<HttpConnector>>;
pub struct HttpClient<B = Body> {
client: Client<HttpProxyConnector, B>,
user_agent: HeaderValue,
proxy_connector: HttpProxyConnector,
}
impl<B> HttpClient<B>
where
B: fmt::Debug + HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
{
pub fn new(
tls_settings: impl Into<MaybeTlsSettings>,
proxy_config: &ProxyConfig,
) -> Result<HttpClient<B>, HttpError> {
HttpClient::new_with_custom_client(tls_settings, proxy_config, &mut Client::builder())
}
pub fn new_with_custom_client(
tls_settings: impl Into<MaybeTlsSettings>,
proxy_config: &ProxyConfig,
client_builder: &mut client::Builder,
) -> Result<HttpClient<B>, HttpError> {
let proxy_connector = build_proxy_connector(tls_settings.into(), proxy_config)?;
let client = client_builder.build(proxy_connector.clone());
let app_name = crate::get_app_name();
let version = crate::get_version();
let user_agent = HeaderValue::from_str(&format!("{}/{}", app_name, version))
.expect("Invalid header value for user-agent!");
Ok(HttpClient {
client,
user_agent,
proxy_connector,
})
}
pub fn send(
&self,
mut request: Request<B>,
) -> BoxFuture<'static, Result<http::Response<Body>, HttpError>> {
let span = tracing::info_span!("http");
let _enter = span.enter();
default_request_headers(&mut request, &self.user_agent);
self.maybe_add_proxy_headers(&mut request);
emit!(http_client::AboutToSendHttpRequest { request: &request });
let response = self.client.request(request);
let fut = async move {
// Capture the time right before we issue the request.
// Request doesn't start the processing until we start polling it.
let before = std::time::Instant::now();
// Send request and wait for the result.
let response_result = response.await;
// Compute the roundtrip time it took to send the request and get
// the response or error.
let roundtrip = before.elapsed();
// Handle the errors and extract the response.
let response = response_result
.map_err(|error| {
// Emit the error into the internal events system.
emit!(http_client::GotHttpWarning {
error: &error,
roundtrip
});
error
})
.context(CallRequestSnafu)?;
// Emit the response into the internal events system.
emit!(http_client::GotHttpResponse {
response: &response,
roundtrip
});
Ok(response)
}
.instrument(span.clone().or_current());
Box::pin(fut)
}
fn maybe_add_proxy_headers(&self, request: &mut Request<B>) {
if let Some(proxy_headers) = self.proxy_connector.http_headers(request.uri()) {
for (k, v) in proxy_headers {
let request_headers = request.headers_mut();
if !request_headers.contains_key(k) {
request_headers.insert(k, v.into());
}
}
}
}
}
pub fn build_proxy_connector(
tls_settings: MaybeTlsSettings,
proxy_config: &ProxyConfig,
) -> Result<ProxyConnector<HttpsConnector<HttpConnector>>, HttpError> {
// Create dedicated TLS connector for the proxied connection with user TLS settings.
let tls = tls_connector_builder(&tls_settings)
.context(BuildTlsConnectorSnafu)?
.build();
let https = build_tls_connector(tls_settings)?;
let mut proxy = ProxyConnector::new(https).unwrap();
// Make proxy connector aware of user TLS settings by setting the TLS connector:
// https://github.com/vectordotdev/vector/issues/13683
proxy.set_tls(Some(tls));
proxy_config
.configure(&mut proxy)
.context(MakeProxyConnectorSnafu)?;
Ok(proxy)
}
pub fn build_tls_connector(
tls_settings: MaybeTlsSettings,
) -> Result<HttpsConnector<HttpConnector>, HttpError> {
let mut http = HttpConnector::new();
http.enforce_http(false);
let tls = tls_connector_builder(&tls_settings).context(BuildTlsConnectorSnafu)?;
let mut https = HttpsConnector::with_connector(http, tls).context(MakeHttpsConnectorSnafu)?;
let settings = tls_settings.tls().cloned();
https.set_callback(move |c, _uri| {
if let Some(settings) = &settings {
settings.apply_connect_configuration(c);
}
Ok(())
});
Ok(https)
}
fn default_request_headers<B>(request: &mut Request<B>, user_agent: &HeaderValue) {
if !request.headers().contains_key("User-Agent") {
request
.headers_mut()
.insert("User-Agent", user_agent.clone());
}
if !request.headers().contains_key("Accept-Encoding") {
// hardcoding until we support compressed responses:
// https://github.com/vectordotdev/vector/issues/5440
request
.headers_mut()
.insert("Accept-Encoding", HeaderValue::from_static("identity"));
}
}
impl<B> Service<Request<B>> for HttpClient<B>
where
B: fmt::Debug + HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error> + Send,
{
type Response = http::Response<Body>;
type Error = HttpError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<B>) -> Self::Future {
self.send(request)
}
}
impl<B> Clone for HttpClient<B> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
user_agent: self.user_agent.clone(),
proxy_connector: self.proxy_connector.clone(),
}
}
}
impl<B> fmt::Debug for HttpClient<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpClient")
.field("client", &self.client)
.field("user_agent", &self.user_agent)
.finish()
}
}
/// Configuration of the authentication strategy for HTTP requests.
///
/// HTTP authentication should be used with HTTPS only, as the authentication credentials are passed as an
/// HTTP header without any additional encryption beyond what is provided by the transport itself.
#[configurable_component]
#[derive(Clone, Debug, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "strategy")]
#[configurable(metadata(docs::enum_tag_description = "The authentication strategy to use."))]
pub enum Auth {
/// Basic authentication.
///
/// The username and password are concatenated and encoded via [base64][base64].
///
/// [base64]: https://en.wikipedia.org/wiki/Base64
Basic {
/// The basic authentication username.
#[configurable(metadata(docs::examples = "${USERNAME}"))]
#[configurable(metadata(docs::examples = "username"))]
user: String,
/// The basic authentication password.
#[configurable(metadata(docs::examples = "${PASSWORD}"))]
#[configurable(metadata(docs::examples = "password"))]
password: SensitiveString,
},
/// Bearer authentication.
///
/// The bearer token value (OAuth2, JWT, etc.) is passed as-is.
Bearer {
/// The bearer authentication token.
token: SensitiveString,
},
}
pub trait MaybeAuth: Sized {
fn choose_one(&self, other: &Self) -> crate::Result<Self>;
}
impl MaybeAuth for Option<Auth> {
fn choose_one(&self, other: &Self) -> crate::Result<Self> {
if self.is_some() && other.is_some() {
Err("Two authorization credentials was provided.".into())
} else {
Ok(self.clone().or_else(|| other.clone()))
}
}
}
impl Auth {
pub fn apply<B>(&self, req: &mut Request<B>) {
self.apply_headers_map(req.headers_mut())
}
pub fn apply_builder(&self, mut builder: Builder) -> Builder {
if let Some(map) = builder.headers_mut() {
self.apply_headers_map(map)
}
builder
}
pub fn apply_headers_map(&self, map: &mut HeaderMap) {
match &self {
Auth::Basic { user, password } => {
let auth = Authorization::basic(user.as_str(), password.inner());
map.typed_insert(auth);
}
Auth::Bearer { token } => match Authorization::bearer(token.inner()) {
Ok(auth) => map.typed_insert(auth),
Err(error) => error!(message = "Invalid bearer token.", token = %token, %error),
},
}
}
}
pub fn get_http_scheme_from_uri(uri: &Uri) -> &'static str {
// If there's no scheme, we just use "http" since it provides the most semantic relevance without inadvertently
// implying things it can't know i.e. returning "https" when we're not actually sure HTTPS was used.
uri.scheme_str().map_or("http", |scheme| match scheme {
"http" => "http",
"https" => "https",
// `http::Uri` ensures that we always get "http" or "https" if the URI is created with a well-formed scheme, but
// it also supports arbitrary schemes, which is where we bomb out down here, since we can't generate a static
// string for an arbitrary input string... and anything other than "http" and "https" makes no sense for an HTTP
// client anyways.
s => panic!("invalid URI scheme for HTTP client: {}", s),
})
}
/// Builds a [TraceLayer] configured for a HTTP server.
///
/// This layer emits HTTP specific telemetry for requests received, responses sent, and handler duration.
pub fn build_http_trace_layer(
span: Span,
) -> TraceLayer<
SharedClassifier<ServerErrorsAsFailures>,
impl Fn(&Request<Body>) -> Span + Clone,
impl Fn(&Request<Body>, &Span) + Clone,
impl Fn(&Response<Body>, Duration, &Span) + Clone,
(),
(),
(),
> {
TraceLayer::new_for_http()
.make_span_with(move |request: &Request<Body>| {
// This is an error span so that the labels are always present for metrics.
error_span!(
parent: &span,
"http-request",
method = %request.method(),
path = %request.uri().path(),
)
})
.on_request(Box::new(|_request: &Request<Body>, _span: &Span| {
emit!(HttpServerRequestReceived);
}))
.on_response(
|response: &Response<Body>, latency: Duration, _span: &Span| {
emit!(HttpServerResponseSent { response, latency });
},
)
.on_failure(())
.on_body_chunk(())
.on_eos(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_request_headers_defaults() {
let user_agent = HeaderValue::from_static("vector");
let mut request = Request::post("http://example.com").body(()).unwrap();
default_request_headers(&mut request, &user_agent);
assert_eq!(
request.headers().get("Accept-Encoding"),
Some(&HeaderValue::from_static("identity")),
);
assert_eq!(request.headers().get("User-Agent"), Some(&user_agent));
}
#[test]
fn test_default_request_headers_does_not_overwrite() {
let mut request = Request::post("http://example.com")
.header("Accept-Encoding", "gzip")
.header("User-Agent", "foo")
.body(())
.unwrap();
default_request_headers(&mut request, &HeaderValue::from_static("vector"));
assert_eq!(
request.headers().get("Accept-Encoding"),
Some(&HeaderValue::from_static("gzip")),
);
assert_eq!(
request.headers().get("User-Agent"),
Some(&HeaderValue::from_static("foo"))
);
}
}