offline-protocol-mls 0.22.0

MLS (Message Layer Security) integration for end-to-end encryption in the Offline Protocol SDK
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
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
//! Main MLS manager - the primary interface for MLS operations.

use crate::error::{MlsError, Result};
use crate::group::{GroupManager, DEFAULT_CIPHERSUITE};
use crate::provider::MlsProvider;
use crate::session::SessionManager;
use crate::storage::MlsStorage;
use crate::storage_adapter::MlsStorageAdapter;
use crate::types::{
    EncryptedMessage, GroupId, GroupInfo, GroupMetadata, GroupRole, KeyPackageBundle,
    MlsMessageType, StorageKeyType, WelcomeMessage,
};

use offline_protocol_core::Address;
use openmls::prelude::tls_codec::{Deserialize as TlsDeserialize, Serialize as TlsSerialize};
use openmls::prelude::*;
use openmls_basic_credential::SignatureKeyPair;
use openmls_traits::OpenMlsProvider;
use std::sync::{Arc, RwLock};
use tracing::{debug, info, warn};
use uuid::Uuid;

/// Length of an Ed25519 public key, in bytes.
const ED25519_PUBLIC_KEY_LEN: usize = 32;

/// Default lifetime for key packages (30 days in seconds).
const DEFAULT_KEY_PACKAGE_LIFETIME_SECS: u64 = 30 * 24 * 60 * 60;

/// How long an expired key package's private init key is kept before it is
/// destroyed (7 days in seconds).
///
/// Expiry stops a package being advertised; this window is what still lets a
/// Welcome built against it just before that moment be processed. Past it the
/// material is genuinely deleted — without this, every package this device ever
/// minted would keep its init key in provider storage for the life of the
/// install, because the only other thing that removes one is a peer actually
/// using it.
const KEY_PACKAGE_PURGE_GRACE_SECS: u64 = 7 * 24 * 60 * 60;

/// Ceiling on live, unconsumed key packages the push path will keep in flight.
///
/// The pool is normally self-limiting: one package per peer, minted only when
/// that peer's previous one was consumed or expired, so its size tracks the
/// number of peers with an outstanding unused advertisement. This is the
/// backstop for the case where it does not — a device meeting an unbounded
/// stream of peers that never establish sessions. Reaching it degrades the
/// push path to sharing one package again, which is what it did unconditionally
/// before, so the failure mode is the old behaviour rather than a new one; it
/// is reported (see `PushKeyPackagePoolExhausted`) rather than left silent.
pub const MAX_PUSH_KEY_PACKAGES: usize = 64;

/// A key package handed to the push path, plus how healthy the pool was.
///
/// The flag is not an error: the package is usable either way. It reports that
/// the pool hit [`MAX_PUSH_KEY_PACKAGES`] and this package is therefore shared
/// with another peer, which is the one condition under which the push path
/// still has the reuse shape it otherwise no longer has.
#[derive(Debug, Clone)]
pub struct PushKeyPackage {
    /// The package to advertise.
    pub bundle: KeyPackageBundle,
    /// Whether the pool ceiling forced this package to be shared.
    pub pool_exhausted: bool,
}

/// Whether `candidate` was minted more recently than `current`, treating an
/// absent `current` as older than anything.
fn newer_than(candidate: &KeyPackageBundle, current: Option<&KeyPackageBundle>) -> bool {
    current.is_none_or(|existing| candidate.created_at_ms > existing.created_at_ms)
}

/// Main MLS manager for end-to-end encryption.
pub struct MlsManager {
    /// The local user's ID.
    user_id: String,

    /// Storage backend for persisting MLS state.
    storage: Arc<dyn MlsStorage>,

    /// OpenMLS provider.
    provider: MlsProvider,

    /// Cached credential.
    credential: RwLock<Option<CredentialWithKey>>,

    /// Cached signature key pair (avoids re-reading storage on every crypto op).
    cached_signer: RwLock<Option<SignatureKeyPair>>,

    /// Session manager for 1:1 messaging.
    session_manager: SessionManager,

    /// Group manager for multi-party groups.
    group_manager: GroupManager,
}

impl MlsManager {
    /// Creates a new MLS manager.
    pub fn new(user_id: impl Into<String>, storage: Arc<dyn MlsStorage>) -> Result<Self> {
        let user_id = user_id.into();

        let adapter = MlsStorageAdapter::new(storage.clone());
        let provider = MlsProvider::new(adapter);

        let session_manager =
            SessionManager::new(user_id.clone(), storage.clone(), provider.clone());
        let group_manager = GroupManager::new(storage.clone(), provider.clone());

        let manager = Self {
            user_id,
            storage,
            provider,
            credential: RwLock::new(None),
            cached_signer: RwLock::new(None),
            session_manager,
            group_manager,
        };

        manager.ensure_identity()?;

        Ok(manager)
    }

    /// Returns the local user's ID.
    pub fn user_id(&self) -> &str {
        &self.user_id
    }

    /// Loads this device's identity key from `storage`, minting and persisting
    /// one on first call, and returns the address it derives to.
    ///
    /// This is the bootstrap entry point: it exists so the address can be known
    /// *before* an [`MlsManager`] is constructed. The manager needs its own id
    /// at construction time (it goes into the credential and every session
    /// slot), but under self-certifying addressing that id is a function of the
    /// identity key — which used to be minted inside the constructor. Callers
    /// break the circle by calling this first and passing the resulting address
    /// to [`Self::new`].
    ///
    /// Idempotent: a second call returns the stored key and the same address.
    /// The keypair is written before the address is derived, so a caller that
    /// crashes between the two finds the same identity on the next start rather
    /// than minting a second one.
    pub fn load_or_create_identity(
        storage: &Arc<dyn MlsStorage>,
    ) -> Result<(SignatureKeyPair, Address)> {
        let key_type = StorageKeyType::Identity.as_str();

        let signature_keys = match storage.load(key_type, "key_pair")? {
            Some(json) => serde_json::from_slice(&json).map_err(|e| {
                MlsError::Deserialization(format!("Failed to deserialize signature keys: {}", e))
            })?,
            None => {
                let keys = SignatureKeyPair::new(DEFAULT_CIPHERSUITE.signature_algorithm())
                    .map_err(|e| MlsError::CryptoGeneration(format!("{:?}", e)))?;
                let keys_json = serde_json::to_vec(&keys)
                    .map_err(|e| MlsError::Serialization(e.to_string()))?;
                storage.store(key_type, "key_pair", &keys_json)?;
                info!("Minted a new identity key");
                keys
            }
        };

        let address = Self::derive_address(signature_keys.public())?;
        Ok((signature_keys, address))
    }

    /// Ensures the user has an identity.
    fn ensure_identity(&self) -> Result<()> {
        if self.load_identity()? {
            return Ok(());
        }
        self.create_identity()?;
        info!(user_id = %self.user_id, "Created new MLS identity");
        Ok(())
    }

    /// Requires the stored identity key to derive to `self.user_id` when that
    /// id is an address.
    ///
    /// A nickname id (tests, legacy) has no derivation to check, so it passes
    /// unchecked — the check is about catching a *broken* self-certifying
    /// identity, not about enforcing that ids are addresses.
    fn verify_identity_binding(&self, public_key: &[u8]) -> Result<()> {
        let Ok(expected) = self.user_id.parse::<Address>() else {
            return Ok(());
        };

        let derived = Self::derive_address(public_key)?;
        if derived != expected {
            return Err(MlsError::IdentityAddressMismatch {
                expected: expected.to_string(),
                derived: derived.to_string(),
            });
        }
        Ok(())
    }

    /// Loads the identity from storage.
    fn load_identity(&self) -> Result<bool> {
        let key_type = StorageKeyType::Identity.as_str();
        let keys_data = self.storage.load(key_type, "key_pair")?;

        match keys_data {
            Some(json) => {
                let signature_keys: SignatureKeyPair =
                    serde_json::from_slice(&json).map_err(|e| {
                        MlsError::Deserialization(format!(
                            "Failed to deserialize signature keys: {}",
                            e
                        ))
                    })?;

                let public_key = signature_keys.public();

                // Under self-certifying addressing the id is this key's hash,
                // so a disagreement means the wrong namespace was opened or the
                // stored key was replaced. Caught here rather than shipping a
                // credential every peer would reject.
                self.verify_identity_binding(public_key)?;

                let credential =
                    Credential::new(CredentialType::Basic, self.user_id.as_bytes().to_vec());

                let credential_with_key = CredentialWithKey {
                    credential,
                    signature_key: public_key.into(),
                };

                {
                    let mut guard = self
                        .credential
                        .write()
                        .map_err(|_| MlsError::NotInitialized)?;
                    *guard = Some(credential_with_key);
                }
                {
                    let mut guard = self
                        .cached_signer
                        .write()
                        .map_err(|_| MlsError::NotInitialized)?;
                    *guard = Some(signature_keys);
                }

                debug!(user_id = %self.user_id, "Loaded existing MLS identity");
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Creates a new identity.
    fn create_identity(&self) -> Result<()> {
        let signature_keys = SignatureKeyPair::new(DEFAULT_CIPHERSUITE.signature_algorithm())
            .map_err(|e| MlsError::CryptoGeneration(format!("{:?}", e)))?;

        // A freshly minted key derives to a fresh address, so an
        // address-shaped `user_id` reaching here means the caller asked this
        // manager to *claim* an address whose key it does not hold — the
        // storage was empty when it should have held that identity. Checked
        // before the key is persisted so the refusal leaves nothing behind.
        // The supported bootstrap is `load_or_create_identity` first, then
        // `new` with the address it returned.
        self.verify_identity_binding(signature_keys.public())?;

        let keys_json = serde_json::to_vec(&signature_keys)
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        let key_type = StorageKeyType::Identity.as_str();
        self.storage.store(key_type, "key_pair", &keys_json)?;

        let public_key = signature_keys.public();

        let credential = Credential::new(CredentialType::Basic, self.user_id.as_bytes().to_vec());

        let credential_with_key = CredentialWithKey {
            credential,
            signature_key: public_key.into(),
        };

        {
            let mut guard = self
                .credential
                .write()
                .map_err(|_| MlsError::NotInitialized)?;
            *guard = Some(credential_with_key);
        }
        {
            let mut guard = self
                .cached_signer
                .write()
                .map_err(|_| MlsError::NotInitialized)?;
            *guard = Some(signature_keys);
        }

        Ok(())
    }

    /// Gets the credential with key.
    fn get_credential(&self) -> Result<CredentialWithKey> {
        let guard = self
            .credential
            .read()
            .map_err(|_| MlsError::NotInitialized)?;
        guard.clone().ok_or(MlsError::NotInitialized)
    }

    /// Gets a signer for MLS operations, using the in-memory cache.
    ///
    /// `SignatureKeyPair` doesn't implement `Clone`, so we serialize from
    /// the cached copy to avoid hitting storage on every crypto operation.
    fn get_signer(&self) -> Result<SignatureKeyPair> {
        let guard = self
            .cached_signer
            .read()
            .map_err(|_| MlsError::NotInitialized)?;

        let cached = guard.as_ref().ok_or(MlsError::NotInitialized)?;
        let bytes =
            serde_json::to_vec(cached).map_err(|e| MlsError::Serialization(e.to_string()))?;
        serde_json::from_slice(&bytes).map_err(|e| MlsError::Deserialization(e.to_string()))
    }

    // ========================================================================
    // KEY PACKAGE MANAGEMENT
    // ========================================================================

    /// Generates a new key package for distribution over the push path.
    pub fn generate_key_package(&self) -> Result<KeyPackageBundle> {
        self.generate_key_package_inner(false)
    }

    /// Generates a key package reserved for a publication slot.
    ///
    /// Distinct from [`Self::generate_key_package`] only in that the result is
    /// withheld from [`Self::get_or_create_key_package`] — see
    /// [`KeyPackageBundle::reserved_for_publication`] for why sharing one
    /// package between a published record and a pushed exchange corrupts both.
    pub fn generate_publication_key_package(&self) -> Result<KeyPackageBundle> {
        self.generate_key_package_inner(true)
    }

    fn generate_key_package_inner(&self, reserved: bool) -> Result<KeyPackageBundle> {
        let credential = self.get_credential()?;
        let signature_keys = self.get_signer()?;

        let key_package_bundle = KeyPackage::builder()
            .build(
                DEFAULT_CIPHERSUITE,
                &self.provider,
                &signature_keys,
                credential,
            )
            .map_err(|e| MlsError::KeyPackageCreation(e.to_string()))?;

        let key_package_data = key_package_bundle
            .key_package()
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        // Stamped now because deriving it later from the serialized bytes
        // costs a parse plus a signature validation, which the pool scan
        // would pay per stored package per push. Best-effort: a record
        // without it takes the derive path once and is backfilled on load.
        let provider_hash_ref = key_package_bundle
            .key_package()
            .hash_ref(self.provider.crypto())
            .ok()
            .and_then(|hash_ref| hash_ref.tls_serialize_detached().ok());

        let package_id = Uuid::new_v4().to_string();

        let key_type = StorageKeyType::KeyPackage.as_str();
        let mut bundle = KeyPackageBundle::new(
            package_id,
            self.user_id.clone(),
            key_package_data,
            DEFAULT_KEY_PACKAGE_LIFETIME_SECS,
        );
        bundle.reserved_for_publication = reserved;
        bundle.provider_hash_ref = provider_hash_ref;
        let serialized =
            serde_json::to_vec(&bundle).map_err(|e| MlsError::Serialization(e.to_string()))?;
        self.storage
            .store(key_type, &bundle.package_id, &serialized)?;

        debug!(package_id = %bundle.package_id, "Generated new key package");
        Ok(bundle)
    }

    /// Gets an existing *unclaimed* key package or generates a new one.
    ///
    /// Two kinds of package are skipped, for the same underlying reason — an
    /// MLS init key is consumed by its first user, so two parties must never be
    /// pointed at one:
    ///
    /// - packages reserved for publication slots, or a pushed-to peer and a
    ///   stranger who fetched the published record would race for it;
    /// - packages already claimed by a peer over the push path
    ///   ([`Self::take_push_key_package`]), or this peer-less entry point would
    ///   hand out a key another peer is expected to use.
    ///
    /// This is the peer-less escape hatch (the FFI surface and tests). Callers
    /// that know the recipient should use [`Self::take_push_key_package`],
    /// which is what actually holds the one-key-per-peer property; a package
    /// handed out here is unclaimed, so the push path may later claim it for
    /// the first peer it is pushed to.
    pub fn get_or_create_key_package(&self) -> Result<KeyPackageBundle> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let packages = self.storage.list_keys(key_type)?;

        for package_id in packages {
            if let Some(bundle) = self.load_stored_key_package(&package_id)? {
                if bundle.reserved_for_publication || bundle.assigned_peer.is_some() {
                    continue;
                }
                return Ok(bundle);
            }
        }

        self.generate_key_package()
    }

    /// Hands `peer_id` the key package to advertise to it, minting one if it
    /// has no live package of its own.
    ///
    /// This is the push path's entry point, and the whole point of it is that
    /// two peers never receive the same init key. Before this existed the push
    /// path returned the first stored package to every caller until somebody's
    /// Welcome consumed it — the LastResort-style reuse RFC 9420 §16.8 permits
    /// only as a denial-of-service fallback, and which the Least Authority MDK
    /// audit flagged as enabling unsolicited joins and cross-group linkage. It
    /// also made a second peer's Welcome unprocessable once the first had used
    /// the key, with nothing to re-drive the exchange.
    ///
    /// Assignment is stored on the package rather than in a separate map, so it
    /// survives restarts for free and cannot disagree with the pool it
    /// describes. Resolution order:
    ///
    /// 1. this peer's own live package — a repeat push costs no new material;
    /// 2. an unclaimed package (minted by the peer-less entry point, or by a
    ///    build predating assignment), claimed here so upgrading does not
    ///    strand it;
    /// 3. a freshly minted package, claimed for this peer.
    ///
    /// Past [`MAX_PUSH_KEY_PACKAGES`] live packages it stops growing the pool
    /// and reuses the newest one, reporting that through
    /// [`PushKeyPackage::pool_exhausted`] so the caller can surface it. That is
    /// a deliberate degradation to the old behaviour rather than an error: the
    /// alternative — refusing to advertise, or evicting a package a peer may
    /// still be about to use — costs session establishment, which is worse than
    /// the weakened forward secrecy it would buy.
    ///
    /// Only step 3 is gated by the ceiling, because only minting grows the
    /// pool: claiming an unclaimed package relabels one that already exists, so
    /// degrading to a shared package while a claimable one sits idle would buy
    /// nothing. A corollary is that the shared package is always assigned to
    /// *another* peer — reaching that branch means neither an own nor an
    /// unclaimed package was found — and "newest" makes it the most recently
    /// assigned one, which has the most lifetime left but is also the peer most
    /// likely to be mid-establishment. If the over-ceiling peer's Welcome lands
    /// first, that peer's held advertisement becomes unprocessable until the
    /// next push to it mints a successor. Sharing the oldest instead would
    /// trade that for the shortest remaining lifetime; neither is free, and the
    /// exhaustion report is what makes the condition visible either way.
    ///
    /// Consumption is what rotates a peer's key: a Welcome built against the
    /// package removes its init key from provider storage, the loader then
    /// reports the package gone, and the next push to that peer mints a fresh
    /// one.
    pub fn take_push_key_package(&self, peer_id: &str) -> Result<PushKeyPackage> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let package_ids = self.storage.list_keys(key_type)?;

        let mut live = 0usize;
        let mut assigned_here: Option<KeyPackageBundle> = None;
        let mut unclaimed: Option<KeyPackageBundle> = None;
        let mut newest: Option<KeyPackageBundle> = None;

        // One pass, which also does the pruning: `load_stored_key_package`
        // drops consumed and long-expired entries as it reads them, so the
        // count below is of genuinely usable packages.
        for package_id in package_ids {
            let Some(bundle) = self.load_stored_key_package(&package_id)? else {
                continue;
            };
            if bundle.reserved_for_publication {
                continue;
            }
            live += 1;

            if bundle.assigned_peer.as_deref() == Some(peer_id) {
                // Newest wins if a past interruption left this peer two.
                if newer_than(&bundle, assigned_here.as_ref()) {
                    assigned_here = Some(bundle.clone());
                }
            } else if bundle.assigned_peer.is_none() && newer_than(&bundle, unclaimed.as_ref()) {
                unclaimed = Some(bundle.clone());
            }

            if newer_than(&bundle, newest.as_ref()) {
                newest = Some(bundle);
            }
        }

        if let Some(bundle) = assigned_here {
            return Ok(PushKeyPackage {
                bundle,
                pool_exhausted: false,
            });
        }

        // Before the ceiling check, not after: claiming relabels a package that
        // already exists, so it cannot breach a bound on how many exist.
        if let Some(bundle) = unclaimed {
            return Ok(PushKeyPackage {
                bundle: self.claim_key_package(bundle, peer_id)?,
                pool_exhausted: false,
            });
        }

        // Minting is the only thing left that would grow the pool, so it is the
        // only thing the ceiling gates.
        if live >= MAX_PUSH_KEY_PACKAGES {
            // `live` is non-zero here, so `newest` is `Some`; minting on the
            // unreachable branch keeps this total without an unwrap.
            if let Some(bundle) = newest {
                debug!(
                    peer_id = %peer_id,
                    live = live,
                    "Push key-package pool at capacity; reusing an existing package"
                );
                return Ok(PushKeyPackage {
                    bundle,
                    pool_exhausted: true,
                });
            }
        }

        let bundle = self.claim_key_package(self.generate_key_package()?, peer_id)?;

        Ok(PushKeyPackage {
            bundle,
            pool_exhausted: false,
        })
    }

    /// Records `peer_id` as the owner of `bundle` and persists the claim.
    fn claim_key_package(
        &self,
        mut bundle: KeyPackageBundle,
        peer_id: &str,
    ) -> Result<KeyPackageBundle> {
        bundle.assigned_peer = Some(peer_id.to_string());
        let serialized =
            serde_json::to_vec(&bundle).map_err(|e| MlsError::Serialization(e.to_string()))?;
        self.storage.store(
            StorageKeyType::KeyPackage.as_str(),
            &bundle.package_id,
            &serialized,
        )?;
        debug!(
            package_id = %bundle.package_id,
            peer_id = %peer_id,
            "Assigned key package to peer"
        );
        Ok(bundle)
    }

    /// Loads a specific key package this device owns, or `None` if it is gone.
    ///
    /// `None` is the *consumption signal* the publication slots run on: the
    /// load prunes and reports missing any package whose private init key has
    /// left the OpenMLS provider, which is exactly what processing a Welcome
    /// built against it does. A slot whose package reads back `None` has been
    /// used by somebody and needs replacing.
    pub fn key_package_by_id(&self, package_id: &str) -> Result<Option<KeyPackageBundle>> {
        self.load_stored_key_package(package_id)
    }

    /// Deletes a key package this device owns.
    ///
    /// Exists to reclaim a *publication* package that was minted but whose
    /// record was never built or queued. Such a package is reserved, so
    /// [`Self::get_or_create_key_package`] will never hand it out, and no slot
    /// references it — nothing else would remove it before its lifetime runs
    /// out, so a repeatedly failing publish would otherwise strand fresh
    /// provider key material every refresh.
    ///
    /// "Strand" is meant literally, which is why this destroys the private init
    /// key too: deleting the bundle record alone leaves the material OpenMLS
    /// holds in place with nothing left pointing at it.
    pub fn delete_key_package(&self, package_id: &str) -> Result<()> {
        let Some(data) = self
            .storage
            .load(StorageKeyType::KeyPackage.as_str(), package_id)?
        else {
            return Ok(());
        };

        match serde_json::from_slice::<KeyPackageBundle>(&data) {
            Ok(bundle) => self.purge_key_package_material(package_id, &bundle),
            // Legacy raw storage: the record *is* the serialized key package,
            // the same reading `load_stored_key_package` applies when it
            // upgrades one. Wrapping it lets the purge derive the provider ref
            // and destroy the init key instead of stranding it — and if the
            // bytes are not a key package at all, the purge finds no ref and
            // falls back to deleting the record, which is all that is left to
            // do for a record that names nothing.
            Err(_) => {
                let legacy = KeyPackageBundle::new(
                    package_id.to_string(),
                    self.user_id.clone(),
                    data,
                    DEFAULT_KEY_PACKAGE_LIFETIME_SECS,
                );
                self.purge_key_package_material(package_id, &legacy)
            }
        }
    }

    /// Imports a contact's key package for later use.
    ///
    /// Security (SEC-M5): the caller-supplied `user_id` becomes both the
    /// storage key and — at session creation — the identity this key
    /// package is trusted for. Reject storage-hostile ids (the id is a raw
    /// `key_id`), cryptographically validate the key package, and require
    /// the embedded credential identity to equal `user_id` so a key
    /// package generated by one user can never be imported under
    /// another's name.
    ///
    /// The identity claim is then *proved* rather than trusted: see
    /// `Self::verify_address_binding`. No Authentication Service verdict
    /// travels with the call any more, because there is nothing for the caller
    /// to know — the key package carries its own proof.
    pub fn import_key_package(&self, user_id: &str, key_package_data: &[u8]) -> Result<()> {
        offline_protocol_core::validate_id_chars(user_id, "User ID")
            .map_err(|e| MlsError::InvalidUserId(e.to_string()))?;

        let key_package_in = KeyPackageIn::tls_deserialize_exact(key_package_data)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;
        let key_package = key_package_in
            .validate(self.provider.crypto(), ProtocolVersion::Mls10)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;

        Self::verify_credential_identity(&key_package, user_id)?;
        Self::verify_address_binding(&key_package, user_id)?;

        let key_type = StorageKeyType::ContactKeyPackage.as_str();
        self.storage.store(key_type, user_id, key_package_data)?;

        debug!(user_id = %user_id, "Imported key package for contact");
        Ok(())
    }

    /// Gets a contact's key package.
    fn get_contact_key_package(&self, user_id: &str) -> Result<KeyPackage> {
        let key_type = StorageKeyType::ContactKeyPackage.as_str();
        let data = self
            .storage
            .load(key_type, user_id)?
            .ok_or_else(|| MlsError::NoKeyPackage(user_id.to_string()))?;

        let key_package_in = KeyPackageIn::tls_deserialize_exact(&data)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;

        // Validate using the crypto backend
        let key_package = key_package_in
            .validate(self.provider.crypto(), ProtocolVersion::Mls10)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;

        // Defense in depth: entries written to storage out-of-band must not
        // come back attributed to the wrong user. Both checks run again here
        // rather than only at import, because a cached package is re-read long
        // after the receive-time gate that admitted it — which is exactly the
        // window a container write aims at.
        Self::verify_credential_identity(&key_package, user_id)?;
        Self::verify_address_binding(&key_package, user_id)?;

        Ok(key_package)
    }

    /// Requires the key package's leaf signature key to derive to the address
    /// in `user_id`.
    ///
    /// This is the check that makes a key package's identity claim mean
    /// something. [`Self::verify_credential_identity`] compares the leaf's
    /// *basic credential*, which per RFC 9420 is "a bare assertion of an
    /// identity" — self-asserted, so an attacker who generates their own
    /// signature keypair and writes someone else's address into the credential
    /// passes it. The leaf signature key is not self-asserted relative to an
    /// address: the address *is* its hash, so re-deriving it either reproduces
    /// the claim or refutes it.
    ///
    /// This matters because a validated key package is not necessarily a
    /// *freshly received* one. Packages are cached in the install-scoped
    /// protocol-state store and re-read later, and the receive-time signature
    /// gate does not travel with them. Without this comparison, anyone able to
    /// write that store could swap in their own package and have the local node
    /// build the session — and encrypt to — their leaf instead of the peer's.
    ///
    /// # Why a non-address `user_id` is an error, not a skip
    ///
    /// Answering `Ok(())` for an id that does not parse as an [`Address`] would
    /// hand every attacker the bypass: claim a nickname and the check that
    /// distinguishes you from its owner never runs. The predecessor of this
    /// function *was* conditional — it checked only when the caller held a pin
    /// — and that conditionality is precisely what an unpinned peer exploited.
    /// It is unconditional here, which is what makes it the whole trust
    /// mechanism rather than a supplement to one.
    fn verify_address_binding(key_package: &KeyPackage, user_id: &str) -> Result<()> {
        let claimed = user_id.parse::<Address>().map_err(|e| {
            MlsError::InvalidUserId(format!("'{}' is not an address: {}", user_id, e))
        })?;

        let derived = Self::derive_address(key_package.leaf_node().signature_key().as_slice())?;
        if derived != claimed {
            return Err(MlsError::KeyPackageAddressMismatch {
                claimed: claimed.to_string(),
                derived: derived.to_string(),
            });
        }
        Ok(())
    }

    /// Requires the key package's leaf credential identity to equal
    /// `user_id`. Credentials in this SDK are basic credentials carrying
    /// the owner's user id as raw bytes (see `IdentityManager`).
    fn verify_credential_identity(key_package: &KeyPackage, user_id: &str) -> Result<()> {
        let identity = key_package.leaf_node().credential().serialized_content();
        if identity != user_id.as_bytes() {
            return Err(MlsError::CredentialIdentityMismatch {
                expected: user_id.to_string(),
                found: String::from_utf8_lossy(identity).into_owned(),
            });
        }
        Ok(())
    }

    /// Gets pending key packages.
    pub fn get_pending_key_packages(&self) -> Result<Vec<KeyPackageBundle>> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let package_ids = self.storage.list_keys(key_type)?;

        let mut bundles = Vec::new();
        for package_id in package_ids {
            if let Some(bundle) = self.load_stored_key_package(&package_id)? {
                bundles.push(bundle);
            }
        }

        Ok(bundles)
    }

    /// Marks a key package as synced.
    pub fn mark_key_package_synced(&self, package_id: &str) -> Result<()> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        self.storage.delete(key_type, package_id)?;
        debug!(package_id = %package_id, "Marked key package as synced");
        Ok(())
    }

    // ========================================================================
    // 1:1 ENCRYPTED MESSAGING
    // ========================================================================

    /// Checks if a session exists with another user.
    pub fn has_session(&self, other_user_id: &str) -> Result<bool> {
        self.session_manager.has_session(other_user_id)
    }

    /// Creates a new 1:1 session with another user.
    pub fn create_session(&self, other_user_id: &str) -> Result<WelcomeMessage> {
        let their_key_package = self.get_contact_key_package(other_user_id)?;
        let credential = self.get_credential()?;
        let signature_keys = self.get_signer()?;

        let welcome = self.session_manager.create_session(
            other_user_id,
            their_key_package,
            &credential,
            &signature_keys,
        )?;

        let key_type = StorageKeyType::ContactKeyPackage.as_str();
        self.storage.delete(key_type, other_user_id)?;

        Ok(welcome)
    }

    /// Joins a session using a Welcome message.
    pub fn join_session(&self, welcome: &WelcomeMessage) -> Result<GroupInfo> {
        self.session_manager.join_session(welcome)
    }

    /// Replaces an existing session with an incoming Welcome message.
    ///
    /// This implements the "welcome-wins" strategy for race condition resolution.
    /// When both peers simultaneously create a session, this method allows one peer
    /// to replace their own session with the other peer's Welcome, ensuring both
    /// end up with the same cryptographic state.
    pub fn replace_session_with_welcome(&self, welcome: &WelcomeMessage) -> Result<GroupInfo> {
        let other_user_id = &welcome.inviter_id;

        // Security: `inviter_id` arrives on the wire and is used below as a
        // raw storage key for deletes — reject storage-hostile values just
        // like `import_key_package` does for its user id.
        offline_protocol_core::validate_id_chars(other_user_id, "User ID")
            .map_err(|e| MlsError::InvalidUserId(e.to_string()))?;

        // SEC-M6: reject a mismatched session slot BEFORE the best-effort
        // deletes below, so a forged Welcome that squats a third party's slot
        // performs no mutation. `join_session` re-checks this as its own
        // boundary; hoisting it here keeps the reject side effect-free.
        self.session_manager.verify_welcome_slot(welcome)?;

        // Clear any pending welcome we were about to send
        let _ = self.clear_pending_welcome(other_user_id);

        // Delete conflicting contact key package (we no longer need it)
        let key_type = StorageKeyType::ContactKeyPackage.as_str();
        let _ = self.storage.delete(key_type, other_user_id);

        // Join using their Welcome. `join_session` adopts non-destructively
        // (stage-then-swap), so a retransmitted Welcome that re-stages is a safe
        // no-op rather than deleting and re-creating our existing session.
        self.session_manager.join_session(welcome)
    }

    /// Encrypts a message for a 1:1 session.
    pub fn encrypt_for_user(
        &self,
        other_user_id: &str,
        plaintext: &[u8],
    ) -> Result<EncryptedMessage> {
        if !self.has_session(other_user_id)? {
            let welcome = self.create_session(other_user_id)?;
            warn!(
                other_user_id = %other_user_id,
                "Created new session - Welcome message needs to be sent"
            );
            let key_type = StorageKeyType::PendingWelcome.as_str();
            let welcome_data =
                serde_json::to_vec(&welcome).map_err(|e| MlsError::Serialization(e.to_string()))?;
            self.storage.store(key_type, other_user_id, &welcome_data)?;
        }

        let signature_keys = self.get_signer()?;
        self.session_manager
            .encrypt_message(other_user_id, plaintext, &signature_keys)
    }

    /// Encrypts a message for a 1:1 session that is known to exist.
    ///
    /// Unlike `encrypt_for_user`, this skips the `has_session()` storage check
    /// and goes directly to `encrypt_message()`. The caller must guarantee the
    /// session exists (e.g., via an in-memory cache). If the session was deleted
    /// externally, `SessionNotFound` is returned.
    pub fn encrypt_for_existing_session(
        &self,
        other_user_id: &str,
        plaintext: &[u8],
    ) -> Result<EncryptedMessage> {
        let signature_keys = self.get_signer()?;
        self.session_manager
            .encrypt_message(other_user_id, plaintext, &signature_keys)
    }

    /// Gets a pending Welcome message.
    pub fn get_pending_welcome(&self, other_user_id: &str) -> Result<Option<WelcomeMessage>> {
        let key_type = StorageKeyType::PendingWelcome.as_str();
        match self.storage.load(key_type, other_user_id)? {
            Some(data) => {
                let welcome: WelcomeMessage = serde_json::from_slice(&data)
                    .map_err(|e| MlsError::Deserialization(e.to_string()))?;
                Ok(Some(welcome))
            }
            None => Ok(None),
        }
    }

    /// Clears a pending Welcome message.
    pub fn clear_pending_welcome(&self, other_user_id: &str) -> Result<()> {
        let key_type = StorageKeyType::PendingWelcome.as_str();
        self.storage.delete(key_type, other_user_id)?;
        Ok(())
    }

    /// Decrypts a message from a 1:1 session.
    ///
    /// `claimed_sender` is the transport-level sender this message will be
    /// attributed to; decryption fails with
    /// [`MlsError::SenderIdentityMismatch`] if it does not match the
    /// MLS-authenticated credential (SEC-M1).
    pub fn decrypt_from_user(
        &self,
        encrypted: &EncryptedMessage,
        claimed_sender: &str,
    ) -> Result<Option<Vec<u8>>> {
        self.session_manager
            .decrypt_message(encrypted, claimed_sender)
    }

    /// Lists all active 1:1 sessions.
    pub fn list_sessions(&self) -> Result<Vec<String>> {
        self.session_manager.list_sessions()
    }

    /// Deletes a 1:1 session.
    pub fn delete_session(&self, other_user_id: &str) -> Result<()> {
        self.session_manager.delete_session(other_user_id)
    }

    // ========================================================================
    // GROUP MESSAGING
    // ========================================================================

    /// Creates a new group.
    pub fn create_group(&self, group_name: &str) -> Result<GroupInfo> {
        let group_id = GroupId::new(format!("group:{}", Uuid::new_v4()))?;
        let credential = self.get_credential()?;
        let signature_keys = self.get_signer()?;

        let group = self
            .group_manager
            .create_group(&group_id, &credential, &signature_keys)?;

        // Store group metadata with creator as admin
        let metadata = GroupMetadata::new_with_creator(Some(group_name.to_string()), &self.user_id);
        self.save_group_metadata(&group_id, &metadata)?;

        let mut info = self.group_manager.get_group_info(&group, &group_id);
        info.name = metadata.name;
        info.created_at_ms = metadata.created_at_ms;
        info.last_activity_ms = metadata.last_activity_ms;

        info!(group_id = %group_id, name = %group_name, "Created new group");
        Ok(info)
    }

    /// Adds a member to a group.
    ///
    /// Returns a tuple of (WelcomeMessage, EncryptedMessage) where the
    /// WelcomeMessage should be sent to the invitee and the EncryptedMessage
    /// (Commit) should be distributed to all existing group members so they
    /// can advance their MLS epoch.
    ///
    /// `invitee_user_id` binds the package to the identity it is being added
    /// under. This path previously ran neither check — not even the
    /// credential-identity one `import_key_package` has always had — so a
    /// package could be admitted to a group under a roster label that had
    /// nothing to do with it. The 1:1 path and the group path apply the same
    /// two checks.
    pub fn add_group_member(
        &self,
        group_id: &GroupId,
        invitee_user_id: &str,
        member_key_package: &[u8],
    ) -> Result<(WelcomeMessage, EncryptedMessage)> {
        let key_package = KeyPackageIn::tls_deserialize_exact(member_key_package)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?
            .validate(self.provider.crypto(), ProtocolVersion::Mls10)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;

        Self::verify_credential_identity(&key_package, invitee_user_id)?;
        Self::verify_address_binding(&key_package, invitee_user_id)?;

        let mut group = self
            .group_manager
            .load_group(group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(group_id.to_string()))?;

        let signature_keys = self.get_signer()?;
        let (commit, welcome) =
            self.group_manager
                .add_member(&mut group, key_package, &signature_keys)?;

        self.group_manager.save_group(group_id, &group)?;

        let welcome_bytes = welcome
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        let commit_bytes = commit
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        // Include group name in welcome for the invitee
        let group_name = self.load_group_metadata(group_id)?.and_then(|m| m.name);

        let now_ms = chrono::Utc::now().timestamp_millis() as u64;

        let welcome_msg = WelcomeMessage {
            group_id: group_id.clone(),
            welcome_data: welcome_bytes,
            inviter_id: self.user_id.clone(),
            group_name,
            timestamp_ms: now_ms,
        };

        let commit_msg = EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Commit,
            epoch: group.epoch().as_u64(),
            ciphertext: commit_bytes,
            sender_id: self.user_id.clone(),
            timestamp_ms: now_ms,
        };

        Ok((welcome_msg, commit_msg))
    }

    /// Removes a member from a group.
    ///
    /// Removes **every** leaf whose credential names `member_id`, in one
    /// commit, rather than the first one found.
    ///
    /// Two leaves cannot name one identity in a tree whose leaves all passed
    /// the binding, and the reason is worth writing down because it is not
    /// obvious: RFC 9420 requires signature keys to be unique across a group
    /// (OpenMLS enforces it — "Duplicate signature key in proposals and
    /// group"), and since `verify_leaf_binding` ties a credential to the hash
    /// of its own signature key, two leaves with the same credential would have
    /// to carry the same key. So through the wire gates the duplicate case is
    /// refused one layer down, twice over.
    ///
    /// That argument covers the gates, not the tree. It says nothing about the
    /// case `verify_sender_leaf` and the `get_group_info` filter exist for — a
    /// leaf written straight into the install-scoped provider store. A forged
    /// leaf claiming a peer's address carries the *attacker's* signature key,
    /// so it violates no uniqueness rule and sits alongside that peer's real
    /// leaf quite happily. There the loop is doing real work: first-match would
    /// remove one of the two and leave the other in the group holding live
    /// keys, while every roster read shows the member gone — an
    /// access-revocation failure that would surface as nothing at all.
    ///
    /// Removing every match costs one `Vec` and cannot have that failure
    /// mode.
    pub fn remove_group_member(
        &self,
        group_id: &GroupId,
        member_id: &str,
    ) -> Result<EncryptedMessage> {
        let mut group = self
            .group_manager
            .load_group(group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(group_id.to_string()))?;

        let member_indices: Vec<LeafNodeIndex> = group
            .members()
            .filter(|m| m.credential.serialized_content() == member_id.as_bytes())
            .map(|m| m.index)
            .collect();

        if member_indices.is_empty() {
            return Err(MlsError::UserNotInGroup(member_id.to_string()));
        }

        let signature_keys = self.get_signer()?;
        let commit =
            self.group_manager
                .remove_member(&mut group, &member_indices, &signature_keys)?;

        self.group_manager.save_group(group_id, &group)?;

        let ciphertext = commit
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        Ok(EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Commit,
            epoch: group.epoch().as_u64(),
            ciphertext,
            sender_id: self.user_id.clone(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        })
    }

    /// Leaves a group.
    pub fn leave_group(&self, group_id: &GroupId) -> Result<()> {
        self.group_manager.delete_group(group_id)?;
        info!(group_id = %group_id, "Left group");
        Ok(())
    }

    /// Encrypts a message for a group.
    pub fn encrypt_for_group(
        &self,
        group_id: &GroupId,
        plaintext: &[u8],
    ) -> Result<EncryptedMessage> {
        let mut group = self
            .group_manager
            .load_group(group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(group_id.to_string()))?;

        let signature_keys = self.get_signer()?;
        let mls_message =
            self.group_manager
                .encrypt_message(&mut group, plaintext, &signature_keys)?;

        self.group_manager.save_group(group_id, &group)?;

        let ciphertext = mls_message
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        Ok(EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Application,
            epoch: group.epoch().as_u64(),
            ciphertext,
            sender_id: self.user_id.clone(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        })
    }

    /// Decrypts a message from a group.
    ///
    /// `claimed_sender` is the transport-level sender this message will be
    /// attributed to; decryption fails with
    /// [`MlsError::SenderIdentityMismatch`] if it does not match the
    /// MLS-authenticated credential (SEC-M1). The check runs before any
    /// commit is merged, so a spoofed commit cannot advance group state.
    pub fn decrypt_from_group(
        &self,
        encrypted: &EncryptedMessage,
        claimed_sender: &str,
    ) -> Result<Option<Vec<u8>>> {
        let mut group = self
            .group_manager
            .load_group(&encrypted.group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(encrypted.group_id.to_string()))?;

        let mls_message = MlsMessageIn::tls_deserialize_exact(&encrypted.ciphertext)
            .map_err(|e| MlsError::Deserialization(e.to_string()))?;

        let result = self.group_manager.decrypt_message(
            &mut group,
            &encrypted.group_id,
            mls_message,
            claimed_sender,
        )?;

        self.group_manager.save_group(&encrypted.group_id, &group)?;

        Ok(result)
    }

    /// Joins a group using a Welcome message.
    pub fn join_group(&self, welcome: &WelcomeMessage) -> Result<GroupInfo> {
        // SEC-M6 (group-Welcome side): the `session:` namespace is owned
        // exclusively by identity-bound 1:1 sessions installed via
        // `join_session`. A group Welcome carries an attacker-controllable
        // `group_id` with no (self, inviter) binding and writes the same
        // storage/OpenMLS keyspace, so one naming a `session:*` slot would seed
        // or overwrite a third party's 1:1 session and hijack the victim's
        // outbound encryption — the exact hijack SEC-M6 blocks on the
        // session-Welcome path. Reject before staging. Enforced here (rather
        // than only in the mesh handler) so *every* caller of `join_group` is
        // covered. Legitimate mesh groups are always `group:<uuid>`
        // (see `create_group`), so this rejects only forged Welcomes.
        if welcome.group_id.as_str().starts_with("session:") {
            return Err(MlsError::ReservedSessionNamespace {
                group_id: welcome.group_id.to_string(),
            });
        }

        let mls_msg = MlsMessageIn::tls_deserialize_exact(&welcome.welcome_data)
            .map_err(|e| MlsError::Deserialization(e.to_string()))?;

        let welcome_msg = match mls_msg.extract() {
            MlsMessageBodyIn::Welcome(w) => w,
            _ => {
                return Err(MlsError::WelcomeProcessing(
                    "Not a Welcome message".to_string(),
                ))
            }
        };

        let group = self
            .group_manager
            .join_group(welcome_msg, &welcome.group_id)?;
        let mut info = self.group_manager.get_group_info(&group, &welcome.group_id);
        info.name = welcome.group_name.clone();

        info!(group_id = %welcome.group_id, "Joined group");
        Ok(info)
    }

    /// Lists all groups.
    pub fn list_groups(&self) -> Result<Vec<GroupId>> {
        let all_groups = self.group_manager.list_groups()?;
        Ok(all_groups
            .into_iter()
            .filter(|g| !g.as_str().starts_with("session:"))
            .collect())
    }

    /// Gets information about a group.
    pub fn get_group_info(&self, group_id: &GroupId) -> Result<Option<GroupInfo>> {
        let group = match self.group_manager.load_group(group_id)? {
            Some(g) => g,
            None => return Ok(None),
        };

        let mut info = self.group_manager.get_group_info(&group, group_id);

        // Merge stored metadata
        if let Some(metadata) = self.load_group_metadata(group_id)? {
            info.name = metadata.name;
            info.created_at_ms = metadata.created_at_ms;
            info.last_activity_ms = metadata.last_activity_ms;
        }

        Ok(Some(info))
    }

    /// Returns `true` if local MLS group state exists for `group_id`.
    ///
    /// This is the authoritative test for "do we actually participate in this
    /// group via MLS" — it gates on the stored group marker, not the member
    /// send-cache (which relay reconciliation can populate without any MLS
    /// state). Callers use it to distinguish a genuine legacy relay-only
    /// (unencrypted) group, which has no MLS state, from an unauthenticated
    /// plaintext frame spoofed against a group the node secures with MLS.
    pub fn has_group(&self, group_id: &GroupId) -> Result<bool> {
        Ok(self.group_manager.load_group(group_id)?.is_some())
    }

    /// Updates the group name.
    pub fn set_group_name(&self, group_id: &GroupId, name: &str) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        metadata.name = Some(name.to_string());
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    /// Gets group metadata.
    pub fn get_group_metadata(&self, group_id: &GroupId) -> Result<Option<GroupMetadata>> {
        self.load_group_metadata(group_id)
    }

    /// Sets custom metadata for a group.
    pub fn set_group_custom_metadata(
        &self,
        group_id: &GroupId,
        key: &str,
        value: &str,
    ) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        metadata.custom.insert(key.to_string(), value.to_string());
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    /// Removes a custom metadata key for a group.
    pub fn remove_group_custom_metadata(&self, group_id: &GroupId, key: &str) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        metadata.custom.remove(key);
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    /// Sets a member's role in a group.
    pub fn set_member_role(
        &self,
        group_id: &GroupId,
        user_id: &str,
        role: GroupRole,
    ) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        metadata.set_role(user_id, role);
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    /// Enables or disables receive-side authorization of group membership
    /// commits. See [`crate::group::GroupManager::set_enforce_admin_commits`]
    /// for the fork consequence — this is off by default and enabling it is a
    /// deployment decision, not a hardening toggle.
    ///
    /// Applies to group commits only. The session manager owns a separate
    /// group manager and is left untouched, so 1:1 sessions are unaffected
    /// regardless of this setting.
    pub fn set_enforce_admin_commits(&mut self, enforce: bool) {
        self.group_manager.set_enforce_admin_commits(enforce);
    }

    /// Records the group's creator, **only if none is on record yet**.
    ///
    /// `created_by` is the fallback [`GroupMetadata`] consults when no admin
    /// role is stored (see the protocol layer's `check_is_admin`), so it must
    /// behave monotonically: a device that created the group, or already
    /// adopted a creator from the Welcome that admitted it, keeps what it has.
    /// Only the "no information" state is fillable. That makes the write
    /// idempotent under duplicate Welcomes and stops a later invite — from an
    /// inviter whose own metadata disagrees — from rewriting an established
    /// admin fallback.
    ///
    /// Returns `Ok(())` whether or not the value was adopted; use
    /// [`Self::get_group_metadata`] to observe the result.
    pub fn set_group_creator(&self, group_id: &GroupId, creator_id: &str) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        if metadata.created_by.is_some() {
            return Ok(());
        }
        metadata.created_by = Some(creator_id.to_string());
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    /// Removes a member's role metadata from a group.
    pub fn remove_member_role(&self, group_id: &GroupId, user_id: &str) -> Result<()> {
        let mut metadata = self
            .load_group_metadata(group_id)?
            .unwrap_or_else(|| GroupMetadata::new(None));
        metadata.remove_role(user_id);
        metadata.touch();
        self.save_group_metadata(group_id, &metadata)
    }

    // ========================================================================
    // GENERIC MESSAGE HANDLING
    // ========================================================================

    /// Decrypts any incoming encrypted message.
    ///
    /// `claimed_sender` is the transport-level sender this message will be
    /// attributed to; it must match the MLS-authenticated credential
    /// (SEC-M1).
    pub fn decrypt(
        &self,
        encrypted: &EncryptedMessage,
        claimed_sender: &str,
    ) -> Result<Option<Vec<u8>>> {
        if encrypted.group_id.as_str().starts_with("session:") {
            self.decrypt_from_user(encrypted, claimed_sender)
        } else {
            self.decrypt_from_group(encrypted, claimed_sender)
        }
    }

    /// Processes a Welcome message.
    pub fn process_welcome(&self, welcome: &WelcomeMessage) -> Result<GroupInfo> {
        if welcome.group_id.as_str().starts_with("session:") {
            self.join_session(welcome)
        } else {
            self.join_group(welcome)
        }
    }
}

impl MlsManager {
    /// Loads a stored key package bundle, handling legacy raw storage and expiration.
    ///
    /// Also validates that the key package's private key still exists in the
    /// OpenMLS provider storage. Key packages whose private keys have been
    /// consumed (e.g. by a previous Welcome processing) are pruned.
    fn load_stored_key_package(&self, package_id: &str) -> Result<Option<KeyPackageBundle>> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let data = match self.storage.load(key_type, package_id)? {
            Some(data) => data,
            None => return Ok(None),
        };

        let mut bundle = match serde_json::from_slice::<KeyPackageBundle>(&data) {
            Ok(bundle) => bundle,
            Err(_) => {
                let legacy_bundle = KeyPackageBundle::new(
                    package_id.to_string(),
                    self.user_id.clone(),
                    data,
                    DEFAULT_KEY_PACKAGE_LIFETIME_SECS,
                );
                let serialized = serde_json::to_vec(&legacy_bundle)
                    .map_err(|e| MlsError::Serialization(e.to_string()))?;
                self.storage.store(key_type, package_id, &serialized)?;
                legacy_bundle
            }
        };

        if bundle.is_expired() {
            // Expiry and key destruction are separate moments on purpose. A
            // peer handed this package shortly before it expired may still
            // Welcome us, and that Welcome is only processable while the init
            // key is resident — so the record is kept (invisible to every
            // caller, since they all read through here) until the grace window
            // closes, and only then is the material destroyed.
            if bundle.expired_past_grace(KEY_PACKAGE_PURGE_GRACE_SECS) {
                self.purge_key_package_material(package_id, &bundle)?;
            }
            return Ok(None);
        }

        // Usability means the private init key is still in provider storage.
        // The lookup key is cached on the record; deriving it instead is the
        // expensive path (a parse plus a signature validation), paid once for
        // records written before the cache existed and stamped back below so
        // their next load is cheap.
        let needs_backfill = bundle.provider_hash_ref.is_none();
        let Some(hash_ref) = self.bundle_hash_ref(&bundle) else {
            warn!(
                package_id = %package_id,
                "Key package bytes no longer parse as a key package, pruning stale entry"
            );
            self.storage.delete(key_type, package_id)?;
            return Ok(None);
        };
        if !self.provider_has_init_key(&hash_ref) {
            warn!(
                package_id = %package_id,
                "Key package private key no longer in provider storage, pruning stale entry"
            );
            self.storage.delete(key_type, package_id)?;
            return Ok(None);
        }

        if needs_backfill {
            if let Ok(bytes) = hash_ref.tls_serialize_detached() {
                bundle.provider_hash_ref = Some(bytes);
                let serialized = serde_json::to_vec(&bundle)
                    .map_err(|e| MlsError::Serialization(e.to_string()))?;
                self.storage.store(key_type, package_id, &serialized)?;
            }
        }

        Ok(Some(bundle))
    }

    /// Destroys a key package: its bundle record *and* the private init key
    /// OpenMLS holds for it.
    ///
    /// Deleting the record alone — which is all this crate used to do — leaves
    /// the init key resident forever, because the only other thing that removes
    /// one is OpenMLS consuming it to process a Welcome. That turns every
    /// expired or reclaimed package into permanently retained key material,
    /// which is exactly the property the lifetime was supposed to bound.
    ///
    /// The provider key goes first: if that fails, the record is deliberately
    /// left in place so the next scan retries rather than orphaning key
    /// material no record points at any more. The package is already out of
    /// every caller's reach by the time this runs, so a retained record costs
    /// one storage read per scan and nothing else.
    fn purge_key_package_material(
        &self,
        package_id: &str,
        bundle: &KeyPackageBundle,
    ) -> Result<()> {
        if let Some(hash_ref) = self.bundle_hash_ref(bundle) {
            use openmls_traits::storage::StorageProvider;
            if let Err(e) = self.provider.storage().delete_key_package(&hash_ref) {
                warn!(
                    package_id = %package_id,
                    error = %e,
                    "Failed to delete a key package's private init key; keeping the record to retry"
                );
                return Ok(());
            }
        }

        self.storage
            .delete(StorageKeyType::KeyPackage.as_str(), package_id)?;
        debug!(package_id = %package_id, "Purged key package and its init key");
        Ok(())
    }

    /// Computes the OpenMLS hash reference a key package's private material is
    /// stored under, or `None` if the bytes no longer parse as a key package.
    ///
    /// This is the expensive path — a TLS parse plus a signature validation —
    /// that [`KeyPackageBundle::provider_hash_ref`] caches the result of; go
    /// through [`Self::bundle_hash_ref`] when a bundle is in hand.
    fn key_package_hash_ref(&self, key_package_data: &[u8]) -> Option<KeyPackageRef> {
        let kp_in = KeyPackageIn::tls_deserialize_exact(key_package_data).ok()?;
        let kp: KeyPackage = kp_in
            .validate(self.provider.crypto(), ProtocolVersion::Mls10)
            .ok()?;
        kp.hash_ref(self.provider.crypto()).ok()
    }

    /// Resolves the provider hash reference for one of this device's bundles:
    /// the copy cached at mint time when present and decodable, else derived
    /// from the serialized package bytes.
    fn bundle_hash_ref(&self, bundle: &KeyPackageBundle) -> Option<KeyPackageRef> {
        bundle
            .provider_hash_ref
            .as_deref()
            .and_then(|bytes| KeyPackageRef::tls_deserialize_exact(bytes).ok())
            .or_else(|| self.key_package_hash_ref(&bundle.key_package_data))
    }

    /// Whether the private init key `hash_ref` names is still in the OpenMLS
    /// provider storage. Absent means consumed (a Welcome was processed
    /// against it) or never stored.
    fn provider_has_init_key(&self, hash_ref: &KeyPackageRef) -> bool {
        use openmls_traits::storage::StorageProvider;
        let found: std::result::Result<Option<openmls::key_packages::KeyPackageBundle>, _> =
            self.provider.storage().key_package(hash_ref);
        matches!(found, Ok(Some(_)))
    }

    /// Ground-truth usability check from the serialized package bytes alone,
    /// bypassing the cached provider ref. Test-only so tests observe the
    /// provider directly rather than a cache they may be manipulating;
    /// production reads go through [`Self::bundle_hash_ref`].
    #[cfg(test)]
    fn is_key_package_usable(&self, key_package_data: &[u8]) -> bool {
        self.key_package_hash_ref(key_package_data)
            .map(|hash_ref| self.provider_has_init_key(&hash_ref))
            .unwrap_or(false)
    }

    /// Loads group metadata from storage.
    fn load_group_metadata(&self, group_id: &GroupId) -> Result<Option<GroupMetadata>> {
        let key_type = StorageKeyType::GroupMetadata.as_str();
        match self.storage.load(key_type, group_id.as_str())? {
            Some(data) => {
                let mut metadata: GroupMetadata = serde_json::from_slice(&data)
                    .map_err(|e| MlsError::Deserialization(e.to_string()))?;
                // Migrate legacy "role:*" keys from `custom` into `roles`
                if metadata.roles.is_empty()
                    && metadata
                        .custom
                        .keys()
                        .any(|k| k.starts_with(GroupMetadata::LEGACY_ROLE_KEY_PREFIX))
                {
                    metadata.migrate_legacy_roles();
                    // Persist the migration so it only runs once
                    if let Err(e) = self.save_group_metadata(group_id, &metadata) {
                        warn!(group_id = %group_id.as_str(), error = %e, "Failed to persist legacy role migration");
                    }
                }
                Ok(Some(metadata))
            }
            None => Ok(None),
        }
    }

    /// Saves group metadata to storage.
    fn save_group_metadata(&self, group_id: &GroupId, metadata: &GroupMetadata) -> Result<()> {
        let key_type = StorageKeyType::GroupMetadata.as_str();
        let data =
            serde_json::to_vec(metadata).map_err(|e| MlsError::Serialization(e.to_string()))?;
        self.storage.store(key_type, group_id.as_str(), &data)?;
        Ok(())
    }
}

// ============================================================================
// KEY ROTATION AND KEY PACKAGE MANAGEMENT
// ============================================================================

impl MlsManager {
    /// Updates the cryptographic keys for a group (triggers MLS self-update).
    ///
    /// This provides post-compromise security by rotating keys. The returned
    /// commit message must be sent to all other group members.
    ///
    /// # Returns
    ///
    /// Returns the commit message that must be distributed to all group members.
    pub fn update_keys(&self, group_id: &GroupId) -> Result<EncryptedMessage> {
        use openmls::treesync::LeafNodeParameters;

        let mut group = self
            .group_manager
            .load_group(group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(group_id.to_string()))?;

        let signature_keys = self.get_signer()?;

        let bundle = group
            .self_update(
                &self.provider,
                &signature_keys,
                LeafNodeParameters::default(),
            )
            .map_err(|e| MlsError::OpenMls(format!("Self-update failed: {}", e)))?;

        let (commit, _welcome, _group_info) = bundle.into_contents();

        group
            .merge_pending_commit(&self.provider)
            .map_err(|e| MlsError::OpenMls(format!("Failed to merge self-update commit: {}", e)))?;

        self.group_manager.save_group(group_id, &group)?;

        // Update metadata last activity
        if let Some(mut metadata) = self.load_group_metadata(group_id)? {
            metadata.touch();
            self.save_group_metadata(group_id, &metadata)?;
        }

        let ciphertext = commit
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        debug!(group_id = %group_id, epoch = %group.epoch().as_u64(), "Updated group keys");

        Ok(EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Commit,
            epoch: group.epoch().as_u64(),
            ciphertext,
            sender_id: self.user_id.clone(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        })
    }

    /// Ensures at least `min` valid key packages are available.
    ///
    /// Generates new key packages if the current count is below the minimum.
    /// This is useful for offline scenarios where multiple key packages should
    /// be pre-generated for distribution.
    ///
    /// # Arguments
    ///
    /// * `min` - Minimum number of key packages to maintain, capped at
    ///   [`MAX_PUSH_KEY_PACKAGES`]. The packages this mints are unclaimed, so
    ///   [`Self::take_push_key_package`] draws them down one per peer; asking
    ///   for more than the pool ceiling would only mint key material that
    ///   ceiling stops it ever handing out, while holding the pool at capacity
    ///   so every peer past the last claim is advertised a shared package.
    ///
    /// # Returns
    ///
    /// Returns the total number of valid key packages after ensuring minimum.
    pub fn ensure_min_key_packages(&self, min: usize) -> Result<usize> {
        let min = min.min(MAX_PUSH_KEY_PACKAGES);
        let key_type = StorageKeyType::KeyPackage.as_str();
        let package_ids = self.storage.list_keys(key_type)?;

        // Count valid (non-expired) packages
        let mut valid_count = 0;
        for package_id in &package_ids {
            if self.load_stored_key_package(package_id)?.is_some() {
                valid_count += 1;
            }
        }

        // Generate more if needed
        let to_generate = min.saturating_sub(valid_count);
        for _ in 0..to_generate {
            self.generate_key_package()?;
            valid_count += 1;
        }

        debug!(
            valid_count = valid_count,
            generated = to_generate,
            "Ensured minimum key packages"
        );

        Ok(valid_count)
    }

    /// Returns the number of valid (non-expired) key packages available.
    pub fn count_valid_key_packages(&self) -> Result<usize> {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let package_ids = self.storage.list_keys(key_type)?;

        let mut count = 0;
        for package_id in package_ids {
            if self.load_stored_key_package(&package_id)?.is_some() {
                count += 1;
            }
        }

        Ok(count)
    }

    // ========================================================================
    // IDENTITY AND SIGNING OPERATIONS
    // ========================================================================

    /// Returns the identity public key as raw bytes.
    ///
    /// This is the Ed25519 public key used for MLS operations. It can be shared
    /// with others to establish your identity and verify signatures.
    pub fn get_identity_public_key(&self) -> Result<Vec<u8>> {
        let credential = self.get_credential()?;
        Ok(credential.signature_key.as_slice().to_vec())
    }

    /// Signs arbitrary data with the identity private key.
    ///
    /// Uses Ed25519 signatures (the same algorithm used for MLS operations).
    /// The signature can be verified by anyone with the corresponding public key.
    ///
    /// # Arguments
    ///
    /// * `data` - The data to sign
    ///
    /// # Returns
    ///
    /// Returns the signature as raw bytes.
    pub fn sign_data(&self, data: &[u8]) -> Result<Vec<u8>> {
        use openmls_traits::signatures::Signer;

        let signer = self.get_signer()?;
        let signature = signer
            .sign(data)
            .map_err(|e| MlsError::Signing(format!("Failed to sign data: {:?}", e)))?;
        Ok(signature.as_slice().to_vec())
    }

    /// Verifies a signature against a public key.
    ///
    /// # Arguments
    ///
    /// * `public_key` - The Ed25519 public key bytes (32 bytes)
    /// * `data` - The original data that was signed
    /// * `signature` - The signature to verify (64 bytes)
    ///
    /// # Returns
    ///
    /// Returns `true` if the signature is valid, `false` otherwise.
    pub fn verify_signature(public_key: &[u8], data: &[u8], signature: &[u8]) -> Result<bool> {
        use ed25519_dalek::{Signature, Verifier, VerifyingKey};

        // Parse the public key (Ed25519 public keys are 32 bytes)
        let verifying_key = VerifyingKey::try_from(public_key).map_err(|e| {
            MlsError::InvalidPublicKey(format!("Invalid Ed25519 public key: {}", e))
        })?;

        // Parse the signature (Ed25519 signatures are 64 bytes)
        let sig = Signature::try_from(signature).map_err(|e| {
            MlsError::VerificationFailed(format!("Invalid signature format: {}", e))
        })?;

        // Verify the signature
        match verifying_key.verify(data, &sig) {
            Ok(()) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Derives the canonical self-certifying address of an Ed25519 identity
    /// key: `off1…`, the bech32m encoding of
    /// `0x01 ‖ SHA-256(public_key)[..20]`.
    ///
    /// This is the only address derivation in the SDK. Bridges and apps reach
    /// it through the `derive_address` FFI function rather than reimplementing
    /// it, so that every platform agrees byte for byte.
    ///
    /// # Arguments
    ///
    /// * `public_key` - The Ed25519 public key bytes (exactly 32)
    ///
    /// # Errors
    ///
    /// Returns [`MlsError::InvalidPublicKey`] if `public_key` is not 32 bytes.
    /// The length is part of the format contract: hashing a differently-sized
    /// input would yield a different address for the same identity. The bytes
    /// are deliberately *not* checked against the curve — an address is
    /// defined over key bytes, and what proves ownership is the signature
    /// verification that accompanies it (see [`Self::verify_signature`]), so
    /// binding the address format to a signature library's parsing strictness
    /// would only risk the derivation drifting between versions.
    pub fn derive_address(public_key: &[u8]) -> Result<Address> {
        use sha2::{Digest, Sha256};

        if public_key.len() != ED25519_PUBLIC_KEY_LEN {
            return Err(MlsError::InvalidPublicKey(format!(
                "Ed25519 public key must be {} bytes, got {}",
                ED25519_PUBLIC_KEY_LEN,
                public_key.len()
            )));
        }

        let hash = Sha256::digest(public_key);
        let mut truncated = [0u8; Address::HASH_LEN];
        truncated.copy_from_slice(&hash[..Address::HASH_LEN]);
        Ok(Address::from_hash_bytes(truncated))
    }

    /// Derives a deterministic user ID from a public key.
    ///
    /// # Arguments
    ///
    /// * `public_key` - The Ed25519 public key bytes
    ///
    /// # Returns
    ///
    /// Returns the derived address in its canonical `off1…` string form.
    /// Unlike [`Self::derive_address`] this accepts any input length, which
    /// is precisely why it is deprecated: a caller passing a truncated or
    /// padded key gets a plausible-looking address for an identity that
    /// cannot exist.
    #[deprecated(
        note = "use derive_address; this returns the self-certifying off1… address, no longer base58"
    )]
    pub fn derive_user_id_from_public_key(public_key: &[u8]) -> String {
        use sha2::{Digest, Sha256};

        let hash = Sha256::digest(public_key);
        let mut truncated = [0u8; Address::HASH_LEN];
        truncated.copy_from_slice(&hash[..Address::HASH_LEN]);
        Address::from_hash_bytes(truncated).to_string()
    }
}

/// Adversarial fixtures for tests in other crates.
///
/// Forging a leaf needs raw OpenMLS, which the protocol crate deliberately does
/// not depend on, and needs to go *past* `add_group_member`'s binding check —
/// which is the whole point, since the attacker runs their own build and that
/// check is theirs to delete. Feature-gated so no release build in this
/// workspace enables it — a downstream consumer could still turn the feature on
/// for itself — and kept in this module because it touches private state.
#[cfg(feature = "test-utils")]
impl MlsManager {
    /// Seats a leaf in `group_id` whose credential claims `impersonated` but
    /// whose signature key is minted here — an identity nobody can prove.
    ///
    /// The group must already exist and this manager must be able to commit to
    /// it. Every later Welcome for that group carries the forged leaf in its
    /// ratchet tree, which is what a receiver must refuse.
    ///
    /// Returns the Add commit, TLS-serialized. That is the *other* half of the
    /// attack and needs to be reachable from the protocol crate: a receiver
    /// already in the group is attacked by the commit, not by a Welcome, and
    /// what it must do with one differs — refuse it **permanently**, since a
    /// refusal parked on the retry path is re-decrypted until it expires and is
    /// then misread as an epoch fork.
    pub fn seat_forged_leaf_for_testing(
        &self,
        group_id: &GroupId,
        impersonated: &str,
    ) -> Result<Vec<u8>> {
        let forged_storage: Arc<dyn MlsStorage> = Arc::new(crate::storage::InMemoryStorage::new());
        let forged_provider = MlsProvider::new(MlsStorageAdapter::new(forged_storage));
        let forged_keys = SignatureKeyPair::new(DEFAULT_CIPHERSUITE.signature_algorithm())
            .map_err(|e| MlsError::CryptoGeneration(format!("{:?}", e)))?;
        forged_keys
            .store(forged_provider.storage())
            .map_err(|e| MlsError::CryptoGeneration(format!("storing forged key: {:?}", e)))?;

        let credential = CredentialWithKey {
            credential: Credential::new(CredentialType::Basic, impersonated.as_bytes().to_vec()),
            signature_key: forged_keys.public().into(),
        };
        let key_package = KeyPackage::builder()
            .build(
                DEFAULT_CIPHERSUITE,
                &forged_provider,
                &forged_keys,
                credential,
            )
            .map_err(|e| MlsError::KeyPackageCreation(e.to_string()))?
            .key_package()
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))?;

        let validated = KeyPackageIn::tls_deserialize_exact(&key_package)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?
            .validate(self.provider.crypto(), ProtocolVersion::Mls10)
            .map_err(|e| MlsError::InvalidKeyPackage(e.to_string()))?;

        let mut group = self
            .group_manager
            .load_group(group_id)?
            .ok_or_else(|| MlsError::GroupNotFound(group_id.to_string()))?;
        let signer = self.get_signer()?;
        let (commit, _welcome) = self
            .group_manager
            .add_member(&mut group, validated, &signer)?;
        self.group_manager.save_group(group_id, &group)?;

        commit
            .tls_serialize_detached()
            .map_err(|e| MlsError::Serialization(e.to_string()))
    }
}

/// Returns `true` when `bytes` parse as a well-formed MLS wire message
/// (`MlsMessageIn` TLS framing, consuming the input exactly).
///
/// Inbound routing uses this to distinguish MLS ciphertext from legacy
/// plaintext that merely happens to be valid base64: the strict TLS framing
/// (protocol version, wire format, exact-length body) makes an accidental
/// match against non-MLS bytes vanishingly unlikely. This is a framing
/// check only — it says nothing about whether the message can be decrypted.
pub fn is_mls_framed(bytes: &[u8]) -> bool {
    MlsMessageIn::tls_deserialize_exact(bytes).is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::InMemoryStorage;

    /// A manager running as `label`, at the address `label`'s identity key
    /// derives to.
    ///
    /// Takes the production bootstrap, not a nickname: every peer id that
    /// crosses `import_key_package` or `add_group_member` is now checked
    /// against the key that signed the package, and a nickname has no
    /// derivation to check — so a fixture at `"bob"` would exercise a
    /// configuration that cannot exist.
    fn create_test_manager(label: &str) -> MlsManager {
        create_addressed_manager(label).0
    }

    /// The address the identity behind `label` derives to, as a wire string.
    fn addr(label: &str) -> String {
        test_identity(label).1.to_string()
    }

    /// The 1:1 session slot shared by `a` and `b`.
    ///
    /// Computed, never written out: the slot orders its halves by `Address`
    /// bytes, and the bech32 charset is not ASCII-monotonic, so a hand-written
    /// `session:<a>:<b>` literal is right only by accident.
    fn slot(a: &str, b: &str) -> GroupId {
        GroupId::for_session(&addr(a), &addr(b)).unwrap()
    }

    /// A deterministic identity keypair for `label`, plus the address it
    /// derives to.
    ///
    /// Seeded from the label rather than generated so a test can name the same
    /// identity twice, and so the address in a failure message is stable across
    /// runs. Only the *derivation* is being pinned here — the seed is a test
    /// convenience, not a key-generation scheme anything ships.
    pub(crate) fn test_identity(label: &str) -> (SignatureKeyPair, Address) {
        use sha2::{Digest, Sha256};

        let seed: [u8; 32] = Sha256::digest(label.as_bytes()).into();
        let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
        let public = signing.verifying_key().to_bytes().to_vec();
        let address = MlsManager::derive_address(&public).unwrap();
        let keys = SignatureKeyPair::from_raw(
            DEFAULT_CIPHERSUITE.signature_algorithm(),
            signing.to_bytes().to_vec(),
            public,
        );
        (keys, address)
    }

    /// Writes `keys` where [`MlsManager::load_or_create_identity`] will find
    /// them, standing in for a previous run of this profile.
    pub(crate) fn seed_identity(storage: &Arc<dyn MlsStorage>, keys: &SignatureKeyPair) {
        storage
            .store(
                StorageKeyType::Identity.as_str(),
                "key_pair",
                &serde_json::to_vec(keys).unwrap(),
            )
            .unwrap();
    }

    /// A manager bootstrapped the way production does it: mint/load the
    /// identity first, then construct at the address it derives to.
    fn create_addressed_manager(label: &str) -> (MlsManager, Address) {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (keys, address) = test_identity(label);
        seed_identity(&storage, &keys);
        let manager = MlsManager::new(address.to_string(), storage).unwrap();
        (manager, address)
    }

    /// Same, but keeps a handle on the storage so a test can age a package in
    /// place — the only way to reach the expiry and purge paths without either
    /// waiting 30 days or making the clock injectable.
    fn create_test_manager_with_storage(user_id: &str) -> (MlsManager, Arc<InMemoryStorage>) {
        let storage = Arc::new(InMemoryStorage::new());
        let manager = MlsManager::new(user_id, storage.clone()).unwrap();
        (manager, storage)
    }

    /// Rewrites a stored package's expiry to `secs_ago` seconds in the past.
    fn expire_package(storage: &InMemoryStorage, package_id: &str, secs_ago: u64) {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let data = storage
            .load(key_type, package_id)
            .unwrap()
            .expect("package to age is not in storage");
        let mut bundle: KeyPackageBundle = serde_json::from_slice(&data).unwrap();
        let now_ms = chrono::Utc::now().timestamp_millis() as u64;
        bundle.expires_at_ms = now_ms - (secs_ago * 1000);
        storage
            .store(key_type, package_id, &serde_json::to_vec(&bundle).unwrap())
            .unwrap();
    }

    /// Whether the private init key for `bundle` is still in provider storage.
    fn init_key_present(manager: &MlsManager, bundle: &KeyPackageBundle) -> bool {
        manager.is_key_package_usable(&bundle.key_package_data)
    }

    /// Rewrites a stored package's record without its cached provider hash
    /// ref, the way a build predating the cache would have written it.
    fn strip_cached_ref(storage: &InMemoryStorage, package_id: &str) {
        let key_type = StorageKeyType::KeyPackage.as_str();
        let data = storage
            .load(key_type, package_id)
            .unwrap()
            .expect("package to strip is not in storage");
        let mut bundle: KeyPackageBundle = serde_json::from_slice(&data).unwrap();
        bundle.provider_hash_ref = None;
        storage
            .store(key_type, package_id, &serde_json::to_vec(&bundle).unwrap())
            .unwrap();
    }

    /// The provider hash ref is stamped at mint so the pool scan never pays a
    /// TLS parse plus a signature validation per stored package per push —
    /// unstamped, a scan-heavy path (many peers, full pool) costs tens of
    /// debug-build seconds.
    #[test]
    fn test_minted_package_carries_its_provider_hash_ref() {
        let manager = create_test_manager("alice");
        let bundle = manager.take_push_key_package(&addr("bob")).unwrap().bundle;

        let cached = bundle
            .provider_hash_ref
            .as_deref()
            .expect("mint must stamp the provider hash ref");
        let derived = manager
            .key_package_hash_ref(&bundle.key_package_data)
            .expect("freshly minted package bytes must parse")
            .tls_serialize_detached()
            .unwrap();
        assert_eq!(
            cached,
            &derived[..],
            "cached ref disagrees with the one derived from the package bytes"
        );
    }

    /// Records written before the cache existed take the derive path once and
    /// are stamped back, so every later load is cheap.
    #[test]
    fn test_record_without_cached_ref_is_backfilled_on_first_load() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        let minted = manager.take_push_key_package(&addr("bob")).unwrap().bundle;
        strip_cached_ref(&storage, &minted.package_id);

        let loaded = manager
            .key_package_by_id(&minted.package_id)
            .unwrap()
            .expect("a record without a cached ref must still load");
        assert_eq!(
            loaded.provider_hash_ref, minted.provider_hash_ref,
            "load must hand back a bundle stamped with the same ref the mint computed"
        );

        let stored: KeyPackageBundle = serde_json::from_slice(
            &storage
                .load(StorageKeyType::KeyPackage.as_str(), &minted.package_id)
                .unwrap()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            stored.provider_hash_ref, minted.provider_hash_ref,
            "the backfilled ref must be persisted, not only returned"
        );
    }

    /// The purge destroys key material for pre-cache records too, deriving
    /// the ref they never carried.
    #[test]
    fn test_purge_destroys_init_key_for_a_record_without_cached_ref() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        let bundle = manager.take_push_key_package(&addr("bob")).unwrap().bundle;
        strip_cached_ref(&storage, &bundle.package_id);
        expire_package(
            &storage,
            &bundle.package_id,
            KEY_PACKAGE_PURGE_GRACE_SECS + 60,
        );

        assert!(manager
            .key_package_by_id(&bundle.package_id)
            .unwrap()
            .is_none());
        assert!(
            !init_key_present(&manager, &bundle),
            "the private init key outlived a pre-cache package"
        );
    }

    /// An expired package stops being advertised immediately, but its init key
    /// has to outlive the last advertisement: a peer handed it just before
    /// expiry may still Welcome us, and that Welcome is only processable while
    /// the key is resident.
    #[test]
    fn test_expired_package_is_withdrawn_but_its_init_key_survives_the_grace_window() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        let bundle = manager.take_push_key_package(&addr("bob")).unwrap().bundle;

        expire_package(&storage, &bundle.package_id, 60);

        assert!(
            manager
                .key_package_by_id(&bundle.package_id)
                .unwrap()
                .is_none(),
            "an expired package must not be handed out"
        );
        assert!(
            init_key_present(&manager, &bundle),
            "the init key was destroyed on the expiry edge, breaking a late Welcome"
        );

        // The next push to that peer mints a replacement rather than reviving it.
        let replacement = manager.take_push_key_package(&addr("bob")).unwrap().bundle;
        assert_ne!(replacement.package_id, bundle.package_id);
    }

    /// Past the grace window the key material is genuinely destroyed. Without
    /// this, every package this device ever minted keeps its init key for the
    /// life of the install — deleting the bundle record, which is all this
    /// crate used to do, never touched the key OpenMLS holds.
    #[test]
    fn test_package_past_the_grace_window_has_its_init_key_destroyed() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        let bundle = manager.take_push_key_package(&addr("bob")).unwrap().bundle;
        assert!(init_key_present(&manager, &bundle));

        expire_package(
            &storage,
            &bundle.package_id,
            KEY_PACKAGE_PURGE_GRACE_SECS + 60,
        );

        // The purge runs as a side effect of the scan that reads it.
        assert!(manager
            .key_package_by_id(&bundle.package_id)
            .unwrap()
            .is_none());

        assert!(
            !init_key_present(&manager, &bundle),
            "the private init key outlived its package"
        );
        assert!(
            storage
                .load(StorageKeyType::KeyPackage.as_str(), &bundle.package_id)
                .unwrap()
                .is_none(),
            "the bundle record outlived its key material"
        );
    }

    /// Reclaiming an unpublished package has to reclaim the key too, for the
    /// same reason — the publication path mints one per failed refresh, and a
    /// record-only delete would strand fresh key material every time.
    #[test]
    fn test_delete_key_package_destroys_the_init_key() {
        let manager = create_test_manager("alice");
        let bundle = manager.generate_publication_key_package().unwrap();
        assert!(init_key_present(&manager, &bundle));

        manager.delete_key_package(&bundle.package_id).unwrap();

        assert!(
            !init_key_present(&manager, &bundle),
            "delete_key_package left the private init key in provider storage"
        );
    }

    /// A legacy record — raw key package bytes rather than a serialized bundle,
    /// which `load_stored_key_package` still upgrades in place — must have its
    /// init key destroyed too. Reading the record as unparseable and deleting
    /// only the record is what strands key material.
    #[test]
    fn test_delete_key_package_destroys_the_init_key_of_a_legacy_record() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        let bundle = manager.generate_publication_key_package().unwrap();
        // Rewrite the record the way a build predating the bundle wrote it.
        storage
            .store(
                StorageKeyType::KeyPackage.as_str(),
                &bundle.package_id,
                &bundle.key_package_data,
            )
            .unwrap();

        manager.delete_key_package(&bundle.package_id).unwrap();

        assert!(
            !init_key_present(&manager, &bundle),
            "a legacy record's private init key survived its deletion"
        );
        assert!(
            storage
                .load(StorageKeyType::KeyPackage.as_str(), &bundle.package_id)
                .unwrap()
                .is_none(),
            "the legacy record outlived its key material"
        );
    }

    /// A record whose bytes name no key package at all still gets deleted —
    /// there is no material to destroy, and leaving it would make the pool scan
    /// carry it forever.
    #[test]
    fn test_delete_key_package_removes_an_unreadable_record() {
        let (manager, storage) = create_test_manager_with_storage("alice");
        storage
            .store(
                StorageKeyType::KeyPackage.as_str(),
                "junk",
                b"not a package",
            )
            .unwrap();

        manager.delete_key_package("junk").unwrap();

        assert!(storage
            .load(StorageKeyType::KeyPackage.as_str(), "junk")
            .unwrap()
            .is_none());
    }

    /// `ensure_min_key_packages` mints *unclaimed* packages, which the push
    /// path draws down one per peer. Minting past the pool ceiling would put
    /// material in storage that the ceiling then stops it ever handing out,
    /// while pinning the pool at capacity so every peer past the last claim is
    /// advertised a shared init key.
    #[test]
    fn test_ensure_min_key_packages_is_capped_at_the_pool_ceiling() {
        let manager = create_test_manager("alice");

        let count = manager
            .ensure_min_key_packages(MAX_PUSH_KEY_PACKAGES + 50)
            .unwrap();

        assert_eq!(count, MAX_PUSH_KEY_PACKAGES);
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            MAX_PUSH_KEY_PACKAGES,
            "pre-filling minted past the ceiling the push path enforces"
        );
    }

    #[test]
    fn test_manager_creation() {
        let manager = create_test_manager("alice");
        assert_eq!(manager.user_id(), addr("alice"));
    }

    #[test]
    fn test_key_package_generation() {
        let manager = create_test_manager("alice");
        let package = manager.generate_key_package().unwrap();

        assert_eq!(package.user_id, addr("alice"));
        assert!(!package.key_package_data.is_empty());
        assert!(!package.is_expired());
    }

    /// The push path must never hand out a package standing in a published
    /// slot. If it did, the pushed-to peer and a stranger who fetched the
    /// record would race for the same single-use init key, and the loser's
    /// Welcome is unprocessable.
    #[test]
    fn test_get_or_create_never_returns_a_publication_package() {
        let manager = create_test_manager("alice");
        let reserved = manager.generate_publication_key_package().unwrap();
        assert!(reserved.reserved_for_publication);

        let pushed = manager.get_or_create_key_package().unwrap();
        assert_ne!(
            pushed.package_id, reserved.package_id,
            "the push path took the package a published record is standing on"
        );
        assert!(!pushed.reserved_for_publication);

        // And it stays stable across calls — the reserved one is skipped every
        // time, not just minted around once.
        let pushed_again = manager.get_or_create_key_package().unwrap();
        assert_eq!(pushed.package_id, pushed_again.package_id);
    }

    /// `key_package_by_id` returning `None` is the consumption signal the
    /// publication slots run on, so it must distinguish a package this device
    /// still holds from one it does not.
    #[test]
    fn test_key_package_by_id_reports_presence() {
        let manager = create_test_manager("alice");
        let bundle = manager.generate_publication_key_package().unwrap();

        let found = manager.key_package_by_id(&bundle.package_id).unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().package_id, bundle.package_id);

        assert!(manager
            .key_package_by_id("no-such-package")
            .unwrap()
            .is_none());
    }

    /// Publication slots are independent: two slots must never end up holding
    /// the same package, or one Welcome consumes both.
    #[test]
    fn test_publication_packages_are_distinct_per_slot() {
        let manager = create_test_manager("alice");
        let a = manager.generate_publication_key_package().unwrap();
        let b = manager.generate_publication_key_package().unwrap();
        assert_ne!(a.package_id, b.package_id);
        assert_ne!(a.key_package_data, b.key_package_data);
    }

    #[test]
    fn test_get_or_create_key_package() {
        let manager = create_test_manager("alice");
        let pkg1 = manager.get_or_create_key_package().unwrap();
        let pkg2 = manager.get_or_create_key_package().unwrap();
        // Since we are now properly persisting keys, pkg2 should be the same as pkg1
        // IF the logic reuses existing key packages.
        // get_or_create_key_package logic iterates list_keys.
        assert_eq!(pkg1.package_id, pkg2.package_id);
    }

    // ========================================================================
    // PUSH-PATH KEY PACKAGE POOL
    // ========================================================================

    /// The property the whole per-peer pool exists for: two peers must never be
    /// advertised the same init key. Sharing one weakens forward secrecy at
    /// session establishment (a single compromised init key opens every Welcome
    /// built against it) and is the LastResort-style reuse RFC 9420 §16.8
    /// permits only as a denial-of-service fallback.
    #[test]
    fn test_push_path_gives_each_peer_its_own_key_package() {
        let manager = create_test_manager("alice");

        let for_bob = manager.take_push_key_package(&addr("bob")).unwrap();
        let for_carol = manager.take_push_key_package(&addr("carol")).unwrap();

        assert_ne!(
            for_bob.bundle.package_id, for_carol.bundle.package_id,
            "two peers were advertised the same key package"
        );
        assert_ne!(
            for_bob.bundle.key_package_data, for_carol.bundle.key_package_data,
            "two peers were advertised the same init key"
        );
        assert!(!for_bob.pool_exhausted && !for_carol.pool_exhausted);
        assert_eq!(
            for_bob.bundle.assigned_peer.as_deref(),
            Some(addr("bob").as_str())
        );
        assert_eq!(
            for_carol.bundle.assigned_peer.as_deref(),
            Some(addr("carol").as_str())
        );
    }

    /// The other half of the property: a repeat push to one peer must NOT mint
    /// fresh key material. Pushes to the same peer are routine (rediscovery,
    /// session establishment, group invites), and minting per push would grow
    /// the pool without bound and hit the ceiling within days.
    #[test]
    fn test_push_path_reuses_one_package_for_repeat_pushes_to_a_peer() {
        let manager = create_test_manager("alice");

        let first = manager.take_push_key_package(&addr("bob")).unwrap();
        let second = manager.take_push_key_package(&addr("bob")).unwrap();
        let third = manager.take_push_key_package(&addr("bob")).unwrap();

        assert_eq!(first.bundle.package_id, second.bundle.package_id);
        assert_eq!(first.bundle.package_id, third.bundle.package_id);
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            1,
            "repeat pushes to one peer minted extra key material"
        );
    }

    /// A peer's package is rotated by *consumption*, not by time: once a
    /// Welcome built against it has been processed the init key is gone, and
    /// the next push to that peer must mint a fresh one rather than re-handing
    /// a package nobody can use.
    #[test]
    fn test_push_path_mints_a_fresh_package_after_the_peer_consumed_one() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");

        let advertised = alice.take_push_key_package(&addr("bob")).unwrap().bundle;
        bob.import_key_package(&addr("alice"), &advertised.key_package_data)
            .unwrap();
        let welcome = bob.create_session(&addr("alice")).unwrap();
        alice.join_session(&welcome).unwrap();

        let next = alice.take_push_key_package(&addr("bob")).unwrap();
        assert_ne!(
            next.bundle.package_id, advertised.package_id,
            "a consumed package was advertised again"
        );
        assert!(!next.pool_exhausted);
    }

    /// The race the old shape created, end to end: one package handed to two
    /// peers means the second Welcome is built against an init key the first
    /// has already consumed, and it can never be processed. Nothing re-drives
    /// the exchange, so that peer is stuck.
    #[test]
    fn test_two_peers_can_both_establish_sessions_after_being_pushed_to() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let carol = create_test_manager("carol");

        for (peer, manager) in [(addr("bob"), &bob), (addr("carol"), &carol)] {
            let advertised = alice.take_push_key_package(&peer).unwrap().bundle;
            manager
                .import_key_package(&addr("alice"), &advertised.key_package_data)
                .unwrap();
        }

        // Both Welcomes are built before either is processed — the interleaving
        // that makes shared init keys fail.
        let from_bob = bob.create_session(&addr("alice")).unwrap();
        let from_carol = carol.create_session(&addr("alice")).unwrap();

        alice.join_session(&from_bob).unwrap();
        alice
            .join_session(&from_carol)
            .expect("second peer's Welcome must still be processable");

        assert!(alice.has_session(&addr("bob")).unwrap());
        assert!(alice.has_session(&addr("carol")).unwrap());
    }

    /// Publication slots stay off-limits to the push path for the same
    /// single-use reason, now via the peer-keyed entry point.
    #[test]
    fn test_push_path_never_takes_a_publication_package() {
        let manager = create_test_manager("alice");
        let reserved = manager.generate_publication_key_package().unwrap();

        for peer in [addr("bob"), addr("carol"), addr("dave")] {
            let taken = manager.take_push_key_package(&peer).unwrap();
            assert_ne!(
                taken.bundle.package_id, reserved.package_id,
                "the push path took the package a published record stands on"
            );
        }
    }

    /// The peer-less entry point (the FFI surface and tests) must not hand out
    /// a package a peer is expected to use, or it re-opens the cross-peer
    /// sharing the pool prevents.
    #[test]
    fn test_get_or_create_never_returns_a_peer_assigned_package() {
        let manager = create_test_manager("alice");
        let for_bob = manager.take_push_key_package(&addr("bob")).unwrap().bundle;

        let unclaimed = manager.get_or_create_key_package().unwrap();
        assert_ne!(unclaimed.package_id, for_bob.package_id);
        assert!(unclaimed.assigned_peer.is_none());
    }

    /// An unclaimed package — minted by the peer-less entry point, or by a
    /// build predating assignment — is claimed rather than left behind, so
    /// upgrading does not strand the package already in storage.
    #[test]
    fn test_push_path_claims_an_unclaimed_package_instead_of_stranding_it() {
        let manager = create_test_manager("alice");
        let legacy = manager.get_or_create_key_package().unwrap();
        assert!(legacy.assigned_peer.is_none());

        let taken = manager.take_push_key_package(&addr("bob")).unwrap();
        assert_eq!(
            taken.bundle.package_id, legacy.package_id,
            "the pre-existing package was stranded instead of claimed"
        );
        assert_eq!(
            taken.bundle.assigned_peer.as_deref(),
            Some(addr("bob").as_str())
        );
        assert_eq!(manager.count_valid_key_packages().unwrap(), 1);
    }

    /// At the ceiling the pool stops growing and shares a package, which is the
    /// old behaviour — deliberately, since refusing to advertise would cost
    /// session establishment. It must say so, because that is the one condition
    /// under which the reuse this pool removes is back.
    #[test]
    fn test_push_pool_ceiling_shares_a_package_and_reports_it() {
        let manager = create_test_manager("alice");

        for i in 0..MAX_PUSH_KEY_PACKAGES {
            let taken = manager.take_push_key_package(&format!("peer{i}")).unwrap();
            assert!(
                !taken.pool_exhausted,
                "pool reported exhausted at {i}, below the ceiling"
            );
        }
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            MAX_PUSH_KEY_PACKAGES
        );

        let over = manager.take_push_key_package("one-peer-too-many").unwrap();
        assert!(over.pool_exhausted, "ceiling breach was not reported");
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            MAX_PUSH_KEY_PACKAGES,
            "the pool grew past its ceiling"
        );

        // A peer that already holds a package keeps getting its own, even with
        // the pool at capacity — the ceiling must not downgrade existing peers.
        let established = manager.take_push_key_package("peer0").unwrap();
        assert!(!established.pool_exhausted);
        assert_eq!(established.bundle.assigned_peer.as_deref(), Some("peer0"));
    }

    /// The ceiling bounds how many packages *exist*, so it must gate minting
    /// and nothing else. A full pool holding an unclaimed package has one to
    /// give: claiming it relabels a package rather than adding one, and
    /// degrading to a shared init key while it sat idle would weaken forward
    /// secrecy to stay under a bound the claim never approaches.
    #[test]
    fn test_ceiling_claims_an_unclaimed_package_rather_than_sharing() {
        let manager = create_test_manager("alice");

        for i in 0..(MAX_PUSH_KEY_PACKAGES - 1) {
            manager.take_push_key_package(&format!("peer{i}")).unwrap();
        }
        // The last live slot is an unclaimed package — as the peer-less entry
        // point, `ensure_min_key_packages`, or a pre-upgrade record leaves one.
        let unclaimed = manager.get_or_create_key_package().unwrap();
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            MAX_PUSH_KEY_PACKAGES,
            "test premise: the pool is at the ceiling"
        );

        let taken = manager.take_push_key_package("late-arrival").unwrap();
        assert!(
            !taken.pool_exhausted,
            "shared a package while a claimable one was in the pool"
        );
        assert_eq!(
            taken.bundle.package_id, unclaimed.package_id,
            "the claimable package was passed over"
        );
        assert_eq!(taken.bundle.assigned_peer.as_deref(), Some("late-arrival"));
        assert_eq!(
            manager.count_valid_key_packages().unwrap(),
            MAX_PUSH_KEY_PACKAGES,
            "claiming grew the pool"
        );

        // With the last unclaimed package now spoken for, the next new peer has
        // nothing left to claim and does take the shared-package degradation.
        let over = manager.take_push_key_package("one-peer-too-many").unwrap();
        assert!(over.pool_exhausted);
    }

    #[test]
    fn test_import_key_package_binds_credential_identity() {
        let alice = create_test_manager("alice");
        let mallory = create_test_manager("mallory");
        let mallory_kp = mallory.generate_key_package().unwrap();

        // Importing mallory's key package under "bob" must be rejected —
        // otherwise a session "with bob" would encrypt to mallory's keys.
        let err = alice
            .import_key_package(&addr("bob"), &mallory_kp.key_package_data)
            .unwrap_err();
        assert!(matches!(err, MlsError::CredentialIdentityMismatch { .. }));

        // Importing under the matching identity succeeds.
        alice
            .import_key_package(&addr("mallory"), &mallory_kp.key_package_data)
            .unwrap();
    }

    /// A key package whose basic credential claims `claimed` but whose leaf
    /// signature key is `keys`.
    ///
    /// Built against raw OpenMLS on purpose: [`MlsManager::new`] refuses to
    /// construct at an address its stored key does not derive to, so an
    /// impostor is no longer expressible through this crate's own API. That
    /// refusal is the point — but it means the substitution has to be forged
    /// one layer down to be tested at all, the same way the `SenderIdentityMismatch`
    /// tests do.
    fn substituted_key_package(claimed: &str, keys: &SignatureKeyPair) -> Vec<u8> {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let provider = MlsProvider::new(MlsStorageAdapter::new(storage));
        keys.store(provider.storage()).unwrap();

        let credential = CredentialWithKey {
            credential: Credential::new(CredentialType::Basic, claimed.as_bytes().to_vec()),
            signature_key: keys.public().into(),
        };

        KeyPackage::builder()
            .build(DEFAULT_CIPHERSUITE, &provider, keys, credential)
            .unwrap()
            .key_package()
            .tls_serialize_detached()
            .unwrap()
    }

    #[test]
    fn test_credential_identity_check_alone_does_not_stop_a_substitution() {
        // The premise for the derivation check below, stated as a test so it
        // cannot quietly stop being true. `verify_credential_identity` compares
        // a self-asserted string, so an impostor who writes bob's address into
        // their own credential sails through *that* check on its own.
        let (mallorys_keys, _) = test_identity("mallory");
        let forged = substituted_key_package(&addr("bob"), &mallorys_keys);

        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let provider = MlsProvider::new(MlsStorageAdapter::new(storage));
        let key_package = KeyPackageIn::tls_deserialize_exact(&forged)
            .unwrap()
            .validate(provider.crypto(), ProtocolVersion::Mls10)
            .unwrap();

        MlsManager::verify_credential_identity(&key_package, &addr("bob"))
            .expect("the identity check cannot tell the two bobs apart");
    }

    #[test]
    fn test_substituted_key_package_is_refused_by_the_derivation() {
        // The same substitution, refused — and refused on *first contact*,
        // which the pin it replaced could not do. There is nothing to have
        // learned about bob beforehand: his address is the hash of his key, so
        // a package signed by anyone else re-derives to a different address.
        let alice = create_test_manager("alice");
        let real_bob = create_test_manager("bob");
        let (mallorys_keys, _) = test_identity("mallory");

        let forged = substituted_key_package(&addr("bob"), &mallorys_keys);
        let err = alice.import_key_package(&addr("bob"), &forged).unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::KeyPackageAddressMismatch { ref claimed, .. } if *claimed == addr("bob")
            ),
            "expected an address mismatch, got {:?}",
            err
        );

        // The genuine article still imports, with no prior contact either.
        let real_kp = real_bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &real_kp.key_package_data)
            .expect("the real peer's key package derives to its own address");
    }

    #[test]
    fn test_a_nickname_peer_id_is_refused_rather_than_skipping_the_check() {
        // The bypass this check must not have. If a non-address id answered
        // "nothing to derive, pass", an attacker would simply claim one — so a
        // peer id that is not an address is an error, not a waiver.
        let alice = create_test_manager("alice");
        let bob_kp = create_test_manager("bob").generate_key_package().unwrap();

        let err = alice
            .import_key_package("bob", &bob_kp.key_package_data)
            .unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::CredentialIdentityMismatch { .. } | MlsError::InvalidUserId(_)
            ),
            "a nickname must be refused, got {:?}",
            err
        );
    }

    #[test]
    fn test_add_group_member_binds_identity_and_derivation() {
        // The group path ran neither check before — not even the credential
        // identity one — so a package could join a group under a roster label
        // that had nothing to do with it.
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let mallory = create_test_manager("mallory");

        let group_id = alice.create_group("Test Group").unwrap().group_id;

        // Wrong identity outright.
        let mallory_kp = mallory.generate_key_package().unwrap();
        let err = alice
            .add_group_member(&group_id, &addr("bob"), &mallory_kp.key_package_data)
            .unwrap_err();
        assert!(matches!(err, MlsError::CredentialIdentityMismatch { .. }));

        // Right address in the credential, wrong key behind it.
        let (mallorys_keys, _) = test_identity("mallory");
        let forged = substituted_key_package(&addr("bob"), &mallorys_keys);
        let err = alice
            .add_group_member(&group_id, &addr("bob"), &forged)
            .unwrap_err();
        assert!(matches!(err, MlsError::KeyPackageAddressMismatch { .. }));

        // The genuine invitee joins.
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .add_group_member(&group_id, &addr("bob"), &bob_kp.key_package_data)
            .expect("the real invitee is admitted");
    }

    #[test]
    fn test_import_key_package_rejects_hostile_user_id() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let bob_kp = bob.generate_key_package().unwrap();

        for hostile in ["", "..", "bob/evil", "bob\\evil", "bob\0evil"] {
            let err = alice
                .import_key_package(hostile, &bob_kp.key_package_data)
                .unwrap_err();
            assert!(
                matches!(err, MlsError::InvalidUserId(_)),
                "expected InvalidUserId for {:?}, got {:?}",
                hostile,
                err
            );
        }
    }

    #[test]
    fn test_get_contact_key_package_rejects_poisoned_store() {
        // A key package written to storage out-of-band (bypassing import
        // validation, e.g. persisted before this fix) under the wrong user
        // id must fail identity verification at use time.
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (alice_keys, alice_address) = test_identity("alice");
        seed_identity(&storage, &alice_keys);
        let alice = MlsManager::new(alice_address.to_string(), storage.clone()).unwrap();
        let mallory = create_test_manager("mallory");
        let mallory_kp = mallory.generate_key_package().unwrap();

        storage
            .store(
                StorageKeyType::ContactKeyPackage.as_str(),
                &addr("bob"),
                &mallory_kp.key_package_data,
            )
            .unwrap();

        // create_session(bob) loads the poisoned package and must refuse.
        let err = alice.create_session(&addr("bob")).unwrap_err();
        assert!(matches!(err, MlsError::CredentialIdentityMismatch { .. }));
    }

    /// The *derivation* half of the cached-read check, which the poisoned-store
    /// test above cannot reach.
    ///
    /// That test stores mallory's own genuine package under bob's key, so the
    /// credential identity check ([`MlsManager::verify_credential_identity`])
    /// refuses it first and
    /// [`MlsManager::verify_address_binding`] never runs. A *substituted*
    /// package — credential claiming bob's address, leaf key mallory's — sails
    /// past the credential check by construction and can only be caught by
    /// re-deriving the address from the key.
    ///
    /// This is the call site the re-check exists for. Import-time validation
    /// does not travel with a cached package: it is re-read from the
    /// install-scoped store long after the receive-time gate admitted it, which
    /// is exactly the window a container write aims at. Deleting the
    /// `verify_address_binding` line from `get_contact_key_package` leaves
    /// every other test in this workspace green, so without this one the
    /// second call site could be dropped by a refactor in silence.
    #[test]
    fn test_get_contact_key_package_rejects_a_substituted_package() {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (alice_keys, alice_address) = test_identity("alice");
        seed_identity(&storage, &alice_keys);
        let alice = MlsManager::new(alice_address.to_string(), storage.clone()).unwrap();

        // Claims bob's address, signed by mallory's key.
        let (mallorys_keys, _) = test_identity("mallory");
        let forged = substituted_key_package(&addr("bob"), &mallorys_keys);

        storage
            .store(
                StorageKeyType::ContactKeyPackage.as_str(),
                &addr("bob"),
                &forged,
            )
            .unwrap();

        let err = alice.create_session(&addr("bob")).unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::KeyPackageAddressMismatch { ref claimed, .. } if *claimed == addr("bob")
            ),
            "a substituted cached package must be refused at use time, got {:?}",
            err
        );

        // And no session was built against mallory's leaf.
        assert!(!alice.has_session(&addr("bob")).unwrap());
    }

    #[test]
    fn test_replace_session_with_welcome_rejects_hostile_inviter_id() {
        // `inviter_id` arrives on the wire and is used as a raw storage key
        // for deletes — hostile values must be rejected before any storage
        // operation runs.
        let alice = create_test_manager("alice");
        let welcome = WelcomeMessage {
            group_id: slot("alice", "bob"),
            welcome_data: vec![],
            inviter_id: "../../etc".to_string(),
            group_name: None,
            timestamp_ms: 0,
        };
        let err = alice.replace_session_with_welcome(&welcome).unwrap_err();
        assert!(matches!(err, MlsError::InvalidUserId(_)));
    }

    /// Builds a converged alice/bob 1:1 session for sender-binding tests.
    fn create_test_session() -> (MlsManager, MlsManager) {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        let welcome = alice.create_session(&addr("bob")).unwrap();
        bob.join_session(&welcome).unwrap();
        (alice, bob)
    }

    #[test]
    fn test_session_decrypt_rejects_spoofed_sender() {
        let (alice, bob) = create_test_session();

        // A message from alice's session must not be attributable to a
        // different wire sender. The envelope names `session:alice:bob`, which
        // is not the slot bob shares with "mallory", so the slot binding
        // rejects it *before* the group is loaded — strictly earlier than the
        // SEC-M1 credential check, which cannot run until a decrypt succeeds.
        let ct = alice.encrypt_for_user(&addr("bob"), b"hello").unwrap();
        let err = bob.decrypt_from_user(&ct, &addr("mallory")).unwrap_err();
        assert!(
            matches!(err, MlsError::SessionIdentityMismatch { .. }),
            "spoofed sender must be rejected by the slot binding, got {:?}",
            err
        );

        // Rejecting pre-decrypt also means the forgery does not consume the
        // ratchet generation it named, so the *same* generation still decrypts
        // for the legitimate sender. (Before the binding, a spoofed frame
        // burned the generation and the genuine message was lost.)
        let pt = bob.decrypt_from_user(&ct, &addr("alice")).unwrap();
        assert_eq!(pt.as_deref(), Some(&b"hello"[..]));

        // SEC-M1 itself (correct slot, wrong credential) stays reachable and is
        // covered by `test_group_decrypt_rejects_spoofed_sender`, where a group
        // has enough members for the two identities to differ.
    }

    #[test]
    fn test_epoch_fork_classifies_as_session_desync() {
        // An established session that forks (one side advances its epoch without
        // the other merging the commit) must surface as the *recoverable*
        // `SessionDesync`, not an opaque `Decryption` — that is what lets the
        // protocol layer re-key instead of silently dropping.
        let (alice, bob) = create_test_session();

        // Alice self-updates and merges locally, advancing only her epoch; bob
        // never sees the commit, so the two sides are now one epoch apart.
        let group_id = slot("alice", "bob");
        alice.update_keys(&group_id).unwrap();

        // A message alice encrypts at her new epoch cannot decrypt at bob's old
        // epoch → OpenMLS `WrongEpoch` → `MlsError::SessionDesync`.
        let ct = alice.encrypt_for_user(&addr("bob"), b"after-fork").unwrap();
        let err = bob.decrypt_from_user(&ct, &addr("alice")).unwrap_err();
        assert!(
            matches!(err, MlsError::SessionDesync(_)),
            "epoch fork must classify as SessionDesync, got {:?}",
            err
        );
    }

    /// Serializes an `MlsMessage(PrivateMessage)` from scratch — no group, no
    /// keys, no captured ciphertext. Wire format per RFC 9420:
    /// `version(u16) || wire_format(u16) || group_id<V> || epoch(u64) ||
    /// content_type(u8) || authenticated_data<V> || encrypted_sender_data<V> ||
    /// ciphertext<V>`, where `<V>` is a QUIC varint length (single byte below
    /// 64). Used to demonstrate what an off-path attacker can actually build.
    /// Appends `len` as a QUIC variable-length integer.
    ///
    /// Two-byte encoding is not optional here: a 1:1 slot over two `off1…`
    /// addresses is ~96 bytes, well past the 63-byte ceiling a single byte can
    /// express. Hardcoding one byte was fine while ids were nicknames and
    /// silently produced an unparseable frame the moment they stopped being.
    fn push_varint(out: &mut Vec<u8>, len: usize) {
        match len {
            0..=63 => out.push(len as u8),
            64..=16_383 => {
                out.push(0x40 | (len >> 8) as u8);
                out.push((len & 0xff) as u8);
            }
            _ => panic!("test payloads stay under the 2-byte varint ceiling"),
        }
    }

    fn forge_private_message(group_id: &str, epoch: u64) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&1u16.to_be_bytes()); // ProtocolVersion::Mls10
        out.extend_from_slice(&2u16.to_be_bytes()); // WireFormat::PrivateMessage
        push_varint(&mut out, group_id.len());
        out.extend_from_slice(group_id.as_bytes());
        out.extend_from_slice(&epoch.to_be_bytes());
        out.push(1); // ContentType::Application
        out.push(0); // authenticated_data: empty
        out.push(8); // encrypted_sender_data: 8 bytes of nothing
        out.extend_from_slice(&[0u8; 8]);
        out.push(16); // ciphertext: 16 bytes of nothing
        out.extend_from_slice(&[0u8; 16]);
        out
    }

    #[test]
    fn test_forged_frame_reaches_session_desync_without_any_key_material() {
        // Honest statement of the residual threat model. OpenMLS validates the
        // framing header (group id, then epoch) *before* any AEAD, sender-data
        // decryption, or signature check, and a 1:1 slot id is derivable from
        // two public user ids. So an attacker with no key material, no captured
        // ciphertext and no session can hand-serialize a frame that classifies
        // as the recoverable `SessionDesync` — the classification that drives a
        // re-key. This is inherent to MLS framing, not an OpenMLS bug.
        //
        // The mitigation is NOT that this is unreachable (it is reachable, as
        // asserted here) but that everything hung off it is bounded and
        // non-destructive: the slot binding below, the per-peer re-key floor,
        // and a heal that no longer discards queued plaintext.
        let (_alice, bob) = create_test_session();

        let forged = EncryptedMessage {
            group_id: slot("alice", "bob"),
            message_type: MlsMessageType::Application,
            epoch: 9_999,
            ciphertext: forge_private_message(slot("alice", "bob").as_str(), 9_999),
            sender_id: addr("alice"),
            timestamp_ms: 0,
        };

        let err = bob.decrypt_from_user(&forged, &addr("alice")).unwrap_err();
        assert!(
            matches!(err, MlsError::SessionDesync(_)),
            "a forged future-epoch frame reaches the desync classification pre-AEAD, got {:?}",
            err
        );
    }

    #[test]
    fn test_forged_frame_naming_a_foreign_slot_is_rejected_before_desync() {
        // The slot binding is what stops the forgery above from being pointed
        // at *any* session while naming *any* sender. Without it the claimed
        // sender and the targeted group are independent, so one derivable slot
        // id yields a re-key (and a peer-keyed map entry, and a key-package
        // send) for arbitrary attacker-chosen identities.
        let (_alice, bob) = create_test_session();

        let forged = EncryptedMessage {
            group_id: slot("alice", "bob"),
            message_type: MlsMessageType::Application,
            epoch: 9_999,
            ciphertext: forge_private_message(slot("alice", "bob").as_str(), 9_999),
            sender_id: addr("mallory"),
            timestamp_ms: 0,
        };

        let err = bob
            .decrypt_from_user(&forged, &addr("mallory"))
            .unwrap_err();
        assert!(
            matches!(err, MlsError::SessionIdentityMismatch { .. }),
            "a frame naming another pair's slot must not classify as recoverable, got {:?}",
            err
        );
    }

    #[test]
    fn test_corrupt_ciphertext_is_not_classified_as_session_desync() {
        // A malformed frame must stay a plain decrypt failure, which the
        // protocol layer fails closed on. Note this covers only *malformed*
        // input — it never reaches the framing validation, so it is not
        // evidence that forged frames cannot reach `SessionDesync`. They can:
        // see `test_forged_frame_reaches_session_desync_without_any_key_material`.
        let (alice, bob) = create_test_session();
        let mut ct = alice.encrypt_for_user(&addr("bob"), b"hello").unwrap();
        // Corrupt the AEAD-protected body.
        for b in ct.ciphertext.iter_mut() {
            *b ^= 0xFF;
        }
        let err = bob.decrypt_from_user(&ct, &addr("alice")).unwrap_err();
        assert!(
            !matches!(err, MlsError::SessionDesync(_)),
            "corrupt ciphertext must not be treated as a recoverable desync, got {:?}",
            err
        );
    }

    #[test]
    fn test_join_session_binds_slot_to_inviter() {
        // Regression (session-hijack): a Welcome from an authenticated inviter
        // may only install the 1:1 session slot for (self, inviter). An inviter
        // that names a *third* party's slot must be rejected before any group
        // state is touched — otherwise the inviter overwrites/seeds the
        // victim's session with that third party, so the victim's outbound
        // messages to that party encrypt to the attacker's group.
        let bob = create_test_manager("bob");

        // mallory, authenticating honestly as herself, sends bob a Welcome whose
        // group_id squats alice+bob's session slot.
        let hijack = WelcomeMessage {
            group_id: slot("alice", "bob"),
            welcome_data: vec![], // rejected before deserialization
            inviter_id: addr("mallory"),
            group_name: None,
            timestamp_ms: 0,
        };

        // Both join entry points must reject the mismatched slot.
        let err = bob.join_session(&hijack).unwrap_err();
        assert!(
            matches!(err, MlsError::WelcomeIdentityMismatch { .. }),
            "join_session: expected WelcomeIdentityMismatch, got {:?}",
            err
        );
        let err = bob.replace_session_with_welcome(&hijack).unwrap_err();
        assert!(
            matches!(err, MlsError::WelcomeIdentityMismatch { .. }),
            "replace_session_with_welcome: expected WelcomeIdentityMismatch, got {:?}",
            err
        );

        // Nothing was installed: bob has no session with either identity.
        assert!(!bob.has_session(&addr("alice")).unwrap());
        assert!(!bob.has_session(&addr("mallory")).unwrap());

        // The check is precise, not over-broad: a correctly-slotted Welcome from
        // mallory (group_id == session:bob:mallory, inviter_id == mallory) still
        // joins normally.
        let bob_kp = bob.generate_key_package().unwrap();
        let mallory = create_test_manager("mallory");
        mallory
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        let legit = mallory.create_session(&addr("bob")).unwrap();
        bob.join_session(&legit).unwrap();
        assert!(bob.has_session(&addr("mallory")).unwrap());
    }

    #[test]
    fn test_join_group_rejects_session_namespace() {
        // Regression (session-hijack via the group-Welcome path): the identity
        // binding on `join_session` only guards the session-Welcome path. A
        // group Welcome carries an attacker-controllable `group_id` and writes
        // the SAME storage/OpenMLS keyspace, so `join_group` must refuse the
        // reserved `session:` namespace outright — otherwise an authenticated
        // peer could seed/overwrite a third party's 1:1 session slot and
        // hijack the victim's outbound encryption.
        let bob = create_test_manager("bob");

        let squat = WelcomeMessage {
            group_id: slot("alice", "bob"),
            welcome_data: vec![], // rejected before deserialization
            inviter_id: addr("mallory"),
            group_name: None,
            timestamp_ms: 0,
        };

        let err = bob.join_group(&squat).unwrap_err();
        assert!(
            matches!(err, MlsError::ReservedSessionNamespace { .. }),
            "join_group: expected ReservedSessionNamespace, got {:?}",
            err
        );

        // The squatted 1:1 slot was never installed.
        assert!(!bob.has_session(&addr("alice")).unwrap());

        // Precision: a legitimately-namespaced group Welcome is not caught by
        // this guard (it fails later at deserialization of the empty blob, not
        // with ReservedSessionNamespace).
        let legit_ns = WelcomeMessage {
            group_id: GroupId::new("group:0bd6e5f2-3a70-4a4e-9c3f-1c1f2a3b4c5d").unwrap(),
            welcome_data: vec![],
            inviter_id: addr("mallory"),
            group_name: None,
            timestamp_ms: 0,
        };
        let err = bob.join_group(&legit_ns).unwrap_err();
        assert!(
            !matches!(err, MlsError::ReservedSessionNamespace { .. }),
            "a group:-namespaced Welcome must not trip the session-namespace guard, got {:?}",
            err
        );
    }

    #[test]
    fn test_join_group_rejects_embedded_group_id_mismatch() {
        // Regression (HIGH-1): OpenMLS persists a joined group under the group
        // id embedded in the Welcome's GroupContext — a value the inviter picks
        // freely at creation (`new_with_group_id`) — while our storage marker
        // and every load/delete lookup key off the *wire* `group_id`, which is
        // all the SEC-M5/M6 bindings validate. If the two diverge, `into_group`
        // would install the group under the attacker's embedded id: an
        // arbitrary slot the wire-id checks never inspected. The join must bind
        // embedded == wire and reject before any state is written.
        let bob = create_test_manager("bob");
        let mallory = create_test_manager("mallory");

        // Mallory builds a real group whose EMBEDDED id is one value...
        let bob_kp = bob.generate_key_package().unwrap();
        let embedded = GroupId::new("group:11111111-1111-4111-8111-111111111111").unwrap();
        let cred = mallory.get_credential().unwrap();
        let signer = mallory.get_signer().unwrap();
        mallory
            .group_manager
            .create_group(&embedded, &cred, &signer)
            .unwrap();
        let (welcome, _commit) = mallory
            .add_group_member(&embedded, &addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        assert_eq!(welcome.group_id, embedded);

        // ...but presents it under a DIFFERENT wire group_id. The wire id clears
        // the reserved-namespace guard (not `session:`), so only the embedded-id
        // binding stands between the attacker and an arbitrary slot.
        let wire = GroupId::new("group:22222222-2222-4222-8222-222222222222").unwrap();
        let tampered = WelcomeMessage {
            group_id: wire.clone(),
            ..welcome
        };

        let err = bob.join_group(&tampered).unwrap_err();
        assert!(
            matches!(err, MlsError::WelcomeGroupIdMismatch { .. }),
            "expected WelcomeGroupIdMismatch, got {:?}",
            err
        );

        // Nothing was installed under EITHER id — the reject precedes into_group.
        assert!(bob.group_manager.load_group(&wire).unwrap().is_none());
        assert!(bob.group_manager.load_group(&embedded).unwrap().is_none());
    }

    #[test]
    fn test_welcome_embedded_id_cannot_hijack_session_slot() {
        // Regression (HIGH-1, the SEC-M6 hijack reached through the embedded id).
        // Bob has a live 1:1 session with Alice at `session:alice:bob`. Mallory,
        // authenticating honestly as herself with a wire `group_id` that PASSES
        // `verify_welcome_slot` (`session:bob:mallory`), sends a Welcome whose
        // *embedded* GroupContext id squats `session:alice:bob`. Without the
        // embedded-id binding, `into_group` overwrites Bob's Alice session so his
        // next `encrypt_for_user("alice")` encrypts to Mallory's group. The
        // binding must reject it and leave Bob's Alice session intact.
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        let welcome = alice.create_session(&addr("bob")).unwrap();
        bob.join_session(&welcome).unwrap();
        assert!(bob.has_session(&addr("alice")).unwrap());

        // Mallory crafts a group whose embedded id squats bob's alice slot.
        let mallory = create_test_manager("mallory");
        let bob_kp2 = bob.generate_key_package().unwrap();
        let squat = slot("alice", "bob");
        let cred = mallory.get_credential().unwrap();
        let signer = mallory.get_signer().unwrap();
        mallory
            .group_manager
            .create_group(&squat, &cred, &signer)
            .unwrap();
        let (mal_welcome, _commit) = mallory
            .add_group_member(&squat, &addr("bob"), &bob_kp2.key_package_data)
            .unwrap();

        // Present it under a wire slot that passes verify_welcome_slot for mallory.
        let attack = WelcomeMessage {
            group_id: slot("bob", "mallory"),
            welcome_data: mal_welcome.welcome_data,
            inviter_id: addr("mallory"),
            group_name: None,
            timestamp_ms: 0,
        };

        let err = bob.join_session(&attack).unwrap_err();
        assert!(
            matches!(err, MlsError::WelcomeGroupIdMismatch { .. }),
            "expected WelcomeGroupIdMismatch, got {:?}",
            err
        );

        // Bob's Alice session survived and still encrypts to Alice's group.
        assert!(bob.has_session(&addr("alice")).unwrap());
        let ct = bob
            .encrypt_for_user(&addr("alice"), b"still private")
            .unwrap();
        let pt = alice.decrypt_from_user(&ct, &addr("bob")).unwrap();
        assert_eq!(pt.as_deref(), Some(&b"still private"[..]));
    }

    /// Builds a two-member group (alice admin, bob member) for group
    /// sender-binding tests. Returns (alice, bob, group_id).
    fn create_test_group_with_bob() -> (MlsManager, MlsManager, GroupId) {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        let info = alice.create_group("Test Group").unwrap();
        let gid = info.group_id.clone();
        let (welcome, _commit) = alice
            .add_group_member(&gid, &addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        bob.join_group(&welcome).unwrap();
        (alice, bob, gid)
    }

    #[test]
    fn test_group_decrypt_rejects_spoofed_sender() {
        let (alice, bob, gid) = create_test_group_with_bob();

        let ct = alice.encrypt_for_group(&gid, b"group message").unwrap();
        let err = bob.decrypt_from_group(&ct, &addr("mallory")).unwrap_err();
        assert!(matches!(err, MlsError::SenderIdentityMismatch { .. }));

        let ct2 = alice.encrypt_for_group(&gid, b"another one").unwrap();
        let pt = bob.decrypt_from_group(&ct2, &addr("alice")).unwrap();
        assert_eq!(pt.as_deref(), Some(&b"another one"[..]));
    }

    #[test]
    fn test_group_commit_with_spoofed_sender_rejected_before_merge() {
        let (alice, bob, gid) = create_test_group_with_bob();

        // Alice issues a key-update commit; bob receives it with a spoofed
        // wire sender. The mismatch must be detected BEFORE the staged
        // commit is merged — bob's epoch must not advance.
        let commit = alice.update_keys(&gid).unwrap();
        let epoch_before = bob.get_group_info(&gid).unwrap().unwrap().epoch;

        let err = bob
            .decrypt_from_group(&commit, &addr("mallory"))
            .unwrap_err();
        assert!(matches!(err, MlsError::SenderIdentityMismatch { .. }));

        let epoch_after = bob.get_group_info(&gid).unwrap().unwrap().epoch;
        assert_eq!(
            epoch_before, epoch_after,
            "spoofed commit must not advance group state"
        );
    }

    #[test]
    fn test_no_session_initially() {
        let manager = create_test_manager("alice");
        assert!(!manager.has_session(&addr("bob")).unwrap());
        assert!(manager.list_sessions().unwrap().is_empty());
    }

    #[test]
    fn test_no_groups_initially() {
        let manager = create_test_manager("alice");
        assert!(manager.list_groups().unwrap().is_empty());
    }

    #[test]
    fn test_group_creation() {
        let manager = create_test_manager("alice");
        let info = manager.create_group("Test Group").unwrap();

        assert_eq!(info.name, Some("Test Group".to_string()));
        assert!(!info.is_session);
        assert_eq!(info.members.len(), 1);

        let groups = manager.list_groups().unwrap();
        assert_eq!(groups.len(), 1);
    }

    /// Regression test for the both-create split-brain re-brick.
    ///
    /// With auto key exchange, both peers create a `session:a:b` group and the
    /// higher-id peer adopts the lower-id "owner"'s Welcome. The owner keeps
    /// retransmitting its Welcome until it sees a group-aware proof, so the
    /// adopter receives the SAME Welcome again *after* it already adopted. MLS
    /// key packages are one-time, so re-staging that Welcome must fail — but it
    /// must fail NON-DESTRUCTIVELY, leaving the converged group intact. The old
    /// delete-then-stage path deleted the good group first and then could not
    /// re-stage, permanently bricking a working session.
    #[test]
    fn test_both_create_adopt_is_non_destructive_on_welcome_retransmit() {
        // alice = lexicographically-lower "owner"; bob = higher "adopter".
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");

        // Exchange key packages both ways (both sides will auto-create).
        let alice_kp = alice.generate_key_package().unwrap();
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        bob.import_key_package(&addr("alice"), &alice_kp.key_package_data)
            .unwrap();

        // Both-create race: each peer creates its own session group + Welcome.
        let alice_welcome = alice.create_session(&addr("bob")).unwrap(); // owner's Welcome
        let _bob_welcome = bob.create_session(&addr("alice")).unwrap(); // adopter's own group
        assert!(bob.has_session(&addr("alice")).unwrap());

        // Adopter adopts the owner's Welcome (first delivery): replaces its own
        // group with alice's, consuming bob's one-time key package.
        bob.join_session(&alice_welcome).unwrap();
        assert!(bob.has_session(&addr("alice")).unwrap());

        // Convergence: alice encrypts and bob decrypts on the shared group.
        let ct = alice
            .encrypt_for_user(&addr("bob"), b"hello over the converged group")
            .unwrap();
        let pt = bob.decrypt_from_user(&ct, &addr("alice")).unwrap();
        assert_eq!(pt.as_deref(), Some(&b"hello over the converged group"[..]));

        // Owner retransmits the SAME Welcome (its periodic retry). Re-staging
        // MUST fail (bob's key package is consumed) but MUST be non-destructive.
        let retransmit = bob.join_session(&alice_welcome);
        assert!(
            retransmit.is_err(),
            "re-staging a consumed key package should fail"
        );

        // The converged group MUST survive the failed retransmit. This is the
        // regression: the old delete-then-stage path left bob with no session.
        assert!(
            bob.has_session(&addr("alice")).unwrap(),
            "duplicate Welcome must not brick the converged session"
        );

        // ...and it must still be functional after the failed retransmit.
        let ct2 = alice
            .encrypt_for_user(&addr("bob"), b"still converged after retransmit")
            .unwrap();
        let pt2 = bob.decrypt_from_user(&ct2, &addr("alice")).unwrap();
        assert_eq!(
            pt2.as_deref(),
            Some(&b"still converged after retransmit"[..])
        );
    }

    /// Windowed media transfers keep up to 8 encrypted chunks in flight
    /// (interleaved with text on the same session ratchet), so a delayed chunk
    /// can arrive many generations behind the newest decrypted message. The
    /// OpenMLS default tolerance (5) would delete its key and permanently stall
    /// the transfer; `SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE` (32) must cover it.
    #[test]
    fn test_out_of_order_decryption_within_sender_ratchet_tolerance() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");

        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        let welcome = alice.create_session(&addr("bob")).unwrap();
        bob.join_session(&welcome).unwrap();

        let ciphertexts: Vec<_> = (0..40)
            .map(|i| {
                alice
                    .encrypt_for_user(&addr("bob"), format!("chunk {}", i).as_bytes())
                    .unwrap()
            })
            .collect();

        // Decrypt the newest message first, ratcheting bob's receive state far
        // ahead of every earlier generation.
        let pt = bob
            .decrypt_from_user(&ciphertexts[39], &addr("alice"))
            .unwrap();
        assert_eq!(pt.as_deref(), Some(&b"chunk 39"[..]));

        // 29 generations behind: far beyond the OpenMLS default of 5, but
        // within our tolerance of 32 — must still decrypt.
        let pt = bob
            .decrypt_from_user(&ciphertexts[10], &addr("alice"))
            .unwrap();
        assert_eq!(pt.as_deref(), Some(&b"chunk 10"[..]));

        // 39 generations behind: beyond the tolerance, the key is deleted and
        // the message must NOT decrypt (proves the configured bound applies).
        let res = bob.decrypt_from_user(&ciphertexts[0], &addr("alice"));
        assert!(
            !matches!(res, Ok(Some(_))),
            "generation beyond the tolerance must not decrypt"
        );
    }

    /// RFC 8032 §7.1 TEST 1 Ed25519 public key.
    const RFC8032_TV1_PK: [u8; 32] = [
        0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07,
        0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07,
        0x51, 0x1a,
    ];

    /// The address of that key, from the BIP-350 reference implementation.
    /// This literal is the cross-platform contract: bridges and apps must all
    /// produce it for this key. Re-derive it from the reference implementation
    /// if it ever needs to change — never edit it to match new code output.
    const RFC8032_TV1_ADDRESS: &str = "off1qysluvwl5922yctzd0u9gpr06gn3k7ldfvgtwgvn";

    #[test]
    fn derive_address_matches_the_pinned_vector() {
        let address = MlsManager::derive_address(&RFC8032_TV1_PK).expect("32-byte key derives");
        assert_eq!(address.to_string(), RFC8032_TV1_ADDRESS);
        // Self-certifying: the rendered form parses back to the same address,
        // so a peer can check a claimed address against a presented key.
        assert_eq!(
            RFC8032_TV1_ADDRESS.parse::<Address>().expect("parses"),
            address
        );
    }

    #[test]
    fn derive_address_rejects_wrong_key_lengths() {
        for len in [0usize, 31, 33, 64] {
            let key = vec![0u8; len];
            assert!(
                matches!(
                    MlsManager::derive_address(&key),
                    Err(MlsError::InvalidPublicKey(_))
                ),
                "{len}-byte key must be rejected"
            );
        }
    }

    #[test]
    fn deprecated_derive_agrees_with_derive_address() {
        // The deprecated entry point must not become a second addressing
        // format while it still exists.
        #[allow(deprecated)]
        let legacy = MlsManager::derive_user_id_from_public_key(&RFC8032_TV1_PK);
        assert_eq!(legacy, RFC8032_TV1_ADDRESS);
        assert_eq!(
            legacy,
            MlsManager::derive_address(&RFC8032_TV1_PK)
                .expect("derives")
                .to_string()
        );
    }

    #[test]
    fn load_or_create_identity_mints_once_and_is_idempotent() {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());

        let (first_keys, first_address) = MlsManager::load_or_create_identity(&storage).unwrap();
        let (second_keys, second_address) = MlsManager::load_or_create_identity(&storage).unwrap();

        // Second call loads, never mints: same key, therefore same address.
        assert_eq!(first_keys.public(), second_keys.public());
        assert_eq!(first_address, second_address);
        assert_eq!(
            MlsManager::derive_address(first_keys.public()).unwrap(),
            first_address,
            "the returned address must be the stored key's derivation"
        );
    }

    #[test]
    fn load_or_create_identity_adopts_an_existing_key() {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (keys, address) = test_identity("alice");
        seed_identity(&storage, &keys);

        let (loaded, loaded_address) = MlsManager::load_or_create_identity(&storage).unwrap();

        assert_eq!(loaded.public(), keys.public());
        assert_eq!(loaded_address, address);
    }

    #[test]
    fn manager_bootstrapped_at_its_derived_address_loads_that_identity() {
        let (manager, address) = create_addressed_manager("alice");

        assert_eq!(manager.user_id(), address.to_string());
        assert_eq!(
            MlsManager::derive_address(&manager.get_identity_public_key().unwrap()).unwrap(),
            address,
            "the manager's identity key must derive to the address it claims"
        );
    }

    /// The address is the identity key's hash, so a manager pointed at storage
    /// holding a *different* identity is a broken bootstrap — the wrong
    /// namespace for this profile, or a replaced key. It must fail loudly
    /// rather than build a credential claiming an address it cannot prove.
    #[test]
    fn manager_refuses_an_address_whose_key_is_not_the_stored_one() {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (alice_keys, alice_address) = test_identity("alice");
        let (_, bob_address) = test_identity("bob");
        seed_identity(&storage, &alice_keys);

        let Err(err) = MlsManager::new(bob_address.to_string(), storage) else {
            panic!("a manager must not claim an address it holds no key for");
        };

        match err {
            MlsError::IdentityAddressMismatch { expected, derived } => {
                assert_eq!(expected, bob_address.to_string());
                assert_eq!(derived, alice_address.to_string());
            }
            other => panic!("expected IdentityAddressMismatch, got {other:?}"),
        }
    }

    /// Empty storage plus an address id means the caller skipped the bootstrap:
    /// a freshly minted key derives to a different address, so claiming this
    /// one would be unprovable. Refused before anything is persisted.
    #[test]
    fn manager_refuses_to_claim_an_address_with_no_stored_identity() {
        let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
        let (_, address) = test_identity("alice");

        let Err(err) = MlsManager::new(address.to_string(), storage.clone()) else {
            panic!("a manager must not mint a key and claim a different address");
        };
        assert!(matches!(err, MlsError::IdentityAddressMismatch { .. }));

        assert!(
            storage
                .load(StorageKeyType::Identity.as_str(), "key_pair")
                .unwrap()
                .is_none(),
            "a refused bootstrap must not leave a key behind"
        );
    }

    /// Nickname ids have no derivation to check, so a manager can still be
    /// *constructed* at one — [`MlsManager::verify_identity_binding`] is about
    /// catching a broken self-certifying identity, not about forcing every id
    /// to be an address.
    ///
    /// Note the asymmetry with [`MlsManager::verify_address_binding`], which
    /// refuses a nickname outright. The two are different questions: this one
    /// asks whether *our own* stored key matches the id we were handed, where a
    /// nickname means "nothing was claimed"; that one asks whether a *peer* owns
    /// the id they claim, where a nickname means "the claim is unprovable" — and
    /// answering "pass" there would be the bypass the whole check exists to close.
    #[test]
    fn manager_with_a_non_address_id_skips_the_binding_check() {
        let manager = MlsManager::new("alice", Arc::new(InMemoryStorage::new())).unwrap();
        assert_eq!(manager.user_id(), "alice");
    }

    // ========================================================================
    // LEAF IDENTITY BINDING (the Authentication Service, RFC 9420 §5.3.1/§7.3)
    // ========================================================================

    /// An impostor holding a leaf that claims someone else's address.
    ///
    /// [`substituted_key_package`] throws its provider away, which is enough to
    /// test a key package being *refused* but not to test what a forged leaf
    /// does once it is in a tree: processing the Welcome addressed to that leaf
    /// needs the private init key, so the provider has to outlive the key
    /// package. This keeps it, and is otherwise the same forgery — a fresh
    /// keypair with a credential naming a victim.
    struct Impostor {
        provider: MlsProvider,
        keys: SignatureKeyPair,
        key_package: Vec<u8>,
        group: Option<MlsGroup>,
    }

    impl Impostor {
        /// Mints a leaf whose credential claims `claimed` and whose signature
        /// key is `key_label`'s — i.e. the attacker's own.
        fn claiming(claimed: &str, key_label: &str) -> Self {
            let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
            let provider = MlsProvider::new(MlsStorageAdapter::new(storage));
            let (keys, _) = test_identity(key_label);
            keys.store(provider.storage()).unwrap();

            let credential = CredentialWithKey {
                credential: Credential::new(CredentialType::Basic, claimed.as_bytes().to_vec()),
                signature_key: keys.public().into(),
            };
            let key_package = KeyPackage::builder()
                .build(DEFAULT_CIPHERSUITE, &provider, &keys, credential)
                .unwrap()
                .key_package()
                .tls_serialize_detached()
                .unwrap();

            Self {
                provider,
                keys,
                key_package,
                group: None,
            }
        }

        /// Joins the group via the Welcome minted against this leaf.
        fn join(&mut self, welcome: &MlsMessageOut) {
            let bytes = welcome.tls_serialize_detached().unwrap();
            let welcome = match MlsMessageIn::tls_deserialize_exact(&bytes)
                .unwrap()
                .extract()
            {
                MlsMessageBodyIn::Welcome(w) => w,
                _ => panic!("not a welcome"),
            };
            let cfg = MlsGroupJoinConfig::builder()
                .use_ratchet_tree_extension(true)
                .build();
            self.group = Some(
                StagedWelcome::new_from_welcome(&self.provider, &cfg, welcome, None)
                    .unwrap()
                    .into_group(&self.provider)
                    .unwrap(),
            );
        }

        /// Merges a commit so the forged leaf tracks the group's epoch.
        ///
        /// Needed because a message is only decryptable at the epoch it was
        /// sealed in: without this the forgery fails as a stale generation and
        /// the test would pass for the wrong reason.
        fn merge_commit(&mut self, commit_bytes: &[u8]) {
            let group = self.group.as_mut().expect("join first");
            let message = MlsMessageIn::tls_deserialize_exact(commit_bytes)
                .unwrap()
                .try_into_protocol_message()
                .unwrap();
            let processed = group.process_message(&self.provider, message).unwrap();
            match processed.into_content() {
                ProcessedMessageContent::StagedCommitMessage(staged) => {
                    group.merge_staged_commit(&self.provider, *staged).unwrap();
                }
                _ => panic!("not a commit"),
            }
        }

        /// Speaks from the forged leaf.
        fn encrypt(&mut self, plaintext: &[u8]) -> Vec<u8> {
            self.group
                .as_mut()
                .expect("join first")
                .create_message(&self.provider, &self.keys, plaintext)
                .unwrap()
                .tls_serialize_detached()
                .unwrap()
        }
    }

    /// Adds `key_package_bytes` to `group_id` the way an attacker would: past
    /// `add_group_member`, which refuses it.
    ///
    /// The attacker runs their own build, so the send-side check is theirs to
    /// delete. Every test here that plants a forged leaf goes through this, so
    /// none of them are accidentally testing the send-side check instead of the
    /// receive-side one.
    fn add_member_bypassing_checks(
        manager: &MlsManager,
        group_id: &GroupId,
        key_package_bytes: &[u8],
    ) -> (MlsMessageOut, MlsMessageOut) {
        let mut group = manager
            .group_manager
            .load_group(group_id)
            .unwrap()
            .expect("group exists");
        let key_package = KeyPackageIn::tls_deserialize_exact(key_package_bytes)
            .unwrap()
            .validate(
                manager.group_manager.provider().crypto(),
                ProtocolVersion::Mls10,
            )
            .unwrap();
        let signer = manager.get_signer().unwrap();
        let (commit, welcome) = manager
            .group_manager
            .add_member(&mut group, key_package, &signer)
            .unwrap();
        manager.group_manager.save_group(group_id, &group).unwrap();
        (commit, welcome)
    }

    fn commit_message(
        group_id: &GroupId,
        commit: &MlsMessageOut,
        sender: &str,
    ) -> EncryptedMessage {
        EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Commit,
            epoch: 0,
            ciphertext: commit.tls_serialize_detached().unwrap(),
            sender_id: sender.to_string(),
            timestamp_ms: 0,
        }
    }

    fn app_message(group_id: &GroupId, ciphertext: Vec<u8>, sender: &str) -> EncryptedMessage {
        EncryptedMessage {
            group_id: group_id.clone(),
            message_type: MlsMessageType::Application,
            epoch: 0,
            ciphertext,
            sender_id: sender.to_string(),
            timestamp_ms: 0,
        }
    }

    /// The whole vulnerability, end to end, as a rejection.
    ///
    /// Mallory is in a group with Alice. She commits a leaf whose credential
    /// says "bob" but whose key is hers, then speaks from it as bob. Before the
    /// binding existed this reached Alice's app: the commit merged, bob showed
    /// up in her roster, and SEC-M1 waved the message through because the wire
    /// sender and the credential agreed — both being strings Mallory chose.
    #[test]
    fn test_committed_forged_leaf_is_refused_and_cannot_speak_as_its_victim() {
        let mallory = create_test_manager("mallory");
        let alice = create_test_manager("alice");
        let alice_kp = alice.generate_key_package().unwrap();

        let gid = mallory.create_group("Team").unwrap().group_id;
        let (welcome, _) = mallory
            .add_group_member(&gid, &addr("alice"), &alice_kp.key_package_data)
            .unwrap();
        alice.join_group(&welcome).unwrap();
        let epoch_before = alice.get_group_info(&gid).unwrap().unwrap().epoch;

        // The send-side check refuses the forgery, so Mallory goes around it.
        let mut impostor = Impostor::claiming(&addr("bob"), "mallorys-second-key");
        assert!(matches!(
            mallory
                .add_group_member(&gid, &addr("bob"), &impostor.key_package)
                .unwrap_err(),
            MlsError::KeyPackageAddressMismatch { .. }
        ));
        let (commit, forged_welcome) =
            add_member_bypassing_checks(&mallory, &gid, &impostor.key_package);

        // Alice refuses the commit, pre-merge.
        let err = alice
            .decrypt_from_group(
                &commit_message(&gid, &commit, &addr("mallory")),
                &addr("mallory"),
            )
            .unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::LeafAddressMismatch { ref claimed, ref context, .. }
                    if *claimed == addr("bob") && *context == crate::error::LeafSource::CommitAdd
            ),
            "expected a CommitAdd binding refusal, got {err:?}"
        );

        // Nothing moved: the epoch is unchanged and bob is not in the roster.
        let after = alice.get_group_info(&gid).unwrap().unwrap();
        assert_eq!(
            after.epoch, epoch_before,
            "a refused commit advanced the epoch"
        );
        assert!(
            !after.members.contains(&addr("bob")),
            "roster: {:?}",
            after.members
        );

        // And the leaf cannot speak. Note the mechanism here is epoch
        // divergence, not the sender-leaf check: Alice refused the commit, so
        // she never advanced to the epoch the impostor is sealing at. That is
        // the honest consequence of refusing, and it is what a real victim
        // experiences — the identity seam itself, on a leaf that *did* reach
        // the tree, is covered by
        // `test_forged_leaf_seated_behind_the_gates_still_cannot_speak`.
        impostor.join(&forged_welcome);
        let forged = impostor.encrypt(b"send me the recovery phrase");
        assert!(
            alice
                .decrypt_from_group(&app_message(&gid, forged, &addr("bob")), &addr("bob"))
                .is_err(),
            "a forged leaf's message was delivered"
        );
    }

    /// The same forgery placed in a Welcome's ratchet tree, which is the
    /// cheaper attack: it needs no existing group, only that the victim accept
    /// one invite from anyone.
    #[test]
    fn test_welcome_carrying_a_forged_leaf_is_refused() {
        let mallory = create_test_manager("mallory");
        let alice = create_test_manager("alice");

        let gid = mallory.create_group("Team").unwrap().group_id;
        let impostor = Impostor::claiming(&addr("bob"), "mallorys-second-key");
        add_member_bypassing_checks(&mallory, &gid, &impostor.key_package);

        // Now invite Alice into the poisoned room.
        let alice_kp = alice.generate_key_package().unwrap();
        let (welcome, _) = mallory
            .add_group_member(&gid, &addr("alice"), &alice_kp.key_package_data)
            .unwrap();

        let err = alice.join_group(&welcome).unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::LeafAddressMismatch { ref claimed, ref context, .. }
                    if *claimed == addr("bob") && *context == crate::error::LeafSource::WelcomeTree
            ),
            "expected a WelcomeTree binding refusal, got {err:?}"
        );

        // The refusal precedes `into_group`, so nothing was installed.
        assert!(alice.get_group_info(&gid).unwrap().is_none());
    }

    /// A forged leaf in a *session* Welcome, refused on the same path.
    ///
    /// `join_session` routes through `join_group_replacing`, whose reject must
    /// also leave any pre-existing session at that slot untouched.
    #[test]
    fn test_session_welcome_carrying_a_forged_leaf_is_refused_non_destructively() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");
        let mallory = create_test_manager("mallory");

        // Bob has a real session with Alice.
        let bob_kp = bob.generate_key_package().unwrap();
        alice
            .import_key_package(&addr("bob"), &bob_kp.key_package_data)
            .unwrap();
        bob.join_session(&alice.create_session(&addr("bob")).unwrap())
            .unwrap();
        assert!(bob.has_session(&addr("alice")).unwrap());

        // Mallory builds a session slot with Bob, then splices a third leaf
        // claiming carol into it before sending the Welcome.
        let bob_kp2 = bob.generate_key_package().unwrap();
        let slot_id = slot("bob", "mallory");
        let cred = mallory.get_credential().unwrap();
        let signer = mallory.get_signer().unwrap();
        mallory
            .group_manager
            .create_group(&slot_id, &cred, &signer)
            .unwrap();
        let impostor = Impostor::claiming(&addr("carol"), "mallorys-second-key");
        add_member_bypassing_checks(&mallory, &slot_id, &impostor.key_package);
        let (welcome, _) = mallory
            .add_group_member(&slot_id, &addr("bob"), &bob_kp2.key_package_data)
            .unwrap();

        let err = bob.join_session(&welcome).unwrap_err();
        assert!(
            matches!(err, MlsError::LeafAddressMismatch { ref context, .. }
                if *context == crate::error::LeafSource::WelcomeTree),
            "expected a WelcomeTree binding refusal, got {err:?}"
        );

        // Bob's real session with Alice is intact and still works.
        assert!(bob.has_session(&addr("alice")).unwrap());
        let ct = bob
            .encrypt_for_user(&addr("alice"), b"still private")
            .unwrap();
        assert_eq!(
            alice
                .decrypt_from_user(&ct, &addr("bob"))
                .unwrap()
                .as_deref(),
            Some(&b"still private"[..])
        );
    }

    /// The use-time half, which is the only one that covers a leaf the entry
    /// gates never saw.
    ///
    /// Installs the poisoned group by staging the Welcome straight into the
    /// provider — the shape a direct write to the install-scoped store leaves,
    /// and the reason the binding is re-checked at decrypt rather than trusted
    /// from join time.
    #[test]
    fn test_forged_leaf_seated_behind_the_gates_still_cannot_speak() {
        let mallory = create_test_manager("mallory");
        let alice = create_test_manager("alice");

        let gid = mallory.create_group("Team").unwrap().group_id;
        let mut impostor = Impostor::claiming(&addr("bob"), "mallorys-second-key");
        let (_, forged_welcome) =
            add_member_bypassing_checks(&mallory, &gid, &impostor.key_package);
        impostor.join(&forged_welcome);

        let alice_kp = alice.generate_key_package().unwrap();
        let (welcome, add_alice_commit) = mallory
            .add_group_member(&gid, &addr("alice"), &alice_kp.key_package_data)
            .unwrap();
        // The forged leaf has to follow the group to Alice's epoch, or its
        // message fails as a stale generation instead of on its identity.
        impostor.merge_commit(&add_alice_commit.ciphertext);

        // Bypass `join_group` entirely: stage and install directly, as a
        // tampered store (or a build predating the gates) would leave things.
        let bytes = welcome.welcome_data.clone();
        let staged_welcome = match MlsMessageIn::tls_deserialize_exact(&bytes)
            .unwrap()
            .extract()
        {
            MlsMessageBodyIn::Welcome(w) => w,
            _ => panic!("not a welcome"),
        };
        let cfg = MlsGroupJoinConfig::builder()
            .use_ratchet_tree_extension(true)
            .build();
        let group = StagedWelcome::new_from_welcome(&alice.provider, &cfg, staged_welcome, None)
            .unwrap()
            .into_group(&alice.provider)
            .unwrap();
        alice.group_manager.save_group(&gid, &group).unwrap();

        // Premise: the forged leaf really is seated in Alice's tree.
        assert!(
            group
                .members()
                .any(|m| m.credential.serialized_content() == addr("bob").as_bytes()),
            "test premise: the forged leaf must be installed"
        );

        // The message is still refused, at the sender-leaf seam.
        let forged = impostor.encrypt(b"send me the recovery phrase");
        let err = alice
            .decrypt_from_group(&app_message(&gid, forged, &addr("bob")), &addr("bob"))
            .unwrap_err();
        assert!(
            matches!(err, MlsError::LeafAddressMismatch { ref context, .. }
                if *context == crate::error::LeafSource::MessageSender),
            "expected a MessageSender binding refusal, got {err:?}"
        );

        // And the roster read skips it rather than reporting a member that
        // proved nothing.
        let info = alice.get_group_info(&gid).unwrap().unwrap();
        assert!(
            !info.members.contains(&addr("bob")),
            "roster surfaced an unproven member: {:?}",
            info.members
        );
        assert!(
            info.members.contains(&addr("mallory")),
            "{:?}",
            info.members
        );
    }

    /// A member renaming *their own* leaf to someone else's address, refused.
    ///
    /// The cheapest form of the attack, and the one an Add-only reading of the
    /// fix would have missed entirely: no new leaf, no key package, no invite.
    /// A member already in the group commits a self-update whose new credential
    /// names a different member, and from then on every message from their leaf
    /// is attributed to that member. MLS permits the credential change — RFC
    /// 9420 §5.3.1 says an Update may carry a new credential and leaves the
    /// verdict to the Authentication Service, which is this.
    ///
    /// This is the `CommitPath` source, the first entry in OpenMLS's own
    /// `credentials_to_verify` and the reason the commit walk follows that
    /// enumeration rather than the book's shorter "add & update proposals".
    #[test]
    fn test_member_renaming_their_own_leaf_to_a_peers_address_is_refused() {
        // `create_test_group_with_bob` seats alice as creator and bob as
        // member; bob is the insider here, renaming his own leaf to alice's
        // address.
        let (alice, bob, gid) = create_test_group_with_bob();
        let epoch_before = alice.get_group_info(&gid).unwrap().unwrap().epoch;

        let mut group = bob.group_manager.load_group(&gid).unwrap().unwrap();
        let signer = bob.get_signer().unwrap();
        let forged = CredentialWithKey {
            // Claims alice, signed by bob's own key — which is the whole point:
            // the leaf is genuinely his, the name on it is not.
            credential: Credential::new(CredentialType::Basic, addr("alice").as_bytes().to_vec()),
            signature_key: signer.public().into(),
        };
        let params = LeafNodeParameters::builder()
            .with_credential_with_key(forged)
            .build();
        let bundle = group
            .self_update(&bob.provider, &signer, params)
            .expect("MLS permits a credential change; the AS is what refuses it");
        group.merge_pending_commit(&bob.provider).unwrap();
        bob.group_manager.save_group(&gid, &group).unwrap();
        let (commit, _, _) = bundle.into_contents();

        let err = alice
            .decrypt_from_group(&commit_message(&gid, &commit, &addr("bob")), &addr("bob"))
            .unwrap_err();
        assert!(
            matches!(
                err,
                MlsError::LeafAddressMismatch { ref claimed, ref context, .. }
                    if *claimed == addr("alice") && *context == crate::error::LeafSource::CommitPath
            ),
            "expected a CommitPath binding refusal, got {err:?}"
        );

        // Not merged: alice's epoch is untouched and her roster still names bob
        // as bob.
        let after = alice.get_group_info(&gid).unwrap().unwrap();
        assert_eq!(after.epoch, epoch_before);
        assert!(after.members.contains(&addr("bob")), "{:?}", after.members);
        assert_eq!(
            after
                .members
                .iter()
                .filter(|m| **m == addr("alice"))
                .count(),
            1,
            "alice must appear once, as herself: {:?}",
            after.members
        );
    }

    /// A nickname credential must be refused, not waved through for having no
    /// derivation to check — the bypass every other gate in this SDK names.
    #[test]
    fn test_leaf_with_a_nickname_credential_is_refused() {
        let mallory = create_test_manager("mallory");
        let alice = create_test_manager("alice");
        let alice_kp = alice.generate_key_package().unwrap();

        let gid = mallory.create_group("Team").unwrap().group_id;
        let impostor = Impostor::claiming("bob", "mallorys-second-key");
        add_member_bypassing_checks(&mallory, &gid, &impostor.key_package);
        let (welcome, _) = mallory
            .add_group_member(&gid, &addr("alice"), &alice_kp.key_package_data)
            .unwrap();

        let err = alice.join_group(&welcome).unwrap_err();
        assert!(
            matches!(err, MlsError::LeafAddressMismatch { ref claimed, .. } if claimed == "bob"),
            "a nickname credential was accepted or misreported: {err:?}"
        );
    }

    /// The honest paths this check could plausibly break, pinned.
    ///
    /// `update_keys` rotates the leaf's HPKE keys through the commit's update
    /// path but keeps the signature key and credential
    /// (`LeafNodeParameters::default()`). If that ever changed — or if someone
    /// reached for `self_update_with_new_signer` — every member would start
    /// refusing every honest key rotation, and this is what says so.
    #[test]
    fn test_key_rotation_and_ordinary_traffic_still_pass_the_binding() {
        let (alice, bob, gid) = create_test_group_with_bob();

        let commit = alice.update_keys(&gid).unwrap();
        bob.decrypt_from_group(&commit, &addr("alice"))
            .expect("an honest key rotation must still merge");

        let ct = alice.encrypt_for_group(&gid, b"after rotation").unwrap();
        assert_eq!(
            bob.decrypt_from_group(&ct, &addr("alice"))
                .unwrap()
                .as_deref(),
            Some(&b"after rotation"[..])
        );

        // And a member added the ordinary way is in both rosters.
        assert!(bob
            .get_group_info(&gid)
            .unwrap()
            .unwrap()
            .members
            .contains(&addr("bob")));
    }

    /// The Welcome-side mirror of the `ExternalSenders` refusal.
    ///
    /// The commit gate refuses a proposal that would *add* the extension; a
    /// group created with one already in its context arrives this way instead,
    /// and the two entry gates should not differ by which route the inviter
    /// took. Mallory merges the extension into her own group first, so the
    /// Welcome she then sends carries it in the group context.
    #[test]
    fn test_welcome_whose_group_context_has_external_senders_is_refused() {
        let mallory = create_test_manager("mallory");
        let alice = create_test_manager("alice");

        let gid = mallory.create_group("Team").unwrap().group_id;

        // Merge an ExternalSenders extension into mallory's own group context.
        {
            let mut group = mallory.group_manager.load_group(&gid).unwrap().unwrap();
            let signer = mallory.get_signer().unwrap();
            let outsider =
                SignatureKeyPair::new(DEFAULT_CIPHERSUITE.signature_algorithm()).unwrap();
            let external = ExternalSender::new(
                outsider.public().into(),
                Credential::new(CredentialType::Basic, b"off1outsider".to_vec()),
            );
            group
                .commit_builder()
                .propose_group_context_extensions(Extensions::single(Extension::ExternalSenders(
                    vec![external],
                )))
                .load_psks(mallory.provider.storage())
                .unwrap()
                .build(
                    mallory.provider.rand(),
                    mallory.provider.crypto(),
                    &signer,
                    |_| true,
                )
                .unwrap()
                .stage_commit(&mallory.provider)
                .unwrap();
            group.merge_pending_commit(&mallory.provider).unwrap();
            mallory.group_manager.save_group(&gid, &group).unwrap();
        }

        let alice_kp = alice.generate_key_package().unwrap();
        let (welcome, _) = mallory
            .add_group_member(&gid, &addr("alice"), &alice_kp.key_package_data)
            .unwrap();

        let err = alice.join_group(&welcome).unwrap_err();
        assert!(
            matches!(err, MlsError::UnsupportedSender { ref detail, .. }
                if detail.contains("ExternalSenders")),
            "expected the invite to be declined for its ExternalSenders context, got {err:?}"
        );
        assert!(
            alice.get_group_info(&gid).unwrap().is_none(),
            "a declined Welcome must not install the group"
        );
    }

    /// Source 4 of the commit walk: a commit proposing an `ExternalSenders`
    /// group-context extension is refused.
    ///
    /// Not a leaf, so there is no binding to check — which is exactly why it
    /// needs its own arm rather than falling off the end of the walk. The
    /// extension authorizes a non-member to send into the group, and its
    /// credential would never be judged by any of the three leaf seams.
    /// Untested, this arm survives deletion.
    #[test]
    fn test_commit_proposing_external_senders_is_refused() {
        let (alice, mallory, gid) = create_test_group_with_bob();

        let mut group = mallory.group_manager.load_group(&gid).unwrap().unwrap();
        let signer = mallory.get_signer().unwrap();

        // An ExternalSenders extension naming a party that is in no leaf.
        let outsider = SignatureKeyPair::new(DEFAULT_CIPHERSUITE.signature_algorithm()).unwrap();
        let external = ExternalSender::new(
            outsider.public().into(),
            Credential::new(CredentialType::Basic, b"off1outsider".to_vec()),
        );
        let extensions = Extensions::single(Extension::ExternalSenders(vec![external]));

        let bundle = group
            .commit_builder()
            .propose_group_context_extensions(extensions)
            .load_psks(mallory.provider.storage())
            .unwrap()
            .build(
                mallory.provider.rand(),
                mallory.provider.crypto(),
                &signer,
                |_| true,
            )
            .unwrap()
            .stage_commit(&mallory.provider)
            .unwrap();
        let (commit, _, _) = bundle.into_contents();

        let err = alice
            .decrypt_from_group(&commit_message(&gid, &commit, &addr("bob")), &addr("bob"))
            .unwrap_err();
        assert!(
            matches!(err, MlsError::UnsupportedSender { ref detail, .. }
                if detail.contains("ExternalSenders")),
            "expected an ExternalSenders refusal, got {err:?}"
        );
    }

    /// Why `remove_group_member`'s loop can never find a second leaf — and why
    /// it is a loop anyway.
    ///
    /// The duplicate it would guard against is refused a layer down: RFC 9420
    /// requires unique signature keys across a group, so seating one identity
    /// twice is rejected by OpenMLS before the roster ever sees it. Pinned as a
    /// test because the *removal* code's correctness rests on it, and it is an
    /// invariant enforced in another crate — exactly the kind that changes
    /// without anyone here noticing.
    #[test]
    fn test_one_identity_cannot_hold_two_leaves_in_a_group() {
        let alice = create_test_manager("alice");
        let bob = create_test_manager("bob");

        let gid = alice.create_group("Team").unwrap().group_id;
        let first = bob.generate_key_package().unwrap();
        alice
            .add_group_member(&gid, &addr("bob"), &first.key_package_data)
            .unwrap();

        // A second, distinct key package for the same identity: different init
        // key, same signature key, because the signature key *is* the identity.
        let second = bob.generate_key_package().unwrap();
        assert_ne!(first.package_id, second.package_id);
        let err = alice
            .add_group_member(&gid, &addr("bob"), &second.key_package_data)
            .unwrap_err();
        assert!(
            matches!(err, MlsError::AddMember(ref m) if m.contains("Duplicate signature key")),
            "expected MLS to refuse a duplicate signature key, got {err:?}"
        );

        // One leaf, and removing it removes the member.
        alice.remove_group_member(&gid, &addr("bob")).unwrap();
        assert!(!alice
            .get_group_info(&gid)
            .unwrap()
            .unwrap()
            .members
            .contains(&addr("bob")));
    }

    /// A non-`Member` sender is refused, not ignored.
    ///
    /// `verify_sender_leaf` covers four sender shapes and only one of them —
    /// `Sender::Member` — resolves to a leaf that can be bound. The other three
    /// take the `UnsupportedSender` arm, and this is the one of them that is
    /// cheap to build: an external join proposal, authenticated to
    /// `Sender::NewMemberProposal`, whose leaf is by definition in no tree yet.
    ///
    /// Worth its own test because the arm *changed disposition* in this change.
    /// It used to fall through to `ProcessedMessageContent::
    /// ExternalJoinProposalMessage` and be tolerated as `Ok(None)`; the same
    /// tolerance applied to a `NewMemberCommit` would have *merged* a commit
    /// from a party holding an unjudged leaf. Nothing else pins that the
    /// tolerance is gone — the surviving `ExternalJoinProposalMessage` arm still
    /// reads like the policy, and its comment says it is not.
    #[test]
    fn test_external_join_proposal_is_refused_as_an_unsupported_sender() {
        let (alice, _bob, gid) = create_test_group_with_bob();

        // An outsider asks to join. The proposal is well-formed and correctly
        // signed by its own key — it is refused for its *sender role*, not for
        // anything malformed, which is the point.
        let outsider = create_test_manager("mallory");
        let kp_bytes = outsider.generate_key_package().unwrap().key_package_data;
        let key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes)
            .unwrap()
            .validate(alice.provider.crypto(), ProtocolVersion::Mls10)
            .unwrap();
        let signer = outsider.get_signer().unwrap();

        let (mls_group_id, epoch) = {
            let group = alice.group_manager.load_group(&gid).unwrap().unwrap();
            (group.group_id().clone(), group.epoch())
        };
        let proposal =
            JoinProposal::new::<MlsStorageAdapter>(key_package, mls_group_id, epoch, &signer)
                .expect(
                    "an external join proposal is well-formed; the SDK just declines to honour it",
                );

        let err = alice
            .decrypt_from_group(
                &app_message(
                    &gid,
                    proposal.tls_serialize_detached().unwrap(),
                    &addr("mallory"),
                ),
                &addr("mallory"),
            )
            .unwrap_err();
        assert!(
            matches!(err, MlsError::UnsupportedSender { ref detail, .. }
                if detail.contains("not a group member")),
            "expected an UnsupportedSender refusal, got {err:?}"
        );
    }

    /// A leaf seated behind the gates is *counted*, not merely hidden.
    ///
    /// The roster filter is the only seam at which a leaf already in local
    /// group state surfaces, and a `warn!` reaches no app. The count is what
    /// the protocol layer turns into `GroupLeafIdentityUnproven`, so a filter
    /// that silently returned the same shortened roster would look identical
    /// here without it.
    ///
    /// Built with the in-module fixture rather than
    /// `seat_forged_leaf_for_testing`, which is behind the `test-utils` feature
    /// for the *protocol* crate's benefit: workspace feature unification turns
    /// it on for `cargo test --workspace`, but `cargo test -p
    /// offline-protocol-mls` would then not compile.
    #[test]
    fn test_roster_read_counts_the_leaves_it_skips() {
        let (alice, _bob, gid) = create_test_group_with_bob();

        let before = alice.get_group_info(&gid).unwrap().unwrap();
        assert_eq!(
            before.unproven_members, 0,
            "an honest group must report no unproven members: {:?}",
            before.members
        );
        let honest_members = before.members.len();

        // Seat a leaf claiming carol, bypassing the gates as a tampered store
        // would. Alice commits it into her own group, so it is in *her* tree.
        let impostor = Impostor::claiming(&addr("carol"), "an-attackers-key");
        add_member_bypassing_checks(&alice, &gid, &impostor.key_package);

        let after = alice.get_group_info(&gid).unwrap().unwrap();
        assert_eq!(
            after.unproven_members, 1,
            "the skipped leaf must be counted, not only dropped"
        );
        assert_eq!(
            after.members.len(),
            honest_members,
            "the roster must be unchanged: {:?}",
            after.members
        );
        assert!(
            !after.members.contains(&addr("carol")),
            "roster surfaced the unproven member: {:?}",
            after.members
        );
    }
}