1 use std::{fmt, io::Cursor};
2
3 use tokio_rustls::rustls::pki_types::{pem::PemObject as _, CertificateDer, PrivateKeyDer};
4
5 use crate::transport::{Certificate, Identity};
6
7 /// h2 alpn in plain format for rustls.
8 pub(crate) const ALPN_H2: &[u8] = b"h2";
9
10 #[derive(Debug)]
11 pub(crate) enum TlsError {
12 #[cfg(feature = "channel")]
13 H2NotNegotiated,
14 #[cfg(feature = "tls-native-roots")]
15 NativeCertsNotFound,
16 CertificateParseError,
17 PrivateKeyParseError,
18 }
19
20 impl fmt::Display for TlsError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 match self {
23 #[cfg(feature = "channel")]
24 TlsError::H2NotNegotiated => write!(f, "HTTP/2 was not negotiated."),
25 #[cfg(feature = "tls-native-roots")]
26 TlsError::NativeCertsNotFound => write!(f, "no native certs found"),
27 TlsError::CertificateParseError => write!(f, "Error parsing TLS certificate."),
28 TlsError::PrivateKeyParseError => write!(
29 f,
30 "Error parsing TLS private key - no RSA or PKCS8-encoded keys found."
31 ),
32 }
33 }
34 }
35
36 impl std::error::Error for TlsError {}
37
convert_certificate_to_pki_types( certificate: &Certificate, ) -> Result<Vec<CertificateDer<'static>>, TlsError>38 pub(crate) fn convert_certificate_to_pki_types(
39 certificate: &Certificate,
40 ) -> Result<Vec<CertificateDer<'static>>, TlsError> {
41 CertificateDer::pem_reader_iter(&mut Cursor::new(certificate))
42 .collect::<Result<Vec<_>, _>>()
43 .map_err(|_| TlsError::CertificateParseError)
44 }
45
convert_identity_to_pki_types( identity: &Identity, ) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), TlsError>46 pub(crate) fn convert_identity_to_pki_types(
47 identity: &Identity,
48 ) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), TlsError> {
49 let cert = convert_certificate_to_pki_types(&identity.cert)?;
50 let key = PrivateKeyDer::from_pem_reader(&mut Cursor::new(&identity.key))
51 .map_err(|_| TlsError::PrivateKeyParseError)?;
52 Ok((cert, key))
53 }
54