Skip to main content

trillium_rustls/
server.rs

1use crate::crypto_provider;
2use futures_rustls::{
3    TlsAcceptor,
4    rustls::{
5        ServerConfig, ServerConnection,
6        pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
7    },
8    server::TlsStream,
9};
10use std::{
11    borrow::Cow,
12    fmt::{Debug, Formatter},
13    io,
14    pin::Pin,
15    sync::Arc,
16    task::{Context, Poll},
17};
18use trillium_server_common::{Acceptor, AsyncRead, AsyncWrite, Transport};
19
20/// trillium [`Acceptor`] for Rustls
21
22#[derive(Clone)]
23pub struct RustlsAcceptor(TlsAcceptor);
24impl Debug for RustlsAcceptor {
25    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
26        f.debug_tuple("Rustls").field(&"<<TlsAcceptor>>").finish()
27    }
28}
29
30impl RustlsAcceptor {
31    /// build a new RustlsAcceptor from a [`ServerConfig`] or a [`TlsAcceptor`]
32    pub fn new(t: impl Into<Self>) -> Self {
33        t.into()
34    }
35
36    /// build a new RustlsAcceptor from a cert chain (pem) and private key.
37    ///
38    /// See
39    /// [`ConfigBuilder::with_single_cert`][`crate::rustls::ConfigBuilder::with_single_cert`]
40    /// for accepted formats. If you need to customize the
41    /// [`ServerConfig`], use ServerConfig's `Into<RustlsAcceptor>`, eg
42    ///
43    /// ```rust,no_run
44    /// use trillium_rustls::{RustlsAcceptor, rustls::ServerConfig};
45    /// # use trillium_rustls::rustls::pki_types::{PrivateKeyDer, pem::PemObject};
46    /// # let certs = vec![];
47    /// # let private_key = PrivateKeyDer::from_pem_slice(b"").unwrap();
48    /// let rustls_acceptor: RustlsAcceptor = ServerConfig::builder()
49    ///     .with_no_client_auth()
50    ///     .with_single_cert(certs, private_key)
51    ///     .expect("could not build rustls ServerConfig")
52    ///     .into();
53    /// ```
54    ///
55    /// # Example
56    ///
57    /// ```rust,no_run
58    /// use trillium_rustls::RustlsAcceptor;
59    /// const KEY: &[u8] = include_bytes!("../examples/key.pem");
60    /// const CERT: &[u8] = include_bytes!("../examples/cert.pem");
61    /// let rustls_acceptor = RustlsAcceptor::from_single_cert(CERT, KEY);
62    /// ```
63    pub fn from_single_cert(cert: &[u8], key: &[u8]) -> Self {
64        Self::single_cert_with_alpn(cert, key, vec![b"h2".to_vec(), b"http/1.1".to_vec()])
65    }
66
67    /// build a [`RustlsAcceptor`] from a cert chain + private key that advertises only
68    /// `http/1.1` via ALPN, opting out of HTTP/2.
69    ///
70    /// This exists as a separate constructor because [`futures_rustls::TlsAcceptor`] does
71    /// not expose its inner [`ServerConfig`] for post-construction mutation. Callers needing
72    /// finer control should construct a [`ServerConfig`] directly and use its `Into`
73    /// conversion.
74    pub fn from_single_cert_no_h2(cert: &[u8], key: &[u8]) -> Self {
75        Self::single_cert_with_alpn(cert, key, vec![b"http/1.1".to_vec()])
76    }
77
78    fn single_cert_with_alpn(cert: &[u8], key: &[u8], alpn_protocols: Vec<Vec<u8>>) -> Self {
79        let cert_chain = CertificateDer::pem_slice_iter(cert)
80            .collect::<Result<_, _>>()
81            .expect("could not read certificate");
82
83        let key_der =
84            PrivateKeyDer::from_pem_slice(key).expect("could not read a private key from `key`");
85
86        let mut config = ServerConfig::builder_with_provider(crypto_provider())
87            .with_safe_default_protocol_versions()
88            .expect("crypto provider did not support safe default protocol versions")
89            .with_no_client_auth()
90            .with_single_cert(cert_chain, key_der)
91            .expect("could not create a rustls ServerConfig from the supplied cert and key");
92        config.alpn_protocols = alpn_protocols;
93        config.into()
94    }
95}
96
97impl From<ServerConfig> for RustlsAcceptor {
98    fn from(sc: ServerConfig) -> Self {
99        Self(Arc::new(sc).into())
100    }
101}
102
103impl From<TlsAcceptor> for RustlsAcceptor {
104    fn from(ta: TlsAcceptor) -> Self {
105        Self(ta)
106    }
107}
108
109/// Transport for rustls server acceptor
110#[derive(Debug)]
111pub struct RustlsServerTransport<T>(TlsStream<T>);
112
113impl<T: AsyncRead + AsyncWrite + Unpin> AsyncRead for RustlsServerTransport<T> {
114    fn poll_read(
115        mut self: Pin<&mut Self>,
116        cx: &mut Context<'_>,
117        buf: &mut [u8],
118    ) -> Poll<io::Result<usize>> {
119        Pin::new(&mut self.0).poll_read(cx, buf)
120    }
121}
122
123impl<T: AsyncWrite + AsyncRead + Unpin> AsyncWrite for RustlsServerTransport<T> {
124    fn poll_write(
125        mut self: Pin<&mut Self>,
126        cx: &mut Context<'_>,
127        buf: &[u8],
128    ) -> Poll<io::Result<usize>> {
129        Pin::new(&mut self.0).poll_write(cx, buf)
130    }
131
132    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
133        Pin::new(&mut self.0).poll_flush(cx)
134    }
135
136    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
137        Pin::new(&mut self.0).poll_close(cx)
138    }
139
140    fn poll_write_vectored(
141        mut self: Pin<&mut Self>,
142        cx: &mut Context<'_>,
143        bufs: &[io::IoSlice<'_>],
144    ) -> Poll<io::Result<usize>> {
145        Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
146    }
147}
148
149impl<T: Transport> Transport for RustlsServerTransport<T> {
150    fn peer_addr(&self) -> io::Result<Option<std::net::SocketAddr>> {
151        self.inner_transport().peer_addr()
152    }
153
154    fn negotiated_alpn(&self) -> Option<Cow<'_, [u8]>> {
155        self.as_ref().alpn_protocol().map(Cow::Borrowed)
156    }
157}
158
159impl<T> RustlsServerTransport<T> {
160    /// access the contained transport type (eg TcpStream)
161    pub fn inner_transport(&self) -> &T {
162        self.0.get_ref().0
163    }
164
165    /// mutably access the contained transport type (eg TcpStream)
166    pub fn inner_transport_mut(&mut self) -> &mut T {
167        self.0.get_mut().0
168    }
169}
170
171impl<T> AsRef<ServerConnection> for RustlsServerTransport<T> {
172    fn as_ref(&self) -> &ServerConnection {
173        self.0.get_ref().1
174    }
175}
176
177impl<T> AsMut<ServerConnection> for RustlsServerTransport<T> {
178    fn as_mut(&mut self) -> &mut ServerConnection {
179        self.0.get_mut().1
180    }
181}
182
183impl<T> From<TlsStream<T>> for RustlsServerTransport<T> {
184    fn from(value: TlsStream<T>) -> Self {
185        Self(value)
186    }
187}
188
189impl<T> From<RustlsServerTransport<T>> for TlsStream<T> {
190    fn from(RustlsServerTransport(value): RustlsServerTransport<T>) -> Self {
191        value
192    }
193}
194
195impl<Input> Acceptor<Input> for RustlsAcceptor
196where
197    Input: Transport,
198{
199    type Error = io::Error;
200    type Output = RustlsServerTransport<Input>;
201
202    async fn accept(&self, input: Input) -> Result<Self::Output, Self::Error> {
203        self.0.accept(input).await.map(RustlsServerTransport)
204    }
205}