### Full TLS Client Example with Native Certs Source: https://context7.com/rustls/rustls-native-certs/llms.txt Demonstrates building a `rustls::ClientConfig` using native root certificates and performing a raw TLS handshake over a `TcpStream` to connect to google.com. It shows how to inspect the negotiated cipher suite and read the HTTP response. ```rust use std::io::{stdout, Read, Write}; use std::net::TcpStream; use std::sync::Arc; fn main() { // 1. Build a RootCertStore from the platform's native certificate store let mut roots = rustls::RootCertStore::empty(); for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs") { roots.add(cert).unwrap(); } // 2. Build a rustls ClientConfig using the native root certs let config = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); // 3. Open a TLS connection let mut conn = rustls::ClientConnection::new( Arc::new(config), "google.com".try_into().unwrap(), ) .unwrap(); let mut sock = TcpStream::connect("google.com:443").expect("cannot connect"); let mut tls = rustls::Stream::new(&mut conn, &mut sock); // 4. Send an HTTP/1.1 request tls.write_all( b"GET / HTTP/1.1\r\nHost: google.com\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n", ) .expect("write failed"); // 5. Inspect the negotiated cipher suite let suite = tls.conn.negotiated_cipher_suite().expect("tls handshake failed"); eprintln!("Negotiated ciphersuite: {:?}", suite.suite()); // stderr: Negotiated ciphersuite: TLS13_AES_256_GCM_SHA384 // 6. Read the response let mut plaintext = Vec::new(); tls.read_to_end(&mut plaintext).unwrap(); stdout().write_all(&plaintext).unwrap(); // stdout: HTTP/1.1 301 Moved Permanently ... } ``` -------------------------------- ### Tagging a Release Version Source: https://github.com/rustls/rustls-native-certs/blob/main/RELEASING.md Use this command to tag the specific version being released. The tag format includes a 'v/' prefix followed by the version number. ```bash git tag -m '0.20.0' v/0.20.0 ``` -------------------------------- ### Publishing the Release to Crates.io Source: https://github.com/rustls/rustls-native-certs/blob/main/RELEASING.md Execute this command to publish the final release of the crate to the crates.io registry. ```bash cargo publish ``` -------------------------------- ### load_native_certs Source: https://github.com/rustls/rustls-native-certs/blob/main/README.md Loads the platform's native certificate store. This function can be expensive and should be called sparingly. It checks the `SSL_CERT_FILE` environment variable first, then uses platform-specific methods (Windows system store, macOS keychain, Linux CA bundle) if the environment variable is not set. ```APIDOC ## load_native_certs ### Description Loads the platform's native certificate store. This function can be expensive and should be called sparingly. It checks the `SSL_CERT_FILE` environment variable first, then uses platform-specific methods (Windows system store, macOS keychain, Linux CA bundle) if the environment variable is not set. ### Method ```rust pub fn load_native_certs() -> CertificateResult ``` ### Returns - `CertificateResult`: Contains `certs: Vec>` loaded with a snapshot of the root certificates found on this platform along with any platform-specific errors. ``` -------------------------------- ### Load Certificates from Platform Native Store Source: https://context7.com/rustls/rustls-native-certs/llms.txt Use this function to load trusted root certificates from the platform's native store. It checks environment variables first and then delegates to the OS-specific backend. This call can be expensive and should be used sparingly. ```rust use rustls::RootCertStore; use rustls_native_certs::load_native_certs; fn build_tls_root_store() -> RootCertStore { let mut roots = RootCertStore::empty(); let result = load_native_certs(); // Report any non-fatal errors (e.g., a single malformed cert) for err in &result.errors { eprintln!("warning: failed to load certificate: {err}"); } // Add all successfully loaded certificates for cert in result.certs { if let Err(e) = roots.add(cert) { eprintln!("warning: could not add certificate to store: {e}"); } } roots } fn main() { let roots = build_tls_root_store(); println!("Loaded {} root certificates", roots.len()); } // Output: Loaded 128 root certificates (count varies by platform) ``` -------------------------------- ### Override Native Certs with Environment Variables Source: https://context7.com/rustls/rustls-native-certs/llms.txt Use `SSL_CERT_FILE` or `SSL_CERT_DIR` environment variables to specify custom certificate paths. When these are set, `load_native_certs` reads only from the specified paths, ignoring the platform's native store. ```rust use rustls_native_certs::load_native_certs; fn main() { // SSL_CERT_FILE=/custom/certs/bundle.pem cargo run // SSL_CERT_DIR=/custom/certs/dir:/backup/certs cargo run // // When SSL_CERT_FILE or SSL_CERT_DIR are set, load_native_certs() // reads from those paths instead of the platform store. std::env::set_var("SSL_CERT_FILE", "/custom/bundle.pem"); let result = load_native_certs(); // Reads only from /custom/bundle.pem — platform store is ignored for err in &result.errors { eprintln!("cert load error: {err}"); } println!("Certs from custom bundle: {}", result.certs.len()); } ``` -------------------------------- ### load_certs_from_paths() Source: https://context7.com/rustls/rustls-native-certs/llms.txt A lower-level function to load PEM certificates from specified file or directory paths. It supports loading from a single PEM file, a directory of certificates (OpenSSL CAdir format), or both. Duplicates between sources are automatically removed. This function is ideal for testing or when explicit control over certificate paths is needed. ```APIDOC ## `load_certs_from_paths()` — Load certificates from explicit file and/or directory paths A lower-level public function that loads PEM certificates from an explicit file path and/or a single directory (OpenSSL-style CAdir). If both arguments are `None`, an empty `CertificateResult` is returned. Certificates loaded from both sources are deduplicated before being returned. This is useful for testing or when the caller manages certificate paths directly. ```rust use std::path::Path; use rustls_native_certs::load_certs_from_paths; fn load_custom_bundle() { // Load from a specific PEM bundle file only let result = load_certs_from_paths( Some(Path::new("/etc/ssl/certs/ca-certificates.crt")), None, ); println!("Loaded {} certs, {} errors", result.certs.len(), result.errors.len()); // Load from a CAdir directory only (e.g., created by openssl c_rehash) let result = load_certs_from_paths( None, Some(Path::new("/etc/ssl/certs")), ); println!("Loaded {} certs from directory", result.certs.len()); // Load from both; duplicates are automatically removed let result = load_certs_from_paths( Some(Path::new("/etc/ssl/certs/ca-certificates.crt")), Some(Path::new("/etc/ssl/certs")), ); for err in &result.errors { eprintln!("error: {err}"); } println!("Unique certs after dedup: {}", result.certs.len()); } ``` ``` -------------------------------- ### Performing a Dry Run of Cargo Publish Source: https://github.com/rustls/rustls-native-certs/blob/main/RELEASING.md Before publishing, run a dry run to check for any potential issues without actually uploading the package to crates.io. ```bash cargo publish --dry-run ``` -------------------------------- ### Pushing Git Tags Source: https://github.com/rustls/rustls-native-certs/blob/main/RELEASING.md After tagging the release locally, push all tags to the remote repository to make them available. ```bash git push --tags ``` -------------------------------- ### Load Native Certificates in Rust Source: https://github.com/rustls/rustls-native-certs/blob/main/README.md This function loads root certificates from the platform's native certificate store. It can be expensive due to disk I/O and parsing, so call it sparingly. It first checks the SSL_CERT_FILE environment variable. ```rust pub fn load_native_certs() -> CertificateResult ``` -------------------------------- ### Load Certificates from Explicit Paths Source: https://context7.com/rustls/rustls-native-certs/llms.txt This lower-level function loads PEM certificates from a specified file path and/or a directory. It handles deduplication if certificates are loaded from both sources. Use this when you need to manage certificate paths directly or for testing purposes. ```rust use std::path::Path; use rustls_native_certs::load_certs_from_paths; fn load_custom_bundle() { // Load from a specific PEM bundle file only let result = load_certs_from_paths( Some(Path::new("/etc/ssl/certs/ca-certificates.crt")), None, ); println!("Loaded {} certs, {} errors", result.certs.len(), result.errors.len()); // Load from a CAdir directory only (e.g., created by openssl c_rehash) let result = load_certs_from_paths( None, Some(Path::new("/etc/ssl/certs")), ); println!("Loaded {} certs from directory", result.certs.len()); // Load from both; duplicates are automatically removed let result = load_certs_from_paths( Some(Path::new("/etc/ssl/certs/ca-certificates.crt")), Some(Path::new("/etc/ssl/certs")), ); for err in &result.errors { eprintln!("error: {err}"); } println!("Unique certs after dedup: {}", result.certs.len()); } ``` -------------------------------- ### Inspect Certificate Load Errors in Rust Source: https://context7.com/rustls/rustls-native-certs/llms.txt Iterate through errors from `load_native_certs` to diagnose failures. Handles IO, OS, and PEM parsing errors with specific details. ```rust use rustls_native_certs::{load_native_certs, ErrorKind}; fn main() { let result = load_native_certs(); for err in result.errors { eprint!("context: {} — ", err.context); match &err.kind { ErrorKind::Io { inner, path } => { eprintln!("IO error at '{}': {inner}", path.display()); // e.g.: IO error at '/etc/ssl/certs/bad.pem': permission denied } ErrorKind::Os(os_err) => { eprintln!("OS / keychain error: {os_err}"); // e.g.: OS / keychain error: The specified item could not be found. } ErrorKind::Pem(pem_err) => { eprintln!("PEM parse error: {pem_err}"); // e.g.: PEM parse error: unexpected end of file } } } println!("Valid certs loaded: {}", result.certs.len()); } ``` -------------------------------- ### Unwrap Certificates or Panic Source: https://context7.com/rustls/rustls-native-certs/llms.txt Similar to `expect()`, this method unwraps the certificates or panics with a fixed message. It is useful in tests or quick scripts where a custom panic message is not necessary. ```rust use rustls_native_certs::load_native_certs; #[cfg(test)] mod tests { use super::*; #[test] fn platform_certs_load_successfully() { let certs = load_native_certs().unwrap(); assert!(!certs.is_empty(), "expected at least one root certificate"); } } ``` -------------------------------- ### Inspect Loaded Trust Anchors Source: https://context7.com/rustls/rustls-native-certs/llms.txt Iterates through loaded native certificates, parses them using `x509-parser`, and prints the Distinguished Name subject of each. This is useful for auditing which Certificate Authorities (CAs) are trusted on the current platform. ```rust use std::error::Error; use x509_parser::prelude::*; fn main() -> Result<(), Box> { let result = rustls_native_certs::load_native_certs(); for err in &result.errors { eprintln!("warning: {err}"); } for cert in result.certs { match parse_x509_certificate(cert.as_ref()) { Ok((_, parsed)) => println!("{}", parsed.tbs_certificate.subject), Err(e) => eprintln!("error parsing certificate: {e}"), } } // Output example: // CN=ISRG Root X1, O=Internet Security Research Group, C=US // CN=DigiCert Global Root CA, OU=www.digicert.com, O=DigiCert Inc, C=US // CN=GlobalSign Root CA, OU=Root CA, O=GlobalSign nv-sa, C=BE Ok(()) } ``` -------------------------------- ### Unwrap Certificates or Panic with a Message Source: https://context7.com/rustls/rustls-native-certs/llms.txt This convenience method on `CertificateResult` unwraps the inner `Vec>` if no errors occurred. It panics with a provided message if any errors were encountered during certificate loading, similar to `Result::expect`. ```rust use rustls_native_certs::load_native_certs; fn main() { // Panics with "could not load platform certs: [...]" if any error occurred let certs = load_native_certs().expect("could not load platform certs"); println!("Loaded {} certificates", certs.len()); } ``` -------------------------------- ### CertificateResult::unwrap() Source: https://context7.com/rustls/rustls-native-certs/llms.txt Similar to `expect()`, this method unwraps the `Vec>` from `CertificateResult`. If errors occurred, it panics with a fixed, default message. This is particularly useful in test scenarios or simple scripts where a custom panic message is not required. ```APIDOC ## `CertificateResult::unwrap()` — Unwrap certificates or panic Like `expect()` but uses a fixed panic message. Useful in tests or quick scripts where a custom message is not needed. ```rust use rustls_native_certs::load_native_certs; #[cfg(test)] mod tests { use super::*; #[test] fn platform_certs_load_successfully() { let certs = load_native_certs().unwrap(); assert!(!certs.is_empty(), "expected at least one root certificate"); } } ``` ``` -------------------------------- ### CertificateResult::expect() Source: https://context7.com/rustls/rustls-native-certs/llms.txt A convenience method on `CertificateResult` that unwraps the `Vec>` if no errors occurred during certificate loading. If any errors are present, it panics with a provided custom message, similar to `Result::expect`. ```APIDOC ## `CertificateResult::expect()` — Unwrap certificates or panic with a message A convenience method on `CertificateResult` that returns the inner `Vec>` if no errors occurred, and panics with the provided message otherwise. Mirrors the ergonomics of `Option::expect` / `Result::expect`. ```rust use rustls_native_certs::load_native_certs; fn main() { // Panics with "could not load platform certs: [...]" if any error occurred let certs = load_native_certs().expect("could not load platform certs"); println!("Loaded {} certificates", certs.len()); } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.