Skip to main content

strata_web_api/
tls.rs

1//! Production-Grade Pure-Rust TLS Transport for HTTP/1.1 and HTTPS.
2//!
3//! Implements memory-safe TLS 1.2 and TLS 1.3 encrypted transport streams using `rustls`
4//! and Mozilla's `webpki-roots`, with zero C/OpenSSL dependencies.
5
6use std::io::{Read, Write};
7use std::net::TcpStream;
8use std::sync::{Arc, OnceLock};
9
10use rustls::pki_types::ServerName;
11use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
12
13/// Abstract transport stream multiplexing between plain TCP and TLS-encrypted connections.
14pub enum HttpTransportStream {
15    Plain(TcpStream),
16    Tls(Box<StreamOwned<ClientConnection, TcpStream>>),
17}
18
19impl Read for HttpTransportStream {
20    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
21        match self {
22            Self::Plain(stream) => stream.read(buf),
23            Self::Tls(stream) => stream.read(buf),
24        }
25    }
26}
27
28impl Write for HttpTransportStream {
29    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
30        match self {
31            Self::Plain(stream) => stream.write(buf),
32            Self::Tls(stream) => stream.write(buf),
33        }
34    }
35
36    fn flush(&mut self) -> std::io::Result<()> {
37        match self {
38            Self::Plain(stream) => stream.flush(),
39            Self::Tls(stream) => stream.flush(),
40        }
41    }
42}
43
44static TLS_CLIENT_CONFIG: OnceLock<Arc<ClientConfig>> = OnceLock::new();
45
46/// Returns a shared, lazily-initialized TLS `ClientConfig` with Mozilla WebPKI root certificates.
47pub fn get_or_init_tls_config() -> Arc<ClientConfig> {
48    TLS_CLIENT_CONFIG
49        .get_or_init(|| {
50            let mut root_store = RootCertStore::empty();
51            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
52
53            let mut config = ClientConfig::builder_with_provider(Arc::new(
54                rustls::crypto::ring::default_provider(),
55            ))
56            .with_safe_default_protocol_versions()
57            .expect("Valid default protocol versions")
58            .with_root_certificates(root_store)
59            .with_no_client_auth();
60
61            config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
62
63            Arc::new(config)
64        })
65        .clone()
66}
67
68use std::time::Duration;
69
70impl HttpTransportStream {
71    /// Returns the negotiated ALPN protocol, if TLS was used and negotiated.
72    pub fn alpn_protocol(&self) -> Option<&[u8]> {
73        match self {
74            Self::Plain(_) => None,
75            Self::Tls(stream) => stream.conn.alpn_protocol(),
76        }
77    }
78
79    /// Configures read timeout on the underlying socket.
80    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> std::io::Result<()> {
81        match self {
82            Self::Plain(stream) => stream.set_read_timeout(timeout),
83            Self::Tls(stream) => stream.sock.set_read_timeout(timeout),
84        }
85    }
86
87    /// Configures write timeout on the underlying socket.
88    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> std::io::Result<()> {
89        match self {
90            Self::Plain(stream) => stream.set_write_timeout(timeout),
91            Self::Tls(stream) => stream.sock.set_write_timeout(timeout),
92        }
93    }
94
95    /// Configures TCP nodelay to disable Nagle's algorithm for low-latency interactive streaming.
96    pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> {
97        match self {
98            Self::Plain(stream) => stream.set_nodelay(nodelay),
99            Self::Tls(stream) => stream.sock.set_nodelay(nodelay),
100        }
101    }
102}
103
104/// Creates an encrypted TLS client transport stream wrapping an established `TcpStream`.
105pub fn create_tls_stream(
106    mut tcp_stream: TcpStream,
107    host: &str,
108) -> Result<HttpTransportStream, String> {
109    let server_name = ServerName::try_from(host.to_string())
110        .map_err(|e| format!("Invalid DNS hostname for TLS SNI '{host}': {e}"))?;
111
112    let config = get_or_init_tls_config();
113    let mut conn = ClientConnection::new(config, server_name)
114        .map_err(|e| format!("TLS client handshake initialization failed: {e}"))?;
115
116    while conn.is_handshaking() {
117        conn.complete_io(&mut tcp_stream)
118            .map_err(|e| format!("TLS handshake failed: {e}"))?;
119    }
120
121    Ok(HttpTransportStream::Tls(Box::new(StreamOwned::new(
122        conn, tcp_stream,
123    ))))
124}