http-smtp-rele 0.15.1

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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Integration and security regression tests.
//!
//! Implements RFC 102 (complete SEC-001–017 matrix) and RFC 103 (E2E scenarios).
//! Uses `SmtpStub` for tests that verify SMTP submission end-to-end.

mod smtp_stub;
mod common;

use axum::http::StatusCode;
use tower::ServiceExt;

use serde_json::json;

use common::{send, send_valid, test_router, test_router_no_smtp, RequestBuilder};
use smtp_stub::{SmtpStub, StubConfig};

// ===========================================================================
// SEC-001 — No Authorization header → 401
// ===========================================================================

#[tokio::test]
async fn sec_001_no_auth_returns_401() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .no_auth()
            .json(common::valid_mail_body())
            .build(),
    )
    .await;
    resp.assert_status(StatusCode::UNAUTHORIZED)
        .assert_code("unauthorized");
}

// ===========================================================================
// SEC-002 — Wrong token → 403
// ===========================================================================

#[tokio::test]
async fn sec_002_wrong_token_returns_403() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("totally-wrong")
            .json(common::valid_mail_body())
            .build(),
    )
    .await;
    resp.assert_status(StatusCode::FORBIDDEN)
        .assert_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_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("disabled-secret")
            .json(common::valid_mail_body())
            .build(),
    )
    .await;
    resp.assert_status(StatusCode::FORBIDDEN)
        .assert_code("forbidden");
}

// ===========================================================================
// SEC-008 — Unknown field "from" → 422
// ===========================================================================

#[tokio::test]
async fn sec_008_unknown_field_from_rejected() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .json(json!({
                "to": "user@example.com",
                "subject": "Test",
                "body": "Hello.",
                "from": "evil@evil.com"
            }))
            .build(),
    )
    .await;
    assert_ne!(resp.status, StatusCode::ACCEPTED, "from field must be rejected");
}

// ===========================================================================
// SEC-009 — Unknown field "bcc" → rejected
// ===========================================================================

#[tokio::test]
async fn sec_009_unknown_field_bcc_rejected() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .json(json!({
                "to": "user@example.com",
                "subject": "Test",
                "body": "Hello.",
                "bcc": "spy@evil.com"
            }))
            .build(),
    )
    .await;
    assert_ne!(resp.status, StatusCode::ACCEPTED, "bcc field must be rejected");
}

// ===========================================================================
// SEC-010 — Unknown field "headers" → rejected
// ===========================================================================

#[tokio::test]
async fn sec_010_unknown_field_headers_rejected() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .json(json!({
                "to": "user@example.com",
                "subject": "Test",
                "body": "Hello.",
                "headers": {"X-Custom": "injected"}
            }))
            .build(),
    )
    .await;
    assert_ne!(resp.status, StatusCode::ACCEPTED, "headers field must be rejected");
}

// ===========================================================================
// SEC-011 — Body too large → 413
// ===========================================================================

#[tokio::test]
async fn sec_011_oversized_body_returns_413() {
    use http_smtp_rele::{api, AppState};

    // Build a router with a tiny body limit
    let mut cfg = common::test_config(1);
    cfg.server.max_request_body_bytes = 100;
    let router = api::build_router(AppState::new(cfg));

    let big = "x".repeat(200);
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .raw_body(big.as_bytes())
            .build(),
    )
    .await;
    assert_eq!(resp.status, StatusCode::PAYLOAD_TOO_LARGE);
}

// ===========================================================================
// SEC-013 — Rate limit exceeded → 429
// ===========================================================================

#[tokio::test]
async fn sec_013_rate_limit_exceeded_returns_429() {
    use http_smtp_rele::{api, AppState};

    // Set per-key burst to 1 so the first request exhausts the key bucket.
    // All tier burst values must be set explicitly — per_key_burst takes priority
    // over the legacy burst_size field.
    let mut cfg = common::test_config(1);
    cfg.rate_limit.per_key_burst = 1;
    cfg.rate_limit.per_key_per_min = 1;
    let router = api::build_router(AppState::new(cfg));

    // First request consumes the single burst token; hits SMTP (port 1 = no listener) → 502
    let _ = send_valid(&router).await;

    // Second request: per-key bucket empty → 429
    let resp = send_valid(&router).await;
    resp.assert_status(StatusCode::TOO_MANY_REQUESTS)
        .assert_code("rate_limited");
}

// ===========================================================================
// SEC-015 — Auth failure response does not contain the token
// ===========================================================================

#[tokio::test]
async fn sec_015_auth_failure_body_has_no_token() {
    let router = test_router_no_smtp();
    let secret = "ultra-secret-token-xyzxxxxxxxxxx";
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer(secret)
            .json(common::valid_mail_body())
            .build(),
    )
    .await;
    assert_eq!(resp.status, StatusCode::FORBIDDEN);
    let body_str = resp.body.to_string();
    assert!(
        !body_str.contains(secret),
        "auth failure response must not echo the submitted token; body={body_str}"
    );
}

// ===========================================================================
// E2E-001 — Full pipeline: HTTP → auth → validation → SMTP stub → 202
// ===========================================================================

#[tokio::test]
async fn e2e_001_valid_request_reaches_smtp_and_returns_202() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let resp = send_valid(&router).await;
    resp.assert_status(StatusCode::ACCEPTED)
        .assert_status_field("accepted");

    // Verify a message was delivered to the stub
    stub.assert_count(1);
    let msg = stub.assert_one();
    assert!(msg.envelope_to.contains("user@example.com"));

    stub.shutdown().await;
}

// ===========================================================================
// E2E-002 — SMTP unavailable → 502
// ===========================================================================

#[tokio::test]
async fn e2e_002_smtp_down_returns_502() {
    // Port 1 has no listener → connection refused
    let router = test_router(1);
    let resp = send_valid(&router).await;
    resp.assert_status(StatusCode::BAD_GATEWAY)
        .assert_code("smtp_unavailable");
}

// ===========================================================================
// E2E-003 — SMTP rejects message → 502
// ===========================================================================

#[tokio::test]
async fn e2e_003_smtp_rejects_message_returns_502() {
    let stub = SmtpStub::start_with_config(
        0,
        StubConfig { reject_mail: true, ..Default::default() },
    )
    .await;
    let router = test_router(stub.port());

    let resp = send_valid(&router).await;
    resp.assert_status(StatusCode::BAD_GATEWAY)
        .assert_code("smtp_unavailable");

    stub.shutdown().await;
}

// ===========================================================================
// E2E-004 — /healthz returns 200 even when SMTP is down
// ===========================================================================

#[tokio::test]
async fn e2e_004_healthz_independent_of_smtp() {
    let router = test_router(1); // SMTP not available
    let resp = send(
        &router,
        RequestBuilder::get("/healthz").build(),
    )
    .await;
    resp.assert_status(StatusCode::OK)
        .assert_status_field("ok");
}

// ===========================================================================
// E2E-005 — /readyz returns 200 when SMTP stub is running
// ===========================================================================

#[tokio::test]
async fn e2e_005_readyz_ok_when_smtp_reachable() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let resp = send(&router, RequestBuilder::get("/readyz").build()).await;
    resp.assert_status(StatusCode::OK);

    stub.shutdown().await;
}

// ===========================================================================
// E2E-006 — /readyz returns 503 when SMTP is down
// ===========================================================================

#[tokio::test]
async fn e2e_006_readyz_503_when_smtp_down() {
    let router = test_router(1);
    let resp = send(&router, RequestBuilder::get("/readyz").build()).await;
    resp.assert_status(StatusCode::SERVICE_UNAVAILABLE);
}

// ===========================================================================
// E2E-007 — request_id in response body matches X-Request-Id header
// ===========================================================================

#[tokio::test]
async fn e2e_007_request_id_consistent() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let req = RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(common::valid_mail_body())
        .build();

    let raw_resp = router.clone().oneshot(req).await.unwrap();
    let x_request_id = raw_resp
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();

    let bytes = axum::body::to_bytes(raw_resp.into_body(), 4096).await.unwrap();
    let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    let body_request_id = body["request_id"].as_str().unwrap_or("");

    assert!(!x_request_id.is_empty(), "X-Request-Id header must be set");
    assert_eq!(
        x_request_id, body_request_id,
        "X-Request-Id header must match request_id in body"
    );

    stub.shutdown().await;
}

// ===========================================================================
// E2E-008 — Valid mail body is forwarded correctly to SMTP stub
// ===========================================================================

#[tokio::test]
async fn e2e_008_mail_envelope_and_body_correct() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let _ = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .json(json!({
                "to": "alice@example.com",
                "subject": "Hello Alice",
                "body": "Dear Alice, this is a test."
            }))
            .build(),
    )
    .await;

    stub.assert_count(1);
    let msg = stub.assert_one();
    assert!(msg.envelope_to.contains("alice@example.com"), "wrong RCPT TO: {}", msg.envelope_to);
    assert!(
        msg.body.contains("Dear Alice"),
        "body not forwarded: {}",
        msg.body
    );
    assert!(
        !msg.body.contains("primary-secret-padded-to-32bytes!"),
        "API secret must not appear in the submitted mail body"
    );

    stub.shutdown().await;
}

// ===========================================================================
// E2E-009 — Wrong Content-Type → 415
// ===========================================================================

#[tokio::test]
async fn e2e_009_wrong_content_type_returns_415() {
    let router = test_router_no_smtp();
    let resp = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .content_type("text/plain")
            .raw_body(b"not json".to_vec())
            .build(),
    )
    .await;
    assert_eq!(
        resp.status,
        StatusCode::UNSUPPORTED_MEDIA_TYPE,
        "wrong content-type must return 415; got {} body={}",
        resp.status,
        resp.body
    );
}

// ===========================================================================
// Structural: From address always comes from config (never from request)
// ===========================================================================

#[tokio::test]
async fn from_address_always_from_config() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let _ = send(
        &router,
        RequestBuilder::post("/v1/send")
            .bearer("primary-secret-padded-to-32bytes!")
            .json(json!({
                "to": "user@example.com",
                "subject": "Test",
                "body": "Hello."
            }))
            .build(),
    )
    .await;

    stub.assert_count(1);
    let msg = stub.assert_one();
    // The MAIL FROM envelope must be the config address, never something from the JSON
    assert!(
        msg.envelope_from.contains("relay@example.com"),
        "MAIL FROM must be relay@example.com (config), got: {}",
        msg.envelope_from
    );

    stub.shutdown().await;
}

// ===========================================================================
// RFC 201-203 — Rate limit tier burst and per-key config
// ===========================================================================

#[tokio::test]
async fn per_key_burst_override_respected() {
    use http_smtp_rele::{api, AppState};

    let mut cfg = common::test_config(1);
    // Key with burst=2; global has burst=50 but key overrides
    cfg.security.api_keys[0].burst = 2;
    cfg.rate_limit.global_burst = 50;
    cfg.rate_limit.per_key_burst = 2;
    let router = api::build_router(AppState::new(cfg));

    // Exhaust the 2-token burst
    let _ = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!").json(common::valid_mail_body()).build()).await;
    let _ = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!").json(common::valid_mail_body()).build()).await;

    // Third request should be rate-limited for this key
    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!").json(common::valid_mail_body()).build()).await;
    resp.assert_status(StatusCode::TOO_MANY_REQUESTS)
        .assert_code("rate_limited");
}

#[tokio::test]
async fn per_key_default_rate_distinct_from_ip_rate() {
    use http_smtp_rele::{api, AppState};

    let mut cfg = common::test_config(1);
    cfg.rate_limit.per_key_per_min = 600;   // generous per-key default
    cfg.rate_limit.per_ip_per_min  = 1;     // very tight IP rate
    cfg.rate_limit.per_ip_burst    = 1;
    cfg.rate_limit.global_burst    = 200;
    cfg.rate_limit.per_key_burst   = 200;
    let router = api::build_router(AppState::new(cfg));

    // With per_ip burst=1, the second request from the same IP hits IP rate limit
    let _ = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!").json(common::valid_mail_body()).build()).await;
    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!").json(common::valid_mail_body()).build()).await;
    resp.assert_status(StatusCode::TOO_MANY_REQUESTS);
    assert_eq!(resp.body["code"], "rate_limited");
}

// ===========================================================================
// RFC 204 — Per-address recipient allowlist
// ===========================================================================

#[tokio::test]
async fn per_address_allowlist_permits_listed_address() {
    use http_smtp_rele::{api, AppState};

    let mut cfg = common::test_config(1);
    cfg.security.api_keys[0].allowed_recipients = vec!["alice@example.com".into()];
    let router = api::build_router(AppState::new(cfg));

    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({
            "to": "alice@example.com",
            "subject": "Hi",
            "body": "Hello."
        }))
        .build()).await;
    // Fails at SMTP (port 1), not at policy — 502 means it got through validation
    resp.assert_status(StatusCode::BAD_GATEWAY);
}

#[tokio::test]
async fn per_address_allowlist_blocks_unlisted_address() {
    use http_smtp_rele::{api, AppState};

    let mut cfg = common::test_config(1);
    cfg.security.api_keys[0].allowed_recipients = vec!["alice@example.com".into()];
    let router = api::build_router(AppState::new(cfg));

    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({
            "to": "bob@example.com",
            "subject": "Hi",
            "body": "Hello."
        }))
        .build()).await;
    resp.assert_status(StatusCode::BAD_REQUEST)
        .assert_code("validation_failed");
}

#[tokio::test]
async fn per_address_empty_list_falls_through_to_domain_policy() {
    use http_smtp_rele::{api, AppState};

    let mut cfg = common::test_config(1);
    // allowed_recipients is empty — domain policy applies
    cfg.security.api_keys[0].allowed_recipients = vec![];
    cfg.mail.allowed_recipient_domains = vec!["example.com".into()];
    let router = api::build_router(AppState::new(cfg));

    // Within allowed domain — reaches SMTP
    let ok = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({"to":"any@example.com","subject":"Hi","body":"Hi"}))
        .build()).await;
    assert_ne!(ok.status, StatusCode::BAD_REQUEST, "should pass domain check");

    // Outside allowed domain — blocked
    let blocked = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({"to":"evil@evil.com","subject":"Hi","body":"Hi"}))
        .build()).await;
    blocked.assert_status(StatusCode::BAD_REQUEST);
}

// ===========================================================================
// RFC 205 — Concurrency limit
// ===========================================================================

#[tokio::test]
async fn concurrency_limit_zero_is_unlimited() {
    // concurrency_limit = 0 (default) should never return 503 from concurrency
    let router = test_router_no_smtp();
    let resp = send_valid(&router).await;
    // 502 (SMTP down) is fine — it means concurrency check passed
    assert_ne!(resp.status, StatusCode::SERVICE_UNAVAILABLE,
        "concurrency=0 should not reject requests");
}

// ===========================================================================
// RFC 301 — SMTP AUTH (config validation)
// ===========================================================================

#[tokio::test]
async fn smtp_auth_user_only_fails_config_validation() {
    use http_smtp_rele::config;
    use std::path::Path;
    // Write a temp config with only auth_user (missing auth_password)
    let toml = r#"
[mail]
default_from = "r@example.com"
[[security.api_keys]]
id = "k"
secret = "sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
enabled = true
[smtp]
auth_user = "user@example.com"
"#;
    let tmp = std::env::temp_dir().join("http-smtp-rele-test-auth.toml");
    std::fs::write(&tmp, toml).unwrap();
    let result = config::load(Path::new(&tmp));
    std::fs::remove_file(&tmp).ok();
    assert!(result.is_err(), "auth_user without auth_password must fail config load");
}

// ===========================================================================
// RFC 302 — Multi-recipient to
// ===========================================================================

#[tokio::test]
async fn multi_recipient_array_delivers_to_all() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({
            "to": ["alice@example.com", "bob@example.com"],
            "subject": "Multi-recipient test",
            "body": "Hello both."
        }))
        .build()).await;
    resp.assert_status(StatusCode::ACCEPTED);

    // The stub receives one SMTP transaction; the message has two RCPT TO entries.
    // lettre sends both recipients in a single DATA session.
    stub.assert_count(1);
    let msg = stub.assert_one();
    // At minimum, one recipient should appear in envelope
    assert!(
        msg.envelope_to.contains("alice@example.com") ||
        msg.envelope_to.contains("bob@example.com"),
        "expected a recipient in envelope, got: {}", msg.envelope_to
    );

    stub.shutdown().await;
}

#[tokio::test]
async fn multi_recipient_string_still_works() {
    let stub = SmtpStub::start(0).await;
    let router = test_router(stub.port());

    let resp = send_valid(&router).await;
    resp.assert_status(StatusCode::ACCEPTED);
    stub.assert_count(1);
    stub.shutdown().await;
}

#[tokio::test]
async fn multi_recipient_empty_array_rejected() {
    let router = test_router_no_smtp();
    let resp = send(&router, RequestBuilder::post("/v1/send")
        .bearer("primary-secret-padded-to-32bytes!")
        .json(serde_json::json!({
            "to": [],
            "subject": "Hi",
            "body": "Hello."
        }))
        .build()).await;
    assert_ne!(resp.status, StatusCode::ACCEPTED, "empty to array must be rejected");
}

// ===========================================================================
// RFC 303 — W3C Forwarded header
// ===========================================================================

#[tokio::test]
async fn forwarded_header_resolved_when_trusted_proxy() {
    use http_smtp_rele::{api, AppState};

    // Configure trust for 127.0.0.1 (the test loopback peer)
    let mut cfg = common::test_config(1);
    cfg.security.trust_proxy_headers = true;
    cfg.security.trusted_source_cidrs = vec!["127.0.0.1/32".into()];
    // Disallow 10.0.0.1 so requests from that IP are blocked
    cfg.security.allowed_source_cidrs = vec!["1.2.3.4/32".into()];
    let router = api::build_router(AppState::new(cfg));

    // Send with Forwarded: for=10.0.0.1 (different from allowed list)
    // The resolved IP would be 10.0.0.1, which is not in allowed_source_cidrs
    use axum::http::header;
    let resp = send(&router, axum::http::Request::builder()
        .method("POST")
        .uri("/v1/send")
        .header(header::AUTHORIZATION, "Bearer primary-secret-padded-to-32bytes!")
        .header(header::CONTENT_TYPE, "application/json")
        .header("forwarded", "for=10.0.0.1")
        .body(axum::body::Body::from(
            serde_json::to_string(&common::valid_mail_body()).unwrap()
        ))
        .unwrap()).await;
    // Should be forbidden (10.0.0.1 not in allowed_source_cidrs)
    resp.assert_status(StatusCode::FORBIDDEN);
}

// ===========================================================================
// RFC 305 — SIGHUP config reload (structural: ArcSwap store/load)
// ===========================================================================

#[tokio::test]
async fn arcswap_config_hot_swap_takes_effect_immediately() {
    use http_smtp_rele::{AppState, config::*};
    

    let cfg = common::test_config(1);
    let state = AppState::new(cfg);

    // Verify initial key
    {
        let c = state.config();
        assert_eq!(c.security.api_keys[0].id, "primary");
    }

    // Swap in a new config with a different key id
    let mut new_cfg = common::test_config(1);
    new_cfg.security.api_keys[0] = ApiKeyConfig {
        id: "new-key".into(),
        secret: SecretString::new("new-secret"),
        enabled: true,
        description: None,
        allowed_recipient_domains: vec!["example.com".into()],
        allowed_recipients: vec![],
        rate_limit_per_min: None,
        burst: 0,
        mask_recipient: None,
    };
    state.reload_config(new_cfg);

    // New config is visible immediately
    {
        let c = state.config();
        assert_eq!(c.security.api_keys[0].id, "new-key");
    }
}

// ===========================================================================