reddb-io-server 1.46.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! HTTP TLS termination for the embedded HTTP server.
//!
//! The HTTP server terminates TLS with `tokio-rustls` and serves both
//! HTTP/2 and HTTP/1.1 through the shared async hyper edge.
//!
//! Capabilities:
//!   * PEM cert / key load from disk.
//!   * Optional mTLS — when a client-CA bundle is configured, every
//!     handshake must present a cert that chains to it.
//!   * Auto-generated self-signed cert for dev (gated by
//!     `RED_HTTP_TLS_DEV=1`) — refuses without that env knob.
//!   * SHA256 fingerprint logged at boot so operators can pin the cert
//!     out-of-band.
//!   * TLS 1.2 + 1.3 only (rustls default; older protocols are not
//!     compiled in). Cipher suites = rustls defaults (FS-only,
//!     no anonymous, no exportables).

use std::io::{self, BufReader, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustls::pki_types::CertificateDer;
use rustls::server::WebPkiClientVerifier;
use rustls::{RootCertStore, ServerConfig, ServerConnection, StreamOwned};

/// Configuration for HTTP TLS termination.
#[derive(Debug, Clone)]
pub struct HttpTlsConfig {
    /// Path to PEM-encoded server certificate chain.
    pub cert_path: PathBuf,
    /// Path to PEM-encoded private key (PKCS#8 or RSA).
    pub key_path: PathBuf,
    /// Optional path to PEM CA bundle. When set, mTLS is required and
    /// every client must present a cert that chains to a CA in this
    /// bundle. When `None`, plain server-side TLS is used (no client
    /// auth — same as the public `https://` web).
    pub client_ca_path: Option<PathBuf>,
}

const HTTP_TLS_PROFILE_ENV: &str = "REDDB_HTTP_TLS_PROFILE";
const PQ_BUILD_REQUIRED: &str = "REDDB_HTTP_TLS_PROFILE needs a build with the http-tls-pq feature";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum HttpTlsProfile {
    Default,
    Hybrid,
    HybridRequired,
}

impl HttpTlsProfile {
    pub(crate) fn from_env() -> Result<Self, String> {
        match std::env::var(HTTP_TLS_PROFILE_ENV) {
            Ok(value) => Self::parse(&value),
            Err(std::env::VarError::NotPresent) => Ok(Self::Default),
            Err(std::env::VarError::NotUnicode(_)) => {
                Err(format!("{HTTP_TLS_PROFILE_ENV} must be valid UTF-8"))
            }
        }
    }

    fn parse(value: &str) -> Result<Self, String> {
        let profile = match value {
            "default" => Self::Default,
            "hybrid" => Self::Hybrid,
            "hybrid-required" => Self::HybridRequired,
            _ => {
                return Err(format!(
                    "{HTTP_TLS_PROFILE_ENV} must be default, hybrid, or hybrid-required"
                ));
            }
        };
        if profile != Self::Default && !cfg!(feature = "http-tls-pq") {
            return Err(PQ_BUILD_REQUIRED.to_string());
        }
        Ok(profile)
    }
}

/// Build a rustls server configuration with the default HTTP TLS profile.
pub fn build_server_config(
    config: &HttpTlsConfig,
) -> Result<Arc<ServerConfig>, Box<dyn std::error::Error>> {
    build_server_config_with_profile(config, HttpTlsProfile::Default)
}

pub(crate) fn build_server_config_with_profile(
    config: &HttpTlsConfig,
    profile: HttpTlsProfile,
) -> Result<Arc<ServerConfig>, Box<dyn std::error::Error>> {
    let _ = rustls::crypto::ring::default_provider().install_default();
    let builder = match profile {
        HttpTlsProfile::Default => ServerConfig::builder(),
        #[cfg(feature = "http-tls-pq")]
        HttpTlsProfile::Hybrid | HttpTlsProfile::HybridRequired => {
            use rustls::crypto::aws_lc_rs::kx_group::X25519MLKEM768;
            use rustls::version::TLS13;

            // Keep ring's cipher suites and certificate algorithms. Only the
            // standard hybrid key exchange comes from the second provider.
            let mut provider = rustls::crypto::ring::default_provider();
            if profile == HttpTlsProfile::HybridRequired {
                provider.kx_groups.clear();
            }
            provider.kx_groups.insert(0, X25519MLKEM768);
            provider
                .cipher_suites
                .retain(|suite| suite.version() == &TLS13);
            ServerConfig::builder_with_provider(Arc::new(provider))
                .with_protocol_versions(&[&TLS13])?
        }
        #[cfg(not(feature = "http-tls-pq"))]
        HttpTlsProfile::Hybrid | HttpTlsProfile::HybridRequired => {
            return Err(PQ_BUILD_REQUIRED.into());
        }
    };

    let cert_pem = std::fs::read(&config.cert_path)
        .map_err(|err| format!("read TLS cert {}: {err}", config.cert_path.display()))?;
    let key_pem = std::fs::read(&config.key_path)
        .map_err(|err| format!("read TLS key {}: {err}", config.key_path.display()))?;

    let certs = rustls_pemfile::certs(&mut BufReader::new(&cert_pem[..]))
        .collect::<Result<Vec<_>, _>>()
        .map_err(|err| format!("decode cert PEM: {err}"))?;
    if certs.is_empty() {
        return Err("TLS cert PEM contained no certificates".into());
    }
    let key = rustls_pemfile::private_key(&mut BufReader::new(&key_pem[..]))
        .map_err(|err| format!("decode key PEM: {err}"))?
        .ok_or("TLS key PEM contained no private key")?;

    // Log SHA256 fingerprint (DER-encoded leaf) for out-of-band pinning.
    let fingerprint = sha256_fingerprint_hex(&certs[0]);
    tracing::info!(
        target: "reddb::http_tls",
        cert = %config.cert_path.display(),
        sha256 = %fingerprint,
        profile = ?profile,
        "HTTP TLS certificate loaded"
    );

    let mut server_config = if let Some(ca_path) = &config.client_ca_path {
        let ca_pem = std::fs::read(ca_path)
            .map_err(|err| format!("read mTLS client CA {}: {err}", ca_path.display()))?;
        let mut roots = RootCertStore::empty();
        let ca_certs: Vec<CertificateDer<'static>> =
            rustls_pemfile::certs(&mut BufReader::new(&ca_pem[..]))
                .collect::<Result<Vec<_>, _>>()
                .map_err(|err| format!("decode mTLS client CA PEM: {err}"))?;
        if ca_certs.is_empty() {
            return Err("mTLS client CA PEM contained no certificates".into());
        }
        for cert in ca_certs {
            roots.add(cert)?;
        }
        let verifier = WebPkiClientVerifier::builder_with_provider(
            Arc::new(roots),
            builder.crypto_provider().clone(),
        )
        .build()
        .map_err(|err| format!("build mTLS client verifier: {err}"))?;
        tracing::info!(
            target: "reddb::http_tls",
            ca = %ca_path.display(),
            "HTTP mTLS enabled — clients must present a cert chaining to this CA"
        );
        builder
            .with_client_cert_verifier(verifier)
            .with_single_cert(certs, key)
            .map_err(|err| format!("install TLS cert/key: {err}"))?
    } else {
        builder
            .with_no_client_auth()
            .with_single_cert(certs, key)
            .map_err(|err| format!("install TLS cert/key: {err}"))?
    };

    // Prefer HTTP/2 while retaining HTTP/1.1 compatibility. The async hyper
    // edge supports both protocols; omitting `h2` here silently forced every
    // production HTTPS client back to HTTP/1.1.
    server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];

    Ok(Arc::new(server_config))
}

/// Derive a self-signed dev certificate when `--http-tls-bind` is set
/// without an explicit cert/key. Gated by `RED_HTTP_TLS_DEV=1`; refuses
/// to auto-generate in any other context (refuses prod by default).
///
/// Writes `http-tls-cert.pem` + `http-tls-key.pem` into `dir`. Returns
/// the populated `HttpTlsConfig` pointing at the freshly-written files.
pub fn auto_generate_dev_cert(dir: &Path) -> Result<HttpTlsConfig, Box<dyn std::error::Error>> {
    let dev_flag = std::env::var("RED_HTTP_TLS_DEV").unwrap_or_default();
    if !matches!(dev_flag.as_str(), "1" | "true" | "yes" | "on") {
        return Err(
            "refusing to auto-generate HTTP TLS cert: set RED_HTTP_TLS_DEV=1 to opt into self-signed dev certs"
                .into(),
        );
    }

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

    if crate::wire::tls::ensure_dev_tls_cert_pair(&cert_path, &key_path, "RedDB HTTP", None)? {
        tracing::warn!(
            target: "reddb::http_tls",
            cert = %cert_path.display(),
            "HTTP TLS dev: generated SELF-SIGNED cert (NOT FOR PRODUCTION)"
        );
    } else {
        tracing::info!(
            target: "reddb::http_tls",
            cert = %cert_path.display(),
            "HTTP TLS dev: reusing existing self-signed cert"
        );
    }
    Ok(HttpTlsConfig {
        cert_path,
        key_path,
        client_ca_path: None,
    })
}

fn sha256_fingerprint_hex(cert: &CertificateDer<'_>) -> String {
    let digest = crate::crypto::sha256(cert.as_ref());
    let mut out = String::with_capacity(64 + 31);
    for (i, byte) in digest.iter().enumerate() {
        if i > 0 {
            // ':'-separated pairs match `openssl x509 -fingerprint`
            // output so operators can copy-paste for pinning.
            out.push(':');
        }
        let _ = std::fmt::Write::write_fmt(&mut out, format_args!("{:02x}", byte));
    }
    out
}

/// Wrap a sync TcpStream in a TLS server connection. Performs the
/// handshake as part of stream construction. Returns a stream that
/// transparently encrypts on write / decrypts on read.
pub fn accept_tls(
    config: Arc<ServerConfig>,
    tcp: TcpStream,
) -> io::Result<StreamOwned<ServerConnection, TcpStream>> {
    let conn = ServerConnection::new(config)
        .map_err(|err| io::Error::other(format!("rustls server: {err}")))?;
    let mut stream = StreamOwned::new(conn, tcp);
    // Force the handshake now so any failure surfaces here (and not on
    // the first read inside the request parser).
    let _ = stream.flush();
    Ok(stream)
}

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

    /// Tests that mutate the process-global `RED_HTTP_TLS_DEV` env var
    /// must serialize to avoid trampling each other under cargo's
    /// default parallel test runner.
    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 http_tls_profile_requires_a_known_value_and_a_capable_build() {
        assert_eq!(
            HttpTlsProfile::parse("default"),
            Ok(HttpTlsProfile::Default)
        );
        assert!(HttpTlsProfile::parse("").is_err());
        assert!(HttpTlsProfile::parse("hybird").is_err());
        let hybrid = HttpTlsProfile::parse("hybrid");
        let strict = HttpTlsProfile::parse("hybrid-required");
        if cfg!(feature = "http-tls-pq") {
            assert_eq!(hybrid, Ok(HttpTlsProfile::Hybrid));
            assert_eq!(strict, Ok(HttpTlsProfile::HybridRequired));
        } else {
            assert_eq!(hybrid, Err(PQ_BUILD_REQUIRED.to_string()));
            assert_eq!(strict, Err(PQ_BUILD_REQUIRED.to_string()));
        }
    }

    fn tls_fixture() -> (tempfile::TempDir, HttpTlsConfig, CertificateDer<'static>) {
        let directory = tempfile::tempdir().expect("temporary TLS fixture");
        let rcgen::CertifiedKey { cert, signing_key } =
            rcgen::generate_simple_self_signed(vec!["localhost".into()])
                .expect("generate server identity");
        let config = HttpTlsConfig {
            cert_path: directory.path().join("server.crt"),
            key_path: directory.path().join("server.key"),
            client_ca_path: None,
        };
        std::fs::write(&config.cert_path, cert.pem()).expect("write server certificate");
        std::fs::write(&config.key_path, signing_key.serialize_pem()).expect("write server key");
        (directory, config, cert.der().clone())
    }

    fn fixture_client(
        provider: rustls::crypto::CryptoProvider,
        version: &'static rustls::SupportedProtocolVersion,
        server_cert: CertificateDer<'static>,
        identity: Option<(&rcgen::Certificate, &rcgen::KeyPair)>,
    ) -> rustls::ClientConnection {
        let mut roots = RootCertStore::empty();
        roots.add(server_cert).expect("trust the fixture server");
        let builder = rustls::ClientConfig::builder_with_provider(Arc::new(provider))
            .with_protocol_versions(&[version])
            .expect("enable client protocol")
            .with_root_certificates(roots);
        let mut client = match identity {
            Some((cert, key)) => builder
                .with_client_auth_cert(
                    vec![cert.der().clone()],
                    key.serialize_der().try_into().expect("client key DER"),
                )
                .expect("load the client identity"),
            None => builder.with_no_client_auth(),
        };
        client.alpn_protocols = vec![b"h2".to_vec()];
        rustls::ClientConnection::new(
            Arc::new(client),
            rustls::pki_types::ServerName::try_from("localhost").expect("fixture DNS name"),
        )
        .expect("create the fixture client")
    }

    fn transfer_tls(
        from: &mut rustls::Connection,
        to: &mut rustls::Connection,
    ) -> Result<(), rustls::Error> {
        let mut wire = Vec::new();
        from.write_tls(&mut wire).expect("write TLS records");
        let mut records = wire.as_slice();
        while !records.is_empty() {
            assert!(to.read_tls(&mut records).expect("read TLS records") > 0);
            to.process_new_packets()?;
        }
        Ok(())
    }

    fn handshake(
        server_config: Arc<ServerConfig>,
        client: rustls::ClientConnection,
    ) -> Result<(rustls::ProtocolVersion, rustls::NamedGroup), rustls::Error> {
        let mut server = rustls::Connection::Server(ServerConnection::new(server_config)?);
        let mut client = rustls::Connection::Client(client);
        for _ in 0..8 {
            transfer_tls(&mut client, &mut server)?;
            transfer_tls(&mut server, &mut client)?;
            if !client.is_handshaking() && !server.is_handshaking() {
                let version = server.protocol_version().expect("negotiated TLS protocol");
                let group = server
                    .negotiated_key_exchange_group()
                    .expect("negotiated exchange group")
                    .name();
                assert_eq!(client.protocol_version(), Some(version));
                assert_eq!(
                    client
                        .negotiated_key_exchange_group()
                        .map(|group| group.name()),
                    Some(group)
                );
                assert_eq!(server.alpn_protocol(), Some(b"h2".as_slice()));
                return Ok((version, group));
            }
        }
        panic!("TLS handshake did not complete");
    }

    #[test]
    fn http_tls_default_keeps_tls12_and_classical_tls13() {
        let (_directory, config, certificate) = tls_fixture();
        let server = build_server_config(&config).expect("ordinary HTTPS configuration");

        for version in [&rustls::version::TLS12, &rustls::version::TLS13] {
            let client = fixture_client(
                rustls::crypto::ring::default_provider(),
                version,
                certificate.clone(),
                None,
            );
            let (negotiated, group) =
                handshake(server.clone(), client).expect("classical handshake");
            assert_eq!(negotiated, version.version);
            assert_eq!(group, rustls::NamedGroup::X25519);
        }
    }

    #[cfg(feature = "http-tls-pq")]
    #[test]
    fn http_tls_hybrid_profiles_negotiate_or_refuse_classical_clients() {
        use rustls::{crypto::aws_lc_rs::kx_group::X25519MLKEM768, NamedGroup, ProtocolVersion};

        let (_directory, config, certificate) = tls_fixture();
        for profile in [HttpTlsProfile::Hybrid, HttpTlsProfile::HybridRequired] {
            let server = build_server_config_with_profile(&config, profile).expect("hybrid HTTPS");
            assert_eq!(
                server.max_early_data_size, 0,
                "TLS early data stays disabled"
            );
            let mut hybrid = rustls::crypto::ring::default_provider();
            hybrid.kx_groups.insert(0, X25519MLKEM768);
            let client = fixture_client(hybrid, &rustls::version::TLS13, certificate.clone(), None);
            assert_eq!(
                handshake(server.clone(), client).expect("hybrid handshake"),
                (ProtocolVersion::TLSv1_3, NamedGroup::X25519MLKEM768)
            );

            let client = fixture_client(
                rustls::crypto::ring::default_provider(),
                &rustls::version::TLS13,
                certificate.clone(),
                None,
            );
            let result = handshake(server.clone(), client);
            if profile == HttpTlsProfile::HybridRequired {
                assert_eq!(
                    result,
                    Err(rustls::Error::PeerIncompatible(
                        rustls::PeerIncompatible::NoKxGroupsInCommon
                    ))
                );
            } else {
                assert_eq!(
                    result.expect("classical TLS 1.3 fallback"),
                    (ProtocolVersion::TLSv1_3, NamedGroup::X25519)
                );
            }

            let client = fixture_client(
                rustls::crypto::ring::default_provider(),
                &rustls::version::TLS12,
                certificate.clone(),
                None,
            );
            assert!(
                handshake(server, client).is_err(),
                "{profile:?} is TLS 1.3 only"
            );
        }
    }

    #[cfg(feature = "http-tls-pq")]
    #[test]
    fn http_tls_hybrid_required_preserves_mtls() {
        let (directory, mut config, certificate) = tls_fixture();
        let mut ca_params = rcgen::CertificateParams::new(Vec::new()).expect("CA parameters");
        ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        let ca_key = rcgen::KeyPair::generate().expect("CA key");
        let ca = ca_params
            .self_signed(&ca_key)
            .expect("issue CA certificate");
        let issuer = rcgen::Issuer::new(ca_params, ca_key);
        let mut client_params =
            rcgen::CertificateParams::new(Vec::new()).expect("client parameters");
        client_params
            .extended_key_usages
            .push(rcgen::ExtendedKeyUsagePurpose::ClientAuth);
        let client_key = rcgen::KeyPair::generate().expect("client key");
        let client_cert = client_params
            .signed_by(&client_key, &issuer)
            .expect("issue client certificate");

        let ca_path = directory.path().join("clients-ca.crt");
        std::fs::write(&ca_path, ca.pem()).expect("write client CA");
        config.client_ca_path = Some(ca_path);
        let server = build_server_config_with_profile(&config, HttpTlsProfile::HybridRequired)
            .expect("hybrid mTLS config");
        let mut provider = rustls::crypto::ring::default_provider();
        provider.kx_groups = vec![rustls::crypto::aws_lc_rs::kx_group::X25519MLKEM768];

        let client = fixture_client(
            provider.clone(),
            &rustls::version::TLS13,
            certificate.clone(),
            Some((&client_cert, &client_key)),
        );
        assert_eq!(
            handshake(server.clone(), client).expect("authorized client completes hybrid mTLS"),
            (
                rustls::ProtocolVersion::TLSv1_3,
                rustls::NamedGroup::X25519MLKEM768
            )
        );

        let client = fixture_client(provider, &rustls::version::TLS13, certificate, None);
        assert_eq!(
            handshake(server, client),
            Err(rustls::Error::NoCertificatesPresented)
        );
    }

    #[test]
    fn fingerprint_format() {
        // 32 zero bytes → 32 ":" -separated lowercase hex pairs.
        let cert = CertificateDer::from(vec![0u8; 8]);
        let fp = sha256_fingerprint_hex(&cert);
        // 32 bytes hex = 64 chars, plus 31 colons = 95 total.
        assert_eq!(fp.len(), 64 + 31);
        assert!(fp.chars().all(|c| c == ':' || c.is_ascii_hexdigit()));
    }

    #[test]
    fn auto_generate_refuses_without_dev_flag() {
        let _g = env_lock().lock();
        let dir = std::env::temp_dir().join(format!(
            "reddb-http-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_HTTP_TLS_DEV");
        }
        let err = auto_generate_dev_cert(&dir).unwrap_err();
        assert!(err.to_string().contains("RED_HTTP_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-http-tls-dev-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        unsafe {
            std::env::set_var("RED_HTTP_TLS_DEV", "1");
        }
        let cfg = auto_generate_dev_cert(&dir).expect("should generate");
        assert!(cfg.cert_path.exists());
        assert!(cfg.key_path.exists());
        let server_config = build_server_config(&cfg).expect("TLS config");
        assert_eq!(
            server_config.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );
        unsafe {
            std::env::remove_var("RED_HTTP_TLS_DEV");
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
}