reddb-io-server 1.44.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
/// Wire Protocol TLS support
///
/// Provides:
/// - Auto-generated self-signed certificates for dev mode
/// - TLS acceptor configuration from cert/key files
/// - TLS-wrapped TCP listener
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustls::ServerConfig;
use tokio_rustls::TlsAcceptor;

/// TLS configuration for the wire protocol.
#[derive(Debug, Clone)]
pub struct WireTlsConfig {
    /// Path to PEM certificate file
    pub cert_path: PathBuf,
    /// Path to PEM private key file
    pub key_path: PathBuf,
}

/// Generate a self-signed certificate for development.
/// Returns (cert_pem, key_pem) as strings.
///
/// The wire cert carries CN `"RedDB Wire {hostname}"` **and**
/// `OrganizationName "RedDB"`. The HTTP edge shares this generator but
/// passes `org = None` (see [`generate_self_signed_dev_cert`]) so its
/// cert keeps no organization.
pub fn generate_self_signed_cert(
    hostname: &str,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    generate_self_signed_dev_cert(hostname, "RedDB Wire", Some("RedDB"))
}

/// Shared self-signed dev-cert generator for the wire and HTTP edges.
///
/// Behaviour-preserving parameterization of two formerly near-identical
/// rcgen blocks (issue #1055): the CN is `"{cn_label} {hostname}"`, and
/// `org` — when `Some` — sets `OrganizationName`. The wire edge passes
/// `Some("RedDB")`; the HTTP edge passes `None` so its cert keeps CN
/// `"RedDB HTTP …"` with **no** organization (do NOT silently add
/// `O=RedDB` to the HTTP cert). The SAN block (`hostname`, `localhost`
/// when distinct, and `127.0.0.1`) is identical for both.
pub(crate) fn generate_self_signed_dev_cert(
    hostname: &str,
    cn_label: &str,
    org: Option<&str>,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    let key_pair = rcgen::KeyPair::generate()?;
    let cert_pem = self_sign_dev_cert(hostname, cn_label, org, &key_pair)?;
    Ok((cert_pem, key_pair.serialize_pem()))
}

fn self_sign_dev_cert(
    hostname: &str,
    cn_label: &str,
    org: Option<&str>,
    key_pair: &rcgen::KeyPair,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut params = rcgen::CertificateParams::new(vec![hostname.to_string()])?;
    params.distinguished_name.push(
        rcgen::DnType::CommonName,
        rcgen::DnValue::Utf8String(format!("{cn_label} {hostname}")),
    );
    if let Some(org) = org {
        params.distinguished_name.push(
            rcgen::DnType::OrganizationName,
            rcgen::DnValue::Utf8String(org.to_string()),
        );
    }

    // Add localhost + IP SANs for dev
    params
        .subject_alt_names
        .push(rcgen::SanType::DnsName(hostname.try_into()?));
    if hostname != "localhost" {
        params
            .subject_alt_names
            .push(rcgen::SanType::DnsName("localhost".try_into()?));
    }
    // 127.0.0.1
    params
        .subject_alt_names
        .push(rcgen::SanType::IpAddress(std::net::IpAddr::V4(
            std::net::Ipv4Addr::LOCALHOST,
        )));

    Ok(params.self_signed(key_pair)?.pem())
}

/// Ensure the development pair exists. Returns true when a certificate was issued.
pub(crate) fn ensure_dev_tls_cert_pair(
    cert_path: &Path,
    key_path: &Path,
    cn_label: &str,
    org: Option<&str>,
) -> Result<bool, Box<dyn std::error::Error>> {
    match key_path.symlink_metadata() {
        Ok(metadata) => {
            if !metadata.is_file() {
                return Err(
                    format!("TLS key {} must be a regular file", key_path.display()).into(),
                );
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;

                if metadata.permissions().mode() & 0o077 != 0 {
                    return Err(format!(
                        "TLS key {} is accessible to other users; replace the development certificate and key",
                        key_path.display()
                    )
                    .into());
                }
            }
            if cert_path.try_exists()? {
                return Ok(false);
            }
            // Recover a missing certificate using the existing private key.
            let key_pair = rcgen::KeyPair::from_pem(&fs::read_to_string(key_path)?)?;
            let cert_pem = self_sign_dev_cert("localhost", cn_label, org, &key_pair)?;
            fs::write(cert_path, cert_pem)?;
        }
        Err(err) if err.kind() == io::ErrorKind::NotFound => {
            let (cert_pem, key_pem) = generate_self_signed_dev_cert("localhost", cn_label, org)?;
            if let Some(dir) = key_path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
                fs::create_dir_all(dir)?;
            }
            let mut options = fs::OpenOptions::new();
            options.write(true).create_new(true);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt;

                options.mode(0o600);
            }
            let mut key_file = options.open(key_path)?;
            let result = key_file.write_all(key_pem.as_bytes());
            drop(key_file);
            if let Err(err) = result.and_then(|()| fs::write(cert_path, cert_pem)) {
                // This call owns the freshly created key. Leave retries free to issue a new pair.
                let _ = fs::remove_file(key_path);
                return Err(err.into());
            }
        }
        Err(err) => return Err(err.into()),
    }
    Ok(true)
}

/// Generate self-signed cert and write to files in the given directory.
/// Returns the WireTlsConfig pointing to the written files.
///
/// Gated by `RED_WIRE_TLS_DEV=1`; refuses to auto-generate in any other
/// context (refuses prod by default). This mirrors the HTTP edge's
/// `RED_HTTP_TLS_DEV` opt-in ([`crate::server::tls::auto_generate_dev_cert`])
/// — the two edges are independent, so enabling dev certs on one does not
/// enable them on the other.
pub fn auto_generate_cert(dir: &Path) -> Result<WireTlsConfig, Box<dyn std::error::Error>> {
    let dev_flag = std::env::var("RED_WIRE_TLS_DEV").unwrap_or_default();
    if !matches!(dev_flag.as_str(), "1" | "true" | "yes" | "on") {
        return Err(
            "refusing to auto-generate wire TLS cert: set RED_WIRE_TLS_DEV=1 to opt into self-signed dev certs"
                .into(),
        );
    }

    let cert_path = dir.join("wire-tls-cert.pem");
    let key_path = dir.join("wire-tls-key.pem");

    if ensure_dev_tls_cert_pair(&cert_path, &key_path, "RedDB Wire", Some("RedDB"))? {
        tracing::info!(
            cert = %cert_path.display(),
            key = %key_path.display(),
            "wire TLS: wrote self-signed cert"
        );
    } else {
        tracing::info!(cert = %cert_path.display(), "wire TLS: reusing existing cert");
    }

    Ok(WireTlsConfig {
        cert_path,
        key_path,
    })
}

/// Build a TLS acceptor from cert and key PEM files.
pub fn build_tls_acceptor(
    config: &WireTlsConfig,
) -> Result<TlsAcceptor, Box<dyn std::error::Error>> {
    // Ensure the ring crypto provider is installed
    let _ = rustls::crypto::ring::default_provider().install_default();

    let cert_pem = std::fs::read(&config.cert_path)?;
    let key_pem = std::fs::read(&config.key_path)?;

    let certs = rustls_pemfile::certs(&mut io::BufReader::new(&cert_pem[..]))
        .collect::<Result<Vec<_>, _>>()?;
    let key = rustls_pemfile::private_key(&mut io::BufReader::new(&key_pem[..]))?
        .ok_or("no private key found in PEM file")?;

    let server_config = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, key)?;

    Ok(TlsAcceptor::from(Arc::new(server_config)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dev_tls_pair_recovers_a_missing_certificate_without_replacing_key() {
        let directory = tempfile::tempdir().expect("TLS directory");
        let cert = directory.path().join("cert.pem");
        let key = directory.path().join("key.pem");
        let ensure = || ensure_dev_tls_cert_pair(&cert, &key, "RedDB Wire", Some("RedDB"));

        assert!(ensure().expect("generate pair"));
        let original_key = fs::read(&key).expect("read key");
        let original_cert = fs::read(&cert).expect("read certificate");
        assert!(!ensure().expect("reuse pair"));
        assert_eq!(
            fs::read(&cert).expect("read reused certificate"),
            original_cert
        );
        fs::remove_file(&cert).expect("remove certificate");

        assert!(ensure().expect("recover missing certificate"));
        assert_eq!(fs::read(&key).expect("read reused key"), original_key);
        build_tls_acceptor(&WireTlsConfig {
            cert_path: cert,
            key_path: key,
        })
        .expect("recovered certificate matches the private key");
    }

    #[cfg(unix)]
    #[test]
    fn dev_tls_key_is_private_and_reuse_rejects_broad_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let directory = tempfile::tempdir().expect("TLS directory");
        let cert = directory.path().join("cert.pem");
        let key = directory.path().join("key.pem");
        let ensure = || ensure_dev_tls_cert_pair(&cert, &key, "RedDB Wire", Some("RedDB"));

        assert!(ensure().expect("generate pair"));
        assert_eq!(
            fs::metadata(&key).expect("key mode").permissions().mode() & 0o077,
            0
        );

        fs::set_permissions(&key, fs::Permissions::from_mode(0o644)).expect("set key mode");
        let err = ensure().expect_err("reject a group- or world-readable key");
        assert!(err.to_string().contains("accessible to other users"));
    }

    /// Parse the subject CN + Organization out of a self-signed PEM cert,
    /// so the wire-vs-HTTP DN difference is pinned end-to-end (issue #1055).
    fn subject_cn_and_orgs(cert_pem: &str) -> (Vec<String>, Vec<String>) {
        let der = rustls_pemfile::certs(&mut io::BufReader::new(cert_pem.as_bytes()))
            .next()
            .expect("one certificate in PEM")
            .expect("valid certificate PEM");
        let (_, parsed) =
            x509_parser::parse_x509_certificate(der.as_ref()).expect("parse generated X.509");
        let subject = parsed.subject();
        let cns = subject
            .iter_common_name()
            .filter_map(|cn| cn.as_str().ok().map(str::to_string))
            .collect();
        let orgs = subject
            .iter_organization()
            .filter_map(|o| o.as_str().ok().map(str::to_string))
            .collect();
        (cns, orgs)
    }

    #[test]
    fn wire_cert_keeps_wire_cn_and_reddb_org() {
        let (cert_pem, key_pem) =
            generate_self_signed_cert("localhost").expect("generate wire cert");
        assert!(key_pem.contains("PRIVATE KEY"), "key PEM emitted");
        let (cns, orgs) = subject_cn_and_orgs(&cert_pem);
        assert_eq!(cns, vec!["RedDB Wire localhost".to_string()]);
        assert_eq!(orgs, vec!["RedDB".to_string()]);
    }

    #[test]
    fn http_cert_keeps_http_cn_and_no_org() {
        // The non-obvious diff (issue #1055): the HTTP cert must keep CN
        // "RedDB HTTP …" and carry NO organization. The shared generator
        // passes org = None so we never silently add O=RedDB to it.
        let (cert_pem, _key) = generate_self_signed_dev_cert("localhost", "RedDB HTTP", None)
            .expect("generate http cert");
        let (cns, orgs) = subject_cn_and_orgs(&cert_pem);
        assert_eq!(cns, vec!["RedDB HTTP localhost".to_string()]);
        assert!(orgs.is_empty(), "HTTP cert must not carry an Organization");
    }

    /// Tests that mutate the process-global `RED_WIRE_TLS_DEV` env var must
    /// serialize to avoid trampling each other under cargo's default
    /// parallel test runner (mirrors the HTTP twin's `env_lock`).
    fn env_lock() -> &'static std::sync::Mutex<()> {
        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
        LOCK.get_or_init(|| std::sync::Mutex::new(()))
    }

    #[test]
    fn auto_generate_refuses_without_dev_flag() {
        let _g = env_lock().lock();
        let dir = std::env::temp_dir().join(format!(
            "reddb-wire-tls-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // Make sure flag is unset.
        unsafe {
            std::env::remove_var("RED_WIRE_TLS_DEV");
        }
        let err = auto_generate_cert(&dir).unwrap_err();
        assert!(err.to_string().contains("RED_WIRE_TLS_DEV"));
    }

    #[test]
    fn auto_generate_with_dev_flag_writes_cert() {
        let _g = env_lock().lock();
        let dir = std::env::temp_dir().join(format!(
            "reddb-wire-tls-dev-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        unsafe {
            std::env::set_var("RED_WIRE_TLS_DEV", "1");
        }
        let cfg = auto_generate_cert(&dir).expect("should generate");
        assert!(cfg.cert_path.exists());
        assert!(cfg.key_path.exists());
        unsafe {
            std::env::remove_var("RED_WIRE_TLS_DEV");
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
}