Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-hyper/src/connector.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use crate::{error::Error, stream::MaybeHttpsStream};
5 use http::uri::Uri;
6 use hyper::rt::{Read, Write};
7 use hyper_util::{
8 client::legacy::connect::{Connection, HttpConnector},
9 rt::TokioIo,
10 };
11 use s2n_tls::{config::Config, connection};
12 use s2n_tls_tokio::TlsConnector;
13 use std::{
14 future::Future,
15 pin::Pin,
16 task::{Context, Poll},
17 };
18 use tower_service::Service;
19
20 /// hyper-compatible connector used to negotiate HTTPS.
21 ///
22 /// hyper clients use a connector to send and receive HTTP requests over an underlying IO stream. By
23 /// default, hyper provides `hyper_util::client::legacy::connect::HttpConnector` for this purpose,
24 /// which sends and receives requests over TCP. The `HttpsConnector` struct wraps an HTTP connector,
25 /// and uses it to negotiate TLS when the HTTPS scheme is in use.
26 #[derive(Clone)]
27 pub struct HttpsConnector<Http, ConnBuilder = Config> {
28 http: Http,
29 conn_builder: ConnBuilder,
30 plaintext_http: bool,
31 }
32
33 impl<ConnBuilder> HttpsConnector<HttpConnector, ConnBuilder>
34 where
35 ConnBuilder: connection::Builder,
36 <ConnBuilder as connection::Builder>::Output: Unpin,
37 {
38 /// Creates a new `HttpsConnector` with the default settings.
39 ///
40 /// Use `HttpsConnector::builder()` instead to configure an `HttpsConnector`.
41 ///
42 /// `conn_builder` will be used to produce the s2n-tls Connections used for negotiating HTTPS,
43 /// which can be an `s2n_tls::config::Config` or other `s2n_tls::connection::Builder`.
44 ///
45 /// Note that s2n-tls-hyper will override the ALPN extension to negotiate HTTP. Any ALPN values
46 /// configured on `conn_builder` with APIs like
47 /// `s2n_tls::config::Builder::set_application_protocol_preference()` will be ignored.
48 pub fn new(conn_builder: ConnBuilder) -> HttpsConnector<HttpConnector, ConnBuilder> {
49 HttpsConnector::builder(conn_builder).build()
50 }
51
52 /// Creates a `Builder` to configure a new `HttpsConnector`.
53 ///
54 /// `conn_builder` will be used to produce the s2n-tls Connections used for negotiating HTTPS,
55 /// which can be an `s2n_tls::config::Config` or other `s2n_tls::connection::Builder`.
56 ///
57 /// This API creates a `Builder` with the default hyper `HttpConnector`. To use an existing HTTP
58 /// connector, use `HttpsConnector::builder_with_http()`.
59 ///
60 /// Note that s2n-tls-hyper will override the ALPN extension to negotiate HTTP. Any ALPN values
61 /// configured on `conn_builder` with APIs like
62 /// `s2n_tls::config::Builder::set_application_protocol_preference()` will be ignored.
63 pub fn builder(conn_builder: ConnBuilder) -> Builder<HttpConnector, ConnBuilder> {
64 let mut http = HttpConnector::new();
65
66 // By default, the `HttpConnector` only allows the HTTP URI scheme to be used. To negotiate
67 // HTTP over TLS via the HTTPS scheme, `enforce_http` must be disabled.
68 http.enforce_http(false);
69
70 HttpsConnector::builder_with_http(http, conn_builder)
71 }
72 }
73
74 impl<Http, ConnBuilder> HttpsConnector<Http, ConnBuilder>
75 where
76 ConnBuilder: connection::Builder,
77 <ConnBuilder as connection::Builder>::Output: Unpin,
78 {
79 /// Creates a `Builder` to configure a new `HttpsConnector`.
80 ///
81 /// `conn_builder` will be used to produce the s2n-tls Connections used for negotiating HTTPS,
82 /// which can be an `s2n_tls::config::Config` or other `s2n_tls::connection::Builder`.
83 ///
84 /// This API allows an `HttpsConnector` to be constructed with an existing HTTP connector, as
85 /// follows:
86 /// ```
87 /// use s2n_tls_hyper::connector::HttpsConnector;
88 /// use s2n_tls::config::Config;
89 /// use hyper_util::client::legacy::connect::HttpConnector;
90 ///
91 /// let mut http = HttpConnector::new();
92 ///
93 /// // Ensure that the HTTP connector permits the HTTPS scheme.
94 /// http.enforce_http(false);
95 ///
96 /// let connector = HttpsConnector::builder_with_http(http, Config::default()).build();
97 /// ```
98 ///
99 /// `HttpsConnector::builder()` can be used to create the HTTP connector automatically.
100 ///
101 /// Note that s2n-tls-hyper will override the ALPN extension to negotiate HTTP. Any ALPN values
102 /// configured on `conn_builder` with APIs like
103 /// `s2n_tls::config::Builder::set_application_protocol_preference()` will be ignored.
104 pub fn builder_with_http(http: Http, conn_builder: ConnBuilder) -> Builder<Http, ConnBuilder> {
105 Builder {
106 http,
107 conn_builder,
108 plaintext_http: false,
109 }
110 }
111 }
112
113 /// Builder used to configure an `HttpsConnector`. Create a new Builder with
114 /// `HttpsConnector::builder`.
115 pub struct Builder<Http, ConnBuilder> {
116 http: Http,
117 conn_builder: ConnBuilder,
118 plaintext_http: bool,
119 }
120
121 impl<Http, ConnBuilder> Builder<Http, ConnBuilder> {
122 /// If enabled, allows communication with plaintext HTTP endpoints in addition to secure HTTPS
123 /// endpoints (default: false).
124 pub fn with_plaintext_http(&mut self, enabled: bool) -> &mut Self {
125 self.plaintext_http = enabled;
126 self
127 }
128
129 /// Builds a new `HttpsConnector`.
130 pub fn build(self) -> HttpsConnector<Http, ConnBuilder> {
131 HttpsConnector {
132 http: self.http,
133 conn_builder: self.conn_builder,
134 plaintext_http: self.plaintext_http,
135 }
136 }
137 }
138
139 // hyper connectors MUST implement `hyper_util::client::legacy::connect::Connect`, which is an alias
140 // for the `tower_service::Service` trait where `Service` is implemented for `http::uri::Uri`, and
141 // `Service::Response` implements traits for compatibility with hyper:
142 // https://docs.rs/hyper-util/latest/hyper_util/client/legacy/connect/trait.Connect.html
143 //
144 // The hyper compatibility traits for `Service::Response` are implemented in `MaybeHttpsStream`.
145 impl<Http, ConnBuilder> Service<Uri> for HttpsConnector<Http, ConnBuilder>
146 where
147 Http: Service<Uri>,
148 Http::Response: Read + Write + Connection + Unpin + Send + 'static,
149 Http::Future: Send + 'static,
150 Http::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
151 ConnBuilder: connection::Builder + Send + Sync + 'static,
152 <ConnBuilder as connection::Builder>::Output: Unpin + Send,
153 {
154 type Response = MaybeHttpsStream<Http::Response, ConnBuilder>;
155 type Error = Error;
156 type Future = Pin<
157 Box<
158 dyn Future<Output = Result<MaybeHttpsStream<Http::Response, ConnBuilder>, Error>>
159 + Send,
160 >,
161 >;
162
163 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
164 match self.http.poll_ready(cx) {
165 Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
166 Poll::Ready(Err(e)) => Poll::Ready(Err(Error::HttpError(e.into()))),
167 Poll::Pending => Poll::Pending,
168 }
169 }
170
171 fn call(&mut self, req: Uri) -> Self::Future {
172 match req.scheme() {
173 Some(scheme) if scheme == &http::uri::Scheme::HTTPS => (),
174 Some(scheme) if scheme == &http::uri::Scheme::HTTP && self.plaintext_http => {
175 let call = self.http.call(req);
176 return Box::pin(async move {
177 let tcp = call.await.map_err(|e| Error::HttpError(e.into()))?;
178 Ok(MaybeHttpsStream::Http(tcp))
179 });
180 }
181 _ => {
182 return Box::pin(async move { Err(Error::InvalidScheme) });
183 }
184 }
185
186 // Attempt to negotiate HTTP/2 by including it in the ALPN extension. Other supported HTTP
187 // versions are also included to prevent the server from rejecting the TLS connection if
188 // HTTP/2 isn't supported:
189 //
190 // https://datatracker.ietf.org/doc/html/rfc7301#section-3.2
191 // In the event that the server supports no
192 // protocols that the client advertises, then the server SHALL respond
193 // with a fatal "no_application_protocol" alert.
194 let builder = connection::ModifiedBuilder::new(self.conn_builder.clone(), |conn| {
195 conn.set_application_protocol_preference([
196 b"h2".to_vec(),
197 b"http/1.1".to_vec(),
198 b"http/1.0".to_vec(),
199 ])
200 });
201
202 // IPv6 addresses are enclosed in square brackets within the host of a URI (e.g.
203 // `https://[::1:2:3:4]/`). These square brackets aren't part of the domain itself, so they
204 // are trimmed off to provide the proper server name to s2n-tls-tokio (e.g. `::1:2:3:4`).
205 let mut domain = req.host().unwrap_or("");
206 if let Some(trimmed) = domain.strip_prefix('[') {
207 if let Some(trimmed) = trimmed.strip_suffix(']') {
208 domain = trimmed;
209 }
210 }
211 let domain = domain.to_owned();
212
213 let call = self.http.call(req);
214 Box::pin(async move {
215 // `HttpsConnector` wraps an HTTP connector that also implements `Service<Uri>`.
216 // `call()` is invoked on the wrapped connector to get the underlying hyper TCP stream,
217 // which is converted into a tokio-compatible stream with `hyper_util::rt::TokioIo`.
218 let tcp = call.await.map_err(|e| Error::HttpError(e.into()))?;
219 let tcp = TokioIo::new(tcp);
220
221 let connector = TlsConnector::new(builder);
222 let tls = connector
223 .connect(&domain, tcp)
224 .await
225 .map_err(Error::TlsError)?;
226
227 Ok(MaybeHttpsStream::Https(TokioIo::new(tls)))
228 })
229 }
230 }
231
232 #[cfg(test)]
233 mod tests {
234 use super::*;
235 use bytes::Bytes;
236 use http_body_util::Empty;
237 use hyper_util::{client::legacy::Client, rt::TokioExecutor};
238 use std::{error::Error as StdError, str::FromStr};
239
240 #[tokio::test]
241 async fn connector_creation() {
242 let config = Config::default();
243 let connector_from_new = HttpsConnector::new(config.clone());
244 let _assert_type: HttpsConnector<HttpConnector, Config> = connector_from_new;
245
246 let connector_from_builder = HttpsConnector::builder(config.clone()).build();
247 let _assert_type: HttpsConnector<HttpConnector, Config> = connector_from_builder;
248
249 let http: u32 = 10;
250 let connector_from_builder_with_http =
251 HttpsConnector::builder_with_http(http, config.clone()).build();
252 let _assert_type: HttpsConnector<u32, Config> = connector_from_builder_with_http;
253
254 let builder = HttpsConnector::builder(config.clone());
255 let connector_from_builder = builder.build();
256 let _assert_type: HttpsConnector<HttpConnector, Config> = connector_from_builder;
257 }
258
259 #[tokio::test]
260 async fn test_invalid_scheme() -> Result<(), Box<dyn StdError>> {
261 let connector = HttpsConnector::new(Config::default());
262 let client: Client<_, Empty<Bytes>> =
263 Client::builder(TokioExecutor::new()).build(connector);
264
265 // Attempt to make a request with an arbitrary invalid scheme.
266 let uri = Uri::from_str("notascheme://www.amazon.com")?;
267 let error = client.get(uri).await.unwrap_err();
268
269 // Ensure that an InvalidScheme error is returned.
270 let error = error.source().unwrap().downcast_ref::<Error>().unwrap();
271 assert!(matches!(error, Error::InvalidScheme));
272
273 // Ensure that the error can produce a valid message
274 assert!(!error.to_string().is_empty());
275
276 Ok(())
277 }
278
279 #[tokio::test]
280 async fn default_builder() -> Result<(), Box<dyn StdError>> {
281 // Ensure that plaintext HTTP is disabled by default.
282 let connector = HttpsConnector::builder(Config::default()).build();
283 assert!(!connector.plaintext_http);
284
285 Ok(())
286 }
287 }