aranya-client 6.0.0

Client library for using Aranya
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
use std::{ptr, time::Duration};

use anyhow::{bail, Context, Result};
use tracing::{debug, info};

use super::common::{sleep, DeviceCtx, DevicesCtx, SLEEP_INTERVAL};
#[cfg(feature = "preview")]
use crate::config::HelloSubscriptionConfig;
use crate::{
    client::{ChanOp, Permission},
    config::{CreateTeamConfig, SyncPeerConfig},
    text, AddTeamConfig, AddTeamQuicSyncConfig, CreateTeamQuicSyncConfig, Rank,
};

/// Tests getting keybundle and device ID.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_get_keybundle_device_id() -> Result<()> {
    let devices = DevicesCtx::new("test_get_keybundle_device_id").await?;

    // Note: get_device_id() and get_key_bundle() are already invoked in `DevicesCtx::new()`.
    // This test makes sure we don't accidentally break the API from a backward compatibility standpoint.
    assert_eq!(
        devices.owner.client.get_device_id().await?,
        devices.owner.id
    );
    assert_eq!(
        devices.owner.client.get_public_key_bundle().await?,
        devices.owner.pk
    );

    Ok(())
}

/// Tests generating random numbers with the aranya client.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_client_rand() -> Result<()> {
    let devices = DevicesCtx::new("test_get_keybundle_device_id").await?;

    let mut buf1 = vec![0u8; 100];
    devices.owner.client.rand(&mut buf1).await;
    let mut buf2 = vec![0u8; 100];
    devices.owner.client.rand(&mut buf2).await;

    // Randomly generated numbers should never match.
    assert_ne!(buf1, buf2);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_trace_id_round_trip() -> Result<()> {
    let work_dir = tempfile::tempdir()?;
    let owner = DeviceCtx::new("trace-roundtrip", "owner", work_dir.path().join("owner")).await?;

    let (client_trace_id, daemon_trace_id) = owner.client.test_trace_id().await?;
    info!("client trace_id: {client_trace_id}");
    info!("daemon trace_id: {daemon_trace_id}");

    assert_eq!(client_trace_id, daemon_trace_id);
    assert_ne!(client_trace_id, "00");

    Ok(())
}

/// Tests sync_now() by showing that an admin cannot perform operations until it syncs with the owner.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_sync_now() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_sync_now").await?;

    // Create the initial team, and get our TeamId and seed.
    let team_id = devices.create_and_add_team().await?;

    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    let owner_addr = devices.owner.aranya_local_addr().await?;

    let owner = devices.owner.client.team(team_id);
    let admin = devices.admin.client.team(team_id);

    // Add the admin as a new device, but don't give it a role.
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner
        .add_device(
            devices.admin.pk.clone(),
            None,
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("owner unable to add admin to team")?;

    // Add the operator as a new device, but don't give it a role.
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    owner
        .add_device(
            devices.operator.pk.clone(),
            None,
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("owner unable to add operator to team")?;

    // Finally, let's give the admin its role, but don't sync with peers.
    owner
        .device(devices.admin.id)
        .assign_role(roles.admin().id)
        .await
        .context("owner unable to assign admin role")?;

    // Now, we try to assign a role using the admin, which is expected to fail
    // because the admin hasn't synced yet and doesn't know about its role.
    let err = admin
        .device(devices.operator.id)
        .assign_role(roles.operator().id)
        .await
        .expect_err("admin has not synced yet, role assignment should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    // Let's sync immediately, which will propagate the role change.
    admin
        .sync_now(owner_addr, None)
        .await
        .context("admin unable to sync with owner")?;

    // Now we should be able to successfully create a label (admin has CreateLabel perm).
    let member_role_rank = admin.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    admin
        .create_label(text!("test_label"), label_rank)
        .await
        .context("admin unable to create label after sync")?;

    Ok(())
}

/// Tests adding/removing sync peers.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_remove_sync_peers() -> Result<()> {
    let mut devices = DevicesCtx::new("test_add_remove_sync_peers").await?;
    let team_id = devices
        .create_and_add_team()
        .await
        .expect("expected to create team");

    // create default roles
    let roles = devices.setup_default_roles(team_id).await?;

    // add all sync peers with sync intervals.
    devices
        .add_all_sync_peers(team_id)
        .await
        .context("unable to add all sync peers")?;

    // TODO: if this is removed the label queries have a seal error.
    devices.add_all_device_roles(team_id, &roles).await?;

    // Add a command to graph by having the owner create a label.
    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team.create_label(text!("label1"), label_rank).await?;

    // Wait for syncing.
    // We're sleeping here rather than syncing via `sync_now()` to test periodic sync functionality.
    sleep(SLEEP_INTERVAL).await;

    // Verify peers automatically sync command with sync peer.
    // They should receive the label that was created.
    let owner_team_labels = owner_team.labels().await?;
    assert_eq!(owner_team_labels.iter().count(), 1);

    let membera_team = devices.membera.client.team(team_id);
    let membera_team_labels = membera_team.labels().await?;
    assert_eq!(membera_team_labels.iter().count(), 1);

    let memberb_team = devices.memberb.client.team(team_id);
    let memberb_team_labels = memberb_team.labels().await?;
    assert_eq!(memberb_team_labels.iter().count(), 1);

    // Remove sync peers.
    for device in devices.devices() {
        for peer in devices.devices() {
            if ptr::eq(device, peer) {
                continue;
            }
            device
                .client
                .team(team_id)
                .remove_sync_peer(peer.aranya_local_addr().await?)
                .await?;
        }
    }

    let owner_addr = devices.owner.aranya_local_addr().await?;
    membera_team.remove_sync_peer(owner_addr).await?;
    let membera_addr = devices.membera.aranya_local_addr().await?;
    owner_team.remove_sync_peer(membera_addr).await?;

    // Create another label.
    owner_team.create_label(text!("label2"), label_rank).await?;

    // Wait for syncing.
    sleep(SLEEP_INTERVAL).await;

    // Verify device doesn't see label after sync peer is removed.
    let labels_after_removing_sync_peer = membera_team.labels().await?;
    assert_eq!(labels_after_removing_sync_peer.iter().count(), 1);

    Ok(())
}

/// Tests creating/assigning/revoking a role.
/// Verifies query indicates correct role assignment status.
/// Verifies device is only allowed to perform operation when role with permission is assigned to it.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_role_create_assign_revoke() -> Result<()> {
    // Set up our team context so we can run the test.
    let devices = DevicesCtx::new("test_role_create_assign_revoke").await?;

    // Grab the shorthand for our address.
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Create the initial team, and get our TeamId.
    let owner = devices
        .owner
        .client
        .create_team({
            CreateTeamConfig::builder()
                .quic_sync(CreateTeamQuicSyncConfig::builder().build()?)
                .build()?
        })
        .await
        .expect("expected to create team");
    let team_id = owner.team_id();
    info!(?team_id);

    let roles = devices.setup_default_roles(team_id).await?;
    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Query to show admin role exists.
    let roles_on_team = owner_team.roles().await?;
    assert_eq!(roles_on_team.iter().count(), 4);
    roles_on_team
        .iter()
        .find(|r| r.name == "admin")
        .ok_or_else(|| anyhow::anyhow!("no admin role"))?;

    let member_role_rank = owner_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));

    // Show that admin cannot create a label.
    admin_team
        .create_label(text!("label1"), label_rank)
        .await
        .expect_err("expected label creation to fail");

    // Add the admin as a new device.
    info!("adding admin to team");
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner
        .add_device(
            devices.admin.pk.clone(),
            None,
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;

    // Add team to admin device.
    let admin_seed = owner
        .encrypt_psk_seed_for_peer(devices.admin.pk.encryption())
        .await?;
    devices
        .admin
        .client
        .add_team({
            AddTeamConfig::builder()
                .team_id(team_id)
                .quic_sync(
                    AddTeamQuicSyncConfig::builder()
                        .wrapped_seed(&admin_seed)?
                        .build()?,
                )
                .build()?
        })
        .await?;

    // Admin sync with owner.
    admin_team
        .sync_now(owner_addr, None)
        .await
        .context("admin unable to sync with owner")?;

    // Show that admin cannot create a label.
    admin_team
        .create_label(text!("label1"), label_rank)
        .await
        .expect_err("expected label creation to fail");

    // Give the admin its role.
    owner
        .device(devices.admin.id)
        .assign_role(roles.admin().id)
        .await?;

    // Admin sync with owner.
    admin_team
        .sync_now(owner_addr, None)
        .await
        .context("admin unable to sync with owner")?;

    // Query to show admin role is assigned to admin device.
    let admin_role = admin_team
        .device(devices.admin.id)
        .role()
        .await?
        .expect("expected admin device to have role assigned to it");
    assert_eq!(admin_role.name, text!("admin"));

    // Create label.
    let label1 = admin_team
        .create_label(text!("label1"), label_rank)
        .await
        .expect("expected admin to create label");

    // Confirm there is 1 label on team.
    assert_eq!(admin_team.labels().await?.iter().count(), 1);

    // Confirm created label exists.
    admin_team.label(label1).await?;

    // Revoke role.
    owner
        .device(devices.admin.id)
        .revoke_role(roles.admin().id)
        .await?;

    // Admin sync with owner.
    admin_team
        .sync_now(owner_addr, None)
        .await
        .context("admin unable to sync with owner")?;

    // Query to show admin role is no longer assigned to admin device.
    if admin_team.device(devices.admin.id).role().await?.is_some() {
        bail!("did not expect role to be assigned to admin device");
    }

    // Show that admin cannot create a label.
    admin_team
        .create_label(text!("label1"), label_rank)
        .await
        .expect_err("expected label creation to fail");

    // TODO: issue#575 show operation fails after delete_role() (after it is added to the API).

    Ok(())
}

/// Tests that a role can be changed after it has been assigned to a device.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_role_change() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_role_change").await?;

    // Create the initial team, and get our TeamId and seed.
    let team_id = devices.create_and_add_team().await?;

    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner = devices.owner.client.team(team_id);

    // Assign operator role to membera.
    owner
        .device(devices.membera.id)
        .change_role(roles.member().id, roles.operator().id)
        .await
        .expect("expected to change role from member to operator");

    Ok(())
}

/// Tests that devices can be added to the team.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_devices() -> Result<()> {
    let mut team = DevicesCtx::new("test_add_devices").await?;

    let team_id = team
        .create_and_add_team()
        .await
        .expect("expected to create team");
    info!(?team_id);

    let owner = team.owner.client.team(team_id);
    let admin = team.admin.client.team(team_id);
    let operator = team.operator.client.team(team_id);

    // There are now three more roles in addition to the original
    // owner role:
    // - admin
    // - operator
    // - member
    // The owner role manages all of those roles.
    let roles = team
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    // Add the initial admin who should be allowed to add
    // devices.
    let admin_role_rank = team
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner
        .add_device(
            team.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("owner should be able to add admin to team")?;

    admin
        .sync_now(team.owner.aranya_local_addr().await?, None)
        .await
        .context("admin unable to sync with owner")?;

    // Admin adds operator without initial role (admin has AddDevice but not AssignRole).
    let operator_role_rank = team
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    admin
        .add_device(
            team.operator.pk.clone(),
            None,
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("admin should be able to add operator to team")?;

    // Owner assigns operator role (owner has AssignRole).
    owner
        .sync_now(team.admin.aranya_local_addr().await?, None)
        .await
        .context("owner unable to sync with admin")?;
    owner
        .device(team.operator.id)
        .assign_role(roles.operator().id)
        .await
        .context("owner should be able to assign operator role")?;

    operator
        .sync_now(team.owner.aranya_local_addr().await?, None)
        .await
        .context("operator unable to sync with owner")?;

    let member_role_rank = team
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    for (name, kb, device_id) in [
        ("membera", team.membera.pk.clone(), team.membera.id),
        ("memberb", team.memberb.pk.clone(), team.memberb.id),
    ] {
        // Admin adds members without role (admin has AddDevice but not AssignRole).
        admin
            .add_device(
                kb,
                None,
                Rank::new(member_role_rank.value().saturating_sub(1)),
            )
            .await
            .with_context(|| format!("admin should be able to add `{name}` to team"))?;
        // Operator syncs to see newly added device, then assigns member role (operator has AssignRole).
        operator
            .sync_now(team.admin.aranya_local_addr().await?, None)
            .await
            .context("operator unable to sync with admin")?;
        operator
            .device(device_id)
            .assign_role(roles.member().id)
            .await
            .with_context(|| {
                format!("operator should be able to assign member role to `{name}`")
            })?;
    }

    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_device_with_initial_role_requires_outranking() -> Result<()> {
    let mut devices =
        DevicesCtx::new("test_add_device_with_initial_role_requires_outranking").await?;

    let team_id = devices.create_and_add_team().await?;

    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Admin already has AddDevice from setup_default_roles, but needs AssignRole
    // to add a device with an initial role assignment.
    owner_team
        .add_perm_to_role(roles.admin().id, Permission::AssignRole)
        .await
        .context("owner should be able to add AssignRole to admin")?;

    // Add admin with rank below admin role (outranks member role at rank 600).
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    let member_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("owner should be able to add admin to team")?;

    admin_team
        .sync_now(devices.owner.aranya_local_addr().await?, None)
        .await
        .context("admin unable to sync with owner")?;

    // Admin should succeed at adding membera with member role
    // because admin outranks the member role and has both AddDevice and AssignRole perms.
    admin_team
        .add_device(
            devices.membera.pk.clone(),
            Some(roles.member().id),
            Rank::new(member_role_rank.value().saturating_sub(1)),
        )
        .await
        .context("admin should be able to add device with member role (admin outranks member)")?;

    // Admin should fail when trying to add a device with the owner role
    // because admin does not outrank the owner role.
    match admin_team
        .add_device(
            devices.memberb.pk.clone(),
            Some(roles.owner().id),
            Rank::new(member_role_rank.value().saturating_sub(1)),
        )
        .await
    {
        Ok(_) => {
            bail!("expected add_device with owner role to fail (admin does not outrank owner)")
        }
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected error: {err:?}"),
    }

    Ok(())
}

/// Tests that devices can be removed from the team.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_remove_devices() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_remove_devices").await?;

    // Create the initial team, and get our TeamId.
    let team_id = devices
        .create_and_add_team()
        .await
        .expect("expected to create team");
    info!(?team_id);

    // Setup default roles and ensure delegations exist for helper routines.
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    // Tell all peers to sync with one another, and assign their roles.
    devices.add_all_device_roles(team_id, &roles).await?;

    // Remove devices from the team while checking that the device count decreases each time a device is removed.
    let owner = devices.owner.client.team(team_id);

    assert_eq!(owner.devices().await?.iter().count(), 5);

    owner.device(devices.membera.id).remove_from_team().await?;
    assert_eq!(owner.devices().await?.iter().count(), 4);

    owner.device(devices.memberb.id).remove_from_team().await?;
    assert_eq!(owner.devices().await?.iter().count(), 3);

    owner.device(devices.operator.id).remove_from_team().await?;
    assert_eq!(owner.devices().await?.iter().count(), 2);

    owner.device(devices.admin.id).remove_from_team().await?;
    assert_eq!(owner.devices().await?.iter().count(), 1);

    owner
        .device(devices.owner.id)
        .remove_from_team()
        .await
        .expect_err("owner should not be able to remove itself from team");

    Ok(())
}

/// Tests functionality to make sure that we can query the fact database for various things.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_query_functions() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_query_functions").await?;

    // Create the initial team, and get our TeamId and seed.
    let team_id = devices.create_and_add_team().await?;

    // Set up the default roles first
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    // Tell all peers to sync with one another, and assign their roles.
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label_id = owner_team.create_label(text!("label1"), label_rank).await?;

    // Assigning labels to devices with the "member" role should succeed since it does not have `CanUseAfc` permission.
    let op = ChanOp::SendRecv;
    owner_team
        .device(devices.membera.id)
        .assign_label(label_id, op)
        .await?;
    owner_team
        .device(devices.memberb.id)
        .assign_label(label_id, op)
        .await?;

    // wait for syncing.
    let owner_addr = devices.owner.aranya_local_addr().await?;
    devices
        .membera
        .client
        .team(team_id)
        .sync_now(owner_addr, None)
        .await?;
    devices
        .memberb
        .client
        .team(team_id)
        .sync_now(owner_addr, None)
        .await?;

    // Test all our fact database queries.
    let memberb = devices.membera.client.team(team_id);

    // First, let's check how many devices are on the team.
    let devices_query = memberb.devices().await?;
    assert_eq!(devices_query.iter().count(), 5);
    debug!(
        "membera devices on team: {:?}",
        devices_query.iter().count()
    );

    // Check the specific role(s) a device has.
    let dev_role = memberb.device(devices.membera.id).role().await?;
    assert_eq!(dev_role.as_ref().map(|r| r.id), Some(roles.member().id));
    debug!("membera role: {:?}", dev_role);

    // Make sure that we have the correct keybundle.
    let keybundle = memberb
        .device(devices.membera.id)
        .public_key_bundle()
        .await?;
    debug!("membera keybundle: {:?}", keybundle);

    // Make sure membera can query labels assigned to it.
    let membera_labels = memberb
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(membera_labels.iter().count(), 1);

    // Make sure owner can query labels created on the team.
    let team_labels = owner_team.labels().await?;
    assert_eq!(team_labels.iter().count(), 1);

    // Make sure owner can query the label on the team.
    owner_team.label(label_id).await?;

    // Query role assigned to a device.
    assert_eq!(
        roles.member().id,
        memberb
            .device(devices.memberb.id)
            .role()
            .await?
            .expect("expected role")
            .id
    );

    // Query all the roles on the team.
    let membera_team = devices.membera.client.team(team_id);
    assert_eq!(membera_team.roles().await?.iter().count(), 4);

    Ok(())
}

/// Tests add_team() by demonstrating that syncing can only occur after
/// a peer calls the add_team() API
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_team() -> Result<()> {
    // Set up our team context so we can run the test.
    let devices = DevicesCtx::new("test_add_team").await?;

    // Grab the shorthand for our address.
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Create the initial team, and get our TeamId.
    let owner = devices
        .owner
        .client
        .create_team({
            CreateTeamConfig::builder()
                .quic_sync(CreateTeamQuicSyncConfig::builder().build()?)
                .build()?
        })
        .await
        .expect("expected to create team");
    let team_id = owner.team_id();
    info!(?team_id);

    let roles = devices.setup_default_roles(team_id).await?;
    let member_role_rank = owner.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));

    // Add the admin as a new device.
    info!("adding admin to team");
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner
        .add_device(
            devices.admin.pk.clone(),
            None,
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;

    // Add the operator as a new device.
    info!("adding operator to team");
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    owner
        .add_device(
            devices.operator.pk.clone(),
            None,
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;

    // Give the admin its role.
    owner
        .device(devices.admin.id)
        .assign_role(roles.admin().id)
        .await?;

    // Let's sync immediately. The role change will not propogate since add_team() hasn't been called.
    {
        let admin = devices.admin.client.team(team_id);
        let err = admin
            .sync_now(owner_addr, None)
            .await
            .expect_err("syncing should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

        // Now, we try to assign a role using the admin, which is expected to fail
        // because the admin hasn't called add_team() yet.
        let err = admin
            .device(devices.operator.id)
            .assign_role(roles.operator().id)
            .await
            .expect_err("role assignment should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");
    }

    let admin_seed = owner
        .encrypt_psk_seed_for_peer(devices.admin.pk.encryption())
        .await?;
    devices
        .admin
        .client
        .add_team({
            AddTeamConfig::builder()
                .team_id(team_id)
                .quic_sync(
                    AddTeamQuicSyncConfig::builder()
                        .wrapped_seed(&admin_seed)?
                        .build()?,
                )
                .build()?
        })
        .await?;
    {
        let admin = devices.admin.client.team(team_id);
        admin.sync_now(owner_addr, None).await?;

        // Now we should be able to successfully create a label (admin has CreateLabel perm).
        admin
            .create_label(text!("test_label"), label_rank)
            .await
            .context("Creating a label should not fail here!")?;
    }

    return Ok(());
}

/// Tests that devices can be removed from the team.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_remove_team() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_remove_team").await?;

    // Create the initial team, and get our TeamId.
    let team_id = devices
        .create_and_add_team()
        .await
        .expect("expected to create team");
    info!(?team_id);

    let owner = devices.owner.client.team(team_id);
    let roles = devices.setup_default_roles(team_id).await?;
    let member_role_rank = owner.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));

    {
        let admin = devices.admin.client.team(team_id);

        // Add the operator as a new device.
        info!("adding operator to team");
        let operator_role_rank = devices
            .owner
            .client
            .team(team_id)
            .rank(roles.operator().id)
            .await?;
        owner
            .add_device(
                devices.operator.pk.clone(),
                None,
                Rank::new(operator_role_rank.value().saturating_sub(1)),
            )
            .await?;

        // Add the admin as a new device.
        let admin_role_rank = devices
            .owner
            .client
            .team(team_id)
            .rank(roles.admin().id)
            .await?;
        owner
            .add_device(
                devices.admin.pk.clone(),
                None,
                Rank::new(admin_role_rank.value().saturating_sub(1)),
            )
            .await?;

        // Give the admin its role.
        owner
            .device(devices.admin.id)
            .assign_role(roles.admin().id)
            .await?;

        admin
            .sync_now(devices.owner.aranya_local_addr().await?, None)
            .await?;

        // We should be able to successfully create a label (admin has CreateLabel perm).
        admin.create_label(text!("test_label"), label_rank).await?;
    }

    // Remove the team from the admin's local storage
    devices.admin.client.remove_team(team_id).await?;

    {
        let admin = devices.admin.client.team(team_id);

        // Label creation should fail since the team was removed from local storage above.
        match admin.create_label(text!("test_label2"), label_rank).await {
            Ok(_) => bail!("Expected label creation to fail"),
            Err(crate::Error::Aranya(_)) => {}
            Err(_) => bail!("Unexpected error"),
        }
    }

    Ok(())
}

/// Tests that a device can create multiple teams and receive sync requests for each team.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_multi_team_sync() -> Result<()> {
    // Set up our team context so we can run the test.
    let devices = DevicesCtx::new("test_multi_team_sync").await?;

    // Grab the shorthand for our address.
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Create the initial team, and get our TeamId.
    let team1 = devices
        .owner
        .client
        .create_team({
            CreateTeamConfig::builder()
                .quic_sync(CreateTeamQuicSyncConfig::builder().build()?)
                .build()?
        })
        .await
        .expect("expected to create team1");
    let team_id1 = team1.team_id();
    info!(?team_id1);

    // Create the second team, and get our TeamId.
    let team2 = devices
        .owner
        .client
        .create_team({
            CreateTeamConfig::builder()
                .quic_sync(CreateTeamQuicSyncConfig::builder().build()?)
                .build()?
        })
        .await
        .expect("expected to create team2");
    let team_id2 = team2.team_id();
    info!(?team_id2);

    // Set up roles for team1
    let roles1 = devices.setup_default_roles(team_id1).await?;

    // Set up roles for team2
    let roles2 = devices.setup_default_roles(team_id2).await?;

    // Add the admin as a new device.
    info!("adding admin to team1");
    let admin_role_rank_t1 = devices
        .owner
        .client
        .team(team_id1)
        .rank(roles1.admin().id)
        .await?;
    let operator_role_rank_t1 = devices
        .owner
        .client
        .team(team_id1)
        .rank(roles1.operator().id)
        .await?;
    team1
        .add_device(
            devices.admin.pk.clone(),
            None,
            Rank::new(admin_role_rank_t1.value().saturating_sub(1)),
        )
        .await?;

    // Add the operator as a new device.
    info!("adding operator to team1");
    team1
        .add_device(
            devices.operator.pk.clone(),
            None,
            Rank::new(operator_role_rank_t1.value().saturating_sub(1)),
        )
        .await?;

    // Give the admin its role.
    team1
        .device(devices.admin.id)
        .assign_role(roles1.admin().id)
        .await?;

    // Add the admin as a new device.
    info!("adding admin to team2");
    let admin_role_rank_t2 = devices
        .owner
        .client
        .team(team_id2)
        .rank(roles2.admin().id)
        .await?;
    let operator_role_rank_t2 = devices
        .owner
        .client
        .team(team_id2)
        .rank(roles2.operator().id)
        .await?;
    team2
        .add_device(
            devices.admin.pk.clone(),
            None,
            Rank::new(admin_role_rank_t2.value().saturating_sub(1)),
        )
        .await?;

    // Add the operator as a new device.
    info!("adding operator to team2");
    team2
        .add_device(
            devices.operator.pk.clone(),
            None,
            Rank::new(operator_role_rank_t2.value().saturating_sub(1)),
        )
        .await?;

    // Give the admin its role.
    team2
        .device(devices.admin.id)
        .assign_role(roles2.admin().id)
        .await?;

    // Let's sync immediately. The role change will not propogate since add_team() hasn't been called.
    {
        let admin = devices.admin.client.team(team_id1);
        let err = admin
            .sync_now(owner_addr, None)
            .await
            .expect_err("syncing team1 should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

        // Now, we try to assign a role using the admin, which is expected to fail
        // because add_team() hasn't been called yet.
        let err = admin
            .device(devices.operator.id)
            .assign_role(roles1.operator().id)
            .await
            .expect_err("role assignment on team1 should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");
    }

    let admin_seed1 = team1
        .encrypt_psk_seed_for_peer(devices.admin.pk.encryption())
        .await?;
    devices
        .admin
        .client
        .add_team({
            AddTeamConfig::builder()
                .team_id(team_id1)
                .quic_sync(
                    AddTeamQuicSyncConfig::builder()
                        .wrapped_seed(&admin_seed1)?
                        .build()?,
                )
                .build()?
        })
        .await?;

    let admin1 = devices.admin.client.team(team_id1);
    admin1.sync_now(owner_addr, None).await?;

    // Now we should be able to successfully create a label (admin has CreateLabel perm).
    let member_role_rank_t1 = admin1.rank(roles1.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank_t1 = Rank::new(member_role_rank_t1.value().saturating_sub(1));
    admin1
        .create_label(text!("team1_label"), label_rank_t1)
        .await
        .context("Creating a label should not fail here!")?;

    // Let's sync immediately. The role change will not propogate since add_team() hasn't been called.
    {
        let admin = devices.admin.client.team(team_id2);
        let err = admin
            .sync_now(owner_addr, None)
            .await
            .expect_err("syncing team2 should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

        // Now, we try to assign a role using the admin, which is expected to fail
        // because add_team() hasn't been called for team2 yet.
        let err = admin
            .device(devices.operator.id)
            .assign_role(roles2.operator().id)
            .await
            .expect_err("role assignment on team2 should fail before add_team()");
        assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");
    }

    let admin_seed2 = team2
        .encrypt_psk_seed_for_peer(devices.admin.pk.encryption())
        .await?;
    devices
        .admin
        .client
        .add_team({
            AddTeamConfig::builder()
                .team_id(team_id2)
                .quic_sync(
                    AddTeamQuicSyncConfig::builder()
                        .wrapped_seed(&admin_seed2)?
                        .build()?,
                )
                .build()?
        })
        .await?;

    let admin2 = devices.admin.client.team(team_id2);
    admin2.sync_now(owner_addr, None).await?;

    // Now we should be able to successfully create a label (admin has CreateLabel perm).
    let member_role_rank_t2 = admin2.rank(roles2.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank_t2 = Rank::new(member_role_rank_t2.value().saturating_sub(1));
    admin2
        .create_label(text!("team2_label"), label_rank_t2)
        .await
        .context("Creating a label should not fail here!")?;

    Ok(())
}

/// Tests hello subscription functionality by demonstrating that devices can subscribe
/// to hello notifications from peers and automatically sync when receiving notifications.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
#[cfg(feature = "preview")]
async fn test_hello_subscription() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_hello_subscription").await?;

    // Create the initial team, and get our TeamId.
    let team_id = devices.create_and_add_team().await?;

    let roles = devices.setup_default_roles(team_id).await?;
    devices.add_all_device_roles(team_id, &roles).await?;

    // Grab addresses for testing
    let admin_addr = devices.admin.aranya_local_addr().await?;

    // Grab the shorthand for the teams we need to operate on.
    let membera_team = devices.membera.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    let sync_config = SyncPeerConfig::builder()
        .sync_now(false)
        .sync_on_hello(true)
        .build()?;

    membera_team.add_sync_peer(admin_addr, sync_config).await?;
    info!("membera added admin as sync peer with sync_on_hello=true");

    // MemberA subscribes to hello notifications from Admin
    // Use a long periodic_interval to ensure sync is triggered by graph change, not periodic send
    membera_team
        .sync_hello_subscribe(
            admin_addr,
            HelloSubscriptionConfig::builder()
                .periodic_interval(Duration::from_secs(60))
                .build()?,
        )
        .await?;
    info!("membera subscribed to hello notifications from admin");

    // Before the action, verify that MemberA doesn't know about any labels created by admin
    // (This will be our way to test if sync worked)
    info!("verifying initial state - membera should not see any labels created by admin");
    let initial_labels = membera_team.labels().await?;
    let initial_label_count = initial_labels.iter().count();
    info!(
        "initial label count as seen by membera: {}",
        initial_label_count
    );

    // Admin performs an action that will update their graph - create a label
    // (admin has permission to create labels)
    info!("admin creating a test label");
    let member_role_rank = admin_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let test_label = admin_team
        .create_label(
            aranya_daemon_api::text!("sync_hello_test_label"),
            label_rank,
        )
        .await?;
    info!("admin created test label: {:?}", test_label);

    // Wait for hello message to be sent and sync to be triggered
    // The hello message should be sent, membera should receive it,
    // check that the command doesn't exist locally, and trigger a sync
    info!("waiting for hello message and automatic sync...");

    // Poll every 100ms for up to 10 seconds for the label count to increase
    let poll_start = std::time::Instant::now();
    let poll_timeout = Duration::from_millis(10_000);
    let poll_interval = Duration::from_millis(100);

    let final_labels = loop {
        let current_labels = membera_team.labels().await?;
        let current_count = current_labels.iter().count();

        if current_count > initial_label_count {
            info!(
                "sync detected - label count increased from {} to {} after {:?}",
                initial_label_count,
                current_count,
                poll_start.elapsed()
            );
            break current_labels;
        }

        if poll_start.elapsed() >= poll_timeout {
            bail!(
                "Sync on hello failed: timeout after {:?} - expected label count to increase from {} but it remained at {}",
                poll_timeout,
                initial_label_count,
                current_count
            );
        }

        sleep(poll_interval).await;
    };

    // Verify that the specific label created by admin is visible
    let label_exists = final_labels
        .iter()
        .any(|label| label.name.as_str() == "sync_hello_test_label");

    if !label_exists {
        bail!("Sync on hello failed: the test label created by admin is not visible to membera");
    }

    info!("sync_on_hello test succeeded - membera automatically synced after receiving hello notification");

    // Test basic subscription/unsubscription functionality for completeness
    info!("testing basic subscription functionality");

    let owner_addr = devices.owner.aranya_local_addr().await?;
    let operator_team = devices.operator.client.team(team_id);

    // Admin subscribes to hello notifications from Owner
    admin_team
        .sync_hello_subscribe(owner_addr, HelloSubscriptionConfig::default())
        .await?;
    info!("admin subscribed to hello notifications from owner");

    // Test multiple subscriptions
    operator_team
        .sync_hello_subscribe(owner_addr, HelloSubscriptionConfig::default())
        .await?;
    operator_team
        .sync_hello_subscribe(admin_addr, HelloSubscriptionConfig::default())
        .await?;
    info!("operator subscribed to both owner and admin");

    // Test unsubscribing
    admin_team.sync_hello_unsubscribe(owner_addr).await?;
    operator_team.sync_hello_unsubscribe(owner_addr).await?;
    operator_team.sync_hello_unsubscribe(admin_addr).await?;
    membera_team.sync_hello_unsubscribe(admin_addr).await?;
    info!("all devices unsubscribed");

    // Test edge cases
    admin_team
        .sync_hello_subscribe(owner_addr, HelloSubscriptionConfig::default())
        .await?;
    admin_team.sync_hello_unsubscribe(owner_addr).await?;
    info!("tested immediate subscribe/unsubscribe");

    // Test unsubscribing from non-subscribed peer
    let memberb_addr = devices.memberb.aranya_local_addr().await?;
    admin_team.sync_hello_unsubscribe(memberb_addr).await?;
    info!("tested unsubscribing from non-subscribed peer");

    Ok(())
}

/// Tests that schedule_delay parameter in sync_hello_subscribe works correctly.
/// Verifies that with high schedule_delay, only graph-change-triggered notifications occur,
/// while with low schedule_delay, scheduled periodic sends pick up all pending changes.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
#[cfg(feature = "preview")]
async fn test_hello_subscription_schedule_delay() -> Result<()> {
    // Set up our team context so we can run the test.
    let mut devices = DevicesCtx::new("test_hello_subscription_schedule_delay").await?;

    // Create the initial team, and get our TeamId.
    let team_id = devices.create_and_add_team().await?;

    let roles = devices.setup_default_roles(team_id).await?;
    devices.add_all_device_roles(team_id, &roles).await?;

    // Grab addresses for testing
    let admin_addr = devices.admin.aranya_local_addr().await?;

    // Grab the shorthand for the teams we need to operate on.
    let membera_team = devices.membera.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    let sync_config = SyncPeerConfig::builder()
        .sync_now(false)
        .sync_on_hello(true)
        .build()?;

    membera_team.add_sync_peer(admin_addr, sync_config).await?;
    info!("membera added admin as sync peer with sync_on_hello=true");

    // Phase 1: Test with high schedule_delay (60s) - should only see first graph change
    info!("Phase 1: Testing with high schedule_delay (60s) and high graph_change_debounce (60s)");
    membera_team
        .sync_hello_subscribe(
            admin_addr,
            HelloSubscriptionConfig::builder()
                .graph_change_debounce(Duration::from_secs(60))
                .periodic_interval(Duration::from_secs(60))
                .build()?,
        )
        .await?;
    info!("membera subscribed to hello notifications from admin with high schedule_delay");

    // Before the action, verify that MemberA doesn't know about any labels created by admin
    info!("verifying initial state - membera should not see any labels created by admin");
    let initial_labels = membera_team.labels().await?;
    let initial_label_count = initial_labels.iter().count();
    info!(
        "initial label count as seen by membera: {}",
        initial_label_count
    );

    // Admin creates first label
    info!("admin creating first test label");
    let member_role_rank = admin_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let test_label_1 = admin_team
        .create_label(
            aranya_daemon_api::text!("schedule_test_label_1"),
            label_rank,
        )
        .await?;
    info!("admin created first test label: {:?}", test_label_1);

    // Wait for first label to be seen (should be sent via graph change notification)
    info!("waiting for first label to be seen via graph change notification...");
    let poll_start = std::time::Instant::now();
    let poll_timeout = Duration::from_secs(10);
    let poll_interval = Duration::from_millis(100);

    let first_label_seen = loop {
        let current_labels = membera_team.labels().await?;
        let current_count = current_labels.iter().count();

        if current_count > initial_label_count {
            let label_exists = current_labels
                .iter()
                .any(|label| label.name.as_str() == "schedule_test_label_1");
            if label_exists {
                info!(
                    "first label seen after {:?} - label count increased from {} to {}",
                    poll_start.elapsed(),
                    initial_label_count,
                    current_count
                );
                break true;
            }
        }

        if poll_start.elapsed() >= poll_timeout {
            bail!(
                "First label not seen: timeout after {:?} - expected label count to increase from {} but it remained at {}",
                poll_timeout,
                initial_label_count,
                current_count
            );
        }

        sleep(poll_interval).await;
    };

    assert!(first_label_seen, "First label should have been seen");

    // Admin creates second label
    info!("admin creating second test label");
    let test_label_2 = admin_team
        .create_label(
            aranya_daemon_api::text!("schedule_test_label_2"),
            label_rank,
        )
        .await?;
    info!("admin created second test label: {:?}", test_label_2);

    // Wait a short time and verify second label is NOT seen (rate-limited and schedule hasn't fired)
    info!("waiting briefly to confirm second label is not seen (rate-limited)...");
    sleep(Duration::from_secs(2)).await;

    let current_labels = membera_team.labels().await?;
    let current_count = current_labels.iter().count();
    let second_label_exists = current_labels
        .iter()
        .any(|label| label.name.as_str() == "schedule_test_label_2");

    if second_label_exists {
        bail!(
            "Second label should not have been seen yet (rate-limited) - found {} labels, expected {}",
            current_count,
            initial_label_count + 1
        );
    }

    info!("confirmed second label not seen - rate limiting working");

    // Phase 2: Test with low schedule_delay (10ms) - should see all labels
    info!("Phase 2: Testing with low schedule_delay (10ms)");
    membera_team.sync_hello_unsubscribe(admin_addr).await?;
    info!("membera unsubscribed from admin");

    membera_team
        .sync_hello_subscribe(
            admin_addr,
            HelloSubscriptionConfig::builder()
                .graph_change_debounce(Duration::from_secs(60))
                .periodic_interval(Duration::from_millis(10))
                .build()?,
        )
        .await?;
    info!("membera subscribed to hello notifications from admin with low periodic_interval");

    // Wait for both labels to be seen (scheduled send should pick up pending changes)
    info!("waiting for both labels to be seen via scheduled periodic send...");
    let poll_start = std::time::Instant::now();
    let poll_timeout = Duration::from_secs(10);
    let poll_interval = Duration::from_millis(100);

    let both_labels_seen = loop {
        let current_labels = membera_team.labels().await?;
        let current_count = current_labels.iter().count();

        if current_count >= initial_label_count + 2 {
            let label1_exists = current_labels
                .iter()
                .any(|label| label.name.as_str() == "schedule_test_label_1");
            let label2_exists = current_labels
                .iter()
                .any(|label| label.name.as_str() == "schedule_test_label_2");

            if label1_exists && label2_exists {
                info!(
                    "both labels seen after {:?} - label count: {} (expected at least {})",
                    poll_start.elapsed(),
                    current_count,
                    initial_label_count + 2
                );
                break true;
            }
        }

        if poll_start.elapsed() >= poll_timeout {
            let current_labels = membera_team.labels().await?;
            let label1_exists = current_labels
                .iter()
                .any(|label| label.name.as_str() == "schedule_test_label_1");
            let label2_exists = current_labels
                .iter()
                .any(|label| label.name.as_str() == "schedule_test_label_2");

            bail!(
                "Both labels not seen: timeout after {:?} - label1: {}, label2: {}, count: {} (expected at least {})",
                poll_timeout,
                label1_exists,
                label2_exists,
                current_labels.iter().count(),
                initial_label_count + 2
            );
        }

        sleep(poll_interval).await;
    };

    assert!(both_labels_seen, "Both labels should have been seen");

    // Cleanup
    membera_team.sync_hello_unsubscribe(admin_addr).await?;
    info!("cleanup: unsubscribed membera from admin");

    Ok(())
}

/// Enforces that default roles can only be seeded once per team.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_setup_default_roles_single_use() -> Result<()> {
    let mut devices = DevicesCtx::new("test_setup_default_roles_single_use").await?;

    let team_id = devices.create_and_add_team().await?;
    devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;

    let owner_team = devices.owner.client.team(team_id);
    match owner_team.setup_default_roles().await {
        Ok(_) => bail!("expected replayed setup_default_roles to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected error re-running setup_default_roles: {err:?}"),
    }

    Ok(())
}

/// Tests that role creation works.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_create_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_create_role").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    let expected_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let test_role = owner_team
        .create_role(text!("test_role"), expected_rank)
        .await
        .expect("expected to create role");

    // Verify the rank can be queried back.
    let rank = owner_team.rank(test_role.id).await?;
    assert_eq!(rank, expected_rank);

    owner_team
        .roles()
        .await?
        .into_iter()
        .find(|r| r.name == "test_role")
        .expect("no test role found");

    // Set up another device, sync it, and make sure they can see the
    // role.
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;
    let admin_team = devices.admin.client.team(team_id);
    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    let test_role2 = admin_team
        .roles()
        .await?
        .into_iter()
        .find(|r| r.name == "test_role")
        .expect("no test role found");
    assert_eq!(test_role.id, test_role2.id);
    assert_eq!(test_role.name, test_role2.name);

    Ok(())
}

/// Tests that role creation works.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_perm_to_created_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_add_perm_to_created_role").await?;

    let team_id = devices.create_and_add_team().await?;
    let owner_team = devices.owner.client.team(team_id);
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Create a custom admin type role with rank derived from the owner's device rank.
    let owner_device_rank = owner_team.rank(devices.owner.id).await?;
    let custom_role_rank = owner_device_rank.value() / 2;
    let admin_role = owner_team
        .create_role(text!("admin"), custom_role_rank.into())
        .await?;
    owner_team
        .add_perm_to_role(admin_role.id, Permission::AddDevice)
        .await
        .expect("expected to assign AddDevice to admin");

    // Add our admin with this role (rank must be < role rank)
    owner_team
        .add_device(
            devices.admin.pk,
            Some(admin_role.id),
            custom_role_rank.saturating_sub(1).into(),
        )
        .await
        .expect("expected to add admin with role");

    // Sync the admin and test that they can add the operator
    let admin_team = devices.admin.client.team(team_id);
    admin_team.sync_now(owner_addr, None).await?;

    // Admin adds operator at an even lower rank
    admin_team
        .add_device(
            devices.operator.pk,
            None,
            custom_role_rank.saturating_sub(100).into(),
        )
        .await
        .expect("admin should be able to add operator");

    Ok(())
}

/// Tests that privilege escalation attempt is rejected.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_privilege_escalation_rejected() -> Result<()> {
    let team_name = "test_privilege_escalation_rejected";
    let mut devices = DevicesCtx::new(team_name).await?;

    // Owner creates the team.
    let team_id = devices.create_and_add_team().await?;
    let owner_team = devices.owner.client.team(team_id);
    let roles = devices.setup_default_roles(team_id).await?;
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    // All custom ranks must be below the lowest default role rank.
    let malicious_role_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let malicious_device_rank = Rank::new(malicious_role_rank.value().saturating_sub(1));
    let target_role_rank = Rank::new(malicious_device_rank.value().saturating_sub(1));

    // Initialize malicious device on team.
    let work_dir = tempfile::tempdir()?;
    let work_dir_path = work_dir.path();
    let device = DeviceCtx::new(team_name, "malicious", work_dir_path.join("malicious")).await?;
    owner_team
        .add_device(device.pk.clone(), None, malicious_device_rank)
        .await?;
    let device_seed = owner_team
        .encrypt_psk_seed_for_peer(device.pk.encryption())
        .await?;
    device
        .client
        .add_team({
            AddTeamConfig::builder()
                .team_id(team_id)
                .quic_sync(
                    AddTeamQuicSyncConfig::builder()
                        .wrapped_seed(&device_seed)?
                        .build()?,
                )
                .build()?
        })
        .await?;

    // Owner creates malicious role on team:
    let role = owner_team
        .create_role(text!("malicious_role"), malicious_role_rank)
        .await
        .expect("expected to create malicious role");

    // Owner only allows role to create new roles.
    owner_team
        .add_perm_to_role(role.id, Permission::CreateRole)
        .await?;

    // Owner assigns role to malicious device.
    owner_team.device(device.id).assign_role(role.id).await?;

    // Malicious device syncs with owner.
    let device_team = device.client.team(team_id);
    let owner_addr = devices.owner.aranya_local_addr().await?;
    device_team.sync_now(owner_addr, None).await?;

    // Malicious device creates a new target role (which it maintains control of).
    let target_role = device_team
        .create_role(text!("target_role"), target_role_rank)
        .await
        .expect("unable to create target role");

    // Malicious device attempts to grant target role a permission it does not have: e.g. CanUseAfc
    // This should be rejected, which indicates a privilege escalation attempt will be rejected.
    device_team
        .add_perm_to_role(target_role.id, Permission::CanUseAfc)
        .await
        .expect_err("expected privilege escalation attempt to fail");

    Ok(())
}

/// Tests that role creation works.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_remove_perm_from_default_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_add_perm_to_created_role").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Add admin with admin role
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk,
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await
        .expect("expected to add admin with role");

    owner_team
        .remove_perm_from_role(roles.admin().id, Permission::AddDevice)
        .await
        .expect("expected to remove AddDevice from admin");

    // Sync the admin
    let admin_team = devices.admin.client.team(team_id);
    admin_team.sync_now(owner_addr, None).await?;

    // Admin cannot add operator
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    admin_team
        .add_device(
            devices.operator.pk,
            None,
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await
        .expect_err("admin should not be able to add operator");

    Ok(())
}

/// Tests that role deletion works.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_delete_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_delete_role").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    owner_team
        .delete_role(roles.member().id)
        .await
        .expect("expected to delete role");

    Ok(())
}

/// A device cannot assign a role to itself. The rank system enforces this:
/// `author_can_operate_on_target` uses strict `>`, so a device never
/// outranks itself and the operation is rejected.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_assign_role_self_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_assign_role_self_rejected").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    // Owner tries to assign a role to itself. Fails because the policy
    // requires the author to strictly outrank the target device.
    let err = owner_team
        .device(devices.owner.id)
        .assign_role(roles.owner().id)
        .await
        .expect_err("assigning role to self should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// The sole owner cannot revoke its own owner role. The rank system
/// prevents self-operations (strict `>` means a device never outranks
/// itself), and the policy also prevents removing the last owner.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_owner_cannot_revoke_owner_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_owner_cannot_revoke_owner_role").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let err = owner_team
        .device(devices.owner.id)
        .revoke_role(roles.owner().id)
        .await
        .expect_err("sole owner cannot revoke its own role");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// A device that already has a role cannot be assigned another role.
/// The policy rejects the operation because an existing role assignment
/// already exists for the target device.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_cannot_assign_role_twice() -> Result<()> {
    let mut devices = DevicesCtx::new("test_cannot_assign_role_twice").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);

    match owner_team
        .device(devices.membera.id)
        .assign_role(roles.operator().id)
        .await
    {
        Ok(_) => bail!("Expected role assignment to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(_) => bail!("Unexpected error"),
    }

    Ok(())
}

/// Deleting a label requires `DeleteLabel` permission and sufficient rank.
/// An operator without `DeleteLabel` cannot delete a label even if it
/// outranks the label.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_delete_label_requires_permission() -> Result<()> {
    let mut devices = DevicesCtx::new("test_delete_label_requires_permission").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    let member_role_rank = owner_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team
        .create_label(text!("delete-label-guard"), label_rank)
        .await?;

    operator_team
        .sync_now(devices.owner.aranya_local_addr().await?, None)
        .await
        .context("operator unable to sync owner state")?;

    let err = operator_team
        .delete_label(label)
        .await
        .expect_err("delete_label without permission should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// A device cannot assign a label to itself. The rank system enforces this:
/// `author_can_operate_on_target` uses strict `>`, so a device never
/// outranks itself and the operation is rejected.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_assign_label_to_device_self_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_assign_label_to_device_self_rejected").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_id = devices.owner.id;
    let owner_team = devices.owner.client.team(team_id);

    let member_role_rank = owner_team.rank(roles.member().id).await?;
    // Label rank must be lower than the member role rank so all team members can operate on it.
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team
        .create_label(text!("device-self-label"), label_rank)
        .await?;

    // Owner tries to assign a label to itself. This fails because the policy
    // requires the author to strictly outrank the target device, and a device
    // can never outrank itself (rank comparison uses `>`).
    let err = owner_team
        .device(owner_id)
        .assign_label(label, ChanOp::SendRecv)
        .await
        .expect_err("assigning label to self should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// Ensures the last owner cannot be removed by another device.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_admin_cannot_remove_last_owner() -> Result<()> {
    let mut devices = DevicesCtx::new("test_admin_cannot_remove_last_owner").await?;

    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let admin_team = devices.admin.client.team(team_id);
    let err = admin_team
        .device(devices.owner.id)
        .remove_from_team()
        .await
        .expect_err("removing the final owner should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

// ========================================================================
// Rank-based tests
// ========================================================================

/// Tests that a label can be created with a specific rank and that the rank
/// can be queried back.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_create_label() -> Result<()> {
    let mut devices = DevicesCtx::new("test_create_label").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let expected_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label_id = owner_team
        .create_label(text!("ranked_label"), expected_rank)
        .await?;

    let rank = owner_team.rank(label_id).await?;
    assert_eq!(rank, expected_rank);

    Ok(())
}

/// Tests that the rank of a label can be changed with a valid old_rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let initial_rank = Rank::new(member_role_rank.value().saturating_sub(2));
    let updated_rank = Rank::new(initial_rank.value().saturating_add(1));
    let label = owner_team
        .create_label(text!("mutable_label"), initial_rank)
        .await?;

    owner_team
        .change_rank(label, initial_rank, updated_rank)
        .await?;

    let new_rank = owner_team.rank(label).await?;
    assert_eq!(new_rank, updated_rank);

    Ok(())
}

/// Tests that a lower-ranked device cannot change the rank of a higher-ranked
/// object (author_rank must be > target_rank).
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_requires_sufficient_author_rank() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_requires_sufficient_author_rank").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    // Create a label with rank higher than the operator device rank
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    let member_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    let high_label_rank = Rank::new(operator_role_rank.value().saturating_add(50));
    let high_label = owner_team
        .create_label(text!("high_label"), high_label_rank)
        .await?;

    // Add operator device and sync
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;

    // Give operator ChangeRank permission
    owner_team
        .add_perm_to_role(roles.operator().id, Permission::ChangeRank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    operator_team.sync_now(owner_addr, None).await?;

    // Operator tries to change rank of object ranked above it -- should fail
    match operator_team
        .change_rank(high_label, high_label_rank, member_role_rank)
        .await
    {
        Ok(_) => bail!("expected change_rank to fail when author rank < object rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Tests that an admin cannot create a role with a rank higher than the
/// admin's own rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_create_role_rank_too_high_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_create_role_rank_too_high_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Add admin with rank below admin role (admin default role already has CreateRole)
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin tries to create role with rank above admin role rank -- should fail
    match admin_team
        .create_role(
            text!("too_high"),
            Rank::new(admin_role_rank.value().saturating_add(100)),
        )
        .await
    {
        Ok(_) => bail!("expected create_role to fail when rank > author rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected create_role error: {err:?}"),
    }

    Ok(())
}

/// Tests that adding a device with a rank higher than its assigned role's rank
/// is rejected (role_rank >= device_rank must hold).
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_device_rank_higher_than_role_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_add_device_rank_higher_than_role_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);

    // Try to add device with rank above member role rank
    // Should fail: role_rank (member) >= device_rank (operator role rank) is false
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    match owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.member().id),
            operator_role_rank,
        )
        .await
    {
        Ok(_) => bail!("expected add_device to fail when device rank > role rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected add_device error: {err:?}"),
    }

    Ok(())
}

/// Tests that changing a device rank above its role's rank is rejected.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_above_role_rank_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_above_role_rank_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);

    // Add admin with member role and device rank below the role rank
    let member_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await?;

    // Try to change device rank above its role rank -- should fail
    match owner_team
        .change_rank(devices.admin.id, device_rank, operator_role_rank)
        .await
    {
        Ok(_) => bail!("expected change_rank to fail when new rank > role rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Tests that role ranks cannot be changed after creation.
///
/// Role ranks are fixed at creation time to maintain the invariant that
/// `role_rank > device_rank` for all devices assigned to the role.
///
/// This applies unconditionally to all roles - a device cannot promote or
/// demote any role's rank, including the rank of its own assigned role.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_role_rank_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_role_rank_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    // Create a role
    let role_rank = Rank::new(member_role_rank.value().saturating_sub(2));
    let role = owner_team
        .create_role(text!("immutable_role"), role_rank)
        .await?;

    // Try to change the role's rank -- should fail
    let attempted_rank = Rank::new(role_rank.value().saturating_add(1));
    match owner_team
        .change_rank(role.id, role_rank, attempted_rank)
        .await
    {
        Ok(_) => bail!("expected change_rank to fail for roles"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    // Verify the role rank was not changed
    let current_role_rank = owner_team.rank(role.id).await?;
    assert_eq!(
        current_role_rank, role_rank,
        "role rank should not have changed"
    );

    Ok(())
}

/// Tests the migration pattern for changing a role's effective rank.
///
/// Since role ranks are immutable after creation, the recommended workflow is:
/// 1. Create a new role with the desired rank
/// 2. Query and copy permissions from the old role to the new role
/// 3. Change devices from the old role to the new role
/// 4. Delete the old role (optional cleanup)
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_role_rank_migration_pattern() -> Result<()> {
    let mut devices = DevicesCtx::new("test_role_rank_migration_pattern").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    // Step 1: Create original role below member role rank with some permissions
    let old_role_rank = member_role_rank.value().saturating_sub(2);
    let old_role = owner_team
        .create_role(text!("old_role"), old_role_rank.into())
        .await?;

    // Add permissions to the old role
    owner_team
        .add_perm_to_role(old_role.id, Permission::CreateLabel)
        .await?;
    owner_team
        .add_perm_to_role(old_role.id, Permission::DeleteLabel)
        .await?;

    // Add device with old role (device rank must be <= role rank)
    let device_rank = old_role_rank.saturating_sub(1);
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(old_role.id),
            device_rank.into(),
        )
        .await?;

    // Verify device has old role
    let assigned = owner_team.device(devices.admin.id).role().await?;
    assert_eq!(assigned.map(|r| r.id), Some(old_role.id));

    // Step 2: Create new role with higher rank
    let new_role_rank = old_role_rank.saturating_add(1);
    let new_role = owner_team
        .create_role(text!("new_role"), new_role_rank.into())
        .await?;

    // Step 3: Query permissions from old role and copy to new role
    let old_perms = owner_team.role_perm(old_role.id).await?;
    assert_eq!(old_perms.len(), 2, "old role should have 2 permissions");
    for &perm in &old_perms {
        owner_team.add_perm_to_role(new_role.id, perm).await?;
    }

    // Verify new role has the same permissions (sort since fact iteration order
    // is not guaranteed across different roles)
    let mut new_perms = owner_team.role_perm(new_role.id).await?;
    let mut old_sorted = old_perms.clone();
    old_sorted.sort_by_key(|p| format!("{p:?}"));
    new_perms.sort_by_key(|p| format!("{p:?}"));
    assert_eq!(
        old_sorted, new_perms,
        "new role should have the same permissions as old role"
    );

    // Step 4: Migrate device from old role to new role
    owner_team
        .device(devices.admin.id)
        .change_role(old_role.id, new_role.id)
        .await
        .context("should be able to change to higher-ranked role")?;

    // Verify device now has new role
    let assigned = owner_team.device(devices.admin.id).role().await?;
    assert_eq!(assigned.map(|r| r.id), Some(new_role.id));

    // Step 5: Delete the old role (cleanup)
    owner_team
        .delete_role(old_role.id)
        .await
        .context("should be able to delete unused role")?;

    // Verify old role no longer exists
    let all_roles = owner_team.roles().await?;
    assert!(
        !all_roles.iter().any(|r| r.id == old_role.id),
        "old role should be deleted"
    );

    Ok(())
}

/// Tests that a lower-ranked device cannot operate on higher-ranked objects:
/// removing devices, deleting roles, or deleting labels.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_insufficient_rank_cannot_operate_on_objects() -> Result<()> {
    let mut devices = DevicesCtx::new("test_insufficient_rank_cannot_operate_on_objects").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    // Add admin and operator devices
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;

    // Create a label with rank above the operator's rank so the operator can't delete it.
    let high_label_rank = Rank::new(operator_role_rank.value().saturating_add(100));
    let high_label = owner_team
        .create_label(text!("high_label"), high_label_rank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    operator_team.sync_now(owner_addr, None).await?;

    // Operator tries to remove admin (higher ranked device) -- should fail
    match operator_team
        .device(devices.admin.id)
        .remove_from_team()
        .await
    {
        Ok(_) => bail!("expected removing higher-ranked device to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected remove_device error: {err:?}"),
    }

    // Operator tries to delete admin role (higher ranked) -- should fail
    match operator_team.delete_role(roles.admin().id).await {
        Ok(_) => bail!("expected deleting higher-ranked role to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected delete_role error: {err:?}"),
    }

    // Operator tries to delete high-rank label -- should fail
    match operator_team.delete_label(high_label).await {
        Ok(_) => bail!("expected deleting higher-ranked label to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected delete_label error: {err:?}"),
    }

    Ok(())
}

/// Tests that change_rank fails when the new_rank exceeds the author's own rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_new_rank_above_author_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_new_rank_above_author_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let low_label_rank = Rank::new(member_role_rank.value().saturating_sub(1));

    // Owner creates a label at low rank
    let label = owner_team
        .create_label(text!("low_label"), low_label_rank)
        .await?;

    // Add operator with ChangeRank perm
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;
    owner_team
        .add_perm_to_role(roles.operator().id, Permission::ChangeRank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    operator_team.sync_now(owner_addr, None).await?;

    // Operator tries to change label rank to above operator's rank -- should fail
    match operator_team
        .change_rank(label, low_label_rank, admin_role_rank)
        .await
    {
        Ok(_) => bail!("expected change_rank to fail when new_rank > author_rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Tests that change_rank fails when the provided old_rank does not match the
/// object's current rank (stale old_rank).
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_stale_old_rank_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_stale_old_rank_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    let initial_rank = Rank::new(member_role_rank.value().saturating_sub(3));
    let updated_rank = Rank::new(initial_rank.value().saturating_add(1));
    let stale_attempt_rank = Rank::new(updated_rank.value().saturating_add(1));
    let label = owner_team
        .create_label(text!("versioned_label"), initial_rank)
        .await?;
    // Change rank from initial to updated
    owner_team
        .change_rank(label, initial_rank, updated_rank)
        .await?;

    // Try to change rank using stale old_rank (initial instead of current updated)
    match owner_team
        .change_rank(label, initial_rank, stale_attempt_rank)
        .await
    {
        Ok(_) => bail!("expected change_rank to fail with stale old_rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Tests that a device can demote its own rank (self-demotion is allowed with
/// just the ChangeRank permission).
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_self_demotion() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_self_demotion").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Add admin -- admin default role already has ChangeRank
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    let admin_rank = Rank::new(admin_role_rank.value().saturating_sub(1));
    let member_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    // Demoted rank must be lower than admin's current rank.
    let demoted_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(devices.admin.pk.clone(), Some(roles.admin().id), admin_rank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin demotes itself
    admin_team
        .change_rank(devices.admin.id, admin_rank, demoted_rank)
        .await
        .context("device should be able to demote its own rank")?;

    // Verify the rank actually changed
    // Need to sync owner to see the change
    owner_team
        .sync_now(devices.admin.aranya_local_addr().await?, None)
        .await?;
    let new_rank = owner_team.rank(devices.admin.id).await?;
    assert_eq!(new_rank, demoted_rank);

    Ok(())
}

/// Tests that a device cannot promote its own rank (self-promotion is rejected).
///
/// This is a critical security control: a device should never be able to
/// escalate its own privileges by increasing its rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_self_promotion_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_self_promotion_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Add admin with ChangeRank permission (admin role has it by default)
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    let admin_rank = Rank::new(admin_role_rank.value().saturating_sub(1));
    let promoted_rank = Rank::new(admin_rank.value().saturating_add(50));
    owner_team
        .add_device(devices.admin.pk.clone(), Some(roles.admin().id), admin_rank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin tries to promote itself -- should fail
    match admin_team
        .change_rank(devices.admin.id, admin_rank, promoted_rank)
        .await
    {
        Ok(_) => bail!("expected self-promotion to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    // Verify the rank was not changed
    let current_rank = admin_team.rank(devices.admin.id).await?;
    assert_eq!(current_rank, admin_rank, "rank should not have changed");

    Ok(())
}

/// Tests that a device at the same rank as another cannot operate on it
/// (strict > is required, not >=).
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_equal_rank_cannot_operate() -> Result<()> {
    let mut devices = DevicesCtx::new("test_equal_rank_cannot_operate").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Add admin and operator both at operator device rank (testing equal ranks)
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    let equal_rank = Rank::new(operator_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(devices.admin.pk.clone(), Some(roles.admin().id), equal_rank)
        .await?;
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            equal_rank,
        )
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin tries to remove operator (same rank) -- should fail (strict >)
    match admin_team
        .device(devices.operator.id)
        .remove_from_team()
        .await
    {
        Ok(_) => bail!("expected removing equal-ranked device to fail"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected remove_device error: {err:?}"),
    }

    Ok(())
}

/// Tests that assigning a role requires the author to outrank both the role
/// and the target device.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_assign_role_requires_outranking_both_role_and_device() -> Result<()> {
    let mut devices = DevicesCtx::new("test_assign_role_requires_outranking_both").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);
    let owner_addr = devices.owner.aranya_local_addr().await?;

    // Give admin the AssignRole permission
    owner_team
        .add_perm_to_role(roles.admin().id, Permission::AssignRole)
        .await?;

    // Create custom roles and devices with ordered ranks below member role rank.
    // Ordering: low_device < low_role < admin < high_device < high_role < member_role
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let high_role_rank = member_role_rank.value().saturating_sub(1);
    let high_device_rank = high_role_rank.saturating_sub(1);
    let admin_rank = high_device_rank.saturating_sub(1);
    let low_role_rank = admin_rank.saturating_sub(1);
    let low_device_rank = low_role_rank.saturating_sub(1);

    let low_role = owner_team
        .create_role(text!("low_role"), low_role_rank.into())
        .await?;
    let high_role = owner_team
        .create_role(text!("high_role"), high_role_rank.into())
        .await?;

    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            admin_rank.into(),
        )
        .await?;
    owner_team
        .add_device(devices.membera.pk.clone(), None, low_device_rank.into())
        .await?;
    owner_team
        .add_device(devices.memberb.pk.clone(), None, high_device_rank.into())
        .await?;

    admin_team.sync_now(owner_addr, None).await?;

    // Case 1: Author outranks device but NOT role -- should fail
    // Admin (300) tries to assign high_role (500) to membera (100)
    let result = admin_team
        .device(devices.membera.id)
        .assign_role(high_role.id)
        .await;
    assert!(
        matches!(result, Err(crate::Error::Aranya(_))),
        "Case 1: expected assign_role to fail when author doesn't outrank the role, got {result:?}"
    );

    // Case 2: Author outranks role but NOT device -- should fail
    // Admin (300) tries to assign low_role (200) to memberb (400)
    let result = admin_team
        .device(devices.memberb.id)
        .assign_role(low_role.id)
        .await;
    assert!(
        matches!(result, Err(crate::Error::Aranya(_))),
        "Case 2: expected assign_role to fail when author doesn't outrank the device, got {result:?}"
    );

    // Case 3: Author outranks BOTH role and device -- should succeed
    // Admin (300) tries to assign low_role (200) to membera (100)
    admin_team
        .device(devices.membera.id)
        .assign_role(low_role.id)
        .await
        .context("Case 3: assign_role should succeed when author outranks both role and device")?;

    Ok(())
}

/// Tests that creating a label with a rank higher than the author's rank is
/// rejected.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_create_label_rank_too_high_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_create_label_rank_too_high_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Add admin with rank below admin role
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin tries to create label with rank above admin role -- should fail
    match admin_team
        .create_label(
            text!("too_high_label"),
            Rank::new(admin_role_rank.value().saturating_add(100)),
        )
        .await
    {
        Ok(_) => bail!("expected create_label to fail when rank > author rank"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected create_label error: {err:?}"),
    }

    Ok(())
}

/// Tests that adding a permission to a role requires the author to outrank
/// that role.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_perm_change_requires_outranking_role() -> Result<()> {
    let mut devices = DevicesCtx::new("test_perm_change_requires_outranking_role").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    // Add operator with ChangeRolePerms permission
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;
    owner_team
        .add_perm_to_role(roles.operator().id, Permission::ChangeRolePerms)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    operator_team.sync_now(owner_addr, None).await?;

    // Operator tries to add permission to admin role (higher ranked) -- should fail
    match operator_team
        .add_perm_to_role(roles.admin().id, Permission::CreateRole)
        .await
    {
        Ok(_) => bail!("expected add_perm_to_role to fail when author doesn't outrank role"),
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected add_perm_to_role error: {err:?}"),
    }

    Ok(())
}

/// Tests that assigning a role where role_rank equals device_rank is allowed.
///
/// The policy uses `role_rank >= device_rank` (not strict `>`). Equal ranks
/// are safe because a device still cannot modify its own role - modification
/// requires strictly outranking the target via `author_can_operate_on_target`.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_assign_role_where_role_rank_equals_device_rank_allowed() -> Result<()> {
    let mut devices =
        DevicesCtx::new("test_assign_role_where_role_rank_equals_device_rank_allowed").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;

    // Create a custom role below the member role rank
    let role_rank = member_role_rank.value().saturating_sub(1);
    let custom_role = owner_team
        .create_role(text!("equal_rank_role"), role_rank.into())
        .await?;

    // Add device at exactly the same rank as the role
    owner_team
        .add_device(devices.admin.pk.clone(), None, role_rank.into())
        .await?;

    // Assign role where role_rank == device_rank -- should succeed
    owner_team
        .device(devices.admin.id)
        .assign_role(custom_role.id)
        .await
        .context("assigning role with equal rank should succeed")?;

    // Verify the role was assigned
    let assigned_role = owner_team.device(devices.admin.id).role().await?;
    assert_eq!(
        assigned_role.map(|r| r.id),
        Some(custom_role.id),
        "role should be assigned"
    );

    Ok(())
}

/// Tests that changing a device's rank to exactly equal its role's rank is allowed.
///
/// The policy uses `role_rank >= device_rank` (not strict `>`). Equal ranks
/// are safe because the device still cannot modify its own role.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_change_rank_device_to_exact_role_rank_allowed() -> Result<()> {
    let mut devices = DevicesCtx::new("test_change_rank_device_to_exact_role_rank_allowed").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);

    // Add device with member role at rank below the role
    let member_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.member().id)
        .await?;
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(100));
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await?;

    // Change device rank to exactly equal the role rank -- should succeed
    owner_team
        .change_rank(devices.admin.id, device_rank, member_role_rank)
        .await
        .context("changing device rank to equal role rank should succeed")?;

    // Verify the rank was changed
    let new_rank = owner_team.rank(devices.admin.id).await?;
    assert_eq!(new_rank, member_role_rank);

    Ok(())
}

/// Tests that having a permission is not sufficient without also having
/// sufficient rank to operate on the target.
///
/// A device with ChangeRank permission but lower rank than the target
/// cannot change the target's rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_has_permission_but_insufficient_rank() -> Result<()> {
    let mut devices = DevicesCtx::new("test_has_permission_but_insufficient_rank").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let operator_team = devices.operator.client.team(team_id);

    // Create a label ranked higher than operator
    let operator_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.operator().id)
        .await?;
    let high_label_rank = Rank::new(operator_role_rank.value().saturating_add(100));
    let high_label = owner_team
        .create_label(text!("high_label"), high_label_rank)
        .await?;

    // Add operator with ChangeRank permission
    owner_team
        .add_device(
            devices.operator.pk.clone(),
            Some(roles.operator().id),
            Rank::new(operator_role_rank.value().saturating_sub(1)),
        )
        .await?;
    owner_team
        .add_perm_to_role(roles.operator().id, Permission::ChangeRank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    operator_team.sync_now(owner_addr, None).await?;

    // Operator has ChangeRank permission but cannot change higher-ranked label
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let low_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    match operator_team
        .change_rank(high_label, high_label_rank, low_rank)
        .await
    {
        Ok(_) => {
            bail!("expected change_rank to fail despite having permission (insufficient rank)")
        }
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Tests that outranking a target is not sufficient without also having
/// the required permission.
///
/// A device that outranks a target but lacks ChangeRank permission
/// cannot change the target's rank.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_outranks_but_missing_permission() -> Result<()> {
    let mut devices = DevicesCtx::new("test_outranks_but_missing_permission").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices.setup_default_roles(team_id).await?;

    let owner_team = devices.owner.client.team(team_id);
    let admin_team = devices.admin.client.team(team_id);

    // Create a label ranked lower than admin
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let low_label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let low_label = owner_team
        .create_label(text!("low_label"), low_label_rank)
        .await?;

    // Add admin but explicitly remove ChangeRank permission
    let admin_role_rank = devices
        .owner
        .client
        .team(team_id)
        .rank(roles.admin().id)
        .await?;
    owner_team
        .add_device(
            devices.admin.pk.clone(),
            Some(roles.admin().id),
            Rank::new(admin_role_rank.value().saturating_sub(1)),
        )
        .await?;
    owner_team
        .remove_perm_from_role(roles.admin().id, Permission::ChangeRank)
        .await?;

    let owner_addr = devices.owner.aranya_local_addr().await?;
    admin_team.sync_now(owner_addr, None).await?;

    // Admin outranks the label but lacks ChangeRank permission
    let attempted_rank = Rank::new(low_label_rank.value().saturating_add(1));
    match admin_team
        .change_rank(low_label, low_label_rank, attempted_rank)
        .await
    {
        Ok(_) => {
            bail!("expected change_rank to fail despite outranking target (missing permission)")
        }
        Err(crate::Error::Aranya(_)) => {}
        Err(err) => bail!("unexpected change_rank error: {err:?}"),
    }

    Ok(())
}

/// Assigning the same label to a device twice should fail because the
/// label assignment already exists with the same generation.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_duplicate_label_assignment_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_duplicate_label_assignment_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team.create_label(text!("label"), label_rank).await?;

    // First assignment should succeed.
    owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await
        .expect("first label assignment should succeed");

    // Second assignment of the same label should fail.
    let err = owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await
        .expect_err("duplicate label assignment should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// When a device is removed and re-added, old label assignments become
/// stale (generation mismatch). Reassigning the label should succeed.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_device_generation_counter_label_reassignment() -> Result<()> {
    let mut devices = DevicesCtx::new("test_device_generation_counter_label_reassignment").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team.create_label(text!("label"), label_rank).await?;

    // Generation counter should start at 0.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(0), "initial generation should be 0");

    // Assign label to membera.
    owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await?;

    // Verify label is visible.
    let labels = owner_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(labels.iter().count(), 1, "label should be assigned");

    // Remove membera from team.
    owner_team
        .device(devices.membera.id)
        .remove_from_team()
        .await?;

    // Generation counter increments on removal.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(1), "generation should be 1 after removal");

    // Re-add membera with the member role.
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(
            devices.membera.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await?;

    // Generation counter should not change on re-add.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(1), "generation should still be 1 after re-add");

    // Old label assignment should be stale (not visible).
    let labels = owner_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(
        labels.iter().count(),
        0,
        "stale label should not be visible"
    );

    // Reassigning the same label should succeed (stale gen < current gen).
    owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await?;

    // Generation counter should still be 1 (reassignment doesn't change it).
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(
        gen,
        Some(1),
        "generation should still be 1 after reassignment"
    );

    // Label should now be visible.
    let labels = owner_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(
        labels.iter().count(),
        1,
        "reassigned label should be visible"
    );

    Ok(())
}

/// Adding the same device to a team twice should fail because the
/// Device fact already exists.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_add_device_to_team_twice_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_add_device_to_team_twice_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(1));

    // Try to add membera again (already on team).
    let err = owner_team
        .add_device(
            devices.membera.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await
        .expect_err("adding same device twice should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// Revoking a label from a device that was removed from the team should
/// fail. Additionally, if a label was assigned before the device was
/// removed and the device is later re-added, attempting to revoke that
/// old assignment should also fail because the generation counter no
/// longer matches.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_revoke_stale_label_assignment_rejected() -> Result<()> {
    let mut devices = DevicesCtx::new("test_revoke_stale_label_assignment_rejected").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team.create_label(text!("label"), label_rank).await?;

    // Generation should start at 0.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(0), "initial generation should be 0");

    // Assign label to membera.
    owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await
        .expect("label assignment should succeed");

    // Remove membera from team.
    owner_team
        .device(devices.membera.id)
        .remove_from_team()
        .await
        .expect("remove_from_team should succeed");

    // Generation counter increments on removal.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(1), "generation should be 1 after removal");

    // Revoking a label from a removed device should fail.
    let err = owner_team
        .device(devices.membera.id)
        .revoke_label(label)
        .await
        .expect_err("revoking label from removed device should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    // Re-add membera with the member role.
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(
            devices.membera.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await
        .expect("re-adding device should succeed");

    // Generation counter should not change on re-add.
    let gen = owner_team
        .device(devices.membera.id)
        .generation()
        .await
        .expect("generation should succeed");
    assert_eq!(gen, Some(1), "generation should still be 1 after re-add");

    // Try to revoke the stale label assignment (generation mismatch).
    let err = owner_team
        .device(devices.membera.id)
        .revoke_label(label)
        .await
        .expect_err("revoking stale label assignment should fail");
    assert!(matches!(err, crate::Error::Aranya(_)), "{err:?}");

    Ok(())
}

/// When one device assigns a label and another concurrently removes the
/// target device (without syncing), the label assignment should be
/// invalidated after syncing because its embedded generation counter
/// won't match the device's current generation after reordering.
///
/// RemoveDevice has priority 400 and AssignLabelToDevice has priority
/// 100, so the braid deterministically orders the remove before the
/// assign when they are concurrent. This means:
///   1. RemoveDevice runs first, bumping device_gen from 0 to 1.
///   2. AssignLabelToDevice runs second with embedded device_gen=0,
///      but the device's current gen is now 1 — the check fails.
///
/// Timeline:
///   owner: assign label to membera (captures device_gen=0)
///   admin: remove membera from team (bumps device_gen to 1)
///   (no sync between owner and admin during these operations)
///   sync all -> braid reorders remove before assign (priority 400 > 100)
///   -> assign fails because device_gen=0 != current_gen=1
///   owner: re-add membera (device_gen stays 1)
///   -> label should not be assigned
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn test_concurrent_label_assign_and_device_removal() -> Result<()> {
    let mut devices = DevicesCtx::new("test_concurrent_label_assign_and_device_removal").await?;
    let team_id = devices.create_and_add_team().await?;
    let roles = devices
        .setup_default_roles(team_id)
        .await
        .context("unable to setup default roles")?;
    devices.add_all_device_roles(team_id, &roles).await?;

    let owner_team = devices.owner.client.team(team_id);

    // Create a label that can be assigned to members.
    let member_role_rank = owner_team.rank(roles.member().id).await?;
    let label_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    let label = owner_team.create_label(text!("label"), label_rank).await?;

    // Sync so admin sees all devices and the label.
    let owner_addr = devices.owner.aranya_local_addr().await?;
    let admin_team = devices.admin.client.team(team_id);
    admin_team.sync_now(owner_addr, None).await?;

    // Verify initial generation is 0 on both devices.
    let gen = owner_team.device(devices.membera.id).generation().await?;
    assert_eq!(gen, Some(0), "initial generation should be 0 on owner");
    let gen = admin_team.device(devices.membera.id).generation().await?;
    assert_eq!(gen, Some(0), "initial generation should be 0 on admin");

    // --- Concurrent operations without syncing ---
    // Owner assigns the label to membera (captures device_gen=0).
    owner_team
        .device(devices.membera.id)
        .assign_label(label, ChanOp::SendRecv)
        .await
        .expect("label assignment should succeed locally");

    // On the owner's device the label assignment is valid and gen is still 0.
    let labels = owner_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(
        labels.iter().count(),
        1,
        "label should be assigned on owner before sync"
    );
    let gen = owner_team.device(devices.membera.id).generation().await?;
    assert_eq!(
        gen,
        Some(0),
        "generation should still be 0 on owner before sync"
    );

    // Admin removes membera from the team (bumps device_gen to 1).
    // Admin has not synced with owner, so it doesn't know about the
    // label assignment.
    admin_team
        .device(devices.membera.id)
        .remove_from_team()
        .await
        .expect("remove should succeed locally");

    // On admin, the generation was bumped to 1 by the removal.
    let gen = admin_team.device(devices.membera.id).generation().await?;
    assert_eq!(
        gen,
        Some(1),
        "generation should be 1 on admin after removal"
    );

    // Owner still sees gen=0 because it hasn't synced the removal yet.
    let gen = owner_team.device(devices.membera.id).generation().await?;
    assert_eq!(
        gen,
        Some(0),
        "generation should still be 0 on owner before sync"
    );

    // --- Sync to trigger braid reordering ---
    // RemoveDevice (priority 400) is ordered before AssignLabelToDevice
    // (priority 100) by the braid. After syncing:
    //   1. Both devices evaluate RemoveDevice first -> gen bumps to 1.
    //   2. Both devices evaluate AssignLabelToDevice second -> check
    //      fails because embedded device_gen=0 != current gen=1.
    admin_team.sync_now(owner_addr, None).await?;
    // Sync back to owner so it sees the removal.
    owner_team
        .sync_now(devices.admin.aranya_local_addr().await?, None)
        .await?;

    // After sync, both devices should agree: gen is 1 because the
    // remove was processed. The label assignment was rejected.
    let gen = owner_team.device(devices.membera.id).generation().await?;
    assert_eq!(gen, Some(1), "generation should be 1 on owner after sync");

    // Re-add membera so we can query label state for this device.
    let device_rank = Rank::new(member_role_rank.value().saturating_sub(1));
    owner_team
        .add_device(
            devices.membera.pk.clone(),
            Some(roles.member().id),
            device_rank,
        )
        .await
        .context("re-adding device should succeed")?;

    // Generation stays at 1 after re-add (only removal increments it).
    let gen = owner_team.device(devices.membera.id).generation().await?;
    assert_eq!(gen, Some(1), "generation should still be 1 after re-add");

    // The label that was previously assigned (and valid before sync)
    // should NOT be assigned now. The concurrent removal changed the
    // generation to 1, so the assignment authored with device_gen=0
    // was rejected during braid evaluation.
    let labels = owner_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(
        labels.iter().count(),
        0,
        "label should not be assigned after concurrent removal invalidated the assignment"
    );

    // Verify on the admin's device as well.
    admin_team.sync_now(owner_addr, None).await?;
    let labels = admin_team
        .device(devices.membera.id)
        .label_assignments()
        .await?;
    assert_eq!(
        labels.iter().count(),
        0,
        "label should not be assigned on admin after sync either"
    );

    Ok(())
}