lazydns 0.3.20

A light and fast DNS server/forwarder implementation 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
//! Configuration validation
//!
//! Validates configuration values for correctness and consistency.

use crate::config::Config;
use crate::{Error, Result};
use serde_yaml::Value;
use std::net::SocketAddr;

/// Valid port range (1-65535, 0 is reserved)
const MIN_PORT: u16 = 1;

/// Valid TTL range (0-2147483647, max i32)
const MAX_TTL: u32 = i32::MAX as u32;

/// Reasonable timeout range (1-3600 seconds)
const MIN_TIMEOUT_SECS: u64 = 1;
const MAX_TIMEOUT_SECS: u64 = 3600;

/// Reasonable rate limit range
const MIN_RATE_LIMIT: u32 = 1;
const MAX_RATE_LIMIT: u32 = 1_000_000;

/// Reasonable window range (1-86400 seconds = 1 day)
const MIN_WINDOW_SECS: u64 = 1;
const MAX_WINDOW_SECS: u64 = 86400;

/// Validate a configuration
///
/// Checks that all configuration values are valid and consistent.
///
/// # Arguments
///
/// * `config` - The configuration to validate
///
/// # Errors
///
/// Returns an error if validation fails.
pub fn validate_config(config: &Config) -> Result<()> {
    // Validate logging configuration
    validate_log_level(&config.log.level)?;
    validate_log_format(&config.log.format)?;
    // Rotation is now validated via serde/RotationTrigger enum

    // Validate admin and monitoring addresses
    validate_socket_addr(&config.admin.addr, "admin")?;
    validate_socket_addr(&config.monitoring.addr, "monitoring")?;

    // Validate plugins
    validate_plugins(&config.plugins)?;

    Ok(())
}

/// Validate log level
fn validate_log_level(level: &str) -> Result<()> {
    let valid_levels = ["trace", "debug", "info", "warn", "error"];

    if !valid_levels.contains(&level) {
        return Err(Error::Config(format!(
            "Invalid log level '{}'. Must be one of: {}",
            level,
            valid_levels.join(", ")
        )));
    }

    Ok(())
}

fn validate_log_format(format: &str) -> Result<()> {
    let valid = ["text", "json"];
    if !valid.contains(&format) {
        return Err(Error::Config(format!(
            "Invalid log format '{}'. Must be one of: {}",
            format,
            valid.join(", ")
        )));
    }
    Ok(())
}

/// Validate plugins
fn validate_plugins(plugins: &[crate::config::PluginConfig]) -> Result<()> {
    // Check for duplicate plugin names
    let mut names = std::collections::HashSet::new();

    for plugin in plugins {
        let name = plugin.effective_name();

        if !names.insert(name) {
            return Err(Error::Config(format!("Duplicate plugin name: '{}'", name)));
        }
    }

    // Validate plugin types are not empty
    for plugin in plugins {
        if plugin.plugin_type.is_empty() {
            return Err(Error::Config("Plugin type cannot be empty".to_string()));
        }

        // Validate plugin-specific numeric parameters
        validate_plugin_args(&plugin.plugin_type, &plugin.effective_args())?;
    }

    Ok(())
}

/// Validate socket address format
fn validate_socket_addr(addr: &str, context: &str) -> Result<()> {
    // Normalize address format:
    // ":port" -> "0.0.0.0:port" (IPv4 wildcard)
    // "::port" -> "[::]:port" (IPv6 wildcard)
    // "::1:port" -> "[::1]:port" (IPv6 loopback with port)
    let normalized_addr = if let Some(port) = addr.strip_prefix(":::") {
        // ":::port" -> "[::]:port" (IPv6 wildcard)
        format!("[::]:{}", port)
    } else if let Some(rest) = addr.strip_prefix("::") {
        // Check if it's "::" followed by IPv6 address and port (such as "::1:8080")
        // or just "::port" (such as "::8080")
        if let Some(last_colon) = rest.rfind(':') {
            if last_colon > 0 {
                // Has more than just "" after "::" before the last colon
                // Check if everything after the last colon is a valid port number
                if rest[last_colon + 1..].parse::<u16>().is_ok() {
                    // It's an IPv6 address with port (such as "::1:8080")
                    let ip_part = &rest[..last_colon];
                    let port_part = &rest[last_colon + 1..];
                    format!("[::{}]:{}", ip_part, port_part)
                } else {
                    // Not a port number, treat as plain IPv6 address
                    addr.to_string()
                }
            } else {
                // "::port" format -> "[::]:port"
                format!("[::]:{}", rest)
            }
        } else if rest.parse::<u16>().is_ok() {
            // No colon in rest, but rest is a valid port number (such as "::8080")
            // This is IPv6 wildcard shorthand: "::port" -> "[::]:port"
            format!("[::]:{}", rest)
        } else {
            // Just "::" without port, or something else
            addr.to_string()
        }
    } else if addr.starts_with(':') && !addr.starts_with("::[") {
        // ":port" -> "0.0.0.0:port" (IPv4 wildcard)
        format!("0.0.0.0{}", addr)
    } else {
        addr.to_string()
    };

    let socket_addr = normalized_addr
        .parse::<SocketAddr>()
        .map_err(|e| Error::Config(format!("Invalid {} address '{}': {}", context, addr, e)))?;

    // Validate port range (port 0 is reserved)
    let port = socket_addr.port();
    if port < MIN_PORT {
        return Err(Error::Config(format!(
            "Invalid {} port {}: must be at least {}",
            context, port, MIN_PORT
        )));
    }

    Ok(())
}

/// Validate plugin-specific arguments
fn validate_plugin_args(
    plugin_type: &str,
    args: &std::collections::HashMap<String, Value>,
) -> Result<()> {
    match plugin_type {
        "rate_limit" | "ratelimit" => {
            validate_u32_range(args, "max_queries", MIN_RATE_LIMIT, MAX_RATE_LIMIT, false)?;
            validate_u64_range(args, "window_secs", MIN_WINDOW_SECS, MAX_WINDOW_SECS, false)?;
        }
        "ttl" => {
            validate_u32_range(args, "fix", 0, MAX_TTL, true)?;
            validate_u32_range(args, "min", 0, MAX_TTL, true)?;
            validate_u32_range(args, "max", 0, MAX_TTL, true)?;
        }
        "downloader" => {
            validate_u64_range(
                args,
                "timeout_secs",
                MIN_TIMEOUT_SECS,
                MAX_TIMEOUT_SECS,
                true,
            )?;
            validate_u64_range(args, "retry_delay_secs", 0, MAX_TIMEOUT_SECS, true)?;
            validate_usize_range(args, "max_retries", 0, 100, true)?;
        }
        "cache" => {
            validate_usize_range(args, "size", 1, usize::MAX, true)?;
            validate_u32_range(args, "negative_ttl", 0, MAX_TTL, true)?;
        }
        "forward" => {
            validate_u64_range(args, "timeout", MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS, true)?;
            validate_usize_range(args, "concurrent", 1, 1000, true)?;
        }
        _ => {
            // For unknown plugin types, skip specific validation
        }
    }

    Ok(())
}

/// Validate u32 value in range
fn validate_u32_range(
    args: &std::collections::HashMap<String, Value>,
    key: &str,
    min: u32,
    max: u32,
    optional: bool,
) -> Result<()> {
    if let Some(value) = args.get(key) {
        let val = extract_u32(value, key)?;
        if val < min || val > max {
            return Err(Error::Config(format!(
                "Parameter '{}' must be between {} and {}, got {}",
                key, min, max, val
            )));
        }
    } else if !optional {
        return Err(Error::Config(format!(
            "Required parameter '{}' is missing",
            key
        )));
    }
    Ok(())
}

/// Validate u64 value in range
fn validate_u64_range(
    args: &std::collections::HashMap<String, Value>,
    key: &str,
    min: u64,
    max: u64,
    optional: bool,
) -> Result<()> {
    if let Some(value) = args.get(key) {
        let val = extract_u64(value, key)?;
        if val < min || val > max {
            return Err(Error::Config(format!(
                "Parameter '{}' must be between {} and {}, got {}",
                key, min, max, val
            )));
        }
    } else if !optional {
        return Err(Error::Config(format!(
            "Required parameter '{}' is missing",
            key
        )));
    }
    Ok(())
}

/// Validate usize value in range
fn validate_usize_range(
    args: &std::collections::HashMap<String, Value>,
    key: &str,
    min: usize,
    max: usize,
    optional: bool,
) -> Result<()> {
    if let Some(value) = args.get(key) {
        let val = extract_usize(value, key)?;
        if val < min || val > max {
            return Err(Error::Config(format!(
                "Parameter '{}' must be between {} and {}, got {}",
                key, min, max, val
            )));
        }
    } else if !optional {
        return Err(Error::Config(format!(
            "Required parameter '{}' is missing",
            key
        )));
    }
    Ok(())
}

/// Extract u32 from YAML value
fn extract_u32(value: &Value, key: &str) -> Result<u32> {
    match value {
        Value::Number(n) => n
            .as_u64()
            .and_then(|v| u32::try_from(v).ok())
            .ok_or_else(|| {
                Error::Config(format!("Parameter '{}' must be a valid u32 number", key))
            }),
        Value::String(s) => s
            .parse::<u32>()
            .map_err(|_| Error::Config(format!("Parameter '{}' must be a valid u32 number", key))),
        _ => Err(Error::Config(format!(
            "Parameter '{}' must be a number",
            key
        ))),
    }
}

/// Extract u64 from YAML value
fn extract_u64(value: &Value, key: &str) -> Result<u64> {
    match value {
        Value::Number(n) => n.as_u64().ok_or_else(|| {
            Error::Config(format!("Parameter '{}' must be a valid u64 number", key))
        }),
        Value::String(s) => s
            .parse::<u64>()
            .map_err(|_| Error::Config(format!("Parameter '{}' must be a valid u64 number", key))),
        _ => Err(Error::Config(format!(
            "Parameter '{}' must be a number",
            key
        ))),
    }
}

/// Extract usize from YAML value
fn extract_usize(value: &Value, key: &str) -> Result<usize> {
    match value {
        Value::Number(n) => n
            .as_u64()
            .and_then(|v| usize::try_from(v).ok())
            .ok_or_else(|| {
                Error::Config(format!("Parameter '{}' must be a valid usize number", key))
            }),
        Value::String(s) => s.parse::<usize>().map_err(|_| {
            Error::Config(format!("Parameter '{}' must be a valid usize number", key))
        }),
        _ => Err(Error::Config(format!(
            "Parameter '{}' must be a number",
            key
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{PluginConfig, loader};

    #[test]
    fn test_validate_valid_config() {
        let config = Config::new();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_log_level_valid() {
        assert!(validate_log_level("info").is_ok());
        assert!(validate_log_level("debug").is_ok());
        assert!(validate_log_level("trace").is_ok());
        assert!(validate_log_level("warn").is_ok());
        assert!(validate_log_level("error").is_ok());
    }

    #[test]
    fn test_validate_log_level_invalid() {
        let result = validate_log_level("invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_plugins_duplicate_names() {
        // Duplicate names should fail: two forward plugins is a duplicate
        let plugins = vec![
            PluginConfig::new("forward".to_string()),
            PluginConfig::new("forward".to_string()),
        ];

        let result = validate_plugins(&plugins);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_plugins_empty_type() {
        let plugins = vec![PluginConfig::new("".to_string())];

        let result = validate_plugins(&plugins);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_plugins_valid() {
        let plugins = vec![
            PluginConfig::new("forward".to_string()),
            PluginConfig::new("cache".to_string()),
        ];

        let result = validate_plugins(&plugins);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_socket_addr_valid() {
        // IPv4 formats
        assert!(validate_socket_addr("127.0.0.1:8080", "test").is_ok());
        assert!(validate_socket_addr("0.0.0.0:53", "test").is_ok());
        assert!(validate_socket_addr(":8000", "test").is_ok()); // IPv4 wildcard shorthand
        assert!(validate_socket_addr(":53", "test").is_ok());

        // IPv6 formats
        assert!(validate_socket_addr("[::1]:8080", "test").is_ok()); // Standard IPv6
        assert!(validate_socket_addr("[::]:8080", "test").is_ok()); // IPv6 wildcard
        assert!(validate_socket_addr("::1:8080", "test").is_ok()); // IPv6 without brackets
        assert!(validate_socket_addr("::8080", "test").is_ok()); // IPv6 wildcard shorthand
        assert!(validate_socket_addr(":::8080", "test").is_ok()); // Alternative IPv6 wildcard shorthand
    }

    #[test]
    fn test_validate_socket_addr_invalid() {
        assert!(validate_socket_addr("invalid", "test").is_err());
        assert!(validate_socket_addr("127.0.0.1:99999", "test").is_err());
        assert!(validate_socket_addr("127.0.0.1", "test").is_err());
        // Port 0 is reserved
        assert!(validate_socket_addr("127.0.0.1:0", "test").is_err());
    }

    #[test]
    fn test_validate_rate_limit_params() {
        use std::collections::HashMap;

        let mut args = HashMap::new();
        args.insert("max_queries".to_string(), Value::Number(100.into()));
        args.insert("window_secs".to_string(), Value::Number(60.into()));

        assert!(validate_plugin_args("rate_limit", &args).is_ok());
    }

    #[test]
    fn test_validate_config_with_shorthand_admin_addr() {
        let yaml = r#"
admin:
  enabled: true
  addr: ":8000"
plugins: []
"#;
        let config = loader::load_from_yaml(yaml).unwrap();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_rate_limit_out_of_range() {
        use std::collections::HashMap;

        let mut args = HashMap::new();
        args.insert("max_queries".to_string(), Value::Number(0.into())); // Too small
        args.insert("window_secs".to_string(), Value::Number(60.into()));

        assert!(validate_plugin_args("rate_limit", &args).is_err());
    }

    #[test]
    fn test_validate_ttl_params() {
        use std::collections::HashMap;

        let mut args = HashMap::new();
        args.insert("fix".to_string(), Value::Number(300.into()));
        args.insert("min".to_string(), Value::Number(30.into()));
        args.insert("max".to_string(), Value::Number(3600.into()));

        assert!(validate_plugin_args("ttl", &args).is_ok());
    }

    #[test]
    fn test_validate_downloader_timeout() {
        use std::collections::HashMap;

        let mut args = HashMap::new();
        args.insert("timeout_secs".to_string(), Value::Number(30.into()));

        assert!(validate_plugin_args("downloader", &args).is_ok());

        // Test out of range
        args.insert("timeout_secs".to_string(), Value::Number(5000.into())); // Too large
        assert!(validate_plugin_args("downloader", &args).is_err());
    }

    #[test]
    fn test_validate_cache_params() {
        use std::collections::HashMap;

        let mut args = HashMap::new();
        args.insert("size".to_string(), Value::Number(1024.into()));
        args.insert("negative_ttl".to_string(), Value::Number(300.into()));

        assert!(validate_plugin_args("cache", &args).is_ok());

        // Test invalid size (0)
        args.insert("size".to_string(), Value::Number(0.into()));
        assert!(validate_plugin_args("cache", &args).is_err());
    }
}