Skip to main content

arks_server/
tls.rs

1//! Product in-process TLS terminate helpers (operator-supplied PEM).
2//!
3//! Used by `arks serve` HTTP (and exported for forge cohost). Design bar:
4//! [[sot:root/arks-claimed-residual-gates]] B9. Ops reverse-proxy remains valid
5//! but does not by itself satisfy B9. Never spawns openssl/git/gh.
6
7use rustls::ServerConfig;
8use rustls::pki_types::{CertificateDer, PrivateKeyDer};
9use std::fs::File;
10use std::io::BufReader;
11use std::path::Path;
12use std::sync::Arc;
13
14/// Load a rustls `ServerConfig` from operator-supplied PEM cert + key paths.
15pub fn load_server_config(
16    cert_path: impl AsRef<Path>,
17    key_path: impl AsRef<Path>,
18) -> Result<Arc<ServerConfig>, String> {
19    let _ = rustls::crypto::ring::default_provider().install_default();
20    let certs = load_certs(cert_path.as_ref())?;
21    let key = load_private_key(key_path.as_ref())?;
22    let mut config = ServerConfig::builder()
23        .with_no_client_auth()
24        .with_single_cert(certs, key)
25        .map_err(|e| format!("tls ServerConfig: {e}"))?;
26    // Prefer HTTP/1.1 ALPN so stock curl/git/ureq negotiate cleanly.
27    config.alpn_protocols = vec![b"http/1.1".to_vec()];
28    Ok(Arc::new(config))
29}
30
31fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>, String> {
32    let f = File::open(path).map_err(|e| format!("tls cert open {}: {e}", path.display()))?;
33    let mut reader = BufReader::new(f);
34    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut reader)
35        .collect::<Result<Vec<_>, _>>()
36        .map_err(|e| format!("tls cert parse {}: {e}", path.display()))?;
37    if certs.is_empty() {
38        return Err(format!("tls cert PEM empty: {}", path.display()));
39    }
40    Ok(certs)
41}
42
43fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>, String> {
44    let f = File::open(path).map_err(|e| format!("tls key open {}: {e}", path.display()))?;
45    let mut reader = BufReader::new(f);
46    rustls_pemfile::private_key(&mut reader)
47        .map_err(|e| format!("tls key parse {}: {e}", path.display()))?
48        .ok_or_else(|| format!("tls key PEM missing: {}", path.display()))
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use std::path::PathBuf;
55
56    /// Write a fresh self-signed `localhost` certificate + key (test-only; no tracked PEMs).
57    fn temp_pems(dir: &std::path::Path) -> (PathBuf, PathBuf) {
58        let ck = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
59            .expect("rcgen self-signed");
60        let crt = dir.join("localhost.crt.pem");
61        let key = dir.join("localhost.key.pem");
62        std::fs::write(&crt, ck.cert.pem()).unwrap();
63        std::fs::write(&key, ck.key_pair.serialize_pem()).unwrap();
64        (crt, key)
65    }
66
67    #[test]
68    fn load_server_config_rejects_missing() {
69        let err = load_server_config("/no/such/cert.pem", "/no/such/key.pem").unwrap_err();
70        assert!(err.contains("tls cert open"), "{err}");
71    }
72
73    #[test]
74    fn load_server_config_from_testdata_pems() {
75        let dir = tempfile::tempdir().unwrap();
76        let (crt, key) = temp_pems(dir.path());
77        let cfg = load_server_config(&crt, &key).expect("load generated PEMs");
78        assert_eq!(cfg.alpn_protocols, vec![b"http/1.1".to_vec()]);
79    }
80}