deepslate 0.3.1

A high-performance Minecraft server proxy written 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Configuration loaded from environment variables or a builder API.

use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;

use thiserror::Error;

/// Errors returned when building proxy configuration.
#[derive(Debug, Error)]
pub enum ConfigError {
    /// A socket address could not be parsed.
    #[error(transparent)]
    AddrParse(#[from] std::net::AddrParseError),
    /// A numeric value could not be parsed.
    #[error(transparent)]
    ParseInt(#[from] std::num::ParseIntError),
    /// A required environment variable was missing.
    #[error("required environment variable {0} is not set")]
    MissingEnv(&'static str),
    /// An environment variable contained an invalid boolean value.
    #[error("invalid boolean for {key}: {value}")]
    InvalidBool {
        /// The environment variable name.
        key: &'static str,
        /// The invalid value.
        value: String,
    },
    /// The forwarding secret file could not be read.
    #[error("failed to read forwarding secret from {path}")]
    SecretFileRead {
        /// The path that was attempted.
        path: String,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The configured forwarding secret is empty.
    #[error("forwarding secret must not be empty")]
    MissingForwardingSecret,
    /// The configured compression level is invalid.
    #[error("invalid compression level {0}: must be 0-12")]
    InvalidCompressionLevel(i32),
    /// A connection limit was set to zero.
    #[error("{0} must be greater than zero")]
    InvalidConnectionLimit(&'static str),
}

/// Proxy configuration.
#[derive(Debug, Clone)]
pub struct Config {
    /// Address the proxy listens on for Minecraft clients.
    pub listen_addr: SocketAddr,
    /// Address the gRPC control plane listens on.
    #[cfg(feature = "grpc")]
    pub grpc_addr: SocketAddr,
    /// Optional bearer token for gRPC control plane authentication.
    ///
    /// When set, every gRPC request must include an `authorization: Bearer <token>`
    /// metadata header. When `None`, the control plane accepts unauthenticated
    /// requests.
    #[cfg(feature = "grpc")]
    pub grpc_auth_token: Option<String>,
    /// Whether online-mode (Mojang authentication) is enabled.
    pub online_mode: bool,
    /// HMAC secret for Velocity modern forwarding.
    pub forwarding_secret: Vec<u8>,
    /// Compression threshold in bytes (-1 to disable).
    pub compression_threshold: i32,
    /// Zlib compression level (0-12, where 1 is fastest and 12 is best).
    pub compression_level: i32,
    /// MOTD shown in the server list.
    pub motd: String,
    /// Maximum player count shown in the server list.
    pub max_players: i32,
    /// Read timeout for client and backend connections.
    pub read_timeout: Duration,
    /// Backend connection timeout.
    ///
    /// Limits how long the proxy waits for a TCP connection to a backend
    /// server. Without this, a firewall silently dropping SYN packets can
    /// block for the OS TCP timeout (typically 75–120 s on Linux).
    pub connect_timeout: Duration,
    /// Maximum number of concurrent connections the proxy will accept.
    ///
    /// When this limit is reached, new connections are immediately dropped.
    pub max_connections: u32,
    /// Maximum number of concurrent connections allowed from a single IP address.
    ///
    /// When this limit is reached for a given IP, additional connections from
    /// that IP are immediately dropped.
    pub max_connections_per_ip: u32,
    /// Ordered list of server IDs to try for initial connections.
    pub try_servers: Vec<String>,
    /// Map of hostnames to ordered server ID lists for forced-host routing.
    ///
    /// When a player connects using a hostname that matches a key in this map,
    /// the proxy tries the associated servers (in order) instead of the global
    /// [`try_servers`](Config::try_servers) list. Only applies to the initial
    /// connection, not server switches.
    pub forced_hosts: HashMap<String, Vec<String>>,
    /// Log level filter string.
    pub log_level: String,
    /// Whether to output logs as JSON.
    pub log_json: bool,
    /// How long to wait for active connections to drain on shutdown.
    pub shutdown_drain: Duration,
    /// Address the Prometheus metrics exporter listens on.
    #[cfg(feature = "metrics")]
    pub metrics_addr: SocketAddr,
}

impl Config {
    /// Load configuration from environment variables.
    ///
    /// # Errors
    ///
    /// Returns an error if a required variable is missing or a value is invalid.
    pub fn from_env() -> Result<Self, ConfigError> {
        let listen_addr = env_or("DEEPSLATE_ADDR", "0.0.0.0:25565").parse()?;
        #[cfg(feature = "grpc")]
        let grpc_addr = env_or("DEEPSLATE_GRPC_ADDR", "127.0.0.1:25577").parse()?;
        #[cfg(feature = "grpc")]
        let grpc_auth_token = grpc_auth_token_from_env()?;
        let online_mode = env_bool("DEEPSLATE_ONLINE_MODE", true)?;
        let forwarding_secret = forwarding_secret_from_env()?;
        let compression_threshold = env_or("DEEPSLATE_COMPRESSION_THRESHOLD", "256").parse()?;
        let compression_level: i32 = env_or("DEEPSLATE_COMPRESSION_LEVEL", "1").parse()?;
        let motd = env_or("DEEPSLATE_MOTD", "A Deepslate Proxy");
        let max_players = env_or("DEEPSLATE_MAX_PLAYERS", "500").parse()?;
        let read_timeout_ms: u64 = env_or("DEEPSLATE_READ_TIMEOUT_MS", "30000").parse()?;
        let connect_timeout_ms: u64 = env_or("DEEPSLATE_CONNECT_TIMEOUT_MS", "5000").parse()?;
        let max_connections = env_or("DEEPSLATE_MAX_CONNECTIONS", "10000").parse()?;
        let max_connections_per_ip = env_or("DEEPSLATE_MAX_CONNECTIONS_PER_IP", "3").parse()?;
        let try_servers = env_or("DEEPSLATE_TRY_SERVERS", "")
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect();
        let forced_hosts = parse_forced_hosts(&env_or("DEEPSLATE_FORCED_HOSTS", ""));
        let log_level = env_or("DEEPSLATE_LOG_LEVEL", "info");
        let log_json = env_bool("DEEPSLATE_LOG_JSON", false)?;
        let shutdown_drain_ms: u64 = env_or("DEEPSLATE_SHUTDOWN_DRAIN_MS", "10000").parse()?;
        #[cfg(feature = "metrics")]
        let metrics_addr = env_or("DEEPSLATE_METRICS_ADDR", "127.0.0.1:9100").parse()?;

        Self {
            listen_addr,
            #[cfg(feature = "grpc")]
            grpc_addr,
            #[cfg(feature = "grpc")]
            grpc_auth_token,
            online_mode,
            forwarding_secret,
            compression_threshold,
            compression_level,
            motd,
            max_players,
            read_timeout: Duration::from_millis(read_timeout_ms),
            connect_timeout: Duration::from_millis(connect_timeout_ms),
            max_connections,
            max_connections_per_ip,
            try_servers,
            forced_hosts,
            log_level,
            log_json,
            shutdown_drain: Duration::from_millis(shutdown_drain_ms),
            #[cfg(feature = "metrics")]
            metrics_addr,
        }
        .validate()
    }

    /// Validate the configuration and return it unchanged on success.
    ///
    /// # Errors
    ///
    /// Returns an error if any field contains an unsupported value.
    pub fn validate(self) -> Result<Self, ConfigError> {
        if self.forwarding_secret.is_empty() {
            return Err(ConfigError::MissingForwardingSecret);
        }

        if !(0..=12).contains(&self.compression_level) {
            return Err(ConfigError::InvalidCompressionLevel(self.compression_level));
        }

        if self.max_connections == 0 {
            return Err(ConfigError::InvalidConnectionLimit(
                "DEEPSLATE_MAX_CONNECTIONS",
            ));
        }

        if self.max_connections_per_ip == 0 {
            return Err(ConfigError::InvalidConnectionLimit(
                "DEEPSLATE_MAX_CONNECTIONS_PER_IP",
            ));
        }

        Ok(self)
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            listen_addr: SocketAddr::from((Ipv4Addr::UNSPECIFIED, 25_565)),
            #[cfg(feature = "grpc")]
            grpc_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 25_577)),
            #[cfg(feature = "grpc")]
            grpc_auth_token: None,
            online_mode: true,
            forwarding_secret: Vec::new(),
            compression_threshold: 256,
            compression_level: 1,
            motd: "A Deepslate Proxy".to_string(),
            max_players: 500,
            read_timeout: Duration::from_secs(30),
            connect_timeout: Duration::from_secs(5),
            max_connections: 10_000,
            max_connections_per_ip: 3,
            try_servers: vec![],
            forced_hosts: HashMap::new(),
            log_level: "info".to_string(),
            log_json: false,
            shutdown_drain: Duration::from_secs(10),
            #[cfg(feature = "metrics")]
            metrics_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 9100)),
        }
    }
}

/// Read an environment variable or return a default.
fn env_or(key: &str, default: &str) -> String {
    std::env::var(key).unwrap_or_else(|_| default.to_string())
}

/// Read a required environment variable.
fn env_required(key: &'static str) -> Result<String, ConfigError> {
    std::env::var(key).map_err(|_| ConfigError::MissingEnv(key))
}

/// Parse a boolean environment variable (accepts true/false/1/0, case-insensitive).
fn env_bool(key: &'static str, default: bool) -> Result<bool, ConfigError> {
    std::env::var(key).map_or_else(
        |_| Ok(default),
        |val| match val.to_lowercase().as_str() {
            "true" | "1" => Ok(true),
            "false" | "0" => Ok(false),
            _ => Err(ConfigError::InvalidBool { key, value: val }),
        },
    )
}

/// Parse a forced-hosts string into a hostname-to-server-list map.
///
/// Expected format: `host1=srv1,srv2;host2=srv3,srv4`.
/// Entries are separated by `;`, and server IDs within an entry by `,`.
/// Hostnames are lowercased for case-insensitive matching.
/// Whitespace around delimiters is trimmed.
/// Empty entries (no `=`) and entries with no server IDs are silently ignored.
fn parse_forced_hosts(raw: &str) -> HashMap<String, Vec<String>> {
    let mut map = HashMap::new();
    for entry in raw.split(';') {
        let entry = entry.trim();
        if entry.is_empty() {
            continue;
        }
        let Some((host, servers_raw)) = entry.split_once('=') else {
            continue;
        };
        let host = host.trim().to_lowercase();
        if host.is_empty() {
            continue;
        }
        let servers: Vec<String> = servers_raw
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect();
        if !servers.is_empty() {
            map.insert(host, servers);
        }
    }
    map
}

/// Load the Velocity forwarding secret.
///
/// Checks `DEEPSLATE_FORWARDING_SECRET_FILE` first — if set, the secret is
/// read from the file at that path (trailing newlines are stripped).  Otherwise
/// falls back to reading the value of `DEEPSLATE_FORWARDING_SECRET` directly.
///
/// When both variables are set, the file variant takes precedence following
/// the Docker / Kubernetes secrets convention.
fn forwarding_secret_from_env() -> Result<Vec<u8>, ConfigError> {
    if let Ok(path) = std::env::var("DEEPSLATE_FORWARDING_SECRET_FILE") {
        let path = path.trim().to_owned();
        let contents =
            std::fs::read(&path).map_err(|source| ConfigError::SecretFileRead { path, source })?;
        Ok(contents
            .strip_suffix(b"\r\n")
            .or_else(|| contents.strip_suffix(b"\n"))
            .unwrap_or(&contents)
            .to_vec())
    } else {
        env_required("DEEPSLATE_FORWARDING_SECRET").map(String::into_bytes)
    }
}

/// Load the optional gRPC authentication token.
///
/// Checks `DEEPSLATE_GRPC_AUTH_TOKEN_FILE` first — if set, the token is read
/// from the file at that path (trailing newlines are stripped). Otherwise falls
/// back to reading `DEEPSLATE_GRPC_AUTH_TOKEN` directly. Returns `None` when
/// neither variable is set.
#[cfg(feature = "grpc")]
fn grpc_auth_token_from_env() -> Result<Option<String>, ConfigError> {
    if let Ok(path) = std::env::var("DEEPSLATE_GRPC_AUTH_TOKEN_FILE") {
        let path = path.trim().to_owned();
        let contents =
            std::fs::read(&path).map_err(|source| ConfigError::SecretFileRead { path, source })?;
        let token = contents
            .strip_suffix(b"\r\n")
            .or_else(|| contents.strip_suffix(b"\n"))
            .unwrap_or(&contents);
        let token = String::from_utf8_lossy(token).into_owned();
        if token.is_empty() {
            Ok(None)
        } else {
            Ok(Some(token))
        }
    } else if let Ok(val) = std::env::var("DEEPSLATE_GRPC_AUTH_TOKEN") {
        let val = val.trim().to_owned();
        if val.is_empty() {
            Ok(None)
        } else {
            Ok(Some(val))
        }
    } else {
        Ok(None)
    }
}

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

    const FILE_VAR: &str = "DEEPSLATE_FORWARDING_SECRET_FILE";
    const ENV_VAR: &str = "DEEPSLATE_FORWARDING_SECRET";

    #[test]
    fn secret_from_env_var() {
        temp_env::with_vars([(ENV_VAR, Some("my-secret")), (FILE_VAR, None)], || {
            let secret = forwarding_secret_from_env().unwrap();
            assert_eq!(secret, b"my-secret");
        });
    }

    #[test]
    fn secret_from_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret");
        std::fs::write(&path, b"file-secret").unwrap();

        temp_env::with_vars(
            [
                (FILE_VAR, Some(path.to_str().unwrap())),
                (ENV_VAR, None::<&str>),
            ],
            || {
                let secret = forwarding_secret_from_env().unwrap();
                assert_eq!(secret, b"file-secret");
            },
        );
    }

    #[test]
    fn secret_file_trims_trailing_lf() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret");
        std::fs::write(&path, b"file-secret\n").unwrap();

        temp_env::with_vars(
            [
                (FILE_VAR, Some(path.to_str().unwrap())),
                (ENV_VAR, None::<&str>),
            ],
            || {
                let secret = forwarding_secret_from_env().unwrap();
                assert_eq!(secret, b"file-secret");
            },
        );
    }

    #[test]
    fn secret_file_trims_trailing_crlf() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret");
        std::fs::write(&path, b"file-secret\r\n").unwrap();

        temp_env::with_vars(
            [
                (FILE_VAR, Some(path.to_str().unwrap())),
                (ENV_VAR, None::<&str>),
            ],
            || {
                let secret = forwarding_secret_from_env().unwrap();
                assert_eq!(secret, b"file-secret");
            },
        );
    }

    #[test]
    fn secret_file_takes_precedence() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret");
        std::fs::write(&path, b"from-file").unwrap();

        temp_env::with_vars(
            [
                (FILE_VAR, Some(path.to_str().unwrap())),
                (ENV_VAR, Some("from-env")),
            ],
            || {
                let secret = forwarding_secret_from_env().unwrap();
                assert_eq!(secret, b"from-file");
            },
        );
    }

    #[test]
    fn secret_file_missing_returns_error() {
        temp_env::with_vars(
            [(FILE_VAR, Some("/no/such/file")), (ENV_VAR, None::<&str>)],
            || {
                let err = forwarding_secret_from_env().unwrap_err();
                assert!(
                    matches!(err, ConfigError::SecretFileRead { .. }),
                    "expected SecretFileRead, got {err:?}"
                );
            },
        );
    }

    #[test]
    fn secret_neither_set_returns_error() {
        temp_env::with_vars([(ENV_VAR, None::<&str>), (FILE_VAR, None::<&str>)], || {
            let err = forwarding_secret_from_env().unwrap_err();
            assert!(
                matches!(err, ConfigError::MissingEnv(_)),
                "expected MissingEnv, got {err:?}"
            );
        });
    }

    #[test]
    fn parse_forced_hosts_single_entry() {
        let map = parse_forced_hosts("pvp.example.com=pvp,pvp-fallback");
        assert_eq!(
            map.get("pvp.example.com").unwrap(),
            &["pvp", "pvp-fallback"]
        );
    }

    #[test]
    fn parse_forced_hosts_multiple_entries() {
        let map = parse_forced_hosts("pvp.example.com=pvp;lobby.example.com=lobby1,lobby2");
        assert_eq!(map.len(), 2);
        assert_eq!(map.get("pvp.example.com").unwrap(), &["pvp"]);
        assert_eq!(map.get("lobby.example.com").unwrap(), &["lobby1", "lobby2"]);
    }

    #[test]
    fn parse_forced_hosts_trims_whitespace() {
        let map = parse_forced_hosts(" pvp.example.com = pvp , games ; lobby.example.com = lobby ");
        assert_eq!(map.get("pvp.example.com").unwrap(), &["pvp", "games"]);
        assert_eq!(map.get("lobby.example.com").unwrap(), &["lobby"]);
    }

    #[test]
    fn parse_forced_hosts_lowercases_hostname() {
        let map = parse_forced_hosts("PVP.Example.COM=pvp");
        assert!(map.contains_key("pvp.example.com"));
        assert!(!map.contains_key("PVP.Example.COM"));
    }

    #[test]
    fn parse_forced_hosts_empty_string() {
        let map = parse_forced_hosts("");
        assert!(map.is_empty());
    }

    #[test]
    fn parse_forced_hosts_skips_malformed() {
        let map = parse_forced_hosts("no-equals;also-bad;good.host=srv");
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("good.host").unwrap(), &["srv"]);
    }

    #[test]
    fn parse_forced_hosts_skips_empty_server_list() {
        let map = parse_forced_hosts("empty.host=;good.host=srv");
        assert_eq!(map.len(), 1);
        assert!(!map.contains_key("empty.host"));
    }

    #[test]
    fn validate_rejects_zero_max_connections() {
        let config = Config {
            forwarding_secret: b"secret".to_vec(),
            max_connections: 0,
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        assert!(
            matches!(err, ConfigError::InvalidConnectionLimit(_)),
            "expected InvalidConnectionLimit, got {err:?}"
        );
    }

    #[test]
    fn validate_rejects_zero_max_connections_per_ip() {
        let config = Config {
            forwarding_secret: b"secret".to_vec(),
            max_connections_per_ip: 0,
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        assert!(
            matches!(err, ConfigError::InvalidConnectionLimit(_)),
            "expected InvalidConnectionLimit, got {err:?}"
        );
    }

    #[test]
    fn validate_accepts_valid_connection_limits() {
        let config = Config {
            forwarding_secret: b"secret".to_vec(),
            max_connections: 5000,
            max_connections_per_ip: 10,
            ..Config::default()
        };
        assert!(config.validate().is_ok());
    }
}