Skip to content

Commit

Permalink
feat!: Make tls more generic (#380)
Browse files Browse the repository at this point in the history
* feat!: Make tls more generic #374

* Format Rust code using rustfmt

* version 0.51.0

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
chrislearn and github-actions[bot] authored Aug 24, 2023
1 parent 6eed4ed commit 617954f
Show file tree
Hide file tree
Showing 16 changed files with 175 additions and 111 deletions.
34 changes: 17 additions & 17 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "2"

[workspace.package]
version = "0.50.5"
version = "0.51.0"
authors = ["Chrislearn Young <chrislearn@hotmail.com>"]
edition = "2021"
rust-version = "1.67"
Expand Down Expand Up @@ -81,23 +81,23 @@ rustls = "0.21.1"
rustls-pemfile = "1.0"
rust-embed = {version = ">= 6, <= 8"}
salvo-utils = { version = "0.0.5", default-features = true }
salvo_macros = { version = "0.50.5", path = "crates/macros", default-features = false }
salvo_core = { version = "0.50.5", path = "crates/core", default-features = false }
salvo_extra = { version = "0.50.5", path = "crates/extra", default-features = false }
salvo-compression = { version = "0.50.5", path = "crates/compression", default-features = false }
salvo-cache = { version = "0.50.5", path = "crates/cache", default-features = false }
salvo-cors = { version = "0.50.5", path = "crates/cors", default-features = false }
salvo-csrf = { version = "0.50.5", path = "crates/csrf", default-features = false }
salvo-flash = { version = "0.50.5", path = "crates/flash", default-features = false }
salvo_macros = { version = "0.51.0", path = "crates/macros", default-features = false }
salvo_core = { version = "0.51.0", path = "crates/core", default-features = false }
salvo_extra = { version = "0.51.0", path = "crates/extra", default-features = false }
salvo-compression = { version = "0.51.0", path = "crates/compression", default-features = false }
salvo-cache = { version = "0.51.0", path = "crates/cache", default-features = false }
salvo-cors = { version = "0.51.0", path = "crates/cors", default-features = false }
salvo-csrf = { version = "0.51.0", path = "crates/csrf", default-features = false }
salvo-flash = { version = "0.51.0", path = "crates/flash", default-features = false }
salvo-http3 = { version = "0.0.4", default-features = false }
salvo-jwt-auth = { version = "0.50.5", path = "crates/jwt-auth", default-features = false }
salvo-oapi = { version = "0.50.5", path = "./crates/oapi", default-features = false }
salvo-oapi-macros = { version = "0.50.5", path = "crates/oapi-macros", default-features = false }
salvo-otel = { version = "0.50.5", path = "crates/otel", default-features = false }
salvo-proxy = { version = "0.50.5", path = "crates/proxy", default-features = false }
salvo-rate-limiter = { version = "0.50.5", path = "crates/rate-limiter", default-features = false }
salvo-serve-static = { version = "0.50.5", path = "crates/serve-static", default-features = false }
salvo-session = { version = "0.50.5", path = "crates/session", default-features = false }
salvo-jwt-auth = { version = "0.51.0", path = "crates/jwt-auth", default-features = false }
salvo-oapi = { version = "0.51.0", path = "./crates/oapi", default-features = false }
salvo-oapi-macros = { version = "0.51.0", path = "crates/oapi-macros", default-features = false }
salvo-otel = { version = "0.51.0", path = "crates/otel", default-features = false }
salvo-proxy = { version = "0.51.0", path = "crates/proxy", default-features = false }
salvo-rate-limiter = { version = "0.51.0", path = "crates/rate-limiter", default-features = false }
salvo-serve-static = { version = "0.51.0", path = "crates/serve-static", default-features = false }
salvo-session = { version = "0.51.0", path = "crates/session", default-features = false }
serde = "1"
serde_json = "1"
serde-xml-rs = "0.6"
Expand Down
14 changes: 7 additions & 7 deletions crates/compression/src/stream.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Compress the body of a response.
use std::collections::VecDeque;
use std::future::Future;
use std::io::{self, Error as IoError, ErrorKind};
use std::io::{self, Error as IoError, ErrorKind, Result as IoResult};
use std::pin::Pin;
use std::task::{Context, Poll};

Expand All @@ -21,7 +21,7 @@ pub(super) struct EncodeStream<B> {
encoder: Option<Encoder>,
body: B,
eof: bool,
encoding: Option<JoinHandle<Result<Encoder, IoError>>>,
encoding: Option<JoinHandle<IoResult<Encoder>>>,
}

impl<B> EncodeStream<B> {
Expand All @@ -37,13 +37,13 @@ impl<B> EncodeStream<B> {
}
impl EncodeStream<BoxStream<'static, Result<Bytes, BoxedError>>> {
#[inline]
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, IoError>>> {
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<IoResult<Bytes>>> {
Stream::poll_next(Pin::new(&mut self.body), cx).map_err(|e| IoError::new(ErrorKind::Other, e))
}
}
impl EncodeStream<HyperBody> {
#[inline]
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, IoError>>> {
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<IoResult<Bytes>>> {
match ready!(Body::poll_frame(Pin::new(&mut self.body), cx)) {
Some(Ok(frame)) => Poll::Ready(frame.into_data().map(Ok).ok()),
Some(Err(e)) => Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e)))),
Expand All @@ -53,7 +53,7 @@ impl EncodeStream<HyperBody> {
}
impl EncodeStream<Option<Bytes>> {
#[inline]
fn poll_chunk(&mut self, _cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, IoError>>> {
fn poll_chunk(&mut self, _cx: &mut Context<'_>) -> Poll<Option<IoResult<Bytes>>> {
if let Some(body) = Pin::new(&mut self.body).take() {
Poll::Ready(Some(Ok(body)))
} else {
Expand All @@ -63,7 +63,7 @@ impl EncodeStream<Option<Bytes>> {
}
impl EncodeStream<VecDeque<Bytes>> {
#[inline]
fn poll_chunk(&mut self, _cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, IoError>>> {
fn poll_chunk(&mut self, _cx: &mut Context<'_>) -> Poll<Option<IoResult<Bytes>>> {
if let Some(body) = Pin::new(&mut self.body).pop_front() {
Poll::Ready(Some(Ok(body)))
} else {
Expand All @@ -75,7 +75,7 @@ impl EncodeStream<VecDeque<Bytes>> {
macro_rules! impl_stream {
($name: ty) => {
impl Stream for EncodeStream<$name> {
type Item = Result<Bytes, IoError>;
type Item = IoResult<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/conn/acme/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Note that the files contain private keys.
*/

use std::error::Error as StdError;
use std::io::{Error as IoError, ErrorKind};
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
use std::path::Path;

use async_trait::async_trait;
Expand Down Expand Up @@ -150,7 +150,7 @@ where
}
}
#[inline]
async fn write_data(file_path: impl AsRef<Path> + Send, data: impl AsRef<[u8]> + Send) -> Result<(), IoError> {
async fn write_data(file_path: impl AsRef<Path> + Send, data: impl AsRef<[u8]> + Send) -> IoResult<()> {
let mut file = OpenOptions::new();
file.write(true).create(true).truncate(true);
#[cfg(unix)]
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/conn/acme/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ where
}

#[inline]
async fn accept(&mut self) -> Result<Accepted<Self::Conn>, IoError> {
async fn accept(&mut self) -> IoResult<Accepted<Self::Conn>> {
let Accepted {
conn,
local_addr,
Expand Down
17 changes: 13 additions & 4 deletions crates/core/src/conn/native_tls/config.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
//! native_tls module
use std::fmt::{self, Formatter};
use std::fs::File;
use std::io::{Error as IoError, ErrorKind, Read};
use std::io::{Error as IoError, ErrorKind, Result as IoResult, Read};
use std::path::{Path, PathBuf};

use futures_util::future::{ready, Ready};
use futures_util::stream::{once, Once, Stream};
use tokio_native_tls::native_tls::Identity;

pub use tokio_native_tls::native_tls::Identity;

use crate::conn::IntoConfigStream;

Expand Down Expand Up @@ -64,9 +65,9 @@ impl NativeTlsConfig {
self
}

/// Generate identity
/// Build identity
#[inline]
pub fn identity(mut self) -> Result<Identity, IoError> {
pub fn build_identity(mut self) -> IoResult<Identity> {
if self.pkcs12.is_empty() {
if let Some(path) = &self.pkcs12_path {
let mut file = File::open(path)?;
Expand All @@ -77,6 +78,14 @@ impl NativeTlsConfig {
}
}

impl TryInto<Identity> for NativeTlsConfig {
type Error = IoError;

fn try_into(self) -> IoResult<Identity> {
self.build_identity()
}
}

impl IntoConfigStream<NativeTlsConfig> for NativeTlsConfig {
type Stream = Once<Ready<NativeTlsConfig>>;

Expand Down
45 changes: 28 additions & 17 deletions crates/core/src/conn/native_tls/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::io::{Error as IoError, ErrorKind, Result as IoResult};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use std::marker::PhantomData;

use futures_util::stream::BoxStream;
use futures_util::task::noop_waker_ref;
Expand All @@ -17,33 +18,40 @@ use crate::conn::{Accepted, Acceptor, Holding, HttpBuilder, IntoConfigStream, Li
use crate::http::{HttpConnection, Version};
use crate::service::HyperHandler;

use super::NativeTlsConfig;
use super::Identity;

/// NativeTlsListener
pub struct NativeTlsListener<C, T> {
config_stream: C,
pub struct NativeTlsListener<S, C, T> {
config_stream: S,
inner: T,
_config: PhantomData<C>,
}
impl<C, T> NativeTlsListener<C, T>
impl<S, C, T> NativeTlsListener<S, C, T>
where
C: IntoConfigStream<NativeTlsConfig> + Send + 'static,
S: IntoConfigStream<C> + Send + 'static,
C: TryInto<Identity, Error = IoError> + Send + 'static,
T: Listener + Send,
{
/// Create a new `NativeTlsListener`.
#[inline]
pub fn new(config_stream: C, inner: T) -> Self {
NativeTlsListener { config_stream, inner }
pub fn new(config_stream: S, inner: T) -> Self {
NativeTlsListener {
config_stream,
inner,
_config: PhantomData,
}
}
}

#[async_trait]
impl<C, T> Listener for NativeTlsListener<C, T>
impl<S, C, T> Listener for NativeTlsListener<S, C, T>
where
C: IntoConfigStream<NativeTlsConfig> + Send + 'static,
S: IntoConfigStream<C> + Send + 'static,
C: TryInto<Identity, Error = IoError> + Send + 'static,
T: Listener + Send,
T::Acceptor: Send + 'static,
{
type Acceptor = NativeTlsAcceptor<BoxStream<'static, NativeTlsConfig>, T::Acceptor>;
type Acceptor = NativeTlsAcceptor<BoxStream<'static, C>, C, T::Acceptor>;

async fn bind(self) -> Self::Acceptor {
self.try_bind().await.unwrap()
Expand Down Expand Up @@ -77,18 +85,19 @@ where
}

/// NativeTlsAcceptor
pub struct NativeTlsAcceptor<C, T> {
config_stream: C,
pub struct NativeTlsAcceptor<S, C, T> {
config_stream: S,
inner: T,
holdings: Vec<Holding>,
tls_acceptor: Option<tokio_native_tls::TlsAcceptor>,
_config: PhantomData<C>,
}
impl<C, T> NativeTlsAcceptor<C, T>
impl<S, C, T> NativeTlsAcceptor<S, C, T>
where
T: Acceptor,
{
/// Create a new `NativeTlsAcceptor`.
pub fn new(config_stream: C, inner: T) -> NativeTlsAcceptor<C, T> {
pub fn new(config_stream: S, inner: T) -> NativeTlsAcceptor<S, C, T> {
let holdings = inner
.holdings()
.iter()
Expand All @@ -114,14 +123,16 @@ where
inner,
holdings,
tls_acceptor: None,
_config: PhantomData,
}
}
}

#[async_trait]
impl<C, T> Acceptor for NativeTlsAcceptor<C, T>
impl<S, C, T> Acceptor for NativeTlsAcceptor<S, C, T>
where
C: Stream<Item = NativeTlsConfig> + Send + Unpin + 'static,
S: Stream<Item = C> + Send + Unpin + 'static,
C: TryInto<Identity, Error = IoError> + Send + 'static,
T: Acceptor + Send + 'static,
<T as Acceptor>::Conn: AsyncRead + AsyncWrite + Unpin + Send,
{
Expand All @@ -145,7 +156,7 @@ where
config
};
if let Some(config) = config {
let identity = config.identity()?;
let identity = config.try_into()?;
let tls_acceptor = tokio_native_tls::native_tls::TlsAcceptor::new(identity);
match tls_acceptor {
Ok(tls_acceptor) => {
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/conn/native_tls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pub mod listener;
pub use listener::NativeTlsListener;

mod config;
pub use config::NativeTlsConfig;
pub use config::{Identity, NativeTlsConfig};

#[cfg(test)]
mod tests {
Expand Down
14 changes: 12 additions & 2 deletions crates/core/src/conn/openssl/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ use std::path::Path;
use futures_util::future::{ready, Ready};
use futures_util::stream::{once, Once, Stream};
use openssl::pkey::PKey;
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslMethod, SslRef};
use openssl::ssl::{SslAcceptor, SslMethod, SslRef};
use openssl::x509::X509;
use tokio::io::ErrorKind;

use crate::conn::IntoConfigStream;

pub use openssl::ssl::SslAcceptorBuilder;

/// Private key and certificate
#[derive(Debug)]
pub struct Keycert {
Expand Down Expand Up @@ -119,7 +121,7 @@ impl OpensslConfig {
}

/// Create [`SslAcceptorBuilder`]
pub fn create_acceptor_builder(&mut self) -> Result<SslAcceptorBuilder, IoError> {
pub fn create_acceptor_builder(&mut self) -> IoResult<SslAcceptorBuilder> {
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;

let mut certs = X509::stack_from_pem(self.keycert.cert()?)?;
Expand Down Expand Up @@ -147,6 +149,14 @@ impl OpensslConfig {
}
}

impl TryInto<SslAcceptorBuilder> for OpensslConfig {
type Error = IoError;

fn try_into(mut self) -> IoResult<SslAcceptorBuilder> {
self.create_acceptor_builder()
}
}

impl IntoConfigStream<OpensslConfig> for OpensslConfig {
type Stream = Once<Ready<OpensslConfig>>;

Expand Down
Loading

0 comments on commit 617954f

Please sign in to comment.