bbox_core/
tls.rs

1use crate::config::{app_dir, config_error_exit, error_exit};
2use rustls::{Certificate, PrivateKey, ServerConfig};
3use rustls_pemfile::{certs, pkcs8_private_keys};
4use std::{fs::File, io::BufReader};
5
6// For self-signed certificates we recommend to use [`mkcert`].
7// To use local CA, you should run:
8//
9// ```sh
10// mkcert -install
11// ```
12//
13// If you want to generate your own cert/private key file, then run:
14//
15// ```sh
16// mkcert localhost 127.0.0.1
17// ```
18//
19// [`mkcert`]: https://github.com/FiloSottile/mkcert
20
21pub fn load_rustls_config(tls_cert: &str, tls_key: &str) -> rustls::ServerConfig {
22    // init server config builder with safe defaults
23    let config = ServerConfig::builder()
24        .with_safe_defaults()
25        .with_no_client_auth();
26
27    // load TLS key/cert files
28    let cert_file = &mut BufReader::new(File::open(app_dir(tls_cert)).unwrap_or_else(error_exit));
29    let key_file = &mut BufReader::new(File::open(app_dir(tls_key)).unwrap_or_else(error_exit));
30
31    // convert files to key/cert objects
32    let cert_chain = certs(cert_file)
33        .unwrap_or_else(error_exit)
34        .into_iter()
35        .map(Certificate)
36        .collect();
37    let mut keys: Vec<PrivateKey> = pkcs8_private_keys(key_file)
38        .unwrap_or_else(error_exit)
39        .into_iter()
40        .map(PrivateKey)
41        .collect();
42
43    // exit if no keys could be parsed
44    if keys.is_empty() {
45        config_error_exit("Could not locate PKCS 8 private keys.");
46    }
47
48    config
49        .with_single_cert(cert_chain, keys.remove(0))
50        .unwrap_or_else(error_exit)
51}