Skip to content

Commit

Permalink
Run cargo fmt --all
Browse files Browse the repository at this point in the history
  • Loading branch information
hargut committed Jul 24, 2024
1 parent c271103 commit 76b6a68
Show file tree
Hide file tree
Showing 30 changed files with 429 additions and 334 deletions.
7 changes: 2 additions & 5 deletions pingora-core/src/connectors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ use offload::OffloadRuntime;
use pingora_error::{ErrorType::*, OrErr, Result};
use pingora_pool::{ConnectionMeta, ConnectionPool};

use crate::connectors::tls::{Connector, do_connect};
use crate::connectors::tls::{do_connect, Connector};
use crate::protocols::Stream;
use crate::server::configuration::ServerConf;
use crate::upstreams::peer::{ALPN, Peer};
use crate::upstreams::peer::{Peer, ALPN};

pub mod http;
mod l4;
Expand Down Expand Up @@ -271,9 +271,6 @@ impl TransportConnector {
}
}




struct PreferredHttpVersion {
// TODO: shard to avoid the global lock
versions: RwLock<HashMap<u64, u8>>, // <hash of peer, version>
Expand Down
24 changes: 11 additions & 13 deletions pingora-core/src/connectors/tls/boringssl_openssl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,27 @@ use std::sync::{Arc, Once};

use log::debug;

use pingora_error::{Error, OrErr, Result};
use pingora_error::ErrorType::{ConnectTimedout, InternalError};
use pingora_error::{Error, OrErr, Result};

use crate::connectors::ConnectorOptions;
use crate::listeners::ALPN;
use crate::protocols::IO;
use crate::protocols::tls::boringssl_openssl::client::handshake;
use crate::protocols::tls::TlsStream;
use crate::protocols::IO;
use crate::tls::ext::{
add_host, clear_error_stack, ssl_add_chain_cert, ssl_set_groups_list,
ssl_set_renegotiate_mode_freely, ssl_set_verify_cert_store, ssl_use_certificate,
ssl_use_private_key, ssl_use_second_key_share,
};
use crate::tls::ssl::{SslConnector, SslFiletype, SslMethod, SslVerifyMode, SslVersion};
#[cfg(feature = "boringssl")]
use crate::tls::ssl::SslCurve;
use crate::tls::ssl::{SslConnector, SslFiletype, SslMethod, SslVerifyMode, SslVersion};
use crate::tls::x509::store::X509StoreBuilder;
use crate::upstreams::peer::Peer;
use crate::utils::tls::boringssl_openssl::{der_to_private_key, der_to_x509};

use super::{Connector, replace_leftmost_underscore, TlsConnectorContext};
use super::{replace_leftmost_underscore, Connector, TlsConnectorContext};

const CIPHER_LIST: &str = "AES-128-GCM-SHA256\
:AES-256-GCM-SHA384\
Expand Down Expand Up @@ -103,7 +103,7 @@ impl TlsConnectorContext for TlsConnectorCtx {

fn build_connector(options: Option<ConnectorOptions>) -> Connector
where
Self: Sized
Self: Sized,
{
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
// TODO: make these conf
Expand Down Expand Up @@ -168,9 +168,9 @@ pub(super) async fn connect<T, P>(
alpn_override: Option<ALPN>,
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>,
) -> Result<TlsStream<T>>
where
T: IO,
P: Peer + Send + Sync
where
T: IO,
P: Peer + Send + Sync,
{
let ctx = tls_ctx.as_any().downcast_ref::<TlsConnectorCtx>().unwrap();
let mut ssl_conf = ctx.0.configure().unwrap();
Expand All @@ -193,11 +193,9 @@ pub(super) async fn connect<T, P>(
if let Some(key_pair) = peer.get_client_cert_key() {
debug!("setting client cert and key");
let leaf = der_to_x509(&*key_pair.leaf())?;
ssl_use_certificate(&mut ssl_conf, &leaf)
.or_err(InternalError, "invalid client cert")?;
ssl_use_certificate(&mut ssl_conf, &leaf).or_err(InternalError, "invalid client cert")?;
let key = der_to_private_key(&*key_pair.key())?;
ssl_use_private_key(&mut ssl_conf, &key)
.or_err(InternalError, "invalid client key")?;
ssl_use_private_key(&mut ssl_conf, &key).or_err(InternalError, "invalid client key")?;

let intermediates = key_pair.intermediates();
if !intermediates.is_empty() {
Expand Down Expand Up @@ -275,4 +273,4 @@ pub(super) async fn connect<T, P>(
},
None => connect_future.await,
}
}
}
28 changes: 18 additions & 10 deletions pingora-core/src/connectors/tls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use std::any::Any;
use std::net::SocketAddr;
use std::sync::Arc;

use pingora_error::{Error, Result};
use pingora_error::ErrorType::ConnectTimedout;
use pingora_error::{Error, Result};

use crate::connectors::l4::connect as l4_connect;
#[cfg(not(feature = "rustls"))]
Expand All @@ -29,7 +29,7 @@ use crate::connectors::tls::rustls::connect as tls_connect;
#[cfg(feature = "rustls")]
use crate::connectors::tls::rustls::TlsConnectorCtx;
use crate::protocols::Stream;
use crate::upstreams::peer::{ALPN, Peer};
use crate::upstreams::peer::{Peer, ALPN};

use super::ConnectorOptions;

Expand All @@ -53,14 +53,15 @@ pub(crate) trait TlsConnectorContext {
fn as_any(&self) -> &dyn Any;

fn build_connector(options: Option<ConnectorOptions>) -> Connector
where Self: Sized;
where
Self: Sized;
}

pub(super) async fn do_connect<P: Peer + Send + Sync>(
peer: &P,
bind_to: Option<SocketAddr>,
alpn_override: Option<ALPN>,
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>,
) -> Result<Stream> {
// Create the future that does the connections, but don't evaluate it until
// we decide if we need a timeout or not
Expand All @@ -82,7 +83,7 @@ async fn do_connect_inner<P: Peer + Send + Sync>(
peer: &P,
bind_to: Option<SocketAddr>,
alpn_override: Option<ALPN>,
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>,
) -> Result<Stream> {
let stream = l4_connect(peer, bind_to).await?;
if peer.tls() {
Expand Down Expand Up @@ -138,17 +139,24 @@ mod tests {
];

for case in none_cases {
assert!(super::replace_leftmost_underscore(case).is_none(), "{}", case);
assert!(
super::replace_leftmost_underscore(case).is_none(),
"{}",
case
);
}

assert_eq!(
Some("bb-b.some.com".to_string()), super::replace_leftmost_underscore("bb_b.some.com")
Some("bb-b.some.com".to_string()),
super::replace_leftmost_underscore("bb_b.some.com")
);
assert_eq!(
Some("a-a-a.some.com".to_string()), super::replace_leftmost_underscore("a_a_a.some.com")
Some("a-a-a.some.com".to_string()),
super::replace_leftmost_underscore("a_a_a.some.com")
);
assert_eq!(
Some("-.some.com".to_string()), super::replace_leftmost_underscore("_.some.com")
Some("-.some.com".to_string()),
super::replace_leftmost_underscore("_.some.com")
);
}
}
}
78 changes: 46 additions & 32 deletions pingora-core/src/connectors/tls/rustls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,31 @@ use std::sync::Arc;

use log::debug;

use pingora_error::{Error, OrErr, Result};
use pingora_error::ErrorType::{ConnectTimedout, InvalidCert};
use pingora_rustls::{load_ca_file_into_store, load_certs_key_file, load_platform_certs_incl_env_into_store};
use pingora_error::{Error, OrErr, Result};
use pingora_rustls::version;
use pingora_rustls::CertificateDer;
use pingora_rustls::ClientConfig;
use pingora_rustls::ClientConfig as RusTlsClientConfig;
use pingora_rustls::PrivateKeyDer;
use pingora_rustls::RootCertStore;
use pingora_rustls::TlsConnector as RusTlsConnector;
use pingora_rustls::version;
use pingora_rustls::{
load_ca_file_into_store, load_certs_key_file, load_platform_certs_incl_env_into_store,
};

use crate::connectors::ConnectorOptions;
use crate::listeners::ALPN;
use crate::protocols::IO;
use crate::protocols::tls::rustls::client::handshake;
use crate::protocols::tls::TlsStream;
use crate::protocols::IO;
use crate::upstreams::peer::Peer;

use super::{Connector, replace_leftmost_underscore, TlsConnectorContext};
use super::{replace_leftmost_underscore, Connector, TlsConnectorContext};

pub(crate) struct TlsConnectorCtx {
config: RusTlsClientConfig,
ca_certs: RootCertStore
ca_certs: RootCertStore,
}
impl TlsConnectorContext for TlsConnectorCtx {
fn as_any(&self) -> &dyn Any {
Expand All @@ -50,7 +52,7 @@ impl TlsConnectorContext for TlsConnectorCtx {

fn build_connector(options: Option<ConnectorOptions>) -> Connector
where
Self: Sized
Self: Sized,
{
// NOTE: Rustls only supports TLS 1.2 & 1.3

Expand Down Expand Up @@ -88,37 +90,35 @@ impl TlsConnectorContext for TlsConnectorCtx {
let config = match certs_key {
Some((certs, key)) => {
match builder.with_client_auth_cert(certs.clone(), key.clone_key()) {
Ok(config) => { config }
Ok(config) => config,
Err(err) => {
// TODO: is there a viable alternative to the panic?
// falling back to no client auth... does not seem to be reasonable.
panic!("{}", format!("Failed to configure client auth cert/key. Error: {}", err));
panic!(
"{}",
format!("Failed to configure client auth cert/key. Error: {}", err)
);
}
}
}
None => {
builder.with_no_client_auth()
}
None => builder.with_no_client_auth(),
};

Connector {
ctx: Arc::new(TlsConnectorCtx {
config,
ca_certs
}),
ctx: Arc::new(TlsConnectorCtx { config, ca_certs }),
}
}
}

pub(super) async fn connect<T, P>(
pub(super) async fn connect<T, P>(
stream: T,
peer: &P,
alpn_override: Option<ALPN>,
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>
tls_ctx: &Arc<dyn TlsConnectorContext + Send + Sync>,
) -> Result<TlsStream<T>>
where
T: IO,
P: Peer + Send + Sync
P: Peer + Send + Sync,
{
let ctx = tls_ctx.as_any().downcast_ref::<TlsConnectorCtx>().unwrap();
let mut config = ctx.config.clone();
Expand All @@ -129,7 +129,7 @@ where

let key_pair = peer.get_client_cert_key();
let updated_config: Option<ClientConfig> = match key_pair {
None => { None }
None => None,
Some(key_arc) => {
debug!("setting client cert and key");

Expand All @@ -138,20 +138,34 @@ where
cert_chain.push(key_arc.leaf().to_owned());

debug!("adding intermediate certificates to mTLS cert chain");
key_arc.intermediates().to_owned().iter()
key_arc
.intermediates()
.to_owned()
.iter()
.map(|i| i.to_vec())
.for_each(|i| cert_chain.push(i));

let certs: Vec<CertificateDer> = cert_chain.into_iter()
.map(|c| c.as_slice().to_owned().into()).collect();
let private_key: PrivateKeyDer = key_arc.key().as_slice().to_owned().try_into().unwrap();

let builder =
ClientConfig::builder_with_protocol_versions(&vec![&version::TLS12, &version::TLS13])
.with_root_certificates(ctx.ca_certs.clone());

let updated_config = builder.with_client_auth_cert(certs, private_key)
.explain_err(InvalidCert, |e| format!("Failed to use peer cert/key to update Rustls config: {:?}",e))?;
let certs: Vec<CertificateDer> = cert_chain
.into_iter()
.map(|c| c.as_slice().to_owned().into())
.collect();
let private_key: PrivateKeyDer =
key_arc.key().as_slice().to_owned().try_into().unwrap();

let builder = ClientConfig::builder_with_protocol_versions(&vec![
&version::TLS12,
&version::TLS13,
])
.with_root_certificates(ctx.ca_certs.clone());

let updated_config = builder
.with_client_auth_cert(certs, private_key)
.explain_err(InvalidCert, |e| {
format!(
"Failed to use peer cert/key to update Rustls config: {:?}",
e
)
})?;
Some(updated_config)
}
};
Expand Down Expand Up @@ -212,4 +226,4 @@ where
},
None => connect_future.await,
}
}
}
12 changes: 10 additions & 2 deletions pingora-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,18 @@ pub use pingora_error::{ErrorType::*, *};
#[cfg(all(not(feature = "rustls"), feature = "boringssl"))]
pub use pingora_boringssl as tls;

#[cfg(all(not(feature = "rustls"), not(feature = "boringssl"), feature = "openssl"))]
#[cfg(all(
not(feature = "rustls"),
not(feature = "boringssl"),
feature = "openssl"
))]
pub use pingora_openssl as tls;

#[cfg(all(not(feature = "boringssl"), not(feature = "openssl"), feature = "rustls"))]
#[cfg(all(
not(feature = "boringssl"),
not(feature = "openssl"),
feature = "rustls"
))]
pub use pingora_rustls as tls;

pub mod prelude {
Expand Down
11 changes: 6 additions & 5 deletions pingora-core/src/listeners/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ use std::{fs::Permissions, sync::Arc};
use l4::{ListenerEndpoint, Stream as L4Stream};
pub use l4::{ServerAddress, TcpSocketOptions};
use pingora_error::Result;
pub use tls::{ALPN, TlsSettings};
use tls::Acceptor;
pub use tls::{TlsSettings, ALPN};

use crate::protocols::{IO, Stream};
pub use crate::protocols::tls::server::TlsAccept;
#[cfg(not(feature = "rustls"))]
use crate::protocols::tls::TlsStream as TlsStreamProvider;
#[cfg(feature = "rustls")]
use crate::protocols::tls::TlsStream as TlsStreamProvider;
pub use crate::protocols::tls::server::TlsAccept;
use crate::protocols::{Stream, IO};
use crate::server::ListenFds;

mod l4;
Expand Down Expand Up @@ -85,7 +85,8 @@ pub(crate) struct UninitializedStream {
impl UninitializedStream {
pub async fn handshake(self) -> Result<Stream> {
if let Some(tls) = self.tls {
let tls_stream : TlsStreamProvider<Box<dyn IO + Send>> = tls.handshake(Box::new(self.l4)).await?;
let tls_stream: TlsStreamProvider<Box<dyn IO + Send>> =
tls.handshake(Box::new(self.l4)).await?;
Ok(Box::new(tls_stream))
} else {
Ok(Box::new(self.l4))
Expand Down Expand Up @@ -187,7 +188,7 @@ impl Listeners {
mod test {
use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
use tokio::time::{Duration, sleep};
use tokio::time::{sleep, Duration};

use super::*;

Expand Down
Loading

0 comments on commit 76b6a68

Please sign in to comment.