feat: web rustls 0.21 support

This commit is contained in:
Rob Ede 2023-08-29 00:41:08 +01:00
parent 5de1c9de75
commit 0f7a3ad93e
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
15 changed files with 356 additions and 105 deletions

View File

@ -69,7 +69,7 @@ jobs:
run: | run: |
cargo test --lib --tests -p=actix-router --all-features cargo test --lib --tests -p=actix-router --all-features
cargo test --lib --tests -p=actix-http --all-features cargo test --lib --tests -p=actix-http --all-features
cargo test --lib --tests -p=actix-web --features=rustls,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
cargo test --lib --tests -p=actix-web-codegen --all-features cargo test --lib --tests -p=actix-web-codegen --all-features
cargo test --lib --tests -p=awc --all-features cargo test --lib --tests -p=awc --all-features
cargo test --lib --tests -p=actix-http-test --all-features cargo test --lib --tests -p=actix-http-test --all-features

View File

@ -39,7 +39,7 @@ jobs:
with: with:
reporter: 'github-pr-check' reporter: 'github-pr-check'
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
clippy_flags: --workspace --all-features --tests --examples --bins -- -Dclippy::todo clippy_flags: --workspace --all-features --tests --examples --bins -- -Dclippy::todo -Aunknown_lints
lint-docs: lint-docs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -63,8 +63,7 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
# temp: unpin once https://github.com/rust-lang/rust/issues/113152 is fixed with: { toolchain: nightly-2023-08-25 }
with: { toolchain: nightly-2023-06-28 }
- uses: taiki-e/cache-cargo-install-action@v1 - uses: taiki-e/cache-cargo-install-action@v1
with: { tool: cargo-public-api } with: { tool: cargo-public-api }

View File

@ -21,7 +21,7 @@ rust-version.workspace = true
[package.metadata.docs.rs] [package.metadata.docs.rs]
# features that docs.rs will build with # features that docs.rs will build with
features = ["http2", "ws", "openssl", "rustls", "compress-brotli", "compress-gzip", "compress-zstd"] features = ["http2", "ws", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd"]
[lib] [lib]
name = "actix_http" name = "actix_http"

View File

@ -247,7 +247,7 @@ pub struct TlsAcceptorConfig {
pub(crate) handshake_timeout: Option<std::time::Duration>, pub(crate) handshake_timeout: Option<std::time::Duration>,
} }
#[cfg(any(feature = "openssl", feature = "rustls", feature = "rustls-0_21"))] #[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
impl TlsAcceptorConfig { impl TlsAcceptorConfig {
/// Set TLS handshake timeout duration. /// Set TLS handshake timeout duration.
pub fn handshake_timeout(self, dur: std::time::Duration) -> Self { pub fn handshake_timeout(self, dur: std::time::Duration) -> Self {

View File

@ -2,7 +2,9 @@
## Unreleased - 2023-xx-xx ## Unreleased - 2023-xx-xx
- Add `TestServerConfig::workers()` setter method. - Add `TestServerConfig::rustls_021()` method for Rustls v0.21 support behind new `rustls-0_21` crate feature.
- Add `TestServerConfig::workers()` method.
- Add `rustls-0_20` crate feature, which the existing `rustls` feature now aliases.
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency. - Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 0.1.1 - 2023-02-26 ## 0.1.1 - 2023-02-26

View File

@ -21,10 +21,14 @@ edition = "2021"
[features] [features]
default = [] default = []
# rustls # TLS via Rustls v0.20
rustls = ["tls-rustls", "actix-http/rustls", "awc/rustls"] rustls = ["rustls-0_20"]
# TLS via Rustls v0.20
rustls-0_20 = ["tls-rustls-0_20", "actix-http/rustls-0_20", "awc/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["tls-rustls-0_21", "actix-http/rustls-0_21", "awc/rustls-0_21"]
# openssl # TLS via OpenSSL
openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"] openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
[dependencies] [dependencies]
@ -44,5 +48,6 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
serde_urlencoded = "0.7" serde_urlencoded = "0.7"
tls-openssl = { package = "openssl", version = "0.10.55", optional = true } tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls = { 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 }
tokio = { version = "1.24.2", features = ["sync"] } tokio = { version = "1.24.2", features = ["sync"] }

View File

@ -34,8 +34,6 @@
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
extern crate tls_openssl as openssl; extern crate tls_openssl as openssl;
#[cfg(feature = "rustls")]
extern crate tls_rustls as rustls;
use std::{fmt, net, thread, time::Duration}; use std::{fmt, net, thread, time::Duration};
@ -141,8 +139,10 @@ where
StreamType::Tcp => false, StreamType::Tcp => false,
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
StreamType::Openssl(_) => true, StreamType::Openssl(_) => true,
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
StreamType::Rustls(_) => true, StreamType::Rustls020(_) => true,
#[cfg(feature = "rustls-0_21")]
StreamType::Rustls021(_) => true,
}; };
// run server in separate orphaned thread // run server in separate orphaned thread
@ -243,8 +243,8 @@ where
.openssl(acceptor.clone()) .openssl(acceptor.clone())
}), }),
}, },
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
StreamType::Rustls(config) => match cfg.tp { StreamType::Rustls020(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || { HttpVer::Http1 => builder.listen("test", tcp, move || {
let app_cfg = let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr); AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
@ -285,6 +285,48 @@ where
.rustls(config.clone()) .rustls(config.clone())
}), }),
}, },
#[cfg(feature = "rustls-0_21")]
StreamType::Rustls021(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_021(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_021(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_021(config.clone())
}),
},
} }
.expect("test server could not be created"); .expect("test server could not be created");
@ -316,7 +358,7 @@ where
builder.set_verify(SslVerifyMode::NONE); builder.set_verify(SslVerifyMode::NONE);
let _ = builder let _ = builder
.set_alpn_protos(b"\x02h2\x08http/1.1") .set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); .map_err(|err| log::error!("Can not set alpn protocol: {err:?}"));
Connector::new() Connector::new()
.conn_lifetime(Duration::from_secs(0)) .conn_lifetime(Duration::from_secs(0))
.timeout(Duration::from_millis(30000)) .timeout(Duration::from_millis(30000))
@ -355,8 +397,10 @@ enum StreamType {
Tcp, Tcp,
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
Openssl(openssl::ssl::SslAcceptor), Openssl(openssl::ssl::SslAcceptor),
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
Rustls(rustls::ServerConfig), Rustls020(tls_rustls_0_20::ServerConfig),
#[cfg(feature = "rustls-0_21")]
Rustls021(tls_rustls_0_21::ServerConfig),
} }
/// Create default test server config. /// Create default test server config.
@ -411,9 +455,16 @@ impl TestServerConfig {
} }
/// Accept secure connections via Rustls. /// Accept secure connections via Rustls.
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
pub fn rustls(mut self, config: rustls::ServerConfig) -> Self { pub fn rustls(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
self.stream = StreamType::Rustls(config); self.stream = StreamType::Rustls020(config);
self
}
/// Accept secure connections via Rustls.
#[cfg(feature = "rustls-0_21")]
pub fn rustls_021(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
self.stream = StreamType::Rustls021(config);
self self
} }

View File

@ -4,13 +4,15 @@
### Added ### Added
- Add `HttpServer::{bind, listen}_auto_h2c()` method behind new `http2` crate feature. - Add `HttpServer::{bind, listen}_auto_h2c()` methods behind new `http2` crate feature.
- Add `HttpServer::{bind, listen}_rustls_021()` methods for Rustls v0.21 support behind new `rustls-0_21` crate feature.
- Add `Resource::{get, post, etc...}` methods for more concisely adding routes that don't need additional guards. - Add `Resource::{get, post, etc...}` methods for more concisely adding routes that don't need additional guards.
- Add `web::Payload::to_bytes[_limited]()` helper methods. - Add `web::Payload::to_bytes[_limited]()` helper methods.
- Add missing constructors on `HttpResponse` for several status codes. - Add missing constructors on `HttpResponse` for several status codes.
- Add `http::header::ContentLength` typed header. - Add `http::header::ContentLength` typed header.
- Implement `Default` for `web::Data`. - Implement `Default` for `web::Data`.
- Implement `serde::Deserialize` for `web::Data`. - Implement `serde::Deserialize` for `web::Data`.
- Add `rustls-0_20` crate feature, which the existing `rustls` feature now aliases.
### Changed ### Changed

View File

@ -21,7 +21,7 @@ rust-version.workspace = true
[package.metadata.docs.rs] [package.metadata.docs.rs]
# features that docs.rs will build with # features that docs.rs will build with
features = ["macros", "openssl", "rustls", "compress-brotli", "compress-gzip", "compress-zstd", "cookies", "secure-cookies"] features = ["macros", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd", "cookies", "secure-cookies"]
rustdoc-args = ["--cfg", "docsrs"] rustdoc-args = ["--cfg", "docsrs"]
[lib] [lib]
@ -52,8 +52,12 @@ http2 = ["actix-http/http2"]
# TLS via OpenSSL # TLS via OpenSSL
openssl = ["http2", "actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"] openssl = ["http2", "actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"]
# TLS via Rustls # TLS via Rustls v0.20
rustls = ["http2", "actix-http/rustls", "actix-tls/accept", "actix-tls/rustls"] rustls = ["rustls-0_20"]
# TLS via Rustls v0.20
rustls-0_20 = ["http2", "actix-http/rustls-0_20", "actix-tls/accept", "actix-tls/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["http2", "actix-http/rustls-0_21", "actix-tls/accept", "actix-tls/rustls-0_21"]
# Internal (PRIVATE!) features used to aid testing and checking feature status. # Internal (PRIVATE!) features used to aid testing and checking feature status.
# Don't rely on these whatsoever. They may disappear at anytime. # Don't rely on these whatsoever. They may disappear at anytime.
@ -69,7 +73,7 @@ actix-rt = { version = "2.6", default-features = false }
actix-server = "2" actix-server = "2"
actix-service = "2" actix-service = "2"
actix-utils = "3" actix-utils = "3"
actix-tls = { version = "3", default-features = false, optional = true } actix-tls = { version = "3.1", default-features = false, optional = true }
actix-http = { version = "3.3", features = ["ws"] } actix-http = { version = "3.3", features = ["ws"] }
actix-router = "0.5" actix-router = "0.5"
@ -101,7 +105,7 @@ url = "2.1"
[dev-dependencies] [dev-dependencies]
actix-files = "0.6" actix-files = "0.6"
actix-test = { version = "0.1", features = ["openssl", "rustls"] } actix-test = { version = "0.1", features = ["openssl", "rustls-0_21"] }
awc = { version = "3", features = ["openssl"] } awc = { version = "3", features = ["openssl"] }
brotli = "3.3.3" brotli = "3.3.3"
@ -116,7 +120,7 @@ rustls-pemfile = "1"
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.20" } tls-rustls = { package = "rustls", version = "0.21" }
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
zstd = "0.12" zstd = "0.12"

View File

@ -7,7 +7,7 @@ use std::{
time::Duration, time::Duration,
}; };
#[cfg(any(feature = "openssl", feature = "rustls"))] #[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
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};
use actix_server::{Server, ServerBuilder}; use actix_server::{Server, ServerBuilder};
@ -16,8 +16,6 @@ use actix_service::{
}; };
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
use actix_tls::accept::openssl::reexports::{AlpnError, SslAcceptor, SslAcceptorBuilder}; use actix_tls::accept::openssl::reexports::{AlpnError, SslAcceptor, SslAcceptorBuilder};
#[cfg(feature = "rustls")]
use actix_tls::accept::rustls::reexports::ServerConfig as RustlsServerConfig;
use crate::{config::AppConfig, Error}; use crate::{config::AppConfig, Error};
@ -31,7 +29,7 @@ struct Config {
keep_alive: KeepAlive, keep_alive: KeepAlive,
client_request_timeout: Duration, client_request_timeout: Duration,
client_disconnect_timeout: Duration, client_disconnect_timeout: Duration,
#[cfg(any(feature = "openssl", feature = "rustls"))] #[allow(dead_code)] // only dead when no TLS features are enabled
tls_handshake_timeout: Option<Duration>, tls_handshake_timeout: Option<Duration>,
} }
@ -109,7 +107,6 @@ where
keep_alive: KeepAlive::default(), keep_alive: KeepAlive::default(),
client_request_timeout: Duration::from_secs(5), client_request_timeout: Duration::from_secs(5),
client_disconnect_timeout: Duration::from_secs(1), client_disconnect_timeout: Duration::from_secs(1),
#[cfg(any(feature = "rustls", feature = "openssl"))]
tls_handshake_timeout: None, tls_handshake_timeout: None,
})), })),
backlog: 1024, backlog: 1024,
@ -170,7 +167,7 @@ where
/// By default max connections is set to a 256. /// By default max connections is set to a 256.
#[allow(unused_variables)] #[allow(unused_variables)]
pub fn max_connection_rate(self, num: usize) -> Self { pub fn max_connection_rate(self, num: usize) -> Self {
#[cfg(any(feature = "rustls", feature = "openssl"))] #[cfg(any(feature = "rustls-0_20", feature = "rustls-0_21", feature = "openssl"))]
actix_tls::accept::max_concurrent_tls_connect(num); actix_tls::accept::max_concurrent_tls_connect(num);
self self
} }
@ -222,8 +219,8 @@ where
/// Defines a timeout for TLS handshake. If the TLS handshake does not complete within this /// Defines a timeout for TLS handshake. If the TLS handshake does not complete within this
/// time, the connection is closed. /// time, the connection is closed.
/// ///
/// By default handshake timeout is set to 3000 milliseconds. /// By default, the handshake timeout is 3 seconds.
#[cfg(any(feature = "openssl", feature = "rustls"))] #[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
pub fn tls_handshake_timeout(self, dur: Duration) -> Self { pub fn tls_handshake_timeout(self, dur: Duration) -> Self {
self.config self.config
.lock() .lock()
@ -247,7 +244,10 @@ where
/// ///
/// # Connection Types /// # Connection Types
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using OpenSSL. /// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using OpenSSL.
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using Rustls. /// - `actix_tls::accept::rustls_0_20::TlsStream<actix_web::rt::net::TcpStream>` when using
/// Rustls v0.20.
/// - `actix_tls::accept::rustls_0_21::TlsStream<actix_web::rt::net::TcpStream>` when using
/// Rustls v0.21.
/// - `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.
@ -368,20 +368,39 @@ where
} }
/// 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 Rustls. /// using Rustls v0.20.
/// ///
/// See [`bind()`](Self::bind) for more details on `addrs` argument. /// See [`bind()`](Self::bind) for more details on `addrs` 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")] #[cfg(feature = "rustls-0_20")]
pub fn bind_rustls<A: net::ToSocketAddrs>( pub fn bind_rustls<A: net::ToSocketAddrs>(
mut self, mut self,
addrs: A, addrs: A,
config: RustlsServerConfig, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig,
) -> io::Result<Self> { ) -> io::Result<Self> {
let sockets = bind_addrs(addrs, self.backlog)?; let sockets = bind_addrs(addrs, self.backlog)?;
for lst in sockets { for lst in sockets {
self = self.listen_rustls_inner(lst, config.clone())?; self = self.listen_rustls_0_20_inner(lst, config.clone())?;
}
Ok(self)
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls v0.21.
///
/// 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_21")]
pub fn bind_rustls_021<A: net::ToSocketAddrs>(
mut self,
addrs: A,
config: actix_tls::accept::rustls_0_21::reexports::ServerConfig,
) -> io::Result<Self> {
let sockets = bind_addrs(addrs, self.backlog)?;
for lst in sockets {
self = self.listen_rustls_0_21_inner(lst, config.clone())?;
} }
Ok(self) Ok(self)
} }
@ -497,25 +516,41 @@ where
Ok(self) Ok(self)
} }
/// 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.20.
/// ///
/// 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")] #[cfg(feature = "rustls-0_20")]
pub fn listen_rustls( pub fn listen_rustls(
self, self,
lst: net::TcpListener, lst: net::TcpListener,
config: RustlsServerConfig, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig,
) -> io::Result<Self> { ) -> io::Result<Self> {
self.listen_rustls_inner(lst, config) self.listen_rustls_0_20_inner(lst, config)
} }
#[cfg(feature = "rustls")] /// Binds to existing listener for accepting incoming TLS connection requests using Rustls
fn listen_rustls_inner( /// v0.21.
///
/// 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_21")]
pub fn listen_rustls_0_21(
self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_21::reexports::ServerConfig,
) -> io::Result<Self> {
self.listen_rustls_0_21_inner(lst, config)
}
#[cfg(feature = "rustls-0_20")]
fn listen_rustls_0_20_inner(
mut self, mut self,
lst: net::TcpListener, lst: net::TcpListener,
config: RustlsServerConfig, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig,
) -> io::Result<Self> { ) -> io::Result<Self> {
let factory = self.factory.clone(); let factory = self.factory.clone();
let cfg = self.config.clone(); let cfg = self.config.clone();
@ -562,6 +597,57 @@ where
Ok(self) Ok(self)
} }
#[cfg(feature = "rustls-0_21")]
fn listen_rustls_0_21_inner(
mut self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_21::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_021_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")] #[cfg(feature = "rustls-0_21")]
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")] #[cfg(feature = "rustls-0_21")]
mod plus_rustls { mod plus_rustls {
use std::io::BufReader; use std::io::BufReader;
@ -743,7 +743,7 @@ mod plus_rustls {
.map(char::from) .map(char::from)
.collect::<String>(); .collect::<String>();
let srv = actix_test::start_with(actix_test::config().rustls(tls_config()), || { let srv = actix_test::start_with(actix_test::config().rustls_021(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,8 @@
## Unreleased - 2023-xx-xx ## Unreleased - 2023-xx-xx
- Add `awc::Connector::rustls_021()` method for Rustls v0.21 support behind new `rustls-0_21` crate feature.
- Add `rustls-0_20` crate feature, which the existing `rustls` feature now aliases.
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency. - Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 3.1.1 - 2023-02-26 ## 3.1.1 - 2023-02-26

View File

@ -21,16 +21,20 @@ path = "src/lib.rs"
[package.metadata.docs.rs] [package.metadata.docs.rs]
# features that docs.rs will build with # features that docs.rs will build with
features = ["openssl", "rustls", "compress-brotli", "compress-gzip", "compress-zstd", "cookies"] features = ["openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd", "cookies"]
[features] [features]
default = ["compress-brotli", "compress-gzip", "compress-zstd", "cookies"] default = ["compress-brotli", "compress-gzip", "compress-zstd", "cookies"]
# openssl # TLS via OpenSSL
openssl = ["tls-openssl", "actix-tls/openssl"] openssl = ["tls-openssl", "actix-tls/openssl"]
# rustls # TLS via Rustls v0.20
rustls = ["tls-rustls", "actix-tls/rustls"] rustls = ["rustls-0_20"]
# TLS via Rustls v0.20
rustls-0_20 = ["tls-rustls-0_20", "actix-tls/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["tls-rustls-0_21", "actix-tls/rustls-0_21"]
# Brotli algorithm content-encoding support # Brotli algorithm content-encoding support
compress-brotli = ["actix-http/compress-brotli", "__compress"] compress-brotli = ["actix-http/compress-brotli", "__compress"]
@ -39,10 +43,10 @@ compress-gzip = ["actix-http/compress-gzip", "__compress"]
# Zstd algorithm content-encoding support # Zstd algorithm content-encoding support
compress-zstd = ["actix-http/compress-zstd", "__compress"] compress-zstd = ["actix-http/compress-zstd", "__compress"]
# cookie parsing and cookie jar # Cookie parsing and cookie jar
cookies = ["cookie"] cookies = ["cookie"]
# trust-dns as dns resolver # Use `trust-dns-resolver` crate as DNS resolver
trust-dns = ["trust-dns-resolver"] trust-dns = ["trust-dns-resolver"]
# Internal (PRIVATE!) features used to aid testing and checking feature status. # Internal (PRIVATE!) features used to aid testing and checking feature status.
@ -59,7 +63,7 @@ actix-codec = "0.5"
actix-service = "2" actix-service = "2"
actix-http = { version = "3.3", features = ["http2", "ws"] } actix-http = { version = "3.3", features = ["http2", "ws"] }
actix-rt = { version = "2.1", default-features = false } actix-rt = { version = "2.1", default-features = false }
actix-tls = { version = "3", features = ["connect", "uri"] } actix-tls = { version = "3.1", features = ["connect", "uri"] }
actix-utils = "3" actix-utils = "3"
base64 = "0.21" base64 = "0.21"
@ -84,7 +88,8 @@ tokio = { version = "1.24.2", features = ["sync"] }
cookie = { version = "0.16", features = ["percent-encode"], optional = true } cookie = { version = "0.16", features = ["percent-encode"], optional = true }
tls-openssl = { package = "openssl", version = "0.10.55", optional = true } tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls = { 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"] }
trust-dns-resolver = { version = "0.22", optional = true } trust-dns-resolver = { version = "0.22", optional = true }
@ -92,8 +97,8 @@ trust-dns-resolver = { version = "0.22", optional = true }
actix-http = { version = "3", features = ["openssl"] } actix-http = { version = "3", 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"] } actix-test = { version = "0.1", features = ["openssl", "rustls-0_21"] }
actix-tls = { version = "3", features = ["openssl", "rustls"] } actix-tls = { version = "3", features = ["openssl", "rustls-0_21"] }
actix-utils = "3" actix-utils = "3"
actix-web = { version = "4", features = ["openssl"] } actix-web = { version = "4", features = ["openssl"] }
@ -110,4 +115,4 @@ zstd = "0.12"
[[example]] [[example]]
name = "client" name = "client"
required-features = ["rustls"] required-features = ["rustls-0_21"]

View File

@ -43,20 +43,22 @@ enum OurTlsConnector {
#[allow(dead_code)] // false positive; used in build_ssl #[allow(dead_code)] // false positive; used in build_ssl
OpensslBuilder(actix_tls::connect::openssl::reexports::SslConnectorBuilder), OpensslBuilder(actix_tls::connect::openssl::reexports::SslConnectorBuilder),
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
Rustls(std::sync::Arc<actix_tls::connect::rustls::reexports::ClientConfig>), Rustls020(std::sync::Arc<actix_tls::connect::rustls_0_20::reexports::ClientConfig>),
#[cfg(feature = "rustls-0_21")]
Rustls021(std::sync::Arc<actix_tls::connect::rustls_0_21::reexports::ClientConfig>),
} }
/// Manages HTTP client network connectivity. /// Manages HTTP client network connectivity.
/// ///
/// The `Connector` type uses a builder-like combinator pattern for service /// The `Connector` type uses a builder-like combinator pattern for service construction that
/// construction that finishes by calling the `.finish()` method. /// finishes by calling the `.finish()` method.
/// ///
/// ```ignore /// ```no_run
/// use std::time::Duration; /// use std::time::Duration;
/// use actix_http::client::Connector;
/// ///
/// let connector = Connector::new() /// let connector = awc::Connector::new()
/// .timeout(Duration::from_secs(5)) /// .timeout(Duration::from_secs(5))
/// .finish(); /// .finish();
/// ``` /// ```
@ -80,22 +82,22 @@ impl Connector<()> {
Connector { Connector {
connector: TcpConnector::new(resolver::resolver()).service(), connector: TcpConnector::new(resolver::resolver()).service(),
config: ConnectorConfig::default(), config: ConnectorConfig::default(),
tls: Self::build_ssl(vec![b"h2".to_vec(), b"http/1.1".to_vec()]), tls: Self::build_tls(vec![b"h2".to_vec(), b"http/1.1".to_vec()]),
} }
} }
/// Provides an empty TLS connector when no TLS feature is enabled. /// Provides an empty TLS connector when no TLS feature is enabled.
#[cfg(not(any(feature = "openssl", feature = "rustls")))] #[cfg(not(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21")))]
fn build_ssl(_: Vec<Vec<u8>>) -> OurTlsConnector { fn build_tls(_: Vec<Vec<u8>>) -> OurTlsConnector {
OurTlsConnector::None OurTlsConnector::None
} }
/// Build TLS connector with rustls, based on supplied ALPN protocols /// Build TLS connector with Rustls v0.21, based on supplied ALPN protocols
/// ///
/// Note that if both `openssl` and `rustls` features are enabled, rustls will be used. /// Note that if other TLS crate features are enabled, Rustls v0.21 will be used.
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_21")]
fn build_ssl(protocols: Vec<Vec<u8>>) -> OurTlsConnector { fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::rustls::{reexports::ClientConfig, webpki_roots_cert_store}; use actix_tls::connect::rustls_0_21::{reexports::ClientConfig, webpki_roots_cert_store};
let mut config = ClientConfig::builder() let mut config = ClientConfig::builder()
.with_safe_defaults() .with_safe_defaults()
@ -104,12 +106,55 @@ impl Connector<()> {
config.alpn_protocols = protocols; config.alpn_protocols = protocols;
OurTlsConnector::Rustls(std::sync::Arc::new(config)) OurTlsConnector::Rustls021(std::sync::Arc::new(config))
} }
/// Build TLS connector with openssl, based on supplied ALPN protocols /// Build TLS connector with Rustls v0.21, based on supplied ALPN protocols
#[cfg(all(feature = "openssl", not(feature = "rustls")))] ///
fn build_ssl(protocols: Vec<Vec<u8>>) -> OurTlsConnector { /// Note that if other TLS crate features are enabled, Rustls v0.21 will be used.
#[cfg(all(
all(feature = "rustls-0_20", feature = "openssl"),
not(feature = "rustls-0_21"),
))]
fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::rustls_0_20::{reexports::ClientConfig, webpki_roots_cert_store};
let mut config = ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(webpki_roots_cert_store())
.with_no_client_auth();
config.alpn_protocols = protocols;
OurTlsConnector::Rustls020(std::sync::Arc::new(config))
}
/// Build TLS connector with Rustls v0.20, based on supplied ALPN protocols
///
/// Note that if other TLS crate features are enabled, Rustls v0.21 will be used.
#[cfg(all(
feature = "rustls-0_20",
not(any(feature = "rustls-0_21", feature = "openssl")),
))]
fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::rustls_0_20::{reexports::ClientConfig, webpki_roots_cert_store};
let mut config = ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(webpki_roots_cert_store())
.with_no_client_auth();
config.alpn_protocols = protocols;
OurTlsConnector::Rustls020(std::sync::Arc::new(config))
}
/// Build TLS connector with OpenSSL, based on supplied ALPN protocols
#[cfg(all(
feature = "openssl",
not(any(feature = "rustls-0_20", feature = "rustls-0_21")),
))]
fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
use actix_tls::connect::openssl::reexports::{SslConnector, SslMethod}; use actix_tls::connect::openssl::reexports::{SslConnector, SslMethod};
use bytes::{BufMut, BytesMut}; use bytes::{BufMut, BytesMut};
@ -129,7 +174,7 @@ impl Connector<()> {
} }
impl<S> Connector<S> { impl<S> Connector<S> {
/// Use custom connector. /// Sets custom connector.
pub fn connector<S1, Io1>(self, connector: S1) -> Connector<S1> pub fn connector<S1, Io1>(self, connector: S1) -> Connector<S1>
where where
Io1: ActixStream + fmt::Debug + 'static, Io1: ActixStream + fmt::Debug + 'static,
@ -158,21 +203,28 @@ where
+ Clone + Clone
+ 'static, + 'static,
{ {
/// Tcp connection timeout, i.e. max time to connect to remote host including dns name /// Sets TCP connection timeout.
/// resolution. Set to 5 second by default. ///
/// This is the max time allowed to connect to remote host, including DNS name resolution.
///
/// By default, the timeout is 5 seconds.
pub fn timeout(mut self, timeout: Duration) -> Self { pub fn timeout(mut self, timeout: Duration) -> Self {
self.config.timeout = timeout; self.config.timeout = timeout;
self self
} }
/// Tls handshake timeout, i.e. max time to do tls handshake with remote host after tcp /// Sets TLS handshake timeout.
/// connection established. Set to 5 second by default. ///
/// This is the max time allowed to perform the TLS handshake with remote host after TCP
/// connection is established.
///
/// By default, the timeout is 5 seconds.
pub fn handshake_timeout(mut self, timeout: Duration) -> Self { pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
self.config.handshake_timeout = timeout; self.config.handshake_timeout = timeout;
self self
} }
/// Use custom OpenSSL `SslConnector` instance. /// Sets custom OpenSSL `SslConnector` instance.
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
pub fn openssl( pub fn openssl(
mut self, mut self,
@ -191,13 +243,23 @@ where
self self
} }
/// Use custom Rustls `ClientConfig` instance. /// Sets custom Rustls v0.20 `ClientConfig` instance.
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
pub fn rustls( pub fn rustls(
mut self, mut self,
connector: std::sync::Arc<actix_tls::connect::rustls::reexports::ClientConfig>, connector: std::sync::Arc<actix_tls::connect::rustls_0_20::reexports::ClientConfig>,
) -> Self { ) -> Self {
self.tls = OurTlsConnector::Rustls(connector); self.tls = OurTlsConnector::Rustls020(connector);
self
}
/// Sets custom Rustls v0.21 `ClientConfig` instance.
#[cfg(feature = "rustls-0_21")]
pub fn rustls_021(
mut self,
connector: std::sync::Arc<actix_tls::connect::rustls_0_21::reexports::ClientConfig>,
) -> Self {
self.tls = OurTlsConnector::Rustls021(connector);
self self
} }
@ -212,12 +274,12 @@ where
unimplemented!("actix-http client only supports versions http/1.1 & http/2") unimplemented!("actix-http client only supports versions http/1.1 & http/2")
} }
}; };
self.tls = Connector::build_ssl(versions); self.tls = Connector::build_tls(versions);
self self
} }
/// Sets the initial window size (in octets) for HTTP/2 stream-level flow control for /// Sets the initial window size (in bytes) for HTTP/2 stream-level flow control for received
/// received data. /// data.
/// ///
/// The default value is 65,535 and is good for APIs, but not for big objects. /// The default value is 65,535 and is good for APIs, but not for big objects.
pub fn initial_window_size(mut self, size: u32) -> Self { pub fn initial_window_size(mut self, size: u32) -> Self {
@ -225,7 +287,7 @@ where
self self
} }
/// Sets the initial window size (in octets) for HTTP/2 connection-level flow control for /// Sets the initial window size (in bytes) for HTTP/2 connection-level flow control for
/// received data. /// received data.
/// ///
/// The default value is 65,535 and is good for APIs, but not for big objects. /// The default value is 65,535 and is good for APIs, but not for big objects.
@ -405,11 +467,44 @@ where
unreachable!("OpenSSL builder is built before this match."); unreachable!("OpenSSL builder is built before this match.");
} }
#[cfg(feature = "rustls")] #[cfg(feature = "rustls-0_20")]
OurTlsConnector::Rustls(tls) => { OurTlsConnector::Rustls020(tls) => {
const H2: &[u8] = b"h2"; const H2: &[u8] = b"h2";
use actix_tls::connect::rustls::{reexports::AsyncTlsStream, TlsConnector}; use actix_tls::connect::rustls_0_20::{reexports::AsyncTlsStream, TlsConnector};
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))
}
#[cfg(feature = "rustls-0_21")]
OurTlsConnector::Rustls021(tls) => {
const H2: &[u8] = b"h2";
use actix_tls::connect::rustls_0_21::{reexports::AsyncTlsStream, TlsConnector};
impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> { impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> {
fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) {

View File

@ -1,6 +1,6 @@
#![cfg(feature = "rustls")] #![cfg(feature = "rustls-0_21")]
extern crate tls_rustls as rustls; extern crate tls_rustls_0_21 as rustls;
use std::{ use std::{
io::BufReader, io::BufReader,
@ -14,7 +14,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::webpki_roots_cert_store; use actix_tls::connect::rustls_0_21::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::{
@ -82,7 +82,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(tls_config()) .rustls_021(tls_config())
.map_err(|_| ()), .map_err(|_| ()),
) )
}) })
@ -102,7 +102,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(Arc::new(config))) .connector(awc::Connector::new().rustls_021(Arc::new(config)))
.finish(); .finish();
// req 1 // req 1