Skip to content

Commit

Permalink
chore(tls): Refactor parsing Identity
Browse files Browse the repository at this point in the history
  • Loading branch information
tottoto committed Jun 30, 2024
1 parent 4e7e742 commit 1b5d429
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 20 deletions.
4 changes: 2 additions & 2 deletions tonic/src/transport/channel/service/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use tokio_rustls::{
};

use super::io::BoxedIo;
use crate::transport::service::tls::{load_identity, TlsError, ALPN_H2};
use crate::transport::service::tls::{TlsError, ALPN_H2};
use crate::transport::tls::{Certificate, Identity};

#[derive(Clone)]
Expand Down Expand Up @@ -48,7 +48,7 @@ impl TlsConnector {
let builder = builder.with_root_certificates(roots);
let mut config = match identity {
Some(identity) => {
let (client_cert, client_key) = load_identity(identity)?;
let (client_cert, client_key) = identity.parse()?;
builder.with_client_auth_cert(client_cert, client_key)?
}
None => builder.with_no_client_auth(),
Expand Down
8 changes: 2 additions & 6 deletions tonic/src/transport/server/service/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ use tokio_rustls::{
TlsAcceptor as RustlsAcceptor,
};

use crate::transport::{
server::Connected,
service::tls::{load_identity, ALPN_H2},
Certificate, Identity,
};
use crate::transport::{server::Connected, service::tls::ALPN_H2, Certificate, Identity};

#[derive(Clone)]
pub(crate) struct TlsAcceptor {
Expand Down Expand Up @@ -41,7 +37,7 @@ impl TlsAcceptor {
}
};

let (cert, key) = load_identity(identity)?;
let (cert, key) = identity.parse()?;
let mut config = builder.with_single_cert(cert, key)?;

config.alpn_protocols.push(ALPN_H2.into());
Expand Down
22 changes: 10 additions & 12 deletions tonic/src/transport/service/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,14 @@ impl Certificate {
}
}

pub(crate) fn load_identity(
identity: Identity,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), TlsError> {
let cert = rustls_pemfile::certs(&mut Cursor::new(identity.cert))
.collect::<Result<Vec<_>, _>>()
.map_err(|_| TlsError::CertificateParseError)?;

let Ok(Some(key)) = rustls_pemfile::private_key(&mut Cursor::new(identity.key)) else {
return Err(TlsError::PrivateKeyParseError);
};

Ok((cert, key))
impl Identity {
pub(crate) fn parse(
&self,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), TlsError> {
let cert = self.cert.parse()?;
let Ok(Some(key)) = rustls_pemfile::private_key(&mut Cursor::new(&self.key)) else {
return Err(TlsError::PrivateKeyParseError);
};
Ok((cert, key))
}
}

0 comments on commit 1b5d429

Please sign in to comment.