Skip to main content

moirai_tls/
lib.rs

1//! Async TLS client for the Moirai runtime.
2//!
3//! Drives the sans-I/O [`rustls`] state machine (via the runtime-agnostic
4//! [`futures_rustls`] adapter) over a Moirai async socket — **no Tokio**. Moirai's
5//! [`moirai_async::io::AsyncRead`]/[`AsyncWrite`](moirai_async::io::AsyncWrite)
6//! traits are signature-identical to `futures_io`, so the bridge is two zero-cost
7//! newtypes; all TLS cryptography and record framing are delegated to the audited
8//! `rustls` stack (ADR-015 — moirai owns transport, not crypto reimplementation).
9//!
10//! ```no_run
11//! # async fn ex<S: moirai_async::io::AsyncRead + moirai_async::io::AsyncWrite + Unpin>(sock: S) {
12//! use moirai_tls::{TlsConnector, ServerName};
13//! let connector = TlsConnector::with_webpki_roots();
14//! let domain = ServerName::try_from("example.com").unwrap();
15//! let _tls = connector.connect(domain, sock).await.unwrap();
16//! # }
17//! ```
18
19#![forbid(unsafe_code)]
20#![deny(missing_docs)]
21
22use std::io;
23use std::pin::Pin;
24use std::sync::Arc;
25use std::task::{Context, Poll};
26
27use futures_rustls::TlsConnector as RustlsConnector;
28use futures_rustls::rustls::{ClientConfig, RootCertStore};
29use moirai_async::io::{AsyncRead as MoiraiRead, AsyncWrite as MoiraiWrite};
30
31/// Re-export of the underlying `rustls` types (config, crypto, errors).
32pub use futures_rustls::rustls;
33/// Server name used for SNI and certificate validation.
34pub use rustls_pki_types::ServerName;
35
36/// Zero-cost adapter exposing a Moirai async stream as a [`futures_io`] stream.
37///
38/// Requires `S: Unpin` (Moirai sockets and the `rustls` stream are `Unpin`), which
39/// keeps the projection safe without `unsafe`.
40#[derive(Debug)]
41pub struct ToFuturesIo<S>(
42    /// The wrapped Moirai async stream.
43    pub S,
44);
45
46impl<S: MoiraiRead + Unpin> futures_io::AsyncRead for ToFuturesIo<S> {
47    #[inline]
48    fn poll_read(
49        self: Pin<&mut Self>,
50        cx: &mut Context<'_>,
51        buf: &mut [u8],
52    ) -> Poll<io::Result<usize>> {
53        MoiraiRead::poll_read(Pin::new(&mut self.get_mut().0), cx, buf)
54    }
55}
56
57impl<S: MoiraiWrite + Unpin> futures_io::AsyncWrite for ToFuturesIo<S> {
58    #[inline]
59    fn poll_write(
60        self: Pin<&mut Self>,
61        cx: &mut Context<'_>,
62        buf: &[u8],
63    ) -> Poll<io::Result<usize>> {
64        MoiraiWrite::poll_write(Pin::new(&mut self.get_mut().0), cx, buf)
65    }
66
67    #[inline]
68    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
69        MoiraiWrite::poll_flush(Pin::new(&mut self.get_mut().0), cx)
70    }
71
72    #[inline]
73    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
74        MoiraiWrite::poll_shutdown(Pin::new(&mut self.get_mut().0), cx)
75    }
76}
77
78/// Zero-cost adapter exposing a [`futures_io`] stream as a Moirai async stream.
79#[derive(Debug)]
80pub struct ToMoiraiIo<S>(
81    /// The wrapped `futures_io` stream.
82    pub S,
83);
84
85impl<S: futures_io::AsyncRead + Unpin> MoiraiRead for ToMoiraiIo<S> {
86    #[inline]
87    fn poll_read(
88        self: Pin<&mut Self>,
89        cx: &mut Context<'_>,
90        buf: &mut [u8],
91    ) -> Poll<io::Result<usize>> {
92        futures_io::AsyncRead::poll_read(Pin::new(&mut self.get_mut().0), cx, buf)
93    }
94}
95
96impl<S: futures_io::AsyncWrite + Unpin> MoiraiWrite for ToMoiraiIo<S> {
97    #[inline]
98    fn poll_write(
99        self: Pin<&mut Self>,
100        cx: &mut Context<'_>,
101        buf: &[u8],
102    ) -> Poll<io::Result<usize>> {
103        futures_io::AsyncWrite::poll_write(Pin::new(&mut self.get_mut().0), cx, buf)
104    }
105
106    #[inline]
107    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
108        futures_io::AsyncWrite::poll_flush(Pin::new(&mut self.get_mut().0), cx)
109    }
110
111    #[inline]
112    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
113        futures_io::AsyncWrite::poll_close(Pin::new(&mut self.get_mut().0), cx)
114    }
115}
116
117/// A negotiated client-side TLS stream over a Moirai async socket `S`.
118///
119/// Implements Moirai's [`AsyncRead`](moirai_async::io::AsyncRead) and
120/// [`AsyncWrite`](moirai_async::io::AsyncWrite), so upper layers (HTTP) treat it
121/// exactly like a plaintext socket.
122pub type TlsStream<S> = ToMoiraiIo<futures_rustls::client::TlsStream<ToFuturesIo<S>>>;
123
124/// Client TLS connector wrapping a shared [`rustls::ClientConfig`].
125#[derive(Clone)]
126pub struct TlsConnector {
127    inner: RustlsConnector,
128}
129
130impl TlsConnector {
131    /// Build a connector from an existing `rustls` client configuration.
132    #[must_use]
133    pub fn from_config(config: Arc<ClientConfig>) -> Self {
134        Self {
135            inner: RustlsConnector::from(config),
136        }
137    }
138
139    /// Build a connector trusting the Mozilla root CA set ([`webpki_roots`]),
140    /// using the pure-Rust RustCrypto provider and safe default protocol versions.
141    /// No C toolchain dependency — all cryptography is implemented in Rust.
142    #[must_use]
143    pub fn with_webpki_roots() -> Self {
144        let mut roots = RootCertStore::empty();
145        roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
146        Self::from_config(Arc::new(client_config_with_roots(roots)))
147    }
148
149    /// Perform the TLS handshake over `stream`, validating the peer certificate
150    /// against `domain`. Returns a [`TlsStream`] exposing Moirai async I/O.
151    ///
152    /// # Errors
153    /// Propagates handshake, certificate-validation, and underlying socket errors.
154    pub async fn connect<S>(
155        &self,
156        domain: ServerName<'static>,
157        stream: S,
158    ) -> io::Result<TlsStream<S>>
159    where
160        S: MoiraiRead + MoiraiWrite + Unpin,
161    {
162        let raw = self.inner.connect(domain, ToFuturesIo(stream)).await?;
163        Ok(ToMoiraiIo(raw))
164    }
165}
166
167/// Construct a pure-Rust RustCrypto-backed [`ClientConfig`] with safe default
168/// protocol versions trusting `roots`. Uses [`moirai_crypto::provider`] instead
169/// of `ring` — zero C dependencies. Shared by [`TlsConnector::with_webpki_roots`]
170/// and tests that supply a custom root (self-signed) store.
171#[must_use]
172pub fn client_config_with_roots(roots: RootCertStore) -> ClientConfig {
173    ClientConfig::builder_with_provider(Arc::new(moirai_crypto::provider()))
174        .with_safe_default_protocol_versions()
175        .expect("moirai-crypto provider supports safe default protocol versions")
176        .with_root_certificates(roots)
177        .with_no_client_auth()
178}