wasm-smtp-core 0.2.0

Environment-independent SMTP client core for WASM and other constrained runtimes.
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
//! Internal test suite for `wasm-smtp-core`.
//!
//! These tests exercise every layer of the crate that does not require a
//! real network:
//!
//! - `protocol_tests` covers reply-line parsing, command formatting,
//!   dot-stuffing, base64 encoding, input validation, and EHLO capability
//!   inspection.
//! - `session_tests` covers the [`crate::session::SessionState`] state
//!   machine.
//! - `error_tests` covers the public error surface and ensures
//!   [`crate::error::InvalidInputError`] cannot embed runtime-supplied
//!   strings.
//! - `client_tests` drives the full SMTP exchange against a synchronous
//!   mock transport.
//!
//! There is no executor: the mock transport always resolves immediately, so
//! a no-op waker is sufficient to drive the futures.

#![allow(
    // These pedantic lints are useful in production code but produce a lot
    // of noise in test fixtures, where short scripts and explicit byte
    // literals are the norm.
    clippy::needless_pass_by_value,
    clippy::similar_names,
    clippy::too_many_lines,
    clippy::unreadable_literal,
    clippy::missing_panics_doc
)]

mod harness {
    use crate::error::IoError;
    use crate::transport::{StartTlsCapable, Transport};
    use core::future::Future;
    use core::pin::pin;
    use core::task::{Context, Poll, Waker};
    use std::cell::RefCell;
    use std::collections::VecDeque;
    use std::rc::Rc;

    /// Behavior of [`MockTransport`]'s STARTTLS upgrade. Tests configure
    /// this when building the transport.
    #[derive(Debug, Clone)]
    pub enum UpgradeBehavior {
        /// `upgrade_to_tls()` returns `Ok(())`.
        Succeed,
        /// `upgrade_to_tls()` returns `Err` with this message.
        Fail(&'static str),
    }

    /// Drive a future to completion using a no-op waker.
    ///
    /// This is sound only for futures whose `Pending` state would never be
    /// observed by a real executor: the mock transport in this module
    /// always resolves its `read` and `write_all` futures synchronously,
    /// so the very first `poll` will return `Ready`.
    pub fn block_on<F: Future>(fut: F) -> F::Output {
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        let mut fut = pin!(fut);
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(value) => value,
            Poll::Pending => panic!("mock-driven future returned Pending"),
        }
    }

    /// Triple of (mock transport, captured outgoing bytes, close flag),
    /// returned by [`MockTransport::new`].
    pub type MockHandles = (MockTransport, Rc<RefCell<Vec<u8>>>, Rc<RefCell<bool>>);

    /// Quadruple returned by [`MockTransport::with_starttls`]: the
    /// transport, the captured-bytes handle, the close flag, and a
    /// counter that is incremented each time `upgrade_to_tls()` is
    /// invoked.
    pub type MockStartTlsHandles = (
        MockTransport,
        Rc<RefCell<Vec<u8>>>,
        Rc<RefCell<bool>>,
        Rc<RefCell<u32>>,
    );

    /// Synchronous mock transport.
    ///
    /// `incoming` is a queue of byte chunks; each chunk is one "wire
    /// delivery" and may be split across multiple `read` calls depending
    /// on the caller's buffer size. When the queue is exhausted, further
    /// `read`s return `Ok(0)`, which the SMTP state machine interprets as
    /// a clean close from the peer.
    ///
    /// `written` is held behind `Rc<RefCell<_>>` so the test can keep a
    /// handle to it after the transport has been moved into the client.
    pub struct MockTransport {
        incoming: VecDeque<Vec<u8>>,
        written: Rc<RefCell<Vec<u8>>>,
        closed: Rc<RefCell<bool>>,
        /// Number of times `upgrade_to_tls()` has been called. Incremented
        /// whether the call succeeds or fails.
        upgrades: Rc<RefCell<u32>>,
        /// Configured behavior for `upgrade_to_tls()`.
        upgrade_behavior: UpgradeBehavior,
    }

    impl MockTransport {
        /// Construct a mock transport from a list of byte chunks. Each
        /// chunk corresponds to one "wire packet". Returns the transport
        /// together with shared handles to the captured outgoing bytes
        /// and the close flag.
        ///
        /// The transport's `upgrade_to_tls()` succeeds by default but is
        /// not exposed; tests that exercise STARTTLS should use
        /// [`Self::with_starttls`] instead.
        pub fn new(chunks: &[&[u8]]) -> MockHandles {
            let (t, w, c, _u) = Self::build(chunks, UpgradeBehavior::Succeed);
            (t, w, c)
        }

        /// Construct a mock transport that exposes its STARTTLS upgrade
        /// counter, allowing tests to assert that `upgrade_to_tls()` was
        /// called the expected number of times.
        pub fn with_starttls(chunks: &[&[u8]], behavior: UpgradeBehavior) -> MockStartTlsHandles {
            Self::build(chunks, behavior)
        }

        fn build(chunks: &[&[u8]], behavior: UpgradeBehavior) -> MockStartTlsHandles {
            let written = Rc::new(RefCell::new(Vec::new()));
            let closed = Rc::new(RefCell::new(false));
            let upgrades = Rc::new(RefCell::new(0u32));
            let mut q: VecDeque<Vec<u8>> = VecDeque::new();
            for c in chunks {
                q.push_back((*c).to_vec());
            }
            (
                Self {
                    incoming: q,
                    written: Rc::clone(&written),
                    closed: Rc::clone(&closed),
                    upgrades: Rc::clone(&upgrades),
                    upgrade_behavior: behavior,
                },
                written,
                closed,
                upgrades,
            )
        }
    }

    impl Transport for MockTransport {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
            let Some(chunk) = self.incoming.front_mut() else {
                return Ok(0);
            };
            let n = buf.len().min(chunk.len());
            buf[..n].copy_from_slice(&chunk[..n]);
            chunk.drain(..n);
            if chunk.is_empty() {
                self.incoming.pop_front();
            }
            Ok(n)
        }

        async fn write_all(&mut self, buf: &[u8]) -> Result<(), IoError> {
            self.written.borrow_mut().extend_from_slice(buf);
            Ok(())
        }

        async fn close(&mut self) -> Result<(), IoError> {
            *self.closed.borrow_mut() = true;
            Ok(())
        }
    }

    impl StartTlsCapable for MockTransport {
        async fn upgrade_to_tls(&mut self) -> Result<(), IoError> {
            *self.upgrades.borrow_mut() += 1;
            match &self.upgrade_behavior {
                UpgradeBehavior::Succeed => Ok(()),
                UpgradeBehavior::Fail(msg) => Err(IoError::new(*msg)),
            }
        }
    }

    /// Concatenate several byte slices into one. Useful for assembling a
    /// scripted server reply that must be delivered in a single chunk.
    pub fn flatten(parts: &[&[u8]]) -> Vec<u8> {
        let mut v = Vec::new();
        for p in parts {
            v.extend_from_slice(p);
        }
        v
    }
}

// ---------------------------------------------------------------------------
// protocol.rs
// ---------------------------------------------------------------------------

mod protocol_tests {
    use crate::error::ProtocolError;
    use crate::protocol::{
        AuthMechanism, Reply, base64_encode, build_auth_plain_initial_response,
        dot_stuff_and_terminate, ehlo_advertises_auth, ehlo_advertises_starttls, format_command,
        format_command_arg, format_mail_from, format_rcpt_to, parse_reply_line,
        select_auth_mechanism, validate_address, validate_ehlo_domain, validate_login_password,
        validate_login_username, validate_plain_password, validate_plain_username,
    };

    // -- parse_reply_line ----------------------------------------------------

    #[test]
    fn parse_reply_line_single_line() {
        let r = parse_reply_line(b"250 OK").expect("must parse");
        assert_eq!(r.code, 250);
        assert!(r.is_last);
        assert_eq!(r.text, b"OK");
    }

    #[test]
    fn parse_reply_line_continuation() {
        let r = parse_reply_line(b"250-mail.example.com Hello").expect("must parse");
        assert_eq!(r.code, 250);
        assert!(!r.is_last);
        assert_eq!(r.text, b"mail.example.com Hello");
    }

    #[test]
    fn parse_reply_line_three_digit_only_is_last() {
        let r = parse_reply_line(b"220").expect("must parse");
        assert_eq!(r.code, 220);
        assert!(r.is_last);
        assert_eq!(r.text, b"");
    }

    #[test]
    fn parse_reply_line_separator_with_empty_text() {
        let r = parse_reply_line(b"250 ").expect("must parse");
        assert_eq!(r.code, 250);
        assert!(r.is_last);
        assert_eq!(r.text, b"");
    }

    #[test]
    fn parse_reply_line_too_short() {
        assert!(matches!(
            parse_reply_line(b""),
            Err(ProtocolError::Malformed(_))
        ));
        assert!(matches!(
            parse_reply_line(b"22"),
            Err(ProtocolError::Malformed(_))
        ));
    }

    #[test]
    fn parse_reply_line_non_digit_code() {
        assert!(matches!(
            parse_reply_line(b"abc OK"),
            Err(ProtocolError::Malformed(_))
        ));
        assert!(matches!(
            parse_reply_line(b"2x0 OK"),
            Err(ProtocolError::Malformed(_))
        ));
    }

    #[test]
    fn parse_reply_line_invalid_separator() {
        assert!(matches!(
            parse_reply_line(b"250?Something"),
            Err(ProtocolError::Malformed(_))
        ));
        assert!(matches!(
            parse_reply_line(b"250\tSomething"),
            Err(ProtocolError::Malformed(_))
        ));
    }

    // -- Reply convenience methods ------------------------------------------

    #[test]
    fn reply_class_and_joined_text() {
        let r = Reply {
            code: 451,
            lines: vec!["temporary".into(), "failure".into()],
        };
        assert_eq!(r.class(), 4);
        assert_eq!(r.joined_text(), "temporary\nfailure");
        let collected: Vec<&str> = r.iter_lines().collect();
        assert_eq!(collected, vec!["temporary", "failure"]);
    }

    // -- format_* -----------------------------------------------------------

    #[test]
    fn format_command_basic() {
        assert_eq!(format_command("QUIT"), b"QUIT\r\n");
        assert_eq!(format_command("RSET"), b"RSET\r\n");
        assert_eq!(format_command("DATA"), b"DATA\r\n");
    }

    #[test]
    fn format_command_arg_basic() {
        assert_eq!(
            format_command_arg("EHLO", "client.example.com"),
            b"EHLO client.example.com\r\n"
        );
    }

    #[test]
    fn format_mail_from_wraps_in_brackets() {
        assert_eq!(
            format_mail_from("user@example.com"),
            b"MAIL FROM:<user@example.com>\r\n"
        );
    }

    #[test]
    fn format_rcpt_to_wraps_in_brackets() {
        assert_eq!(
            format_rcpt_to("recipient@example.org"),
            b"RCPT TO:<recipient@example.org>\r\n"
        );
    }

    // -- dot_stuff_and_terminate --------------------------------------------

    #[test]
    fn dot_stuff_simple_body() {
        let out = dot_stuff_and_terminate(b"Hello world");
        assert_eq!(out, b"Hello world\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_already_crlf_terminated() {
        let out = dot_stuff_and_terminate(b"Hello\r\n");
        assert_eq!(out, b"Hello\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_dot_at_first_byte() {
        let out = dot_stuff_and_terminate(b".dotted");
        assert_eq!(out, b"..dotted\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_dot_after_crlf() {
        let out = dot_stuff_and_terminate(b"first\r\n.second\r\n");
        assert_eq!(out, b"first\r\n..second\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_dot_only_line() {
        // A bare "." line would otherwise be confused with the terminator.
        let out = dot_stuff_and_terminate(b".\r\n");
        assert_eq!(out, b"..\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_dot_inside_line_not_stuffed() {
        let out = dot_stuff_and_terminate(b"a.b\r\n");
        assert_eq!(out, b"a.b\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_multiple_consecutive_dot_lines() {
        let out = dot_stuff_and_terminate(b".a\r\n.b\r\n.c\r\n");
        assert_eq!(out, b"..a\r\n..b\r\n..c\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_double_dot_only_first_is_at_line_start() {
        // First '.' is dot-stuffed (line start); second '.' is content.
        let out = dot_stuff_and_terminate(b"..line\r\n");
        assert_eq!(out, b"...line\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_empty_body() {
        let out = dot_stuff_and_terminate(b"");
        assert_eq!(out, b"\r\n.\r\n");
    }

    #[test]
    fn dot_stuff_terminator_pattern_inside_body_is_stuffed() {
        // The literal byte sequence "\r\n.\r\n" inside the body must not
        // look like a terminator on the wire.
        let out = dot_stuff_and_terminate(b"line\r\n.\r\nmore\r\n");
        assert_eq!(out, b"line\r\n..\r\nmore\r\n.\r\n");
    }

    // -- base64_encode ------------------------------------------------------

    #[test]
    fn base64_encode_rfc4648_vectors() {
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn base64_encode_auth_login_canonical_examples() {
        assert_eq!(base64_encode(b"user"), "dXNlcg==");
        assert_eq!(base64_encode(b"pass"), "cGFzcw==");
        assert_eq!(base64_encode(b"Username:"), "VXNlcm5hbWU6");
        assert_eq!(base64_encode(b"Password:"), "UGFzc3dvcmQ6");
    }

    #[test]
    fn base64_encode_handles_high_bytes() {
        let out = base64_encode(&[0xFF, 0x00, 0xAA]);
        assert_eq!(out, "/wCq");
    }

    // -- validate_address ---------------------------------------------------

    #[test]
    fn validate_address_accepts_simple() {
        assert!(validate_address("a@b.com").is_ok());
        assert!(validate_address("first.last+tag@example.co.jp").is_ok());
    }

    #[test]
    fn validate_address_rejects_empty() {
        assert!(validate_address("").is_err());
    }

    #[test]
    fn validate_address_rejects_crlf_injection() {
        assert!(validate_address("a\r\n@b.com").is_err());
        assert!(validate_address("a@b.com\r").is_err());
        assert!(validate_address("a@b.com\n").is_err());
        assert!(validate_address("a@b.com\r\nRSET").is_err());
    }

    #[test]
    fn validate_address_rejects_brackets() {
        assert!(validate_address("<a@b.com>").is_err());
        assert!(validate_address("a@b<.com").is_err());
    }

    #[test]
    fn validate_address_rejects_whitespace() {
        assert!(validate_address("a @b.com").is_err());
        assert!(validate_address("a@b.com ").is_err());
        assert!(validate_address("a\tb@c.com").is_err());
    }

    #[test]
    fn validate_address_rejects_non_ascii() {
        assert!(validate_address("\u{30E6}\u{30FC}\u{30B6}@example.com").is_err());
    }

    #[test]
    fn validate_address_rejects_nul() {
        assert!(validate_address("a\0b@example.com").is_err());
    }

    // -- validate_ehlo_domain -----------------------------------------------

    #[test]
    fn validate_ehlo_domain_accepts_fqdn_and_address_literal() {
        assert!(validate_ehlo_domain("client.example.com").is_ok());
        assert!(validate_ehlo_domain("[192.0.2.1]").is_ok());
        assert!(validate_ehlo_domain("[IPv6:2001:db8::1]").is_ok());
    }

    #[test]
    fn validate_ehlo_domain_rejects_empty() {
        assert!(validate_ehlo_domain("").is_err());
    }

    #[test]
    fn validate_ehlo_domain_rejects_whitespace_and_crlf() {
        assert!(validate_ehlo_domain("client example com").is_err());
        assert!(validate_ehlo_domain("client.example.com\r\nRSET").is_err());
    }

    #[test]
    fn validate_ehlo_domain_rejects_non_ascii() {
        assert!(validate_ehlo_domain("\u{4F8B}.example").is_err());
    }

    // -- validate_login_* ---------------------------------------------------

    #[test]
    fn validate_login_credentials_reject_empty() {
        assert!(validate_login_username("").is_err());
        assert!(validate_login_password("").is_err());
        assert!(validate_login_username("user").is_ok());
        assert!(validate_login_password("pass").is_ok());
    }

    // -- ehlo_advertises_auth -----------------------------------------------

    #[test]
    fn ehlo_advertises_auth_finds_listed_mechanisms() {
        let lines: Vec<String> = vec![
            "PIPELINING".into(),
            "AUTH LOGIN PLAIN".into(),
            "8BITMIME".into(),
        ];
        assert!(ehlo_advertises_auth(&lines, "LOGIN"));
        assert!(ehlo_advertises_auth(&lines, "PLAIN"));
        assert!(!ehlo_advertises_auth(&lines, "CRAM-MD5"));
    }

    #[test]
    fn ehlo_advertises_auth_is_case_insensitive() {
        let lines: Vec<String> = vec!["auth login".into()];
        assert!(ehlo_advertises_auth(&lines, "LOGIN"));
        assert!(ehlo_advertises_auth(&lines, "login"));
    }

    #[test]
    fn ehlo_advertises_auth_no_auth_line_means_false() {
        let lines: Vec<String> = vec!["PIPELINING".into(), "8BITMIME".into()];
        assert!(!ehlo_advertises_auth(&lines, "LOGIN"));
    }

    // -- ehlo_advertises_starttls -----------------------------------------

    #[test]
    fn ehlo_advertises_starttls_finds_listed_extension() {
        let lines: Vec<String> = vec!["PIPELINING".into(), "STARTTLS".into(), "8BITMIME".into()];
        assert!(ehlo_advertises_starttls(&lines));
    }

    #[test]
    fn ehlo_advertises_starttls_is_case_insensitive() {
        let lines: Vec<String> = vec!["starttls".into()];
        assert!(ehlo_advertises_starttls(&lines));
    }

    #[test]
    fn ehlo_advertises_starttls_returns_false_when_absent() {
        let lines: Vec<String> = vec!["PIPELINING".into(), "AUTH PLAIN".into()];
        assert!(!ehlo_advertises_starttls(&lines));
    }

    #[test]
    fn ehlo_advertises_starttls_handles_empty_caps() {
        let lines: Vec<String> = Vec::new();
        assert!(!ehlo_advertises_starttls(&lines));
    }

    #[test]
    fn ehlo_advertises_starttls_does_not_match_substrings() {
        // `STARTTLS-FOO` (hypothetical) shouldn't match `STARTTLS` exactly.
        let lines: Vec<String> = vec!["STARTTLSPLUS".into()];
        assert!(!ehlo_advertises_starttls(&lines));
    }

    // -- AUTH PLAIN ---------------------------------------------------------

    #[test]
    fn auth_plain_initial_response_canonical_example() {
        // Canonical example: empty authzid, "user", "pass".
        // Payload: \0 u s e r \0 p a s s = 0x00 0x75 0x73 0x65 0x72 0x00 0x70 0x61 0x73 0x73
        // Base64: AHVzZXIAcGFzcw==
        assert_eq!(
            build_auth_plain_initial_response("user", "pass"),
            "AHVzZXIAcGFzcw=="
        );
    }

    #[test]
    fn auth_plain_initial_response_round_trips_through_base64() {
        // Decoding the response should yield exactly \0user\0pass.
        let user = "alice@example.com";
        let pass = "s3cr3t!";
        let b64 = build_auth_plain_initial_response(user, pass);
        let decoded = decode_b64_in_test(&b64);
        let mut expected = Vec::new();
        expected.push(0u8);
        expected.extend_from_slice(user.as_bytes());
        expected.push(0u8);
        expected.extend_from_slice(pass.as_bytes());
        assert_eq!(decoded, expected);
    }

    #[test]
    fn auth_plain_initial_response_handles_utf8_password() {
        // RFC 4616 specifies UTF-8 for both fields; non-ASCII passwords
        // should pass through unchanged in the base64 payload.
        let pass = "p\u{00E1}ssw\u{00F8}rd";
        let b64 = build_auth_plain_initial_response("u", pass);
        let decoded = decode_b64_in_test(&b64);
        assert_eq!(decoded[0], 0);
        assert_eq!(&decoded[1..2], b"u");
        assert_eq!(decoded[2], 0);
        assert_eq!(&decoded[3..], pass.as_bytes());
    }

    /// Tiny base64 decoder used only by test code, to avoid depending on
    /// an external crate just for round-trip verification.
    fn decode_b64_in_test(s: &str) -> Vec<u8> {
        const ALPHABET: &[u8; 64] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut idx = [255u8; 256];
        for (i, &b) in ALPHABET.iter().enumerate() {
            idx[b as usize] = u8::try_from(i).expect("alphabet fits in u8");
        }
        let chars: Vec<u8> = s.bytes().filter(|&b| b != b'=').collect();
        let mut out = Vec::new();
        for quad in chars.chunks(4) {
            let mut n = 0u32;
            for (i, &c) in quad.iter().enumerate() {
                let v = idx[c as usize];
                assert!(v != 255, "non-base64 byte in test input");
                n |= u32::from(v) << (18 - 6 * i);
            }
            let bytes_out = match quad.len() {
                4 => 3,
                3 => 2,
                2 => 1,
                _ => panic!("invalid base64 length"),
            };
            for i in 0..bytes_out {
                out.push(((n >> (16 - 8 * i)) & 0xFF) as u8);
            }
        }
        out
    }

    // -- select_auth_mechanism ---------------------------------------------

    #[test]
    fn select_auth_mechanism_prefers_plain() {
        let lines: Vec<String> = vec!["AUTH PLAIN LOGIN".into()];
        assert_eq!(select_auth_mechanism(&lines), Some(AuthMechanism::Plain));
    }

    #[test]
    fn select_auth_mechanism_falls_back_to_login() {
        let lines: Vec<String> = vec!["AUTH LOGIN".into()];
        assert_eq!(select_auth_mechanism(&lines), Some(AuthMechanism::Login));
    }

    #[test]
    fn select_auth_mechanism_returns_none_when_unsupported_only() {
        let lines: Vec<String> = vec!["AUTH CRAM-MD5".into(), "PIPELINING".into()];
        assert_eq!(select_auth_mechanism(&lines), None);
    }

    #[test]
    fn select_auth_mechanism_returns_none_when_no_auth_advertised() {
        let lines: Vec<String> = vec!["PIPELINING".into(), "8BITMIME".into()];
        assert_eq!(select_auth_mechanism(&lines), None);
    }

    #[test]
    fn select_auth_mechanism_handles_empty_capabilities() {
        let lines: Vec<String> = Vec::new();
        assert_eq!(select_auth_mechanism(&lines), None);
    }

    #[test]
    fn select_auth_mechanism_handles_multiple_auth_lines() {
        // Some servers split AUTH across several capability lines.
        let lines: Vec<String> = vec!["AUTH LOGIN".into(), "AUTH PLAIN".into()];
        assert_eq!(select_auth_mechanism(&lines), Some(AuthMechanism::Plain));
    }

    // -- AuthMechanism Display / name --------------------------------------

    #[test]
    fn auth_mechanism_name_and_display() {
        assert_eq!(AuthMechanism::Plain.name(), "PLAIN");
        assert_eq!(AuthMechanism::Login.name(), "LOGIN");
        assert_eq!(format!("{}", AuthMechanism::Plain), "PLAIN");
        assert_eq!(format!("{}", AuthMechanism::Login), "LOGIN");
    }

    // -- validate_plain_* --------------------------------------------------

    #[test]
    fn validate_plain_credentials_reject_empty() {
        assert!(validate_plain_username("").is_err());
        assert!(validate_plain_password("").is_err());
        assert!(validate_plain_username("user").is_ok());
        assert!(validate_plain_password("pass").is_ok());
    }

    #[test]
    fn validate_plain_credentials_reject_nul_bytes() {
        // NUL is the SASL PLAIN field separator and must never appear
        // inside a credential.
        assert!(validate_plain_username("a\0b").is_err());
        assert!(validate_plain_password("c\0d").is_err());
    }

    #[test]
    fn validate_plain_password_accepts_utf8_and_special_chars() {
        // RFC 4616 explicitly allows UTF-8 in the password field.
        assert!(validate_plain_password("\u{00E1}\u{00F1}\u{4E2D}").is_ok());
        assert!(validate_plain_password("a b\tc").is_ok());
        assert!(validate_plain_password("p@ss w0rd!").is_ok());
    }
}

// ---------------------------------------------------------------------------
// session.rs
// ---------------------------------------------------------------------------

mod session_tests {
    use crate::session::SessionState::{
        Authentication, Closed, Data, Ehlo, Greeting, MailFrom, Quit, RcptTo, StartTls,
    };

    #[test]
    fn forward_progression_is_allowed() {
        assert!(Greeting.can_transition_to(Ehlo));
        assert!(Ehlo.can_transition_to(Authentication));
        assert!(Authentication.can_transition_to(MailFrom));
        assert!(MailFrom.can_transition_to(RcptTo));
        assert!(RcptTo.can_transition_to(Data));
        assert!(Data.can_transition_to(MailFrom));
    }

    #[test]
    fn skipping_authentication_is_allowed() {
        // Unauthenticated submission goes Ehlo -> MailFrom directly.
        assert!(Ehlo.can_transition_to(MailFrom));
    }

    #[test]
    fn starting_a_second_transaction_is_allowed() {
        // After one successful transaction the state is MailFrom; it
        // must be possible to begin another transaction.
        assert!(MailFrom.can_transition_to(MailFrom));
    }

    #[test]
    fn multiple_recipients_stay_in_rcptto() {
        assert!(RcptTo.can_transition_to(RcptTo));
    }

    #[test]
    fn quit_is_allowed_from_every_active_state() {
        for from in [Greeting, Ehlo, Authentication, MailFrom, RcptTo, Data] {
            assert!(from.can_transition_to(Quit), "{from:?} should allow QUIT");
        }
    }

    #[test]
    fn closed_is_reachable_from_every_state() {
        for from in [
            Greeting,
            Ehlo,
            Authentication,
            StartTls,
            MailFrom,
            RcptTo,
            Data,
            Quit,
            Closed,
        ] {
            assert!(from.can_transition_to(Closed), "{from:?} -> Closed");
        }
    }

    #[test]
    fn invalid_transitions_are_rejected() {
        assert!(!Greeting.can_transition_to(Authentication));
        assert!(!Greeting.can_transition_to(MailFrom));
        assert!(!Ehlo.can_transition_to(RcptTo));
        assert!(!Ehlo.can_transition_to(Data));
        assert!(!MailFrom.can_transition_to(Data));
        assert!(!MailFrom.can_transition_to(Authentication));
        assert!(!Data.can_transition_to(RcptTo));
        // Once Closed, the only transition is to Closed itself.
        assert!(!Closed.can_transition_to(Ehlo));
        assert!(!Closed.can_transition_to(MailFrom));
    }

    #[test]
    fn closed_is_the_only_terminal_state() {
        assert!(Closed.is_terminal());
        for s in [
            Greeting,
            Ehlo,
            Authentication,
            StartTls,
            MailFrom,
            RcptTo,
            Data,
            Quit,
        ] {
            assert!(!s.is_terminal(), "{s:?} should not be terminal");
        }
    }

    // -- STARTTLS transitions (Phase 5) -----------------------------------

    #[test]
    fn starttls_is_reachable_from_authentication_only() {
        // The caller may upgrade only after EHLO completed.
        assert!(Authentication.can_transition_to(StartTls));
        // Other states must not jump straight into StartTls.
        for from in [Greeting, Ehlo, MailFrom, RcptTo, Data, Quit, Closed] {
            assert!(
                !from.can_transition_to(StartTls),
                "{from:?} should not be able to enter StartTls"
            );
        }
    }

    #[test]
    fn starttls_returns_to_ehlo_after_upgrade() {
        // RFC 3207 §4.2: the client must re-issue EHLO on the secure
        // channel. The state machine models this by passing through
        // Ehlo on the way back.
        assert!(StartTls.can_transition_to(Ehlo));
        // From Ehlo we can resume the normal flow.
        assert!(Ehlo.can_transition_to(Authentication));
    }

    #[test]
    fn starttls_cannot_skip_to_later_states() {
        // After upgrading we must still re-EHLO before talking auth or
        // MAIL FROM. Skipping Ehlo would mean the new (post-TLS)
        // capabilities are unknown.
        for to in [Authentication, MailFrom, RcptTo, Data, Quit] {
            assert!(
                !StartTls.can_transition_to(to),
                "StartTls should not skip directly to {to:?}"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// error.rs
// ---------------------------------------------------------------------------

mod error_tests {
    use crate::error::{AuthError, InvalidInputError, IoError, ProtocolError, SmtpError, SmtpOp};
    use std::error::Error;

    #[test]
    fn smtp_error_display_protocol_includes_code_and_message() {
        let e = SmtpError::Protocol(ProtocolError::UnexpectedCode {
            during: SmtpOp::MailFrom,
            expected_class: 2,
            actual: 451,
            message: "temporary local problem".into(),
        });
        let s = format!("{e}");
        assert!(s.contains("451"), "should include actual code: {s}");
        assert!(
            s.contains("temporary local problem"),
            "should include server text: {s}"
        );
        // Phase 4: the operation context should be visible to operators
        // reading logs.
        assert!(
            s.contains("MAIL FROM"),
            "should mention the SMTP operation in progress: {s}"
        );
    }

    #[test]
    fn smtp_op_display_uses_wire_keyword() {
        // Quick coverage: every op variant should produce a non-empty
        // string in Display, matching the SMTP wire keyword where there
        // is one.
        for (op, expected) in [
            (SmtpOp::Greeting, "greeting"),
            (SmtpOp::Ehlo, "EHLO"),
            (SmtpOp::AuthPlain, "AUTH PLAIN"),
            (SmtpOp::AuthLogin, "AUTH LOGIN"),
            (SmtpOp::MailFrom, "MAIL FROM"),
            (SmtpOp::RcptTo, "RCPT TO"),
            (SmtpOp::Data, "DATA"),
            (SmtpOp::Quit, "QUIT"),
        ] {
            assert_eq!(format!("{op}"), expected);
            assert_eq!(op.as_str(), expected);
        }
    }

    #[test]
    fn auth_rejected_carries_server_code_and_text() {
        let e = SmtpError::Auth(AuthError::Rejected {
            code: 535,
            message: "5.7.8 invalid".into(),
        });
        let s = format!("{e}");
        assert!(s.contains("535"));
        assert!(s.contains("5.7.8 invalid"));
    }

    #[test]
    fn invalid_input_takes_only_static_strings() {
        // The constructor signature is `&'static str`, so it is a
        // compile-time guarantee that runtime user input cannot be
        // embedded into the error message.
        let e = InvalidInputError::new("test reason");
        assert_eq!(e.reason(), "test reason");
        assert_eq!(format!("{e}"), "test reason");
    }

    #[test]
    fn from_conversions_wrap_in_correct_variant() {
        let e: SmtpError = IoError::new("transport gone").into();
        assert!(matches!(e, SmtpError::Io(_)));
        let e: SmtpError = ProtocolError::UnexpectedClose.into();
        assert!(matches!(e, SmtpError::Protocol(_)));
        let e: SmtpError = AuthError::UnsupportedMechanism.into();
        assert!(matches!(e, SmtpError::Auth(_)));
        let e: SmtpError = InvalidInputError::new("x").into();
        assert!(matches!(e, SmtpError::InvalidInput(_)));
    }

    #[test]
    fn smtp_error_source_chains_to_inner_variant() {
        let e: SmtpError = IoError::new("inner").into();
        let src = e.source().expect("should have source");
        assert!(format!("{src}").contains("inner"));
    }
}

// ---------------------------------------------------------------------------
// client.rs (integration with mock transport)
// ---------------------------------------------------------------------------

mod client_tests {
    use super::harness::{MockTransport, UpgradeBehavior, block_on, flatten};
    use crate::client::SmtpClient;
    use crate::error::{AuthError, ProtocolError, SmtpError, SmtpOp};
    use crate::protocol::AuthMechanism;
    use crate::session::SessionState;

    /// Standard greeting + EHLO reply used by most happy-path tests.
    fn greeting_then_ehlo() -> Vec<u8> {
        flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com Hello [192.0.2.1]\r\n",
            b"250-PIPELINING\r\n",
            b"250-8BITMIME\r\n",
            b"250 AUTH LOGIN PLAIN\r\n",
        ])
    }

    // -- connect / EHLO -----------------------------------------------------

    #[test]
    fn connect_reads_greeting_and_sends_ehlo() {
        let script = greeting_then_ehlo();
        let (transport, written, _closed) = MockTransport::new(&[&script[..]]);
        let client =
            block_on(SmtpClient::connect(transport, "client.example.com")).expect("connect");

        assert_eq!(client.state(), SessionState::Authentication);
        let caps = client.capabilities();
        assert_eq!(caps.len(), 3);
        assert_eq!(caps[0], "PIPELINING");
        assert_eq!(caps[1], "8BITMIME");
        assert_eq!(caps[2], "AUTH LOGIN PLAIN");

        // Only one command should have been sent: EHLO.
        assert_eq!(&*written.borrow(), b"EHLO client.example.com\r\n");
    }

    #[test]
    fn connect_fails_on_non_220_greeting() {
        let script: &[u8] = b"554 Service unavailable\r\n";
        let (transport, _written, _closed) = MockTransport::new(&[script]);
        let err = block_on(SmtpClient::connect(transport, "client.example.com"))
            .expect_err("greeting should fail");
        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode { actual, .. }) => {
                assert_eq!(actual, 554);
            }
            other => panic!("expected ProtocolError::UnexpectedCode, got {other:?}"),
        }
    }

    #[test]
    fn invalid_ehlo_domain_is_rejected_before_io() {
        let (transport, written, _closed) = MockTransport::new(&[]);
        let err = block_on(SmtpClient::connect(transport, "")).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // No bytes should ever have been sent to the transport.
        assert!(written.borrow().is_empty());
    }

    // -- AUTH LOGIN ---------------------------------------------------------

    #[test]
    fn login_sends_correct_auth_login_sequence() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
            b"334 VXNlcm5hbWU6\r\n",
            b"334 UGFzc3dvcmQ6\r\n",
            b"235 Authentication succeeded\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");

        let expected = b"EHLO client.example\r\n\
                         AUTH LOGIN\r\n\
                         dXNlcg==\r\n\
                         cGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn login_fails_when_auth_login_not_advertised() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n", // No AUTH advertised at all
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Auth(AuthError::UnsupportedMechanism)
        ));
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[test]
    fn login_fails_on_535_rejection() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
            b"334 VXNlcm5hbWU6\r\n",
            b"334 UGFzc3dvcmQ6\r\n",
            b"535 5.7.8 Authentication credentials invalid\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        match err {
            SmtpError::Auth(AuthError::Rejected { code, .. }) => assert_eq!(code, 535),
            other => panic!("expected AuthError::Rejected, got {other:?}"),
        }
    }

    #[test]
    fn login_rejects_empty_username_before_io() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let pre_login_writes_len = written.borrow().len();
        let err = block_on(client.login("", "pass")).expect_err("empty user must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // No additional bytes should have been written.
        assert_eq!(written.borrow().len(), pre_login_writes_len);
    }

    // -- send_mail ----------------------------------------------------------

    #[test]
    fn send_mail_full_transaction_no_auth() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            // MAIL FROM
            b"250 OK\r\n",
            // RCPT TO #1
            b"250 OK\r\n",
            // RCPT TO #2 (251 = "User not local; will forward" is also a 2xx)
            b"251 User not local; will forward\r\n",
            // DATA
            b"354 End data with <CR><LF>.<CR><LF>\r\n",
            // After body
            b"250 Queued\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let body = "From: a@example.com\r\nTo: b@example.org\r\nSubject: hi\r\n\r\nHello.\r\n";
        block_on(client.send_mail("a@example.com", &["b@example.org", "c@example.org"], body))
            .expect("send_mail");

        let expected = b"EHLO client.example\r\n\
                         MAIL FROM:<a@example.com>\r\n\
                         RCPT TO:<b@example.org>\r\n\
                         RCPT TO:<c@example.org>\r\n\
                         DATA\r\n\
                         From: a@example.com\r\nTo: b@example.org\r\nSubject: hi\r\n\r\nHello.\r\n.\r\n";
        assert_eq!(&*written.borrow(), expected);
        // After a successful transaction the client is ready for the next.
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn send_mail_dot_stuffs_leading_dot_lines() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"250 OK\r\n",
            b"250 OK\r\n",
            b"354 OK\r\n",
            b"250 Queued\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        // Body whose data section starts with a `.` line and contains
        // double-dot-prefixed line.
        let body = "Subject: t\r\n\r\n.line1\r\n..line2\r\n";
        block_on(client.send_mail("a@b.com", &["c@d.com"], body)).expect("send");

        // Locate the DATA payload, i.e. what follows the literal "DATA\r\n".
        let got = written.borrow();
        let after_data = b"DATA\r\n";
        let pos = got
            .windows(after_data.len())
            .position(|w| w == after_data)
            .expect("DATA marker in capture");
        let payload = &got[pos + after_data.len()..];
        // ".line1" -> "..line1"; "..line2" -> "...line2".
        let expected = b"Subject: t\r\n\r\n..line1\r\n...line2\r\n.\r\n";
        assert_eq!(payload, expected);
    }

    #[test]
    fn send_mail_rejects_empty_recipients() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &[], "x")).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
    }

    #[test]
    fn send_mail_rejects_crlf_injection_in_address() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let pre = written.borrow().len();
        let err = block_on(client.send_mail("a@b.com\r\nRSET", &["c@d.com"], "x"))
            .expect_err("must reject");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // Nothing extra should have been written after the EHLO.
        assert_eq!(written.borrow().len(), pre);
    }

    #[test]
    fn send_mail_after_mail_from_rejection_marks_session_closed() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"550 No such user\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &["c@d.com"], "Subject: x\r\n\r\nx\r\n"))
            .expect_err("server should reject");
        assert!(matches!(
            err,
            SmtpError::Protocol(ProtocolError::UnexpectedCode { .. })
        ));
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[test]
    fn two_send_mails_in_one_session_succeed() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            // First transaction.
            b"250 OK\r\n", // MAIL FROM
            b"250 OK\r\n", // RCPT TO
            b"354 OK\r\n", // DATA
            b"250 Queued\r\n",
            // Second transaction.
            b"250 OK\r\n",
            b"250 OK\r\n",
            b"354 OK\r\n",
            b"250 Queued\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let body = "Subject: t\r\n\r\nbody\r\n";
        block_on(client.send_mail("a@b.com", &["c@d.com"], body)).expect("first send");
        block_on(client.send_mail("a@b.com", &["e@f.com"], body)).expect("second send");
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    // -- QUIT ---------------------------------------------------------------

    #[test]
    fn quit_sends_quit_and_closes_transport() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
            // QUIT
            b"221 Bye\r\n",
        ]);
        let (transport, written, closed) = MockTransport::new(&[&server_script[..]]);
        let client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        block_on(client.quit()).expect("quit");
        assert!(written.borrow().ends_with(b"QUIT\r\n"));
        assert!(*closed.borrow(), "transport.close() must be called");
    }

    // -- protocol robustness ------------------------------------------------

    #[test]
    fn unexpected_close_during_reply_is_classified() {
        // Server sends greeting then dribbles an unfinished EHLO reply.
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n", // continuation, then EOF
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let err = block_on(SmtpClient::connect(transport, "c.example")).expect_err("must fail");
        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedClose) => {}
            other => panic!("expected UnexpectedClose, got {other:?}"),
        }
    }

    #[test]
    fn inconsistent_multiline_codes_are_rejected() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-line1\r\n",
            b"251 line2\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let err = block_on(SmtpClient::connect(transport, "c.example")).expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Protocol(ProtocolError::InconsistentMultiline { .. })
        ));
    }

    #[test]
    fn malformed_reply_line_is_rejected() {
        let server_script: &[u8] = b"abc not a real reply\r\n";
        let (transport, _written, _closed) = MockTransport::new(&[server_script]);
        let err = block_on(SmtpClient::connect(transport, "c.example")).expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Protocol(ProtocolError::Malformed(_))
        ));
    }

    #[test]
    fn read_handles_chunks_split_arbitrarily() {
        // Same script as the basic test, but split across multiple read
        // calls so the buffered reader is exercised.
        let chunks: Vec<&[u8]> = vec![
            b"220 mail.exam",
            b"ple.com ESMTP\r\n250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
        ];
        let (transport, _written, _closed) = MockTransport::new(&chunks);
        let client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        assert_eq!(client.state(), SessionState::Authentication);
    }

    // -- AUTH PLAIN (Phase 4) ----------------------------------------------

    #[test]
    fn login_uses_plain_when_advertised() {
        // Server advertises both PLAIN and LOGIN; login() should pick
        // PLAIN and complete in one round trip (235 immediately after
        // the AUTH PLAIN line).
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN LOGIN\r\n",
            b"235 Authentication succeeded\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");

        // base64("\0user\0pass") == "AHVzZXIAcGFzcw=="
        let expected = b"EHLO client.example\r\n\
                         AUTH PLAIN AHVzZXIAcGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn login_falls_back_to_login_when_only_login_advertised() {
        // Server advertises only LOGIN — exactly the v0.1 behavior.
        // login() must continue to work against this server.
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
            b"334 VXNlcm5hbWU6\r\n",
            b"334 UGFzc3dvcmQ6\r\n",
            b"235 OK\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");

        let expected = b"EHLO client.example\r\n\
                         AUTH LOGIN\r\n\
                         dXNlcg==\r\n\
                         cGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn login_fails_when_no_supported_mechanism_is_advertised() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH CRAM-MD5\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let pre_login = written.borrow().len();
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Auth(AuthError::UnsupportedMechanism)
        ));
        // No auth-related bytes should have been emitted.
        assert_eq!(written.borrow().len(), pre_login);
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[test]
    fn login_plain_handles_535_rejection_as_auth_error() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
            b"535 5.7.8 invalid credentials\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        match err {
            SmtpError::Auth(AuthError::Rejected { code, message }) => {
                assert_eq!(code, 535);
                assert!(message.contains("5.7.8"));
            }
            other => panic!("expected AuthError::Rejected, got {other:?}"),
        }
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[test]
    fn login_with_plain_explicit_uses_plain_even_when_login_also_advertised() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN LOGIN\r\n",
            b"235 OK\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login_with(AuthMechanism::Plain, "user", "pass")).expect("login");

        let expected = b"EHLO client.example\r\n\
                         AUTH PLAIN AHVzZXIAcGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
    }

    #[test]
    fn login_with_login_explicit_uses_login_even_when_plain_also_advertised() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN LOGIN\r\n",
            b"334 VXNlcm5hbWU6\r\n",
            b"334 UGFzc3dvcmQ6\r\n",
            b"235 OK\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login_with(AuthMechanism::Login, "user", "pass")).expect("login");

        let expected = b"EHLO client.example\r\n\
                         AUTH LOGIN\r\n\
                         dXNlcg==\r\n\
                         cGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
    }

    #[test]
    fn login_with_plain_fails_when_only_login_advertised() {
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH LOGIN\r\n",
        ]);
        let (transport, _written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login_with(AuthMechanism::Plain, "user", "pass"))
            .expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Auth(AuthError::UnsupportedMechanism)
        ));
    }

    #[test]
    fn login_rejects_credentials_with_nul_byte_before_io() {
        // A NUL in the credentials would corrupt the SASL PLAIN framing.
        // The validation must catch it before any byte is written.
        let server_script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
        ]);
        let (transport, written, _closed) = MockTransport::new(&[&server_script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let pre_login = written.borrow().len();
        let err = block_on(client.login("user\0evil", "pass")).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        assert_eq!(written.borrow().len(), pre_login);
    }

    #[test]
    fn unsupported_mechanism_message_lists_supported_options() {
        // Smoke-test the improved Display output: the user-facing error
        // should say which mechanisms ARE supported, so the operator
        // can reason about why their server is incompatible.
        let err = SmtpError::Auth(AuthError::UnsupportedMechanism);
        let s = format!("{err}");
        assert!(s.contains("PLAIN"), "should mention PLAIN: {s}");
        assert!(s.contains("LOGIN"), "should mention LOGIN: {s}");
    }

    // -- ProtocolError::UnexpectedCode `during` field (Phase 4) ------------

    /// Helper: extract the `during` operation from an `UnexpectedCode` error,
    /// or panic with a helpful message identifying what we got instead.
    fn during_of(err: SmtpError) -> SmtpOp {
        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode { during, .. }) => during,
            other => panic!("expected UnexpectedCode, got {other:?}"),
        }
    }

    #[test]
    fn unexpected_code_during_greeting() {
        let (transport, _w, _c) = MockTransport::new(&[b"554 service unavailable\r\n"]);
        let err = block_on(SmtpClient::connect(transport, "c.example")).expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::Greeting);
    }

    #[test]
    fn unexpected_code_during_ehlo() {
        // 220 greeting, then 5xx on EHLO.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"502 EHLO not implemented\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let err = block_on(SmtpClient::connect(transport, "c.example")).expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::Ehlo);
    }

    #[test]
    fn unexpected_code_during_mail_from() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"550 sender domain refused\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &["c@d.com"], "Subject: x\r\n\r\nx\r\n"))
            .expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::MailFrom);
    }

    #[test]
    fn unexpected_code_during_rcpt_to() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"250 OK\r\n",           // MAIL FROM accepted
            b"550 no such user\r\n", // RCPT TO refused
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &["c@d.com"], "Subject: x\r\n\r\nx\r\n"))
            .expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::RcptTo);
    }

    #[test]
    fn unexpected_code_during_data_command() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"250 OK\r\n",           // MAIL FROM
            b"250 OK\r\n",           // RCPT TO
            b"503 bad sequence\r\n", // DATA refused
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &["c@d.com"], "Subject: x\r\n\r\nx\r\n"))
            .expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::Data);
    }

    #[test]
    fn unexpected_code_during_data_body() {
        // The 250 after the body is rejected with a 5xx.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"250 OK\r\n",                // MAIL FROM
            b"250 OK\r\n",                // RCPT TO
            b"354 go ahead\r\n",          // DATA accepted
            b"552 message too large\r\n", // body rejected
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.send_mail("a@b.com", &["c@d.com"], "Subject: x\r\n\r\nx\r\n"))
            .expect_err("must fail");
        // We use SmtpOp::Data for both the DATA command and the body,
        // because operators conceptualize them as the same step.
        assert_eq!(during_of(err), SmtpOp::Data);
    }

    #[test]
    fn unexpected_code_during_quit_propagates_after_close() {
        // QUIT replies with a non-221: the error is returned from quit().
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
            b"500 unrecognized\r\n", // QUIT rejected
        ]);
        let (transport, _w, closed) = MockTransport::new(&[&script[..]]);
        let client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.quit()).expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::Quit);
        // Even on failure, the transport must have been closed.
        assert!(*closed.borrow());
    }

    #[test]
    fn auth_plain_unexpected_non_5xx_keeps_protocol_error_with_op() {
        // Non-5xx unexpected codes during AUTH PLAIN should remain
        // ProtocolError::UnexpectedCode (not converted to AuthError),
        // and should be tagged with SmtpOp::AuthPlain.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
            b"432 password expired\r\n", // 4xx, not converted to Auth
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client = block_on(SmtpClient::connect(transport, "c.example")).expect("connect");
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        assert_eq!(during_of(err), SmtpOp::AuthPlain);
    }

    // -- STARTTLS (Phase 5) -----------------------------------------------

    /// Standard STARTTLS-capable server script: plain greeting, plain EHLO
    /// advertising STARTTLS, 220 on STARTTLS, then a fresh EHLO reply (the
    /// post-TLS one, with new capabilities).
    fn starttls_greeting_and_upgrade() -> Vec<u8> {
        flatten(&[
            // Plaintext greeting.
            b"220 mail.example.com ESMTP\r\n",
            // First EHLO reply: includes STARTTLS, no AUTH advertised yet.
            b"250-mail.example.com\r\n",
            b"250-PIPELINING\r\n",
            b"250 STARTTLS\r\n",
            // STARTTLS accepted.
            b"220 ready to start TLS\r\n",
            // Second EHLO reply (post-TLS): now AUTH is advertised.
            b"250-mail.example.com\r\n",
            b"250-PIPELINING\r\n",
            b"250 AUTH PLAIN LOGIN\r\n",
        ])
    }

    #[test]
    fn connect_starttls_runs_full_upgrade_sequence() {
        let (transport, written, _closed, upgrades) = MockTransport::with_starttls(
            &[&starttls_greeting_and_upgrade()[..]],
            UpgradeBehavior::Succeed,
        );
        let client = block_on(SmtpClient::connect_starttls(transport, "client.example"))
            .expect("connect_starttls");

        // After the full upgrade we should be in Authentication, with the
        // POST-TLS capability set advertised.
        assert_eq!(client.state(), SessionState::Authentication);
        let caps = client.capabilities();
        assert_eq!(caps.len(), 2);
        assert_eq!(caps[0], "PIPELINING");
        assert_eq!(caps[1], "AUTH PLAIN LOGIN");

        // Wire bytes: EHLO, STARTTLS, EHLO again. No AUTH yet.
        let expected = b"EHLO client.example\r\n\
                         STARTTLS\r\n\
                         EHLO client.example\r\n";
        assert_eq!(&*written.borrow(), expected);

        // The transport upgrade must have been invoked exactly once.
        assert_eq!(*upgrades.borrow(), 1);
    }

    #[test]
    fn starttls_then_login_uses_post_tls_capabilities() {
        // After STARTTLS the second EHLO reveals AUTH PLAIN, which login()
        // must pick up. This proves we discard the pre-TLS capabilities
        // and parse the new ones.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 STARTTLS\r\n",
            b"220 ready\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
            b"235 OK\r\n",
        ]);
        let (transport, written, _c, _u) =
            MockTransport::with_starttls(&[&script[..]], UpgradeBehavior::Succeed);
        let mut client = block_on(SmtpClient::connect_starttls(transport, "c.example"))
            .expect("connect_starttls");
        block_on(client.login("user", "pass")).expect("login");

        let expected = b"EHLO c.example\r\n\
                         STARTTLS\r\n\
                         EHLO c.example\r\n\
                         AUTH PLAIN AHVzZXIAcGFzcw==\r\n";
        assert_eq!(&*written.borrow(), expected);
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn starttls_fails_when_extension_not_advertised() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            // No STARTTLS in caps.
            b"250-mail.example.com\r\n",
            b"250 8BITMIME\r\n",
        ]);
        let (transport, written, _c, upgrades) =
            MockTransport::with_starttls(&[&script[..]], UpgradeBehavior::Succeed);
        let pre_upgrade_writes_len = 0;
        let err =
            block_on(SmtpClient::connect_starttls(transport, "c.example")).expect_err("must fail");

        match err {
            SmtpError::Protocol(ProtocolError::ExtensionUnavailable { name }) => {
                assert_eq!(name, "STARTTLS");
            }
            other => panic!("expected ExtensionUnavailable, got {other:?}"),
        }
        // We sent the EHLO but nothing else: STARTTLS was never written.
        assert_eq!(&*written.borrow(), b"EHLO c.example\r\n");
        assert!(written.borrow().len() > pre_upgrade_writes_len);
        // upgrade_to_tls() must NOT have been called.
        assert_eq!(*upgrades.borrow(), 0);
    }

    #[test]
    fn starttls_fails_when_server_rejects_command() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 STARTTLS\r\n",
            // Server rejects STARTTLS with a 5xx (atypical but observable).
            b"502 STARTTLS not configured\r\n",
        ]);
        let (transport, _w, _c, upgrades) =
            MockTransport::with_starttls(&[&script[..]], UpgradeBehavior::Succeed);
        let err =
            block_on(SmtpClient::connect_starttls(transport, "c.example")).expect_err("must fail");

        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode { during, actual, .. }) => {
                assert_eq!(during, SmtpOp::StartTls);
                assert_eq!(actual, 502);
            }
            other => panic!("expected UnexpectedCode for StartTls, got {other:?}"),
        }
        // The transport must NOT have been upgraded: the server refused.
        assert_eq!(*upgrades.borrow(), 0);
    }

    #[test]
    fn starttls_propagates_transport_upgrade_failure_as_io_error() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 STARTTLS\r\n",
            b"220 ready\r\n",
        ]);
        let (transport, _w, _c, upgrades) = MockTransport::with_starttls(
            &[&script[..]],
            UpgradeBehavior::Fail("simulated TLS handshake failure"),
        );
        let err =
            block_on(SmtpClient::connect_starttls(transport, "c.example")).expect_err("must fail");

        match err {
            SmtpError::Io(e) => {
                assert!(format!("{e}").contains("TLS handshake"));
            }
            other => panic!("expected Io for upgrade failure, got {other:?}"),
        }
        // The upgrade was attempted exactly once.
        assert_eq!(*upgrades.borrow(), 1);
    }

    #[test]
    fn explicit_starttls_method_works_post_connect() {
        // Same flow but reached via the explicit two-call API:
        // SmtpClient::connect() then client.starttls(). This is the
        // path callers use when they want to inspect capabilities first.
        let (transport, written, _c, _u) = MockTransport::with_starttls(
            &[&starttls_greeting_and_upgrade()[..]],
            UpgradeBehavior::Succeed,
        );
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        // Pre-STARTTLS capabilities visible to the caller.
        assert!(client.capabilities().iter().any(|c| c == "STARTTLS"));
        block_on(client.starttls()).expect("starttls");
        // Post-STARTTLS capabilities have replaced the pre-TLS ones.
        assert!(
            client
                .capabilities()
                .iter()
                .any(|c| c == "AUTH PLAIN LOGIN"),
            "post-TLS caps should include AUTH advertisement: {:?}",
            client.capabilities()
        );
        assert!(
            !client.capabilities().iter().any(|c| c == "STARTTLS"),
            "STARTTLS should not appear in post-TLS caps: {:?}",
            client.capabilities()
        );
        assert_eq!(client.state(), SessionState::Authentication);

        // Bytes match the all-in-one connect_starttls test.
        assert_eq!(
            &*written.borrow(),
            b"EHLO client.example\r\nSTARTTLS\r\nEHLO client.example\r\n"
        );
    }

    #[test]
    fn starttls_rejects_call_after_login() {
        // STARTTLS must be issued BEFORE auth. Calling it after login()
        // is a programming error and must return InvalidInput.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 STARTTLS\r\n",
            b"220 ready\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
            b"235 OK\r\n",
        ]);
        let (transport, _w, _c, upgrades) =
            MockTransport::with_starttls(&[&script[..]], UpgradeBehavior::Succeed);
        let mut client = block_on(SmtpClient::connect_starttls(transport, "c.example"))
            .expect("connect_starttls");
        block_on(client.login("user", "pass")).expect("login");

        // Now the second starttls() must be refused.
        let err = block_on(client.starttls()).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // No additional upgrade was attempted.
        assert_eq!(*upgrades.borrow(), 1);
    }
}