1#![warn(missing_docs)]
71
72use std::cell::{Cell, RefCell};
73use std::collections::HashSet;
74use std::ffi::OsStr;
75use std::future::poll_fn;
76use std::io::{self, Read, Write};
77use std::mem;
78use std::net::Shutdown;
79use std::path::{Path, PathBuf};
80use std::sync::Arc;
81use std::task::{Poll, Waker};
82use std::time::Duration;
83
84use giong::error::Code;
85use giong::net::TcpStream;
86use giong::time::timeout;
87use rustls::client::ResolvesClientCert;
88use rustls::pki_types::pem::PemObject;
89use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
90use rustls::sign::CertifiedKey;
91use rustls::{
92 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
93 SignatureScheme,
94};
95
96pub use rustls;
97
98fn coded(
99 code: Code,
100 message: impl Into<std::borrow::Cow<'static, str>>,
101 fix: &'static str,
102) -> io::Error {
103 giong::error::Error::new(code, message, fix).into()
104}
105
106fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
108 coded(
109 Code::BadCertificateData,
110 e.to_string(),
111 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
112 at least one certificate.",
113 )
114}
115
116fn bad_key(e: impl std::fmt::Display) -> io::Error {
118 coded(
119 Code::BadCertificateData,
120 format!("cannot read the private key: {e}"),
121 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
122 EC forms).",
123 )
124}
125
126fn mismatched_key(e: rustls::Error) -> io::Error {
128 coded(
129 Code::BadCertificateData,
130 format!("the certificate and the private key cannot be used together: {e}"),
131 "check that the key belongs to the first certificate of the chain, and that its type \
132 (RSA, ECDSA, Ed25519) is supported.",
133 )
134}
135
136fn tls_error(e: rustls::Error) -> io::Error {
138 match e {
139 rustls::Error::InvalidCertificate(_) => coded(
140 Code::TlsCertificate,
141 format!("the peer's certificate was rejected: {e}"),
142 "check the name you connect to, the certificate's expiry and its chain; a \
143 private authority has to be trusted with TlsConnector::with_roots.",
144 ),
145 e => coded(
146 Code::TlsProtocol,
147 format!("TLS error: {e}"),
148 "check that the other side speaks TLS on this port, and that both sides share a \
149 protocol version and cipher suite.",
150 ),
151 }
152}
153
154const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
156
157fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
159 let certs = CertificateDer::pem_slice_iter(pem)
160 .collect::<Result<Vec<_>, _>>()
161 .map_err(bad_certificate_data)?;
162 if certs.is_empty() {
163 return Err(bad_certificate_data("no certificate found in the PEM data"));
164 }
165 Ok(certs)
166}
167
168fn ring() -> Arc<rustls::crypto::CryptoProvider> {
169 Arc::new(rustls::crypto::ring::default_provider())
170}
171
172#[derive(Clone)]
176pub struct TlsAcceptor {
177 config: Arc<ServerConfig>,
178 handshake_timeout: Duration,
179}
180
181impl TlsAcceptor {
182 pub fn new(config: Arc<ServerConfig>) -> Self {
184 Self {
185 config,
186 handshake_timeout: HANDSHAKE_TIMEOUT,
187 }
188 }
189
190 pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
194 let certs = pem_certs(cert_chain)?;
195 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
196 let mut config = ServerConfig::builder_with_provider(ring())
197 .with_safe_default_protocol_versions()
198 .map_err(tls_error)?
199 .with_no_client_auth()
200 .with_single_cert(certs, key)
201 .map_err(mismatched_key)?;
202 config.alpn_protocols = vec![b"http/1.1".to_vec()];
203 Ok(Self::new(Arc::new(config)))
204 }
205
206 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
209 self.handshake_timeout = timeout;
210 self
211 }
212
213 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
215 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
216 TlsStream::new(tcp, conn.into())
217 .handshake(self.handshake_timeout)
218 .await
219 }
220}
221
222impl std::fmt::Debug for TlsAcceptor {
223 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224 f.debug_struct("TlsAcceptor")
225 .field("handshake_timeout", &self.handshake_timeout)
226 .finish_non_exhaustive()
227 }
228}
229
230#[derive(Clone)]
251pub struct TlsConnector {
252 config: Arc<ClientConfig>,
253 handshake_timeout: Duration,
254}
255
256impl TlsConnector {
257 pub fn new(config: Arc<ClientConfig>) -> Self {
259 Self {
260 config,
261 handshake_timeout: HANDSHAKE_TIMEOUT,
262 }
263 }
264
265 pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
268 if roots.is_empty() {
269 return Err(io::Error::new(
270 io::ErrorKind::InvalidData,
271 giong::error::Error::new(
272 Code::NoTrustedRoots,
273 "no trusted certificate authority given",
274 "pass at least one certificate, or use TlsConnector::with_system_roots.",
275 ),
276 ));
277 }
278 let config = ClientConfig::builder_with_provider(ring())
279 .with_safe_default_protocol_versions()
280 .map_err(tls_error)?
281 .with_root_certificates(roots)
282 .with_no_client_auth();
283 Ok(Self::new(Arc::new(config)))
284 }
285
286 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
289 let mut roots = RootCertStore::empty();
290 for cert in pem_certs(pem)? {
291 roots.add(cert).map_err(bad_certificate_data)?;
292 }
293 Self::with_roots(roots)
294 }
295
296 pub fn with_system_roots() -> io::Result<Self> {
312 let file = std::env::var_os("SSL_CERT_FILE");
313 let dirs = std::env::var_os("SSL_CERT_DIR");
314 let roots = load_roots(
315 file.as_deref(),
316 dirs.as_deref(),
317 SYSTEM_CA_BUNDLES,
318 SYSTEM_CA_DIR,
319 )?;
320 Self::with_roots(roots)
321 }
322
323 #[cfg(feature = "webpki-roots")]
330 pub fn with_webpki_roots() -> Self {
331 let roots = RootCertStore {
332 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
333 };
334 Self::with_roots(roots).expect("the webpki-roots crate provides roots")
335 }
336
337 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
341 Arc::make_mut(&mut self.config).alpn_protocols =
342 protocols.iter().map(|p| p.to_vec()).collect();
343 self
344 }
345
346 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
349 let certs = pem_certs(cert_chain)?;
350 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
351 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
352 .map_err(mismatched_key)?;
353 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
354 Arc::new(ClientCert(Arc::new(key)));
355 Ok(self)
356 }
357
358 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
361 self.handshake_timeout = timeout;
362 self
363 }
364
365 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
374 let name = parse_server_name(server_name)?;
375 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
376 TlsStream::new(tcp, conn.into())
377 .handshake(self.handshake_timeout)
378 .await
379 }
380}
381
382impl std::fmt::Debug for TlsConnector {
383 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384 f.debug_struct("TlsConnector")
385 .field("handshake_timeout", &self.handshake_timeout)
386 .finish_non_exhaustive()
387 }
388}
389
390fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
392 let ipv6 = name
393 .strip_prefix('[')
394 .and_then(|n| n.strip_suffix(']'))
395 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
396 if let Some(ip) = ipv6 {
397 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
398 }
399 ServerName::try_from(name.to_owned()).map_err(|_| {
400 coded(
401 Code::InvalidServerName,
402 format!("{name:?} is neither a DNS name nor an IP address"),
403 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
404 without a port or a scheme.",
405 )
406 })
407}
408
409#[derive(Debug)]
411struct ClientCert(Arc<CertifiedKey>);
412
413impl ResolvesClientCert for ClientCert {
414 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
415 Some(self.0.clone())
416 }
417
418 fn has_certs(&self) -> bool {
419 true
420 }
421}
422
423const SYSTEM_CA_BUNDLES: &[&str] = &[
425 "/etc/ssl/certs/ca-certificates.crt",
427 "/etc/pki/tls/certs/ca-bundle.crt",
429 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
430 "/etc/ssl/ca-bundle.pem",
432 "/etc/ssl/cert.pem",
434];
435
436const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
438
439fn load_roots(
444 file: Option<&OsStr>,
445 dirs: Option<&OsStr>,
446 bundles: &[&str],
447 dir: &str,
448) -> io::Result<RootCertStore> {
449 let mut roots = Roots {
450 store: RootCertStore::empty(),
451 seen: HashSet::new(),
452 };
453 if file.is_some() || dirs.is_some() {
454 if let Some(file) = file {
455 roots.add_file(Path::new(file)).map_err(|e| {
456 io::Error::new(
457 e.kind(),
458 giong::error::Error::new(
459 Code::BadCertificateData,
460 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
461 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
462 it to use the system's.",
463 )
464 .with_source(e),
465 )
466 })?;
467 }
468 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
469 roots.add_dir(&dir);
470 }
471 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
472 roots.add_file(bundle)?;
473 } else {
474 roots.add_dir(Path::new(dir));
475 }
476 if roots.store.is_empty() {
477 return Err(coded(
478 Code::NoTrustedRoots,
479 "no trusted CA certificates found on this machine",
480 "install the ca-certificates package, set SSL_CERT_FILE, or use \
481 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
482 ));
483 }
484 Ok(roots.store)
485}
486
487struct Roots {
488 store: RootCertStore,
489 seen: HashSet<PathBuf>,
492}
493
494impl Roots {
495 fn add_file(&mut self, path: &Path) -> io::Result<()> {
496 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
497 if !self.seen.insert(real) {
498 return Ok(());
499 }
500 let pem = std::fs::read(path)?;
501 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
502 self.store.add_parsable_certificates(certs);
503 Ok(())
504 }
505
506 fn add_dir(&mut self, dir: &Path) {
507 let Ok(entries) = std::fs::read_dir(dir) else {
508 return;
509 };
510 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
511 paths.sort();
512 for path in paths.iter().filter(|p| p.is_file()) {
513 let _ = self.add_file(path);
515 }
516 }
517}
518
519pub struct TlsStream {
522 tcp: TcpStream,
523 conn: RefCell<Connection>,
524 plain: RefCell<Vec<u8>>,
526 wire: RefCell<Vec<u8>>,
528 eof: Cell<bool>,
530 close_notify: Cell<bool>,
533 sending: Cell<bool>,
536 broken: Cell<bool>,
539 failed: Cell<Option<io::Error>>,
541 waiters: RefCell<Vec<Waker>>,
543}
544
545struct Sending<'a> {
547 stream: &'a TlsStream,
548 complete: bool,
549}
550
551impl Drop for Sending<'_> {
552 fn drop(&mut self) {
553 if !self.complete {
554 self.stream.broken.set(true);
555 }
556 self.stream.sending.set(false);
557 let waiters = mem::take(&mut *self.stream.waiters.borrow_mut());
558 for waker in waiters {
559 waker.wake();
560 }
561 }
562}
563
564impl TlsStream {
565 fn new(tcp: TcpStream, conn: Connection) -> Self {
566 Self {
567 tcp,
568 conn: RefCell::new(conn),
569 plain: RefCell::new(Vec::new()),
570 wire: RefCell::new(Vec::new()),
571 eof: Cell::new(false),
572 close_notify: Cell::new(false),
573 sending: Cell::new(false),
574 broken: Cell::new(false),
575 failed: Cell::new(None),
576 waiters: RefCell::new(Vec::new()),
577 }
578 }
579
580 async fn handshake(self, limit: Duration) -> io::Result<Self> {
582 let handshake = async {
583 while self.conn.borrow().is_handshaking() {
584 self.flush_tls().await?;
585 if !self.conn.borrow().is_handshaking() {
586 break;
587 }
588 if self.eof.get() {
589 return Err(coded(
590 Code::TlsHandshakeEof,
591 "the peer closed the connection during the TLS handshake",
592 "check that the other side speaks TLS on this port, and whether it \
593 wants a client certificate or another server name.",
594 ));
595 }
596 self.pump().await?;
597 }
598 self.flush_tls().await
599 };
600 match timeout(limit, handshake).await {
601 Ok(Ok(())) => Ok(self),
602 Ok(Err(e)) => Err(e),
603 Err(_) => Err(coded(
604 Code::TlsHandshakeTimeout,
605 format!("the TLS handshake did not finish within {limit:?}"),
606 "check that the other side speaks TLS on this port and is not overloaded, or \
607 raise handshake_timeout.",
608 )),
609 }
610 }
611
612 async fn flush_tls(&self) -> io::Result<()> {
614 loop {
615 if !self.conn.borrow().wants_write() {
616 return Ok(());
617 }
618 if self.broken.get() {
619 return Err(coded(
620 Code::TlsBroken,
621 "a TLS write failed or was cancelled; nothing more can be sent",
622 "open a new connection. A write cancelled half-way (a dropped future, a \
623 timeout) leaves a partial record behind, so the stream cannot go on.",
624 ));
625 }
626 if self.sending.get() {
627 poll_fn(|cx| {
630 if !self.sending.get() {
631 return Poll::Ready(());
632 }
633 let mut waiters = self.waiters.borrow_mut();
635 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
636 waiters.push(cx.waker().clone());
637 }
638 Poll::Pending
639 })
640 .await;
641 continue;
642 }
643 let mut wire = mem::take(&mut *self.wire.borrow_mut());
644 {
645 let mut conn = self.conn.borrow_mut();
646 while conn.wants_write() {
647 conn.write_tls(&mut wire)?;
648 }
649 }
650 self.sending.set(true);
651 let mut sending = Sending {
652 stream: self,
653 complete: false,
654 };
655 let (res, mut wire) = self.tcp.write_all(wire).await;
656 res?;
657 sending.complete = true;
658 drop(sending);
659 wire.clear();
660 *self.wire.borrow_mut() = wire;
661 }
662 }
663
664 async fn pump(&self) -> io::Result<()> {
667 let chunk = self.tcp.recv().await?;
669 if chunk.is_empty() {
670 self.eof.set(true);
671 return Ok(());
672 }
673 let result = {
674 let mut conn = self.conn.borrow_mut();
675 let mut plain = self.plain.borrow_mut();
676 let mut input = &chunk[..];
677 let mut result = Ok(());
678 while !input.is_empty() {
679 match conn.read_tls(&mut input) {
682 Ok(0) => {
683 result = Err(coded(
684 Code::TlsProtocol,
685 "rustls accepted no more TLS data",
686 "this is a bug in giong-tls; please report it at \
687 https://github.com/giong-run/Giong/issues.",
688 ));
689 break;
690 }
691 Ok(_) => {}
692 Err(e) => {
693 result = Err(e);
694 break;
695 }
696 }
697 match conn.process_new_packets() {
698 Ok(state) => {
699 let n = state.plaintext_bytes_to_read();
700 if n > 0 {
701 let at = plain.len();
702 plain.resize(at + n, 0);
703 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
704 plain.truncate(at);
705 result = Err(e);
706 break;
707 }
708 }
709 if state.peer_has_closed() {
710 self.close_notify.set(true);
711 self.eof.set(true);
712 break;
713 }
714 }
715 Err(e) => {
716 result = Err(tls_error(e));
717 break;
718 }
719 }
720 }
721 result
722 };
723 drop(chunk);
724 if self.broken.get() {
728 return result;
729 }
730 let flushed = self.flush_tls().await;
731 result.and(flushed)
732 }
733
734 pub async fn recv(&self) -> io::Result<Vec<u8>> {
750 loop {
751 {
752 let mut plain = self.plain.borrow_mut();
753 if !plain.is_empty() {
754 return Ok(mem::take(&mut *plain));
755 }
756 }
757 if let Some(e) = self.failed.take() {
758 return Err(e);
759 }
760 if self.eof.get() {
761 return Ok(Vec::new());
762 }
763 if let Err(e) = self.pump().await {
764 if self.plain.borrow().is_empty() {
766 return Err(e);
767 }
768 self.failed.set(Some(e));
769 }
770 }
771 }
772
773 pub async fn write_all(&self, buf: Vec<u8>) -> (io::Result<()>, Vec<u8>) {
780 let mut sent = 0;
781 while sent < buf.len() {
782 let accepted = self.conn.borrow_mut().writer().write(&buf[sent..]);
784 match accepted {
785 Ok(n) => sent += n,
786 Err(e) => return (Err(e), buf),
787 }
788 if let Err(e) = self.flush_tls().await {
789 return (Err(e), buf);
790 }
791 }
792 (Ok(()), buf)
793 }
794
795 pub async fn shutdown(&self) -> io::Result<()> {
797 self.conn.borrow_mut().send_close_notify();
798 self.flush_tls().await?;
799 self.tcp.shutdown(Shutdown::Write)
800 }
801
802 pub fn received_close_notify(&self) -> bool {
808 self.close_notify.get()
809 }
810
811 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
813 self.conn.borrow().alpn_protocol().map(<[u8]>::to_vec)
814 }
815
816 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
821 self.conn.borrow().peer_certificates().map(<[_]>::to_vec)
822 }
823
824 pub fn resumed(&self) -> bool {
827 self.conn.borrow().handshake_kind() == Some(rustls::HandshakeKind::Resumed)
828 }
829
830 pub fn tcp(&self) -> &TcpStream {
832 &self.tcp
833 }
834}
835
836impl std::fmt::Debug for TlsStream {
837 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
838 f.debug_struct("TlsStream")
839 .field("tcp", &self.tcp)
840 .finish_non_exhaustive()
841 }
842}
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847
848 fn ca_pem(name: &str) -> String {
849 let key = rcgen::KeyPair::generate().unwrap();
850 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
851 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
852 params
853 .distinguished_name
854 .push(rcgen::DnType::CommonName, name);
855 params.self_signed(&key).unwrap().pem()
856 }
857
858 fn scratch(name: &str) -> PathBuf {
860 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
861 let _ = std::fs::remove_dir_all(&dir);
862 std::fs::create_dir_all(&dir).unwrap();
863 dir
864 }
865
866 fn os(path: &Path) -> &OsStr {
867 path.as_os_str()
868 }
869
870 #[test]
871 fn server_names_are_dns_names_or_ip_addresses() {
872 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
873 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
874 assert!(dns("example.com"));
875 assert!(dns("db.prod.svc.cluster.local"));
876 assert!(ip("10.0.0.1"));
877 assert!(ip("::1"));
878 assert!(ip("[::1]"));
879 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
880 let err = parse_server_name(bad).unwrap_err();
881 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
882 }
883 }
884
885 #[test]
886 fn the_first_bundle_that_exists_is_read() {
887 let dir = scratch("bundle");
888 let bundle = dir.join("bundle.pem");
889 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
890 std::fs::write(&bundle, two).unwrap();
891 let missing = dir.join("missing.pem");
892 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
893 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
894 assert_eq!(roots.len(), 2);
895 std::fs::remove_dir_all(dir).unwrap();
896 }
897
898 #[test]
899 fn ssl_cert_file_and_dir_replace_the_system_locations() {
900 let dir = scratch("env");
901 let file = dir.join("file.pem");
902 std::fs::write(&file, ca_pem("from file")).unwrap();
903 let certs = dir.join("certs");
904 std::fs::create_dir(&certs).unwrap();
905 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
906 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
907 std::fs::write(certs.join("README"), "not a certificate").unwrap();
908 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
910 let system = dir.join("system.pem");
911 std::fs::write(&system, ca_pem("system")).unwrap();
912 let bundles = [system.to_str().unwrap()];
913
914 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
915 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
916 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
917 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
918 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
919 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
920 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
921
922 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
923 assert_eq!(err.kind(), io::ErrorKind::NotFound);
924 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
925 std::fs::remove_dir_all(dir).unwrap();
926 }
927
928 #[test]
929 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
930 let dir = scratch("dir");
931 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
932 let roots = load_roots(
933 None,
934 None,
935 &["/nonexistent/bundle.crt"],
936 dir.to_str().unwrap(),
937 );
938 assert_eq!(roots.unwrap().len(), 1);
939
940 let empty = scratch("empty");
941 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
942 assert_eq!(err.kind(), io::ErrorKind::NotFound);
943 assert!(err.to_string().contains("webpki-roots"), "{err}");
944 std::fs::remove_dir_all(dir).unwrap();
945 std::fs::remove_dir_all(empty).unwrap();
946 }
947
948 #[test]
949 fn this_machines_roots_load() {
950 TlsConnector::with_system_roots().unwrap();
952 }
953
954 #[cfg(feature = "webpki-roots")]
955 #[test]
956 fn mozillas_roots_are_compiled_in() {
957 TlsConnector::with_webpki_roots();
958 }
959}