Skip to main content

reddb_server/wire/
tls.rs

1/// Wire Protocol TLS support
2///
3/// Provides:
4/// - Auto-generated self-signed certificates for dev mode
5/// - TLS acceptor configuration from cert/key files
6/// - TLS-wrapped TCP listener
7use std::fs;
8use std::io::{self, Write};
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use rustls::ServerConfig;
13use tokio_rustls::TlsAcceptor;
14
15/// TLS configuration for the wire protocol.
16#[derive(Debug, Clone)]
17pub struct WireTlsConfig {
18    /// Path to PEM certificate file
19    pub cert_path: PathBuf,
20    /// Path to PEM private key file
21    pub key_path: PathBuf,
22}
23
24/// Generate a self-signed certificate for development.
25/// Returns (cert_pem, key_pem) as strings.
26///
27/// The wire cert carries CN `"RedDB Wire {hostname}"` **and**
28/// `OrganizationName "RedDB"`. The HTTP edge shares this generator but
29/// passes `org = None` (see [`generate_self_signed_dev_cert`]) so its
30/// cert keeps no organization.
31pub fn generate_self_signed_cert(
32    hostname: &str,
33) -> Result<(String, String), Box<dyn std::error::Error>> {
34    generate_self_signed_dev_cert(hostname, "RedDB Wire", Some("RedDB"))
35}
36
37/// Shared self-signed dev-cert generator for the wire and HTTP edges.
38///
39/// Behaviour-preserving parameterization of two formerly near-identical
40/// rcgen blocks (issue #1055): the CN is `"{cn_label} {hostname}"`, and
41/// `org` — when `Some` — sets `OrganizationName`. The wire edge passes
42/// `Some("RedDB")`; the HTTP edge passes `None` so its cert keeps CN
43/// `"RedDB HTTP …"` with **no** organization (do NOT silently add
44/// `O=RedDB` to the HTTP cert). The SAN block (`hostname`, `localhost`
45/// when distinct, and `127.0.0.1`) is identical for both.
46pub(crate) fn generate_self_signed_dev_cert(
47    hostname: &str,
48    cn_label: &str,
49    org: Option<&str>,
50) -> Result<(String, String), Box<dyn std::error::Error>> {
51    let key_pair = rcgen::KeyPair::generate()?;
52    let cert_pem = self_sign_dev_cert(hostname, cn_label, org, &key_pair)?;
53    Ok((cert_pem, key_pair.serialize_pem()))
54}
55
56fn self_sign_dev_cert(
57    hostname: &str,
58    cn_label: &str,
59    org: Option<&str>,
60    key_pair: &rcgen::KeyPair,
61) -> Result<String, Box<dyn std::error::Error>> {
62    let mut params = rcgen::CertificateParams::new(vec![hostname.to_string()])?;
63    params.distinguished_name.push(
64        rcgen::DnType::CommonName,
65        rcgen::DnValue::Utf8String(format!("{cn_label} {hostname}")),
66    );
67    if let Some(org) = org {
68        params.distinguished_name.push(
69            rcgen::DnType::OrganizationName,
70            rcgen::DnValue::Utf8String(org.to_string()),
71        );
72    }
73
74    // Add localhost + IP SANs for dev
75    params
76        .subject_alt_names
77        .push(rcgen::SanType::DnsName(hostname.try_into()?));
78    if hostname != "localhost" {
79        params
80            .subject_alt_names
81            .push(rcgen::SanType::DnsName("localhost".try_into()?));
82    }
83    // 127.0.0.1
84    params
85        .subject_alt_names
86        .push(rcgen::SanType::IpAddress(std::net::IpAddr::V4(
87            std::net::Ipv4Addr::LOCALHOST,
88        )));
89
90    Ok(params.self_signed(key_pair)?.pem())
91}
92
93/// Ensure the development pair exists. Returns true when a certificate was issued.
94pub(crate) fn ensure_dev_tls_cert_pair(
95    cert_path: &Path,
96    key_path: &Path,
97    cn_label: &str,
98    org: Option<&str>,
99) -> Result<bool, Box<dyn std::error::Error>> {
100    match key_path.symlink_metadata() {
101        Ok(metadata) => {
102            if !metadata.is_file() {
103                return Err(
104                    format!("TLS key {} must be a regular file", key_path.display()).into(),
105                );
106            }
107            #[cfg(unix)]
108            {
109                use std::os::unix::fs::PermissionsExt;
110
111                if metadata.permissions().mode() & 0o077 != 0 {
112                    return Err(format!(
113                        "TLS key {} is accessible to other users; replace the development certificate and key",
114                        key_path.display()
115                    )
116                    .into());
117                }
118            }
119            if cert_path.try_exists()? {
120                return Ok(false);
121            }
122            // Recover a missing certificate using the existing private key.
123            let key_pair = rcgen::KeyPair::from_pem(&fs::read_to_string(key_path)?)?;
124            let cert_pem = self_sign_dev_cert("localhost", cn_label, org, &key_pair)?;
125            fs::write(cert_path, cert_pem)?;
126        }
127        Err(err) if err.kind() == io::ErrorKind::NotFound => {
128            let (cert_pem, key_pem) = generate_self_signed_dev_cert("localhost", cn_label, org)?;
129            if let Some(dir) = key_path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
130                fs::create_dir_all(dir)?;
131            }
132            let mut options = fs::OpenOptions::new();
133            options.write(true).create_new(true);
134            #[cfg(unix)]
135            {
136                use std::os::unix::fs::OpenOptionsExt;
137
138                options.mode(0o600);
139            }
140            let mut key_file = options.open(key_path)?;
141            let result = key_file.write_all(key_pem.as_bytes());
142            drop(key_file);
143            if let Err(err) = result.and_then(|()| fs::write(cert_path, cert_pem)) {
144                // This call owns the freshly created key. Leave retries free to issue a new pair.
145                let _ = fs::remove_file(key_path);
146                return Err(err.into());
147            }
148        }
149        Err(err) => return Err(err.into()),
150    }
151    Ok(true)
152}
153
154/// Generate self-signed cert and write to files in the given directory.
155/// Returns the WireTlsConfig pointing to the written files.
156///
157/// Gated by `RED_WIRE_TLS_DEV=1`; refuses to auto-generate in any other
158/// context (refuses prod by default). This mirrors the HTTP edge's
159/// `RED_HTTP_TLS_DEV` opt-in ([`crate::server::tls::auto_generate_dev_cert`])
160/// — the two edges are independent, so enabling dev certs on one does not
161/// enable them on the other.
162pub fn auto_generate_cert(dir: &Path) -> Result<WireTlsConfig, Box<dyn std::error::Error>> {
163    let dev_flag = std::env::var("RED_WIRE_TLS_DEV").unwrap_or_default();
164    if !matches!(dev_flag.as_str(), "1" | "true" | "yes" | "on") {
165        return Err(
166            "refusing to auto-generate wire TLS cert: set RED_WIRE_TLS_DEV=1 to opt into self-signed dev certs"
167                .into(),
168        );
169    }
170
171    let cert_path = dir.join("wire-tls-cert.pem");
172    let key_path = dir.join("wire-tls-key.pem");
173
174    if ensure_dev_tls_cert_pair(&cert_path, &key_path, "RedDB Wire", Some("RedDB"))? {
175        tracing::info!(
176            cert = %cert_path.display(),
177            key = %key_path.display(),
178            "wire TLS: wrote self-signed cert"
179        );
180    } else {
181        tracing::info!(cert = %cert_path.display(), "wire TLS: reusing existing cert");
182    }
183
184    Ok(WireTlsConfig {
185        cert_path,
186        key_path,
187    })
188}
189
190/// Build a TLS acceptor from cert and key PEM files.
191pub fn build_tls_acceptor(
192    config: &WireTlsConfig,
193) -> Result<TlsAcceptor, Box<dyn std::error::Error>> {
194    // Ensure the ring crypto provider is installed
195    let _ = rustls::crypto::ring::default_provider().install_default();
196
197    let cert_pem = std::fs::read(&config.cert_path)?;
198    let key_pem = std::fs::read(&config.key_path)?;
199
200    let certs = rustls_pemfile::certs(&mut io::BufReader::new(&cert_pem[..]))
201        .collect::<Result<Vec<_>, _>>()?;
202    let key = rustls_pemfile::private_key(&mut io::BufReader::new(&key_pem[..]))?
203        .ok_or("no private key found in PEM file")?;
204
205    let server_config = ServerConfig::builder()
206        .with_no_client_auth()
207        .with_single_cert(certs, key)?;
208
209    Ok(TlsAcceptor::from(Arc::new(server_config)))
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn dev_tls_pair_recovers_a_missing_certificate_without_replacing_key() {
218        let directory = tempfile::tempdir().expect("TLS directory");
219        let cert = directory.path().join("cert.pem");
220        let key = directory.path().join("key.pem");
221        let ensure = || ensure_dev_tls_cert_pair(&cert, &key, "RedDB Wire", Some("RedDB"));
222
223        assert!(ensure().expect("generate pair"));
224        let original_key = fs::read(&key).expect("read key");
225        let original_cert = fs::read(&cert).expect("read certificate");
226        assert!(!ensure().expect("reuse pair"));
227        assert_eq!(
228            fs::read(&cert).expect("read reused certificate"),
229            original_cert
230        );
231        fs::remove_file(&cert).expect("remove certificate");
232
233        assert!(ensure().expect("recover missing certificate"));
234        assert_eq!(fs::read(&key).expect("read reused key"), original_key);
235        build_tls_acceptor(&WireTlsConfig {
236            cert_path: cert,
237            key_path: key,
238        })
239        .expect("recovered certificate matches the private key");
240    }
241
242    #[cfg(unix)]
243    #[test]
244    fn dev_tls_key_is_private_and_reuse_rejects_broad_permissions() {
245        use std::os::unix::fs::PermissionsExt;
246
247        let directory = tempfile::tempdir().expect("TLS directory");
248        let cert = directory.path().join("cert.pem");
249        let key = directory.path().join("key.pem");
250        let ensure = || ensure_dev_tls_cert_pair(&cert, &key, "RedDB Wire", Some("RedDB"));
251
252        assert!(ensure().expect("generate pair"));
253        assert_eq!(
254            fs::metadata(&key).expect("key mode").permissions().mode() & 0o077,
255            0
256        );
257
258        fs::set_permissions(&key, fs::Permissions::from_mode(0o644)).expect("set key mode");
259        let err = ensure().expect_err("reject a group- or world-readable key");
260        assert!(err.to_string().contains("accessible to other users"));
261    }
262
263    /// Parse the subject CN + Organization out of a self-signed PEM cert,
264    /// so the wire-vs-HTTP DN difference is pinned end-to-end (issue #1055).
265    fn subject_cn_and_orgs(cert_pem: &str) -> (Vec<String>, Vec<String>) {
266        let der = rustls_pemfile::certs(&mut io::BufReader::new(cert_pem.as_bytes()))
267            .next()
268            .expect("one certificate in PEM")
269            .expect("valid certificate PEM");
270        let (_, parsed) =
271            x509_parser::parse_x509_certificate(der.as_ref()).expect("parse generated X.509");
272        let subject = parsed.subject();
273        let cns = subject
274            .iter_common_name()
275            .filter_map(|cn| cn.as_str().ok().map(str::to_string))
276            .collect();
277        let orgs = subject
278            .iter_organization()
279            .filter_map(|o| o.as_str().ok().map(str::to_string))
280            .collect();
281        (cns, orgs)
282    }
283
284    #[test]
285    fn wire_cert_keeps_wire_cn_and_reddb_org() {
286        let (cert_pem, key_pem) =
287            generate_self_signed_cert("localhost").expect("generate wire cert");
288        assert!(key_pem.contains("PRIVATE KEY"), "key PEM emitted");
289        let (cns, orgs) = subject_cn_and_orgs(&cert_pem);
290        assert_eq!(cns, vec!["RedDB Wire localhost".to_string()]);
291        assert_eq!(orgs, vec!["RedDB".to_string()]);
292    }
293
294    #[test]
295    fn http_cert_keeps_http_cn_and_no_org() {
296        // The non-obvious diff (issue #1055): the HTTP cert must keep CN
297        // "RedDB HTTP …" and carry NO organization. The shared generator
298        // passes org = None so we never silently add O=RedDB to it.
299        let (cert_pem, _key) = generate_self_signed_dev_cert("localhost", "RedDB HTTP", None)
300            .expect("generate http cert");
301        let (cns, orgs) = subject_cn_and_orgs(&cert_pem);
302        assert_eq!(cns, vec!["RedDB HTTP localhost".to_string()]);
303        assert!(orgs.is_empty(), "HTTP cert must not carry an Organization");
304    }
305
306    /// Tests that mutate the process-global `RED_WIRE_TLS_DEV` env var must
307    /// serialize to avoid trampling each other under cargo's default
308    /// parallel test runner (mirrors the HTTP twin's `env_lock`).
309    fn env_lock() -> &'static std::sync::Mutex<()> {
310        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
311        LOCK.get_or_init(|| std::sync::Mutex::new(()))
312    }
313
314    #[test]
315    fn auto_generate_refuses_without_dev_flag() {
316        let _g = env_lock().lock();
317        let dir = std::env::temp_dir().join(format!(
318            "reddb-wire-tls-test-{}-{}",
319            std::process::id(),
320            std::time::SystemTime::now()
321                .duration_since(std::time::UNIX_EPOCH)
322                .unwrap()
323                .as_nanos()
324        ));
325        // Make sure flag is unset.
326        unsafe {
327            std::env::remove_var("RED_WIRE_TLS_DEV");
328        }
329        let err = auto_generate_cert(&dir).unwrap_err();
330        assert!(err.to_string().contains("RED_WIRE_TLS_DEV"));
331    }
332
333    #[test]
334    fn auto_generate_with_dev_flag_writes_cert() {
335        let _g = env_lock().lock();
336        let dir = std::env::temp_dir().join(format!(
337            "reddb-wire-tls-dev-{}-{}",
338            std::process::id(),
339            std::time::SystemTime::now()
340                .duration_since(std::time::UNIX_EPOCH)
341                .unwrap()
342                .as_nanos()
343        ));
344        unsafe {
345            std::env::set_var("RED_WIRE_TLS_DEV", "1");
346        }
347        let cfg = auto_generate_cert(&dir).expect("should generate");
348        assert!(cfg.cert_path.exists());
349        assert!(cfg.key_path.exists());
350        unsafe {
351            std::env::remove_var("RED_WIRE_TLS_DEV");
352        }
353        let _ = std::fs::remove_dir_all(&dir);
354    }
355}