http-smtp-rele 0.8.0

Minimal, secure HTTP-to-SMTP submission relay
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! Configuration loading and validation.
//!
//! Config is read from a TOML file at startup. Invalid configuration causes
//! immediate process termination (fail-fast).
//!
//! # Schema overview
//!
//! ```toml
//! [server]
//! bind_address = "127.0.0.1:8080"
//!
//! [security]
//! require_auth = true
//! trust_proxy_headers = false
//! trusted_source_cidrs = ["127.0.0.1/32"]
//!
//! [[security.api_keys]]
//! id = "svc-a"
//! secret = "tok-..."
//! enabled = true
//!
//! [mail]
//! default_from = "relay@example.com"
//!
//! [smtp]
//! host = "127.0.0.1"
//! port = 25
//!
//! [rate_limit]
//!
//! [logging]
//! ```

use std::fmt;
use std::path::Path;

use lettre::Address;
use serde::Deserialize;
use thiserror::Error;

// ---------------------------------------------------------------------------
// SecretString
// ---------------------------------------------------------------------------

/// An opaque string that is never printed in logs or debug output.
///
/// Used to store API key secrets from config. The underlying value is
/// accessible only via [`SecretString::expose`].
#[derive(Clone, Deserialize)]
#[serde(transparent)]
pub struct SecretString(String);

impl SecretString {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Return the underlying secret value.
    ///
    /// Callers must not log, store, or transmit the returned value.
    pub fn expose(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for SecretString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("[REDACTED]")
    }
}

impl fmt::Display for SecretString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("[REDACTED]")
    }
}

// ---------------------------------------------------------------------------
// Config structs
// ---------------------------------------------------------------------------

/// Top-level application configuration.

/// Submission status tracking configuration (RFC 086, 087).
#[derive(Debug, Clone, Deserialize)]
pub struct StatusConfig {
    /// Enable status tracking. When false, no records are created.
    /// Requires restart to change.
    #[serde(default = "default_status_enabled")]
    pub enabled: bool,
    /// Backend: "memory" only in MVP. Requires restart to change.
    #[serde(default = "default_status_store")]
    pub store: String,
    /// Record time-to-live in seconds. SIGHUP-reloadable.
    #[serde(default = "default_status_ttl_seconds")]
    pub ttl_seconds: u64,
    /// Maximum records in store. SIGHUP-reloadable.
    #[serde(default = "default_status_max_records")]
    pub max_records: usize,
    /// Background cleanup interval in seconds. SIGHUP-reloadable.
    #[serde(default = "default_status_cleanup_interval_seconds")]
    pub cleanup_interval_seconds: u64,
    /// Path to the SQLite database file. Required when `store = "sqlite"`.
    /// The parent directory must exist; the file is created on first run.
    pub db_path: Option<std::path::PathBuf>,
}

fn default_status_enabled() -> bool { true }
fn default_status_store() -> String { "memory".into() }
fn default_status_ttl_seconds() -> u64 { 3600 }
fn default_status_max_records() -> usize { 10_000 }
fn default_status_cleanup_interval_seconds() -> u64 { 60 }

#[derive(Debug, Clone, Deserialize)]
pub struct AppConfig {
    pub server:     ServerConfig,
    pub security:   SecurityConfig,
    pub mail:       MailConfig,
    pub smtp:       SmtpConfig,
    pub rate_limit: RateLimitConfig,
    pub logging:    LoggingConfig,
    #[serde(default)]
    pub status:     StatusConfig,
}

impl Default for StatusConfig {
    fn default() -> Self {
        Self {
            enabled: default_status_enabled(),
            store: default_status_store(),
            ttl_seconds: default_status_ttl_seconds(),
            max_records: default_status_max_records(),
            cleanup_interval_seconds: default_status_cleanup_interval_seconds(),
            db_path: None,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ServerConfig {
    pub bind_address: String,
    #[serde(default = "default_max_request_body_bytes")]
    pub max_request_body_bytes: usize,
    #[serde(default = "default_request_timeout_seconds")]
    pub request_timeout_seconds: u64,
    #[serde(default = "default_shutdown_timeout_seconds")]
    pub shutdown_timeout_seconds: u64,
    /// Maximum concurrent in-flight requests. 0 = unlimited.
    #[serde(default)]
    pub concurrency_limit: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SecurityConfig {
    #[serde(default = "default_true")]
    pub require_auth: bool,
    /// When true, read `X-Forwarded-For` to resolve client IP.
    /// Only applies when the peer IP is listed in `trusted_source_cidrs`.
    #[serde(default)]
    pub trust_proxy_headers: bool,
    /// CIDRs whose X-Forwarded-For headers may be trusted for IP resolution.
    /// Distinct from `allowed_source_cidrs` — see security model.
    #[serde(default)]
    pub trusted_source_cidrs: Vec<String>,
    /// CIDRs that are permitted to connect at all (empty = allow all source IPs).
    /// Applied after IP resolution; independent of proxy header trust.
    #[serde(default)]
    pub allowed_source_cidrs: Vec<String>,
    #[serde(default)]
    pub api_keys: Vec<ApiKeyConfig>,
}

/// Per-API-key configuration entry.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiKeyConfig {
    pub id: String,
    pub secret: SecretString,
    #[serde(default = "default_true")]
    pub enabled: bool,
    pub description: Option<String>,
    /// Recipient domain allowlist for this key (empty = use global policy).
    #[serde(default)]
    pub allowed_recipient_domains: Vec<String>,
    /// Exact recipient address allowlist (empty = domain-level policy only).
    /// Takes precedence over `allowed_recipient_domains` when non-empty.
    #[serde(default)]
    pub allowed_recipients: Vec<String>,
    /// Per-key sustained rate (tokens/minute). None = inherit `[rate_limit].per_key_per_min`.
    pub rate_limit_per_min: Option<u32>,
    /// Per-key burst override. 0 = inherit `[rate_limit].per_key_burst`.
    #[serde(default)]
    pub burst: u32,
    /// Override global `[logging].mask_recipient` for this key (RFC 603).
    /// `None` = inherit global setting.
    pub mask_recipient: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MailConfig {
    pub default_from: String,
    pub default_from_name: Option<String>,
    /// Global recipient domain allowlist (empty = allow all domains).
    #[serde(default)]
    pub allowed_recipient_domains: Vec<String>,
    #[serde(default = "default_max_subject_chars")]
    pub max_subject_chars: usize,
    #[serde(default = "default_max_body_bytes")]
    pub max_body_bytes: usize,
    /// Maximum number of recipients per request. Default 10.
    #[serde(default = "default_max_recipients")]
    pub max_recipients: usize,
    /// Maximum number of attachments per request (RFC 502).
    #[serde(default = "default_max_attachments")]
    pub max_attachments: usize,
    /// Maximum decoded size per attachment in bytes (RFC 502). Default 10 MiB.
    #[serde(default = "default_max_attachment_bytes")]
    pub max_attachment_bytes: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SmtpConfig {
    #[serde(default = "default_smtp_mode")]
    pub mode: String,
    /// TLS mode: "none" (plain TCP), "starttls" (STARTTLS), or "tls" (implicit TLS).
    #[serde(default = "default_smtp_tls")]
    pub tls: String,
    #[serde(default = "default_smtp_host")]
    pub host: String,
    #[serde(default = "default_smtp_port")]
    pub port: u16,
    #[serde(default = "default_connect_timeout_seconds")]
    pub connect_timeout_seconds: u64,
    #[serde(default = "default_submission_timeout_seconds")]
    pub submission_timeout_seconds: u64,
    /// SMTP AUTH username. Must be set together with `auth_password` (RFC 301).
    pub auth_user: Option<String>,
    /// SMTP AUTH password. Never logged. Must be set together with `auth_user`.
    pub auth_password: Option<SecretString>,
    /// Command for pipe mode. Only used when `mode = "pipe"` (RFC 304).
    #[serde(default = "default_pipe_command")]
    pub pipe_command: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RateLimitConfig {
    // Sustained rates (tokens/minute)
    #[serde(default = "default_global_per_min")]
    pub global_per_min: u32,
    #[serde(default = "default_per_ip_per_min")]
    pub per_ip_per_min: u32,
    /// Default per-key rate. Overridden by `ApiKeyConfig.rate_limit_per_min`.
    #[serde(default = "default_per_key_per_min")]
    pub per_key_per_min: u32,

    // Burst capacities (tokens a fresh bucket starts with)
    #[serde(default = "default_global_burst")]
    pub global_burst: u32,
    #[serde(default = "default_per_ip_burst")]
    pub per_ip_burst: u32,
    /// Default per-key burst. Overridden by `ApiKeyConfig.burst` when > 0.
    #[serde(default = "default_per_key_burst")]
    pub per_key_burst: u32,

    /// Legacy field — sets all three burst values if the per-tier fields are absent.
    /// Deprecated; use `global_burst`, `per_ip_burst`, `per_key_burst` instead.
    #[serde(default)]
    pub burst_size: u32,

    /// Maximum entries in the per-IP bucket map; LRU eviction above this.
    /// 0 = unlimited (not recommended in production).
    #[serde(default = "default_ip_table_size")]
    pub ip_table_size: usize,
}

impl RateLimitConfig {
    /// Effective global burst: per-tier value if set, else legacy `burst_size`, else default.
    pub fn effective_global_burst(&self) -> u32 {
        if self.global_burst > 0 { self.global_burst }
        else if self.burst_size > 0 { self.burst_size }
        else { default_global_burst() }
    }
    pub fn effective_per_ip_burst(&self) -> u32 {
        if self.per_ip_burst > 0 { self.per_ip_burst }
        else if self.burst_size > 0 { self.burst_size }
        else { default_per_ip_burst() }
    }
    pub fn effective_per_key_burst(&self) -> u32 {
        if self.per_key_burst > 0 { self.per_key_burst }
        else if self.burst_size > 0 { self.burst_size }
        else { default_per_key_burst() }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct LoggingConfig {
    /// Output format: `"text"` (default) or `"json"`.
    #[serde(default = "default_log_format")]
    pub format: String,
    #[serde(default = "default_log_level")]
    pub level: String,
    /// When true, mask the recipient address in audit log entries.
    #[serde(default)]
    pub mask_recipient: bool,
}

// ---------------------------------------------------------------------------
// Default value functions
// ---------------------------------------------------------------------------

fn default_max_request_body_bytes() -> usize { 1_048_576 }
fn default_request_timeout_seconds() -> u64 { 30 }
fn default_shutdown_timeout_seconds() -> u64 { 30 }
fn default_true() -> bool { true }
fn default_max_subject_chars() -> usize { 255 }
fn default_max_body_bytes() -> usize { 65_536 }
fn default_smtp_mode() -> String { "smtp".into() }
fn default_smtp_host() -> String { "127.0.0.1".into() }
fn default_smtp_port() -> u16 { 25 }
fn default_connect_timeout_seconds() -> u64 { 5 }
fn default_submission_timeout_seconds() -> u64 { 30 }
fn default_global_per_min() -> u32 { 60 }
fn default_per_ip_per_min() -> u32 { 20 }
#[allow(dead_code)]
fn default_burst_size() -> u32 { 5 }
fn default_max_recipients() -> usize { 10 }
fn default_max_attachments() -> usize { 5 }
fn default_max_attachment_bytes() -> usize { 10 * 1024 * 1024 } // 10 MiB
fn default_pipe_command() -> String { "/usr/sbin/sendmail".into() }
fn default_smtp_tls() -> String { "none".into() }
fn default_global_burst() -> u32 { 10 }
fn default_per_ip_burst() -> u32 { 5 }
fn default_per_key_burst() -> u32 { 5 }
fn default_per_key_per_min() -> u32 { 30 }
fn default_ip_table_size() -> usize { 10_000 }
fn default_log_format() -> String { "text".into() }
fn default_log_level() -> String { "info".into() }

// ---------------------------------------------------------------------------
// Config error
// ---------------------------------------------------------------------------

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("cannot read config file: {0}")]
    Io(#[from] std::io::Error),

    #[error("config parse error: {0}")]
    Parse(#[from] toml::de::Error),

    #[error("invalid server.bind_address: must be host:port (e.g. 127.0.0.1:8080)")]
    InvalidBindAddress,

    #[error("invalid mail.default_from: must be a valid email address")]
    InvalidDefaultFrom,

    #[error("security.require_auth is true but no api_keys are defined")]
    NoApiKeys,

    #[error("no api_keys entries have enabled = true")]
    NoEnabledApiKeys,

    #[error("invalid CIDR: {0}")]
    InvalidCidr(String),

    #[error("configuration error: {0}")]
    Validation(String),

    #[error("invalid smtp.port: must be 1-65535")]
    InvalidSmtpPort,

    #[error("invalid rate_limit values: all per_min values must be > 0")]
    InvalidRateLimit,

    #[error("invalid logging.level: must be trace, debug, info, warn, or error")]
    InvalidLogLevel,

    #[error("invalid logging.format: must be 'text' or 'json'")]
    InvalidLogFormat,
}

// ---------------------------------------------------------------------------
// Load and validate
// ---------------------------------------------------------------------------

pub fn load_from_str(toml_str: &str) -> Result<AppConfig, ConfigError> {
    let config: AppConfig = toml::from_str(toml_str)?;
    validate_config(&config)?;
    Ok(config)
}

pub fn load(path: &Path) -> Result<AppConfig, ConfigError> {
    let text = std::fs::read_to_string(path)?;
    let config: AppConfig = toml::from_str(&text)?;
    validate_config(&config)?;
    Ok(config)
}

pub fn validate_config(config: &AppConfig) -> Result<(), ConfigError> {
    // bind_address
    config
        .server
        .bind_address
        .parse::<std::net::SocketAddr>()
        .map_err(|_| ConfigError::InvalidBindAddress)?;

    // default_from
    config
        .mail
        .default_from
        .parse::<Address>()
        .map_err(|_| ConfigError::InvalidDefaultFrom)?;

    // API keys
    if config.security.require_auth && config.security.api_keys.is_empty() {
        return Err(ConfigError::NoApiKeys);
    }
    if config.security.require_auth
        && !config.security.api_keys.iter().any(|k| k.enabled)
    {
        return Err(ConfigError::NoEnabledApiKeys);
    }

    // CIDRs — validate both lists
    for cidr in config.security.trusted_source_cidrs.iter()
        .chain(config.security.allowed_source_cidrs.iter())
    {
        cidr.parse::<ipnet::IpNet>()
            .map_err(|_| ConfigError::InvalidCidr(cidr.clone()))?;
    }

    // SMTP port
    if config.smtp.port == 0 {
        return Err(ConfigError::InvalidSmtpPort);
    }

    // SMTP TLS mode
    match config.smtp.tls.as_str() {
        "none" | "starttls" | "tls" => {}
        other => return Err(ConfigError::Validation(
            format!("smtp.tls must be \"none\", \"starttls\", or \"tls\"; got \"{other}\"")
        )),
    }

    // SMTP AUTH: both user and password must be set or both absent
    match (&config.smtp.auth_user, &config.smtp.auth_password) {
        (Some(_), None) | (None, Some(_)) => {
            return Err(ConfigError::Validation(
                "smtp.auth_user and smtp.auth_password must both be set or both absent".into(),
            ));
        }
        _ => {}
    }

    // Status store: db_path required for sqlite; feature check
    if config.status.store == "sqlite" {
        if config.status.db_path.is_none() {
            return Err(ConfigError::Validation(
                "status.db_path is required when status.store = \"sqlite\"".into()
            ));
        }
        #[cfg(not(feature = "sqlite"))]
        return Err(ConfigError::Validation(
            "status.store = \"sqlite\" is not available in this build.              Rebuild with: cargo build --features sqlite".into()
        ));
    } else if !matches!(config.status.store.as_str(), "memory") {
        return Err(ConfigError::Validation(
            format!("status.store must be \"memory\" or \"sqlite\"; got \"{}\""
                , config.status.store)
        ));
    }

    // Pipe mode: auth credentials are not applicable
    if config.smtp.mode == "pipe"
        && (config.smtp.auth_user.is_some() || config.smtp.auth_password.is_some())
    {
        return Err(ConfigError::Validation(
            r#"smtp.auth_user/auth_password are not applicable when smtp.mode = "pipe""#.into(),
        ));
    }

    // Rate limits
    if config.rate_limit.global_per_min == 0 || config.rate_limit.per_ip_per_min == 0 {
        return Err(ConfigError::InvalidRateLimit);
    }

    // Log level
    let valid_levels = ["trace", "debug", "info", "warn", "error"];
    if !valid_levels.contains(&config.logging.level.as_str()) {
        return Err(ConfigError::InvalidLogLevel);
    }

    // Log format
    let valid_formats = ["text", "json"];
    if !valid_formats.contains(&config.logging.format.as_str()) {
        return Err(ConfigError::InvalidLogFormat);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn minimal_config_str() -> String {
        r#"
[server]
bind_address = "127.0.0.1:8080"

[security]
require_auth = false

[rate_limit]

[mail]
default_from = "noreply@example.com"

[smtp]

[logging]
"#
        .into()
    }

    #[test]
    fn valid_config_parses() {
        let config: AppConfig = toml::from_str(&minimal_config_str()).unwrap();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn invalid_bind_address() {
        let text = minimal_config_str().replace("127.0.0.1:8080", "notanaddress");
        let config: AppConfig = toml::from_str(&text).unwrap();
        assert!(matches!(validate_config(&config), Err(ConfigError::InvalidBindAddress)));
    }

    #[test]
    fn invalid_default_from() {
        let text = minimal_config_str().replace("noreply@example.com", "notanemail");
        let config: AppConfig = toml::from_str(&text).unwrap();
        assert!(matches!(validate_config(&config), Err(ConfigError::InvalidDefaultFrom)));
    }

    #[test]
    fn require_auth_no_keys() {
        let text = minimal_config_str().replace("require_auth = false", "require_auth = true");
        let config: AppConfig = toml::from_str(&text).unwrap();
        assert!(matches!(validate_config(&config), Err(ConfigError::NoApiKeys)));
    }

    #[test]
    fn secret_string_is_redacted_in_debug() {
        let s = SecretString::new("very-secret");
        assert!(!format!("{:?}", s).contains("very-secret"));
        assert!(!format!("{}", s).contains("very-secret"));
        assert_eq!(s.expose(), "very-secret");
    }

    #[test]
    fn defaults_are_sensible() {
        let config: AppConfig = toml::from_str(&minimal_config_str()).unwrap();
        assert_eq!(config.server.max_request_body_bytes, 1_048_576);
        assert_eq!(config.smtp.port, 25);
        assert_eq!(config.rate_limit.global_per_min, 60);
        assert_eq!(config.logging.format, "text");
    }
}