1use std::path::Path;
32use std::sync::Arc;
33use std::sync::OnceLock;
34
35use rustls::pki_types::{CertificateDer, PrivateKeyDer};
36
37use crate::error::{Error, Result};
38
39#[derive(Debug, Clone, Default)]
41pub enum TrustStore {
42 #[default]
46 NativeWithWebPkiFallback,
47 NativeOnly,
50 WebPkiOnly,
53 Custom(Vec<CertificateDer<'static>>),
56}
57
58#[derive(Clone)]
60pub enum ClientIdentity {
61 Pem {
63 cert_chain: Vec<CertificateDer<'static>>,
65 private_key_der: Vec<u8>,
67 key_label: String,
69 },
70}
71
72impl std::fmt::Debug for ClientIdentity {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 Self::Pem {
76 cert_chain,
77 key_label,
78 ..
79 } => f
80 .debug_struct("ClientIdentity::Pem")
81 .field("cert_count", &cert_chain.len())
82 .field("key_label", key_label)
83 .finish_non_exhaustive(),
84 }
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
90pub enum TlsVersion {
91 Tls12,
93 Tls13,
95}
96
97impl TlsVersion {
98 fn to_rustls(self) -> &'static rustls::SupportedProtocolVersion {
99 match self {
100 Self::Tls12 => &rustls::version::TLS12,
101 Self::Tls13 => &rustls::version::TLS13,
102 }
103 }
104}
105
106#[derive(Clone)]
110pub struct TlsConfig {
111 trust_store: TrustStore,
112 custom_ca_roots: Vec<CertificateDer<'static>>,
113 client_identity: Option<ClientIdentity>,
114 verify_hostname: bool,
115 verify_certificate: bool,
116 min_version: Option<TlsVersion>,
117 max_version: Option<TlsVersion>,
118 sni_enabled: bool,
119 root_store: Arc<OnceLock<Result<rustls::RootCertStore>>>,
120}
121
122impl std::fmt::Debug for TlsConfig {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 f.debug_struct("TlsConfig")
125 .field("trust_store", &self.trust_store)
126 .field("has_custom_ca", &!self.custom_ca_roots.is_empty())
127 .field("has_client_identity", &self.client_identity.is_some())
128 .field("verify_hostname", &self.verify_hostname)
129 .field("verify_certificate", &self.verify_certificate)
130 .field("min_version", &self.min_version)
131 .field("max_version", &self.max_version)
132 .field("sni_enabled", &self.sni_enabled)
133 .finish_non_exhaustive()
134 }
135}
136
137impl Default for TlsConfig {
138 fn default() -> Self {
139 Self::builder().build()
140 }
141}
142
143impl TlsConfig {
144 #[must_use]
147 pub fn builder() -> TlsConfigBuilder {
148 TlsConfigBuilder::new()
149 }
150
151 #[must_use]
156 pub fn builder_with_defaults() -> TlsConfigBuilder {
157 Self::builder()
158 }
159
160 #[must_use]
163 pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
164 self.verify_certificate = !accept;
165 self.verify_hostname = !accept;
166 self
167 }
168
169 pub fn tls_connector(&self) -> Result<tokio_rustls::TlsConnector> {
182 let config = self.build_rustls_config()?;
183 Ok(tokio_rustls::TlsConnector::from(Arc::new(config)))
184 }
185
186 pub fn build_rustls_config(&self) -> Result<rustls::ClientConfig> {
193 let root_store = self.build_root_store()?;
194
195 let mut protocol_versions = Vec::new();
196 match (self.min_version, self.max_version) {
197 (Some(min), Some(max)) => {
198 if min > max {
199 return Err(Error::TlsConfig(format!(
200 "invalid TLS version range: min ({min:?}) > max ({max:?})"
201 )));
202 }
203 for v in Self::supported_versions() {
204 if v >= min && v <= max {
205 protocol_versions.push(v.to_rustls());
206 }
207 }
208 }
209 (Some(min), None) => {
210 for v in Self::supported_versions() {
211 if v >= min {
212 protocol_versions.push(v.to_rustls());
213 }
214 }
215 }
216 (None, Some(max)) => {
217 for v in Self::supported_versions() {
218 if v <= max {
219 protocol_versions.push(v.to_rustls());
220 }
221 }
222 }
223 (None, None) => {
224 for v in Self::supported_versions() {
225 protocol_versions.push(v.to_rustls());
226 }
227 }
228 }
229
230 if protocol_versions.is_empty() {
231 return Err(Error::TlsConfig(
232 "no supported TLS versions in configured range".into(),
233 ));
234 }
235
236 let provider = process_crypto_provider()?;
237 let supported_schemes = provider
238 .signature_verification_algorithms
239 .supported_schemes();
240 let mut config = if self.verify_certificate && self.verify_hostname {
241 rustls::ClientConfig::builder_with_provider(provider.clone())
242 .with_protocol_versions(&protocol_versions)
243 .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
244 .with_root_certificates(root_store)
245 .with_no_client_auth()
246 } else if self.verify_certificate {
247 rustls::ClientConfig::builder_with_provider(provider.clone())
248 .with_protocol_versions(&protocol_versions)
249 .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
250 .dangerous()
251 .with_custom_certificate_verifier(no_hostname_verifier(&root_store, provider)?)
252 .with_no_client_auth()
253 } else {
254 rustls::ClientConfig::builder_with_provider(provider)
255 .with_protocol_versions(&protocol_versions)
256 .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
257 .dangerous()
258 .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
259 .with_no_client_auth()
260 };
261
262 #[cfg(feature = "http2")]
269 {
270 config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
271 }
272 #[cfg(not(feature = "http2"))]
273 {
274 config.alpn_protocols = vec![b"http/1.1".to_vec()];
275 }
276 config.enable_sni = self.sni_enabled;
277
278 if let Some(identity) = &self.client_identity {
279 config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(identity.clone()));
280 }
281
282 Ok(config)
283 }
284
285 fn build_root_store(&self) -> Result<rustls::RootCertStore> {
287 self.root_store
288 .get_or_init(|| self.build_root_store_uncached())
289 .clone()
290 }
291
292 fn build_root_store_uncached(&self) -> Result<rustls::RootCertStore> {
293 match &self.trust_store {
294 TrustStore::NativeWithWebPkiFallback => match Self::try_native_roots() {
295 Ok(store) if !store.is_empty() => Ok(store),
296 _ => Ok(Self::webpki_roots()),
297 },
298 TrustStore::NativeOnly => Self::try_native_roots(),
299 TrustStore::WebPkiOnly => Ok(Self::webpki_roots()),
300 TrustStore::Custom(certs) => {
301 if certs.is_empty() {
302 return Err(Error::CaBundle("custom CA bundle is empty".into()));
303 }
304 let mut store = rustls::RootCertStore::empty();
305 for cert in certs {
306 store
307 .add(cert.clone())
308 .map_err(|e| Error::CaBundle(format!("invalid CA certificate: {e}")))?;
309 }
310 Ok(store)
311 }
312 }
313 }
314
315 #[cfg(not(feature = "tls-native-roots"))]
316 fn try_native_roots() -> Result<rustls::RootCertStore> {
317 Err(Error::TlsConfig(
318 "native root certificates are disabled; enable tls-native-roots".into(),
319 ))
320 }
321
322 #[cfg(feature = "tls-native-roots")]
323 fn try_native_roots() -> Result<rustls::RootCertStore> {
324 let mut roots = rustls::RootCertStore::empty();
325
326 #[cfg(feature = "tls-native-roots")]
327 {
328 #[cfg(all(target_os = "linux", feature = "tls-native-roots"))]
329 let pem_paths: &[&str] = &[
330 "/etc/ssl/certs/ca-certificates.crt",
331 "/etc/pki/tls/certs/ca-bundle.crt",
332 "/etc/ssl/ca-bundle.pem",
333 ];
334
335 #[cfg(all(target_os = "macos", feature = "tls-native-roots"))]
336 let pem_paths: &[&str] = &["/etc/ssl/cert.pem", "/usr/local/etc/openssl/cert.pem"];
337
338 #[cfg(any(target_os = "linux", target_os = "macos"))]
339 for path in pem_paths {
340 if let Ok(certs) = load_pem_certs_from_path(Path::new(path)) {
341 for cert in certs {
342 if let Err(e) = roots.add(cert) {
343 #[cfg(feature = "tracing")]
344 tracing::warn!(
345 "eggfetch: skipped invalid CA certificate in {path}: {e}"
346 );
347 #[cfg(not(feature = "tracing"))]
348 let _ = (path, &e);
349 }
350 }
351 }
352 }
353 }
354
355 #[cfg(all(
356 feature = "tls-native-roots",
357 not(any(target_os = "linux", target_os = "macos"))
358 ))]
359 {
360 for cert in rustls_native_certs::load_native_certs().certs {
361 if let Err(e) = roots.add(cert) {
362 #[cfg(feature = "tracing")]
363 tracing::warn!("eggfetch: skipped invalid native CA certificate: {e}");
364 #[cfg(not(feature = "tracing"))]
365 let _ = &e;
366 }
367 }
368 }
369
370 if roots.is_empty() {
371 return Err(Error::TlsConfig(
372 "native root certificates not available".into(),
373 ));
374 }
375 Ok(roots)
376 }
377
378 fn webpki_roots() -> rustls::RootCertStore {
379 let mut roots = rustls::RootCertStore::empty();
380 roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
381 roots
382 }
383
384 fn supported_versions() -> impl Iterator<Item = TlsVersion> {
385 [TlsVersion::Tls12, TlsVersion::Tls13].into_iter()
386 }
387
388 #[must_use]
390 pub fn verify_hostname(&self) -> bool {
391 self.verify_hostname
392 }
393
394 #[must_use]
396 pub fn verify_certificate(&self) -> bool {
397 self.verify_certificate
398 }
399
400 #[must_use]
402 pub fn sni_enabled(&self) -> bool {
403 self.sni_enabled
404 }
405
406 #[allow(dead_code)]
416 pub(crate) fn build_quic_rustls_config(&self) -> Result<rustls::ClientConfig> {
417 let root_store = self.build_root_store()?;
418
419 let provider = process_crypto_provider()?;
420 let supported_schemes = provider
421 .signature_verification_algorithms
422 .supported_schemes();
423 let mut config = if self.verify_certificate && self.verify_hostname {
424 rustls::ClientConfig::builder_with_provider(provider.clone())
425 .with_protocol_versions(&[&rustls::version::TLS13])
426 .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
427 .with_root_certificates(root_store)
428 .with_no_client_auth()
429 } else if self.verify_certificate {
430 rustls::ClientConfig::builder_with_provider(provider.clone())
431 .with_protocol_versions(&[&rustls::version::TLS13])
432 .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
433 .dangerous()
434 .with_custom_certificate_verifier(no_hostname_verifier(&root_store, provider)?)
435 .with_no_client_auth()
436 } else {
437 rustls::ClientConfig::builder_with_provider(provider)
438 .with_protocol_versions(&[&rustls::version::TLS13])
439 .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
440 .dangerous()
441 .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
442 .with_no_client_auth()
443 };
444
445 config.alpn_protocols = vec![b"h3".to_vec()];
446 config.enable_sni = self.sni_enabled;
447
448 if let Some(identity) = &self.client_identity {
449 config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(identity.clone()));
450 }
451
452 Ok(config)
453 }
454}
455
456pub struct TlsConfigBuilder {
458 trust_store: TrustStore,
459 custom_ca_roots: Vec<CertificateDer<'static>>,
460 client_identity: Option<ClientIdentity>,
461 verify_hostname: bool,
462 verify_certificate: bool,
463 min_version: Option<TlsVersion>,
464 max_version: Option<TlsVersion>,
465 sni_enabled: bool,
466}
467
468impl Default for TlsConfigBuilder {
469 fn default() -> Self {
470 Self::new()
471 }
472}
473
474impl TlsConfigBuilder {
475 #[must_use]
477 pub fn new() -> Self {
478 Self {
479 trust_store: TrustStore::NativeWithWebPkiFallback,
480 custom_ca_roots: Vec::new(),
481 client_identity: None,
482 verify_hostname: true,
483 verify_certificate: true,
484 min_version: None,
485 max_version: None,
486 sni_enabled: true,
487 }
488 }
489
490 #[must_use]
492 pub fn trust_store(mut self, store: TrustStore) -> Self {
493 self.trust_store = store;
494 self
495 }
496
497 pub fn ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
505 let certs = load_pem_certs_from_path(path.as_ref())?;
506 if certs.is_empty() {
507 if path.as_ref().is_dir() {
508 return Ok(self);
509 }
510 return Err(Error::CaBundle(format!(
511 "no certificates found in {}",
512 path.as_ref().display()
513 )));
514 }
515 self.custom_ca_roots = certs;
516 self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
517 Ok(self)
518 }
519
520 pub fn add_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
532 let certs = load_pem_certs_from_path(path.as_ref())?;
533 if certs.is_empty() {
534 if path.as_ref().is_dir() {
535 return Ok(self);
536 }
537 return Err(Error::CaBundle(format!(
538 "no certificates found in {}",
539 path.as_ref().display()
540 )));
541 }
542 if !matches!(&self.trust_store, TrustStore::Custom(_)) {
543 self.custom_ca_roots.clear();
544 }
545 for cert in certs {
546 if !self
547 .custom_ca_roots
548 .iter()
549 .any(|existing| existing.as_ref() == cert.as_ref())
550 {
551 self.custom_ca_roots.push(cert);
552 }
553 }
554 self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
555 Ok(self)
556 }
557
558 pub fn ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
565 let certs = parse_pem_certificates(pem_bytes)?;
566 if certs.is_empty() {
567 return Err(Error::CaBundle("no certificates found in PEM data".into()));
568 }
569 self.custom_ca_roots = certs;
570 self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
571 Ok(self)
572 }
573
574 pub fn ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
584 let certs: Vec<CertificateDer<'static>> =
585 der_certs.into_iter().map(CertificateDer::from).collect();
586 if certs.is_empty() {
587 return Err(Error::CaBundle("no DER certificates provided".into()));
588 }
589 self.custom_ca_roots = certs;
590 self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
591 Ok(self)
592 }
593
594 #[must_use]
596 pub fn client_identity(mut self, identity: ClientIdentity) -> Self {
597 self.client_identity = Some(identity);
598 self
599 }
600
601 pub fn client_cert_path(
608 self,
609 cert_path: impl AsRef<Path>,
610 key_path: impl AsRef<Path>,
611 ) -> Result<Self> {
612 let certs = load_pem_certs_from_path(cert_path.as_ref())?;
613 if certs.is_empty() {
614 return Err(Error::ClientCert(format!(
615 "no certificates found in {}",
616 cert_path.as_ref().display()
617 )));
618 }
619
620 let key_bytes = std::fs::read(key_path.as_ref()).map_err(|e| {
621 Error::PrivateKey(format!(
622 "failed to read private key {}: {e}",
623 key_path.as_ref().display()
624 ))
625 })?;
626 let (key_data, key_label) = parse_private_key(&key_bytes)?;
627
628 Ok(self.client_identity(ClientIdentity::Pem {
629 cert_chain: certs,
630 private_key_der: key_data,
631 key_label,
632 }))
633 }
634
635 #[must_use]
641 pub fn verify_hostname(mut self, enabled: bool) -> Self {
642 self.verify_hostname = enabled;
643 self
644 }
645
646 #[must_use]
653 pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
654 self.verify_certificate = !accept;
655 self.verify_hostname = !accept;
656 self
657 }
658
659 #[must_use]
661 pub fn min_tls_version(mut self, version: TlsVersion) -> Self {
662 self.min_version = Some(version);
663 self
664 }
665
666 #[must_use]
668 pub fn max_tls_version(mut self, version: TlsVersion) -> Self {
669 self.max_version = Some(version);
670 self
671 }
672
673 #[must_use]
678 pub fn sni(mut self, enabled: bool) -> Self {
679 self.sni_enabled = enabled;
680 self
681 }
682
683 #[must_use]
685 pub fn build(self) -> TlsConfig {
686 TlsConfig {
687 trust_store: self.trust_store,
688 custom_ca_roots: self.custom_ca_roots,
689 client_identity: self.client_identity,
690 verify_hostname: self.verify_hostname,
691 verify_certificate: self.verify_certificate,
692 min_version: self.min_version,
693 max_version: self.max_version,
694 sni_enabled: self.sni_enabled,
695 root_store: Arc::new(OnceLock::new()),
696 }
697 }
698}
699
700#[derive(Debug)]
702struct NoVerifier {
703 supported_schemes: Vec<rustls::SignatureScheme>,
704}
705
706pub(crate) fn process_crypto_provider() -> Result<Arc<rustls::crypto::CryptoProvider>> {
707 if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
708 return Ok(provider.clone());
709 }
710
711 #[cfg(feature = "tls-rustls")]
716 {
717 let provider = rustls::crypto::ring::default_provider();
721 let _ = provider.install_default();
722 if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
723 return Ok(provider.clone());
724 }
725 }
726 let _ = rustls::ClientConfig::builder();
730 rustls::crypto::CryptoProvider::get_default()
731 .cloned()
732 .ok_or_else(|| Error::TlsConfig("no default TLS crypto provider".into()))
733}
734
735#[derive(Debug)]
740struct NoHostnameVerifier {
741 roots: Arc<rustls::RootCertStore>,
742 delegate: Arc<rustls::client::WebPkiServerVerifier>,
743 supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
744}
745
746fn no_hostname_verifier(
747 roots: &rustls::RootCertStore,
748 provider: Arc<rustls::crypto::CryptoProvider>,
749) -> Result<Arc<dyn rustls::client::danger::ServerCertVerifier>> {
750 let roots = Arc::new(roots.clone());
751 let supported_algs = provider.signature_verification_algorithms;
752 let delegate =
753 rustls::client::WebPkiServerVerifier::builder_with_provider(roots.clone(), provider)
754 .build()
755 .map_err(|e| Error::TlsConfig(format!("failed to build certificate verifier: {e}")))?;
756 Ok(Arc::new(NoHostnameVerifier {
757 roots,
758 delegate,
759 supported_algs,
760 }))
761}
762
763impl rustls::client::danger::ServerCertVerifier for NoHostnameVerifier {
764 fn verify_server_cert(
765 &self,
766 end_entity: &CertificateDer<'_>,
767 intermediates: &[CertificateDer<'_>],
768 _server_name: &rustls::pki_types::ServerName<'_>,
769 _ocsp_response: &[u8],
770 now: rustls::pki_types::UnixTime,
771 ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
772 let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
773 rustls::client::verify_server_cert_signed_by_trust_anchor(
774 &cert,
775 &self.roots,
776 intermediates,
777 now,
778 self.supported_algs.all,
779 )?;
780 Ok(rustls::client::danger::ServerCertVerified::assertion())
781 }
782
783 fn verify_tls12_signature(
784 &self,
785 message: &[u8],
786 cert: &CertificateDer<'_>,
787 dss: &rustls::DigitallySignedStruct,
788 ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
789 self.delegate.verify_tls12_signature(message, cert, dss)
790 }
791
792 fn verify_tls13_signature(
793 &self,
794 message: &[u8],
795 cert: &CertificateDer<'_>,
796 dss: &rustls::DigitallySignedStruct,
797 ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
798 self.delegate.verify_tls13_signature(message, cert, dss)
799 }
800
801 fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
802 self.delegate.supported_verify_schemes()
803 }
804}
805
806impl rustls::client::danger::ServerCertVerifier for NoVerifier {
807 fn verify_server_cert(
808 &self,
809 _end_entity: &CertificateDer<'_>,
810 _intermediates: &[CertificateDer<'_>],
811 _server_name: &rustls::pki_types::ServerName<'_>,
812 _ocsp_response: &[u8],
813 _now: rustls::pki_types::UnixTime,
814 ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
815 Ok(rustls::client::danger::ServerCertVerified::assertion())
816 }
817
818 fn verify_tls12_signature(
819 &self,
820 _message: &[u8],
821 _cert: &CertificateDer<'_>,
822 _dss: &rustls::DigitallySignedStruct,
823 ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
824 Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
825 }
826
827 fn verify_tls13_signature(
828 &self,
829 _message: &[u8],
830 _cert: &CertificateDer<'_>,
831 _dss: &rustls::DigitallySignedStruct,
832 ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
833 Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
834 }
835
836 fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
837 self.supported_schemes.clone()
838 }
839}
840
841struct SingleCertResolver {
843 cert_chain: Vec<CertificateDer<'static>>,
844 private_key_der: Vec<u8>,
845 key_label: String,
846}
847
848impl std::fmt::Debug for SingleCertResolver {
849 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
850 f.debug_struct("SingleCertResolver")
851 .field("cert_count", &self.cert_chain.len())
852 .field("key_label", &self.key_label)
853 .finish_non_exhaustive()
854 }
855}
856
857impl SingleCertResolver {
858 fn new(identity: ClientIdentity) -> Self {
859 match identity {
860 ClientIdentity::Pem {
861 cert_chain,
862 private_key_der,
863 key_label,
864 } => Self {
865 cert_chain,
866 private_key_der,
867 key_label,
868 },
869 }
870 }
871}
872
873impl rustls::client::ResolvesClientCert for SingleCertResolver {
874 fn resolve(
875 &self,
876 _root_hint_subjects: &[&[u8]],
877 _sigschemes: &[rustls::SignatureScheme],
878 ) -> Option<Arc<rustls::sign::CertifiedKey>> {
879 let key_der = match self.key_label.as_str() {
880 "RSA PRIVATE KEY" => PrivateKeyDer::Pkcs1(rustls::pki_types::PrivatePkcs1KeyDer::from(
881 self.private_key_der.clone(),
882 )),
883 "EC PRIVATE KEY" => PrivateKeyDer::Sec1(rustls::pki_types::PrivateSec1KeyDer::from(
884 self.private_key_der.clone(),
885 )),
886 _ => PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
887 self.private_key_der.clone(),
888 )),
889 };
890 let signing_key = match rustls::crypto::ring::sign::any_supported_type(&key_der) {
891 Ok(k) => k,
892 Err(e) => {
893 #[cfg(feature = "tracing")]
894 tracing::warn!(
895 "eggfetch: unsupported private key type ({key_label}): {e}",
896 key_label = self.key_label
897 );
898 #[cfg(not(feature = "tracing"))]
899 let _ = (&self.key_label, &e);
900 return None;
901 }
902 };
903 Some(Arc::new(rustls::sign::CertifiedKey::new(
904 self.cert_chain.clone(),
905 signing_key,
906 )))
907 }
908
909 fn has_certs(&self) -> bool {
910 !self.cert_chain.is_empty()
911 }
912}
913
914const PEM_BEGIN: &[u8] = b"-----BEGIN ";
918const PEM_END: &[u8] = b"-----END ";
920
921fn load_pem_certs_from_path(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
923 if path.is_dir() {
924 let mut entries = std::fs::read_dir(path)
925 .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?
926 .filter_map(std::result::Result::ok)
927 .collect::<Vec<_>>();
928 entries.sort_by_key(std::fs::DirEntry::file_name);
929
930 let mut certs = Vec::new();
931 for entry in entries {
932 if !entry.metadata().is_ok_and(|metadata| metadata.is_file()) {
933 continue;
934 }
935 if let Ok(data) = std::fs::read(entry.path()) {
936 certs.extend(parse_pem_certificates(&data)?);
937 }
938 }
939 return Ok(certs);
940 }
941
942 let data = std::fs::read(path)
943 .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?;
944 parse_pem_certificates(&data)
945}
946
947fn parse_pem_certificates(pem_bytes: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
954 let mut certs = Vec::new();
955 let mut rest = pem_bytes;
956
957 while let Some(pos) = find_pem_start(rest) {
958 let section = &rest[pos..];
962 let section_len = pem_section_len(section)
963 .ok_or_else(|| Error::CaBundle("unterminated PEM block in certificate data".into()))?;
964 let (label, data) = pem_rfc7468::decode_vec(§ion[..section_len])
965 .map_err(|e| Error::CaBundle(format!("invalid PEM block in certificate data: {e}")))?;
966 if label == "CERTIFICATE" {
967 certs.push(CertificateDer::from(data));
968 } else {
969 #[cfg(feature = "tracing")]
974 tracing::warn!("eggfetch: ignoring non-certificate PEM block `{label}` in CA bundle");
975 #[cfg(not(feature = "tracing"))]
976 let _ = &label;
977 }
978 rest = §ion[section_len..];
979 }
980
981 Ok(certs)
982}
983
984fn find_pem_start(data: &[u8]) -> Option<usize> {
986 if data.len() < PEM_BEGIN.len() {
987 return None;
988 }
989 data.windows(PEM_BEGIN.len()).position(|w| w == PEM_BEGIN)
990}
991
992fn pem_section_len(data: &[u8]) -> Option<usize> {
1000 let after_begin = &data[PEM_BEGIN.len()..];
1001 let end_marker = after_begin
1002 .windows(PEM_END.len())
1003 .position(|w| w == PEM_END)?
1004 + PEM_BEGIN.len();
1005 let line_end = data[end_marker..]
1006 .iter()
1007 .position(|&b| b == b'\n')
1008 .map_or(data.len(), |p| end_marker + p + 1);
1009 Some(line_end)
1010}
1011
1012fn parse_private_key(key_bytes: &[u8]) -> Result<(Vec<u8>, String)> {
1017 let mut rest = key_bytes;
1018
1019 while let Some(pos) = find_pem_start(rest) {
1020 let section = &rest[pos..];
1021 let section_len = pem_section_len(section).ok_or_else(|| {
1022 Error::PrivateKey("unterminated PEM block in private key data".into())
1023 })?;
1024 let (label, data) = pem_rfc7468::decode_vec(§ion[..section_len]).map_err(|e| {
1025 Error::PrivateKey(format!("invalid PEM block in private key data: {e}"))
1026 })?;
1027 if matches!(label, "PRIVATE KEY" | "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
1028 return Ok((data, label.to_string()));
1029 }
1030 rest = §ion[section_len..];
1031 }
1032
1033 Err(Error::PrivateKey("no private key found in PEM data".into()))
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038 use super::*;
1039 use proptest::prelude::*;
1040
1041 #[test]
1042 fn default_tls_config() {
1043 let config = TlsConfig::default();
1044 assert!(config.verify_hostname());
1045 assert!(config.verify_certificate());
1046 assert!(config.sni_enabled());
1047 }
1048
1049 #[test]
1050 fn builder_defaults() {
1051 let config = TlsConfig::builder().build();
1052 assert!(config.verify_hostname());
1053 assert!(config.verify_certificate());
1054 assert!(config.sni_enabled());
1055 }
1056
1057 #[test]
1058 fn builder_disable_verification() {
1059 let config = TlsConfig::builder()
1060 .danger_accept_invalid_certs(true)
1061 .build();
1062 assert!(!config.verify_hostname());
1063 assert!(!config.verify_certificate());
1064 }
1065
1066 #[test]
1067 fn config_disable_verification_preserves_other_settings() {
1068 let config = TlsConfig::builder()
1069 .sni(false)
1070 .min_tls_version(TlsVersion::Tls13)
1071 .build()
1072 .danger_accept_invalid_certs(true);
1073 assert!(!config.verify_hostname());
1074 assert!(!config.verify_certificate());
1075 assert!(!config.sni_enabled());
1076 assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1077 }
1078
1079 #[test]
1080 fn builder_custom_tls_version() {
1081 let config = TlsConfig::builder()
1082 .min_tls_version(TlsVersion::Tls13)
1083 .build();
1084 assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1085 }
1086
1087 #[test]
1088 fn builder_invalid_version_range() {
1089 let config = TlsConfig::builder()
1090 .min_tls_version(TlsVersion::Tls13)
1091 .max_tls_version(TlsVersion::Tls12)
1092 .build();
1093 let err = config.build_rustls_config().unwrap_err();
1094 assert_eq!(err.kind(), "tls_config");
1095 }
1096
1097 #[test]
1098 fn builder_sni_disabled() {
1099 let config = TlsConfig::builder().sni(false).build();
1100 assert!(!config.sni_enabled());
1101 }
1102
1103 #[test]
1104 fn trust_store_default() {
1105 let config = TlsConfig::builder().build();
1106 assert!(matches!(
1107 config.trust_store,
1108 TrustStore::NativeWithWebPkiFallback
1109 ));
1110 }
1111
1112 #[test]
1113 fn trust_store_custom_empty_rejected() {
1114 let result = TlsConfig::builder()
1115 .ca_certificate_pem(b"")
1116 .map(super::TlsConfigBuilder::build);
1117 assert!(result.is_err());
1118 }
1119
1120 #[test]
1121 fn add_ca_certificate_path_combines_files_and_directories() {
1122 let make_ca_pem = || {
1123 let mut params = rcgen::CertificateParams::default();
1124 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1125 let key = rcgen::KeyPair::generate().unwrap();
1126 params.self_signed(&key).unwrap().pem()
1127 };
1128 let first = make_ca_pem();
1129 let second = make_ca_pem();
1130 let tempdir = tempfile::tempdir().unwrap();
1131 let first_path = tempdir.path().join("first.pem");
1132 let cert_dir = tempdir.path().join("certs");
1133 std::fs::create_dir(&cert_dir).unwrap();
1134 std::fs::write(&first_path, first).unwrap();
1135 std::fs::write(cert_dir.join("second.pem"), second).unwrap();
1136
1137 let config = TlsConfig::builder()
1138 .ca_certificate_path(first_path)
1139 .unwrap()
1140 .add_ca_certificate_path(cert_dir)
1141 .unwrap()
1142 .build();
1143 assert_eq!(config.custom_ca_roots.len(), 2);
1144
1145 let empty_dir = tempdir.path().join("empty");
1146 std::fs::create_dir(&empty_dir).unwrap();
1147 let config = TlsConfig::builder()
1148 .ca_certificate_path(tempdir.path().join("first.pem"))
1149 .unwrap()
1150 .add_ca_certificate_path(empty_dir)
1151 .unwrap()
1152 .build();
1153 assert_eq!(config.custom_ca_roots.len(), 1);
1154 }
1155
1156 #[test]
1157 fn tls_version_ordering() {
1158 assert!(TlsVersion::Tls12 < TlsVersion::Tls13);
1159 }
1160
1161 #[test]
1162 fn build_rustls_config_verification() {
1163 let config = TlsConfig::builder().build();
1164 let result = config.build_rustls_config();
1165 assert!(result.is_ok());
1166 }
1167
1168 #[test]
1169 fn webpki_only_builds_without_native_roots() {
1170 let config = TlsConfig::builder()
1171 .trust_store(TrustStore::WebPkiOnly)
1172 .build();
1173 assert!(config.build_rustls_config().is_ok());
1174 }
1175
1176 #[cfg(not(feature = "tls-native-roots"))]
1177 #[test]
1178 fn native_only_reports_disabled_feature() {
1179 let config = TlsConfig::builder()
1180 .trust_store(TrustStore::NativeOnly)
1181 .build();
1182 let error = config.build_rustls_config().unwrap_err();
1183 assert!(error.to_string().contains("tls-native-roots"));
1184 }
1185
1186 #[test]
1187 fn build_rustls_config_no_verify() {
1188 let config = TlsConfig::builder()
1189 .danger_accept_invalid_certs(true)
1190 .sni(false)
1191 .build();
1192 let rustls_config = config.build_rustls_config().unwrap();
1193 assert!(!rustls_config.enable_sni);
1194 }
1195
1196 #[test]
1197 fn build_rustls_config_version_range() {
1198 let config = TlsConfig::builder()
1199 .min_tls_version(TlsVersion::Tls12)
1200 .max_tls_version(TlsVersion::Tls13)
1201 .build();
1202 let result = config.build_rustls_config();
1203 assert!(result.is_ok());
1204 }
1205
1206 #[test]
1207 fn parse_empty_pem_certificates() {
1208 let result = parse_pem_certificates(b"");
1209 assert!(result.unwrap().is_empty());
1210 }
1211
1212 #[test]
1213 fn parse_invalid_pem_certificates() {
1214 let result = parse_pem_certificates(b"not valid pem data");
1215 assert!(result.unwrap().is_empty());
1216 }
1217
1218 #[test]
1219 fn parse_pem_certificates_skip_garbage_between_blocks() {
1220 let valid_block = |body: &[u8]| -> Vec<u8> {
1223 let mut block = b"-----BEGIN CERTIFICATE-----\n".to_vec();
1224 block.extend_from_slice(body);
1225 block.extend_from_slice(b"\n-----END CERTIFICATE-----\n");
1226 block
1227 };
1228 let first = valid_block(b"AAAA");
1230 let second = valid_block(b"BBBB");
1231 let mut pem = first;
1232 pem.extend_from_slice(b"\nthis is not valid PEM \x01\x02 data\n");
1233 pem.extend_from_slice(&second);
1234
1235 let certs = parse_pem_certificates(&pem).unwrap();
1236 assert_eq!(certs.len(), 2, "both certificates must be recovered");
1237 }
1238
1239 #[test]
1240 fn parse_pem_certificates_multi_block_bundle() {
1241 let mut pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n".to_vec();
1244 pem.extend_from_slice(b"-----BEGIN CERTIFICATE-----\nBBBB\n-----END CERTIFICATE-----\n");
1245 pem.extend_from_slice(b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n");
1246
1247 let certs = parse_pem_certificates(&pem).unwrap();
1248 assert_eq!(certs.len(), 2, "both certificates, key section skipped");
1249 }
1250
1251 #[test]
1252 fn parse_private_key_skips_leading_garbage() {
1253 let key_block = b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
1254 let mut pem = b"corrupt \x03 preamble\n".to_vec();
1255 pem.extend_from_slice(key_block);
1256
1257 let (der, label) = parse_private_key(&pem).unwrap();
1258 assert_eq!(label, "PRIVATE KEY");
1259 assert_eq!(der, vec![0u8, 0, 0]);
1261 }
1262
1263 #[test]
1264 fn parse_pem_certificates_rejects_corrupted_blocks() {
1265 let pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n\
1266-----BEGIN CERTIFICATE-----\n%%%\n-----END CERTIFICATE-----\n";
1267 let err = parse_pem_certificates(pem).unwrap_err();
1268 assert_eq!(err.kind(), "ca_bundle");
1269 }
1270
1271 #[test]
1272 fn error_variants() {
1273 let err = Error::TlsConfig("test".into());
1274 assert_eq!(err.kind(), "tls_config");
1275
1276 let err = Error::CaBundle("test".into());
1277 assert_eq!(err.kind(), "ca_bundle");
1278
1279 let err = Error::ClientCert("test".into());
1280 assert_eq!(err.kind(), "client_cert");
1281
1282 let err = Error::PrivateKey("test".into());
1283 assert_eq!(err.kind(), "private_key");
1284
1285 let err = Error::CertificateVerification("test".into());
1286 assert_eq!(err.kind(), "certificate_verification");
1287
1288 let err = Error::HostnameVerification("test".into());
1289 assert_eq!(err.kind(), "hostname_verification");
1290 }
1291
1292 #[test]
1293 fn debug_impl_no_secrets() {
1294 let config = TlsConfig::builder().build();
1295 let debug = format!("{config:?}");
1296 assert!(debug.contains("verify_hostname: true"));
1297 assert!(debug.contains("verify_certificate: true"));
1298 }
1299
1300 #[test]
1301 fn client_identity_debug_no_private_key() {
1302 let identity = ClientIdentity::Pem {
1303 cert_chain: vec![],
1304 private_key_der: b"super-secret-private-key-data".to_vec(),
1305 key_label: "PRIVATE KEY".to_string(),
1306 };
1307 let debug = format!("{identity:?}");
1308 assert!(
1309 !debug.contains("super-secret"),
1310 "ClientIdentity Debug must not leak private key bytes: {debug}"
1311 );
1312 assert!(debug.contains("cert_count"));
1313 assert!(debug.contains("key_label"));
1314 }
1315
1316 proptest::proptest! {
1317 #[test]
1318 fn parse_pem_certificates_empty_input(_ in 0u64..100) {
1319 let result = parse_pem_certificates(b"");
1320 prop_assert!(result.unwrap().is_empty());
1321 }
1322
1323 #[test]
1324 fn parse_pem_certificates_garbage(input in ".{0,200}") {
1325 let _ = parse_pem_certificates(input.as_bytes());
1327 }
1328
1329 #[test]
1330 fn tls_config_builder_round_trip(sni in prop::bool::ANY) {
1331 let config = TlsConfig::builder()
1332 .sni(sni)
1333 .build();
1334 prop_assert_eq!(config.sni_enabled(), sni);
1335 prop_assert!(config.verify_hostname());
1337 prop_assert!(config.verify_certificate());
1338 }
1339
1340 #[test]
1341 fn build_rustls_config_valid_for_defaults(_ in 0u64..100) {
1342 let config = TlsConfig::default();
1343 let result = config.build_rustls_config();
1344 prop_assert!(result.is_ok());
1345 }
1346 }
1347}