http-smtp-rele 0.13.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Integration-level security regression tests.
//!
//! These tests exercise the full Axum router using `tower::ServiceExt::oneshot`.
//! No real TCP connection is made — the router is called in-process.
//!
//! # Coverage
//!
//! | ID      | What                                    | Covered here |
//! |---------|-----------------------------------------|-------------|
//! | SEC-001 | No auth header → 401                    | ✓ |
//! | SEC-002 | Wrong token → 403                       | ✓ |
//! | SEC-003 | Disabled key → 403                      | ✓ |
//! | SEC-004 | CR/LF in subject → 400                  | validation::tests |
//! | SEC-005 | CR/LF in from_name → 400                | validation::tests |
//! | SEC-006 | CR/LF in reply_to → 400                 | validation::tests |
//! | SEC-007 | CR/LF in to → 400                       | validation::tests |
//! | SEC-008 | Unknown field "from" → 400              | ✓ |
//! | SEC-009 | Unknown field "bcc" → 400               | ✓ |
//! | SEC-010 | Unknown field "headers" → 400           | ✓ |
//! | SEC-011 | Body too large → 413                    | ✓ |
//! | SEC-012 | Disallowed domain → 400                 | validation::tests |
//! | SEC-013 | Rate limit exceeded → 429               | rate_limit::tests |
//! | SEC-014 | Forged X-Forwarded-For from untrusted   | auth::tests (unit) |
//! | SEC-015 | Auth log has no token value             | structural (no log sink in unit) |
//! | SEC-016 | Send log has no body value              | structural (skip(payload) enforced) |
//! | SEC-017 | SecretString Debug is redacted          | validation::tests + config::tests |

use axum::{
    body::Body,
    http::{header, Request, StatusCode},
};
use serde_json::{json, Value};
use tower::ServiceExt;

use crate::{
    api,
    config::{
        ApiKeyConfig, AppConfig, LoggingConfig, MailConfig, RateLimitConfig, SecretString,
        SecurityConfig, ServerConfig, SmtpConfig,
    },
    AppState,
};

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

/// Build a minimal, fully-functional AppConfig for tests.
///
/// Uses port 1 for SMTP — connections will always fail, but the transport
/// object is constructed without error (no connection at init time).
fn test_config() -> AppConfig {
    AppConfig {
        server: ServerConfig {
            bind_address: "127.0.0.1:0".into(),
            max_request_body_bytes: 256,  // intentionally small for SEC-011
            request_timeout_seconds: 5,
            shutdown_timeout_seconds: 5,
            concurrency_limit: 0,
            tls_cert: None,
            tls_key: None,
        },
        security: SecurityConfig {
            require_auth: true,
            trust_proxy_headers: false,
            trusted_source_cidrs: vec![],
            allowed_source_cidrs: vec![],
            api_keys: vec![
                ApiKeyConfig {
                    id: "enabled-key".into(),
                    secret: SecretString::new("valid-secret"),
                    enabled: true,
                    description: None,
                    allowed_recipient_domains: vec!["example.com".into()],
                    rate_limit_per_min: None,
                    allowed_recipients: vec![],
                    burst: 0,
                    mask_recipient: None,
                },
                ApiKeyConfig {
                    id: "disabled-key".into(),
                    secret: SecretString::new("disabled-secret"),
                    enabled: false,
                    description: None,
                    allowed_recipient_domains: vec![],
                    rate_limit_per_min: None,
                    allowed_recipients: vec![],
                    burst: 0,
                    mask_recipient: None,
                },
            ],
        },
        mail: MailConfig {
            default_from: "relay@example.com".into(),
            default_from_name: None,
            allowed_recipient_domains: vec!["example.com".into()],
            max_subject_chars: 255,
            max_body_bytes: 200,  // intentionally small for SEC-011
            max_recipients: 10,
            max_attachments: 5,
            max_attachment_bytes: 10 * 1024 * 1024,
            max_bulk_messages: 10,
        },
        smtp: SmtpConfig {
            mode: "smtp".into(),
            host: "127.0.0.1".into(),
            port: 1,  // no listener — SMTP submit will fail, but that's after validation
            connect_timeout_seconds: 1,
            submission_timeout_seconds: 1,
            auth_user: None,
            auth_password: None,
            pipe_command: "/usr/sbin/sendmail".into(),
            tls: "none".into(),
            bulk_concurrency: 5,
        },
        rate_limit: RateLimitConfig {
            global_per_min: 60,
            per_ip_per_min: 20,
            per_key_per_min: 30,
            global_burst: 5,
            per_ip_burst: 5,
            per_key_burst: 5,
            burst_size: 0,
            ip_table_size: 100,
        },
        logging: LoggingConfig {
            format: "text".into(),
            level: "error".into(),  // suppress output during tests
            mask_recipient: true,
        },
        status: Default::default(),
    }
}

fn test_router() -> axum::Router {
    let state = AppState::new(test_config());
    api::build_router(state)
}

/// POST /v1/send with a full valid auth header and JSON body.
async fn send_request(
    router: &axum::Router,
    auth: Option<&str>,
    body: Value,
) -> (StatusCode, Value) {
    let mut builder = Request::builder()
        .method("POST")
        .uri("/v1/send")
        .header(header::CONTENT_TYPE, "application/json");
    if let Some(token) = auth {
        builder = builder.header(header::AUTHORIZATION, format!("Bearer {token}"));
    }
    let req = builder.body(Body::from(body.to_string())).unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = axum::body::to_bytes(resp.into_body(), 8192).await.unwrap();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(json!({}));
    (status, json)
}

fn valid_body() -> Value {
    json!({
        "to": "user@example.com",
        "subject": "Test",
        "body": "Hello."
    })
}

// ---------------------------------------------------------------------------
// SEC-001: No Authorization header → 401 unauthorized
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_001_no_auth_header_returns_401() {
    let router = test_router();
    let (status, body) = send_request(&router, None, valid_body()).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED, "body={body}");
    assert_eq!(body["code"], "unauthorized");
}

// ---------------------------------------------------------------------------
// SEC-002: Wrong token → 403 forbidden
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_002_wrong_token_returns_403() {
    let router = test_router();
    let (status, body) = send_request(&router, Some("completely-wrong"), valid_body()).await;
    assert_eq!(status, StatusCode::FORBIDDEN, "body={body}");
    assert_eq!(body["code"], "forbidden");
}

// ---------------------------------------------------------------------------
// SEC-003: Disabled key with correct secret → 403 (not 200)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_003_disabled_key_returns_403() {
    let router = test_router();
    let (status, body) = send_request(&router, Some("disabled-secret"), valid_body()).await;
    assert_eq!(status, StatusCode::FORBIDDEN, "body={body}");
    assert_eq!(body["code"], "forbidden");
}

// ---------------------------------------------------------------------------
// SEC-008: Unknown field "from" → 400 validation_failed
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_008_unknown_field_from_rejected() {
    let router = test_router();
    let bad = json!({
        "to": "user@example.com",
        "subject": "Test",
        "body": "Hello.",
        "from": "evil@evil.com"
    });
    let (status, body) = send_request(&router, Some("valid-secret"), bad).await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "body={body}");
}

// ---------------------------------------------------------------------------
// SEC-009: Unknown field "bcc" → 400 / 422
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_009_unknown_field_bcc_rejected() {
    let router = test_router();
    let bad = json!({
        "to": "user@example.com",
        "subject": "Test",
        "body": "Hello.",
        "bcc": "spy@evil.com"
    });
    let (status, _) = send_request(&router, Some("valid-secret"), bad).await;
    assert!(
        status == StatusCode::UNPROCESSABLE_ENTITY || status == StatusCode::BAD_REQUEST,
        "expected 422 or 400, got {status}"
    );
}

// ---------------------------------------------------------------------------
// SEC-010: Unknown field "headers" → 400 / 422
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_010_unknown_field_headers_rejected() {
    let router = test_router();
    let bad = json!({
        "to": "user@example.com",
        "subject": "Test",
        "body": "Hello.",
        "headers": {"X-Custom": "injected"}
    });
    let (status, _) = send_request(&router, Some("valid-secret"), bad).await;
    assert!(
        status == StatusCode::UNPROCESSABLE_ENTITY || status == StatusCode::BAD_REQUEST,
        "expected 422 or 400, got {status}"
    );
}

// ---------------------------------------------------------------------------
// SEC-011: Body exceeding max_request_body_bytes → 413
// ---------------------------------------------------------------------------

#[tokio::test]
async fn sec_011_oversized_request_body_returns_413() {
    let router = test_router();
    // test_config sets max_request_body_bytes = 256
    let giant = "x".repeat(300);
    let req = Request::builder()
        .method("POST")
        .uri("/v1/send")
        .header(header::CONTENT_TYPE, "application/json")
        .header(header::AUTHORIZATION, "Bearer valid-secret")
        .body(Body::from(giant))
        .unwrap();
    let resp = router.oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
}

// ---------------------------------------------------------------------------
// Structural: From is always from config (mail::tests also cover this)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn from_address_cannot_be_overridden_via_extra_field() {
    // The "from" field is rejected by deny_unknown_fields (SEC-008).
    // This test double-checks that even with a crafted payload structure,
    // the router does not accept it.
    let router = test_router();
    let with_from = json!({
        "to": "user@example.com",
        "subject": "Hi",
        "body": "Text.",
        "from": "spoofed@attacker.com"
    });
    let (status, _) = send_request(&router, Some("valid-secret"), with_from).await;
    assert_ne!(
        status,
        StatusCode::ACCEPTED,
        "A request with a 'from' field must never result in 202 Accepted"
    );
}

// --- Tests from src/validation.rs ---
#[cfg(test)]
mod validation_tests {
    use crate::{
        auth::AuthContext,
        config::{
            ApiKeyConfig, AppConfig, LoggingConfig, MailConfig, RateLimitConfig, SecretString,
            SecurityConfig, ServerConfig, SmtpConfig,
        },
        error::AppError,
        validation::{validate_mail_request, MailRequest},
    };
    use std::net::IpAddr;

    fn make_auth(key_id: &str) -> AuthContext {
        AuthContext {
            key_id: key_id.to_string(),
            client_ip: IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            key_rate_limit_per_min: None,
            key_burst: 0,
        }
    }

    fn minimal_config() -> AppConfig {
        AppConfig {
            server: ServerConfig {
                bind_address: "127.0.0.1:8080".into(),
                max_request_body_bytes: 65536,
                request_timeout_seconds: 30,
                shutdown_timeout_seconds: 30,
                concurrency_limit: 0,
                tls_cert: None,
                tls_key: None,
            },
            security: SecurityConfig {
                require_auth: true,
                trust_proxy_headers: false,
                trusted_source_cidrs: vec![],
                    allowed_source_cidrs: vec![],
                api_keys: vec![ApiKeyConfig {
                    id: "test-key".into(),
                    secret: SecretString::new("tok"),
                    enabled: true,
                    description: None,
                    allowed_recipient_domains: vec![],
                    allowed_recipients: vec![],
                    rate_limit_per_min: None,
                    burst: 0,
                    mask_recipient: None,
                }],
            },
            mail: MailConfig {
                default_from: "relay@example.com".into(),
                default_from_name: None,
                allowed_recipient_domains: vec![],
                max_subject_chars: 200,
                max_body_bytes: 1_000_000,
                max_recipients: 10,
                max_attachments: 5,
                max_attachment_bytes: 10 * 1024 * 1024,
            max_bulk_messages: 10,
            },
            smtp: SmtpConfig {
                mode: "smtp".into(),
                host: "127.0.0.1".into(),
                port: 25,
                connect_timeout_seconds: 5,
                submission_timeout_seconds: 30,
                auth_user: None,
                auth_password: None,
                pipe_command: "/usr/sbin/sendmail".into(),
                tls: "none".into(),
                bulk_concurrency: 5,
            },
            rate_limit: RateLimitConfig {
                global_per_min: 60,
                per_ip_per_min: 20,
                per_key_per_min: 30,
                global_burst: 5,
                per_ip_burst: 5,
                per_key_burst: 5,
                burst_size: 0,
                ip_table_size: 100,
            },
            logging: LoggingConfig {
                format: "text".into(),
                level: "info".into(),
                mask_recipient: false,
            },
            status: Default::default(),
        }
    }

    fn minimal_request() -> MailRequest {
        MailRequest {
            to: crate::validation::Recipients(vec!["user@example.com".into()]),
            subject: "Hello".into(),
            body: "Test body".into(),
            from_name: None,
            reply_to: None,
            body_html: None,
            cc: None,
            attachments: None,
            metadata: None,
        }
    }

    #[test]
    fn valid_request_passes() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = minimal_request();
        assert!(validate_mail_request(req, &cfg, &auth).is_ok());
    }

    #[test]
    fn invalid_email_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            to: crate::validation::Recipients(vec!["not-an-email".into()]),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn crlf_in_subject_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            subject: "Hello\r\nBcc: evil@x.com".into(),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn empty_subject_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            subject: "   ".into(),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn oversized_subject_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            subject: "a".repeat(201),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn nul_in_body_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            body: "Hello\0world".into(),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn crlf_in_from_name_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            from_name: Some("Evil\r\nBcc: attacker@evil.com".into()),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn disallowed_domain_rejected() {
        let mut cfg = minimal_config();
        cfg.mail.allowed_recipient_domains = vec!["allowed.com".into()];
        let auth = make_auth("test-key");
        let req = MailRequest {
            to: crate::validation::Recipients(vec!["user@other.com".into()]),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn allowed_domain_passes() {
        let mut cfg = minimal_config();
        cfg.mail.allowed_recipient_domains = vec!["example.com".into()];
        let auth = make_auth("test-key");
        let req = minimal_request(); // to = user@example.com
        assert!(validate_mail_request(req, &cfg, &auth).is_ok());
    }

    #[test]
    fn per_key_domain_restriction_works() {
        let mut cfg = minimal_config();
        cfg.security.api_keys[0].allowed_recipient_domains = vec!["allowed.com".into()];
        let auth = make_auth("test-key");
        let req = minimal_request(); // to = user@example.com (not allowed)
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    #[test]
    fn metadata_client_request_id_extracted() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            metadata: Some(serde_json::json!({"request_id": "client-123"})),
            ..minimal_request()
        };
        let v = validate_mail_request(req, &cfg, &auth).unwrap();
        assert_eq!(v.client_request_id.as_deref(), Some("client-123"));
    }

    /// SEC-006: CR/LF in `reply_to` is rejected before SMTP.
    #[test]
    fn crlf_in_reply_to_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        for bad in &[
            "user@example.com
Bcc: evil@evil.com",
            "user@example.com
X-Header: injected",
        ] {
            let req = MailRequest {
                reply_to: Some(crate::validation::Recipients(vec![bad.to_string()])),
                ..minimal_request()
            };
            assert!(
                matches!(validate_mail_request(req, &cfg, &auth), Err(AppError::Validation(_))),
                "expected Validation error for reply_to={bad:?}"
            );
        }
    }

    /// SEC-007: CR/LF in `to` is rejected before SMTP.
    #[test]
    fn crlf_in_to_rejected() {
        let cfg = minimal_config();
        let auth = make_auth("test-key");
        let req = MailRequest {
            to: crate::validation::Recipients(vec!["user@example.com\nBcc: attacker@evil.com".to_string()]),
            ..minimal_request()
        };
        assert!(matches!(
            validate_mail_request(req, &cfg, &auth),
            Err(AppError::Validation(_))
        ));
    }

    /// SEC-017 (unit): SecretString never exposes its value through Debug.
    #[test]
    fn secret_string_redacted_in_debug() {
        use crate::config::SecretString;
        let s = SecretString::new("super-secret-token-value");
        let debug = format!("{s:?}");
        assert!(
            !debug.contains("super-secret-token-value"),
            "SecretString Debug must not expose secret; got: {debug}"
        );
    }
}