wasm-smtp-core 0.5.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
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
//! 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>>,
        /// Chunks queued to be revealed only after `upgrade_to_tls()`
        /// has been called. Empty for non-STARTTLS tests.
        pending_post: 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 and that models a real STARTTLS-aware server: the
        /// `pre_chunks` are delivered before any `upgrade_to_tls()`
        /// call, and the `post_chunks` are revealed only after the
        /// upgrade has been performed. This mirrors the behaviour of a
        /// real submission server, which does not pipeline the post-TLS
        /// EHLO reply onto the plaintext channel — and lets us
        /// exercise the v0.5.0 STARTTLS-injection defence without
        /// false positives caused by the older "all bytes in one
        /// chunk" mock layout.
        ///
        /// Tests that want to deliberately simulate a STARTTLS
        /// injection (bytes pipelined onto the plaintext channel after
        /// the `220`) should pass those bytes as part of `pre_chunks`
        /// and verify that the upgrade is rejected.
        pub fn with_starttls(
            pre_chunks: &[&[u8]],
            post_chunks: &[&[u8]],
            behavior: UpgradeBehavior,
        ) -> MockStartTlsHandles {
            Self::build(pre_chunks, post_chunks, behavior)
        }

        fn build(
            pre_chunks: &[&[u8]],
            post_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 pre_chunks {
                q.push_back((*c).to_vec());
            }
            let mut pending_post: VecDeque<Vec<u8>> = VecDeque::new();
            for c in post_chunks {
                pending_post.push_back((*c).to_vec());
            }
            (
                Self {
                    incoming: q,
                    pending_post,
                    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 => {
                    // Real servers withhold the post-TLS EHLO reply until
                    // the TLS handshake has completed. Move the queued
                    // post-upgrade chunks into the live read queue now.
                    while let Some(chunk) = self.pending_post.pop_front() {
                        self.incoming.push_back(chunk);
                    }
                    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_enhanced_status_codes,
        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,
    };

    // XOAUTH2 helpers are only present when the feature is enabled.
    #[cfg(feature = "xoauth2")]
    use crate::protocol::{
        build_xoauth2_initial_response, validate_oauth2_token, validate_xoauth2_user,
    };

    // -- 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::new(451, 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());
    }

    /// Phase 9 / M-5: NUL bytes in LOGIN credentials would corrupt
    /// SASL framing on the post-base64 server side, so the
    /// validators must reject them. Before v0.5.0 these were thin
    /// "non-empty only" checks; they are now thin aliases over the
    /// stricter `validate_plain_*` validators.
    #[test]
    fn validate_login_username_rejects_nul() {
        assert!(validate_login_username("a\0b").is_err());
    }

    #[test]
    fn validate_login_password_rejects_nul() {
        assert!(validate_login_password("a\0b").is_err());
    }

    // -- validate_address: RFC 5321 length limits (M-4) -------------------

    #[test]
    fn validate_address_rejects_overly_long_total() {
        // Construct an address that is exactly 1 octet over the
        // 254-octet path limit (RFC 5321 §4.5.3.1.3). Use a 60-octet
        // local-part + '@' + 194-octet domain = 255 octets total.
        let local = "a".repeat(60);
        let domain = format!("{}.example", "x".repeat(186)); // 186 + ".example" (8) = 194
        let addr = format!("{local}@{domain}");
        assert_eq!(addr.len(), 255);
        assert!(validate_address(&addr).is_err());
    }

    #[test]
    fn validate_address_accepts_at_total_limit() {
        // Boundary: exactly 254 octets is allowed.
        let local = "a".repeat(60);
        let domain = format!("{}.example", "x".repeat(185)); // 185 + 8 = 193
        let addr = format!("{local}@{domain}");
        assert_eq!(addr.len(), 254);
        assert!(validate_address(&addr).is_ok());
    }

    #[test]
    fn validate_address_rejects_overly_long_local_part() {
        // 65-octet local-part > MAX_LOCAL_PART_LEN (64).
        let addr = format!("{}@example.com", "a".repeat(65));
        assert!(validate_address(&addr).is_err());
    }

    #[test]
    fn validate_address_accepts_at_local_part_limit() {
        // 64-octet local-part is allowed.
        let addr = format!("{}@example.com", "a".repeat(64));
        assert!(validate_address(&addr).is_ok());
    }

    #[test]
    fn validate_address_rejects_overly_long_domain() {
        // 256-octet domain > MAX_DOMAIN_LEN (255).
        let addr = format!("user@{}", "x".repeat(256));
        assert!(validate_address(&addr).is_err());
    }

    // -- 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));
    }

    // -- ehlo_advertises_enhanced_status_codes ----------------------------

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

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

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

    #[test]
    fn ehlo_advertises_enhancedstatuscodes_does_not_match_substrings() {
        // The keyword check splits on whitespace and compares exactly.
        let lines: Vec<String> = vec!["ENHANCEDSTATUSCODESPLUS".into()];
        assert!(!ehlo_advertises_enhanced_status_codes(&lines));
    }

    // -- EnhancedStatus parsing -------------------------------------------
    //
    // We cannot test `parse_enhanced_status_prefix` directly because it is
    // private to protocol.rs. Instead we test it through `Reply::try_parse_enhanced`,
    // which is the only caller and the API a downstream consumer would use.

    #[test]
    fn reply_parses_enhanced_status_basic() {
        let reply = Reply::new(550, vec!["5.7.1 relay denied".into()]);
        let es = reply.try_parse_enhanced().expect("should parse");
        assert_eq!(es.class, 5);
        assert_eq!(es.subject, 7);
        assert_eq!(es.detail, 1);
        assert_eq!(es.to_dotted(), "5.7.1");
        assert_eq!(format!("{es}"), "5.7.1");
    }

    #[test]
    fn reply_parses_enhanced_status_class_2_and_4() {
        // RFC 3463 specifies class 2 (success), 4 (transient), 5 (permanent).
        for (class_byte, want) in [(b'2', 2), (b'4', 4), (b'5', 5)] {
            let line = format!("{}.0.0 ok", class_byte as char);
            let reply = Reply::new(250, vec![line]);
            let es = reply.try_parse_enhanced().expect("should parse");
            assert_eq!(es.class, want);
        }
    }

    #[test]
    fn reply_rejects_invalid_enhanced_class_digits() {
        // Class 1, 3, 6, etc. must not be parsed: RFC 3463 only defines 2/4/5.
        for bad in [b'0', b'1', b'3', b'6', b'9'] {
            let line = format!("{}.0.0 something", bad as char);
            let reply = Reply::new(250, vec![line]);
            assert!(
                reply.try_parse_enhanced().is_none(),
                "class {} must not parse",
                bad as char
            );
        }
    }

    #[test]
    fn reply_rejects_malformed_enhanced_status() {
        for bad in [
            "5..1 missing subject",
            "5.7. missing detail",
            "5-7-1 wrong separator",
            "5.7 too short",
            "noenhanced text only",
            "",
        ] {
            let reply = Reply::new(550, vec![bad.into()]);
            assert!(
                reply.try_parse_enhanced().is_none(),
                "{bad:?} must not parse"
            );
        }
    }

    #[test]
    fn reply_message_text_strips_enhanced_prefix_when_present() {
        // The full text is preserved by joined_text(), but message_text()
        // strips the enhanced prefix for human-friendly display.
        let mut reply = Reply::new(550, vec!["5.7.1 relay access denied".into()]);
        // message_text() relies on the enhanced field being set, mimicking
        // what the client does when ENHANCEDSTATUSCODES is enabled.
        let es = reply.try_parse_enhanced().unwrap();
        reply.attach_enhanced_status(es);
        assert_eq!(reply.joined_text(), "5.7.1 relay access denied");
        assert_eq!(reply.message_text(), "relay access denied");
    }

    #[test]
    fn reply_message_text_unchanged_without_enhanced() {
        // Without an enhanced code attached, message_text() == joined_text().
        let reply = Reply::new(550, vec!["something or other".into()]);
        assert_eq!(reply.message_text(), reply.joined_text());
    }

    // -- 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());
    }

    // -- XOAUTH2 ----------------------------------------------------------
    //
    // These tests cover helpers that are only present when the
    // `xoauth2` feature is enabled. The `select_auth_mechanism` test
    // is included here because it asserts a property about the
    // _absence_ of XOAUTH2 from auto-selection, which is meaningful
    // only when XOAUTH2 itself is available.
    //
    // The single test that does NOT belong here is
    // `auth_mechanism_xoauth2_name_is_exact_keyword`, which tests the
    // always-present `AuthMechanism::XOAuth2` variant's `name()`
    // accessor. That one is unconditional below.

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_initial_response_canonical_example() {
        // Canonical Google example. Payload (with SOH = \x01):
        //   user=someuser@example.com\x01auth=Bearer ya29.vF9...\x01\x01
        // We just verify the wire bytes round-trip through base64.
        let response = build_xoauth2_initial_response("someuser@example.com", "ya29.test_token");

        // Decode to inspect the structure. We don't have a public base64
        // decoder, so we reconstruct the expected bytes and check that a
        // fresh encode yields the same string.
        let mut expected_payload = Vec::new();
        expected_payload.extend_from_slice(b"user=someuser@example.com");
        expected_payload.push(0x01);
        expected_payload.extend_from_slice(b"auth=Bearer ya29.test_token");
        expected_payload.push(0x01);
        expected_payload.push(0x01);
        let expected_b64 = base64_encode(&expected_payload);

        assert_eq!(response, expected_b64);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_initial_response_uses_soh_separators() {
        // The wire-format bytes (pre-base64) must contain exactly two
        // SOH bytes between fields and one trailing SOH-SOH. We reconstruct
        // and compare.
        let r1 = build_xoauth2_initial_response("u", "t");
        let mut payload = Vec::new();
        payload.extend_from_slice(b"user=u\x01auth=Bearer t\x01\x01");
        assert_eq!(r1, base64_encode(&payload));
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn validate_xoauth2_user_rejects_empty_and_control_bytes() {
        assert!(validate_xoauth2_user("").is_err());
        assert!(validate_xoauth2_user("u\0v").is_err());
        assert!(validate_xoauth2_user("u\rv").is_err());
        assert!(validate_xoauth2_user("u\nv").is_err());
        // SOH would corrupt the SASL frame.
        assert!(validate_xoauth2_user("u\x01v").is_err());
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn validate_xoauth2_user_accepts_typical_email_addresses() {
        assert!(validate_xoauth2_user("user@example.com").is_ok());
        assert!(validate_xoauth2_user("first.last+tag@example.co.uk").is_ok());
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn validate_oauth2_token_rejects_empty_and_whitespace() {
        assert!(validate_oauth2_token("").is_err());
        assert!(validate_oauth2_token("token with space").is_err());
        assert!(validate_oauth2_token("token\twith\ttab").is_err());
        assert!(validate_oauth2_token("token\nwith\nnewline").is_err());
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn validate_oauth2_token_rejects_non_ascii() {
        assert!(validate_oauth2_token("\u{00FF}token").is_err());
        assert!(validate_oauth2_token("token\u{4E2D}").is_err());
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn validate_oauth2_token_accepts_typical_bearer_tokens() {
        // Realistic Google token shape.
        assert!(
            validate_oauth2_token("ya29.A0AfH6SMBx-LAUH4xRcZbqK_pE7Hk0_lOxe2eGdt9CD8s8I").is_ok()
        );
        // Realistic Microsoft token shape (JWT).
        assert!(
            validate_oauth2_token("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIifQ.signature_part")
                .is_ok()
        );
        // Punctuation characters allowed by RFC 6750.
        assert!(validate_oauth2_token("a-b_c.d+e/f=g~h").is_ok());
    }

    // Note: the next test asserts the absence of XOAUTH2 from
    // auto-selection, which is meaningful only when XOAUTH2 itself
    // is compiled in. Without the feature, `AuthMechanism::XOAuth2`
    // can't be auto-picked because it can't be picked at all.
    #[cfg(feature = "xoauth2")]
    #[test]
    fn select_auth_mechanism_does_not_pick_xoauth2() {
        // Even when XOAUTH2 is the only advertised mechanism,
        // `select_auth_mechanism` returns None — XOAUTH2 requires a
        // bearer token rather than a static password and must be
        // opted-in explicitly via `login_with` or `login_xoauth2`.
        let lines: Vec<String> = vec!["AUTH XOAUTH2".into()];
        assert!(select_auth_mechanism(&lines).is_none());
    }

    // The AuthMechanism::XOAuth2 enum variant is present in either
    // feature configuration (the enum is non_exhaustive); only its
    // associated I/O code paths and helpers are gated.
    #[test]
    fn auth_mechanism_xoauth2_name_is_exact_keyword() {
        assert_eq!(AuthMechanism::XOAuth2.name(), "XOAUTH2");
        assert_eq!(format!("{}", AuthMechanism::XOAuth2), "XOAUTH2");
    }
}

// ---------------------------------------------------------------------------
// 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,
            enhanced: None,
            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::StartTls, "STARTTLS"),
            (SmtpOp::AuthPlain, "AUTH PLAIN"),
            (SmtpOp::AuthLogin, "AUTH LOGIN"),
            (SmtpOp::AuthXOAuth2, "AUTH XOAUTH2"),
            (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,
            enhanced: None,
            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,
                enhanced,
                message,
            }) => {
                assert_eq!(code, 535);
                assert!(message.contains("5.7.8"));
                // ENHANCEDSTATUSCODES is not advertised in the script
                // above, so the prefix should remain in the message
                // (and not be parsed out into the structured field).
                assert!(
                    enhanced.is_none(),
                    "without EHLO advertisement, no enhanced parse"
                );
            }
            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) -----------------------------------------------

    /// Pre-TLS portion of a STARTTLS-aware server script: greeting,
    /// EHLO with STARTTLS advertised, 220 ready-to-start.
    fn starttls_pre_upgrade() -> Vec<u8> {
        flatten(&[
            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",
        ])
    }

    /// Post-TLS portion: re-issued EHLO reply on the secure channel,
    /// now advertising AUTH PLAIN/LOGIN.
    fn starttls_post_upgrade() -> Vec<u8> {
        flatten(&[
            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_pre_upgrade()[..]],
            &[&starttls_post_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 pre = 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 post = flatten(&[
            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(&[&pre[..]], &[&post[..]], 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_pre_upgrade()[..]],
            &[&starttls_post_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 pre = 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 post = flatten(&[
            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(&[&pre[..]], &[&post[..]], 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);
    }

    // -- STARTTLS injection defense (Phase 9 / M-2) ----------------------

    #[test]
    fn starttls_buffer_residue_aborts_upgrade() {
        // Simulate a STARTTLS injection attack: extra SMTP commands
        // are pipelined onto the plaintext channel right after the
        // server's `220 ready` reply, before the TLS handshake. A
        // robust client must detect the unread residue at the moment
        // of upgrade and refuse to proceed.
        let pre_with_injected_residue = 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",
            // Attacker-injected command bytes pipelined onto the
            // plaintext channel — these would, without the defense,
            // be read AFTER the upgrade and treated as if they had
            // arrived over the secured channel.
            b"NOOP smuggled\r\n",
            b"MAIL FROM:<attacker@example.com>\r\n",
        ]);
        let (transport, _w, closed, upgrades) = MockTransport::with_starttls(
            &[&pre_with_injected_residue[..]],
            &[],
            UpgradeBehavior::Succeed,
        );
        let err = block_on(SmtpClient::connect_starttls(transport, "c.example"))
            .expect_err("must reject the injected residue");

        match err {
            SmtpError::Protocol(ProtocolError::StartTlsBufferResidue { byte_count }) => {
                // The two injected lines together total > 0 bytes; we
                // don't pin an exact value because "where the line
                // boundary fell" depends on the read chunk size. The
                // important check is that the defense fires.
                assert!(byte_count > 0, "byte_count must be positive: {byte_count}");
            }
            other => panic!("expected StartTlsBufferResidue, got {other:?}"),
        }

        // The session must NOT have proceeded to TLS — upgrade_to_tls
        // must not have been called.
        assert_eq!(
            *upgrades.borrow(),
            0,
            "upgrade_to_tls must not be called when residue is detected"
        );
        // The transport's `close()` is the caller's responsibility
        // via `quit()` or drop; our state-machine-level invariant is
        // that the session has been moved to Closed and any further
        // calls fail-fast. We verify the transport-level close flag
        // is left alone here, and rely on the next test below to
        // confirm session-state semantics.
        let _ = closed; // unused, retained for potential future test
    }

    #[test]
    fn starttls_buffer_residue_byte_count_is_residual_length() {
        // Verify that byte_count actually counts the unread bytes
        // remaining when the upgrade is about to begin. We use a
        // single, exactly-known injection.
        let pre = 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"X\r\n", // exactly 3 bytes of residue
        ]);
        let (transport, _w, _c, _u) =
            MockTransport::with_starttls(&[&pre[..]], &[], UpgradeBehavior::Succeed);
        let err = block_on(SmtpClient::connect_starttls(transport, "c.example"))
            .expect_err("must reject");
        match err {
            SmtpError::Protocol(ProtocolError::StartTlsBufferResidue { byte_count }) => {
                assert_eq!(byte_count, 3, "expected exactly the 3 bytes of `X\\r\\n`");
            }
            other => panic!("unexpected: {other:?}"),
        }
    }

    // -- ENHANCEDSTATUSCODES (Phase 6) ------------------------------------

    /// EHLO reply that advertises ENHANCEDSTATUSCODES alongside AUTH.
    fn greeting_then_ehlo_with_esmtp() -> Vec<u8> {
        flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250-PIPELINING\r\n",
            b"250-ENHANCEDSTATUSCODES\r\n",
            b"250 AUTH PLAIN\r\n",
        ])
    }

    #[test]
    fn unexpected_code_carries_enhanced_when_advertised() {
        let script = flatten(&[
            &greeting_then_ehlo_with_esmtp()[..],
            b"235 2.7.0 ok\r\n",                  // AUTH PLAIN ok
            b"550 5.7.1 relay access denied\r\n", // MAIL FROM rejected
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let err = block_on(client.send_mail(
            "a@example.com",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");

        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode {
                during,
                actual,
                enhanced,
                message,
                ..
            }) => {
                assert_eq!(during, SmtpOp::MailFrom);
                assert_eq!(actual, 550);
                let es = enhanced.expect("enhanced should be Some when advertised");
                assert_eq!(es.class, 5);
                assert_eq!(es.subject, 7);
                assert_eq!(es.detail, 1);
                // The wire form is preserved in `message`. The Display
                // impl renders `[5.7.1]` separately from the message.
                assert!(message.contains("5.7.1"));
            }
            other => panic!("expected UnexpectedCode with enhanced, got {other:?}"),
        }
    }

    #[test]
    fn unexpected_code_no_enhanced_when_not_advertised() {
        // EHLO does NOT include ENHANCEDSTATUSCODES; even if the server
        // sends "5.7.1" in the reply text, we must not parse it.
        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"235 OK\r\n",
            b"550 5.7.1 relay access denied\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let err = block_on(client.send_mail(
            "a@example.com",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");

        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode { enhanced, .. }) => {
                assert!(
                    enhanced.is_none(),
                    "without EHLO advertisement, enhanced must be None"
                );
            }
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    #[test]
    fn unexpected_code_display_includes_enhanced_bracket() {
        // When enhanced is set, Display renders `[x.y.z]` after the code.
        let script = flatten(&[
            &greeting_then_ehlo_with_esmtp()[..],
            b"235 OK\r\n",
            b"550 5.7.1 relay access denied\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let err = block_on(client.send_mail(
            "a@example.com",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");
        let s = format!("{err}");
        assert!(
            s.contains("[5.7.1]"),
            "Display should include enhanced bracket: {s}"
        );
        assert!(s.contains("550"), "Display should include basic code: {s}");
    }

    #[test]
    fn auth_rejected_carries_enhanced_when_advertised() {
        // ENHANCEDSTATUSCODES is advertised; AUTH PLAIN is rejected with
        // 535 5.7.8. The enhanced field must be propagated into
        // AuthError::Rejected.
        let script = flatten(&[
            &greeting_then_ehlo_with_esmtp()[..],
            b"535 5.7.8 invalid credentials\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&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,
                enhanced,
                message,
            }) => {
                assert_eq!(code, 535);
                let es = enhanced.expect("enhanced should be Some");
                assert_eq!((es.class, es.subject, es.detail), (5, 7, 8));
                assert!(message.contains("5.7.8"));
            }
            other => panic!("expected Auth::Rejected with enhanced, got {other:?}"),
        }
    }

    #[test]
    fn starttls_aborts_upgrade_when_buffer_holds_residue() {
        // STARTTLS injection / pipelining defence (RFC 3207 §5).
        //
        // The server "answers" the STARTTLS command with both a 220
        // ready reply AND an attacker-supplied EHLO-shaped line on
        // the same plaintext channel, before the TLS handshake. The
        // client must detect the residue, abort the upgrade, and
        // surface ProtocolError::StartTlsBufferResidue.
        let pre = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 STARTTLS\r\n",
            // Honest 220 reply + attacker-injected pipelined data:
            b"220 ready to start TLS\r\n",
            // Bytes pipelined onto the plaintext stream — these would
            // be read AFTER the TLS handshake on a vulnerable client
            // and treated as if they had arrived from the (now
            // authenticated) server.
            b"250 INJECTED capability\r\n",
        ]);
        // post_chunks empty: the upgrade must be rejected before
        // upgrade_to_tls() is reached, so no post-TLS bytes will be
        // read.
        let (transport, _w, _c, upgrades) =
            MockTransport::with_starttls(&[&pre[..]], &[], UpgradeBehavior::Succeed);
        let err = block_on(SmtpClient::connect_starttls(transport, "client.example"))
            .expect_err("must fail with residue error");

        match err {
            SmtpError::Protocol(ProtocolError::StartTlsBufferResidue { byte_count }) => {
                // The injected line is 25 bytes ("250 INJECTED capability\r\n").
                assert_eq!(byte_count, 25);
            }
            other => panic!("expected StartTlsBufferResidue, got {other:?}"),
        }
        // The TLS upgrade must NOT have been attempted: we caught the
        // injection BEFORE handing the socket off.
        assert_eq!(*upgrades.borrow(), 0);
    }

    #[test]
    fn enhancedstatuscodes_disabled_after_starttls_re_ehlo_without_it() {
        // The post-TLS EHLO reply governs the post-TLS enhanced state.
        // If the server stops advertising ENHANCEDSTATUSCODES after the
        // upgrade, parses are no longer attempted.
        let pre = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            // Pre-TLS EHLO advertises ENHANCEDSTATUSCODES.
            b"250-mail.example.com\r\n",
            b"250-STARTTLS\r\n",
            b"250 ENHANCEDSTATUSCODES\r\n",
            b"220 ready\r\n",
        ]);
        let post = flatten(&[
            // Post-TLS EHLO drops it.
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN\r\n",
            b"535 5.7.8 invalid\r\n", // 5.7.8 should NOT be parsed now
        ]);
        let (transport, _w, _c, _u) =
            MockTransport::with_starttls(&[&pre[..]], &[&post[..]], UpgradeBehavior::Succeed);
        let mut client = block_on(SmtpClient::connect_starttls(transport, "client.example"))
            .expect("connect_starttls");
        let err = block_on(client.login("user", "pass")).expect_err("must fail");
        match err {
            SmtpError::Auth(AuthError::Rejected { enhanced, .. }) => {
                assert!(
                    enhanced.is_none(),
                    "post-TLS EHLO dropped ENHANCEDSTATUSCODES: enhanced must be None"
                );
            }
            other => panic!("unexpected: {other:?}"),
        }
    }

    // -- XOAUTH2 (Phase 6 / Phase 7) --------------------------------------
    //
    // The XOAUTH2 SASL profile is gated behind the `xoauth2` cargo
    // feature (default-on). All tests that drive the
    // `login_xoauth2` / `login_with(AuthMechanism::XOAuth2, ..)`
    // code paths are conditional on the feature.

    /// EHLO reply that advertises AUTH XOAUTH2 (and PLAIN, so we can also
    /// check that `select_auth_mechanism` still picks PLAIN, not XOAUTH2).
    #[cfg(feature = "xoauth2")]
    fn greeting_then_ehlo_with_xoauth2() -> Vec<u8> {
        flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250-PIPELINING\r\n",
            b"250 AUTH PLAIN LOGIN XOAUTH2\r\n",
        ])
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_happy_path_succeeds_directly() {
        // 235 directly: server accepted the bearer token.
        let script = flatten(&[
            &greeting_then_ehlo_with_xoauth2()[..],
            b"235 2.7.0 Accepted\r\n",
        ]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login_xoauth2("user@example.com", "ya29.token")).expect("login");

        // Wire bytes: EHLO, then AUTH XOAUTH2 <b64>. Reconstruct the
        // expected base64 to compare.
        let mut payload = Vec::new();
        payload.extend_from_slice(b"user=user@example.com\x01auth=Bearer ya29.token\x01\x01");
        let b64 = crate::protocol::base64_encode(&payload);
        let expected = format!("EHLO client.example\r\nAUTH XOAUTH2 {b64}\r\n");
        assert_eq!(&*written.borrow(), expected.as_bytes());
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_login_with_explicit_mechanism_works() {
        // login_with(XOAuth2, ...) should be equivalent to login_xoauth2.
        let script = flatten(&[&greeting_then_ehlo_with_xoauth2()[..], b"235 OK\r\n"]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login_with(AuthMechanism::XOAuth2, "user@example.com", "ya29.token"))
            .expect("login_with XOAuth2");
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_handles_334_error_continuation() {
        // RFC 7628-style flow: server returns 334 with base64 JSON,
        // client sends an empty line, server sends final 5xx.
        // The 5xx text and any enhanced code must end up in the
        // AuthError::Rejected.
        let script = flatten(&[
            &greeting_then_ehlo_with_xoauth2()[..],
            b"334 eyJzdGF0dXMiOiI0MDEifQ==\r\n", // {"status":"401"} in b64
            b"535 5.7.8 Username and Password not accepted\r\n",
        ]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        // ENHANCEDSTATUSCODES is NOT advertised in this script, so
        // enhanced will be None — but we still verify the rejection
        // path itself.
        let err = block_on(client.login_xoauth2("user@example.com", "ya29.token"))
            .expect_err("must fail");
        match err {
            SmtpError::Auth(AuthError::Rejected { code, message, .. }) => {
                assert_eq!(code, 535);
                assert!(message.contains("Username and Password"));
            }
            other => panic!("expected Auth::Rejected, got {other:?}"),
        }

        // The client must have written the empty continuation line
        // between AUTH XOAUTH2 and the final read.
        let bytes = written.borrow();
        // The pattern "...<b64>\r\n\r\n" indicates the empty
        // continuation. Search for the trailing `\r\n\r\n`.
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(
            s.ends_with("\r\n\r\n"),
            "must end with empty continuation line: {s:?}"
        );
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_returns_unsupported_when_not_advertised() {
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250 AUTH PLAIN LOGIN\r\n", // no XOAUTH2
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login_xoauth2("user", "ya29.token")).expect_err("must fail");
        assert!(matches!(
            err,
            SmtpError::Auth(AuthError::UnsupportedMechanism)
        ));
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_validates_token_before_io() {
        // A token with a space would be rejected by the server but we
        // catch it locally. No bytes should be sent for AUTH.
        let script = flatten(&[&greeting_then_ehlo_with_xoauth2()[..]]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        // Capture the written bytes after EHLO so we can compare.
        let after_ehlo = written.borrow().len();
        let err = block_on(client.login_xoauth2("user", "bad token")).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // Nothing was written for AUTH.
        assert_eq!(written.borrow().len(), after_ehlo);
        // The session is still usable: input validation does not
        // poison the connection.
        assert_eq!(client.state(), SessionState::Authentication);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_validates_user_before_io() {
        let script = flatten(&[&greeting_then_ehlo_with_xoauth2()[..]]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        // SOH in the user would corrupt the SASL framing.
        let err = block_on(client.login_xoauth2("u\x01v", "ya29.token")).expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // Session should remain usable for legitimate retry.
        assert_eq!(client.state(), SessionState::Authentication);
    }

    #[cfg(feature = "xoauth2")]
    #[test]
    fn xoauth2_with_enhanced_status_propagates_code() {
        // ENHANCEDSTATUSCODES + XOAUTH2 + 334 error continuation +
        // final 5xx with enhanced. The enhanced should be parsed off
        // the final reply.
        let script = flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250-ENHANCEDSTATUSCODES\r\n",
            b"250 AUTH XOAUTH2\r\n",
            b"334 eyJzdGF0dXMiOiI0MDEifQ==\r\n",
            b"535 5.7.8 Bad credentials\r\n",
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        let err = block_on(client.login_xoauth2("user@example.com", "ya29.token"))
            .expect_err("must fail");
        match err {
            SmtpError::Auth(AuthError::Rejected { enhanced, .. }) => {
                let es = enhanced.expect("enhanced should be Some");
                assert_eq!((es.class, es.subject, es.detail), (5, 7, 8));
            }
            other => panic!("unexpected: {other:?}"),
        }
    }
}

// ---------------------------------------------------------------------------
// SMTPUTF8 (Phase 7) — feature-gated
// ---------------------------------------------------------------------------

#[cfg(feature = "smtputf8")]
mod smtputf8_tests {
    use super::harness::{MockTransport, block_on, flatten};
    use crate::client::SmtpClient;
    use crate::error::{ProtocolError, SmtpError, SmtpOp};
    use crate::protocol::{
        ehlo_advertises_smtputf8, format_mail_from_smtputf8, validate_address_utf8,
    };
    use crate::session::SessionState;

    // -- ehlo_advertises_smtputf8 -----------------------------------------

    #[test]
    fn ehlo_advertises_smtputf8_finds_listed_extension() {
        let lines: Vec<String> = vec!["PIPELINING".into(), "SMTPUTF8".into()];
        assert!(ehlo_advertises_smtputf8(&lines));
    }

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

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

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

    // -- validate_address_utf8 --------------------------------------------

    #[test]
    fn validate_address_utf8_accepts_ascii() {
        // Anything the strict ASCII validator accepts must also pass here.
        assert!(validate_address_utf8("user@example.com").is_ok());
        assert!(validate_address_utf8("a.b+c@d.example").is_ok());
    }

    /// Phase 9 / M-4: UTF-8 length limits also apply to `validate_address_utf8`.
    /// Japanese characters are 3 octets each in UTF-8, so 100 of them
    /// produce a 300-octet local-part which is past every limit.
    #[test]
    fn validate_address_utf8_rejects_overly_long_japanese_local_part() {
        let long_local: String = "\u{4E2D}".repeat(100);
        let addr = format!("{long_local}@example.jp");
        assert!(addr.len() > 254);
        assert!(validate_address_utf8(&addr).is_err());
    }

    #[test]
    fn validate_address_utf8_rejects_overly_long_total() {
        // 64-byte ASCII local-part (at the limit) + '@' + 191-byte ASCII
        // domain = 256 octets, just over the 254 cap.
        let local = "a".repeat(64);
        let domain = format!("{}.example", "x".repeat(183)); // 183 + 8 = 191
        let addr = format!("{local}@{domain}");
        assert_eq!(addr.len(), 256);
        assert!(validate_address_utf8(&addr).is_err());
    }

    #[test]
    fn validate_address_utf8_accepts_japanese_local_part() {
        assert!(validate_address_utf8("\u{9001}\u{4FE1}@example.jp").is_ok());
    }

    #[test]
    fn validate_address_utf8_accepts_idn_domain() {
        // U-label domain (Japanese ".jp" 例え.jp).
        assert!(validate_address_utf8("user@\u{4F8B}\u{3048}.jp").is_ok());
    }

    #[test]
    fn validate_address_utf8_accepts_combined_local_and_domain() {
        assert!(validate_address_utf8("\u{9001}\u{4FE1}@\u{4F8B}\u{3048}.jp").is_ok());
    }

    #[test]
    fn validate_address_utf8_rejects_empty() {
        assert!(validate_address_utf8("").is_err());
    }

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

    #[test]
    fn validate_address_utf8_rejects_nul() {
        assert!(validate_address_utf8("a\0b@c.com").is_err());
    }

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

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

    #[test]
    fn validate_address_utf8_accepts_ideographic_space() {
        // U+3000 is whitespace by Unicode category but valid in some
        // local parts and not a SMTP framing concern.
        assert!(validate_address_utf8("a\u{3000}b@c.com").is_ok());
    }

    #[test]
    fn validate_address_utf8_rejects_ascii_control_chars() {
        // ASCII DEL (0x7F).
        assert!(validate_address_utf8("a\u{007F}b@c.com").is_err());
        // Bell (0x07).
        assert!(validate_address_utf8("a\u{0007}b@c.com").is_err());
    }

    #[test]
    fn validate_address_utf8_rejects_c1_control_chars() {
        // U+0080-U+009F are C1 controls.
        assert!(validate_address_utf8("a\u{0085}b@c.com").is_err());
        assert!(validate_address_utf8("a\u{0095}b@c.com").is_err());
    }

    // -- format_mail_from_smtputf8 ----------------------------------------

    #[test]
    fn format_mail_from_smtputf8_appends_parameter() {
        let bytes = format_mail_from_smtputf8("user@example.com");
        assert_eq!(bytes, b"MAIL FROM:<user@example.com> SMTPUTF8\r\n");
    }

    #[test]
    fn format_mail_from_smtputf8_carries_utf8_address() {
        let bytes = format_mail_from_smtputf8("\u{9001}\u{4FE1}@example.jp");
        // The bytes must be exact UTF-8 of the input.
        let mut expected: Vec<u8> = Vec::new();
        expected.extend_from_slice(b"MAIL FROM:<");
        expected.extend_from_slice("\u{9001}\u{4FE1}@example.jp".as_bytes());
        expected.extend_from_slice(b"> SMTPUTF8\r\n");
        assert_eq!(bytes, expected);
    }

    // -- send_mail_smtputf8 E2E -------------------------------------------

    /// Greeting + EHLO advertising both AUTH PLAIN and SMTPUTF8.
    fn greeting_then_ehlo_with_smtputf8() -> Vec<u8> {
        flatten(&[
            b"220 mail.example.com ESMTP\r\n",
            b"250-mail.example.com\r\n",
            b"250-PIPELINING\r\n",
            b"250-SMTPUTF8\r\n",
            b"250 AUTH PLAIN\r\n",
        ])
    }

    #[test]
    fn send_mail_smtputf8_full_flow_with_japanese_addresses() {
        let script = flatten(&[
            &greeting_then_ehlo_with_smtputf8()[..],
            b"235 OK\r\n",       // AUTH PLAIN
            b"250 OK\r\n",       // MAIL FROM
            b"250 OK\r\n",       // RCPT TO
            b"354 go ahead\r\n", // DATA
            b"250 Queued\r\n",   // body accepted
        ]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        block_on(client.send_mail_smtputf8(
            "\u{9001}\u{4FE1}@example.jp",
            &["\u{53D7}\u{4FE1}@\u{4F8B}\u{3048}.jp"],
            "Subject: hi\r\n\r\nbody\r\n",
        ))
        .expect("send_mail_smtputf8");

        // The wire bytes should include: EHLO, AUTH PLAIN, MAIL FROM with
        // SMTPUTF8 parameter, RCPT TO without parameter, DATA, body, .
        let bytes = written.borrow();
        let s = std::str::from_utf8(&bytes).expect("bytes are valid UTF-8");
        assert!(s.contains("MAIL FROM:<\u{9001}\u{4FE1}@example.jp> SMTPUTF8\r\n"));
        assert!(s.contains("RCPT TO:<\u{53D7}\u{4FE1}@\u{4F8B}\u{3048}.jp>\r\n"));
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn send_mail_smtputf8_fails_when_extension_not_advertised() {
        // EHLO does not advertise SMTPUTF8.
        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"235 OK\r\n",
        ]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let after_login = written.borrow().len();

        let err = block_on(client.send_mail_smtputf8(
            "\u{9001}\u{4FE1}@example.jp",
            &["\u{53D7}\u{4FE1}@example.jp"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");

        match err {
            SmtpError::Protocol(ProtocolError::ExtensionUnavailable { name }) => {
                assert_eq!(name, "SMTPUTF8");
            }
            other => panic!("expected ExtensionUnavailable, got {other:?}"),
        }
        // No bytes were written for MAIL FROM: the failure happened
        // before any transport I/O.
        assert_eq!(written.borrow().len(), after_login);
        assert_eq!(client.state(), SessionState::Closed);
    }

    #[test]
    fn send_mail_smtputf8_validates_addresses_before_io() {
        let script = flatten(&[&greeting_then_ehlo_with_smtputf8()[..], b"235 OK\r\n"]);
        let (transport, written, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let after_login = written.borrow().len();

        // CR in the address must be caught locally.
        let err = block_on(client.send_mail_smtputf8(
            "u\rser@example.com",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
        // Nothing was written for the failed send.
        assert_eq!(written.borrow().len(), after_login);
        // Session remains usable for retry.
        assert_eq!(client.state(), SessionState::MailFrom);
    }

    #[test]
    fn send_mail_smtputf8_rejects_server_error_during_mail_from() {
        let script = flatten(&[
            &greeting_then_ehlo_with_smtputf8()[..],
            b"235 OK\r\n",                    // AUTH PLAIN
            b"550 sender domain refused\r\n", // MAIL FROM rejected
        ]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let err = block_on(client.send_mail_smtputf8(
            "\u{9001}\u{4FE1}@example.jp",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");
        match err {
            SmtpError::Protocol(ProtocolError::UnexpectedCode { during, actual, .. }) => {
                assert_eq!(during, SmtpOp::MailFrom);
                assert_eq!(actual, 550);
            }
            other => panic!("expected UnexpectedCode for MailFrom: {other:?}"),
        }
    }

    #[test]
    fn ascii_send_mail_unchanged_when_smtputf8_feature_enabled() {
        // Even with the feature on, the default `send_mail` continues
        // to use the strict ASCII validator. A UTF-8 address must be
        // refused by the default API.
        let script = flatten(&[&greeting_then_ehlo_with_smtputf8()[..], b"235 OK\r\n"]);
        let (transport, _w, _c) = MockTransport::new(&[&script[..]]);
        let mut client =
            block_on(SmtpClient::connect(transport, "client.example")).expect("connect");
        block_on(client.login("user", "pass")).expect("login");
        let err = block_on(client.send_mail(
            "\u{9001}\u{4FE1}@example.jp",
            &["b@example.org"],
            "Subject: x\r\n\r\nx\r\n",
        ))
        .expect_err("must fail");
        assert!(matches!(err, SmtpError::InvalidInput(_)));
    }
}