1use alloc::sync::Arc;
4use core::fmt;
5use std::path::{Path, PathBuf};
6
7use rustls::client::WebPkiServerVerifier;
8use rustls::client::danger::ServerCertVerifier;
9use rustls::crypto::CryptoProvider;
10use rustls::pki_types::CertificateDer;
11use rustls::pki_types::pem::PemObject;
12use rustls::{CertificateError, RootCertStore};
13
14use crate::error::{PeerError, Refusal};
15
16#[derive(Clone)]
27pub struct Roots(RootsKind);
28
29#[derive(Clone)]
30enum RootsKind {
31 Pem(String),
32 File(PathBuf),
33 #[cfg(feature = "platform-roots")]
34 Platform,
35}
36
37impl fmt::Debug for Roots {
38 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39 match &self.0 {
40 RootsKind::Pem(text) => formatter
41 .debug_struct("Roots::Pem")
42 .field("bytes", &text.len())
43 .finish(),
44 RootsKind::File(path) => formatter.debug_tuple("Roots::File").field(path).finish(),
45 #[cfg(feature = "platform-roots")]
46 RootsKind::Platform => formatter.write_str("Roots::Platform"),
47 }
48 }
49}
50
51impl Roots {
52 pub fn bundle_pem(text: impl Into<String>) -> Self {
55 Self(RootsKind::Pem(text.into()))
56 }
57
58 pub fn bundle_file(path: impl Into<PathBuf>) -> Self {
62 Self(RootsKind::File(path.into()))
63 }
64
65 #[cfg(feature = "platform-roots")]
72 pub fn platform() -> Self {
73 Self(RootsKind::Platform)
74 }
75
76 pub(crate) fn verifier(
78 &self,
79 provider: &Arc<CryptoProvider>,
80 ) -> Result<Arc<dyn ServerCertVerifier>, PeerError> {
81 let (text, path) = match &self.0 {
82 RootsKind::Pem(text) => (text.as_bytes().to_vec(), None),
83 RootsKind::File(path) => (read_anchors(path)?, Some(path.as_path())),
84 #[cfg(feature = "platform-roots")]
85 RootsKind::Platform => {
86 let verifier = rustls_platform_verifier::Verifier::new(provider.clone())
87 .map_err(|_| PeerError::Certificate)?;
88 return Ok(Arc::new(verifier));
89 }
90 };
91 let roots = anchors(&text, path)?;
92 let verifier =
93 WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone())
94 .build()
95 .map_err(|_| PeerError::Certificate)?;
96 Ok(verifier)
97 }
98}
99
100pub(crate) fn read_anchors(path: &Path) -> Result<Vec<u8>, PeerError> {
102 std::fs::read(path).map_err(|error| PeerError::CaFile {
103 path: Some(path.to_path_buf()),
104 certificate: None,
105 read: Some(error),
106 })
107}
108
109pub(crate) fn anchors(text: &[u8], path: Option<&Path>) -> Result<RootCertStore, PeerError> {
112 let failed = |certificate| PeerError::CaFile {
113 path: path.map(Path::to_path_buf),
114 certificate,
115 read: None,
116 };
117 let mut roots = RootCertStore::empty();
118 for (index, certificate) in CertificateDer::pem_slice_iter(text).enumerate() {
119 roots
120 .add(certificate.map_err(|_| failed(Some(index)))?)
121 .map_err(|_| failed(Some(index)))?;
122 }
123 if roots.is_empty() {
124 return Err(failed(None));
125 }
126 Ok(roots)
127}
128
129pub(crate) fn refusal_of(error: rustls::Error) -> rustls::Error {
134 let rustls::Error::InvalidCertificate(reason) = &error else {
135 return error;
136 };
137 match reason {
138 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => {
139 Refusal::NameMismatch.into_rustls()
140 }
141 CertificateError::Expired
142 | CertificateError::ExpiredContext { .. }
143 | CertificateError::NotValidYet
144 | CertificateError::NotValidYetContext { .. }
145 | CertificateError::Revoked
146 | CertificateError::BadEncoding => error,
147 _ => Refusal::NotTrusted.into_rustls(),
148 }
149}