-
Notifications
You must be signed in to change notification settings - Fork 550
/
Copy pathconfig.rs
493 lines (435 loc) · 13.8 KB
/
config.rs
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
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use std::path::Path;
use tokio::fs;
use url::Url;
use crate::transport::{DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_KEEPALIVE_SECS, DEFAULT_NODELAY};
/// Application-layer heartbeat interval in secs
const DEFAULT_HEARTBEAT_INTERVAL_SECS: u64 = 30;
const DEFAULT_HEARTBEAT_TIMEOUT_SECS: u64 = 40;
/// Client
const DEFAULT_CLIENT_RETRY_INTERVAL_SECS: u64 = 1;
/// String with Debug implementation that emits "MASKED"
/// Used to mask sensitive strings when logging
#[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone)]
pub struct MaskedString(String);
impl Debug for MaskedString {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
f.write_str("MASKED")
}
}
impl Deref for MaskedString {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<&str> for MaskedString {
fn from(s: &str) -> MaskedString {
MaskedString(String::from(s))
}
}
#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Default)]
pub enum TransportType {
#[default]
#[serde(rename = "tcp")]
Tcp,
#[serde(rename = "tls")]
Tls,
#[serde(rename = "noise")]
Noise,
#[serde(rename = "websocket")]
Websocket,
}
/// Per service config
/// All Option are optional in configuration but must be Some value in runtime
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct ClientServiceConfig {
#[serde(rename = "type", default = "default_service_type")]
pub service_type: ServiceType,
#[serde(skip)]
pub name: String,
pub local_addr: String,
pub token: Option<MaskedString>,
pub nodelay: Option<bool>,
pub retry_interval: Option<u64>,
}
impl ClientServiceConfig {
pub fn with_name(name: &str) -> ClientServiceConfig {
ClientServiceConfig {
name: name.to_string(),
..Default::default()
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
pub enum ServiceType {
#[serde(rename = "tcp")]
#[default]
Tcp,
#[serde(rename = "udp")]
Udp,
}
fn default_service_type() -> ServiceType {
Default::default()
}
/// Per service config
/// All Option are optional in configuration but must be Some value in runtime
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct ServerServiceConfig {
#[serde(rename = "type", default = "default_service_type")]
pub service_type: ServiceType,
#[serde(skip)]
pub name: String,
pub bind_addr: String,
pub token: Option<MaskedString>,
pub nodelay: Option<bool>,
}
impl ServerServiceConfig {
pub fn with_name(name: &str) -> ServerServiceConfig {
ServerServiceConfig {
name: name.to_string(),
..Default::default()
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct TlsConfig {
pub hostname: Option<String>,
pub trusted_root: Option<String>,
pub pkcs12: Option<String>,
pub pkcs12_password: Option<MaskedString>,
}
fn default_noise_pattern() -> String {
String::from("Noise_NK_25519_ChaChaPoly_BLAKE2s")
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct NoiseConfig {
#[serde(default = "default_noise_pattern")]
pub pattern: String,
pub local_private_key: Option<MaskedString>,
pub remote_public_key: Option<String>,
// TODO: Maybe psk can be added
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct WebsocketConfig {
pub tls: bool,
}
fn default_nodelay() -> bool {
DEFAULT_NODELAY
}
fn default_keepalive_secs() -> u64 {
DEFAULT_KEEPALIVE_SECS
}
fn default_keepalive_interval() -> u64 {
DEFAULT_KEEPALIVE_INTERVAL
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct TcpConfig {
#[serde(default = "default_nodelay")]
pub nodelay: bool,
#[serde(default = "default_keepalive_secs")]
pub keepalive_secs: u64,
#[serde(default = "default_keepalive_interval")]
pub keepalive_interval: u64,
pub proxy: Option<Url>,
}
impl Default for TcpConfig {
fn default() -> Self {
Self {
nodelay: default_nodelay(),
keepalive_secs: default_keepalive_secs(),
keepalive_interval: default_keepalive_interval(),
proxy: None,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
#[serde(deny_unknown_fields)]
pub struct TransportConfig {
#[serde(rename = "type")]
pub transport_type: TransportType,
#[serde(default)]
pub tcp: TcpConfig,
pub tls: Option<TlsConfig>,
pub noise: Option<NoiseConfig>,
pub websocket: Option<WebsocketConfig>,
}
fn default_heartbeat_timeout() -> u64 {
DEFAULT_HEARTBEAT_TIMEOUT_SECS
}
fn default_client_retry_interval() -> u64 {
DEFAULT_CLIENT_RETRY_INTERVAL_SECS
}
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
pub struct ClientConfig {
pub remote_addr: String,
pub default_token: Option<MaskedString>,
pub services: HashMap<String, ClientServiceConfig>,
#[serde(default)]
pub transport: TransportConfig,
#[serde(default = "default_heartbeat_timeout")]
pub heartbeat_timeout: u64,
#[serde(default = "default_client_retry_interval")]
pub retry_interval: u64,
}
fn default_heartbeat_interval() -> u64 {
DEFAULT_HEARTBEAT_INTERVAL_SECS
}
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
pub bind_addr: String,
pub default_token: Option<MaskedString>,
pub services: HashMap<String, ServerServiceConfig>,
#[serde(default)]
pub transport: TransportConfig,
#[serde(default = "default_heartbeat_interval")]
pub heartbeat_interval: u64,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub server: Option<ServerConfig>,
pub client: Option<ClientConfig>,
}
impl Config {
fn from_str(s: &str) -> Result<Config> {
let mut config: Config = toml::from_str(s).with_context(|| "Failed to parse the config")?;
if let Some(server) = config.server.as_mut() {
Config::validate_server_config(server)?;
}
if let Some(client) = config.client.as_mut() {
Config::validate_client_config(client)?;
}
if config.server.is_none() && config.client.is_none() {
Err(anyhow!("Neither of `[server]` or `[client]` is defined"))
} else {
Ok(config)
}
}
fn validate_server_config(server: &mut ServerConfig) -> Result<()> {
// Validate services
for (name, s) in &mut server.services {
s.name.clone_from(name);
if s.token.is_none() {
s.token.clone_from(&server.default_token);
if s.token.is_none() {
bail!("The token of service {} is not set", name);
}
}
}
Config::validate_transport_config(&server.transport, true)?;
Ok(())
}
fn validate_client_config(client: &mut ClientConfig) -> Result<()> {
// Validate services
for (name, s) in &mut client.services {
s.name.clone_from(name);
if s.token.is_none() {
s.token.clone_from(&client.default_token);
if s.token.is_none() {
bail!("The token of service {} is not set", name);
}
}
if s.retry_interval.is_none() {
s.retry_interval = Some(client.retry_interval);
}
}
Config::validate_transport_config(&client.transport, false)?;
Ok(())
}
fn validate_transport_config(config: &TransportConfig, is_server: bool) -> Result<()> {
config
.tcp
.proxy
.as_ref()
.map_or(Ok(()), |u| match u.scheme() {
"socks5" => Ok(()),
"http" => Ok(()),
_ => Err(anyhow!(format!("Unknown proxy scheme: {}", u.scheme()))),
})?;
match config.transport_type {
TransportType::Tcp => Ok(()),
TransportType::Tls => {
let tls_config = config
.tls
.as_ref()
.ok_or_else(|| anyhow!("Missing TLS configuration"))?;
if is_server {
tls_config
.pkcs12
.as_ref()
.and(tls_config.pkcs12_password.as_ref())
.ok_or_else(|| anyhow!("Missing `pkcs12` or `pkcs12_password`"))?;
}
Ok(())
}
TransportType::Noise => {
// The check is done in transport
Ok(())
}
TransportType::Websocket => Ok(()),
}
}
pub async fn from_file(path: &Path) -> Result<Config> {
let s: String = fs::read_to_string(path)
.await
.with_context(|| format!("Failed to read the config {:?}", path))?;
Config::from_str(&s).with_context(|| {
"Configuration is invalid. Please refer to the configuration specification."
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs, path::PathBuf};
use anyhow::Result;
fn list_config_files<T: AsRef<Path>>(root: T) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
files.push(path);
} else if path.is_dir() {
files.append(&mut list_config_files(path)?);
}
}
Ok(files)
}
fn get_all_example_config() -> Result<Vec<PathBuf>> {
Ok(list_config_files("./examples")?
.into_iter()
.filter(|x| x.ends_with(".toml"))
.collect())
}
#[test]
fn test_example_config() -> Result<()> {
let paths = get_all_example_config()?;
for p in paths {
let s = fs::read_to_string(p)?;
Config::from_str(&s)?;
}
Ok(())
}
#[test]
fn test_valid_config() -> Result<()> {
let paths = list_config_files("tests/config_test/valid_config")?;
for p in paths {
let s = fs::read_to_string(p)?;
Config::from_str(&s)?;
}
Ok(())
}
#[test]
fn test_invalid_config() -> Result<()> {
let paths = list_config_files("tests/config_test/invalid_config")?;
for p in paths {
let s = fs::read_to_string(p)?;
assert!(Config::from_str(&s).is_err());
}
Ok(())
}
#[test]
fn test_validate_server_config() -> Result<()> {
let mut cfg = ServerConfig::default();
cfg.services.insert(
"foo1".into(),
ServerServiceConfig {
service_type: ServiceType::Tcp,
name: "foo1".into(),
bind_addr: "127.0.0.1:80".into(),
token: None,
..Default::default()
},
);
// Missing the token
assert!(Config::validate_server_config(&mut cfg).is_err());
// Use the default token
cfg.default_token = Some("123".into());
assert!(Config::validate_server_config(&mut cfg).is_ok());
assert_eq!(
cfg.services
.get("foo1")
.as_ref()
.unwrap()
.token
.as_ref()
.unwrap()
.0,
"123"
);
// The default token won't override the service token
cfg.services.get_mut("foo1").unwrap().token = Some("4".into());
assert!(Config::validate_server_config(&mut cfg).is_ok());
assert_eq!(
cfg.services
.get("foo1")
.as_ref()
.unwrap()
.token
.as_ref()
.unwrap()
.0,
"4"
);
Ok(())
}
#[test]
fn test_validate_client_config() -> Result<()> {
let mut cfg = ClientConfig::default();
cfg.services.insert(
"foo1".into(),
ClientServiceConfig {
service_type: ServiceType::Tcp,
name: "foo1".into(),
local_addr: "127.0.0.1:80".into(),
token: None,
..Default::default()
},
);
// Missing the token
assert!(Config::validate_client_config(&mut cfg).is_err());
// Use the default token
cfg.default_token = Some("123".into());
assert!(Config::validate_client_config(&mut cfg).is_ok());
assert_eq!(
cfg.services
.get("foo1")
.as_ref()
.unwrap()
.token
.as_ref()
.unwrap()
.0,
"123"
);
// The default token won't override the service token
cfg.services.get_mut("foo1").unwrap().token = Some("4".into());
assert!(Config::validate_client_config(&mut cfg).is_ok());
assert_eq!(
cfg.services
.get("foo1")
.as_ref()
.unwrap()
.token
.as_ref()
.unwrap()
.0,
"4"
);
Ok(())
}
}