Skip to content

Commit

Permalink
error: avoid leaking pem::PemError into api
Browse files Browse the repository at this point in the history
Having `From<pem::PemError>` defined on the public `Error`
type means that the `pem` type leaks into rcgen's public API,
complicating semver incompatible updates.

This commit updates the sites that previously used this trait to
use the crate internal `ExternalError` extension trait to map the
`PemError` err to the generic rcgen `Error::PemError` err.

Additionally, the `rcgen::Error::PemError` variant is changed to hold
a `String` with the `pem::PemError` error string instead of the type
itself. This allows the `From` impl on `Error` to be removed, fixing the
type leak.
  • Loading branch information
cpu committed Dec 8, 2023
1 parent c584880 commit a53aa2f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
9 changes: 1 addition & 8 deletions rcgen/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub enum Error {
Time,
#[cfg(feature = "pem")]
/// Error from the pem crate
PemError(pem::PemError),
PemError(String),
/// Error generated by a remote key operation
RemoteKeyError,
/// Unsupported field when generating a CSR
Expand Down Expand Up @@ -98,13 +98,6 @@ impl fmt::Display for Error {

impl std::error::Error for Error {}

#[cfg(feature = "pem")]
impl From<pem::PemError> for Error {
fn from(e: pem::PemError) -> Self {
Error::PemError(e)
}
}

/// A trait describing an error that can be converted into an `rcgen::Error`.
///
/// We use this trait to avoid leaking external error types into the public API
Expand Down
10 changes: 8 additions & 2 deletions rcgen/src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl KeyPair {
/// Parses the key pair from the ASCII PEM format
#[cfg(feature = "pem")]
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)?;
let private_key = pem::parse(pem_str)._err()?;
let private_key_der: &[_] = private_key.contents();
Ok(private_key_der.try_into()?)
}
Expand All @@ -91,7 +91,7 @@ impl KeyPair {
pem_str: &str,
alg: &'static SignatureAlgorithm,
) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)?;
let private_key = pem::parse(pem_str)._err()?;
let private_key_der: &[_] = private_key.contents();
Ok(Self::from_der_and_sign_algo(private_key_der, alg)?)
}
Expand Down Expand Up @@ -383,6 +383,12 @@ impl<T> ExternalError<T> for Result<T, ring::error::Unspecified> {
}
}

impl<T> ExternalError<T> for Result<T, pem::PemError> {
fn _err(self) -> Result<T, Error> {
self.map_err(|e| Error::PemError(e.to_string()))
}
}

pub(crate) trait PublicKeyData {
fn alg(&self) -> &SignatureAlgorithm;

Expand Down

0 comments on commit a53aa2f

Please sign in to comment.