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 Sep 20, 2024
1 parent 3975e65 commit 5a9f667
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 19 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 @@ -12,7 +12,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 @@ -60,7 +60,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
7 changes: 2 additions & 5 deletions tonic/src/transport/server/service/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ use tokio_rustls::{
TlsAcceptor as RustlsAcceptor,
};

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

#[derive(Clone)]
pub(crate) struct TlsAcceptor {
Expand Down Expand Up @@ -40,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 @@ -43,16 +43,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 5a9f667

Please sign in to comment.