Skip to main content

karyon_net/layers/
tls.rs

1use std::{
2    io,
3    net::{IpAddr, Ipv4Addr},
4    pin::Pin,
5    sync::Arc,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10use rustls_pki_types::{self as pki_types, CertificateDer};
11
12use karyon_core::{
13    async_runtime::io::{AsyncRead, AsyncWrite},
14    async_util::timeout,
15};
16
17#[cfg(feature = "tokio")]
18use tokio::io::ReadBuf;
19
20use crate::{
21    ACCEPT_HANDSHAKE_TIMEOUT, Addr, ByteStream, Endpoint, Error, Result,
22    async_rustls::{TlsAcceptor, TlsConnector, TlsStream, rustls},
23    layer::{ClientLayer, ServerLayer},
24    transports::tcp::TcpListener,
25};
26
27/// TLS client config.
28#[derive(Clone)]
29pub struct ClientTlsConfig {
30    pub client_config: rustls::ClientConfig,
31    pub dns_name: String,
32}
33
34/// TLS server config.
35#[derive(Clone)]
36pub struct ServerTlsConfig {
37    pub server_config: rustls::ServerConfig,
38}
39
40/// TLS middleware layer. Implements both `ClientLayer` and `ServerLayer`.
41///
42/// Wraps any `ByteStream` with TLS encryption.
43///
44/// # Example
45///
46/// ```no_run
47/// use karyon_net::{tcp, ClientLayer, Endpoint};
48/// use karyon_net::tls::{TlsLayer, ClientTlsConfig};
49///
50/// async {
51///     let ep: Endpoint = "tcp://127.0.0.1:443".parse().unwrap();
52///     let stream = tcp::connect(&ep, Default::default()).await.unwrap();
53///     // let tls_stream = ClientLayer::handshake(
54///     //     &TlsLayer::client(config), stream
55///     // ).await.unwrap();
56/// };
57/// ```
58#[derive(Clone)]
59pub struct TlsLayer {
60    client_config: Option<ClientTlsConfig>,
61    server_config: Option<ServerTlsConfig>,
62}
63
64impl TlsLayer {
65    /// Create a TLS layer for client connections.
66    pub fn client(config: ClientTlsConfig) -> Self {
67        Self {
68            client_config: Some(config),
69            server_config: None,
70        }
71    }
72
73    /// Create a TLS layer for server connections.
74    pub fn server(config: ServerTlsConfig) -> Self {
75        Self {
76            client_config: None,
77            server_config: Some(config),
78        }
79    }
80}
81
82impl ClientLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for TlsLayer {
83    async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
84        let config = self.client_config.as_ref().ok_or_else(|| {
85            Error::IO(io::Error::new(
86                io::ErrorKind::InvalidInput,
87                "missing TLS client config",
88            ))
89        })?;
90
91        let connector = TlsConnector::from(Arc::new(config.client_config.clone()));
92        let dns = pki_types::ServerName::try_from(config.dns_name.clone())?;
93
94        let peer = stream.peer_endpoint();
95        let local = stream.local_endpoint();
96        let tls = connector.connect(dns, stream).await?;
97
98        Ok(Box::new(TlsByteStream {
99            inner: TlsStream::Client(tls),
100            peer_endpoint: peer,
101            local_endpoint: local,
102        }))
103    }
104}
105
106impl ServerLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for TlsLayer {
107    async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
108        let config = self.server_config.as_ref().ok_or_else(|| {
109            Error::IO(io::Error::new(
110                io::ErrorKind::InvalidInput,
111                "missing TLS server config",
112            ))
113        })?;
114
115        let acceptor = TlsAcceptor::from(Arc::new(config.server_config.clone()));
116
117        let peer = stream.peer_endpoint();
118        let local = stream.local_endpoint();
119        let tls = acceptor.accept(stream).await?;
120
121        Ok(Box::new(TlsByteStream {
122            inner: TlsStream::Server(tls),
123            peer_endpoint: peer,
124            local_endpoint: local,
125        }))
126    }
127}
128
129/// TLS stream wrapping any `ByteStream`.
130pub struct TlsByteStream {
131    inner: TlsStream<Box<dyn ByteStream>>,
132    peer_endpoint: Option<Endpoint>,
133    local_endpoint: Option<Endpoint>,
134}
135
136impl ByteStream for TlsByteStream {
137    fn peer_endpoint(&self) -> Option<Endpoint> {
138        self.peer_endpoint.clone()
139    }
140    fn local_endpoint(&self) -> Option<Endpoint> {
141        self.local_endpoint.clone()
142    }
143    fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
144        // TlsStream::get_ref() exposes the rustls connection state;
145        // peer_certificates() returns whatever the peer presented during
146        // the handshake (if any).
147        let (_, state) = self.inner.get_ref();
148        state
149            .peer_certificates()
150            .map(|certs| certs.iter().map(|c| c.clone().into_owned()).collect())
151    }
152}
153
154// -- AsyncRead / AsyncWrite delegation --
155
156#[cfg(feature = "smol")]
157impl AsyncRead for TlsByteStream {
158    fn poll_read(
159        mut self: Pin<&mut Self>,
160        cx: &mut Context<'_>,
161        buf: &mut [u8],
162    ) -> Poll<io::Result<usize>> {
163        Pin::new(&mut self.inner).poll_read(cx, buf)
164    }
165}
166
167#[cfg(feature = "tokio")]
168impl AsyncRead for TlsByteStream {
169    fn poll_read(
170        mut self: Pin<&mut Self>,
171        cx: &mut Context<'_>,
172        buf: &mut ReadBuf<'_>,
173    ) -> Poll<io::Result<()>> {
174        Pin::new(&mut self.inner).poll_read(cx, buf)
175    }
176}
177
178#[cfg(feature = "smol")]
179impl AsyncWrite for TlsByteStream {
180    fn poll_write(
181        mut self: Pin<&mut Self>,
182        cx: &mut Context<'_>,
183        buf: &[u8],
184    ) -> Poll<io::Result<usize>> {
185        Pin::new(&mut self.inner).poll_write(cx, buf)
186    }
187
188    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
189        Pin::new(&mut self.inner).poll_flush(cx)
190    }
191
192    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
193        Pin::new(&mut self.inner).poll_close(cx)
194    }
195}
196
197#[cfg(feature = "tokio")]
198impl AsyncWrite for TlsByteStream {
199    fn poll_write(
200        mut self: Pin<&mut Self>,
201        cx: &mut Context<'_>,
202        buf: &[u8],
203    ) -> Poll<io::Result<usize>> {
204        Pin::new(&mut self.inner).poll_write(cx, buf)
205    }
206
207    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
208        Pin::new(&mut self.inner).poll_flush(cx)
209    }
210
211    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
212        Pin::new(&mut self.inner).poll_shutdown(cx)
213    }
214}
215
216/// TLS listener. Wraps a TCP listener with TLS acceptance.
217pub struct TlsListener {
218    inner: TcpListener,
219    layer: TlsLayer,
220    /// Max time `accept` waits for a handshake.
221    handshake_timeout: Duration,
222}
223
224impl TlsListener {
225    /// Create a TLS listener from a TCP listener and TLS config.
226    pub fn new(inner: TcpListener, config: ServerTlsConfig) -> Self {
227        Self {
228            inner,
229            layer: TlsLayer::server(config),
230            handshake_timeout: ACCEPT_HANDSHAKE_TIMEOUT,
231        }
232    }
233
234    /// Set the max time `accept` waits for a handshake. Defaults to 10s.
235    pub fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
236        self.handshake_timeout = timeout;
237        self
238    }
239
240    /// Accept a new TLS connection. The handshake runs inline and fails
241    /// after the handshake timeout (10s by default), so a slow client
242    /// stalls a plain accept loop for up to that long. Servers should accept on a `TcpListener` and run
243    /// `TlsLayer::handshake` in a separate task instead.
244    pub async fn accept(&self) -> Result<Box<dyn ByteStream>> {
245        let stream = self.inner.accept().await?;
246        timeout(
247            self.handshake_timeout,
248            ServerLayer::handshake(&self.layer, stream),
249        )
250        .await?
251    }
252
253    /// Local endpoint this listener is bound to.
254    pub fn local_endpoint(&self) -> Result<Endpoint> {
255        let tcp_ep = self.inner.local_endpoint()?;
256        let port = tcp_ep.port().unwrap_or(0);
257        let addr = tcp_ep
258            .addr()
259            .unwrap_or(Addr::Ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED)));
260        Ok(Endpoint::Tls(addr, port))
261    }
262}