mailsis-utils 0.2.3

Utilities for Mailsis.
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
//! TOML configuration loading for the SMTP server.
//!
//! The server reads a single `config.toml` file at startup to determine
//! bind address, TLS certificates, credential sources, handler backends,
//! and per-domain routing rules. [`load_config`] parses the file into
//! a strongly-typed [`Config`] hierarchy.

use std::{collections::HashMap, fs, path::Path};

use serde::Deserialize;

/// Top-level configuration for the Mailsis SMTP server.
#[derive(Debug, Deserialize)]
pub struct Config {
    pub smtp: SmtpConfig,
}

/// SMTP server configuration.
#[derive(Debug, Deserialize)]
pub struct SmtpConfig {
    #[serde(default = "default_host")]
    pub host: String,

    #[serde(default = "default_hostname")]
    pub hostname: String,

    #[serde(default = "default_port")]
    pub port: u16,

    #[serde(default)]
    pub auth_required: bool,

    #[serde(default)]
    pub tls: TlsConfig,

    #[serde(default)]
    pub auth: AuthConfig,

    #[serde(default)]
    pub handlers: HashMap<String, HandlerConfig>,

    #[serde(default)]
    pub routing: RoutingConfig,
}

/// TLS certificate configuration.
#[derive(Debug, Deserialize)]
pub struct TlsConfig {
    #[serde(default = "default_cert")]
    pub cert: String,

    #[serde(default = "default_key")]
    pub key: String,
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            cert: default_cert(),
            key: default_key(),
        }
    }
}

/// Authentication configuration.
#[derive(Debug, Deserialize)]
pub struct AuthConfig {
    #[serde(default = "default_credentials_file")]
    pub credentials_file: String,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            credentials_file: default_credentials_file(),
        }
    }
}

/// Configuration for a named message handler.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
pub enum HandlerConfig {
    /// File-based storage handler.
    #[serde(rename = "file_storage")]
    FileStorage {
        #[serde(default = "default_mailbox_path")]
        path: String,
        #[serde(default = "default_true")]
        metadata: bool,
    },

    /// Redis queue handler.
    #[serde(rename = "redis")]
    Redis {
        #[serde(default = "default_redis_url")]
        url: String,
        #[serde(default = "default_redis_queue")]
        queue: String,
    },

    /// Void handler that always refuses delivery with a fixed SMTP reply.
    ///
    /// Intended as a default routing target to deny everything that does not
    /// match an explicit routing rule.
    #[serde(rename = "reject")]
    Reject {
        #[serde(default = "default_reject_code")]
        code: u16,
        #[serde(default = "default_reject_message")]
        message: String,
    },
}

/// Routing configuration with rules and a default handler.
#[derive(Debug, Deserialize)]
pub struct RoutingConfig {
    /// Default handler name for routed messages.
    #[serde(default = "default_handler_name")]
    pub default: String,

    /// Default transformers applied to all routed messages unless
    /// overridden per rule.
    #[serde(default)]
    pub transformers: Vec<TransformerConfig>,

    /// Sequence of routing rules to be applied according to specificity.
    #[serde(default)]
    pub rules: Vec<RoutingRuleConfig>,
}

impl Default for RoutingConfig {
    fn default() -> Self {
        Self {
            default: default_handler_name(),
            transformers: Vec::new(),
            rules: Vec::new(),
        }
    }
}

/// A single routing rule that matches by address or domain.
#[derive(Debug, Clone, Deserialize)]
pub struct RoutingRuleConfig {
    /// Exact email address match (e.g. "admin@example.com").
    pub address: Option<String>,

    /// Domain match, supports wildcard prefix (e.g. "example.com" or "*.example.com").
    pub domain: Option<String>,

    /// Name of the handler to route to.
    pub handler: String,

    /// Transformers for this rule, overrides the default transformers if present.
    pub transformers: Option<Vec<TransformerConfig>>,

    /// Whether authentication is required for recipients matching this rule.
    /// Overrides the global `smtp.auth_required` setting when present.
    pub auth_required: Option<bool>,
}

/// Configuration for a message transformer.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
pub enum TransformerConfig {
    /// Ensures a Message-ID header exists in the email body.
    #[serde(rename = "message_id")]
    MessageId {
        /// Domain used when generating new Message-ID values.
        #[serde(default = "default_host")]
        domain: String,
    },

    /// Verifies SPF, DKIM, and DMARC; adds an Authentication-Results header.
    #[serde(rename = "email_auth")]
    EmailAuth {
        /// The authserv-id for the Authentication-Results header.
        /// Defaults to the global `hostname` if not specified.
        #[serde(default)]
        authserv_id: String,
    },
}

/// Loads configuration from a TOML file.
pub fn load_config(path: &Path) -> Result<Config, ConfigError> {
    let content = fs::read_to_string(path).map_err(ConfigError::Io)?;
    toml::from_str(&content).map_err(ConfigError::Parse)
}

/// Errors that can occur while loading configuration.
#[derive(Debug)]
pub enum ConfigError {
    /// An I/O error occurred reading the file.
    Io(std::io::Error),
    /// A parse error occurred deserializing TOML.
    Parse(toml::de::Error),
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigError::Io(e) => write!(f, "Config I/O error: {e}"),
            ConfigError::Parse(e) => write!(f, "Config parse error: {e}"),
        }
    }
}

impl std::error::Error for ConfigError {}

fn default_host() -> String {
    "127.0.0.1".to_string()
}

fn default_hostname() -> String {
    "localhost".to_string()
}

fn default_port() -> u16 {
    2525
}

fn default_cert() -> String {
    "certs/server.cert.pem".to_string()
}

fn default_key() -> String {
    "certs/server.key.pem".to_string()
}

fn default_credentials_file() -> String {
    "passwords/example.txt".to_string()
}

fn default_mailbox_path() -> String {
    "mailbox".to_string()
}

fn default_true() -> bool {
    true
}

fn default_redis_url() -> String {
    "redis://127.0.0.1:6379".to_string()
}

fn default_redis_queue() -> String {
    "incoming_emails".to_string()
}

fn default_handler_name() -> String {
    "local".to_string()
}

fn default_reject_code() -> u16 {
    550
}

fn default_reject_message() -> String {
    "Relay access denied".to_string()
}

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

    #[test]
    fn test_parse_minimal_config() {
        let toml = r#"
[smtp]
host = "0.0.0.0"
port = 25
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.smtp.host, "0.0.0.0");
        assert_eq!(config.smtp.port, 25);
        assert!(!config.smtp.auth_required);
        assert_eq!(config.smtp.routing.default, "local");
    }

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
[smtp]
host = "0.0.0.0"
port = 25
auth_required = true

[smtp.tls]
cert = "my/cert.pem"
key = "my/key.pem"

[smtp.auth]
credentials_file = "my/passwords.txt"

[smtp.handlers.local]
type = "file_storage"
path = "my_mailbox"
metadata = false

[smtp.handlers.queue]
type = "redis"
url = "redis://redis:6379"
queue = "emails"

[smtp.routing]
default = "local"

[[smtp.routing.rules]]
address = "admin@example.com"
handler = "queue"

[[smtp.routing.rules]]
domain = "example.com"
handler = "queue"

[[smtp.routing.rules]]
domain = "*.internal.org"
handler = "local"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.smtp.host, "0.0.0.0");
        assert_eq!(config.smtp.port, 25);
        assert!(config.smtp.auth_required);
        assert_eq!(config.smtp.tls.cert, "my/cert.pem");
        assert_eq!(config.smtp.auth.credentials_file, "my/passwords.txt");
        assert_eq!(config.smtp.handlers.len(), 2);
        assert_eq!(config.smtp.routing.rules.len(), 3);

        // Verify handler types
        match &config.smtp.handlers["local"] {
            HandlerConfig::FileStorage { path, metadata } => {
                assert_eq!(path, "my_mailbox");
                assert!(!metadata);
            }
            _ => panic!("Expected FileStorage handler"),
        }

        match &config.smtp.handlers["queue"] {
            HandlerConfig::Redis { url, queue } => {
                assert_eq!(url, "redis://redis:6379");
                assert_eq!(queue, "emails");
            }
            _ => panic!("Expected Redis handler"),
        }

        // Verify routing rules
        assert_eq!(
            config.smtp.routing.rules[0].address.as_deref(),
            Some("admin@example.com")
        );
        assert_eq!(config.smtp.routing.rules[0].handler, "queue");
        assert_eq!(
            config.smtp.routing.rules[1].domain.as_deref(),
            Some("example.com")
        );
        assert_eq!(
            config.smtp.routing.rules[2].domain.as_deref(),
            Some("*.internal.org")
        );
    }

    #[test]
    fn test_parse_transformers_config() {
        let toml = r#"
[smtp]

[[smtp.routing.transformers]]
type = "message_id"
domain = "mail.example.com"

[[smtp.routing.rules]]
domain = "example.com"
handler = "local"

  [[smtp.routing.rules.transformers]]
  type = "message_id"
  domain = "example.com"

[[smtp.routing.rules]]
domain = "other.com"
handler = "local"
"#;
        let config: Config = toml::from_str(toml).unwrap();

        // Default transformers
        assert_eq!(config.smtp.routing.transformers.len(), 1);
        match &config.smtp.routing.transformers[0] {
            TransformerConfig::MessageId { domain } => {
                assert_eq!(domain, "mail.example.com");
            }
            _ => panic!("Expected MessageId transformer"),
        }

        // Per-rule transformers
        assert!(config.smtp.routing.rules[0].transformers.is_some());
        let rule_transformers = config.smtp.routing.rules[0].transformers.as_ref().unwrap();
        assert_eq!(rule_transformers.len(), 1);
        match &rule_transformers[0] {
            TransformerConfig::MessageId { domain } => {
                assert_eq!(domain, "example.com");
            }
            _ => panic!("Expected MessageId transformer"),
        }

        // Rule without transformers
        assert!(config.smtp.routing.rules[1].transformers.is_none());
    }

    #[test]
    fn test_parse_auth_required_per_rule() {
        let toml = r#"
[smtp]

[[smtp.routing.rules]]
address = "secure@example.com"
handler = "local"
auth_required = true

[[smtp.routing.rules]]
domain = "open.com"
handler = "local"
auth_required = false

[[smtp.routing.rules]]
domain = "default.com"
handler = "local"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.smtp.routing.rules[0].auth_required, Some(true));
        assert_eq!(config.smtp.routing.rules[1].auth_required, Some(false));
        assert_eq!(config.smtp.routing.rules[2].auth_required, None);
    }

    #[test]
    fn test_parse_defaults() {
        let toml = r#"
[smtp]
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.smtp.host, "127.0.0.1");
        assert_eq!(config.smtp.port, 2525);
        assert_eq!(config.smtp.tls.cert, "certs/server.cert.pem");
        assert_eq!(config.smtp.tls.key, "certs/server.key.pem");
        assert_eq!(config.smtp.auth.credentials_file, "passwords/example.txt");
    }

    #[test]
    fn test_config_error_display_io() {
        let error = ConfigError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file missing",
        ));
        assert!(error.to_string().starts_with("Config I/O error:"));
    }

    #[test]
    fn test_config_error_display_parse() {
        let toml_err = toml::from_str::<Config>("invalid toml {{{{").unwrap_err();
        let error = ConfigError::Parse(toml_err);
        assert!(error.to_string().starts_with("Config parse error:"));
    }

    #[test]
    fn test_load_config_success() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        std::fs::write(&config_path, "[smtp]\nhost = \"0.0.0.0\"\nport = 25\n").unwrap();

        let config = load_config(&config_path).unwrap();
        assert_eq!(config.smtp.host, "0.0.0.0");
        assert_eq!(config.smtp.port, 25);
    }

    #[test]
    fn test_load_config_file_not_found() {
        let result = load_config(Path::new("/nonexistent/config.toml"));
        assert!(result.is_err());
    }

    #[test]
    fn test_load_config_invalid_toml() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let config_path = temp_dir.path().join("bad.toml");
        std::fs::write(&config_path, "this is not valid {{{{ toml").unwrap();

        let result = load_config(&config_path);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_reject_handler_defaults() {
        let toml = r#"
[smtp]

[smtp.handlers.block]
type = "reject"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        match &config.smtp.handlers["block"] {
            HandlerConfig::Reject { code, message } => {
                assert_eq!(*code, 550);
                assert_eq!(message, "Relay access denied");
            }
            other => panic!("Expected Reject handler, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_reject_handler_custom() {
        let toml = r#"
[smtp]

[smtp.handlers.deny]
type = "reject"
code = 521
message = "No mail accepted here"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        match &config.smtp.handlers["deny"] {
            HandlerConfig::Reject { code, message } => {
                assert_eq!(*code, 521);
                assert_eq!(message, "No mail accepted here");
            }
            other => panic!("Expected Reject handler, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_email_auth_transformer() {
        let toml = r#"
[smtp]

[[smtp.routing.transformers]]
type = "email_auth"
authserv_id = "mx.example.com"
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.smtp.routing.transformers.len(), 1);
        match &config.smtp.routing.transformers[0] {
            TransformerConfig::EmailAuth { authserv_id } => {
                assert_eq!(authserv_id, "mx.example.com");
            }
            _ => panic!("Expected EmailAuth transformer"),
        }
    }
}