ferrotunnel 1.5.0

A production-ready reverse tunnel system in Rust
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Configuration types for `FerroTunnel` client and server.
//!
//! These types provide type-safe configuration for embedding `FerroTunnel`
//! in your applications.
//!
//! Config fields are private; construct these types through
//! [`ClientBuilder`](crate::ClientBuilder) / [`ServerBuilder`](crate::ServerBuilder)
//! and read them back through the getters. This keeps the authentication token
//! out of derived `Debug` output and lets new fields be added without breaking
//! callers.

use ferrotunnel_common::{
    LimitsConfig, Result, TunnelError, DEFAULT_HTTP_PORT, DEFAULT_LOCAL_ADDR, DEFAULT_TUNNEL_PORT,
};
use ferrotunnel_core::validate_limits;
use std::fmt;
use std::net::SocketAddr;
#[cfg(feature = "http3")]
use std::path::Path;
#[cfg(feature = "http3")]
use std::path::PathBuf;
use std::time::Duration;

/// Placeholder shown in place of the authentication token in `Debug` output.
const REDACTED: &str = "<redacted>";

/// Configuration for the tunnel client.
///
/// Use [`ClientBuilder`](crate::ClientBuilder) for ergonomic construction, then
/// read values back through the getters. The `Debug` implementation redacts the
/// authentication token.
#[derive(Clone)]
pub struct ClientConfig {
    /// Server address to connect to (host:port)
    pub(crate) server_addr: String,

    /// Authentication token
    pub(crate) token: String,

    /// Local address to forward traffic to
    pub(crate) local_addr: String,

    /// Tunnel ID used for HTTP routing (matched against the Host header)
    pub(crate) tunnel_id: Option<String>,

    /// Enable automatic reconnection on disconnect
    pub(crate) auto_reconnect: bool,

    /// Delay between reconnection attempts
    pub(crate) reconnect_delay: Duration,

    /// Maximum time to wait for the initial connection in `start()`. `None` waits indefinitely. Default 30s.
    pub(crate) startup_timeout: Option<Duration>,

    /// Resource limits for protocol framing and connection handling.
    pub(crate) limits: LimitsConfig,
}

impl ClientConfig {
    /// Validate the configuration.
    pub fn validate(&self) -> Result<()> {
        if self.server_addr.is_empty() {
            return Err(TunnelError::Config("server_addr is required".into()));
        }
        if self.token.is_empty() {
            return Err(TunnelError::Config("token is required".into()));
        }
        if self.local_addr.is_empty() {
            return Err(TunnelError::Config("local_addr is required".into()));
        }
        validate_limits(&self.limits)?;
        Ok(())
    }

    /// Server address the client connects to (`host:port`).
    pub fn server_addr(&self) -> &str {
        &self.server_addr
    }

    /// Authentication token presented to the server.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Local address traffic is forwarded to.
    pub fn local_addr(&self) -> &str {
        &self.local_addr
    }

    /// Tunnel ID used for HTTP routing, if set.
    pub fn tunnel_id(&self) -> Option<&str> {
        self.tunnel_id.as_deref()
    }

    /// Whether automatic reconnection is enabled.
    pub fn auto_reconnect(&self) -> bool {
        self.auto_reconnect
    }

    /// Delay between reconnection attempts.
    pub fn reconnect_delay(&self) -> Duration {
        self.reconnect_delay
    }

    /// Maximum time `start()` waits for the initial connection. `None` waits indefinitely.
    pub fn startup_timeout(&self) -> Option<Duration> {
        self.startup_timeout
    }

    /// Resource limits for protocol framing and connection handling.
    pub fn limits(&self) -> &LimitsConfig {
        &self.limits
    }
}

impl fmt::Debug for ClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientConfig")
            .field("server_addr", &self.server_addr)
            .field("token", &REDACTED)
            .field("local_addr", &self.local_addr)
            .field("tunnel_id", &self.tunnel_id)
            .field("auto_reconnect", &self.auto_reconnect)
            .field("reconnect_delay", &self.reconnect_delay)
            .field("startup_timeout", &self.startup_timeout)
            .field("limits", &self.limits)
            .finish()
    }
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            server_addr: String::new(),
            token: String::new(),
            local_addr: DEFAULT_LOCAL_ADDR.to_string(),
            tunnel_id: None,
            auto_reconnect: true,
            reconnect_delay: Duration::from_secs(5),
            startup_timeout: Some(Duration::from_secs(30)),
            limits: LimitsConfig::default(),
        }
    }
}

/// Configuration for the tunnel server.
///
/// Use [`ServerBuilder`](crate::ServerBuilder) for ergonomic construction, then
/// read values back through the getters. The `Debug` implementation redacts the
/// authentication token.
#[derive(Clone)]
pub struct ServerConfig {
    /// Address to bind the tunnel control plane
    pub(crate) bind_addr: SocketAddr,

    /// Address to bind the HTTP ingress
    pub(crate) http_bind_addr: SocketAddr,

    /// Optional address to bind HTTP/3 ingress (UDP)
    #[cfg(feature = "http3")]
    pub(crate) http3_bind_addr: Option<SocketAddr>,

    /// Path to certificate file for HTTP/3 ingress
    #[cfg(feature = "http3")]
    pub(crate) http3_cert_path: Option<PathBuf>,

    /// Path to private key file for HTTP/3 ingress
    #[cfg(feature = "http3")]
    pub(crate) http3_key_path: Option<PathBuf>,

    /// Authentication token (clients must provide this)
    pub(crate) token: String,

    /// Resource limits for protocol framing and connection handling.
    pub(crate) limits: LimitsConfig,
}

impl ServerConfig {
    /// Validate the configuration.
    pub fn validate(&self) -> Result<()> {
        if self.token.is_empty() {
            return Err(TunnelError::Config("token is required".into()));
        }
        validate_limits(&self.limits)?;
        #[cfg(feature = "http3")]
        if self.http3_bind_addr.is_some()
            && (self.http3_cert_path.is_none() || self.http3_key_path.is_none())
        {
            return Err(TunnelError::Config(
                "HTTP/3 ingress requires certificate and key paths".into(),
            ));
        }
        Ok(())
    }

    /// Address the tunnel control plane binds to.
    pub fn bind_addr(&self) -> SocketAddr {
        self.bind_addr
    }

    /// Address the HTTP ingress binds to.
    pub fn http_bind_addr(&self) -> SocketAddr {
        self.http_bind_addr
    }

    /// Address the HTTP/3 ingress binds to, if configured.
    #[cfg(feature = "http3")]
    pub fn http3_bind_addr(&self) -> Option<SocketAddr> {
        self.http3_bind_addr
    }

    /// Certificate path for the HTTP/3 ingress, if configured.
    #[cfg(feature = "http3")]
    pub fn http3_cert_path(&self) -> Option<&Path> {
        self.http3_cert_path.as_deref()
    }

    /// Private-key path for the HTTP/3 ingress, if configured.
    #[cfg(feature = "http3")]
    pub fn http3_key_path(&self) -> Option<&Path> {
        self.http3_key_path.as_deref()
    }

    /// Authentication token clients must present.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Resource limits for protocol framing and connection handling.
    pub fn limits(&self) -> &LimitsConfig {
        &self.limits
    }
}

impl fmt::Debug for ServerConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("ServerConfig");
        debug
            .field("bind_addr", &self.bind_addr)
            .field("http_bind_addr", &self.http_bind_addr);
        #[cfg(feature = "http3")]
        debug
            .field("http3_bind_addr", &self.http3_bind_addr)
            .field("http3_cert_path", &self.http3_cert_path)
            .field("http3_key_path", &self.http3_key_path);
        debug
            .field("token", &REDACTED)
            .field("limits", &self.limits)
            .finish()
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            bind_addr: ([0, 0, 0, 0], DEFAULT_TUNNEL_PORT).into(),
            http_bind_addr: ([0, 0, 0, 0], DEFAULT_HTTP_PORT).into(),
            #[cfg(feature = "http3")]
            http3_bind_addr: None,
            #[cfg(feature = "http3")]
            http3_cert_path: None,
            #[cfg(feature = "http3")]
            http3_key_path: None,
            token: String::new(),
            limits: LimitsConfig::default(),
        }
    }
}

/// Information about an established tunnel connection.
///
/// Returned by `Client::start()`. Read the fields through the getters.
#[derive(Debug, Clone)]
pub struct TunnelInfo {
    /// The session ID assigned by the server.
    ///
    /// Currently a client-generated placeholder until the core library exposes
    /// the server-assigned session ID.
    pub(crate) session_id: Option<uuid::Uuid>,

    /// Reserved for the public URL where the tunnel is reachable.
    ///
    /// Not yet populated: `public_url()` currently always returns `None`. It is
    /// kept so callers can adopt the accessor before the value is wired up.
    pub(crate) public_url: Option<String>,
}

impl TunnelInfo {
    /// The session ID for the established tunnel, if assigned.
    pub fn session_id(&self) -> Option<uuid::Uuid> {
        self.session_id
    }

    /// The public URL where the tunnel is reachable.
    ///
    /// Reserved for future use; currently always `None`.
    pub fn public_url(&self) -> Option<&str> {
        self.public_url.as_deref()
    }
}

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

    #[test]
    fn test_client_config_default() {
        let config = ClientConfig::default();
        assert!(config.server_addr.is_empty());
        assert!(config.token.is_empty());
        assert_eq!(config.local_addr, "127.0.0.1:8080");
        assert!(config.auto_reconnect);
        assert_eq!(config.reconnect_delay, Duration::from_secs(5));
        assert_eq!(config.startup_timeout, Some(Duration::from_secs(30)));
        assert_eq!(config.limits.max_frame_bytes, 16 * 1024 * 1024);
    }

    #[test]
    fn test_client_config_validate_success() {
        let config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "secret-token".to_string(),
            local_addr: "127.0.0.1:8080".to_string(),
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_client_config_validate_rejects_zero_frame_limit() {
        let mut config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "secret-token".to_string(),
            local_addr: "127.0.0.1:8080".to_string(),
            ..Default::default()
        };
        config.limits.max_frame_bytes = 0;
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("max_frame_bytes"));
    }

    #[test]
    fn test_client_config_validate_rejects_oversized_frame_limit() {
        let mut config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "secret-token".to_string(),
            local_addr: "127.0.0.1:8080".to_string(),
            ..Default::default()
        };
        // Just above the protocol frame ceiling (16 MiB) is now rejected.
        config.limits.max_frame_bytes = 17 * 1024 * 1024;
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("max_frame_bytes"));
    }

    #[test]
    fn test_client_config_validate_missing_server_addr() {
        let config = ClientConfig {
            server_addr: String::new(),
            token: "secret".to_string(),
            local_addr: "127.0.0.1:8080".to_string(),
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("server_addr"));
    }

    #[test]
    fn test_client_config_validate_missing_token() {
        let config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: String::new(),
            local_addr: "127.0.0.1:8080".to_string(),
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("token"));
    }

    #[test]
    fn test_client_config_validate_missing_local_addr() {
        let config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "secret".to_string(),
            local_addr: String::new(),
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("local_addr"));
    }

    #[test]
    fn test_client_config_getters() {
        let config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "secret".to_string(),
            local_addr: "127.0.0.1:8080".to_string(),
            tunnel_id: Some("my-tunnel".to_string()),
            ..Default::default()
        };
        assert_eq!(config.server_addr(), "localhost:7835");
        assert_eq!(config.token(), "secret");
        assert_eq!(config.local_addr(), "127.0.0.1:8080");
        assert_eq!(config.tunnel_id(), Some("my-tunnel"));
        assert!(config.auto_reconnect());
        assert_eq!(config.reconnect_delay(), Duration::from_secs(5));
        assert_eq!(config.startup_timeout(), Some(Duration::from_secs(30)));
        assert_eq!(config.limits().max_frame_bytes, 16 * 1024 * 1024);
    }

    #[test]
    fn test_client_config_debug_redacts_token() {
        let config = ClientConfig {
            server_addr: "localhost:7835".to_string(),
            token: "super-secret-token".to_string(),
            ..Default::default()
        };
        let rendered = format!("{config:?}");
        assert!(!rendered.contains("super-secret-token"));
        assert!(rendered.contains("<redacted>"));
    }

    #[test]
    fn test_server_config_default() {
        let config = ServerConfig::default();
        assert_eq!(config.bind_addr, SocketAddr::from(([0, 0, 0, 0], 7835)));
        assert_eq!(
            config.http_bind_addr,
            SocketAddr::from(([0, 0, 0, 0], 8080))
        );
        assert!(config.token.is_empty());
        assert_eq!(config.limits.max_frame_bytes, 16 * 1024 * 1024);
    }

    #[test]
    fn test_server_config_validate_success() {
        let config = ServerConfig {
            token: "secret-token".to_string(),
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_server_config_validate_rejects_zero_frame_limit() {
        let mut config = ServerConfig {
            token: "secret-token".to_string(),
            ..Default::default()
        };
        config.limits.max_frame_bytes = 0;
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("max_frame_bytes"));
    }

    #[test]
    fn test_server_config_validate_rejects_oversized_frame_limit() {
        let mut config = ServerConfig {
            token: "secret-token".to_string(),
            ..Default::default()
        };
        // Just above the protocol frame ceiling (16 MiB) is now rejected.
        config.limits.max_frame_bytes = 17 * 1024 * 1024;
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("max_frame_bytes"));
    }

    #[test]
    fn test_server_config_validate_missing_token() {
        let config = ServerConfig::default();
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("token"));
    }

    #[test]
    fn test_server_config_getters() {
        let config = ServerConfig {
            token: "secret".to_string(),
            ..Default::default()
        };
        assert_eq!(config.bind_addr(), SocketAddr::from(([0, 0, 0, 0], 7835)));
        assert_eq!(
            config.http_bind_addr(),
            SocketAddr::from(([0, 0, 0, 0], 8080))
        );
        assert_eq!(config.token(), "secret");
        assert_eq!(config.limits().max_frame_bytes, 16 * 1024 * 1024);
    }

    #[test]
    fn test_server_config_debug_redacts_token() {
        let config = ServerConfig {
            token: "super-secret-token".to_string(),
            ..Default::default()
        };
        let rendered = format!("{config:?}");
        assert!(!rendered.contains("super-secret-token"));
        assert!(rendered.contains("<redacted>"));
    }

    #[test]
    fn test_tunnel_info_none_values() {
        let info = TunnelInfo {
            session_id: None,
            public_url: None,
        };
        assert!(info.session_id().is_none());
        assert!(info.public_url().is_none());
    }

    #[test]
    fn test_tunnel_info_with_values() {
        let uuid = uuid::Uuid::new_v4();
        let info = TunnelInfo {
            session_id: Some(uuid),
            public_url: Some("https://tunnel.example.com".to_string()),
        };
        assert_eq!(info.session_id(), Some(uuid));
        assert_eq!(info.public_url(), Some("https://tunnel.example.com"));
    }
}