rusmes-smtp 0.1.2

Async SMTP server for RusMES — RFC 5321 compliant with STARTTLS, AUTH (PLAIN/LOGIN/CRAM-MD5/SCRAM-SHA-256), PIPELINING, DSN, and BDAT/CHUNKING
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use super::*;
use async_trait::async_trait;
use rusmes_core::{MailProcessorRouter, RateLimitConfig, RateLimiter};
use rusmes_metrics::MetricsCollector;
use rusmes_storage::backends::filesystem::FilesystemBackend;

/// Auth backend that always reports `Ok(None)` for SCRAM lookups so we can
/// exercise the "mechanism not available" branch of the SMTP SCRAM handler.
struct ScramMissingBackend;

#[async_trait]
impl AuthBackend for ScramMissingBackend {
    async fn authenticate(&self, _username: &Username, _password: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn verify_identity(&self, _username: &Username) -> anyhow::Result<bool> {
        Ok(true)
    }

    async fn list_users(&self) -> anyhow::Result<Vec<Username>> {
        Ok(Vec::new())
    }

    async fn create_user(&self, _username: &Username, _password: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn delete_user(&self, _username: &Username) -> anyhow::Result<()> {
        Ok(())
    }

    async fn change_password(
        &self,
        _username: &Username,
        _new_password: &str,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    // Inherits the trait default: `fetch_scram_credentials -> Ok(None)`.
}

fn make_session(
    auth_backend: Arc<dyn AuthBackend>,
    storage_backend: Arc<dyn StorageBackend>,
) -> SmtpSession {
    let metrics = Arc::new(MetricsCollector::new());
    let processor_router = Arc::new(MailProcessorRouter::new(metrics));
    let rate_limiter = Arc::new(RateLimiter::new(RateLimitConfig::default()));
    let remote_addr: SocketAddr = "127.0.0.1:54321"
        .parse()
        .expect("static socket addr literal must parse");
    SmtpSession {
        remote_addr,
        state: SmtpState::Authenticated,
        transaction: SmtpTransaction::new(),
        config: SmtpConfig {
            require_auth: true,
            ..SmtpConfig::default()
        },
        authenticated: false,
        username: None,
        relaying_allowed: false,
        processor_router,
        auth_backend,
        rate_limiter,
        storage_backend,
        recipient_cache: Arc::new(RwLock::new(HashMap::new())),
        cram_md5_challenge: None,
        scram_state: None,
        ehlo_used: false,
        peer_certificates: None,
    }
}

/// Cluster 1D: when the auth backend reports `Ok(None)` for a user's SCRAM
/// credentials, the SMTP server must respond `504 5.5.4 ... mechanism not
/// available` per RFC 4954 §4 and decline the SCRAM exchange (PLAIN/LOGIN
/// remain available to the client).
#[tokio::test]
async fn scram_rejected_when_credentials_missing() {
    let tmp = std::env::temp_dir().join(format!("rusmes-smtp-scram-test-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir for filesystem backend");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);

    let mut session = make_session(auth, storage);

    // Build a valid SCRAM client-first message: GS2 header `n,,` + n=user,r=nonce.
    // The server should fetch credentials, get `Ok(None)`, and respond 504.
    let client_first = "n,,n=alice,r=fyko+d2lbbFgONRv9qkxdawL";
    let initial = BASE64.encode(client_first.as_bytes());

    let response = session
        .handle_auth_scram_sha256(Some(initial))
        .await
        .expect("handle_auth_scram_sha256 must not error on Ok(None)");

    assert_eq!(
        response.code(),
        504,
        "missing SCRAM credentials must yield 504 (mechanism not available)"
    );
    assert!(
        !session.authenticated,
        "session must not be marked authenticated when SCRAM is declined"
    );
    assert!(
        session.scram_state.is_none(),
        "no SCRAM state should be retained after a 504 reply"
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

// ── Metrics counter tests ──────────────────────────────────────────────────
//
// These tests drive protocol-layer methods directly and assert on *delta* values
// so they are safe under parallel nextest workers that share the global singleton.

/// `test_smtp_connection_counter_increments` — the MetricsCollector counter
/// `smtp_connections_total` increments by 1 when `inc_smtp_connections()` is called.
/// This mirrors what `SmtpSessionHandler::handle()` does at session start.
#[test]
fn test_smtp_connection_counter_increments() {
    let m = MetricsCollector::new();
    assert_eq!(m.smtp_connections_count(), 0);
    m.inc_smtp_connections();
    assert_eq!(m.smtp_connections_count(), 1);
    m.inc_smtp_connections();
    assert_eq!(m.smtp_connections_count(), 2);
}

/// `test_smtp_auth_success_counter` — a successful PLAIN AUTH increments
/// `smtp_auth_success_total` by 1 (delta check on global metrics).
#[tokio::test]
async fn test_smtp_auth_success_counter() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-auth-ok-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));

    // AlwaysOkBackend: authenticate always returns Ok(true).
    struct AlwaysOkBackend;
    #[async_trait]
    impl AuthBackend for AlwaysOkBackend {
        async fn authenticate(&self, _u: &Username, _p: &str) -> anyhow::Result<bool> {
            Ok(true)
        }
        async fn verify_identity(&self, _u: &Username) -> anyhow::Result<bool> {
            Ok(true)
        }
        async fn list_users(&self) -> anyhow::Result<Vec<Username>> {
            Ok(vec![])
        }
        async fn create_user(&self, _u: &Username, _p: &str) -> anyhow::Result<()> {
            Ok(())
        }
        async fn delete_user(&self, _u: &Username) -> anyhow::Result<()> {
            Ok(())
        }
        async fn change_password(&self, _u: &Username, _p: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    let auth: Arc<dyn AuthBackend> = Arc::new(AlwaysOkBackend);
    let mut session = make_session(auth, storage);

    let before = rusmes_metrics::global_metrics().smtp_auth_success_count();
    // Build a valid PLAIN credential: \0username\0password (base64-encoded).
    let plain = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"\0testuser\0testpass",
    );
    let resp = session
        .handle_auth_plain(plain)
        .await
        .expect("handle_auth_plain must not error");
    assert_eq!(resp.code(), 235, "expected 235 Authentication successful");
    let after = rusmes_metrics::global_metrics().smtp_auth_success_count();
    assert_eq!(
        after - before,
        1,
        "smtp_auth_success_total should increment by 1 on successful PLAIN auth"
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

/// `test_smtp_auth_failure_counter` — a rejected PLAIN AUTH increments
/// `smtp_auth_failure_total` by 1 (delta check on global metrics).
#[tokio::test]
async fn test_smtp_auth_failure_counter() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-auth-fail-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));

    // AlwaysFailBackend: authenticate always returns Ok(false).
    struct AlwaysFailBackend;
    #[async_trait]
    impl AuthBackend for AlwaysFailBackend {
        async fn authenticate(&self, _u: &Username, _p: &str) -> anyhow::Result<bool> {
            Ok(false)
        }
        async fn verify_identity(&self, _u: &Username) -> anyhow::Result<bool> {
            Ok(false)
        }
        async fn list_users(&self) -> anyhow::Result<Vec<Username>> {
            Ok(vec![])
        }
        async fn create_user(&self, _u: &Username, _p: &str) -> anyhow::Result<()> {
            Ok(())
        }
        async fn delete_user(&self, _u: &Username) -> anyhow::Result<()> {
            Ok(())
        }
        async fn change_password(&self, _u: &Username, _p: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    let auth: Arc<dyn AuthBackend> = Arc::new(AlwaysFailBackend);
    let mut session = make_session(auth, storage);

    let before = rusmes_metrics::global_metrics().smtp_auth_failure_count();
    let plain = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"\0wronguser\0wrongpass",
    );
    let resp = session
        .handle_auth_plain(plain)
        .await
        .expect("handle_auth_plain must not error");
    assert_eq!(resp.code(), 535, "expected 535 Authentication failed");
    let after = rusmes_metrics::global_metrics().smtp_auth_failure_count();
    assert_eq!(
        after - before,
        1,
        "smtp_auth_failure_total should increment by 1 on failed PLAIN auth"
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

/// `test_smtp_message_accepted_counter` — completing a DATA transaction
/// increments `smtp_messages_received` (the "accepted" counter) by 1.
///
/// We drive `handle_data_input` directly with an in-memory reader/writer so we
/// don't need a full TCP stack.
#[tokio::test]
async fn test_smtp_message_accepted_counter() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-msg-ok-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    // Set up a valid transaction (sender + recipient).
    session.transaction.sender = Some("sender@example.com".parse().expect("valid sender address"));
    session
        .transaction
        .recipients
        .push("rcpt@example.com".parse().expect("valid recipient address"));

    // Craft DATA stream: header + blank line + body + terminator dot.
    // `&[u8]` implements `AsyncRead` so `BufReader<&[u8]>` works directly.
    let data_stream: &[u8] = b"From: sender@example.com\r\nSubject: test\r\n\r\nHello\r\n.\r\n";
    let mut async_reader = tokio::io::BufReader::new(data_stream);

    let mut writer_buf: Vec<u8> = Vec::new();
    let remote_addr: SocketAddr = "127.0.0.1:54321"
        .parse()
        .expect("static socket addr literal must parse");

    let before = rusmes_metrics::global_metrics().smtp_messages_accepted_count();

    SmtpSessionHandler::handle_data_input(
        &mut session,
        &mut async_reader,
        &mut writer_buf,
        &remote_addr,
    )
    .await
    .expect("handle_data_input must succeed");

    let after = rusmes_metrics::global_metrics().smtp_messages_accepted_count();
    assert_eq!(
        after - before,
        1,
        "smtp_messages_received should increment by 1 on DATA acceptance"
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn test_transaction_validity() {
    let mut tx = SmtpTransaction::new();
    assert!(!tx.is_valid());

    tx.sender = Some(
        "sender@example.com"
            .parse()
            .expect("valid email address literal"),
    );
    assert!(!tx.is_valid());

    tx.recipients.push(
        "rcpt@example.com"
            .parse()
            .expect("valid email address literal"),
    );
    assert!(tx.is_valid());

    tx.reset();
    assert!(!tx.is_valid());
}

#[test]
fn test_smtp_config_default() {
    let config = SmtpConfig::default();
    assert_eq!(config.hostname, "localhost");
    assert_eq!(config.max_message_size, 10 * 1024 * 1024);
    assert!(!config.require_auth);
    assert!(!config.enable_starttls);
}

// ── SMTPUTF8 / RFC 6531 session-layer tests ────────────────────────────

/// The EHLO capability list must include `SMTPUTF8`.
#[tokio::test]
async fn test_ehlo_advertises_smtputf8() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-ehlo-smtputf8-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    let resp = session
        .handle_ehlo("client.example.com".to_string())
        .await
        .expect("handle_ehlo must not error");

    let formatted = resp.format();
    assert!(
        formatted.contains("SMTPUTF8"),
        "EHLO response must advertise SMTPUTF8; got:\n{}",
        formatted
    );
    assert!(session.ehlo_used, "ehlo_used flag must be set after EHLO");

    let _ = std::fs::remove_dir_all(&tmp);
}

/// After HELO (not EHLO), the SMTPUTF8 mail parameter must be rejected.
#[tokio::test]
async fn test_smtputf8_requires_ehlo_not_helo() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-smtputf8-helo-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    // HELO — no ESMTP extensions.
    session
        .handle_helo("client.example.com".to_string())
        .await
        .expect("handle_helo must not error");
    assert!(!session.ehlo_used, "ehlo_used must be false after HELO");

    // MAIL FROM with SMTPUTF8 parameter — must be rejected.
    let from = "sender@example.com"
        .parse::<MailAddress>()
        .expect("valid address");
    let params = vec![crate::command::MailParam::new("SMTPUTF8".to_string(), None)];

    let resp = session
        .handle_mail(from, params)
        .await
        .expect("handle_mail must not error internally");

    assert!(
        resp.code() >= 500,
        "SMTPUTF8 after HELO must yield a 5xx error; got {}",
        resp.code()
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

/// A non-ASCII local-part sent without the SMTPUTF8 parameter must be
/// rejected with 501 5.5.4 even after EHLO (RFC 6531 §3.4).
#[tokio::test]
async fn test_smtputf8_param_required_for_unicode_address() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-smtputf8-param-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);
    // Mark as authenticated so handle_mail's require_auth guard is satisfied.
    session.authenticated = true;

    // EHLO first — ESMTP extensions available.
    session
        .handle_ehlo("client.example.com".to_string())
        .await
        .expect("handle_ehlo must not error");

    // Construct a non-ASCII address via the SMTPUTF8 constructor,
    // then pass it WITHOUT the SMTPUTF8 parameter in MAIL FROM.
    let domain = rusmes_proto::Domain::new("example.com").expect("valid domain");
    let from = MailAddress::new_smtputf8("münchen", domain)
        .expect("SMTPUTF8 address must be constructable");

    // No SMTPUTF8 parameter — should trigger 501 5.5.4.
    let resp = session
        .handle_mail(from, vec![])
        .await
        .expect("handle_mail must not error internally");

    assert_eq!(
        resp.code(),
        501,
        "Non-ASCII address without SMTPUTF8 param must yield 501; got {}",
        resp.code()
    );
    assert!(
        resp.format().contains("5.5.4"),
        "Response must contain enhanced status 5.5.4; got:\n{}",
        resp.format()
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

// ── DATA tempfile spill threshold tests ───────────────────────────────────

/// Collect the set of file paths currently present in `dir`.
///
/// Only entries that are plain files (not directories) are included.  Errors
/// reading individual entries are silently ignored so that transient system
/// tempfiles do not derail the test.
fn snapshot_dir_files(dir: &std::path::Path) -> std::collections::HashSet<std::path::PathBuf> {
    std::fs::read_dir(dir)
        .map(|rd| {
            rd.filter_map(|entry| {
                let entry = entry.ok()?;
                let ft = entry.file_type().ok()?;
                if ft.is_file() {
                    Some(entry.path())
                } else {
                    None
                }
            })
            .collect()
        })
        .unwrap_or_default()
}

/// Below the threshold, DATA should stay in memory (MessageBody::Small).
///
/// Verified using an isolated `data_spill_dir`: no files appear in that
/// directory when the in-memory path is taken.
#[tokio::test]
async fn test_data_input_stays_in_memory_below_threshold() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-data-mem-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    // Dedicated spill dir — isolated from other concurrent tests.
    let spill_dir = tmp.join("spill");
    std::fs::create_dir_all(&spill_dir).expect("create spill dir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    // Set threshold to 1 MiB; payload is 64 KiB, well below threshold.
    session.config.data_tempfile_threshold = 1024 * 1024;
    session.config.data_spill_dir = spill_dir.clone();

    session.transaction.sender = Some("sender@example.com".parse().expect("valid sender address"));
    session
        .transaction
        .recipients
        .push("rcpt@example.com".parse().expect("valid recipient address"));

    // Build a 64 KiB body (line-based, dot-terminated).
    let body_line = "X".repeat(78) + "\r\n"; // 80 bytes per line
    let line_count = (64 * 1024) / 80; // ~819 lines for ~64 KiB
    let mut data = String::from("From: sender@example.com\r\nSubject: mem-test\r\n\r\n");
    for _ in 0..line_count {
        data.push_str(&body_line);
    }
    data.push_str(".\r\n");

    let data_bytes = data.into_bytes();
    let mut async_reader = tokio::io::BufReader::new(data_bytes.as_slice());
    let mut writer_buf: Vec<u8> = Vec::new();
    let remote_addr: SocketAddr = "127.0.0.1:54321"
        .parse()
        .expect("static socket addr literal must parse");

    SmtpSessionHandler::handle_data_input(
        &mut session,
        &mut async_reader,
        &mut writer_buf,
        &remote_addr,
    )
    .await
    .expect("handle_data_input must succeed for small payload");

    // Verify the response is 250 OK (message accepted).
    let response_str = String::from_utf8_lossy(&writer_buf);
    assert!(
        response_str.contains("250"),
        "Expected 250 OK response for small payload; got: {}",
        response_str
    );

    // In-memory path must not create any files in the isolated spill dir.
    let spill_files = snapshot_dir_files(&spill_dir);
    assert!(
        spill_files.is_empty(),
        "In-memory path must not create tempfiles in spill_dir; found: {:?}",
        spill_files
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

/// Above the threshold, DATA should spill to a tempfile (MessageBody::Large).
///
/// Verified using an isolated `data_spill_dir` in two stages:
/// 1. Immediately after `handle_data_input` returns, at least one file exists
///    in the isolated spill dir (the spill file was created and kept).
/// 2. After yielding briefly so the spawned cleanup task can run, the spill
///    file is deleted (the isolated dir is empty again).
#[tokio::test]
async fn test_data_input_spills_above_threshold() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-data-spill-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    // Dedicated spill dir — isolated from other concurrent tests.
    let spill_dir = tmp.join("spill");
    std::fs::create_dir_all(&spill_dir).expect("create spill dir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    // Set threshold to 64 KiB; payload is ~2 MiB, triggering spill.
    session.config.data_tempfile_threshold = 64 * 1024;
    session.config.data_spill_dir = spill_dir.clone();
    // Raise max_message_size so the 2 MiB message is accepted.
    session.config.max_message_size = 10 * 1024 * 1024;

    session.transaction.sender = Some("sender@example.com".parse().expect("valid sender address"));
    session
        .transaction
        .recipients
        .push("rcpt@example.com".parse().expect("valid recipient address"));

    // Build a ~2 MiB body.
    let body_line = "Y".repeat(78) + "\r\n"; // 80 bytes per line
    let line_count = (2 * 1024 * 1024) / 80; // ~26214 lines for ~2 MiB
    let mut data = String::from("From: sender@example.com\r\nSubject: spill-test\r\n\r\n");
    for _ in 0..line_count {
        data.push_str(&body_line);
    }
    data.push_str(".\r\n");

    let data_bytes = data.into_bytes();
    let mut async_reader = tokio::io::BufReader::new(data_bytes.as_slice());
    let mut writer_buf: Vec<u8> = Vec::new();
    let remote_addr: SocketAddr = "127.0.0.1:54321"
        .parse()
        .expect("static socket addr literal must parse");

    SmtpSessionHandler::handle_data_input(
        &mut session,
        &mut async_reader,
        &mut writer_buf,
        &remote_addr,
    )
    .await
    .expect("handle_data_input must succeed for large payload");

    // Verify the response is 250 OK.
    let response_str = String::from_utf8_lossy(&writer_buf);
    assert!(
        response_str.contains("250"),
        "Expected 250 OK response for large payload; got: {}",
        response_str
    );

    // Immediately after the call, the spill file must exist in the isolated dir.
    let spill_files_after_call = snapshot_dir_files(&spill_dir);
    assert!(
        !spill_files_after_call.is_empty(),
        "Spill path must have created at least one file in spill_dir immediately after the call"
    );

    // Yield to the Tokio runtime so the spawned cleanup task gets a chance to run
    // and delete the spill file.
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // After cleanup the spill dir must be empty.
    let spill_files_after_cleanup = snapshot_dir_files(&spill_dir);
    assert!(
        spill_files_after_cleanup.is_empty(),
        "Spill tempfile must be deleted by the cleanup task; still present: {:?}",
        spill_files_after_cleanup
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

/// Exactly at the threshold (not one byte over), message stays in memory.
///
/// Verified using an isolated `data_spill_dir`: at exactly threshold bytes,
/// the strict `>` condition in the spill logic is not triggered, so the
/// isolated spill directory remains empty.
#[tokio::test]
async fn test_data_input_threshold_boundary() {
    let tmp = std::env::temp_dir().join(format!(
        "rusmes-smtp-data-boundary-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("create tempdir");

    // Dedicated spill dir — isolated from other concurrent tests.
    let spill_dir = tmp.join("spill");
    std::fs::create_dir_all(&spill_dir).expect("create spill dir");

    let storage: Arc<dyn StorageBackend> = Arc::new(FilesystemBackend::new(&tmp));
    let auth: Arc<dyn AuthBackend> = Arc::new(ScramMissingBackend);
    let mut session = make_session(auth, storage);

    // Threshold: 1024 bytes. Payload: exactly 1024 bytes of body.
    // The strict `>` semantics mean at exactly threshold, it stays in memory.
    let threshold = 1024usize;
    session.config.data_tempfile_threshold = threshold;
    session.config.data_spill_dir = spill_dir.clone();
    session.config.max_message_size = 10 * 1024 * 1024;

    session.transaction.sender = Some("sender@example.com".parse().expect("valid sender address"));
    session
        .transaction
        .recipients
        .push("rcpt@example.com".parse().expect("valid recipient address"));

    // Build header; then fill body to reach threshold exactly.
    let header = "From: sender@example.com\r\nSubject: boundary\r\n\r\n";
    // body_line is 80 bytes (78 'Z' + \r\n), we add lines until we're at/near threshold.
    let body_line = "Z".repeat(78) + "\r\n";
    let lines_needed = threshold / 80; // bytes in full lines up to threshold
    let mut data = String::from(header);
    for _ in 0..lines_needed {
        data.push_str(&body_line);
    }
    data.push_str(".\r\n");

    let data_bytes = data.into_bytes();
    let mut async_reader = tokio::io::BufReader::new(data_bytes.as_slice());
    let mut writer_buf: Vec<u8> = Vec::new();
    let remote_addr: SocketAddr = "127.0.0.1:54321"
        .parse()
        .expect("static socket addr literal must parse");

    SmtpSessionHandler::handle_data_input(
        &mut session,
        &mut async_reader,
        &mut writer_buf,
        &remote_addr,
    )
    .await
    .expect("handle_data_input must succeed at threshold boundary");

    let response_str = String::from_utf8_lossy(&writer_buf);
    assert!(
        response_str.contains("250"),
        "Expected 250 OK at threshold boundary; got: {}",
        response_str
    );

    // At exactly threshold bytes, the isolated spill dir must remain empty.
    let spill_files = snapshot_dir_files(&spill_dir);
    assert!(
        spill_files.is_empty(),
        "At-threshold boundary must stay in memory (no files in spill_dir); found: {:?}",
        spill_files
    );

    let _ = std::fs::remove_dir_all(&tmp);
}