stream-tungstenite 0.6.1

A streaming implementation of the Tungstenite WebSocket protocol
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
//! WebSocket connector - establishes WebSocket connections over transports.

use async_trait::async_trait;
use futures_util::{Sink, Stream};
use std::fmt::Debug;
use tokio::net::TcpStream;
use tokio_tungstenite::{
    client_async_tls_with_config, Connector as TlsConnector, MaybeTlsStream, WebSocketStream,
};
use tungstenite::client::IntoClientRequest;
use tungstenite::handshake::client::Response;
use tungstenite::protocol::WebSocketConfig;
use tungstenite::Message;

use crate::error::ConnectError;
use crate::transport::Transport;

/// Type alias for the default WebSocket stream type
pub type DefaultWsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;

/// WebSocket stream trait - abstraction over different stream types
pub trait WsStream:
    Stream<Item = Result<Message, tungstenite::Error>>
    + Sink<Message, Error = tungstenite::Error>
    + Unpin
    + Send
    + 'static
{
}

impl<T> WsStream for T where
    T: Stream<Item = Result<Message, tungstenite::Error>>
        + Sink<Message, Error = tungstenite::Error>
        + Unpin
        + Send
        + 'static
{
}

/// Connector trait - responsible for establishing WebSocket connections
#[async_trait]
pub trait Connector: Send + Sync + 'static {
    /// The WebSocket stream type produced by this connector
    type Stream: WsStream;

    /// Connect to the given URI and return a WebSocket stream
    async fn connect(&self, uri: &str) -> Result<(Self::Stream, Response), ConnectError>;

    /// Get the connector name (for logging/debugging)
    fn name(&self) -> &'static str {
        "connector"
    }
}

/// Default WebSocket connector using TLS transport
#[derive(Clone)]
pub struct DefaultConnector {
    /// WebSocket protocol configuration
    ws_config: Option<WebSocketConfig>,
    /// Whether to disable Nagle's algorithm
    disable_nagle: bool,
    /// TLS connector configuration
    tls_connector: Option<TlsConnector>,
}

// Manual Debug implementation since TlsConnector doesn't implement Debug
impl Debug for DefaultConnector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DefaultConnector")
            .field("ws_config", &self.ws_config)
            .field("disable_nagle", &self.disable_nagle)
            .field("tls_connector", &self.tls_connector.is_some())
            .finish()
    }
}

impl DefaultConnector {
    /// Create a new default connector with system default TLS configuration
    #[must_use]
    pub const fn new() -> Self {
        Self {
            ws_config: None,
            disable_nagle: false,
            tls_connector: None,
        }
    }

    /// Set WebSocket configuration
    #[must_use]
    pub const fn with_ws_config(mut self, config: WebSocketConfig) -> Self {
        self.ws_config = Some(config);
        self
    }

    /// Disable Nagle's algorithm (`TCP_NODELAY`)
    #[must_use]
    pub const fn with_nodelay(mut self, nodelay: bool) -> Self {
        self.disable_nagle = nodelay;
        self
    }

    /// Set custom TLS connector
    ///
    /// This allows full control over TLS configuration including:
    /// - Custom CA certificates
    /// - Client certificate authentication
    /// - Certificate verification policies
    /// - Protocol version constraints
    ///
    /// # Example
    /// ```no_run
    /// # use stream_tungstenite::connection::DefaultConnector;
    /// # #[cfg(feature = "native-tls")]
    /// # {
    /// use tokio_tungstenite::Connector;
    /// use native_tls::TlsConnector as NativeTlsConnector;
    ///
    /// let tls = NativeTlsConnector::builder()
    ///     .danger_accept_invalid_certs(true) // For testing only!
    ///     .build()
    ///     .unwrap();
    ///
    /// let connector = DefaultConnector::new()
    ///     .with_tls_connector(Connector::NativeTls(tls));
    /// # }
    /// ```
    #[must_use]
    pub fn with_tls_connector(mut self, connector: TlsConnector) -> Self {
        self.tls_connector = Some(connector);
        self
    }

    /// Create a connector optimized for low latency
    #[must_use]
    pub fn low_latency() -> Self {
        Self {
            ws_config: Some(
                WebSocketConfig::default()
                    .max_message_size(Some(64 << 20)) // 64 MB
                    .max_frame_size(Some(16 << 20)), // 16 MB
            ),
            disable_nagle: true,
            tls_connector: None,
        }
    }

    // === Convenience methods for common TLS configurations ===

    /// Disable certificate verification (DANGEROUS - use only for testing!)
    ///
    /// This creates a TLS connector that accepts any certificate, including:
    /// - Self-signed certificates
    /// - Expired certificates
    /// - Certificates with wrong hostname
    ///
    /// # Security Warning
    /// This makes your connection vulnerable to man-in-the-middle attacks.
    /// **NEVER use this in production!**
    ///
    /// # Example
    /// ```no_run
    /// # use stream_tungstenite::connection::DefaultConnector;
    /// let connector = DefaultConnector::new()
    ///     .danger_accept_invalid_certs()
    ///     .expect("Failed to create insecure connector");
    /// ```
    #[cfg(all(feature = "native-tls", not(feature = "__rustls-tls")))]
    pub fn danger_accept_invalid_certs(mut self) -> Result<Self, ConnectError> {
        use native_tls::TlsConnector as NativeTlsConnector;

        let tls = NativeTlsConnector::builder()
            .danger_accept_invalid_certs(true)
            .danger_accept_invalid_hostnames(true)
            .build()
            .map_err(|e| {
                ConnectError::Tls(format!("Failed to build insecure TLS connector: {e}"))
            })?;

        self.tls_connector = Some(TlsConnector::NativeTls(tls));
        Ok(self)
    }

    /// Disable certificate verification using rustls (DANGEROUS - use only for testing!)
    ///
    /// # Security Warning
    /// This makes your connection vulnerable to man-in-the-middle attacks.
    /// **NEVER use this in production!**
    #[cfg(feature = "__rustls-tls")]
    pub fn danger_accept_invalid_certs(mut self) -> Result<Self, ConnectError> {
        use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerifier};
        use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
        use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
        use std::sync::Arc;

        #[derive(Debug)]
        struct NoVerifier;

        impl ServerCertVerifier for NoVerifier {
            fn verify_server_cert(
                &self,
                _end_entity: &CertificateDer<'_>,
                _intermediates: &[CertificateDer<'_>],
                _server_name: &ServerName<'_>,
                _ocsp_response: &[u8],
                _now: UnixTime,
            ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
                Ok(rustls::client::danger::ServerCertVerified::assertion())
            }

            fn verify_tls12_signature(
                &self,
                _message: &[u8],
                _cert: &CertificateDer<'_>,
                _dss: &DigitallySignedStruct,
            ) -> Result<HandshakeSignatureValid, rustls::Error> {
                Ok(HandshakeSignatureValid::assertion())
            }

            fn verify_tls13_signature(
                &self,
                _message: &[u8],
                _cert: &CertificateDer<'_>,
                _dss: &DigitallySignedStruct,
            ) -> Result<HandshakeSignatureValid, rustls::Error> {
                Ok(HandshakeSignatureValid::assertion())
            }

            fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
                vec![
                    SignatureScheme::RSA_PKCS1_SHA256,
                    SignatureScheme::RSA_PKCS1_SHA384,
                    SignatureScheme::RSA_PKCS1_SHA512,
                    SignatureScheme::ECDSA_NISTP256_SHA256,
                    SignatureScheme::ECDSA_NISTP384_SHA384,
                    SignatureScheme::ECDSA_NISTP521_SHA512,
                    SignatureScheme::RSA_PSS_SHA256,
                    SignatureScheme::RSA_PSS_SHA384,
                    SignatureScheme::RSA_PSS_SHA512,
                    SignatureScheme::ED25519,
                ]
            }
        }

        let mut config = ClientConfig::builder()
            .dangerous()
            .with_custom_certificate_verifier(Arc::new(NoVerifier))
            .with_no_client_auth();

        config.alpn_protocols = vec![b"http/1.1".to_vec()];

        self.tls_connector = Some(TlsConnector::Rustls(Arc::new(config)));
        Ok(self)
    }

    /// Add a custom CA certificate to trust
    ///
    /// This is useful when connecting to servers with self-signed certificates
    /// or internal CAs.
    ///
    /// # Example
    /// ```no_run
    /// # use stream_tungstenite::connection::DefaultConnector;
    /// # #[cfg(feature = "native-tls")]
    /// # {
    /// use native_tls::Certificate;
    /// use std::fs;
    ///
    /// let ca_cert = fs::read("ca-cert.pem").unwrap();
    /// let cert = Certificate::from_pem(&ca_cert).unwrap();
    ///
    /// let connector = DefaultConnector::new()
    ///     .with_custom_ca_cert(cert)
    ///     .expect("Failed to add CA cert");
    /// # }
    /// ```
    #[cfg(feature = "native-tls")]
    pub fn with_custom_ca_cert(
        mut self,
        cert: native_tls::Certificate,
    ) -> Result<Self, ConnectError> {
        use native_tls::TlsConnector as NativeTlsConnector;

        let tls = NativeTlsConnector::builder()
            .add_root_certificate(cert)
            .build()
            .map_err(|e| {
                ConnectError::Tls(format!("Failed to build TLS connector with custom CA: {e}"))
            })?;

        self.tls_connector = Some(TlsConnector::NativeTls(tls));
        Ok(self)
    }

    /// Configure client certificate authentication
    ///
    /// This is required when the server uses mutual TLS (mTLS) authentication.
    ///
    /// # Example
    /// ```no_run
    /// # use stream_tungstenite::connection::DefaultConnector;
    /// # #[cfg(feature = "native-tls")]
    /// # {
    /// use native_tls::Identity;
    /// use std::fs;
    ///
    /// let pkcs12 = fs::read("client-cert.p12").unwrap();
    /// let identity = Identity::from_pkcs12(&pkcs12, "password").unwrap();
    ///
    /// let connector = DefaultConnector::new()
    ///     .with_client_identity(identity)
    ///     .expect("Failed to configure client cert");
    /// # }
    /// ```
    #[cfg(feature = "native-tls")]
    pub fn with_client_identity(
        mut self,
        identity: native_tls::Identity,
    ) -> Result<Self, ConnectError> {
        use native_tls::TlsConnector as NativeTlsConnector;

        let tls = NativeTlsConnector::builder()
            .identity(identity)
            .build()
            .map_err(|e| {
                ConnectError::Tls(format!(
                    "Failed to build TLS connector with client identity: {e}"
                ))
            })?;

        self.tls_connector = Some(TlsConnector::NativeTls(tls));
        Ok(self)
    }
}

impl Default for DefaultConnector {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Connector for DefaultConnector {
    type Stream = DefaultWsStream;

    async fn connect(&self, uri: &str) -> Result<(Self::Stream, Response), ConnectError> {
        // Parse the URI and create request
        let request = uri
            .into_client_request()
            .map_err(|e| ConnectError::InvalidUri(format!("Failed to parse URI '{uri}': {e}")))?;

        // Extract host and port
        let host = request
            .uri()
            .host()
            .ok_or_else(|| ConnectError::InvalidUri("No host in URI".into()))?;

        let port = request
            .uri()
            .port_u16()
            .unwrap_or_else(|| match request.uri().scheme_str() {
                Some("wss") => 443,
                _ => 80,
            });

        let addr = format!("{host}:{port}");

        // Establish TCP connection
        let socket = TcpStream::connect(&addr).await.map_err(|e| {
            tracing::debug!(addr = %addr, error = ?e, "TCP connection failed");
            ConnectError::TcpConnect(e.to_string())
        })?;

        // Apply socket options
        if self.disable_nagle {
            socket
                .set_nodelay(true)
                .map_err(|e| ConnectError::Io(format!("Failed to set TCP_NODELAY: {e}")))?;
        }

        // Perform WebSocket upgrade (with TLS if wss://)
        let (ws_stream, response) = client_async_tls_with_config(
            request,
            socket,
            self.ws_config,
            self.tls_connector.clone(),
        )
        .await
        .map_err(|e| {
            tracing::debug!(uri = %uri, error = ?e, "WebSocket connection failed");
            ConnectError::WebSocketUpgrade(e.to_string())
        })?;

        tracing::debug!(uri = %uri, "WebSocket connection established");
        Ok((ws_stream, response))
    }

    fn name(&self) -> &'static str {
        "default"
    }
}

/// Connector that wraps a Transport implementation
#[derive(Debug, Clone)]
pub struct TransportConnector<T: Transport> {
    #[allow(dead_code)]
    transport: T,
    ws_config: Option<WebSocketConfig>,
}

impl<T: Transport> TransportConnector<T> {
    /// Create a new connector with the given transport
    #[must_use]
    pub const fn new(transport: T) -> Self {
        Self {
            transport,
            ws_config: None,
        }
    }

    /// Set WebSocket configuration
    #[must_use]
    pub const fn with_ws_config(mut self, config: WebSocketConfig) -> Self {
        self.ws_config = Some(config);
        self
    }
}

/// Connection info returned after successful connection
#[derive(Debug, Clone)]
pub struct ConnectionInfo {
    /// The URI connected to
    pub uri: String,
    /// HTTP response from the WebSocket upgrade
    pub response_status: u16,
    /// Response headers (selected)
    pub response_headers: Vec<(String, String)>,
}

impl ConnectionInfo {
    /// Create connection info from response
    #[must_use]
    pub fn from_response(uri: &str, response: &Response) -> Self {
        let headers = response
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
            .collect();

        Self {
            uri: uri.to_string(),
            response_status: response.status().as_u16(),
            response_headers: headers,
        }
    }
}

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

    #[test]
    fn test_default_connector_creation() {
        let connector = DefaultConnector::new();
        assert_eq!(connector.name(), "default");
    }

    #[test]
    fn test_low_latency_connector() {
        let connector = DefaultConnector::low_latency();
        assert!(connector.disable_nagle);
        assert!(connector.ws_config.is_some());
    }
}