Skip to content

Commit

Permalink
Change TLS to conditionally load native certs
Browse files Browse the repository at this point in the history
Until now, when TLS was used, native OS certs were always loaded.
This should not be the case if CA is provided in rustls config
or options.
  • Loading branch information
Jarema committed Jan 5, 2023
1 parent 5c2ac90 commit 33deb4c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 14 deletions.
31 changes: 17 additions & 14 deletions async-nats/src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,23 @@ pub(crate) async fn load_key(path: PathBuf) -> io::Result<PrivateKey> {

pub(crate) async fn config_tls(options: &ConnectorOptions) -> io::Result<rustls::ClientConfig> {
let mut root_store = rustls::RootCertStore::empty();
for cert in rustls_native_certs::load_native_certs().map_err(|err| {
io::Error::new(
ErrorKind::Other,
format!("could not load platform certs: {err}"),
)
})? {
root_store
.add(&rustls::Certificate(cert.0))
.map_err(|err| {
io::Error::new(
ErrorKind::Other,
format!("failed to read root certificates: {err}"),
)
})?;
// load native system certs only if user did not specify them.
if options.tls_client_config.is_some() || options.certificates.is_empty() {
for cert in rustls_native_certs::load_native_certs().map_err(|err| {
io::Error::new(
ErrorKind::Other,
format!("could not load platform certs: {err}"),
)
})? {
root_store
.add(&rustls::Certificate(cert.0))
.map_err(|err| {
io::Error::new(
ErrorKind::Other,
format!("failed to read root certificates: {err}"),
)
})?;
}
}

// use provided ClientConfig or built it from options.
Expand Down
14 changes: 14 additions & 0 deletions async-nats/tests/tls_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,18 @@ mod client {
.unwrap()
.unwrap();
}

#[tokio::test]
async fn tls_with_native_certs() {
let client = async_nats::ConnectOptions::new()
.require_tls(true)
.connect("tls://demo.nats.io")
.await
.unwrap();

client
.publish("subject".into(), "data".into())
.await
.unwrap();
}
}

0 comments on commit 33deb4c

Please sign in to comment.