deepslate 0.2.0

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
//! 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),
}

/// 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,
    /// 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 in milliseconds.
    pub read_timeout_ms: u64,
    /// 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,
}

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", "0.0.0.0:25577").parse()?;
        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 = env_or("DEEPSLATE_READ_TIMEOUT", "30000").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()?;

        Self {
            listen_addr,
            #[cfg(feature = "grpc")]
            grpc_addr,
            online_mode,
            forwarding_secret,
            compression_threshold,
            compression_level,
            motd,
            max_players,
            read_timeout_ms,
            try_servers,
            forced_hosts,
            log_level,
            log_json,
            shutdown_drain: Duration::from_millis(shutdown_drain_ms),
        }
        .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));
        }

        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::UNSPECIFIED, 25_577)),
            online_mode: true,
            forwarding_secret: Vec::new(),
            compression_threshold: 256,
            compression_level: 1,
            motd: "A Deepslate Proxy".to_string(),
            max_players: 500,
            read_timeout_ms: 30_000,
            try_servers: vec![],
            forced_hosts: HashMap::new(),
            log_level: "info".to_string(),
            log_json: false,
            shutdown_drain: Duration::from_secs(10),
        }
    }
}

/// 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)
    }
}

#[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"));
    }
}