1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

actix-web: Add rustls 0.23 (#3363)

* Fix type confusion in some scenarios

When the feature for rustls 0.22 is enabled, and rustls 0.23 is also
present in a project, there suddently exist multiple paths for errors
when building middleware chains due to the use of two consecutive `?`
operators without specifying the intermediate error type.

This commit addresses the issue by removing the first `?`, so that the
first error type will always be known, and the second `?` always has a
well defined implementation.

* Add CHANGES entry about type confusion

* actix-http: add rustls 0.23 support

* actix-http: update ws example, tests for rustls 0.23

* actix-http: add rustls 0.23 to changelog

* Update comments to mention 0.23 instead of 0.22

* awc: add rustls 0.23 support

This also fixes certificate lookup when native-roots is enabled for rustls 0.22.

* awc: update changelog for rustls 0.23

* awc: Add base rustls-0_23 feature without roots to better enable custom config

* actix-test: add rustls-0.23

* actix-test: add rustls 0.23 to changelog

* awc: update changelog with rustls 0.23 tweaks

* actix-web: add rustls 0.23

* Add rustls-0_23 to CI

* Update tls_rustls.rs

* review nits

* review nits part 2

* fix doc test

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
asonix 2024-05-18 14:05:58 -05:00 committed by GitHub
parent 48d7adb7bf
commit 2e63ff5928
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 292 additions and 24 deletions

View File

@ -12,11 +12,12 @@
//! Protocol: HTTP/1.1 //! Protocol: HTTP/1.1
//! ``` //! ```
extern crate tls_rustls_023 as rustls;
use std::io; use std::io;
use actix_http::{Error, HttpService, Request, Response}; use actix_http::{Error, HttpService, Request, Response};
use actix_utils::future::ok; use actix_utils::future::ok;
use tls_rustls_023 as rustls;
#[actix_rt::main] #[actix_rt::main]
async fn main() -> io::Result<()> { async fn main() -> io::Result<()> {

View File

@ -2,6 +2,7 @@
## Unreleased ## Unreleased
- Add `TestServerConfig::rustls_0_23()` method for Rustls v0.23 support behind new `rustls-0_23` crate feature.
- Minimum supported Rust version (MSRV) is now 1.72. - Minimum supported Rust version (MSRV) is now 1.72.
- Various types from `awc`, such as `ClientRequest` and `ClientResponse`, are now re-exported. - Various types from `awc`, such as `ClientRequest` and `ClientResponse`, are now re-exported.

View File

@ -29,6 +29,8 @@ rustls-0_20 = ["tls-rustls-0_20", "actix-http/rustls-0_20", "awc/rustls-0_20"]
rustls-0_21 = ["tls-rustls-0_21", "actix-http/rustls-0_21", "awc/rustls-0_21"] rustls-0_21 = ["tls-rustls-0_21", "actix-http/rustls-0_21", "awc/rustls-0_21"]
# TLS via Rustls v0.22 # TLS via Rustls v0.22
rustls-0_22 = ["tls-rustls-0_22", "actix-http/rustls-0_22", "awc/rustls-0_22-webpki-roots"] rustls-0_22 = ["tls-rustls-0_22", "actix-http/rustls-0_22", "awc/rustls-0_22-webpki-roots"]
# TLS via Rustls v0.23
rustls-0_23 = ["tls-rustls-0_23", "actix-http/rustls-0_23", "awc/rustls-0_23-webpki-roots"]
# TLS via OpenSSL # TLS via OpenSSL
openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"] openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
@ -53,4 +55,5 @@ tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true } tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true }
tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true } tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true }
tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true } tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true }
tls-rustls-0_23 = { package = "rustls", version = "0.23", default-features = false, optional = true }
tokio = { version = "1.24.2", features = ["sync"] } tokio = { version = "1.24.2", features = ["sync"] }

View File

@ -145,6 +145,8 @@ where
StreamType::Rustls021(_) => true, StreamType::Rustls021(_) => true,
#[cfg(feature = "rustls-0_22")] #[cfg(feature = "rustls-0_22")]
StreamType::Rustls022(_) => true, StreamType::Rustls022(_) => true,
#[cfg(feature = "rustls-0_23")]
StreamType::Rustls023(_) => true,
}; };
// run server in separate orphaned thread // run server in separate orphaned thread
@ -371,6 +373,48 @@ where
.rustls_0_22(config.clone()) .rustls_0_22(config.clone())
}), }),
}, },
#[cfg(feature = "rustls-0_23")]
StreamType::Rustls023(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.h1(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_23(config.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.h2(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_23(config.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.finish(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_23(config.clone())
}),
},
} }
.expect("test server could not be created"); .expect("test server could not be created");
@ -447,6 +491,8 @@ enum StreamType {
Rustls021(tls_rustls_0_21::ServerConfig), Rustls021(tls_rustls_0_21::ServerConfig),
#[cfg(feature = "rustls-0_22")] #[cfg(feature = "rustls-0_22")]
Rustls022(tls_rustls_0_22::ServerConfig), Rustls022(tls_rustls_0_22::ServerConfig),
#[cfg(feature = "rustls-0_23")]
Rustls023(tls_rustls_0_23::ServerConfig),
} }
/// Create default test server config. /// Create default test server config.
@ -537,6 +583,13 @@ impl TestServerConfig {
self self
} }
/// Accepts secure connections via Rustls v0.23.
#[cfg(feature = "rustls-0_23")]
pub fn rustls_0_23(mut self, config: tls_rustls_0_23::ServerConfig) -> Self {
self.stream = StreamType::Rustls023(config);
self
}
/// Sets client timeout for first request. /// Sets client timeout for first request.
pub fn client_request_timeout(mut self, dur: Duration) -> Self { pub fn client_request_timeout(mut self, dur: Duration) -> Self {
self.client_request_timeout = dur; self.client_request_timeout = dur;

View File

@ -5,6 +5,9 @@
### Added ### Added
- Add `unicode` crate feature (on-by-default) to switch between `regex` and `regex-lite` as a trade-off between full unicode support and binary size. - Add `unicode` crate feature (on-by-default) to switch between `regex` and `regex-lite` as a trade-off between full unicode support and binary size.
- Add `rustls-0_23` crate feature.
- Add `HttpServer::{bind_rustls_0_23, listen_rustls_0_23}()` builder methods.
- Add `HttpServer::tls_handshake_timeout()` builder method for `rustls-0_22` and `rustls-0_23`.
### Changed ### Changed

View File

@ -27,6 +27,7 @@ features = [
"rustls-0_20", "rustls-0_20",
"rustls-0_21", "rustls-0_21",
"rustls-0_22", "rustls-0_22",
"rustls-0_23",
"compress-brotli", "compress-brotli",
"compress-gzip", "compress-gzip",
"compress-zstd", "compress-zstd",
@ -71,6 +72,8 @@ rustls-0_20 = ["http2", "actix-http/rustls-0_20", "actix-tls/accept", "actix-tls
rustls-0_21 = ["http2", "actix-http/rustls-0_21", "actix-tls/accept", "actix-tls/rustls-0_21"] rustls-0_21 = ["http2", "actix-http/rustls-0_21", "actix-tls/accept", "actix-tls/rustls-0_21"]
# TLS via Rustls v0.22 # TLS via Rustls v0.22
rustls-0_22 = ["http2", "actix-http/rustls-0_22", "actix-tls/accept", "actix-tls/rustls-0_22"] rustls-0_22 = ["http2", "actix-http/rustls-0_22", "actix-tls/accept", "actix-tls/rustls-0_22"]
# TLS via Rustls v0.23
rustls-0_23 = ["http2", "actix-http/rustls-0_23", "actix-tls/accept", "actix-tls/rustls-0_23"]
# Full unicode support # Full unicode support
unicode = ["dep:regex", "actix-router/unicode"] unicode = ["dep:regex", "actix-router/unicode"]
@ -122,7 +125,7 @@ url = "2.1"
[dev-dependencies] [dev-dependencies]
actix-files = "0.6" actix-files = "0.6"
actix-test = { version = "0.1", features = ["openssl", "rustls-0_22"] } actix-test = { version = "0.1", features = ["openssl", "rustls-0_23"] }
awc = { version = "3", features = ["openssl"] } awc = { version = "3", features = ["openssl"] }
brotli = "6" brotli = "6"
@ -137,7 +140,7 @@ rustls-pemfile = "2"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
static_assertions = "1" static_assertions = "1"
tls-openssl = { package = "openssl", version = "0.10.55" } tls-openssl = { package = "openssl", version = "0.10.55" }
tls-rustls = { package = "rustls", version = "0.22" } tls-rustls = { package = "rustls", version = "0.23" }
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
zstd = "0.13" zstd = "0.13"

View File

@ -64,7 +64,10 @@
//! - `compress-gzip` - gzip and deflate content encoding compression support (enabled by default) //! - `compress-gzip` - gzip and deflate content encoding compression support (enabled by default)
//! - `compress-zstd` - zstd content encoding compression support (enabled by default) //! - `compress-zstd` - zstd content encoding compression support (enabled by default)
//! - `openssl` - HTTPS support via `openssl` crate, supports `HTTP/2` //! - `openssl` - HTTPS support via `openssl` crate, supports `HTTP/2`
//! - `rustls` - HTTPS support via `rustls` crate, supports `HTTP/2` //! - `rustls` - HTTPS support via `rustls` 0.20 crate, supports `HTTP/2`
//! - `rustls-0_21` - HTTPS support via `rustls` 0.21 crate, supports `HTTP/2`
//! - `rustls-0_22` - HTTPS support via `rustls` 0.22 crate, supports `HTTP/2`
//! - `rustls-0_23` - HTTPS support via `rustls` 0.23 crate, supports `HTTP/2`
//! - `secure-cookies` - secure cookies support //! - `secure-cookies` - secure cookies support
#![deny(rust_2018_idioms, nonstandard_style)] #![deny(rust_2018_idioms, nonstandard_style)]

View File

@ -12,6 +12,7 @@ use std::{
feature = "rustls-0_20", feature = "rustls-0_20",
feature = "rustls-0_21", feature = "rustls-0_21",
feature = "rustls-0_22", feature = "rustls-0_22",
feature = "rustls-0_23",
))] ))]
use actix_http::TlsAcceptorConfig; use actix_http::TlsAcceptorConfig;
use actix_http::{body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response}; use actix_http::{body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response};
@ -242,7 +243,13 @@ where
/// time, the connection is closed. /// time, the connection is closed.
/// ///
/// By default, the handshake timeout is 3 seconds. /// By default, the handshake timeout is 3 seconds.
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))] #[cfg(any(
feature = "openssl",
feature = "rustls-0_20",
feature = "rustls-0_21",
feature = "rustls-0_22",
feature = "rustls-0_23",
))]
pub fn tls_handshake_timeout(self, dur: Duration) -> Self { pub fn tls_handshake_timeout(self, dur: Duration) -> Self {
self.config self.config
.lock() .lock()
@ -270,6 +277,10 @@ where
/// Rustls v0.20. /// Rustls v0.20.
/// - `actix_tls::accept::rustls_0_21::TlsStream<actix_web::rt::net::TcpStream>` when using /// - `actix_tls::accept::rustls_0_21::TlsStream<actix_web::rt::net::TcpStream>` when using
/// Rustls v0.21. /// Rustls v0.21.
/// - `actix_tls::accept::rustls_0_22::TlsStream<actix_web::rt::net::TcpStream>` when using
/// Rustls v0.22.
/// - `actix_tls::accept::rustls_0_23::TlsStream<actix_web::rt::net::TcpStream>` when using
/// Rustls v0.23.
/// - `actix_web::rt::net::TcpStream` when no encryption is used. /// - `actix_web::rt::net::TcpStream` when no encryption is used.
/// ///
/// See the `on_connect` example for additional details. /// See the `on_connect` example for additional details.
@ -466,6 +477,25 @@ where
Ok(self) Ok(self)
} }
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls v0.23.
///
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_23")]
pub fn bind_rustls_0_23<A: net::ToSocketAddrs>(
mut self,
addrs: A,
config: actix_tls::accept::rustls_0_23::reexports::ServerConfig,
) -> io::Result<Self> {
let sockets = bind_addrs(addrs, self.backlog)?;
for lst in sockets {
self = self.listen_rustls_0_23_inner(lst, config.clone())?;
}
Ok(self)
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using OpenSSL. /// using OpenSSL.
/// ///
@ -595,7 +625,7 @@ where
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// Binds to existing listener for accepting incoming TLS connection requests using Rustls
/// v0.21. /// v0.21.
/// ///
/// See [`listen()`](Self::listen) for more details on the `lst` argument. /// See [`listen()`](Self::listen()) for more details on the `lst` argument.
/// ///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones. /// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_21")] #[cfg(feature = "rustls-0_21")]
@ -712,7 +742,7 @@ where
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// Binds to existing listener for accepting incoming TLS connection requests using Rustls
/// v0.22. /// v0.22.
/// ///
/// See [`listen()`](Self::listen) for more details on the `lst` argument. /// See [`listen()`](Self::listen()) for more details on the `lst` argument.
/// ///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones. /// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_22")] #[cfg(feature = "rustls-0_22")]
@ -775,6 +805,72 @@ where
Ok(self) Ok(self)
} }
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls
/// v0.23.
///
/// See [`listen()`](Self::listen()) for more details on the `lst` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_23")]
pub fn listen_rustls_0_23(
self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_23::reexports::ServerConfig,
) -> io::Result<Self> {
self.listen_rustls_0_23_inner(lst, config)
}
#[cfg(feature = "rustls-0_23")]
fn listen_rustls_0_23_inner(
mut self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_23::reexports::ServerConfig,
) -> io::Result<Self> {
let factory = self.factory.clone();
let cfg = self.config.clone();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
scheme: "https",
});
let on_connect_fn = self.on_connect_fn.clone();
self.builder =
self.builder
.listen(format!("actix-web-service-{}", addr), lst, move || {
let c = cfg.lock().unwrap();
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
let svc = HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout);
let svc = if let Some(handler) = on_connect_fn.clone() {
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
} else {
svc
};
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
let acceptor_config = match c.tls_handshake_timeout {
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
None => TlsAcceptorConfig::default(),
};
svc.finish(map_config(fac, move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.rustls_0_23_with_config(config.clone(), acceptor_config)
})?;
Ok(self)
}
/// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL. /// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL.
/// ///
/// See [`listen()`](Self::listen) for more details on the `lst` argument. /// See [`listen()`](Self::listen) for more details on the `lst` argument.

View File

@ -1,6 +1,6 @@
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
extern crate tls_openssl as openssl; extern crate tls_openssl as openssl;
#[cfg(feature = "rustls-0_22")] #[cfg(feature = "rustls-0_23")]
extern crate tls_rustls as rustls; extern crate tls_rustls as rustls;
use std::{ use std::{
@ -704,7 +704,7 @@ async fn test_brotli_encoding_large_openssl() {
srv.stop().await; srv.stop().await;
} }
#[cfg(feature = "rustls-0_22")] #[cfg(feature = "rustls-0_23")]
mod plus_rustls { mod plus_rustls {
use std::io::BufReader; use std::io::BufReader;
@ -740,7 +740,7 @@ mod plus_rustls {
.map(char::from) .map(char::from)
.collect::<String>(); .collect::<String>();
let srv = actix_test::start_with(actix_test::config().rustls_0_22(tls_config()), || { let srv = actix_test::start_with(actix_test::config().rustls_0_23(tls_config()), || {
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| async { App::new().service(web::resource("/").route(web::to(|bytes: Bytes| async {
// echo decompressed request body back in response // echo decompressed request body back in response
HttpResponse::Ok() HttpResponse::Ok()

View File

@ -2,6 +2,9 @@
## Unreleased ## Unreleased
- Add `rustls-0_23`, `rustls-0_23-webpki-roots`, and `rustls-0_23-native-roots` crate features.
- Add `awc::Connector::rustls_0_23()` constructor.
- Fix `rustls-0_22-native-roots` root store lookup
- Update `brotli` dependency to `6`. - Update `brotli` dependency to `6`.
- Minimum supported Rust version (MSRV) is now 1.72. - Minimum supported Rust version (MSRV) is now 1.72.

View File

@ -27,6 +27,7 @@ features = [
"rustls-0_20", "rustls-0_20",
"rustls-0_21", "rustls-0_21",
"rustls-0_22-webpki-roots", "rustls-0_22-webpki-roots",
"rustls-0_23-webpki-roots",
"compress-brotli", "compress-brotli",
"compress-gzip", "compress-gzip",
"compress-zstd", "compress-zstd",
@ -48,6 +49,12 @@ rustls-0_21 = ["tls-rustls-0_21", "actix-tls/rustls-0_21"]
rustls-0_22-webpki-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-webpki-roots"] rustls-0_22-webpki-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-webpki-roots"]
# TLS via Rustls v0.22 (Native roots) # TLS via Rustls v0.22 (Native roots)
rustls-0_22-native-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-native-roots"] rustls-0_22-native-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-native-roots"]
# TLS via Rustls v0.23
rustls-0_23 = ["tls-rustls-0_23", "actix-tls/rustls-0_23"]
# TLS via Rustls v0.23 (WebPKI roots)
rustls-0_23-webpki-roots = ["rustls-0_23", "actix-tls/rustls-0_23-webpki-roots"]
# TLS via Rustls v0.23 (Native roots)
rustls-0_23-native-roots = ["rustls-0_23", "actix-tls/rustls-0_23-native-roots"]
# Brotli algorithm content-encoding support # Brotli algorithm content-encoding support
compress-brotli = ["actix-http/compress-brotli", "__compress"] compress-brotli = ["actix-http/compress-brotli", "__compress"]
@ -104,6 +111,7 @@ tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true, features = ["dangerous_configuration"] } tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true, features = ["dangerous_configuration"] }
tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true, features = ["dangerous_configuration"] } tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true, features = ["dangerous_configuration"] }
tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true } tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true }
tls-rustls-0_23 = { package = "rustls", version = "0.23", optional = true, default-features = false }
trust-dns-resolver = { version = "0.23", optional = true } trust-dns-resolver = { version = "0.23", optional = true }
@ -111,8 +119,8 @@ trust-dns-resolver = { version = "0.23", optional = true }
actix-http = { version = "3.6", features = ["openssl"] } actix-http = { version = "3.6", features = ["openssl"] }
actix-http-test = { version = "3", features = ["openssl"] } actix-http-test = { version = "3", features = ["openssl"] }
actix-server = "2" actix-server = "2"
actix-test = { version = "0.1", features = ["openssl", "rustls-0_22"] } actix-test = { version = "0.1", features = ["openssl", "rustls-0_23"] }
actix-tls = { version = "3.3", features = ["openssl", "rustls-0_22"] } actix-tls = { version = "3.3", features = ["openssl", "rustls-0_23"] }
actix-utils = "3" actix-utils = "3"
actix-web = { version = "4", features = ["openssl"] } actix-web = { version = "4", features = ["openssl"] }
@ -126,7 +134,8 @@ rcgen = "0.12"
rustls-pemfile = "2" rustls-pemfile = "2"
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
zstd = "0.13" zstd = "0.13"
tls-rustls-0_23 = { package = "rustls", version = "0.23" } # add rustls 0.23 with default features to make aws_lc_rs work in tests
[[example]] [[example]]
name = "client" name = "client"
required-features = ["rustls-0_22-webpki-roots"] required-features = ["rustls-0_23-webpki-roots"]

View File

@ -37,6 +37,12 @@ pub struct ClientBuilder<S = (), M = ()> {
} }
impl ClientBuilder { impl ClientBuilder {
/// Create a new ClientBuilder with default settings
///
/// Note: If the `rustls-0_23` feature is enabled and neither `rustls-0_23-native-roots` nor
/// `rustls-0_23-webpki-roots` are enabled, this ClientBuilder will build without TLS. In order
/// to enable TLS in this scenario, a custom `Connector` _must_ be added to the builder before
/// finishing construction.
#[allow(clippy::new_ret_no_self)] #[allow(clippy::new_ret_no_self)]
pub fn new() -> ClientBuilder< pub fn new() -> ClientBuilder<
impl Service< impl Service<

View File

@ -57,6 +57,10 @@ enum OurTlsConnector {
))] ))]
#[allow(dead_code)] // false positive; used in build_tls #[allow(dead_code)] // false positive; used in build_tls
Rustls022(std::sync::Arc<actix_tls::connect::rustls_0_22::reexports::ClientConfig>), Rustls022(std::sync::Arc<actix_tls::connect::rustls_0_22::reexports::ClientConfig>),
#[cfg(feature = "rustls-0_23")]
#[allow(dead_code)] // false positive; used in build_tls
Rustls023(std::sync::Arc<actix_tls::connect::rustls_0_23::reexports::ClientConfig>),
} }
/// Manages HTTP client network connectivity. /// Manages HTTP client network connectivity.
@ -80,6 +84,14 @@ pub struct Connector<T> {
} }
impl Connector<()> { impl Connector<()> {
/// Create a new connector with default TLS settings
///
/// # Panics
///
/// - When the `rustls-0_23-webpki-roots` or `rustls-0_23-native-roots` features are enabled
/// and no default crypto provider has been loaded, this method will panic.
/// - When the `rustls-0_23-native-roots` or `rustls-0_22-native-roots` features are enabled
/// and the runtime system has no native root certificates, this method will panic.
#[allow(clippy::new_ret_no_self, clippy::let_unit_value)] #[allow(clippy::new_ret_no_self, clippy::let_unit_value)]
pub fn new() -> Connector< pub fn new() -> Connector<
impl Service< impl Service<
@ -96,10 +108,32 @@ impl Connector<()> {
} }
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(any(feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-webpki-roots"))] { if #[cfg(any(feature = "rustls-0_23-webpki-roots", feature = "rustls-0_23-native-roots"))] {
/// Build TLS connector with Rustls v0.22, based on supplied ALPN protocols. /// Build TLS connector with Rustls v0.23, based on supplied ALPN protocols.
/// ///
/// Note that if other TLS crate features are enabled, Rustls v0.22 will be used. /// Note that if other TLS crate features are enabled, Rustls v0.23 will be used.
fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::rustls_0_23::{self, reexports::ClientConfig};
cfg_if::cfg_if! {
if #[cfg(feature = "rustls-0_23-webpki-roots")] {
let certs = rustls_0_23::webpki_roots_cert_store();
} else if #[cfg(feature = "rustls-0_23-native-roots")] {
let certs = rustls_0_23::native_roots_cert_store().expect("Failed to find native root certificates");
}
}
let mut config = ClientConfig::builder()
.with_root_certificates(certs)
.with_no_client_auth();
config.alpn_protocols = protocols;
OurTlsConnector::Rustls023(std::sync::Arc::new(config))
}
} else if #[cfg(any(feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots"))] {
/// Build TLS connector with Rustls v0.22, based on supplied ALPN protocols.
fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::rustls_0_22::{self, reexports::ClientConfig}; use actix_tls::connect::rustls_0_22::{self, reexports::ClientConfig};
@ -107,7 +141,7 @@ impl Connector<()> {
if #[cfg(feature = "rustls-0_22-webpki-roots")] { if #[cfg(feature = "rustls-0_22-webpki-roots")] {
let certs = rustls_0_22::webpki_roots_cert_store(); let certs = rustls_0_22::webpki_roots_cert_store();
} else if #[cfg(feature = "rustls-0_22-native-roots")] { } else if #[cfg(feature = "rustls-0_22-native-roots")] {
let certs = rustls_0_22::native_roots_cert_store(); let certs = rustls_0_22::native_roots_cert_store().expect("Failed to find native root certificates");
} }
} }
@ -167,7 +201,8 @@ impl Connector<()> {
OurTlsConnector::OpensslBuilder(ssl) OurTlsConnector::OpensslBuilder(ssl)
} }
} else { } else {
/// Provides an empty TLS connector when no TLS feature is enabled. /// Provides an empty TLS connector when no TLS feature is enabled, or when only the
/// `rustls-0_23` crate feature is enabled.
fn build_tls(_: Vec<Vec<u8>>) -> OurTlsConnector { fn build_tls(_: Vec<Vec<u8>>) -> OurTlsConnector {
OurTlsConnector::None OurTlsConnector::None
} }
@ -278,6 +313,24 @@ where
self self
} }
/// Sets custom Rustls v0.23 `ClientConfig` instance.
///
/// In order to enable ALPN, set the `.alpn_protocols` field on the ClientConfig to the
/// following:
///
/// ```no_run
/// vec![b"h2".to_vec(), b"http/1.1".to_vec()]
/// # ;
/// ```
#[cfg(feature = "rustls-0_23")]
pub fn rustls_0_23(
mut self,
connector: std::sync::Arc<actix_tls::connect::rustls_0_23::reexports::ClientConfig>,
) -> Self {
self.tls = OurTlsConnector::Rustls023(connector);
self
}
/// Sets maximum supported HTTP major version. /// Sets maximum supported HTTP major version.
/// ///
/// Supported versions are HTTP/1.1 and HTTP/2. /// Supported versions are HTTP/1.1 and HTTP/2.
@ -588,6 +641,40 @@ where
Some(actix_service::boxed::rc_service(tls_service)) Some(actix_service::boxed::rc_service(tls_service))
} }
#[cfg(feature = "rustls-0_23")]
OurTlsConnector::Rustls023(tls) => {
const H2: &[u8] = b"h2";
use actix_tls::connect::rustls_0_23::{reexports::AsyncTlsStream, TlsConnector};
#[allow(non_local_definitions)]
impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> {
fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) {
let sock = self.into_parts().0;
let h2 = sock
.get_ref()
.1
.alpn_protocol()
.map_or(false, |protos| protos.windows(2).any(|w| w == H2));
if h2 {
(Box::new(sock), Protocol::Http2)
} else {
(Box::new(sock), Protocol::Http1)
}
}
}
let handshake_timeout = self.config.handshake_timeout;
let tls_service = TlsConnectorService {
tcp_service: tcp_service_inner,
tls_service: TlsConnector::service(tls),
timeout: handshake_timeout,
};
Some(actix_service::boxed::rc_service(tls_service))
}
}; };
let tcp_config = self.config.no_disconnect_timeout(); let tcp_config = self.config.no_disconnect_timeout();

View File

@ -1,6 +1,6 @@
#![cfg(feature = "rustls-0_22-webpki-roots")] #![cfg(feature = "rustls-0_23-webpki-roots")]
extern crate tls_rustls_0_22 as rustls; extern crate tls_rustls_0_23 as rustls;
use std::{ use std::{
io::BufReader, io::BufReader,
@ -13,7 +13,7 @@ use std::{
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{fn_service, map_config, ServiceFactoryExt}; use actix_service::{fn_service, map_config, ServiceFactoryExt};
use actix_tls::connect::rustls_0_22::webpki_roots_cert_store; use actix_tls::connect::rustls_0_23::webpki_roots_cert_store;
use actix_utils::future::ok; use actix_utils::future::ok;
use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse}; use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
use rustls::{ use rustls::{
@ -83,7 +83,7 @@ mod danger {
} }
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::ring::default_provider() rustls::crypto::aws_lc_rs::default_provider()
.signature_verification_algorithms .signature_verification_algorithms
.supported_schemes() .supported_schemes()
} }
@ -107,7 +107,7 @@ async fn test_connection_reuse_h2() {
App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.rustls_0_22(tls_config()) .rustls_0_23(tls_config())
.map_err(|_| ()), .map_err(|_| ()),
) )
}) })
@ -126,7 +126,7 @@ async fn test_connection_reuse_h2() {
.set_certificate_verifier(Arc::new(danger::NoCertificateVerification)); .set_certificate_verifier(Arc::new(danger::NoCertificateVerification));
let client = awc::Client::builder() let client = awc::Client::builder()
.connector(awc::Connector::new().rustls_0_22(Arc::new(config))) .connector(awc::Connector::new().rustls_0_23(Arc::new(config)))
.finish(); .finish();
// req 1 // req 1