openmls 0.8.1

A Rust implementation of the Messaging Layer Security (MLS) protocol, as defined in RFC 9420.
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
use std::slice::from_ref;

use mls_group::{
    tests_and_kats::utils::{flip_last_byte, setup_alice_bob, setup_alice_bob_group, setup_client},
    EncryptionKeyPair, GroupEpochSecrets, MessageSecretsStore,
};
use openmls_basic_credential::SignatureKeyPair;
use openmls_test::openmls_test;
use openmls_traits::storage::CURRENT_VERSION;
use signable::Signable;
use tls_codec::{Deserialize, Serialize};

use crate::{
    binary_tree::LeafNodeIndex,
    credentials::{test_utils::new_credential, NewSignerBundle},
    framing::*,
    group::{errors::*, *},
    key_packages::*,
    messages::{
        group_info::GroupInfoTBS, proposals::*, EncryptedGroupSecrets, GroupSecretsError, Welcome,
    },
    prelude::{
        ConfirmationTag, ExtensionTypeNotValidInLeafNodeError, InvalidExtensionError, LeafNode,
    },
    schedule::{ExternalPsk, PreSharedKeyId, Psk},
    test_utils::{
        frankenstein::{FrankenFramedContentBody, FrankenPublicMessage},
        single_group_test_framework::{AddMemberConfig, CorePartyState, GroupState},
        test_framework::{
            errors::ClientError, noop_authentication_service, ActionType::Commit, CodecUse,
            MlsGroupTestSetup,
        },
    },
    tree::sender_ratchet::SenderRatchetConfiguration,
    treesync::{
        errors::ApplyUpdatePathError, node::leaf_node::Capabilities, LeafNodeParameters, TreeSync,
    },
};

#[openmls_test]
fn test_mls_group_persistence<Provider: OpenMlsProvider>() {
    let alice_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    // Define the MlsGroup configuration
    let mls_group_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_config,
        group_id.clone(),
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    let alice_group_deserialized = MlsGroup::load(alice_provider.storage(), &group_id)
        .expect("Could not deserialize MlsGroup: error")
        .expect("Could not deserialize MlsGroup: doesn't exist");

    assert_eq!(
        (
            alice_group.export_ratchet_tree(),
            alice_group
                .export_secret(alice_provider.crypto(), "test", &[], 32)
                .unwrap()
        ),
        (
            alice_group_deserialized.export_ratchet_tree(),
            alice_group_deserialized
                .export_secret(alice_provider.crypto(), "test", &[], 32)
                .unwrap()
        )
    );
}

// This tests if the remover is correctly passed to the callback when one member
// issues a RemoveProposal and another members issues the next Commit.
#[openmls_test]
fn remover() {
    // Create separate providers for each participant to avoid storage conflicts
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let charlie_provider = &Provider::default();

    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential, bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);
    let (_charlie_credential, charlie_kpb, charlie_signer, _charlie_pk) =
        setup_client("Charly", ciphersuite, charlie_provider);

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    // Test persistence after Alice creates group
    alice_group
        .ensure_persistence(alice_provider.storage())
        .unwrap();

    // === Alice adds Bob ===
    let (_queued_message, welcome, _group_info) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_kpb.key_package()),
        )
        .expect("Could not add member to group.");

    // Test persistence after Alice adds Bob
    alice_group
        .ensure_persistence(alice_provider.storage())
        .unwrap();

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");

    // Test persistence after Alice merges commit
    alice_group
        .ensure_persistence(alice_provider.storage())
        .unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome.into_welcome().expect("expected a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");

    // Test persistence after Bob joins group
    bob_group
        .ensure_persistence(bob_provider.storage())
        .unwrap();

    // === Bob adds Charlie ===
    let (queued_messages, welcome, _group_info) = bob_group
        .add_members(
            bob_provider,
            &bob_signer,
            from_ref(charlie_kpb.key_package()),
        )
        .unwrap();

    // Test persistence after Bob adds Charlie
    bob_group
        .ensure_persistence(bob_provider.storage())
        .unwrap();

    let alice_processed_message = alice_group
        .process_message(
            alice_provider,
            queued_messages
                .into_protocol_message()
                .expect("Unexpected message type"),
        )
        .expect("Could not process messages.");
    if let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        alice_processed_message.into_content()
    {
        alice_group
            .merge_staged_commit(alice_provider, *staged_commit)
            .expect("Error merging commit.");

        // Test persistence after Alice merges Bob's staged commit
        alice_group
            .ensure_persistence(alice_provider.storage())
            .unwrap();
    } else {
        unreachable!("Expected a StagedCommit.");
    }

    bob_group
        .merge_pending_commit(bob_provider)
        .expect("error merging pending commit");

    // Test persistence after Bob merges pending commit
    bob_group
        .ensure_persistence(bob_provider.storage())
        .unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome.into_welcome().expect("expected a welcome");

    let mut charlie_group = StagedWelcome::new_from_welcome(
        charlie_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(bob_group.export_ratchet_tree().into()),
    )
    .expect("Error creating group from Welcome")
    .into_group(charlie_provider)
    .expect("Error creating group from Welcome");

    // Test persistence after Charlie joins group
    charlie_group
        .ensure_persistence(charlie_provider.storage())
        .unwrap();

    // === Alice removes Bob & Charlie commits ===

    let (queued_messages, _) = alice_group
        .propose_remove_member(alice_provider, &alice_signer, LeafNodeIndex::new(1))
        .expect("Could not propose removal");

    // Test persistence after Alice proposes removal
    alice_group
        .ensure_persistence(alice_provider.storage())
        .unwrap();

    let charlie_processed_message = charlie_group
        .process_message(
            charlie_provider,
            queued_messages
                .into_protocol_message()
                .expect("Unexpected message type"),
        )
        .expect("Could not process messages.");

    // Check that we received the correct proposals
    if let ProcessedMessageContent::ProposalMessage(staged_proposal) =
        charlie_processed_message.into_content()
    {
        if let Proposal::Remove(ref remove_proposal) = staged_proposal.proposal() {
            // Check that Bob was removed
            assert_eq!(remove_proposal.removed(), LeafNodeIndex::new(1));
            // Store proposal
            charlie_group
                .store_pending_proposal(charlie_provider.storage(), *staged_proposal.clone())
                .unwrap();

            // Test persistence after Charlie stores pending proposal
            charlie_group
                .ensure_persistence(charlie_provider.storage())
                .unwrap();
        }

        // Check that Alice removed Bob
        assert!(matches!(
            staged_proposal.sender(),
            Sender::Member(member) if member.u32() == 0
        ));
    } else {
        unreachable!("Expected a QueuedProposal.");
    }

    // Charlie commits
    let (_queued_messages, _welcome, _group_info) = charlie_group
        .commit_to_pending_proposals(charlie_provider, &charlie_signer)
        .expect("Could not commit proposal");

    // Test persistence after Charlie commits pending proposals
    charlie_group
        .ensure_persistence(charlie_provider.storage())
        .unwrap();

    // Check that we receive the correct proposal
    if let Some(staged_commit) = charlie_group.pending_commit() {
        let remove = staged_commit
            .remove_proposals()
            .next()
            .expect("Expected a proposal.");
        // Check that Bob was removed
        assert_eq!(remove.remove_proposal().removed().u32(), 1);
        // Check that Alice removed Bob
        assert!(matches!(remove.sender(), Sender::Member(member) if member.u32() == 0));
    } else {
        unreachable!("Expected a StagedCommit.");
    };

    charlie_group
        .merge_pending_commit(charlie_provider)
        .expect("error merging pending commit");
}

#[openmls_test]
fn export_secret() {
    let alice_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    assert!(
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test1",
                &[],
                ciphersuite.hash_length()
            )
            .expect("An unexpected error occurred.")
            != alice_group
                .export_secret(
                    alice_provider.crypto(),
                    "test2",
                    &[],
                    ciphersuite.hash_length()
                )
                .expect("An unexpected error occurred.")
    );
    assert!(
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[0u8],
                ciphersuite.hash_length()
            )
            .expect("An unexpected error occurred.")
            != alice_group
                .export_secret(
                    alice_provider.crypto(),
                    "test",
                    &[1u8],
                    ciphersuite.hash_length()
                )
                .expect("An unexpected error occurred.")
    )
}

#[cfg(feature = "extensions-draft-08")]
#[openmls_test]
fn safe_export_secret() {
    use crate::schedule::application_export_tree::ApplicationExportTreeError;

    let alice_party = CorePartyState::<Provider>::new("alice");
    let bob_party = CorePartyState::<Provider>::new("bob");

    let alice_pre_group = alice_party.generate_pre_group(ciphersuite);
    let bob_pre_group = bob_party.generate_pre_group(ciphersuite);

    // Create config
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build();

    // Join config
    let mls_group_join_config = mls_group_create_config.join_config().clone();

    // Initialize the group state
    let group_id = GroupId::from_slice(b"test");
    let mut group_state =
        GroupState::new_from_party(group_id, alice_pre_group, mls_group_create_config).unwrap();

    group_state
        .add_member(AddMemberConfig {
            adder: "alice",
            addees: vec![bob_pre_group],
            join_config: mls_group_join_config.clone(),
            tree: None,
        })
        .expect("Could not add member");

    let [alice_group_state, bob_group_state] = group_state.members_mut(&["alice", "bob"]);

    // Alice updates her leaf node
    let alice_commit = alice_group_state
        .group
        .self_update(
            &alice_group_state.party.core_state.provider,
            &alice_group_state.party.signer,
            LeafNodeParameters::default(),
        )
        .expect("Could not create self update");
    // Safely export from the pending commit
    let alice_application_secret = alice_group_state
        .group
        .safe_export_secret_from_pending(
            alice_group_state.party.core_state.provider.crypto(),
            alice_group_state.party.core_state.provider.storage(),
            0x8000,
        )
        .expect("Could not export secret");

    alice_group_state
        .group
        .merge_pending_commit(&alice_group_state.party.core_state.provider)
        .unwrap();
    let component_id = 0x8000;

    // Bob processes the update
    let processed_message = bob_group_state
        .group
        .process_message(
            &bob_group_state.party.core_state.provider,
            MlsMessageIn::from(alice_commit.into_commit())
                .into_protocol_message()
                .unwrap(),
        )
        .unwrap();

    let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        processed_message.into_content()
    else {
        panic!("Expected a StagedCommitMessage");
    };

    bob_group_state
        .group
        .merge_staged_commit(&bob_group_state.party.core_state.provider, *staged_commit)
        .unwrap();

    let bob_application_secret = bob_group_state
        .group
        .safe_export_secret(
            bob_group_state.party.core_state.provider.crypto(),
            bob_group_state.party.core_state.provider.storage(),
            component_id,
        )
        .unwrap();

    assert_eq!(alice_application_secret, bob_application_secret);

    // Trying with a different component ID (should yield a different secret)
    let differing_component_id = 0x8001;
    let alice_differing_application_secret = alice_group_state
        .group
        .safe_export_secret(
            alice_group_state.party.core_state.provider.crypto(),
            alice_group_state.party.core_state.provider.storage(),
            differing_component_id,
        )
        .unwrap();
    assert_ne!(alice_application_secret, alice_differing_application_secret);

    // Trying with the same component ID for the second time (should fail)
    let error = alice_group_state
        .group
        .safe_export_secret(
            alice_group_state.party.core_state.provider.crypto(),
            alice_group_state.party.core_state.provider.storage(),
            component_id,
        )
        .expect_err("Expected an error when exporting the same component ID twice");
    assert!(matches!(
        error,
        SafeExportSecretError::ApplicationExportTree(ApplicationExportTreeError::PuncturedInput)
    ));
}

#[openmls_test]
fn staged_join() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential, bob_kpb, _bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    let (_queued_message, welcome, _group_info) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_kpb.key_package()),
        )
        .expect("Could not add member to group.");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("couldn't merge commit that adds bob");

    let join_config = mls_group_create_config.join_config();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome.into_welcome().expect("expected a welcome");

    let staged_bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        join_config,
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("error creating staged mls group");

    let welcome_sender = staged_bob_group
        .welcome_sender()
        .expect("couldn't determine sender of welcome");

    assert_eq!(
        welcome_sender.credential(),
        alice_kpb.key_package().leaf_node().credential()
    );

    let bob_group = staged_bob_group
        .into_group(bob_provider)
        .expect("error turning StagedWelcome into MlsGroup");

    assert_eq!(
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .expect("An unexpected error occurred."),
        bob_group
            .export_secret(
                bob_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .expect("An unexpected error occurred.")
    );
}

#[openmls_test]
fn test_invalid_plaintext() {
    // Some basic setup functions for the MlsGroup.
    let mls_group_create_config = MlsGroupCreateConfig::test_default(ciphersuite);

    let number_of_clients = 20;
    let setup = MlsGroupTestSetup::<Provider>::new(
        mls_group_create_config,
        number_of_clients,
        CodecUse::StructMessages,
    );
    // Create a basic group with more than 4 members to create a tree with intermediate nodes.
    let group_id = setup
        .create_random_group(10, ciphersuite, noop_authentication_service)
        .expect("An unexpected error occurred.");
    let mut groups = setup.groups.write().expect("An unexpected error occurred.");
    let group = groups
        .get_mut(&group_id)
        .expect("An unexpected error occurred.");

    let (_, client_id) = &group
        .members()
        .find(|(index, _)| index == &0)
        .expect("An unexpected error occurred.");

    let clients = setup.clients.read().expect("An unexpected error occurred.");
    let client = clients
        .get(client_id)
        .expect("An unexpected error occurred.")
        .read()
        .expect("An unexpected error occurred.");

    let (mls_message, _welcome_option, _group_info) = client
        .self_update(Commit, &group_id, LeafNodeParameters::default())
        .expect("error creating self update");

    // Store the context and membership key so that we can re-compute the membership tag later.
    let client_groups = client.groups.read().unwrap();
    let client_group = client_groups.get(&group_id).unwrap();
    let membership_key = client_group.message_secrets().membership_key();

    // Tamper with the message such that signature verification fails
    // Once #574 is addressed the new function from there should be used to manipulate the signature.
    // Right now the membership tag is verified first, wihich yields `VerificationError::InvalidMembershipTag`
    // error instead of a `CredentialError:InvalidSignature`.
    let mut msg_invalid_signature = mls_message.clone();
    if let MlsMessageBodyOut::PublicMessage(ref mut pt) = msg_invalid_signature.body {
        pt.invalidate_signature()
    };

    // Tamper with the message such that sender lookup fails
    let mut msg_invalid_sender = mls_message;
    let random_sender = Sender::build_member(LeafNodeIndex::new(987543210));
    match &mut msg_invalid_sender.body {
        MlsMessageBodyOut::PublicMessage(pt) => {
            pt.set_sender(random_sender);
            pt.set_membership_tag(
                client.provider.crypto(),
                ciphersuite,
                membership_key,
                client_group.message_secrets().serialized_context(),
            )
            .unwrap()
        }
        _ => panic!("This should be a plaintext!"),
    };

    drop(client_groups);
    drop(client);
    drop(clients);

    let error = setup
        // We're the "no_client" id to prevent the original sender from treating
        // this message as his own and merging the pending commit.
        .distribute_to_members(
            "no_client".as_bytes(),
            group,
            &msg_invalid_signature.into(),
            &noop_authentication_service,
        )
        .expect_err("No error when distributing message with invalid signature.");

    assert_eq!(
        ClientError::ProcessMessageError(ProcessMessageError::ValidationError(
            ValidationError::InvalidMembershipTag
        )),
        error
    );

    let error = setup
        // We're the "no_client" id to prevent the original sender from treating
        // this message as his own and merging the pending commit.
        .distribute_to_members(
            "no_client".as_bytes(),
            group,
            &msg_invalid_sender.into(),
            &noop_authentication_service,
        )
        .expect_err("No error when distributing message with invalid signature.");

    assert_eq!(
        ClientError::ProcessMessageError(ProcessMessageError::ValidationError(
            ValidationError::UnknownMember
        )),
        error
    );
}

#[openmls_test]
fn test_verify_staged_commit_credentials() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential, bob_kpb, _bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    // Define the MlsGroup configuration
    let mls_group_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_config,
        group_id,
        alice_credential_with_key.clone(),
    )
    .expect("An unexpected error occurred.");

    // There should be no pending commit after group creation.
    assert!(alice_group.pending_commit().is_none());

    let bob_key_package = bob_kpb.key_package();

    // === Alice adds Bob to the group ===
    let (proposal, _) = alice_group
        .propose_add_member(alice_provider, &alice_signer, bob_key_package)
        .expect("error creating self-update proposal");

    let alice_processed_message = alice_group
        .process_message(alice_provider, proposal.into_protocol_message().unwrap())
        .expect("Could not process messages.");
    assert!(alice_group.pending_commit().is_none());

    if let ProcessedMessageContent::ProposalMessage(staged_proposal) =
        alice_processed_message.into_content()
    {
        alice_group
            .store_pending_proposal(alice_provider.storage(), *staged_proposal)
            .unwrap();
    } else {
        unreachable!("Expected a StagedCommit.");
    }

    let (_msg, welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();

    // Merging the pending commit should clear the pending commit and we should
    // end up in the same state as bob.
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");
    assert!(alice_group.pending_commit().is_none());
    assert!(alice_group.pending_proposals().next().is_none());

    let welcome: MlsMessageIn = welcome_option.expect("expected a welcome").into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("error creating group from welcome")
    .into_group(bob_provider)
    .expect("error creating group from welcome");

    assert_eq!(
        bob_group.export_ratchet_tree(),
        alice_group.export_ratchet_tree()
    );
    assert_eq!(
        bob_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap(),
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap()
    );
    // Bob is added and the state aligns.

    // === Make a new, empty commit and check that the leaf node credentials match ===
    let (commit_msg, _welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_contents();

    // empty commits should only produce a single message
    assert!(_welcome_option.is_none());
    assert!(_group_info.is_none());

    // There should be a pending commit after issuing a self-update commit.
    let alice_pending_commit = alice_group
        .pending_commit()
        .expect("alice should have the self-update as pending commit");

    // The commit contains only Alice's credentials, in the update path leaf node.
    for cred in alice_pending_commit.credentials_to_verify() {
        assert_eq!(cred, &alice_credential_with_key.credential);
    }

    // great, they match! now commit
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("alice failed to merge the pending empty commit");

    // === transfer message to bob and process it ===

    // this requires serializing and deserializing
    let mut wire_msg = Vec::<u8>::new();
    commit_msg
        .tls_serialize(&mut wire_msg)
        .expect("alice failed serializing her message");
    let msg_in = MlsMessageIn::tls_deserialize(&mut &wire_msg[..])
        .expect("bob failed deserializing alice's message");

    // neither party should have pending proposals
    assert!(alice_group.pending_proposals().next().is_none());
    assert!(bob_group.pending_proposals().next().is_none());

    // neither should have pending commits after merging and before processing
    assert!(bob_group.pending_commit().is_none());
    assert!(alice_group.pending_commit().is_none());

    // further process the deserialized message
    let processed_message = bob_group
        .process_message(bob_provider, msg_in.try_into_protocol_message().unwrap())
        .expect("bob failed processing alice's message");

    // the processed message must be a staged commit message
    assert!(matches!(
        processed_message.content(),
        ProcessedMessageContent::StagedCommitMessage(_)
    ));

    if let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        processed_message.into_content()
    {
        // The commit contains only Alice's credentials, in the update path leaf node.
        for cred in staged_commit.credentials_to_verify() {
            assert_eq!(cred, &alice_credential_with_key.credential);
        }

        // bob merges alice's message
        bob_group
            .merge_staged_commit(bob_provider, *staged_commit)
            .expect("bob failed merging alice's empty commit (staged)");

        // finally, the state should match
        assert_eq!(
            bob_group.export_ratchet_tree(),
            alice_group.export_ratchet_tree()
        );
        assert_eq!(
            bob_group
                .export_secret(
                    bob_provider.crypto(),
                    "test",
                    &[],
                    ciphersuite.hash_length()
                )
                .unwrap(),
            alice_group
                .export_secret(
                    alice_provider.crypto(),
                    "test",
                    &[],
                    ciphersuite.hash_length()
                )
                .unwrap()
        );
    } else {
        unreachable!()
    }

    // neither should have pending commits after merging and processing
    assert!(bob_group.pending_commit().is_none());
    assert!(alice_group.pending_commit().is_none());
}

#[openmls_test]
fn test_commit_with_update_path_leaf_node() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();

    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential, bob_kpb, _bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key.clone(),
    )
    .expect("An unexpected error occurred.");

    // There should be no pending commit after group creation.
    assert!(alice_group.pending_commit().is_none());

    let bob_key_package = bob_kpb.key_package();

    // === Alice adds Bob to the group ===
    let (proposal, _) = alice_group
        .propose_add_member(alice_provider, &alice_signer, bob_key_package)
        .expect("error creating self-update proposal");

    let alice_processed_message = alice_group
        .process_message(alice_provider, proposal.into_protocol_message().unwrap())
        .expect("Could not process messages.");
    assert!(alice_group.pending_commit().is_none());

    if let ProcessedMessageContent::ProposalMessage(staged_proposal) =
        alice_processed_message.into_content()
    {
        alice_group
            .store_pending_proposal(alice_provider.storage(), *staged_proposal)
            .unwrap();
    } else {
        unreachable!("Expected a StagedCommit.");
    }

    println!("\nCreating commit with add proposal.");
    let (_msg, welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();
    println!("Done creating commit.");

    // Merging the pending commit should clear the pending commit and we should
    // end up in the same state as bob.
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");
    assert!(alice_group.pending_commit().is_none());
    assert!(alice_group.pending_proposals().next().is_none());

    let welcome: MlsMessageIn = welcome_option.expect("expected a welcome").into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("error creating group from welcome")
    .into_group(bob_provider)
    .expect("error creating group from welcome");

    assert_eq!(
        bob_group.export_ratchet_tree(),
        alice_group.export_ratchet_tree()
    );
    assert_eq!(
        bob_group
            .export_secret(
                bob_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap(),
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap()
    );
    // Bob is added and the state aligns.

    // === Make a new, empty commit and check that the leaf node credentials match ===

    println!("\nCreating self-update commit.");
    let (commit_msg, _welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();
    println!("Done creating commit.");

    // empty commits should only produce a single message
    assert!(_welcome_option.is_none());
    assert!(_group_info.is_none());

    // There should be a pending commit after issuing a self-update commit.
    let alice_pending_commit = alice_group
        .pending_commit()
        .expect("alice should have the self-update as pending commit");

    // The credential on the update_path leaf node should be set and be the same as alice's
    // credential
    let alice_update_path_leaf_node = alice_pending_commit
        .update_path_leaf_node()
        .expect("expected alice's staged commit to have an update path");
    assert_eq!(
        alice_update_path_leaf_node.credential(),
        &alice_credential_with_key.credential
    );

    // great, they match! now commit
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("alice failed to merge the pending empty commit");

    // === transfer message to bob and process it ===

    // this requires serializing and deserializing
    let mut wire_msg = Vec::<u8>::new();
    commit_msg
        .tls_serialize(&mut wire_msg)
        .expect("alice failed serializing her message");
    let msg_in = MlsMessageIn::tls_deserialize(&mut &wire_msg[..])
        .expect("bob failed deserializing alice's message");

    // neither party should have pending proposals
    assert!(alice_group.pending_proposals().next().is_none());
    assert!(bob_group.pending_proposals().next().is_none());

    // neither should have pending commits after merging and before processing
    assert!(bob_group.pending_commit().is_none());
    assert!(alice_group.pending_commit().is_none());

    // further process the deserialized message
    let processed_message = bob_group
        .process_message(bob_provider, msg_in.try_into_protocol_message().unwrap())
        .expect("bob failed processing alice's message");

    // the processed message must be a staged commit message
    assert!(matches!(
        processed_message.content(),
        ProcessedMessageContent::StagedCommitMessage(_)
    ));

    if let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        processed_message.into_content()
    {
        // bob must check the credential in the leaf node of the update_path of alice's commit
        let bob_update_path_leaf_node = staged_commit
            .update_path_leaf_node()
            .expect("staged commit received by bob should carry an update path with a leaf node");
        assert_eq!(
            bob_update_path_leaf_node.credential(),
            &alice_credential_with_key.credential
        );

        // bob merges alice's message
        bob_group
            .merge_staged_commit(bob_provider, *staged_commit)
            .expect("bob failed merging alice's empty commit (staged)");

        // finally, the state should match
        assert_eq!(
            bob_group.export_ratchet_tree(),
            alice_group.export_ratchet_tree()
        );
        assert_eq!(
            bob_group
                .export_secret(
                    alice_provider.crypto(),
                    "test",
                    &[],
                    ciphersuite.hash_length()
                )
                .unwrap(),
            alice_group
                .export_secret(
                    alice_provider.crypto(),
                    "test",
                    &[],
                    ciphersuite.hash_length()
                )
                .unwrap()
        );
    } else {
        unreachable!()
    }

    // neither should have pending commits after merging and processing
    assert!(bob_group.pending_commit().is_none());
    assert!(alice_group.pending_commit().is_none());
}

#[openmls_test]
fn test_pending_commit_logic() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential, bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::test_default(ciphersuite);

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    // There should be no pending commit after group creation.
    assert!(alice_group.pending_commit().is_none());

    let bob_key_package = bob_kpb.key_package();

    // Let's add bob
    let (proposal, _) = alice_group
        .propose_add_member(bob_provider, &alice_signer, bob_key_package)
        .expect("error creating add-bob proposal");

    let alice_processed_message = alice_group
        .process_message(bob_provider, proposal.into_protocol_message().unwrap())
        .expect("Could not process messages.");
    assert!(alice_group.pending_commit().is_none());

    if let ProcessedMessageContent::ProposalMessage(staged_proposal) =
        alice_processed_message.into_content()
    {
        alice_group
            .store_pending_proposal(alice_provider.storage(), *staged_proposal)
            .unwrap();
    } else {
        unreachable!("Expected a StagedCommit.");
    }

    // There should be no pending commit after issuing and processing a proposal.
    assert!(alice_group.pending_commit().is_none());

    println!("\nCreating commit with add proposal.");
    let (_msg, _welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();
    println!("Done creating commit.");

    // There should be a pending commit after issueing a proposal.
    assert!(alice_group.pending_commit().is_some());

    // If there is a pending commit, other commit- or proposal-creating actions
    // should fail.
    let error = alice_group
        .add_members(alice_provider, &alice_signer, from_ref(bob_key_package))
        .expect_err("no error committing while a commit is pending");
    assert!(matches!(
        error,
        AddMembersError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .propose_add_member(alice_provider, &alice_signer, bob_key_package)
        .expect_err("no error creating a proposal while a commit is pending");
    assert!(matches!(
        error,
        ProposeAddMemberError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .remove_members(alice_provider, &alice_signer, &[LeafNodeIndex::new(1)])
        .expect_err("no error committing while a commit is pending");
    assert!(matches!(
        error,
        RemoveMembersError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .propose_remove_member(alice_provider, &alice_signer, LeafNodeIndex::new(1))
        .expect_err("no error creating a proposal while a commit is pending");
    assert!(matches!(
        error,
        ProposeRemoveMemberError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .commit_to_pending_proposals(alice_provider, &alice_signer)
        .expect_err("no error committing while a commit is pending");
    assert!(matches!(
        error,
        CommitToPendingProposalsError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect_err("no error committing while a commit is pending");
    assert!(matches!(
        error,
        SelfUpdateError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));
    let error = alice_group
        .propose_self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect_err("no error creating a proposal while a commit is pending");
    assert!(matches!(
        error,
        ProposeSelfUpdateError::GroupStateError(MlsGroupStateError::PendingCommit)
    ));

    // Clearing the pending commit should actually clear it.
    alice_group
        .clear_pending_commit(alice_provider.storage())
        .unwrap();
    assert!(alice_group.pending_commit().is_none());

    // Creating a new commit should commit the same proposals.
    let (_msg, welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();

    // Merging the pending commit should clear the pending commit and we should
    // end up in the same state as bob.
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");
    assert!(alice_group.pending_commit().is_none());

    let welcome: MlsMessageIn = welcome_option.expect("expected a welcome").into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("error creating group from welcome")
    .into_group(bob_provider)
    .expect("error creating group from welcome");

    assert_eq!(
        bob_group.export_ratchet_tree(),
        alice_group.export_ratchet_tree()
    );
    assert_eq!(
        bob_group
            .export_secret(
                bob_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap(),
        alice_group
            .export_secret(
                alice_provider.crypto(),
                "test",
                &[],
                ciphersuite.hash_length()
            )
            .unwrap()
    );

    // While a commit is pending, merging Bob's commit should clear the pending commit.
    let (_msg, _welcome_option, _group_info) = alice_group
        .self_update(alice_provider, &alice_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();

    let (msg, _welcome_option, _group_info) = bob_group
        .self_update(bob_provider, &bob_signer, LeafNodeParameters::default())
        .expect("error creating self-update commit")
        .into_messages();

    let alice_processed_message = alice_group
        .process_message(alice_provider, msg.into_protocol_message().unwrap())
        .expect("Could not process messages.");
    assert!(alice_group.pending_commit().is_some());

    if let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        alice_processed_message.into_content()
    {
        alice_group
            .merge_staged_commit(alice_provider, *staged_commit)
            .expect("Error merging commit.");
    } else {
        unreachable!("Expected a StagedCommit.");
    }
    assert!(alice_group.pending_commit().is_none());
}

// Test that the key package and the corresponding private key are deleted when
// creating a new group for a welcome message.
#[openmls_test]
fn key_package_deletion() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential_with_key, bob_kpb, _bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);
    let bob_key_package = bob_kpb.key_package();

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    // === Alice adds Bob ===
    let (_queued_message, welcome, _group_info) = alice_group
        .add_members(alice_provider, &alice_signer, from_ref(bob_key_package))
        .unwrap();

    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    // === Bob joins the group ===
    let _bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");

    // TEST: The key package must be gone from the key store.
    let result: Option<KeyPackageBundle> = bob_provider
        .storage()
        .key_package(&bob_key_package.hash_ref(bob_provider.crypto()).unwrap())
        .unwrap();
    assert!(
        result.is_none(),
        "The key package is still in the key store after creating a new group from it."
    );
}

#[openmls_test]
fn remove_prosposal_by_ref() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let charlie_provider = &Provider::default();

    let group_id = GroupId::from_slice(b"Test Group");

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_bob_credential_with_key, bob_kpb, _bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);
    let bob_key_package = bob_kpb.key_package().clone();
    let (_charlie_credential_with_key, charlie_kpb, _charlie_signer, _charlie_pk) =
        setup_client("Charlie", ciphersuite, charlie_provider);
    let charlie_key_package = charlie_kpb.key_package();

    // Define the MlsGroup configuration
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new_with_group_id(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        group_id,
        alice_credential_with_key,
    )
    .expect("An unexpected error occurred.");

    // alice adds bob and bob processes the welcome
    let (_, welcome, _) = alice_group
        .add_members(alice_provider, &alice_signer, &[bob_key_package])
        .unwrap();
    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        mls_group_create_config.join_config(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .unwrap()
    .into_group(bob_provider)
    .unwrap();
    // alice proposes to add charlie
    let (_, reference) = alice_group
        .propose_add_member(alice_provider, &alice_signer, charlie_key_package)
        .unwrap();

    assert_eq!(alice_group.proposal_store().proposals().count(), 1);
    // clearing the proposal by reference
    alice_group
        .remove_pending_proposal(alice_provider.storage(), &reference)
        .unwrap();
    assert!(alice_group.proposal_store().is_empty());

    // the proposal should not be stored anymore
    let err = alice_group
        .remove_pending_proposal(alice_provider.storage(), &reference)
        .unwrap_err();
    assert!(matches!(err, RemoveProposalError::ProposalNotFound));

    // the commit should have no proposal
    let (commit, _, _) = alice_group
        .commit_to_pending_proposals(alice_provider, &alice_signer)
        .unwrap();
    let msg = bob_group
        .process_message(
            bob_provider,
            MlsMessageIn::from(commit)
                .try_into_protocol_message()
                .unwrap(),
        )
        .unwrap();
    match msg.into_content() {
        ProcessedMessageContent::StagedCommitMessage(commit) => {
            // assert that no proposal was commited
            assert!(commit.add_proposals().next().is_none());
            assert!(commit.update_proposals().next().is_none());
            assert!(commit.remove_proposals().next().is_none());
            assert!(commit.psk_proposals().next().is_none());
            assert_eq!(alice_group.members().count(), 2);
        }
        _ => unreachable!("Expected a StagedCommit."),
    }
}

#[openmls_test]
fn max_past_epochs_join_config() {
    let alice_provider = &Provider::default();
    let max_past_epochs = 10;

    let create_config = MlsGroupCreateConfig::builder()
        .max_past_epochs(max_past_epochs)
        .build();

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    let alice_group = MlsGroup::new(
        alice_provider,
        &alice_signer,
        &create_config,
        alice_credential_with_key,
    )
    .expect("failed to create group");

    assert_eq!(
        alice_group.message_secrets_store.max_epochs,
        max_past_epochs
    );
}

// Test that the builder pattern accurately configures the new group.
#[openmls_test]
fn builder_pattern() {
    let alice_provider = &Provider::default();

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    // Variables for the MlsGroup configuration
    let test_group_id = GroupId::from_slice(b"Test Group");
    let test_lifetime = Lifetime::new(3600);
    let test_wire_format_policy = PURE_CIPHERTEXT_WIRE_FORMAT_POLICY;
    let test_padding_size = 100;
    let test_external_senders = Extension::ExternalSenders(vec![ExternalSender::new(
        alice_credential_with_key.signature_key.clone(),
        alice_credential_with_key.credential.clone(),
    )]);
    let test_required_capabilities = Extension::RequiredCapabilities(
        RequiredCapabilitiesExtension::new(&[ExtensionType::Unknown(0xff00)], &[], &[]),
    );
    let test_gc_extensions = Extensions::from_vec(vec![
        test_external_senders.clone(),
        test_required_capabilities.clone(),
    ])
    .expect("error creating group context extensions");

    let test_ciphersuite = ciphersuite;
    let test_sender_ratchet_config = SenderRatchetConfiguration::new(10, 2000);
    let test_max_past_epochs = 10;
    let test_number_of_resumption_psks = 5;
    let test_capabilities = Capabilities::new(
        None,
        None,
        Some(&[ExtensionType::Unknown(0xff00)]),
        None,
        None,
    );
    let test_leaf_extensions = Extensions::single(Extension::Unknown(
        0xff00,
        UnknownExtension(vec![0x00, 0x01, 0x02]),
    ))
    .expect("failed to create single-element extensions list");

    // === Alice creates a group ===
    let alice_group = MlsGroup::builder()
        .with_group_id(test_group_id.clone())
        .padding_size(test_padding_size)
        .sender_ratchet_configuration(test_sender_ratchet_config)
        .with_group_context_extensions(test_gc_extensions.clone())
        .ciphersuite(test_ciphersuite)
        .with_wire_format_policy(test_wire_format_policy)
        .lifetime(test_lifetime)
        .use_ratchet_tree_extension(true)
        .max_past_epochs(test_max_past_epochs)
        .number_of_resumption_psks(test_number_of_resumption_psks)
        .with_capabilities(test_capabilities.clone())
        .with_leaf_node_extensions(test_leaf_extensions.clone())
        .expect("error adding leaf node extension to builder")
        .build(alice_provider, &alice_signer, alice_credential_with_key)
        .expect("error creating group using builder");

    // Check that the group was created with the correct configuration

    // first the config
    let group_config = alice_group.configuration();
    assert_eq!(group_config.padding_size(), test_padding_size);
    assert_eq!(
        group_config.sender_ratchet_configuration(),
        &test_sender_ratchet_config
    );
    assert_eq!(group_config.wire_format_policy(), test_wire_format_policy);
    assert!(group_config.use_ratchet_tree_extension);
    assert_eq!(group_config.max_past_epochs, test_max_past_epochs);
    assert_eq!(
        group_config.number_of_resumption_psks,
        test_number_of_resumption_psks
    );

    // and the rest of the parameters
    let group_context = alice_group.export_group_context();
    assert_eq!(alice_group.group_id(), &test_group_id);
    let external_senders = group_context
        .extensions()
        .external_senders()
        .expect("error getting external senders")
        .to_vec();
    assert_eq!(
        Extension::ExternalSenders(external_senders),
        test_external_senders
    );
    assert_eq!(ciphersuite, test_ciphersuite);
    assert_eq!(group_context.extensions(), &test_gc_extensions);
    let lifetime = alice_group
        .own_leaf()
        .expect("error getting own leaf")
        .life_time()
        .expect("leaf doesn't have a lifetime");
    assert_eq!(lifetime, &test_lifetime);
    let own_leaf = alice_group.own_leaf_node().expect("can't find own leaf");
    let capabilities = own_leaf.capabilities();
    // Check that all non-GREASE capabilities match
    // Filter out GREASE values for comparison since they're automatically injected
    let filtered_ciphersuites: Vec<_> = capabilities
        .ciphersuites()
        .iter()
        .filter(|cs| !cs.is_grease())
        .copied()
        .collect();
    let filtered_extensions: Vec<_> = capabilities
        .extensions()
        .iter()
        .filter(|ext| !ext.is_grease())
        .copied()
        .collect();
    let filtered_proposals: Vec<_> = capabilities
        .proposals()
        .iter()
        .filter(|prop| !prop.is_grease())
        .copied()
        .collect();
    let filtered_credentials: Vec<_> = capabilities
        .credentials()
        .iter()
        .filter(|cred| !cred.is_grease())
        .copied()
        .collect();
    assert_eq!(filtered_ciphersuites, test_capabilities.ciphersuites());
    assert_eq!(filtered_extensions, test_capabilities.extensions());
    assert_eq!(filtered_proposals, test_capabilities.proposals());
    assert_eq!(filtered_credentials, test_capabilities.credentials());
    let leaf_extensions = own_leaf.extensions();
    assert_eq!(leaf_extensions, &test_leaf_extensions);

    // Make sure that building with an invalid leaf node extension fails
    let err = Extensions::<LeafNode>::single(Extension::RequiredCapabilities(
        RequiredCapabilitiesExtension::new(&[], &[], &[]),
    ))
    .expect_err(
        "should not be able single-element leaf node extensions list with RequiredCapabilities",
    );

    assert_eq!(
        err,
        InvalidExtensionError::ExtensionTypeNotValidInLeafNode(
            ExtensionTypeNotValidInLeafNodeError(ExtensionType::RequiredCapabilities)
        )
    );
}

// Test the successful update of Group Context Extension with type Extension::Unknown(0xff11)
#[openmls_test]
fn update_group_context_with_unknown_extension<Provider: OpenMlsProvider + Default>() {
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    // === Define the unknown group context extension and initial data ===
    const UNKNOWN_EXTENSION_TYPE: u16 = 0xff11;
    let unknown_extension_data = vec![1, 2];
    let unknown_gc_extension = Extension::Unknown(
        UNKNOWN_EXTENSION_TYPE,
        UnknownExtension(unknown_extension_data),
    );
    let required_extension_types = &[ExtensionType::Unknown(UNKNOWN_EXTENSION_TYPE)];
    let required_capabilities = Extension::RequiredCapabilities(
        RequiredCapabilitiesExtension::new(required_extension_types, &[], &[]),
    );
    let capabilities = Capabilities::new(None, None, Some(required_extension_types), None, None);
    let test_gc_extensions = Extensions::from_vec(vec![
        unknown_gc_extension.clone(),
        required_capabilities.clone(),
    ])
    .expect("error creating test group context extensions");
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .with_group_context_extensions(test_gc_extensions.clone())
        .capabilities(capabilities.clone())
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        alice_credential_with_key,
    )
    .expect("error creating group");

    // === Verify the initial group context extension data is correct ===
    let group_context_extensions = alice_group.context().extensions();
    let mut extracted_data = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data.unwrap(),
        vec![1, 2],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );

    // === Alice adds Bob ===
    let bob_provider = &Provider::default();
    let (bob_credential_with_key, _bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    let bob_key_package = KeyPackage::builder()
        .leaf_node_capabilities(capabilities)
        .build(
            ciphersuite,
            bob_provider,
            &bob_signer,
            bob_credential_with_key,
        )
        .expect("error building key package");

    let (_, welcome, _) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_key_package.key_package()),
        )
        .unwrap();
    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");

    // === Verify Bob's initial group context extension data is correct ===
    let group_context_extensions = bob_group.context().extensions();
    let mut extracted_data_2 = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data_2 = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data_2.unwrap(),
        vec![1, 2],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );

    // === Propose the new group context extension ===
    let updated_unknown_extension_data = vec![3, 4]; // Sample data for the extension
    let updated_unknown_gc_extension = Extension::Unknown(
        UNKNOWN_EXTENSION_TYPE,
        UnknownExtension(updated_unknown_extension_data.clone()),
    );

    let mut updated_extensions = test_gc_extensions.clone();
    updated_extensions
        .add_or_replace(updated_unknown_gc_extension)
        .expect("updated extension should be valid here");
    let (update_proposal, _) = alice_group
        .propose_group_context_extensions(alice_provider, updated_extensions, &alice_signer)
        .expect("failed to propose group context extensions with unknown extension");

    assert_eq!(
        alice_group.pending_proposals().count(),
        1,
        "Expected one pending proposal"
    );

    // === Commit to the proposed group context extension ===
    let (update_commit, _, _) = alice_group
        .commit_to_pending_proposals(alice_provider, &alice_signer)
        .expect("failed to commit to pending group context extensions");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");

    // === let bob process the updates  ===
    assert_eq!(
        bob_group.pending_proposals().count(),
        0,
        "Expected no pending proposals"
    );

    let processed_update_message = bob_group
        .process_message(
            bob_provider,
            update_proposal.into_protocol_message().unwrap(),
        )
        .expect("bob failed processing the update");

    match processed_update_message.into_content() {
        ProcessedMessageContent::ProposalMessage(msg) => {
            bob_group
                .store_pending_proposal(bob_provider.storage(), *msg)
                .unwrap();
        }
        other => panic!("expected proposal, got {other:?}"),
    }

    assert_eq!(
        bob_group.pending_proposals().count(),
        1,
        "Expected one pending proposal"
    );

    let processed_commit_message = bob_group
        .process_message(bob_provider, update_commit.into_protocol_message().unwrap())
        .expect("bob failed processing the update");

    match processed_commit_message.into_content() {
        ProcessedMessageContent::StagedCommitMessage(staged_commit) => bob_group
            .merge_staged_commit(bob_provider, *staged_commit)
            .expect("error merging group context update commit"),
        other => panic!("expected commit, got {other:?}"),
    };

    // === Verify the group context extension was updated ===
    let group_context_extensions = alice_group.context().extensions();
    let mut extracted_data_updated = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data_updated = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data_updated.unwrap(),
        vec![3, 4],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );

    // === Verify Bob sees the group context extension updated ===
    let bob_group_loaded = MlsGroup::load(bob_provider.storage(), bob_group.group_id())
        .expect("error loading group")
        .expect("no such group");
    let group_context_extensions_2 = bob_group_loaded.export_group_context().extensions();
    let mut extracted_data_2 = None;
    for extension in group_context_extensions_2.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data_2 = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data_2.unwrap(),
        vec![3, 4],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );
}

#[openmls_test]
fn update_proposal_bob() {
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        alice_credential_with_key,
    )
    .expect("error creating group");

    // === Alice adds Bob ===
    let bob_provider = &Provider::default();
    let (bob_credential_with_key, _bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    let bob_key_package = KeyPackage::builder()
        .build(
            ciphersuite,
            bob_provider,
            &bob_signer,
            bob_credential_with_key,
        )
        .expect("error building key package");

    let (_, welcome, _) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_key_package.key_package()),
        )
        .unwrap();
    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");

    // === Bob proposes an update ===
    let (update_proposal, _proposal_reference) = bob_group
        .propose_self_update(
            bob_provider,
            &bob_signer,
            LeafNodeParameters::builder().build(),
        )
        .unwrap();

    // === Alice processes the update proposal from Bob ===
    let processed_message = alice_group
        .process_message(
            alice_provider,
            update_proposal.into_protocol_message().unwrap(),
        )
        .unwrap();

    let ProcessedMessageContent::ProposalMessage(proposal_msg) = processed_message.into_content()
    else {
        panic!("expected proposal");
    };
    bob_group
        .store_pending_proposal(bob_provider.storage(), *proposal_msg)
        .unwrap();

    // === Alice commits to the proposal ===
    let (commit, _, _) = alice_group
        .commit_to_pending_proposals(alice_provider, &alice_signer)
        .expect("failed to commit to pending group context extensions");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging pending commit");

    // === Bob processes the commit  ===
    let processed_message = bob_group
        .process_message(bob_provider, commit.into_protocol_message().unwrap())
        .expect("bob failed processing the update");

    let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        processed_message.into_content()
    else {
        panic!("Expected a commit");
    };
    bob_group
        .merge_staged_commit(bob_provider, *staged_commit)
        .expect("error merging commit to own update proposal");
}

#[openmls_test]
fn update_proposal_alice() {
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        alice_credential_with_key,
    )
    .expect("error creating group");

    // === Alice adds Bob ===
    let bob_provider = &Provider::default();
    let (bob_credential_with_key, _bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    let bob_key_package = KeyPackage::builder()
        .build(
            ciphersuite,
            bob_provider,
            &bob_signer,
            bob_credential_with_key,
        )
        .expect("error building key package");

    let (_, welcome, _) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_key_package.key_package()),
        )
        .unwrap();
    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");

    // === Alice proposes an update ===
    let (update_proposal, _proposal_reference) = alice_group
        .propose_self_update(
            alice_provider,
            &alice_signer,
            LeafNodeParameters::builder().build(),
        )
        .unwrap();

    // === Bob processes the update proposal from Alice ===
    let processed_message = bob_group
        .process_message(
            bob_provider,
            update_proposal.into_protocol_message().unwrap(),
        )
        .unwrap();

    let ProcessedMessageContent::ProposalMessage(proposal_msg) = processed_message.into_content()
    else {
        panic!("expected proposal");
    };
    bob_group
        .store_pending_proposal(bob_provider.storage(), *proposal_msg)
        .unwrap();

    // === Bob commits to the proposal ===
    let (commit, _, _) = bob_group
        .commit_to_pending_proposals(bob_provider, &bob_signer)
        .expect("failed to commit to pending group context extensions");

    bob_group
        .merge_pending_commit(bob_provider)
        .expect("error merging pending commit");

    // === Alice processes the commit  ===
    let processed_message = alice_group
        .process_message(alice_provider, commit.into_protocol_message().unwrap())
        .expect("bob failed processing the update");

    let ProcessedMessageContent::StagedCommitMessage(staged_commit) =
        processed_message.into_content()
    else {
        panic!("Expected a commit");
    };
    alice_group
        .merge_staged_commit(alice_provider, *staged_commit)
        .expect("error merging commit to own update proposal");

    assert_eq!(
        alice_group.epoch_authenticator(),
        bob_group.epoch_authenticator()
    );
}

#[openmls_test]
fn test_update_group_context_with_unknown_extension_using_update_function<
    Provider: OpenMlsProvider + Default,
>() {
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    // === Define the unknown group context extension and initial data ===
    const UNKNOWN_EXTENSION_TYPE: u16 = 0xff11;
    let unknown_extension_data = vec![1, 2];
    let unknown_gc_extension = Extension::Unknown(
        UNKNOWN_EXTENSION_TYPE,
        UnknownExtension(unknown_extension_data),
    );
    let required_extension_types = &[ExtensionType::Unknown(UNKNOWN_EXTENSION_TYPE)];
    let required_capabilities = Extension::RequiredCapabilities(
        RequiredCapabilitiesExtension::new(required_extension_types, &[], &[]),
    );
    let capabilities = Capabilities::new(None, None, Some(required_extension_types), None, None);
    let test_gc_extensions = Extensions::from_vec(vec![
        unknown_gc_extension.clone(),
        required_capabilities.clone(),
    ])
    .expect("error creating test group context extensions");
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .with_group_context_extensions(test_gc_extensions.clone())
        .capabilities(capabilities.clone())
        .ciphersuite(ciphersuite)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new(
        alice_provider,
        &alice_signer,
        &mls_group_create_config,
        alice_credential_with_key,
    )
    .expect("error creating group");

    // === Verify the initial group context extension data is correct ===
    let group_context_extensions = alice_group.context().extensions();
    let mut extracted_data = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data.unwrap(),
        vec![1, 2],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );

    // === Propose the new group context extension using update_group_context_extensions ===
    let updated_unknown_extension_data = vec![3, 4];
    let updated_unknown_gc_extension = Extension::Unknown(
        UNKNOWN_EXTENSION_TYPE,
        UnknownExtension(updated_unknown_extension_data.clone()),
    );

    let mut updated_extensions = test_gc_extensions.clone();
    updated_extensions
        .add_or_replace(updated_unknown_gc_extension)
        .expect("updated extension should be valid here");

    let update_result = alice_group.update_group_context_extensions(
        alice_provider,
        updated_extensions,
        &alice_signer,
    );
    assert!(
        update_result.is_ok(),
        "Failed to update group context extensions: {:?}",
        update_result.err()
    );

    // === Test clearing staged commit before merge, verify context shows expected data ===
    alice_group
        .clear_pending_commit(alice_provider.storage())
        .unwrap();
    let group_context_extensions = alice_group.context().extensions();
    let mut extracted_data = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data.unwrap(),
        vec![1, 2],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );

    // === Propose the new group context extension using update_group_context_extensions ===
    let updated_unknown_extension_data = vec![4, 5]; // Sample data for the extension
    let updated_unknown_gc_extension = Extension::Unknown(
        UNKNOWN_EXTENSION_TYPE,
        UnknownExtension(updated_unknown_extension_data.clone()),
    );

    let mut updated_extensions = test_gc_extensions.clone();
    updated_extensions
        .add_or_replace(updated_unknown_gc_extension)
        .expect("updated extension should be valid here");
    let update_result = alice_group.update_group_context_extensions(
        alice_provider,
        updated_extensions,
        &alice_signer,
    );
    assert!(
        update_result.is_ok(),
        "Failed to update group context extensions: {:?}",
        update_result.err()
    );

    // === Merge Pending Commit ===
    alice_group.merge_pending_commit(alice_provider).unwrap();

    // === Verify the group context extension was updated ===
    let group_context_extensions = alice_group.context().extensions();
    let mut extracted_data_updated = None;
    for extension in group_context_extensions.iter() {
        if let Extension::Unknown(UNKNOWN_EXTENSION_TYPE, UnknownExtension(data)) = extension {
            extracted_data_updated = Some(data.clone());
        }
    }
    assert_eq!(
        extracted_data_updated.unwrap(),
        vec![4, 5],
        "The data of Extension::Unknown(0xff11) does not match the expected data"
    );
}

// Test that unknown group context and leaf node extensions can be used in groups
#[openmls_test]
fn unknown_extensions() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();

    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("Alice", ciphersuite, alice_provider);

    let unknown_gc_extension = Extension::Unknown(0xff00, UnknownExtension(vec![0, 1, 2, 3]));
    let unknown_leaf_extension = Extension::Unknown(0xff01, UnknownExtension(vec![4, 5, 6, 7]));
    let unknown_kp_extension = Extension::Unknown(0xff02, UnknownExtension(vec![8, 9, 10, 11]));
    let required_extensions = &[
        ExtensionType::Unknown(0xff00),
        ExtensionType::Unknown(0xff01),
    ];
    let required_capabilities =
        Extension::RequiredCapabilities(RequiredCapabilitiesExtension::new(&[], &[], &[]));
    let capabilities = Capabilities::new(None, None, Some(required_extensions), None, None);
    let test_gc_extensions = Extensions::from_vec(vec![
        unknown_gc_extension.clone(),
        required_capabilities.clone(),
    ])
    .expect("error creating group context extensions");
    let test_kp_extensions = Extensions::single(unknown_kp_extension.clone())
        .expect("failed to create single-element extensions list");

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_capabilities(capabilities.clone())
        .with_leaf_node_extensions(
            Extensions::single(unknown_leaf_extension.clone())
                .expect("failed to create single-element extensions list"),
        )
        .expect("error adding unknown leaf extension to builder")
        .with_group_context_extensions(test_gc_extensions.clone())
        .build(alice_provider, &alice_signer, alice_credential_with_key)
        .expect("error creating group using builder");

    // Check that everything was added successfully
    let group_context_extensions = alice_group.export_group_context().extensions();
    assert_eq!(group_context_extensions, &test_gc_extensions);
    let leaf_node = alice_group.own_leaf().expect("error getting own leaf");
    assert_eq!(
        leaf_node.extensions(),
        &Extensions::single(unknown_leaf_extension)
            .expect("failed to create single-element extensions list")
    );

    // Now let's add Bob to the group and make sure that he joins the group successfully

    // === Alice adds Bob ===
    let (bob_credential_with_key, _bob_kpb, bob_signer, _bob_pk) =
        setup_client("Bob", ciphersuite, bob_provider);

    // Generate a KP that supports the unknown extensions
    let bob_key_package = KeyPackage::builder()
        .leaf_node_capabilities(capabilities)
        .key_package_extensions(test_kp_extensions.clone())
        .build(
            ciphersuite,
            bob_provider,
            &bob_signer,
            bob_credential_with_key,
        )
        .expect("error building key package");

    assert_eq!(
        bob_key_package.key_package().extensions(),
        &Extensions::single(unknown_kp_extension)
            .expect("failed to create single-element extensions list")
    );

    // alice adds bob and bob processes the welcome to ensure that the unknown
    // extensions are processed correctly
    let (_, welcome, _) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(bob_key_package.key_package()),
        )
        .unwrap();
    alice_group.merge_pending_commit(alice_provider).unwrap();

    let welcome: MlsMessageIn = welcome.into();
    let welcome = welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    let _bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome,
        Some(alice_group.export_ratchet_tree().into()),
    )
    .expect("Error creating staged join from Welcome")
    .into_group(bob_provider)
    .expect("Error creating group from staged join");
}

#[openmls_test]
fn join_multiple_groups_last_resort_extension() {
    // start with alice, bob, charlie, common config items
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let charlie_provider = &Provider::default();
    let (alice_credential_with_key, _alice_kpb, alice_signer, _alice_pk) =
        setup_client("alice", ciphersuite, alice_provider);
    let (bob_credential_with_key, _bob_kpb, bob_signer, _bob_pk) =
        setup_client("bob", ciphersuite, bob_provider);
    let (charlie_credential_with_key, _charlie_kpb, charlie_signer, _charlie_pk) =
        setup_client("charlie", ciphersuite, charlie_provider);
    let leaf_capabilities =
        Capabilities::new(None, None, Some(&[ExtensionType::LastResort]), None, None);
    let keypkg_extensions = Extensions::single(Extension::LastResort(LastResortExtension::new()))
        .expect("failed to create single-element extensions list");
    // alice creates MlsGroup
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build(alice_provider, &alice_signer, alice_credential_with_key)
        .expect("error creating group for alice using builder");
    // bob creates MlsGroup
    let mut bob_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build(bob_provider, &bob_signer, bob_credential_with_key)
        .expect("error creating group for bob using builder");
    // charlie creates KeyPackage
    let charlie_keypkg = KeyPackage::builder()
        .leaf_node_capabilities(leaf_capabilities)
        .key_package_extensions(keypkg_extensions.clone())
        .build(
            ciphersuite,
            charlie_provider,
            &charlie_signer,
            charlie_credential_with_key,
        )
        .expect("error building key package for charlie");
    // alice calls add_members(...) with charlie's KeyPackage; produces Commit and Welcome messages
    let (_, alice_welcome, _) = alice_group
        .add_members(
            alice_provider,
            &alice_signer,
            from_ref(charlie_keypkg.key_package()),
        )
        .expect("error adding charlie to alice's group");
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("error merging commit for alice's group");

    // charlie calls new_from_welcome(...) with alice's Welcome message; SHOULD SUCCEED
    let alice_welcome: MlsMessageIn = alice_welcome.into();
    let alice_welcome = alice_welcome
        .into_welcome()
        .expect("expected message to be a welcome");

    StagedWelcome::new_from_welcome(
        charlie_provider,
        &MlsGroupJoinConfig::default(),
        alice_welcome,
        None,
    )
    .expect("error creating staged join from welcome")
    .into_group(charlie_provider)
    .expect("error creating group from staged join");

    // bob calls add_members(...) with charlie's KeyPackage; produces Commit and Welcome messages
    let (_, bob_welcome, _) = bob_group
        .add_members(
            bob_provider,
            &bob_signer,
            from_ref(charlie_keypkg.key_package()),
        )
        .expect("error adding charlie to bob's group");
    bob_group
        .merge_pending_commit(bob_provider)
        .expect("error merging commit for bob's group");

    // charlie calls new_from_welcome(...) with bob's Welcome message; SHOULD SUCCEED
    let bob_welcome: MlsMessageIn = bob_welcome.into();
    let bob_welcome = bob_welcome
        .into_welcome()
        .expect("expected message to be a welcome");
    StagedWelcome::new_from_welcome(
        charlie_provider,
        &MlsGroupJoinConfig::default(),
        bob_welcome,
        None,
    )
    .expect("error creating staged join from welcome")
    .into_group(charlie_provider)
    .expect("error creating group from staged join");
    // done :-)
}

#[openmls_test]
fn deletion() {
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, alice_kpb, alice_signer, alice_pk) =
        setup_client("alice", ciphersuite, alice_provider);

    // delete the kpb from the provider, as we don't need it

    <StorageProvider as openmls_traits::storage::StorageProvider<CURRENT_VERSION>>::delete_key_package
        (
            alice_provider.storage(),
            &alice_kpb.key_package().hash_ref(alice_provider.crypto()).unwrap(),
        ).unwrap();

    <StorageProvider as openmls_traits::storage::StorageProvider<CURRENT_VERSION>>::delete_encryption_key_pair
        (alice_provider
        .storage(),alice_kpb.key_package().leaf_node().encryption_key())
        .unwrap();

    // alice creates MlsGroup
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build(alice_provider, &alice_signer, alice_credential_with_key)
        .expect("error creating group for alice using builder");

    SignatureKeyPair::delete(
        alice_provider.storage(),
        alice_pk.as_slice(),
        ciphersuite.signature_algorithm(),
    )
    .unwrap();

    // alice deletes the group
    alice_group.delete(alice_provider.storage()).unwrap();

    let storage = alice_provider.storage();
    let group_id = alice_group.group_id();
    let current_epoch = alice_group.epoch();
    let own_leaf_index = alice_group.own_leaf_index();

    let all_gone = storage.tree::<_, TreeSync>(group_id).unwrap().is_none()
        && storage
            .confirmation_tag::<_, ConfirmationTag>(group_id)
            .unwrap()
            .is_none()
        && storage
            .group_context::<_, GroupContext>(group_id)
            .unwrap()
            .is_none()
        && storage
            .interim_transcript_hash::<_, InterimTranscriptHash>(group_id)
            .unwrap()
            .is_none()
        && storage
            .own_leaf_index::<_, LeafNodeIndex>(group_id)
            .unwrap()
            .is_none()
        && storage
            .group_epoch_secrets::<_, GroupEpochSecrets>(group_id)
            .unwrap()
            .is_none()
        && storage
            .message_secrets::<_, MessageSecretsStore>(group_id)
            .unwrap()
            .is_none()
        && storage
            .mls_group_join_config::<_, MlsGroupJoinConfig>(group_id)
            .unwrap()
            .is_none()
        && storage
            .own_leaf_nodes::<_, LeafNode>(group_id)
            .unwrap()
            .is_empty()
        && storage
            .group_state::<MlsGroupState, _>(group_id)
            .unwrap()
            .is_none()
        && storage
            .encryption_epoch_key_pairs::<_, _, EncryptionKeyPair>(
                group_id,
                &current_epoch,
                own_leaf_index.u32(),
            )
            .unwrap()
            .is_empty()
        && alice_group.proposal_store().is_empty();

    // The trait doesn't allow us to check whether the proposal queue is empty,
    // or whether all resumption PSKs have been deleted.

    assert!(all_gone);
}

#[openmls_test::openmls_test]
fn failed_groupinfo_decryption() {
    let provider = &Provider::default();
    let epoch = 123;
    let group_id = GroupId::random(provider.rand());
    let tree_hash = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
    let confirmed_transcript_hash = vec![1, 1, 1];
    let extensions = Extensions::empty();
    let confirmation_tag = ConfirmationTag(Mac {
        mac_value: vec![1, 2, 3, 4, 5, 6, 7, 8, 9].into(),
    });

    // Create credentials and keys
    let (alice_credential_with_key, alice_signature_keys) =
        new_credential(provider, b"Alice", ciphersuite.signature_algorithm());

    let key_package_bundle = KeyPackageBundle::generate(
        provider,
        &alice_signature_keys,
        ciphersuite,
        alice_credential_with_key,
    );

    let group_info_tbs = {
        let group_context = GroupContext::new(
            ciphersuite,
            group_id,
            epoch,
            tree_hash,
            confirmed_transcript_hash,
            Extensions::empty(),
        );

        GroupInfoTBS::new(
            group_context,
            extensions,
            confirmation_tag,
            LeafNodeIndex::new(0),
        )
        .unwrap()
    };

    // Generate key and nonce for the symmetric cipher.
    let welcome_key = AeadKey::random(ciphersuite, provider.rand());
    let welcome_nonce = AeadNonce::random(provider.rand());

    // Generate receiver key pair.
    let receiver_key_pair = provider
        .crypto()
        .derive_hpke_keypair(
            ciphersuite.hpke_config(),
            Secret::random(ciphersuite, provider.rand())
                .expect("Not enough randomness.")
                .as_slice(),
        )
        .expect("error deriving receiver hpke key pair");
    let hpke_context = b"group info welcome test info";
    let group_secrets = b"these should be the group secrets";
    let mut encrypted_group_secrets = hpke::encrypt_with_label(
        receiver_key_pair.public.as_slice(),
        "Welcome",
        hpke_context,
        group_secrets,
        ciphersuite,
        provider.crypto(),
    )
    .unwrap();

    let group_info = group_info_tbs
        .sign(&alice_signature_keys)
        .expect("Error signing group info");

    // Mess with the ciphertext by flipping the last byte.
    flip_last_byte(&mut encrypted_group_secrets);

    let broken_secrets = vec![EncryptedGroupSecrets::new(
        key_package_bundle
            .key_package
            .hash_ref(provider.crypto())
            .expect("Could not hash KeyPackage."),
        encrypted_group_secrets,
    )];

    // Encrypt the group info.
    let encrypted_group_info = welcome_key
        .aead_seal(
            provider.crypto(),
            &group_info
                .tls_serialize_detached()
                .expect("An unexpected error occurred."),
            &[],
            &welcome_nonce,
        )
        .expect("An unexpected error occurred.");

    // Now build the welcome message.
    let broken_welcome = Welcome::new(ciphersuite, broken_secrets, encrypted_group_info);

    let error = StagedWelcome::new_from_welcome(
        provider,
        &MlsGroupJoinConfig::default(),
        broken_welcome,
        None,
    )
    .and_then(|staged_join| staged_join.into_group(provider))
    .expect_err("Creation of mls group from a broken Welcome was successful.");

    assert!(matches!(
        error,
        WelcomeError::GroupSecrets(GroupSecretsError::DecryptionFailed)
    ))
}

/// Test what happens if the KEM ciphertext for the receiver in the UpdatePath
/// is broken.
#[openmls_test::openmls_test]
fn update_path() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();

    // === Alice creates a group with her and Bob ===
    // TODO: don't let alice and bob share the provider
    let (
        mut alice_group,
        _alice_signature_keys,
        mut bob_group,
        bob_signature_keys,
        _alice_credential_with_key,
        _bob_credential_with_key,
    ) = setup_alice_bob_group(ciphersuite, alice_provider, bob_provider);

    // === Bob updates and commits ===
    let mut bob_new_leaf_node = bob_group.own_leaf_node().unwrap().clone();
    bob_new_leaf_node
        .update(
            ciphersuite,
            bob_provider,
            &bob_signature_keys,
            bob_group.group_id().clone(),
            bob_group.own_leaf_index(),
            LeafNodeParameters::default(),
        )
        .unwrap();

    let (update_bob, _welcome_option, _group_info_option) = bob_group
        .self_update(
            bob_provider,
            &bob_signature_keys,
            LeafNodeParameters::default(),
        )
        .expect("Could not create proposal.")
        .into_contents();

    // Now we break Alice's HPKE ciphertext in Bob's commit by breaking
    // apart the commit, manipulating the ciphertexts and the piecing it
    // back together.
    let pm = match update_bob.body {
        mls_group::MlsMessageBodyOut::PublicMessage(pm) => pm,
        _ => panic!("Wrong message type"),
    };

    let franken_pm = FrankenPublicMessage::from(pm.clone());
    let mut content = franken_pm.content.clone();
    let FrankenFramedContentBody::Commit(ref mut commit) = content.body else {
        panic!("Unexpected content type");
    };
    let Some(ref mut path) = commit.path else {
        panic!("No path in commit.");
    };

    for node in &mut path.nodes {
        for eps in &mut node.encrypted_path_secrets {
            let mut eps_ctxt_vec = Vec::<u8>::from(eps.ciphertext.clone());
            eps_ctxt_vec[0] ^= 0xff;
            eps.ciphertext = eps_ctxt_vec.into();
        }
    }

    // Rebuild the PublicMessage with the new content
    let group_context = bob_group.export_group_context().clone();
    let membership_key = bob_group.message_secrets().membership_key().as_slice();

    let broken_message = FrankenPublicMessage::auth(
        bob_provider,
        ciphersuite,
        &bob_signature_keys,
        content,
        Some(&group_context.into()),
        Some(membership_key),
        Some(pm.confirmation_tag().unwrap().0.mac_value.clone()),
    );

    let protocol_message = ProtocolMessage::from(PublicMessage::from(broken_message));

    let result = alice_group.process_message(alice_provider, protocol_message);
    assert_eq!(
        result.expect_err("Successful processing of a broken commit."),
        ProcessMessageError::InvalidCommit(StageCommitError::UpdatePathError(
            ApplyUpdatePathError::UnableToDecrypt
        ))
    );
}

// Test several scenarios when PSKs are used in a group
#[openmls_test::openmls_test]
fn psks() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();

    // Basic group setup.
    let (
        alice_credential_with_key,
        alice_signature_keys,
        bob_key_package_bundle,
        bob_signature_keys,
    ) = setup_alice_bob(ciphersuite, alice_provider, bob_provider);

    // === Alice creates a group with a PSK ===
    let psk_id = vec![1u8, 2, 3];

    let secret =
        Secret::random(ciphersuite, alice_provider.rand()).expect("Not enough randomness.");
    let external_psk = ExternalPsk::new(psk_id);
    let preshared_key_id = PreSharedKeyId::new(
        ciphersuite,
        alice_provider.rand(),
        Psk::External(external_psk),
    )
    .expect("An unexpected error occured.");
    preshared_key_id
        .store(alice_provider, secret.as_slice())
        .unwrap();
    preshared_key_id
        .store(bob_provider, secret.as_slice())
        .unwrap();
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build(
            alice_provider,
            &alice_signature_keys,
            alice_credential_with_key,
        )
        .expect("Error creating group.");

    // === Alice creates a PSK proposal ===
    log::info!(" >>> Creating psk proposal ...");
    let (_psk_proposal, _proposal_ref) = alice_group
        .propose_external_psk(alice_provider, &alice_signature_keys, preshared_key_id)
        .expect("Could not create PSK proposal");

    // === Alice adds Bob (and commits to PSK proposal) ===
    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            alice_provider,
            &alice_signature_keys,
            from_ref(bob_key_package_bundle.key_package()),
        )
        .expect("Could not create commit");

    log::info!(" >>> Merging commit ...");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");

    let ratchet_tree = alice_group.export_ratchet_tree();

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome.into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Could not stage welcome")
    .into_group(bob_provider)
    .expect("Could not create group from welcome");

    // === Bob updates and commits ===
    let (_commit, _welcome_option, _group_info_option) = bob_group
        .self_update(
            bob_provider,
            &bob_signature_keys,
            LeafNodeParameters::default(),
        )
        .expect("An unexpected error occurred.")
        .into_contents();
}

// Test several scenarios when PSKs are used in a group
#[openmls_test::openmls_test]
fn staged_commit_creation() {
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    // Basic group setup.
    let (alice_credential_with_key, alice_signature_keys, bob_key_package_bundle, _) =
        setup_alice_bob(ciphersuite, alice_provider, bob_provider);

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build(
            alice_provider,
            &alice_signature_keys,
            alice_credential_with_key,
        )
        .expect("Error creating group.");

    // === Alice adds Bob ===
    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            alice_provider,
            &alice_signature_keys,
            from_ref(bob_key_package_bundle.key_package()),
        )
        .expect("Could not create commit");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");

    let ratchet_tree = alice_group.export_ratchet_tree();

    let bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &MlsGroupJoinConfig::default(),
        welcome.into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Could not stage welcome")
    .into_group(bob_provider)
    .expect("Could not create group from welcome");

    // Let's make sure we end up in the same group state.
    assert_eq!(
        bob_group.epoch_authenticator(),
        alice_group.epoch_authenticator()
    );
    assert_eq!(
        bob_group.export_ratchet_tree(),
        alice_group.export_ratchet_tree()
    )
}

// Test processing of own commits
#[openmls_test::openmls_test]
fn own_commit_processing() {
    // Basic group setup.
    let alice_provider = &Provider::default();
    let (alice_credential_with_key, alice_signature_keys) =
        new_credential(alice_provider, b"Alice", ciphersuite.signature_algorithm());

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build(
            alice_provider,
            &alice_signature_keys,
            alice_credential_with_key,
        )
        .expect("Error creating group.");

    // Alice creates a commit
    let (commit_out, _welcome_option, _group_info_option) = alice_group
        .self_update(
            alice_provider,
            &alice_signature_keys,
            LeafNodeParameters::default(),
        )
        .expect("Could not create commit")
        .into_contents();

    let commit_in = MlsMessageIn::from(commit_out);

    // Alice attempts to process her own commit
    let error = alice_group
        .process_message(alice_provider, commit_in.into_protocol_message().unwrap())
        .expect_err("no error while processing own commit");
    assert_eq!(
        error,
        ProcessMessageError::InvalidCommit(StageCommitError::OwnCommit)
    );
}

#[openmls_test::openmls_test]
fn proposal_application_after_self_was_removed() {
    // We're going to test if proposals are still applied, even after a client
    // notices that it was removed from a group.  We do so by having Alice
    // create a group, add Bob and then create a commit where Bob is removed and
    // Charlie is added in a single commit (by Alice). We then check if
    // everyone's membership list is as expected.

    // Basic group setup.
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let charlie_provider = &Provider::default();

    let (alice_credential_with_key, _, alice_signature_keys, _pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_, bob_kpb, _, _) = setup_client("Bob", ciphersuite, bob_provider);
    let (_, charlie_kpb, _, _) = setup_client("Charlie", ciphersuite, charlie_provider);

    let join_group_config = MlsGroupJoinConfig::builder()
        .wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build();

    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build(
            alice_provider,
            &alice_signature_keys,
            alice_credential_with_key,
        )
        .expect("Error creating group.");

    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            alice_provider,
            &alice_signature_keys,
            from_ref(bob_kpb.key_package()),
        )
        .expect("Could not create commit");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");

    let ratchet_tree = alice_group.export_ratchet_tree();

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &join_group_config,
        welcome.into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Could not stage welcome")
    .into_group(bob_provider)
    .expect("Could not create group from welcome");

    // Alice adds Charlie and removes Bob in the same commit.
    // She first creates a proposal to remove Bob
    let bob_index = alice_group
        .members()
        .find(
            |Member {
                 index: _,
                 credential,
                 ..
             }| { credential.serialized_content() == b"Bob" },
        )
        .expect("Couldn't find Bob in tree.")
        .index;

    assert_eq!(bob_index.u32(), 1);

    let (bob_remove_proposal, _bob_remove_proposal_ref) = alice_group
        .propose_remove_member(alice_provider, &alice_signature_keys, bob_index)
        .expect("Could not create proposal");

    // Bob processes the proposal
    let processed_message = bob_group
        .process_message(
            bob_provider,
            bob_remove_proposal.into_protocol_message().unwrap(),
        )
        .unwrap();

    let staged_proposal = match processed_message.into_content() {
        ProcessedMessageContent::ProposalMessage(proposal) => *proposal,
        _ => panic!("Wrong message type"),
    };

    bob_group
        .store_pending_proposal(bob_provider.storage(), staged_proposal)
        .expect("Error storing proposal");

    // Alice then commit to the proposal and at the same time adds Charlie
    let (commit, welcome, _group_info_option) = alice_group
        .add_members(
            alice_provider,
            &alice_signature_keys,
            from_ref(charlie_kpb.key_package()),
        )
        .expect("Could not create commit");

    // Alice merges her own commit
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");

    // Bob processes the commit
    println!("Bob processes the commit");
    let processed_message = bob_group
        .process_message(bob_provider, commit.into_protocol_message().unwrap())
        .unwrap();

    let staged_commit = match processed_message.into_content() {
        ProcessedMessageContent::StagedCommitMessage(commit) => *commit,
        _ => panic!("Wrong message type"),
    };

    bob_group
        .merge_staged_commit(bob_provider, staged_commit)
        .expect("Error merging commit.");

    // Charlie processes the welcome
    println!("Charlie processes the commit");
    let ratchet_tree = alice_group.export_ratchet_tree();

    let charlie_group = StagedWelcome::new_from_welcome(
        charlie_provider,
        &join_group_config,
        welcome.into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Error staging welcome.")
    .into_group(charlie_provider)
    .expect("Error creating group from welcome.");

    // We can now check that Bob correctly processed his commit and applied the changes
    // to his tree after he was removed by comparing membership lists. In
    // particular, Bob's list should show that he was removed and Charlie was
    // added.
    let alice_members = alice_group.members();

    let bob_members = bob_group.members();

    let charlie_members = charlie_group.members();

    for (alice_member, (bob_member, charlie_member)) in
        alice_members.zip(bob_members.zip(charlie_members))
    {
        // Note that we can't compare encryption keys for Bob because they
        // didn't get updated.
        assert_eq!(alice_member.index, bob_member.index);

        let alice_id = alice_member.credential.serialized_content();
        let bob_id = bob_member.credential.serialized_content();
        let charlie_id = charlie_member.credential.serialized_content();
        assert_eq!(alice_id, bob_id);
        assert_eq!(alice_member.signature_key, bob_member.signature_key);
        assert_eq!(charlie_member.index, bob_member.index);
        assert_eq!(charlie_id, bob_id);
        assert_eq!(charlie_member.signature_key, bob_member.signature_key);
        assert_eq!(charlie_member.encryption_key, alice_member.encryption_key);
    }

    let mut bob_members = bob_group.members();

    let member = bob_members.next().unwrap();
    let bob_next_id = member.credential.serialized_content();
    assert_eq!(bob_next_id, b"Alice");
    let member = bob_members.next().unwrap();
    let bob_next_id = member.credential.serialized_content();
    assert_eq!(bob_next_id, b"Charlie");
}

#[openmls_test::openmls_test]
fn proposal_application_after_self_was_removed_ref() {
    // We're going to test if proposals are still applied, even after a client
    // notices that it was removed from a group.  We do so by having Alice
    // create a group, add Bob and then create a commit where Bob is removed and
    // Charlie is added in a single commit (by Alice). We then check if
    // everyone's membership list is as expected.

    // Basic group setup.
    let alice_provider = &Provider::default();
    let bob_provider = &Provider::default();
    let charlie_provider = &Provider::default();

    let (alice_credential_with_key, _, alice_signature_keys, _pk) =
        setup_client("Alice", ciphersuite, alice_provider);
    let (_, bob_kpb, _, _) = setup_client("Bob", ciphersuite, bob_provider);
    let (_, charlie_kpb, _, _) = setup_client("Charlie", ciphersuite, charlie_provider);

    let join_group_config = MlsGroupJoinConfig::builder()
        .wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build();

    let mut alice_group = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
        .build(
            alice_provider,
            &alice_signature_keys,
            alice_credential_with_key,
        )
        .expect("Error creating group.");

    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            alice_provider,
            &alice_signature_keys,
            from_ref(bob_kpb.key_package()),
        )
        .expect("Could not create commit");

    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");

    let ratchet_tree = alice_group.export_ratchet_tree();

    let mut bob_group = StagedWelcome::new_from_welcome(
        bob_provider,
        &join_group_config,
        welcome.into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Could not stage welcome")
    .into_group(bob_provider)
    .expect("Could not create group from welcome");

    // Alice adds Charlie and removes Bob in the same commit.
    // She first creates a proposal to remove Bob
    let bob_index = alice_group
        .members()
        .find(
            |Member {
                 index: _,
                 credential,
                 ..
             }| { credential.serialized_content() == b"Bob" },
        )
        .expect("Couldn't find Bob in tree.")
        .index;

    assert_eq!(bob_index.u32(), 1);

    let (bob_remove_proposal, _bob_remove_proposal_ref) = alice_group
        .propose_remove_member(alice_provider, &alice_signature_keys, bob_index)
        .expect("Could not create proposal");

    let (charlie_add_proposal, _charlie_add_proposal_ref) = alice_group
        .propose_add_member(
            alice_provider,
            &alice_signature_keys,
            charlie_kpb.key_package(),
        )
        .expect("Could not create proposal");

    // Bob processes the proposals
    let processed_message = bob_group
        .process_message(
            bob_provider,
            bob_remove_proposal.into_protocol_message().unwrap(),
        )
        .unwrap();

    let staged_proposal = match processed_message.into_content() {
        ProcessedMessageContent::ProposalMessage(proposal) => *proposal,
        _ => panic!("Wrong message type"),
    };

    bob_group
        .store_pending_proposal(bob_provider.storage(), staged_proposal)
        .expect("Error storing proposal");

    let processed_message = bob_group
        .process_message(
            bob_provider,
            charlie_add_proposal.into_protocol_message().unwrap(),
        )
        .unwrap();

    let staged_proposal = match processed_message.into_content() {
        ProcessedMessageContent::ProposalMessage(proposal) => *proposal,
        _ => panic!("Wrong message type"),
    };

    bob_group
        .store_pending_proposal(bob_provider.storage(), staged_proposal)
        .expect("Error storing proposal");

    // Alice then commits to the proposal and at the same time adds Charlie
    alice_group.print_ratchet_tree("Alice's tree before commit\n");
    let alice_rt_before = alice_group.export_ratchet_tree();
    let (commit, welcome, _group_info_option) = alice_group
        .commit_to_pending_proposals(alice_provider, &alice_signature_keys)
        .expect("Could not create commit");

    // Alice merges her own commit
    alice_group
        .merge_pending_commit(alice_provider)
        .expect("Could not merge commit");
    alice_group.print_ratchet_tree("Alice's tree after commit\n");

    // Bob processes the commit
    println!("Bob processes the commit");
    bob_group.print_ratchet_tree("Bob's tree before processing the commit\n");
    let bob_rt_before = bob_group.export_ratchet_tree();
    assert_eq!(alice_rt_before, bob_rt_before);
    let processed_message = bob_group
        .process_message(bob_provider, commit.into_protocol_message().unwrap())
        .unwrap();
    println!("Bob finished processesing the commit");

    let staged_commit = match processed_message.into_content() {
        ProcessedMessageContent::StagedCommitMessage(commit) => *commit,
        _ => panic!("Wrong message type"),
    };

    bob_group
        .merge_staged_commit(bob_provider, staged_commit)
        .expect("Error merging commit.");

    // Charlie processes the welcome
    println!("Charlie processes the commit");
    let ratchet_tree = alice_group.export_ratchet_tree();

    let charlie_group = StagedWelcome::new_from_welcome(
        charlie_provider,
        &join_group_config,
        welcome.unwrap().into_welcome().unwrap(),
        Some(ratchet_tree.into()),
    )
    .expect("Error staging welcome.")
    .into_group(charlie_provider)
    .expect("Error creating group from welcome.");

    // We can now check that Bob correctly processed his and applied the changes
    // to his tree after he was removed by comparing membership lists. In
    // particular, Bob's list should show that he was removed and Charlie was
    // added.
    let alice_members = alice_group.members();

    let bob_members = bob_group.members();

    let charlie_members = charlie_group.members();

    for (alice_member, (bob_member, charlie_member)) in
        alice_members.zip(bob_members.zip(charlie_members))
    {
        // Note that we can't compare encryption keys for Bob because they
        // didn't get updated.
        assert_eq!(alice_member.index, bob_member.index);

        let alice_id = alice_member.credential.serialized_content();
        let bob_id = bob_member.credential.serialized_content();
        let charlie_id = charlie_member.credential.serialized_content();
        assert_eq!(alice_id, bob_id);
        assert_eq!(alice_member.signature_key, bob_member.signature_key);
        assert_eq!(charlie_member.index, bob_member.index);
        assert_eq!(charlie_id, bob_id);
        assert_eq!(charlie_member.signature_key, bob_member.signature_key);
        assert_eq!(charlie_member.encryption_key, alice_member.encryption_key);
    }

    let mut bob_members = bob_group.members();

    let member = bob_members.next().unwrap();
    let bob_next_id = member.credential.serialized_content();
    assert_eq!(bob_next_id, b"Alice");
    let member = bob_members.next().unwrap();
    let bob_next_id = member.credential.serialized_content();
    assert_eq!(bob_next_id, b"Charlie");
}

// Test processing of own commits
#[openmls_test::openmls_test]
fn signature_key_rotation() {
    let alice_party = CorePartyState::<Provider>::new("alice");
    let bob_party = CorePartyState::<Provider>::new("bob");

    let alice_pre_group = alice_party.generate_pre_group(ciphersuite);
    let old_credential_with_key = alice_pre_group.credential_with_key.clone();
    let bob_pre_group = bob_party.generate_pre_group(ciphersuite);

    // Create config
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build();

    // Join config
    let mls_group_join_config = mls_group_create_config.join_config().clone();

    // Initialize the group state
    let group_id = GroupId::from_slice(b"test");
    let mut group_state =
        GroupState::new_from_party(group_id, alice_pre_group, mls_group_create_config).unwrap();

    group_state
        .add_member(AddMemberConfig {
            adder: "alice",
            addees: vec![bob_pre_group],
            join_config: mls_group_join_config.clone(),
            tree: None,
        })
        .expect("Could not add member");

    // Generate a new signer for Alice
    let new_pre_group_state = alice_party.generate_pre_group(ciphersuite);

    // Create a commit that updates Alice's signer
    let [alice_group_state] = group_state.members_mut(&["alice"]);

    let old_signature_key = alice_group_state
        .party
        .credential_with_key
        .signature_key
        .clone();
    let new_signature_key = new_pre_group_state
        .credential_with_key
        .signature_key
        .clone();
    assert_ne!(old_signature_key, new_signature_key);

    // Pass leaf node parameters with old credential with key (to make it fail)
    let leaf_node_parameters = LeafNodeParameters::builder()
        .with_credential_with_key(old_credential_with_key)
        .build();

    let new_signer = NewSignerBundle {
        signer: &new_pre_group_state.signer,
        credential_with_key: new_pre_group_state.credential_with_key,
    };

    let err = alice_group_state
        .group
        .self_update_with_new_signer(
            &alice_group_state.party.core_state.provider,
            &alice_group_state.party.signer,
            new_signer.clone(),
            leaf_node_parameters,
        )
        .unwrap_err();

    assert_eq!(
        err,
        SelfUpdateError::CreateCommitError(CreateCommitError::InvalidLeafNodeParameters)
    );

    // Calling with default LeafNodeParameters should work
    let bundle = alice_group_state
        .group
        .self_update_with_new_signer(
            &alice_group_state.party.core_state.provider,
            &alice_group_state.party.signer,
            new_signer,
            LeafNodeParameters::default(),
        )
        .unwrap();

    alice_group_state
        .group
        .merge_pending_commit(&alice_group_state.party.core_state.provider)
        .unwrap();

    group_state
        .deliver_and_apply_if(bundle.into_commit().into(), |state| {
            state.party.core_state.name != "alice"
        })
        .unwrap();

    // Check that the signature key was rotated
    let [bob_group_state] = group_state.members_mut(&["bob"]);
    let alice_signature_key = bob_group_state
        .group
        .members()
        .find(|m| m.index == LeafNodeIndex::new(0))
        .unwrap()
        .signature_key;
    assert_eq!(alice_signature_key.as_slice(), new_signature_key.as_slice());

    // Check that we can send messages using the new signer.
    let [alice_group_state] = group_state.members_mut(&["alice"]);

    let bundle = alice_group_state
        .group
        .self_update(
            &alice_group_state.party.core_state.provider,
            &new_pre_group_state.signer,
            LeafNodeParameters::default(),
        )
        .unwrap();

    group_state
        .deliver_and_apply_if(bundle.into_commit().into(), |state| {
            state.party.core_state.name != "alice"
        })
        .unwrap();
}

#[openmls_test::openmls_test]
fn group_replacement() {
    // Create a group with Alice and Bob
    let alice_party = CorePartyState::<Provider>::new("alice");
    let bob_party = CorePartyState::<Provider>::new("bob");

    let alice_pre_group = alice_party.generate_pre_group(ciphersuite);

    let alice_credential_with_key = alice_pre_group.credential_with_key.clone();
    let alice_signer = alice_pre_group.signer.clone();

    let bob_pre_group = bob_party.generate_pre_group(ciphersuite);

    let bob_kpb = KeyPackageBundle::generate(
        &bob_party.provider,
        &bob_pre_group.signer,
        ciphersuite,
        bob_pre_group.credential_with_key.clone(),
    );

    let bob_kpb2 = KeyPackageBundle::generate(
        &bob_party.provider,
        &bob_pre_group.signer,
        ciphersuite,
        bob_pre_group.credential_with_key.clone(),
    );

    // Create config
    let mls_group_create_config = MlsGroupCreateConfig::builder()
        .ciphersuite(ciphersuite)
        .use_ratchet_tree_extension(true)
        .build();

    // Join config
    let mls_group_join_config = mls_group_create_config.join_config().clone();

    // Initialize the group state
    let group_id = GroupId::from_slice(b"test");
    let mut group_state =
        GroupState::new_from_party(group_id.clone(), alice_pre_group, mls_group_create_config)
            .unwrap();

    group_state
        .add_member(AddMemberConfig {
            adder: "alice",
            addees: vec![bob_pre_group],
            join_config: mls_group_join_config.clone(),
            tree: None,
        })
        .expect("Could not add member");

    // Creating a new group with the same ID should fail
    let err = MlsGroup::builder()
        .ciphersuite(ciphersuite)
        .with_group_id(group_id.clone())
        .use_ratchet_tree_extension(true)
        .build(
            &alice_party.provider,
            &alice_signer,
            alice_credential_with_key.clone(),
        )
        .expect_err("Creating a group with an existing ID succeeded unexpectedly.");
    assert_eq!(err, NewGroupError::GroupAlreadyExists);

    let mut alice_group = MlsGroup::builder()
        .replace_old_group()
        .ciphersuite(ciphersuite)
        .with_group_id(group_id.clone())
        .use_ratchet_tree_extension(true)
        .build(
            &alice_party.provider,
            &alice_signer,
            alice_credential_with_key.clone(),
        )
        .expect("Group creation failed despite replace flag");

    // Alice invites Bob to the new group
    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            &alice_party.provider,
            &alice_signer,
            &[bob_kpb.key_package().clone()],
        )
        .unwrap();

    let welcome = welcome.into_welcome().unwrap();
    let processed_welcome = ProcessedWelcome::new_from_welcome(
        &bob_party.provider,
        &mls_group_join_config,
        welcome.clone(),
    )
    .unwrap();
    let err = JoinBuilder::new(&bob_party.provider, processed_welcome)
        .build()
        .expect_err("Bob joined the new group unexpectedly.");
    assert_eq!(err, WelcomeError::GroupAlreadyExists);

    let mut alice_group = MlsGroup::builder()
        .replace_old_group()
        .ciphersuite(ciphersuite)
        .with_group_id(group_id)
        .use_ratchet_tree_extension(true)
        .build(
            &alice_party.provider,
            &alice_signer,
            alice_credential_with_key,
        )
        .expect("Group creation failed despite replace flag");

    // Alice invites Bob to the new group
    let (_commit, welcome, _group_info_option) = alice_group
        .add_members(
            &alice_party.provider,
            &alice_signer,
            &[bob_kpb2.key_package().clone()],
        )
        .unwrap();

    let welcome = welcome.into_welcome().unwrap();

    let processed_welcome = ProcessedWelcome::new_from_welcome(
        &bob_party.provider,
        &mls_group_join_config,
        welcome.clone(),
    )
    .unwrap();

    let _ = JoinBuilder::new(&bob_party.provider, processed_welcome)
        .replace_old_group()
        .build()
        .expect("Bob failed to join the new group despite replace flag.");
}