1use crate::{HttpsLayerSettings, MaybeHttpsStream};
2use boring::error::ErrorStack;
3use boring::ssl::{ConnectConfiguration, SslConnector, SslConnectorBuilder, SslMethod, SslRef};
4use http::uri::Scheme;
5use http::Uri;
6use hyper::rt::{Read, ReadBufCursor, Write};
7use hyper_util::client::legacy::connect::{Connected, Connection, HttpConnector};
8use hyper_util::rt::TokioIo;
9use std::error::Error;
10use std::fmt;
11use std::future::Future;
12use std::io;
13use std::pin::Pin;
14use std::task::{Context, Poll};
15use tokio::io::{AsyncRead, AsyncWrite};
16use tokio_boring::client::{AsTarget, Connector, Target};
17use tower_layer::Layer;
18use tower_service::Service;
19
20#[derive(Clone)]
22pub struct HttpsConnector<T> {
23 http: T,
24 inner: Inner,
25}
26
27impl HttpsConnector<HttpConnector> {
28 pub fn new() -> Result<HttpsConnector<HttpConnector>, ErrorStack> {
33 let mut http = HttpConnector::new();
34 http.enforce_http(false);
35
36 HttpsLayer::new().map(|l| l.layer(http))
37 }
38}
39
40impl<S, T> HttpsConnector<S>
41where
42 S: Service<Uri, Response = TokioIo<T>> + Send,
43 S::Error: Into<Box<dyn Error + Send + Sync>>,
44 S::Future: Unpin + Send + 'static,
45 T: AsyncRead + AsyncWrite + Connection + Unpin + fmt::Debug + Sync + Send + 'static,
46{
47 pub fn with_connector(
51 http: S,
52 ssl: SslConnectorBuilder,
53 ) -> Result<HttpsConnector<S>, ErrorStack> {
54 HttpsLayer::with_connector(ssl).map(|l| l.layer(http))
55 }
56
57 pub fn set_callback<F>(&mut self, callback: F)
63 where
64 F: Fn(&mut ConnectConfiguration, &Uri) -> Result<(), ErrorStack> + 'static + Sync + Send,
65 {
66 self.inner
67 .ssl
68 .on_config(move |config, target| callback(config, &target.uri));
69 }
70
71 pub fn set_ssl_callback<F>(&mut self, callback: F)
73 where
74 F: Fn(&mut SslRef, &Uri) -> Result<(), ErrorStack> + 'static + Sync + Send,
75 {
76 self.inner
77 .ssl
78 .on_ssl(move |ssl, target| callback(ssl, &target.uri));
79 }
80}
81
82pub struct HttpsLayer {
84 inner: Inner,
85}
86
87#[derive(Clone)]
88struct Inner {
89 ssl: Connector<HttpTarget>,
90}
91
92struct HttpTarget {
93 uri: Uri,
94 peer_name: String,
95}
96
97impl HttpTarget {
98 fn try_new(uri: Uri) -> Result<Self, &'static str> {
99 let peer_name = uri.host().ok_or("URI missing host")?.to_owned();
100 Ok(Self { uri, peer_name })
101 }
102}
103
104impl AsTarget for HttpTarget {
105 fn as_target(&self) -> Target<'_> {
106 Target::new(&self.peer_name, self.uri.port_u16().unwrap_or(443))
107 }
108}
109
110fn effective_session_cache_capacity(settings: &HttpsLayerSettings) -> usize {
111 settings.session_cache_capacity.max(1)
114}
115
116impl HttpsLayer {
117 pub fn new() -> Result<HttpsLayer, ErrorStack> {
121 let mut ssl = SslConnector::builder(SslMethod::tls())?;
122
123 ssl.set_alpn_protos(b"\x02h2\x08http/1.1")?;
124
125 Self::with_connector(ssl)
126 }
127
128 pub fn with_connector(ssl: SslConnectorBuilder) -> Result<HttpsLayer, ErrorStack> {
132 Self::with_connector_and_settings(ssl, HttpsLayerSettings::default())
133 }
134
135 pub fn with_connector_and_settings(
137 ssl: SslConnectorBuilder,
138 settings: HttpsLayerSettings,
139 ) -> Result<HttpsLayer, ErrorStack> {
140 let session_cache_capacity = effective_session_cache_capacity(&settings);
141 let ssl =
142 Connector::<HttpTarget>::with_session_cache_capacity(ssl, session_cache_capacity)?;
143
144 Ok(HttpsLayer {
145 inner: Inner { ssl },
146 })
147 }
148
149 pub fn set_callback<F>(&mut self, callback: F)
155 where
156 F: Fn(&mut ConnectConfiguration, &Uri) -> Result<(), ErrorStack> + 'static + Sync + Send,
157 {
158 self.inner
159 .ssl
160 .on_config(move |config, target| callback(config, &target.uri));
161 }
162
163 pub fn set_ssl_callback<F>(&mut self, callback: F)
165 where
166 F: Fn(&mut SslRef, &Uri) -> Result<(), ErrorStack> + 'static + Sync + Send,
167 {
168 self.inner
169 .ssl
170 .on_ssl(move |ssl, target| callback(ssl, &target.uri));
171 }
172}
173
174impl<S> Layer<S> for HttpsLayer {
175 type Service = HttpsConnector<S>;
176
177 fn layer(&self, inner: S) -> HttpsConnector<S> {
178 HttpsConnector {
179 http: inner,
180 inner: self.inner.clone(),
181 }
182 }
183}
184
185impl<T, S> Service<Uri> for HttpsConnector<S>
186where
187 S: Service<Uri, Response = TokioIo<T>> + Send,
188 S::Error: Into<Box<dyn Error + Send + Sync>>,
189 S::Future: Unpin + Send + 'static,
190 T: AsyncRead + AsyncWrite + Connection + Unpin + fmt::Debug + Sync + Send + 'static,
191{
192 type Response = MaybeHttpsStream<T>;
193 type Error = Box<dyn Error + Sync + Send>;
194 #[allow(clippy::type_complexity)]
195 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
196
197 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
198 self.http.poll_ready(cx).map_err(Into::into)
199 }
200
201 fn call(&mut self, uri: Uri) -> Self::Future {
202 let is_tls_scheme = uri
203 .scheme()
204 .map(|s| s == &Scheme::HTTPS || s.as_str() == "wss")
205 .unwrap_or(false);
206
207 let tls_setup = if is_tls_scheme {
208 Some((self.inner.ssl.clone(), uri.clone()))
209 } else {
210 None
211 };
212
213 let connect = self.http.call(uri);
214
215 let f = async {
216 let conn = connect.await.map_err(Into::into)?.into_inner();
217
218 let Some((ssl, uri)) = tls_setup else {
219 return Ok(MaybeHttpsStream::Http(conn));
220 };
221
222 let target = HttpTarget::try_new(uri)?;
223 let stream = ssl.connect(&target, conn).await?;
224
225 Ok(MaybeHttpsStream::Https(stream))
226 };
227
228 Box::pin(f)
229 }
230}
231
232impl<T> Connection for MaybeHttpsStream<T>
233where
234 T: Connection,
235{
236 fn connected(&self) -> Connected {
237 match self {
238 MaybeHttpsStream::Http(s) => s.connected(),
239 MaybeHttpsStream::Https(s) => {
240 let mut connected = s.get_ref().connected();
241
242 if s.ssl().selected_alpn_protocol() == Some(b"h2") {
243 connected = connected.negotiated_h2();
244 }
245
246 connected
247 }
248 }
249 }
250}
251
252impl<T> Read for MaybeHttpsStream<T>
253where
254 T: AsyncRead + AsyncWrite + Unpin,
255{
256 fn poll_read(
257 mut self: Pin<&mut Self>,
258 cx: &mut Context<'_>,
259 buf: ReadBufCursor<'_>,
260 ) -> Poll<Result<(), io::Error>> {
261 match &mut *self {
262 MaybeHttpsStream::Http(inner) => Pin::new(&mut TokioIo::new(inner)).poll_read(cx, buf),
263 MaybeHttpsStream::Https(inner) => Pin::new(&mut TokioIo::new(inner)).poll_read(cx, buf),
264 }
265 }
266}
267
268impl<T> Write for MaybeHttpsStream<T>
269where
270 T: AsyncRead + AsyncWrite + Unpin,
271{
272 fn poll_write(
273 mut self: Pin<&mut Self>,
274 ctx: &mut Context<'_>,
275 buf: &[u8],
276 ) -> Poll<io::Result<usize>> {
277 match &mut *self {
278 MaybeHttpsStream::Http(inner) => {
279 Pin::new(&mut TokioIo::new(inner)).poll_write(ctx, buf)
280 }
281 MaybeHttpsStream::Https(inner) => {
282 Pin::new(&mut TokioIo::new(inner)).poll_write(ctx, buf)
283 }
284 }
285 }
286
287 fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
288 match &mut *self {
289 MaybeHttpsStream::Http(inner) => Pin::new(&mut TokioIo::new(inner)).poll_flush(ctx),
290 MaybeHttpsStream::Https(inner) => Pin::new(&mut TokioIo::new(inner)).poll_flush(ctx),
291 }
292 }
293
294 fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
295 match &mut *self {
296 MaybeHttpsStream::Http(inner) => Pin::new(&mut TokioIo::new(inner)).poll_shutdown(ctx),
297 MaybeHttpsStream::Https(inner) => Pin::new(&mut TokioIo::new(inner)).poll_shutdown(ctx),
298 }
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::{effective_session_cache_capacity, HttpTarget};
305 use crate::HttpsLayerSettings;
306
307 #[test]
308 fn zero_session_cache_capacity_preserves_legacy_behavior() {
309 let mut settings = HttpsLayerSettings::builder();
310 settings.set_session_cache_capacity(0);
311
312 assert_eq!(effective_session_cache_capacity(&settings.build()), 1);
313 }
314
315 #[test]
316 fn missing_host_error_is_preserved() {
317 let error = HttpTarget::try_new("/missing-host".parse().unwrap())
318 .err()
319 .expect("missing host should fail");
320
321 assert_eq!(error, "URI missing host");
322 }
323}