ave-http 0.11.0

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

pub mod common;
use common::TestDbExt;

use ave_http::auth::database::DatabaseError;
use prometheus_client::{encoding::text::encode, registry::Registry};
use test_log::test;

use std::{sync::Arc, time::Duration};

use ave_http::auth::{
    AuthDatabase,
    admin_handlers::{
        RemovePermissionQuery, assign_role, remove_role,
        remove_role_permission, remove_user_permission, set_role_permission,
        set_user_permission, update_user,
    },
    middleware::AuthContextExtractor,
    models::{
        AuthContext, Permission, SetPermissionRequest, SystemConfigValue,
        UpdateUserRequest,
    },
};
use axum::{
    Extension, Json,
    extract::{Path, Query},
    http::StatusCode,
};
use std::collections::BTreeSet;

fn metric_value(metrics: &str, name: &str) -> f64 {
    metrics
        .lines()
        .find_map(|line| {
            if line.starts_with(name) {
                line.split_whitespace().nth(1)?.parse::<f64>().ok()
            } else {
                None
            }
        })
        .unwrap_or(0.0)
}

#[test]
fn security_tests_route_inputs_exist_in_http_catalog() {
    let mut catalog = common::server_main_route_catalog();
    catalog.extend(common::server_auth_route_catalog());
    catalog.extend(common::server_public_auth_route_catalog());

    let expected: BTreeSet<(String, String)> = [
        ("get".to_string(), "/metrics".to_string()),
        ("get".to_string(), "/peer-id".to_string()),
        ("post".to_string(), "/login".to_string()),
    ]
    .into_iter()
    .collect();

    let missing: Vec<_> = expected.difference(&catalog).cloned().collect();
    assert!(
        missing.is_empty(),
        "Security tests reference routes that do not exist in server.rs: {missing:?}"
    );
}

// =============================================================================
// PASSWORD POLICY VALIDATION TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_password_too_short() {
    let (db, _dirs) = common::create_test_db();

    let result = db.create_user("testuser", "Short1!", None, None, Some(false));

    assert!(matches!(result, Err(DatabaseError::Validation(_))));
}

#[test(tokio::test)]
async fn test_password_too_long() {
    let (db, _dirs) = common::create_test_db();

    let long_pass = "Aa1!".repeat(33); // 132 chars (exceeds 128 limit)
    let result =
        db.create_user("testuser", &long_pass, None, None, Some(false));

    assert!(matches!(result, Err(DatabaseError::Validation(_))));
}

#[test(tokio::test)]
async fn test_password_missing_uppercase() {
    let (db, _dirs) = common::create_test_db();

    let result = db.create_user("testuser", "lowercase123!", None, None, None);

    assert!(matches!(result, Err(DatabaseError::Validation(_))));
}

#[test(tokio::test)]
async fn test_password_missing_lowercase() {
    let (db, _dirs) = common::create_test_db();

    let result = db.create_user("testuser", "UPPERCASE123!", None, None, None);

    assert!(matches!(result, Err(DatabaseError::Validation(_))));
}

#[test(tokio::test)]
async fn test_password_missing_digit() {
    let (db, _dirs) = common::create_test_db();

    let result = db.create_user("testuser", "NoDigitsHere!", None, None, None);

    assert!(matches!(result, Err(DatabaseError::Validation(_))));
}

#[test(tokio::test)]
async fn test_password_with_unicode() {
    let (db, _dirs) = common::create_test_db();

    // Should work with unicode characters
    let result = db.create_user("testuser", "Pass123🔐中文", None, None, None);

    assert!(result.is_ok());
}

// =============================================================================
// SQL INJECTION PROTECTION TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_sql_injection_in_username() {
    let (db, _dirs) = common::create_test_db();

    // Try SQL injection in username - should be REJECTED by input validation
    // SECURITY FIX: After adding input validation, dangerous characters are rejected
    let malicious_username = "admin' OR '1'='1";
    let result =
        db.create_user(malicious_username, "Password123!", None, None, None);

    // UPDATED: Should REJECT username with single quotes (dangerous character)
    assert!(
        result.is_err(),
        "Should reject username with SQL injection attempt"
    );

    // Verify we still use parameterized queries (defense in depth)
    // Even though input validation blocks the attack, we ensure SQL injection
    // is impossible even if validation is bypassed
    let safe_username = "validuser";
    db.create_user(safe_username, "Password123!", None, None, Some(false))
        .unwrap();

    let verify_result = db.verify_credentials(safe_username, "Password123!");
    assert!(verify_result.is_ok());
    let user = verify_result.unwrap();
    assert_eq!(user.username, safe_username);
}

#[test(tokio::test)]
async fn test_sql_injection_in_role_name() {
    let (db, _dirs) = common::create_test_db();

    let malicious_role_name = "admin'; DROP TABLE users; --";
    let result = db.create_role(malicious_role_name, Some("Malicious role"));

    // Should safely handle
    assert!(result.is_ok());

    // Tables should still exist
    let users = db.list_users(false, 100, 0);
    assert!(users.is_ok());
}

// =============================================================================
// CONCURRENT ACCESS TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_concurrent_user_creation() {
    let (db, _dirs) = common::create_test_db();
    let db = std::sync::Arc::new(db);

    let mut handles = vec![];

    for i in 0..10 {
        let db_clone = db.clone();
        let handle = std::thread::spawn(move || {
            db_clone.create_user(
                &format!("user{}", i),
                "Password123!",
                None,
                None,
                None,
            )
        });
        handles.push(handle);
    }

    let results: Vec<_> =
        handles.into_iter().map(|h| h.join().unwrap()).collect();

    // All should succeed
    let success_count = results.iter().filter(|r| r.is_ok()).count();
    assert_eq!(success_count, 10);
}

#[test(tokio::test)]
async fn test_concurrent_duplicate_user_creation() {
    let (db, _dirs) = common::create_test_db();
    let db = std::sync::Arc::new(db);

    let mut handles = vec![];

    // Try to create same user from multiple threads
    for _ in 0..10 {
        let db_clone = db.clone();
        let handle = std::thread::spawn(move || {
            db_clone.create_user(
                "duplicate_user",
                "Password123!",
                None,
                None,
                None,
            )
        });
        handles.push(handle);
    }

    let results: Vec<_> =
        handles.into_iter().map(|h| h.join().unwrap()).collect();

    // Only one should succeed
    let success_count = results.iter().filter(|r| r.is_ok()).count();
    assert_eq!(success_count, 1);

    // Others should fail with duplicate error
    let duplicate_count = results
        .iter()
        .filter(|r| matches!(r, Err(DatabaseError::Duplicate(_))))
        .count();
    assert_eq!(duplicate_count, 9);
}

#[test(tokio::test)]
async fn test_concurrent_api_key_verification() {
    let (db, _dirs) = common::create_test_db();
    let db = std::sync::Arc::new(db);

    // Create user and API key
    let user = db
        .create_user("test_user", "Password123!", None, None, Some(false))
        .unwrap();
    let (api_key, _) = db
        .create_api_key(user.id, Some("concurrent"), None, None, false)
        .unwrap();

    let mut handles = vec![];

    // Verify same API key from multiple threads
    for _ in 0..20 {
        let db_clone = db.clone();
        let key_clone = api_key.clone();
        let handle = std::thread::spawn(move || {
            db_clone.authenticate_api_key_request(&key_clone, None, "/peer-id")
        });
        handles.push(handle);
    }

    let results: Vec<_> =
        handles.into_iter().map(|h| h.join().unwrap()).collect();

    // All should succeed
    let success_count = results.iter().filter(|r| r.is_ok()).count();
    assert_eq!(success_count, 20);
}

#[test(tokio::test)]
async fn test_auth_metrics_are_exposed_in_prometheus() {
    let (app, _dirs) = common::TestApp::build(true, true, None).await;
    let api_key = common::login_app(&app, "admin", "AdminPass123!")
        .await
        .expect("admin login");

    let (status, body) = common::make_app_request_raw(
        &app,
        "/metrics",
        "GET",
        Some(&api_key),
        None,
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("auth_db_request_seconds"));
    assert!(body.contains("auth_db_transaction_seconds"));
    assert!(body.contains("auth_db_blocking_in_flight"));
    assert!(body.contains("request_kind=\"login\""));
    assert!(body.contains("request_kind=\"api_key_auth\""));
    assert!(body.contains("operation=\"authenticate_api_key_request\""));
}

#[test(tokio::test)]
async fn test_auth_blocking_in_flight_metric_tracks_running_tasks() {
    let (db, _dirs) = common::create_test_db();
    let mut registry = Registry::default();
    db.register_prometheus_metrics(&mut registry);

    let (started_tx, started_rx) = tokio::sync::oneshot::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();

    let db_for_task = db.clone();
    let handle = tokio::spawn(async move {
        db_for_task
            .run_blocking("blocking_metric_probe", move |_| {
                let _ = started_tx.send(());
                release_rx.recv().expect("release signal");
                Ok::<(), DatabaseError>(())
            })
            .await
    });

    tokio::time::timeout(Duration::from_secs(2), started_rx)
        .await
        .expect("blocking task started in time")
        .expect("blocking task start signal");
    tokio::time::sleep(Duration::from_millis(50)).await;

    let mut text = String::new();
    encode(&mut text, &registry).expect("encode metrics");
    assert_eq!(metric_value(&text, "auth_db_blocking_in_flight"), 1.0);

    release_tx.send(()).expect("release task");
    handle.await.expect("join task").expect("task result");

    let mut text = String::new();
    encode(&mut text, &registry).expect("encode metrics");
    assert_eq!(metric_value(&text, "auth_db_blocking_in_flight"), 0.0);
}

// =============================================================================
// EDGE CASES - SPECIAL CHARACTERS AND ENCODING
// =============================================================================

#[test(tokio::test)]
async fn test_unicode_username() {
    let (db, _dirs) = common::create_test_db();

    let unicode_username = "用户名🔐";
    let result =
        db.create_user(unicode_username, "Password123!", None, None, None);

    assert!(result.is_ok());

    let user = result.unwrap();
    assert_eq!(user.username, unicode_username);
}

#[test(tokio::test)]
async fn test_whitespace_in_names() {
    let (db, _dirs) = common::create_test_db();

    // Username with spaces
    let username = "user with spaces";
    let result =
        db.create_user(username, "Password123!", None, None, Some(false));
    assert!(result.is_ok());

    // Role with tabs
    let role_name = "role\twith\ttabs";
    let role = db.create_role(role_name, None);
    assert!(role.is_ok());
}

#[test(tokio::test)]
async fn test_very_long_strings() {
    let (db, _dirs) = common::create_test_db();

    // UPDATED: After adding length validation, very long usernames are rejected
    // Very long username (255 chars) - should be REJECTED (limit is 64)
    let long_username = "a".repeat(255);
    let result =
        db.create_user(&long_username, "Password123!", None, None, None);
    assert!(
        result.is_err(),
        "Should reject username longer than 64 chars"
    );

    // Test that maximum allowed username works (64 chars)
    let max_username = "a".repeat(64);
    let result =
        db.create_user(&max_username, "Password123!", None, None, None);
    assert!(result.is_ok(), "Should accept username of exactly 64 chars");

    // Very long role name now rejected by validation (limit is 100)
    let long_role_name = "b".repeat(255);
    let role = db.create_role(&long_role_name, None);
    assert!(
        role.is_err(),
        "Should reject role names longer than 100 chars"
    );

    // Boundary: max allowed role name (100 chars) should work
    let max_role_name = "b".repeat(100);
    let role = db.create_role(&max_role_name, None);
    assert!(role.is_ok(), "Should accept role name of exactly 100 chars");
}

// =============================================================================
// BOUNDARY TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_zero_ttl_api_key_never_expires() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Create key with 0 TTL (never expires)
    let (api_key, _) = db
        .create_api_key(user.id, Some("ttl0"), None, Some(0i64), false)
        .unwrap();

    // Should work immediately
    assert!(
        db.authenticate_api_key_request(&api_key, None, "/peer-id")
            .is_ok()
    );

    // Should still work after a delay
    std::thread::sleep(std::time::Duration::from_secs(1));
    assert!(
        db.authenticate_api_key_request(&api_key, None, "/peer-id")
            .is_ok()
    );
}

#[test(tokio::test)]
async fn test_explicit_zero_ttl_overrides_default() {
    use ave_bridge::auth::{
        ApiKeyConfig, AuthConfig, LockoutConfig, RateLimitConfig, SessionConfig,
    };
    use tempfile::TempDir;

    // Create temp directory for isolated test
    let _tmp_dir = TempDir::new().unwrap();

    // Create config with a default TTL of 30 days
    let config = AuthConfig {
        durability: false,
        enable: true,
        database_path: _tmp_dir.path().to_path_buf(),
        superadmin: "admin".to_string(),
        api_key: ApiKeyConfig {
            default_ttl_seconds: 2592000, // 30 days
            max_keys_per_user: 10,
            prefix: "ave_node_".to_string(),
        },
        lockout: LockoutConfig::default(),
        rate_limit: RateLimitConfig::default(),
        session: SessionConfig::default(),
    };

    let db = AuthDatabase::new(config, "TestPass123!", None)
        .expect("Failed to create database");

    let user = db
        .create_user("ttluser", "Password123!", None, None, Some(false))
        .unwrap();

    // Test 1: Create key with explicit TTL=0 (should never expire despite default_ttl)
    let (api_key_zero, key_info_zero) = db
        .create_api_key(user.id, Some("never-expire"), None, Some(0), false)
        .unwrap();

    assert!(
        key_info_zero.expires_at.is_none(),
        "Key with explicit TTL=0 should never expire (expires_at should be None)"
    );

    // Verify key works
    assert!(
        db.authenticate_api_key_request(&api_key_zero, None, "/peer-id")
            .is_ok()
    );

    // Test 2: Create key without TTL (should use default_ttl of 30 days)
    let (_api_key_default, key_info_default) = db
        .create_api_key(user.id, Some("use-default"), None, None, false)
        .unwrap();

    assert!(
        key_info_default.expires_at.is_some(),
        "Key without explicit TTL should use default_ttl (expires_at should be Some)"
    );

    // Test 3: Create key with explicit positive TTL
    let (_api_key_custom, key_info_custom) = db
        .create_api_key(user.id, Some("custom-ttl"), None, Some(3600), false)
        .unwrap();

    assert!(
        key_info_custom.expires_at.is_some(),
        "Key with explicit positive TTL should have expiration"
    );

    println!("✓ Explicit TTL=0 correctly overrides default_ttl:");
    println!("  - TTL=0 explicit: never expires (None)");
    println!("  - TTL=None: uses default_ttl (Some)");
    println!("  - TTL=3600: custom expiration (Some)");
}

#[test(tokio::test)]
async fn test_inactive_user_cannot_login() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Deactivate user
    db.update_user(user.id, None, Some(false)).unwrap();

    // Cannot login
    let result = db.verify_credentials("testuser", "Password123!");
    assert!(matches!(result, Err(DatabaseError::PermissionDenied(_))));
}

#[test(tokio::test)]
async fn test_inactive_user_api_keys_dont_work() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();
    let (api_key, _) = db
        .create_api_key(user.id, Some("lockout"), None, None, false)
        .unwrap();

    // Deactivate user
    db.update_user(user.id, None, Some(false)).unwrap();

    // API key should not work
    let result = db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(matches!(result, Err(DatabaseError::PermissionDenied(_))));
}

#[test(tokio::test)]
async fn test_deleted_user_api_keys_dont_work() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();
    let (api_key, _) = db
        .create_api_key(user.id, Some("lockout2"), None, None, false)
        .unwrap();

    // Delete user
    db.delete_user(user.id).unwrap();

    // API key should not work
    let result = db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(result.is_err());
}

// =============================================================================
// PERMISSION CASCADE TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_deleted_role_removes_user_permissions() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();
    let role = db.create_role("editor", None).unwrap();

    db.set_role_permission(role.id, "node_subject", "get", true)
        .unwrap();
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // User has permission
    let perms_before = db.get_user_effective_permissions(user.id).unwrap();
    assert!(perms_before.iter().any(|p| p.resource == "node_subject"
        && p.action == "get"
        && p.allowed));

    // Delete role
    db.delete_role(role.id).unwrap();

    // User should no longer have permission
    let perms_after = db.get_user_effective_permissions(user.id).unwrap();
    assert!(!perms_after.iter().any(|p| p.resource == "node_subject"
        && p.action == "get"
        && p.allowed));
}

// =============================================================================
// ADMIN PERMISSION GUARDS
// =============================================================================

#[test(tokio::test)]
async fn non_superadmin_cannot_modify_permissions_of_admin_via_role_inheritance()
 {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    let admin_role = db
        .create_role("admin_guard", Some("Admin guard role"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    let actor = db
        .create_user(
            "admin_actor",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            None,
        )
        .unwrap();
    let target = db
        .create_user(
            "admin_target",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            None,
        )
        .unwrap();

    let permissions = db.get_effective_permissions(actor.id).unwrap();
    let roles = db.get_user_roles(actor.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: actor.id,
        username: actor.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    let result = set_user_permission(
        AuthContextExtractor(auth_ctx),
        Extension(db.clone()),
        Path(target.id),
        Json(Permission {
            resource: "admin_system".to_string(),
            action: "all".to_string(),
            allowed: true,
            is_system: None,
            source: None,
            role_name: None,
        }),
    )
    .await;

    assert!(matches!(result, Err((StatusCode::FORBIDDEN, _))));
}

#[test(tokio::test)]
async fn non_superadmin_cannot_remove_permissions_of_admin_via_role_inheritance()
 {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    let admin_role = db
        .create_role("admin_guard_remove", Some("Admin guard role"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    let actor = db
        .create_user(
            "admin_actor_remove",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            None,
        )
        .unwrap();
    let target = db
        .create_user(
            "admin_target_remove",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            None,
        )
        .unwrap();

    db.set_user_permission(
        target.id,
        "node_subject",
        "get",
        true,
        Some(actor.id),
    )
    .unwrap();

    let permissions = db.get_effective_permissions(actor.id).unwrap();
    let roles = db.get_user_roles(actor.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: actor.id,
        username: actor.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    let result = remove_user_permission(
        AuthContextExtractor(auth_ctx),
        Extension(db.clone()),
        Path(target.id),
        Query(RemovePermissionQuery {
            resource: "node_subject".to_string(),
            action: "get".to_string(),
        }),
    )
    .await;

    assert!(matches!(result, Err((StatusCode::FORBIDDEN, _))));
}

#[test(tokio::test)]
async fn superadmin_flag_grants_all_permissions_even_without_overrides() {
    let ctx = AuthContext {
        user_id: 1,
        username: "root".to_string(),
        roles: vec!["superadmin".to_string()], // Superadmin role
        permissions: vec![],                   // No explicit permissions
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    };

    assert!(ctx.has_permission("any_resource", "any_action"));
}

// =============================================================================
// ERROR HANDLING TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_get_nonexistent_user() {
    let (db, _dirs) = common::create_test_db();

    let result = db.get_user_by_id(99999);

    assert!(matches!(result, Err(DatabaseError::NotFound(_))));
}

#[test(tokio::test)]
async fn test_get_nonexistent_role() {
    let (db, _dirs) = common::create_test_db();

    let result = db.get_role_by_name("nonexistent_role");

    assert!(matches!(result, Err(DatabaseError::NotFound(_))));
}

#[test(tokio::test)]
async fn test_assign_nonexistent_role() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    let result = db.assign_role_to_user(user.id, 99999, None);

    assert!(result.is_err());
}

#[test(tokio::test)]
async fn test_assign_role_to_nonexistent_user() {
    let (db, _dirs) = common::create_test_db();

    let role = db.create_role("editor", None).unwrap();

    let result = db.assign_role_to_user(99999, role.id, None);

    assert!(result.is_err());
}

#[test(tokio::test)]
async fn test_revoke_nonexistent_api_key() {
    let (db, _dirs) = common::create_test_db();

    let result =
        db.revoke_api_key("99999999-9999-9999-9999-999999999999", None, None);

    // revoke_api_key doesn't check if key exists, it just succeeds silently
    assert!(result.is_ok());
}

#[test(tokio::test)]
async fn test_update_nonexistent_user() {
    let (db, _dirs) = common::create_test_db();

    let result = db.update_user(99999, Some("NewPass123!"), None);

    assert!(matches!(result, Err(DatabaseError::NotFound(_))));
}

#[test(tokio::test)]
async fn test_delete_nonexistent_user() {
    let (db, _dirs) = common::create_test_db();

    let result = db.delete_user(99999);

    // delete_user doesn't check if user exists, it just succeeds silently
    assert!(result.is_ok());
}

#[test(tokio::test)]
async fn test_delete_nonexistent_role() {
    let (db, _dirs) = common::create_test_db();

    let result = db.delete_role(99999);

    assert!(matches!(result, Err(DatabaseError::NotFound(_))));
}

// =============================================================================
// SUPERADMIN TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_superadmin_bootstrap() {
    let (db, _dirs) = common::create_test_db();

    // Superadmin should exist
    let result = db.verify_credentials("admin", "AdminPass123!");

    assert!(result.is_ok());

    let user = result.unwrap();
    // Verify superadmin role
    let roles = db.get_user_roles(user.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));
}

#[test(tokio::test)]
async fn test_superadmin_has_all_permissions() {
    let (db, _dirs) = common::create_test_db();

    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Superadmin should have all permissions (empty list means all)
    let _perms = db.get_user_effective_permissions(admin.id).unwrap();

    // Superadmins bypass permission checks, so they might have empty perms
    // The middleware should check is_superadmin flag
    // Verify superadmin role
    let roles = db.get_user_roles(admin.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));
}

#[test(tokio::test)]
async fn test_create_regular_user_without_superadmin() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("regularuser", "UserPass123!", None, None, None)
        .unwrap();

    // Verify user does NOT have superadmin role
    let roles = db.get_user_roles(user.id).unwrap();
    assert!(!roles.contains(&"superadmin".to_string()));
}

// =============================================================================
// API KEY REVOCATION TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_revoked_api_key_cannot_be_used() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();
    let (api_key, key_info) = db
        .create_api_key(user.id, Some("rl_main"), None, None, false)
        .unwrap();

    // Revoke key
    db.revoke_api_key(&key_info.id, None, Some("Security breach"))
        .unwrap();

    // Should not verify
    let result = db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(matches!(result, Err(DatabaseError::PermissionDenied(_))));
}

#[test(tokio::test)]
async fn test_double_revoke_api_key() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();
    let (_, key_info) = db
        .create_api_key(user.id, Some("rl_expire"), None, None, false)
        .unwrap();

    // Revoke key
    db.revoke_api_key(&key_info.id, None, None).unwrap();

    // Revoke again (should still work or fail gracefully)
    let result = db.revoke_api_key(&key_info.id, None, None);
    // Either succeeds or fails with NotFound
    assert!(
        result.is_ok() || matches!(result, Err(DatabaseError::NotFound(_)))
    );
}

// =============================================================================
// STRESS TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_many_roles_for_user() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Create and assign 50 roles
    for i in 0..50 {
        let role = db.create_role(&format!("role{}", i), None).unwrap();
        db.assign_role_to_user(user.id, role.id, None).unwrap();
    }

    let roles = db.get_user_roles(user.id).unwrap();
    assert_eq!(roles.len(), 50);
}

#[test(tokio::test)]
async fn test_many_permissions_for_role() {
    let (db, _dirs) = common::create_test_db();

    let role = db.create_role("power_user", None).unwrap();

    // Use actual system resources and actions from schema
    let resources = vec![
        "user",
        "admin_system",
        "admin_api_key",
        "admin_roles",
        "admin_users",
        "node_system",
        "node_subject",
        "node_request",
    ];
    let actions = vec!["get", "post", "put", "patch", "delete", "all"];

    // Grant permissions for all combinations
    for resource in &resources {
        for action in &actions {
            db.set_role_permission(role.id, resource, action, true)
                .unwrap();
        }
    }

    let perms = db.get_role_permissions(role.id).unwrap();
    assert_eq!(perms.len(), resources.len() * actions.len());
}

#[test(tokio::test)]
async fn test_many_api_keys_for_user() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Create 10 API keys
    for i in 0..10 {
        db.create_api_key(
            user.id,
            Some(&format!("key{}", i)),
            None,
            None,
            false,
        )
        .unwrap();
    }

    let keys = db.list_user_api_keys(user.id, false).unwrap();
    assert_eq!(keys.len(), 10);
}

// =============================================================================
// SECURITY FIX VERIFICATION TESTS
// =============================================================================

/// Test that API key IDs are UUIDs and not sequential integers
/// Security Fix: Prevents IDOR attacks via predictable IDs
#[test(tokio::test)]
async fn test_api_key_public_ids_are_uuids_not_sequential() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Create multiple API keys
    let mut public_ids = vec![];
    for i in 0..5 {
        let (_, key_info) = db
            .create_api_key(
                user.id,
                Some(&format!("key{}", i)),
                None,
                None,
                false,
            )
            .unwrap();
        public_ids.push(key_info.id.clone());
    }

    // Verify all public_ids are UUIDs (format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
    for public_id in &public_ids {
        assert_eq!(public_id.len(), 36, "UUID should be 36 characters");
        assert_eq!(
            public_id.chars().filter(|c| *c == '-').count(),
            4,
            "UUID should have 4 dashes"
        );

        // Verify it's not a simple sequential number
        assert!(
            public_id.parse::<i64>().is_err(),
            "Public ID should not be a simple integer"
        );
    }

    // Verify they are all unique
    let unique_ids: std::collections::HashSet<_> = public_ids.iter().collect();
    assert_eq!(unique_ids.len(), 5, "All public IDs should be unique");
}

/// Test that pre-authentication rate limiting is enforced
/// Security Fix: Prevents brute force attacks on login endpoint
#[test(tokio::test)]
async fn test_pre_auth_rate_limiting_on_login() {
    use ave_bridge::auth::{
        ApiKeyConfig, AuthConfig, LockoutConfig, RateLimitConfig, SessionConfig,
    };
    use ave_http::auth::database::AuthDatabase;

    // Create test DB with specific rate limit config (100 requests/minute)
    let dir = tempfile::tempdir().expect("Can not create temporal directory");
    let path = dir.path().to_path_buf();

    let config = AuthConfig {
        durability: false,
        enable: true,
        database_path: path,
        superadmin: "admin".to_string(),
        api_key: ApiKeyConfig {
            default_ttl_seconds: 0,
            max_keys_per_user: 10,
            prefix: "ave_node_".to_string(),
        },
        lockout: LockoutConfig {
            max_attempts: 5,
            duration_seconds: 900,
        },
        rate_limit: RateLimitConfig {
            enable: true,
            window_seconds: 60,
            max_requests: 100, // Set to 100 for this test
            limit_by_key: true,
            limit_by_ip: true,
            cleanup_interval_seconds: 3600,
            sensitive_endpoints: vec![],
        },
        session: SessionConfig {
            audit_enable: true,
            audit_retention_days: 90,
            audit_max_entries: 1_000_000,
        },
    };

    let db = AuthDatabase::new(config, "AdminPass123!", None).unwrap();

    // Create a test user
    db.create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Simulate multiple failed login attempts from same IP
    let fake_ip = Some("192.168.1.100");

    // Make requests up to rate limit (100 per 60 seconds)
    let mut successful_checks = 0;
    let mut rate_limited = false;

    for _ in 0..110 {
        match db.check_rate_limit(None, fake_ip, Some("/login")) {
            Ok(_) => successful_checks += 1,
            Err(DatabaseError::RateLimitExceeded(_)) => {
                rate_limited = true;
                break;
            }
            Err(e) => panic!("Unexpected error: {:?}", e),
        }
    }

    // Should hit rate limit before 110 attempts
    assert!(
        rate_limited,
        "Rate limit should be enforced on login endpoint"
    );
    assert!(
        successful_checks <= 100,
        "Should not exceed configured rate limit (got {})",
        successful_checks
    );
}

/// Test that API keys created have public_id populated
/// Security Fix: Ensures migration populates UUIDs for existing keys
#[test(tokio::test)]
async fn test_api_keys_have_public_id_after_migration() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    let (_, key_info) = db
        .create_api_key(user.id, Some("test"), None, None, false)
        .unwrap();

    // id should be populated and non-empty UUID
    assert!(!key_info.id.is_empty(), "id should not be empty");
    assert_ne!(key_info.id, "0", "id should not be default value");
}

/// Test concurrent API key creation respects max_keys limit
/// Security Fix: Addresses race condition vulnerability #6
/// NOTE: Limit is enforced at application level. While a race condition is
/// theoretically possible, SQLite's transaction isolation makes it very unlikely.
#[test(tokio::test)]
async fn test_concurrent_api_key_creation_respects_max_limit() {
    let (db, _dirs) = common::create_test_db();
    let db = std::sync::Arc::new(db);

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    let mut handles = vec![];

    // Try to create 25 keys concurrently (limit is 20)
    for i in 0..25 {
        let db_clone = db.clone();
        let user_id = user.id;
        let handle = std::thread::spawn(move || {
            db_clone.create_api_key(
                user_id,
                Some(&format!("concurrent_key_{}", i)),
                None,
                None,
                false,
            )
        });
        handles.push(handle);
    }

    let results: Vec<_> =
        handles.into_iter().map(|h| h.join().unwrap()).collect();

    // Count successful creations
    let success_count = results.iter().filter(|r| r.is_ok()).count();

    // Should not exceed the max limit (20)
    assert!(
        success_count <= 20,
        "Should not create more than max_keys_per_user limit (got {})",
        success_count
    );

    // Verify actual count in database
    let keys = db.list_user_api_keys(user.id, false).unwrap();
    assert!(
        keys.len() <= 20,
        "Database should not have more than 20 keys (got {})",
        keys.len()
    );
}

/// Test that dangerous characters in API key names are rejected
/// Security Fix: Prevents XSS, SQL injection, command injection, and path traversal
#[test(tokio::test)]
async fn test_dangerous_characters_in_api_key_names_rejected() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Test various dangerous characters that should be rejected
    let dangerous_names = vec![
        "<script>alert('xss')</script>", // XSS
        "'; DROP TABLE users; --",       // SQL injection
        "key`whoami`",                   // Command injection (backtick)
        "key$(whoami)",                  // Command injection (dollar)
        "key|whoami",                    // Command injection (pipe)
        "key;rm -rf /",                  // Command injection (semicolon)
        "../../../etc/passwd",           // Path traversal
        "key\\..\\secrets",              // Path traversal (Windows)
        "key\0hidden",                   // Null byte injection
        "key\ninjected",                 // Newline injection
        "key\rinjected",                 // Carriage return injection
        "key<>test",                     // HTML/XML injection
        "key&test",                      // URL/command injection
        "key*test",                      // Wildcard
        "key?test",                      // Wildcard
        "key%00test",                    // URL encoding
        "key{test}",                     // Template injection
        "key[test]",                     // Array injection
    ];

    for dangerous_name in dangerous_names {
        let result =
            db.create_api_key(user.id, Some(dangerous_name), None, None, false);

        assert!(
            result.is_err(),
            "Should reject dangerous name: {}",
            dangerous_name
        );

        if let Err(e) = result {
            match e {
                DatabaseError::Validation(_) => {
                    // Expected error type
                }
                _ => panic!("Expected ValidationError, got: {:?}", e),
            }
        }
    }

    // Test valid names that should be accepted
    let valid_names = vec![
        "my_api_key",
        "production-key",
        "test key 2024",
        "api.key.1",
        "Key_123",
        "UPPERCASE_KEY",
    ];

    for valid_name in valid_names {
        let result =
            db.create_api_key(user.id, Some(valid_name), None, None, false);

        assert!(
            result.is_ok(),
            "Should accept valid name: {} (error: {:?})",
            valid_name,
            result.err()
        );
    }
}

/// Test that security headers are set to prevent API key leakage
/// Security Fix: Referrer-Policy prevents API keys from leaking via Referer header
#[test(tokio::test)]
async fn test_security_headers_prevent_api_key_leakage() {
    // This test verifies that the security headers are properly configured
    // in the application code. The actual header verification would require
    // integration tests with a running server.

    // Here we verify that the validation logic rejects API keys in query params
    // (they should only be in headers)
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    let (api_key, _key_info) = db
        .create_api_key(user.id, Some("test-key"), None, None, false)
        .unwrap();

    // Verify API key format is correct (should be a bearer token, not URL-friendly)
    assert!(api_key.starts_with("ave_node_"));
    assert!(
        api_key.len() > 40,
        "API key should be long enough to prevent brute force"
    );

    // Verify that API key names are sanitized (already tested in previous test)
    // This ensures that even if displayed in UI, they won't cause XSS

    // The actual Referrer-Policy header test would be:
    // 1. Start test server with security middleware
    // 2. Make authenticated request
    // 3. Check response headers contain: Referrer-Policy: no-referrer
    // 4. Check response headers contain: X-Content-Type-Options: nosniff
    // 5. Check response headers contain: X-Frame-Options: DENY

    // For now, we document that these headers MUST be verified in integration tests
    // The middleware is configured in main.rs lines 101-113
}

/// Test that CRLF injection is prevented in all text fields
/// Security Fix: Prevents header injection and log forgery via CRLF characters
#[test(tokio::test)]
async fn test_crlf_injection_prevented_in_text_fields() {
    let (db, _dirs) = common::create_test_db();

    // Test CRLF in usernames
    let crlf_usernames = vec![
        "user\r\nInjected-Header: malicious",
        "user\nlog-injection",
        "user\rcarriage-return",
        "user\r\n\r\nHTTP/1.1 200 OK",
        "admin\r\nSet-Cookie: session=hijacked",
    ];

    for username in crlf_usernames {
        let result =
            db.create_user(username, "Password123!", None, None, Some(false));
        assert!(
            result.is_err(),
            "Should reject username with CRLF: {:?}",
            username
        );
        if let Err(e) = result {
            match e {
                DatabaseError::Validation(msg) => {
                    assert!(msg.contains("CRLF") || msg.contains("control"));
                }
                _ => panic!("Expected ValidationError for CRLF, got: {:?}", e),
            }
        }
    }

    // Test CRLF in descriptions
    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    let crlf_descriptions = vec![
        "Description\r\nInjected-Header: malicious",
        "Description\nlog-injection",
        "Description\rcarriage-return",
        "Normal desc\r\n\r\nHTTP/1.1 200 OK",
    ];

    for desc in crlf_descriptions {
        let result = db.create_api_key(
            user.id,
            Some("test-key"),
            Some(desc),
            None,
            false,
        );
        assert!(
            result.is_err(),
            "Should reject description with CRLF: {:?}",
            desc
        );
        if let Err(e) = result {
            match e {
                DatabaseError::Validation(msg) => {
                    assert!(msg.contains("CRLF") || msg.contains("control"));
                }
                _ => panic!(
                    "Expected ValidationError for CRLF in description, got: {:?}",
                    e
                ),
            }
        }
    }

    // Test null bytes
    let null_byte_tests = vec![("user\0hidden", "Password123!")];

    for (username, password) in null_byte_tests {
        let result =
            db.create_user(username, password, None, None, Some(false));
        assert!(result.is_err(), "Should reject null bytes in username");
    }

    // Test valid strings work
    let valid_user = db
        .create_user("validuser", "Password123!", None, None, Some(false))
        .unwrap();
    assert_eq!(valid_user.username, "validuser");

    let (_, key_info) = db
        .create_api_key(
            user.id,
            Some("valid-key"),
            Some("Valid description with normal text"),
            None,
            false,
        )
        .unwrap();
    assert_eq!(
        key_info.description,
        Some("Valid description with normal text".to_string())
    );

    // Test length limits
    let long_username = "a".repeat(65);
    let result =
        db.create_user(&long_username, "Password123!", None, None, Some(false));
    assert!(
        result.is_err(),
        "Should reject username longer than 64 chars"
    );

    let long_description = "a".repeat(501);
    let result = db.create_api_key(
        user.id,
        Some("test-long-desc"),
        Some(&long_description),
        None,
        false,
    );
    assert!(
        result.is_err(),
        "Should reject description longer than 500 chars"
    );
}

/// Test configurable CORS settings
/// Vulnerability: #4 CORS Wildcard (CVSS 6.5)
/// Fix: CORS is now configurable via config file
#[test(tokio::test)]
async fn test_cors_configuration_security() {
    use ave_bridge::CorsConfig;

    // Test 1: Default configuration (permissive - development mode)
    let default_config = CorsConfig::default();
    assert!(default_config.enabled, "CORS should be enabled by default");
    assert!(
        default_config.allow_any_origin,
        "Default allows any origin (for development)"
    );
    assert_eq!(default_config.allowed_origins.len(), 0);
    assert!(
        !default_config.allow_credentials,
        "Should never allow credentials with wildcard origin"
    );

    // Test 2: Secure production configuration
    let secure_config = CorsConfig {
        enabled: true,
        allow_any_origin: false,
        allowed_origins: vec![
            "https://app.example.com".to_string(),
            "https://dashboard.example.com".to_string(),
        ],
        allow_credentials: false,
    };
    assert!(
        !secure_config.allow_any_origin,
        "Production should not allow any origin"
    );
    assert_eq!(
        secure_config.allowed_origins.len(),
        2,
        "Should have specific origins"
    );

    // Test 3: CORS disabled configuration
    let disabled_config = CorsConfig {
        enabled: false,
        allow_any_origin: false,
        allowed_origins: vec![],
        allow_credentials: false,
    };
    assert!(!disabled_config.enabled, "CORS can be disabled");

    // Test 4: Verify dangerous combination is caught
    // (allow_any_origin=true with allow_credentials=true is dangerous)
    let dangerous_config = CorsConfig {
        enabled: true,
        allow_any_origin: true,
        allowed_origins: vec![],
        allow_credentials: true, // This is dangerous!
    };
    // Note: The application code should validate this and warn/prevent it
    // But the config allows documenting why this is dangerous
    assert!(
        dangerous_config.allow_any_origin && dangerous_config.allow_credentials,
        "This combination is dangerous and should be avoided in production"
    );
}

// =============================================================================
// VULN-21: USER ENUMERATION VIA ERROR MESSAGES
// =============================================================================

/// Test that user enumeration via different error messages is prevented
/// VULN-21: Invalid credentials, locked accounts, and disabled accounts
/// should all return the same generic error message
#[test(tokio::test)]
async fn test_user_enumeration_prevented_via_error_messages() {
    let (db, _dirs) = common::create_test_db();

    // Create test users with different states
    let _active_user = db
        .create_user("active_user", "Password123!", None, None, Some(false))
        .unwrap();

    let inactive_user = db
        .create_user("inactive_user", "Password123!", None, None, Some(false))
        .unwrap();
    db.update_user(inactive_user.id, None, Some(false)).unwrap();

    let _locked_user = db
        .create_user("locked_user", "Password123!", None, None, Some(false))
        .unwrap();
    // Lock the user by exceeding failed attempts
    for _ in 0..5 {
        let _ = db.verify_credentials("locked_user", "WrongPassword!");
    }

    // Test 1: Non-existent user
    let err1 = db
        .verify_credentials("nonexistent", "Password123!")
        .unwrap_err();

    // Test 2: Inactive user
    let err2 = db
        .verify_credentials("inactive_user", "Password123!")
        .unwrap_err();

    // Test 3: Locked user
    let err3 = db
        .verify_credentials("locked_user", "Password123!")
        .unwrap_err();

    // Test 4: Wrong password
    let err4 = db
        .verify_credentials("active_user", "WrongPassword!")
        .unwrap_err();

    // All errors should be PermissionDenied with the SAME message
    match (&err1, &err2, &err3, &err4) {
        (
            DatabaseError::PermissionDenied(msg1),
            DatabaseError::PermissionDenied(msg2),
            DatabaseError::PermissionDenied(msg3),
            DatabaseError::PermissionDenied(msg4),
        ) => {
            // All messages should be identical to prevent enumeration
            assert_eq!(msg1, "Invalid username or password");
            assert_eq!(msg2, "Invalid username or password");
            assert_eq!(msg3, "Invalid username or password");
            assert_eq!(msg4, "Invalid username or password");

            // Verify they're all the same
            assert_eq!(msg1, msg2);
            assert_eq!(msg2, msg3);
            assert_eq!(msg3, msg4);
        }
        _ => panic!("All errors should be PermissionDenied with same message"),
    }
}

// =============================================================================
// VULN-23: SINGLE SUPERADMIN ENFORCEMENT
// =============================================================================

/// Test that only one superadmin can exist in the system
/// VULN-23: Multiple superadmins should not be allowed
#[test(tokio::test)]
async fn test_only_one_superadmin_allowed() {
    let (db, _dirs) = common::create_test_db();

    // Verify bootstrap superadmin exists
    let count_before = db.count_superadmins().unwrap();
    assert_eq!(
        count_before, 1,
        "Should have exactly 1 superadmin after bootstrap"
    );

    // Try to create another superadmin by assigning the superadmin role (should fail)
    // Get superadmin role ID
    let roles = db.list_roles().unwrap();
    let superadmin_role =
        roles.iter().find(|r| r.name == "superadmin").unwrap();

    let result = db.create_user(
        "second_superadmin",
        "SuperPass123!",
        Some(vec![superadmin_role.id]), // Try to assign superadmin role
        None,
        None,
    );

    // Should fail because a superadmin already exists
    assert!(
        result.is_err(),
        "Should not allow creating second superadmin"
    );

    // Verify count is still 1
    let count_after = db.count_superadmins().unwrap();
    assert_eq!(count_after, 1, "Should still have exactly 1 superadmin");
}

/// Test that superadmin account cannot be deleted
#[test(tokio::test)]
async fn test_superadmin_cannot_be_deleted() {
    let (db, _dirs) = common::create_test_db();

    // Get the bootstrap superadmin
    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();
    // Verify superadmin role
    let roles = db.get_user_roles(admin.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));

    // Try to delete superadmin (should fail)
    let result = db.delete_user(admin.id);

    // Should succeed at DB level (no protection there)
    // Protection is at handler level, but we can test DB behavior
    assert!(result.is_ok(), "DB layer allows deletion");

    // However, handlers should block this
    // This will be tested in integration tests with actual handlers
}

/// Test that superadmin account cannot be deactivated
#[test(tokio::test)]
async fn test_superadmin_cannot_be_deactivated() {
    let (db, _dirs) = common::create_test_db();

    // Get the bootstrap superadmin
    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();
    // Verify superadmin role
    let roles = db.get_user_roles(admin.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));
    assert!(admin.is_active);

    // Try to deactivate superadmin at DB level
    let result = db.update_user(admin.id, None, Some(false));

    // DB layer allows it, but handlers should block
    assert!(result.is_ok(), "DB layer allows deactivation");

    // Verify it was deactivated at DB level
    let updated_admin = db.get_user_by_id(admin.id).unwrap();
    assert!(!updated_admin.is_active, "DB layer allowed deactivation");

    // Handler-level protection will be tested in integration tests
}

/// Test that non-superadmin cannot reset superadmin password
#[test(tokio::test)]
async fn test_non_superadmin_cannot_reset_superadmin_password() {
    let (db, _dirs) = common::create_test_db();

    // Get the bootstrap superadmin
    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();
    // Verify superadmin role
    let roles = db.get_user_roles(admin.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));

    // Reset password at DB level (no protection here)
    let result = db.admin_reset_password(admin.id, "NewPassword123!");
    assert!(result.is_ok(), "DB layer allows password reset");

    // Change password using credentials to clear must_change_password flag
    let result = db.change_password_with_credentials(
        "admin",
        "NewPassword123!",
        "FinalPassword123!",
    );
    assert!(result.is_ok(), "Password change should work");

    // Verify final password works
    let result = db.verify_credentials("admin", "FinalPassword123!");
    assert!(
        result.is_ok(),
        "Final password should work: {:?}",
        result.err()
    );

    // Handler-level protection will be tested in integration tests
}

/// Test count_superadmins function
#[test(tokio::test)]
async fn test_count_superadmins() {
    let (db, _dirs) = common::create_test_db();

    // Should have exactly 1 superadmin (bootstrap)
    let count = db.count_superadmins().unwrap();
    assert_eq!(count, 1);

    // Create a regular user
    db.create_user("regular", "Password123!", None, None, Some(false))
        .unwrap();

    // Count should still be 1
    let count = db.count_superadmins().unwrap();
    assert_eq!(count, 1);

    // Try to create another superadmin (will fail due to validation)
    let roles = db.list_roles().unwrap();
    let superadmin_role =
        roles.iter().find(|r| r.name == "superadmin").unwrap();

    let result = db.create_user(
        "another_super",
        "SuperPass123!",
        Some(vec![superadmin_role.id]),
        None,
        None,
    );
    assert!(result.is_err());

    // Count should still be 1
    let count = db.count_superadmins().unwrap();
    assert_eq!(count, 1);
}

/// SECURITY REGRESSION TEST:
/// Test that assign_role_to_user cannot bypass superadmin uniqueness
#[test(tokio::test)]
async fn test_assign_role_cannot_create_second_superadmin() {
    let (db, _dirs) = common::create_test_db();

    // Get superadmin role ID
    let roles = db.list_roles().unwrap();
    let superadmin_role =
        roles.iter().find(|r| r.name == "superadmin").unwrap();

    // Create a regular user
    let user = db
        .create_user("testuser", "Password123!", None, None, Some(false))
        .unwrap();

    // Try to assign superadmin role (should fail because admin already exists)
    let result = db.assign_role_to_user(user.id, superadmin_role.id, None);

    // At database level, this might succeed, but handlers should prevent it
    // This test verifies the database-level enforcement
    // Handler-level tests will be in integration tests
    if result.is_ok() {
        // If DB allows it, verify count is now 2 (not ideal but documents behavior)
        let count = db.count_superadmins().unwrap();
        assert!(count >= 1, "Should have at least the bootstrap superadmin");
    }
}

/// SECURITY REGRESSION TEST:
/// Test that removing superadmin role from only superadmin should fail at handler level
#[test(tokio::test)]
async fn test_remove_superadmin_role_from_only_superadmin_db_level() {
    let (db, _dirs) = common::create_test_db();

    // Get the bootstrap admin
    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Get superadmin role
    let roles = db.list_roles().unwrap();
    let superadmin_role =
        roles.iter().find(|r| r.name == "superadmin").unwrap();

    // Verify admin is the only superadmin
    let count = db.count_superadmins().unwrap();
    assert_eq!(count, 1);

    // Try to remove superadmin role from admin
    // At DB level this might succeed (protection is at handler level)
    let result = db.remove_role_from_user(admin.id, superadmin_role.id);

    // If it succeeds at DB level, verify the role was removed
    if result.is_ok() {
        let user_roles = db.get_user_roles(admin.id).unwrap();
        assert!(
            !user_roles.contains(&"superadmin".to_string()),
            "DB level allows removal - handler must prevent"
        );

        // System now has no superadmin (bad state)
        let count = db.count_superadmins().unwrap();
        assert_eq!(
            count, 0,
            "DB allows removing last superadmin - handler must prevent"
        );
    }
}

/// SECURITY REGRESSION TEST:
/// Test that update_user cannot remove superadmin role via role_ids parameter
/// Attack vector: PUT /admin/users/{superadmin_id} with role_ids that don't include superadmin
#[test(tokio::test)]
async fn test_update_user_cannot_remove_superadmin_role() {
    let (db, _dirs) = common::create_test_db();

    // Get the bootstrap admin
    let admin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Verify admin is superadmin
    let roles = db.get_user_roles(admin.id).unwrap();
    assert!(roles.contains(&"superadmin".to_string()));

    // Verify count before test
    let count = db.count_superadmins().unwrap();
    assert_eq!(count, 1, "Should have exactly one superadmin before test");

    // This test documents the attack vector:
    // An attacker with admin_users:put could call update_user with role_ids
    // that exclude the superadmin role, effectively demoting the only superadmin
    // The handler protection (validate_superadmin_removal) prevents this attack
}

/// SECURITY REGRESSION TEST:
/// Test that users cannot rotate API keys of other users
/// Attack vector: POST /admin/api-keys/{other_user_key_id}/rotate
#[test(tokio::test)]
async fn test_cannot_rotate_other_users_api_keys() {
    let (db, _dirs) = common::create_test_db();

    // Create two users
    let user1 = db
        .create_user("user1", "Password123!", None, None, Some(false))
        .unwrap();
    let user2 = db
        .create_user("user2", "Password123!", None, None, Some(false))
        .unwrap();

    // Create API key for user1
    let (_, key1) = db
        .create_api_key(user1.id, Some("user1_key"), None, None, false)
        .unwrap();

    // Get user2's roles to verify in handler tests
    // Handler should prevent user2 from rotating user1's key
    let user2_roles = db.get_user_roles(user2.id).unwrap();
    assert!(
        !user2_roles.contains(&"superadmin".to_string()),
        "user2 should not be superadmin for this test"
    );

    // The handler check prevents this attack
    // Integration tests will verify the HTTP endpoint blocks this
    assert_eq!(key1.username, "user1");
}

/// SECURITY REGRESSION TEST:
/// Test that users cannot revoke API keys of other users
/// Attack vector: DELETE /admin/api-keys/{other_user_key_id}
#[test(tokio::test)]
async fn test_cannot_revoke_other_users_api_keys() {
    let (db, _dirs) = common::create_test_db();

    // Create two users
    let user1 = db
        .create_user("user1", "Password123!", None, None, Some(false))
        .unwrap();
    let user2 = db
        .create_user("user2", "Password123!", None, None, Some(false))
        .unwrap();

    // Create API key for user1
    let (_, key1) = db
        .create_api_key(user1.id, Some("user1_key"), None, None, false)
        .unwrap();

    // Verify key is active
    let key_info = db.get_api_key_info(&key1.id).unwrap();
    assert!(!key_info.revoked, "Key should not be revoked initially");

    // Get user2's roles to verify in handler tests
    // Handler should prevent user2 from revoking user1's key
    let user2_roles = db.get_user_roles(user2.id).unwrap();
    assert!(
        !user2_roles.contains(&"superadmin".to_string()),
        "user2 should not be superadmin for this test"
    );

    // The handler check prevents this attack
    // Integration tests will verify the HTTP endpoint blocks this
    assert_eq!(key_info.username, "user1");
}

/// SECURITY REGRESSION TEST:
/// Test that users cannot create service API keys for other users
/// Attack vector: POST /admin/api-keys/user/{other_user_id}
/// This would allow impersonating the target user with full permissions
#[test(tokio::test)]
async fn test_cannot_create_service_keys_for_other_users() {
    let (db, _dirs) = common::create_test_db();

    // Create two users
    let user1 = db
        .create_user("user1", "Password123!", None, None, Some(false))
        .unwrap();
    let user2 = db
        .create_user("user2", "Password123!", None, None, Some(false))
        .unwrap();

    // Verify neither user is superadmin
    let user1_roles = db.get_user_roles(user1.id).unwrap();
    let user2_roles = db.get_user_roles(user2.id).unwrap();
    assert!(
        !user1_roles.contains(&"superadmin".to_string()),
        "user1 should not be superadmin"
    );
    assert!(
        !user2_roles.contains(&"superadmin".to_string()),
        "user2 should not be superadmin"
    );

    // The handler prevents user2 from creating service keys for user1
    // This prevents impersonation attack where user2 could get full access as user1
    // Integration tests will verify the HTTP endpoint blocks this
    assert_ne!(user1.id, user2.id);
}

/// SECURITY REGRESSION TEST:
/// Test that non-superadmin users cannot modify role permissions
/// Attack vector: User with admin_roles:all modifies their own role to grant themselves admin_users:all
#[test(tokio::test)]
async fn test_cannot_escalate_privileges_via_role_permission_modification() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Create a role with admin_roles:all permission
    let role_manager_role = db
        .create_role("role_manager", Some("Can manage roles"))
        .unwrap();
    db.set_role_permission(role_manager_role.id, "admin_roles", "all", true)
        .unwrap();

    // Create user with role_manager role
    let attacker = db
        .create_user(
            "attacker_user",
            "Password123!",
            Some(vec![role_manager_role.id]),
            None,
            None,
        )
        .unwrap();

    let permissions = db.get_effective_permissions(attacker.id).unwrap();
    let roles = db.get_user_roles(attacker.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: attacker.id,
        username: attacker.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Try to escalate privileges by adding admin_users:all to their own role
    let result = set_role_permission(
        AuthContextExtractor(auth_ctx),
        Extension(db.clone()),
        Path(role_manager_role.id),
        Json(SetPermissionRequest {
            resource: "admin_users".to_string(),
            action: "all".to_string(),
            allowed: true,
        }),
    )
    .await;

    // Should be forbidden - only superadmin can modify role permissions
    assert!(
        matches!(result, Err((StatusCode::FORBIDDEN, _))),
        "Non-superadmin should not be able to modify role permissions"
    );
}

/// SECURITY REGRESSION TEST:
/// Test that non-superadmin users cannot remove role permissions
/// Attack vector: User with admin_roles:all removes deny permissions from their own role
#[test(tokio::test)]
async fn test_cannot_remove_role_permission_denials() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Create a role with admin_roles:all but denied admin_system:all
    let limited_admin_role = db
        .create_role("limited_admin", Some("Admin without system access"))
        .unwrap();
    db.set_role_permission(limited_admin_role.id, "admin_roles", "all", true)
        .unwrap();
    db.set_role_permission(limited_admin_role.id, "admin_system", "all", false)
        .unwrap();

    // Create user with limited_admin role
    let attacker = db
        .create_user(
            "limited_admin_user",
            "Password123!",
            Some(vec![limited_admin_role.id]),
            None,
            None,
        )
        .unwrap();

    let permissions = db.get_effective_permissions(attacker.id).unwrap();
    let roles = db.get_user_roles(attacker.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: attacker.id,
        username: attacker.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Try to escalate by removing the denial
    let result = remove_role_permission(
        AuthContextExtractor(auth_ctx),
        Extension(db.clone()),
        Path(limited_admin_role.id),
        Query(RemovePermissionQuery {
            resource: "admin_system".to_string(),
            action: "all".to_string(),
        }),
    )
    .await;

    // Should be forbidden - only superadmin can modify role permissions
    assert!(
        matches!(result, Err((StatusCode::FORBIDDEN, _))),
        "Non-superadmin should not be able to remove role permissions"
    );
}

/// SECURITY TEST:
/// Test that system permissions cannot be modified or deleted
/// Ensures that initial system permissions (is_system = 1) are protected
#[test(tokio::test)]
async fn test_cannot_modify_system_permissions() {
    let (db, _dirs) = common::create_test_db();

    // Get the superadmin role (which has system permissions)
    let superadmin_role = db.get_role_by_name("superadmin").unwrap();

    // Get one of the system permissions
    let perms = db.get_role_permissions(superadmin_role.id).unwrap();
    assert!(!perms.is_empty(), "Superadmin should have permissions");

    // Find a system permission
    let system_perm = perms.iter().find(|p| p.is_system == Some(true));
    assert!(
        system_perm.is_some(),
        "Superadmin should have at least one system permission"
    );

    let perm = system_perm.unwrap();

    // Try to modify the system permission (change allowed from true to false)
    let result = db.set_role_permission(
        superadmin_role.id,
        &perm.resource,
        &perm.action,
        false,
    );

    // Should fail - cannot modify system role permissions
    assert!(
        matches!(result, Err(DatabaseError::PermissionDenied(_))),
        "Should not be able to modify permissions of system role. Got: {:?}",
        result
    );

    // Try to remove the system permission
    let result = db.remove_role_permission(
        superadmin_role.id,
        &perm.resource,
        &perm.action,
    );

    // Should fail - cannot delete system role permissions
    assert!(
        matches!(result, Err(DatabaseError::PermissionDenied(_))),
        "Should not be able to delete permissions of system role. Got: {:?}",
        result
    );
}

/// SECURITY TEST:
/// Test that all system roles (superadmin, admin, etc.) are protected
#[test(tokio::test)]
async fn test_all_system_roles_are_protected() {
    let (db, _dirs) = common::create_test_db();

    let system_roles = vec!["superadmin", "admin", "sender", "manager", "data"];

    for role_name in system_roles {
        let role = db.get_role_by_name(role_name).unwrap();
        assert!(role.is_system, "Role {} should be a system role", role_name);

        let perms = db.get_role_permissions(role.id).unwrap();

        // Each system role should have at least one permission
        assert!(
            !perms.is_empty(),
            "System role {} should have permissions",
            role_name
        );

        // Try to modify the first permission
        let first_perm = &perms[0];
        let result = db.set_role_permission(
            role.id,
            &first_perm.resource,
            &first_perm.action,
            !first_perm.allowed,
        );

        // Should fail - cannot modify system role permissions
        assert!(
            matches!(result, Err(DatabaseError::PermissionDenied(_))),
            "Should not be able to modify permissions of system role {}. Got: {:?}",
            role_name,
            result
        );

        // Try to remove a permission
        let result = db.remove_role_permission(
            role.id,
            &first_perm.resource,
            &first_perm.action,
        );

        // Should also fail
        assert!(
            matches!(result, Err(DatabaseError::PermissionDenied(_))),
            "Should not be able to delete permissions of system role {}. Got: {:?}",
            role_name,
            result
        );
    }
}

/// SECURITY TEST:
/// Test that non-system permissions CAN be modified on custom roles
/// Ensures the validation doesn't block legitimate operations
#[test(tokio::test)]
async fn test_can_modify_non_system_permissions() {
    let (db, _dirs) = common::create_test_db();

    // Create a custom (non-system) role
    let custom_role = db
        .create_role("modifiable_role", Some("Test role"))
        .unwrap();
    assert!(
        !custom_role.is_system,
        "Custom role should not be a system role"
    );

    // Add a permission to the custom role
    // Note: The resource "user" is a system resource, but we CAN modify permissions
    // on a non-system role, even if the resource is a system resource
    db.set_role_permission(custom_role.id, "user", "get", true)
        .unwrap();

    // Verify it was added
    let perms = db.get_role_permissions(custom_role.id).unwrap();
    let perm = perms
        .iter()
        .find(|p| p.resource == "user" && p.action == "get");
    assert!(perm.is_some(), "Permission should be added");
    // The resource "user" is a system resource
    assert_eq!(
        perm.unwrap().is_system,
        Some(true),
        "The 'user' resource is a system resource"
    );

    // Modify the permission (change allowed to false)
    let result = db.set_role_permission(custom_role.id, "user", "get", false);
    assert!(
        result.is_ok(),
        "Should be able to modify permissions on non-system role"
    );

    // Remove the permission
    let result = db.remove_role_permission(custom_role.id, "user", "get");
    assert!(
        result.is_ok(),
        "Should be able to remove permissions from non-system role"
    );

    // Verify it was removed
    let perms = db.get_role_permissions(custom_role.id).unwrap();
    let perm = perms
        .iter()
        .find(|p| p.resource == "user" && p.action == "get");
    assert!(perm.is_none(), "Permission should be removed");
}

/// SECURITY REGRESSION TEST:
/// Test that API keys are revoked when admin resets password
/// Attack vector: Compromised account maintains persistent access via existing API keys
#[test(tokio::test)]
async fn test_api_keys_revoked_on_admin_password_reset() {
    let (db, _dirs) = common::create_test_db();

    // Create user without must_change_password
    let user = db
        .create_user("victim", "OldPass123!", None, None, Some(false))
        .unwrap();

    // Create API key for user
    let (api_key, _key_info) = db
        .create_api_key(user.id, Some("test_key"), None, None, true)
        .unwrap();

    // Verify the key works
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(auth_result.is_ok(), "API key should work before reset");

    // Admin resets password
    db.admin_reset_password(user.id, "NewPass123!").unwrap();

    // Verify the key is now revoked
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(
        auth_result.is_err(),
        "API key should be revoked after password reset"
    );
}

/// SECURITY REGRESSION TEST:
/// Test that API keys are revoked when user changes password (forced change flow)
/// Attack vector: Compromised account maintains persistent access via existing API keys
#[test(tokio::test)]
async fn test_api_keys_revoked_on_user_password_change() {
    let (db, _dirs) = common::create_test_db();

    // Create user without must_change_password flag so API key can work
    let user = db
        .create_user(
            "victim2",
            "OldPass123!",
            None,
            None,
            Some(false), // must_change_password = false (so API key works)
        )
        .unwrap();

    // Create API key for user
    let (api_key, _key_info) = db
        .create_api_key(user.id, Some("test_key2"), None, None, true)
        .unwrap();

    // Verify the key works
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(auth_result.is_ok(), "API key should work before change");

    // User changes password via update_user (simulating authenticated password change)
    db.update_user(user.id, Some("NewPass123!"), None).unwrap();

    // Verify the key is now revoked
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(
        auth_result.is_err(),
        "API key should be revoked after password change"
    );
}

/// SECURITY REGRESSION TEST:
/// Test that non-superadmin cannot change superadmin's password via update_user
/// Attack vector: Admin with admin_users:put changes superadmin password to take control
#[test(tokio::test)]
async fn test_cannot_change_superadmin_password_via_update() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Get bootstrap superadmin user
    let superadmin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Create admin role with admin_users:put permission
    let admin_role = db
        .create_role("user_admin", Some("Can manage users"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "put", true)
        .unwrap();

    // Create attacker user with user_admin role
    let attacker = db
        .create_user(
            "attacker_admin",
            "AttackerPass123!",
            Some(vec![admin_role.id]),
            None,
            None,
        )
        .unwrap();

    let permissions = db.get_effective_permissions(attacker.id).unwrap();
    let roles = db.get_user_roles(attacker.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: attacker.id,
        username: attacker.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Try to change superadmin's password
    let result = update_user(
        AuthContextExtractor(auth_ctx),
        Extension(db.clone()),
        Path(superadmin.id),
        Json(UpdateUserRequest {
            password: Some("HackedPass123!".to_string()),
            is_active: None,
            role_ids: None,
        }),
    )
    .await;

    // Should be forbidden
    assert!(
        matches!(result, Err((StatusCode::FORBIDDEN, _))),
        "Non-superadmin should not be able to change superadmin's password"
    );
}

/// SECURITY REGRESSION TEST:
/// Test that API keys are revoked when password is changed via update_user
/// Attack vector: Compromised account maintains persistent access via existing API keys
#[test(tokio::test)]
async fn test_api_keys_revoked_on_update_user_password_change() {
    let (db, _dirs) = common::create_test_db();

    // Create user without must_change_password
    let user = db
        .create_user("victim3", "OldPass123!", None, None, Some(false))
        .unwrap();

    // Create API key for user
    let (api_key, _key_info) = db
        .create_api_key(user.id, Some("test_key3"), None, None, true)
        .unwrap();

    // Verify the key works
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(
        auth_result.is_ok(),
        "API key should work before password change"
    );

    // Admin changes user's password via update_user
    db.update_user(user.id, Some("NewPass123!"), None).unwrap();

    // Verify the key is now revoked
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(
        auth_result.is_err(),
        "API key should be revoked after password change via update_user"
    );
}

/// SECURITY REGRESSION TEST:
/// Test that API keys are blocked when must_change_password is set
/// Attack vector: User bypasses forced password change by using API keys
#[test(tokio::test)]
async fn test_api_keys_blocked_when_must_change_password() {
    let (db, _dirs) = common::create_test_db();

    // Create user with must_change_password flag
    let user = db
        .create_user("new_user", "InitialPass123!", None, Some(1), None)
        .unwrap();

    // Create API key for user
    let (api_key, _key_info) = db
        .create_api_key(user.id, Some("bypass_key"), None, None, true)
        .unwrap();

    // Try to use API key - should be blocked
    let auth_result =
        db.authenticate_api_key_request(&api_key, None, "/peer-id");
    assert!(
        auth_result.is_err(),
        "API key should be blocked when must_change_password is set"
    );

    // Verify the error is PasswordChangeRequired
    match auth_result {
        Err(DatabaseError::PasswordChangeRequired(_)) => {
            // Expected error type
        }
        _ => panic!("Expected PasswordChangeRequired error"),
    }

    // User changes password
    db.change_password_with_credentials(
        "new_user",
        "InitialPass123!",
        "NewPass123!",
    )
    .unwrap();

    // Now create a new API key and it should work
    let (new_api_key, _new_key_info) = db
        .create_api_key(user.id, Some("valid_key"), None, None, true)
        .unwrap();

    let auth_result =
        db.authenticate_api_key_request(&new_api_key, None, "/peer-id");
    assert!(
        auth_result.is_ok(),
        "API key should work after password has been changed"
    );
}

/// SECURITY TEST: Superadmin can change their own password
#[test(tokio::test)]
async fn test_superadmin_can_change_own_password() {
    let (db, _dirs) = common::create_test_db();

    // Get bootstrap superadmin
    let superadmin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Superadmin changes their own password
    let result = db.update_user(superadmin.id, Some("NewAdminPass123!"), None);
    assert!(
        result.is_ok(),
        "Superadmin should be able to change their own password"
    );

    // Verify old password doesn't work
    let old_login = db.verify_credentials("admin", "AdminPass123!");
    assert!(old_login.is_err(), "Old password should not work");

    // Verify new password works
    let new_login = db.verify_credentials("admin", "NewAdminPass123!");
    assert!(new_login.is_ok(), "New password should work");
}

/// SECURITY TEST: Superadmin can delete their own API keys
#[test(tokio::test)]
async fn test_superadmin_can_delete_own_api_keys() {
    let (db, _dirs) = common::create_test_db();

    let superadmin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Create API key for superadmin (management key)
    let (api_key, key_info) = db
        .create_api_key(superadmin.id, Some("admin_key"), None, None, true)
        .unwrap();

    // Verify key works
    assert!(
        db.authenticate_api_key_request(&api_key, None, "/peer-id")
            .is_ok()
    );

    // Superadmin revokes their own key
    let result = db.revoke_api_key(
        &key_info.id,
        Some(superadmin.id),
        Some("Self-revocation"),
    );
    assert!(
        result.is_ok(),
        "Superadmin should be able to revoke their own API key"
    );

    // Verify key no longer works
    assert!(
        db.authenticate_api_key_request(&api_key, None, "/peer-id")
            .is_err()
    );
}

/// SECURITY TEST: Permission conflicts - user deny overrides role allow
#[test(tokio::test)]
async fn test_permission_conflict_user_deny_overrides_role_allow() {
    let (db, _dirs) = common::create_test_db();

    // Create user
    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Create role with permission
    let role = db.create_role("viewer", None).unwrap();
    db.set_role_permission(role.id, "admin_users", "get", true)
        .unwrap();

    // Assign role to user
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // Verify user has permission from role
    let perms = db.get_effective_permissions(user.id).unwrap();
    assert!(perms.iter().any(|p| p.resource == "admin_users"
        && p.action == "get"
        && p.allowed));

    // Set user-level deny (should override role allow)
    db.set_user_permission(user.id, "admin_users", "get", false, None)
        .unwrap();

    // Verify user-level deny overrides role allow
    let perms = db.get_effective_permissions(user.id).unwrap();
    let events_get = perms
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "get");
    assert!(events_get.is_some());
    assert!(
        !events_get.unwrap().allowed,
        "User-level deny should override role allow"
    );
}

/// SECURITY TEST: Removing role removes permissions immediately
#[test(tokio::test)]
async fn test_removing_role_removes_permissions_immediately() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Create role with permissions
    let role = db.create_role("editor", None).unwrap();
    db.set_role_permission(role.id, "admin_users", "post", true)
        .unwrap();
    db.set_role_permission(role.id, "admin_users", "delete", true)
        .unwrap();

    // Assign role
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // Verify permissions
    let perms = db.get_effective_permissions(user.id).unwrap();
    assert!(
        perms
            .iter()
            .any(|p| p.resource == "admin_users" && p.action == "post")
    );
    assert!(
        perms
            .iter()
            .any(|p| p.resource == "admin_users" && p.action == "delete")
    );

    // Remove role
    db.remove_role_from_user(user.id, role.id).unwrap();

    // Verify permissions are gone
    let perms = db.get_effective_permissions(user.id).unwrap();
    assert!(
        !perms
            .iter()
            .any(|p| p.resource == "admin_users" && p.action == "post")
    );
    assert!(
        !perms
            .iter()
            .any(|p| p.resource == "admin_users" && p.action == "delete")
    );
}

/// SECURITY TEST: Deleting role removes it from all users
#[test(tokio::test)]
async fn test_deleting_role_removes_from_all_users() {
    let (db, _dirs) = common::create_test_db();

    // Create multiple users
    let user1 = db
        .create_user("user1", "Pass123!", None, None, Some(false))
        .unwrap();
    let user2 = db
        .create_user("user2", "Pass123!", None, None, Some(false))
        .unwrap();

    // Create role and assign to both
    let role = db.create_role("shared_role", None).unwrap();
    db.set_role_permission(role.id, "admin_users", "get", true)
        .unwrap();
    db.assign_role_to_user(user1.id, role.id, None).unwrap();
    db.assign_role_to_user(user2.id, role.id, None).unwrap();

    // Verify both have permissions
    assert!(db.get_effective_permissions(user1.id).unwrap().len() > 0);
    assert!(db.get_effective_permissions(user2.id).unwrap().len() > 0);

    // Delete role
    db.delete_role(role.id).unwrap();

    // Verify both users lost permissions
    assert_eq!(db.get_effective_permissions(user1.id).unwrap().len(), 0);
    assert_eq!(db.get_effective_permissions(user2.id).unwrap().len(), 0);
}

/// SECURITY TEST: Management vs Service key permissions
#[test(tokio::test)]
async fn test_management_key_has_full_permissions() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // User only has events:get permission
    let role = db.create_role("viewer", None).unwrap();
    db.set_role_permission(role.id, "admin_users", "get", true)
        .unwrap();
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // Create management key (is_management = true)
    let result = db.create_api_key(
        user.id,
        Some("management_key"),
        None,
        None,
        true, // management key
    );

    // Should succeed in creating the key
    assert!(result.is_ok());
    let (_api_key, key_info) = result.unwrap();
    assert!(
        key_info.is_management,
        "Key should be marked as management key"
    );
}

/// SECURITY TEST: Service key marked correctly
#[test(tokio::test)]
async fn test_service_key_flag() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Create service key (is_management = false)
    let (_api_key, key_info) = db
        .create_api_key(user.id, Some("service_key"), None, None, false)
        .unwrap();

    assert!(
        !key_info.is_management,
        "Key should be marked as service key (not management)"
    );
}

/// SECURITY TEST: Concurrent password changes
#[test(tokio::test)]
async fn test_concurrent_password_changes() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    let user = db
        .create_user("testuser", "OldPass123!", None, None, Some(false))
        .unwrap();

    let mut handles = vec![];
    for i in 0..5 {
        let db_clone = Arc::clone(&db);
        let user_id = user.id;
        let handle = std::thread::spawn(move || {
            db_clone.update_user(user_id, Some(&format!("NewPass{}!", i)), None)
        });
        handles.push(handle);
    }

    let mut successes = 0;
    for handle in handles {
        if handle.join().unwrap().is_ok() {
            successes += 1;
        }
    }

    // At least one should succeed
    assert!(
        successes > 0,
        "At least one concurrent password change should succeed"
    );
}

/// SECURITY TEST: Lockout triggers after 5 failed attempts
#[test(tokio::test)]
async fn test_lockout_triggers_after_failed_attempts() {
    let (db, _dirs) = common::create_test_db();

    db.create_user("victim", "CorrectPass123!", None, None, Some(false))
        .unwrap();

    // Make 4 failed attempts (not enough to trigger lockout)
    for _ in 0..4 {
        let _ = db.verify_credentials("victim", "WrongPass123!");
    }

    // 5th attempt should still work with correct password
    let result = db.verify_credentials("victim", "CorrectPass123!");
    // Note: successful login resets counter, so this works
    assert!(
        result.is_ok(),
        "Should be able to login after 4 failed attempts"
    );

    // Make 5 failed attempts to trigger lockout
    for _ in 0..5 {
        let _ = db.verify_credentials("victim", "WrongPass123!");
    }

    // Should be locked now
    let result = db.verify_credentials("victim", "CorrectPass123!");
    assert!(
        result.is_err(),
        "Account should be locked after 5 failed attempts"
    );
}

/// SECURITY TEST: Password change resets lockout
#[test(tokio::test)]
async fn test_password_change_resets_lockout() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("victim", "OldPass123!", None, None, Some(false))
        .unwrap();

    // Trigger lockout (5 failed attempts)
    for _ in 0..5 {
        let _ = db.verify_credentials("victim", "WrongPass!");
    }

    // Verify locked
    let result = db.verify_credentials("victim", "OldPass123!");
    assert!(result.is_err());

    // Admin resets password
    db.admin_reset_password(user.id, "NewPass123!").unwrap();

    // Should be able to change password now
    let result = db.change_password_with_credentials(
        "victim",
        "NewPass123!",
        "FinalPass123!",
    );
    assert!(
        result.is_ok(),
        "Password change should work after admin reset"
    );

    // Verify failed_login_attempts reset
    let updated_user =
        db.verify_credentials("victim", "FinalPass123!").unwrap();
    assert_eq!(updated_user.failed_login_attempts, 0);
    assert!(updated_user.locked_until.is_none());
}

/// SECURITY TEST: Non-superadmin cannot assign roles to other admins
/// This prevents admins from modifying other admins' privileges
#[test(tokio::test)]
async fn test_admin_cannot_assign_role_to_other_admin() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Create an admin role with admin_users:all permission
    let admin_role = db
        .create_role("user_admin", Some("Can manage users"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    // Create another role that gives admin permissions
    let editor_role = db
        .create_role("editor_admin", Some("Editor admin"))
        .unwrap();
    db.set_role_permission(editor_role.id, "admin_roles", "all", true)
        .unwrap();

    // Create two admin users
    let admin_actor = db
        .create_user(
            "admin_actor",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    let admin_target = db
        .create_user(
            "admin_target",
            "Password123!",
            Some(vec![editor_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    // Verify both are considered admins
    let _actor_user = db.get_user_by_id(admin_actor.id).unwrap();
    let _target_user = db.get_user_by_id(admin_target.id).unwrap();

    // Build auth context for admin_actor
    let permissions = db.get_effective_permissions(admin_actor.id).unwrap();
    let roles = db.get_user_roles(admin_actor.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: admin_actor.id,
        username: admin_actor.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Try to assign a role to the other admin (should fail)
    let result = assign_role(
        AuthContextExtractor(auth_ctx.clone()),
        Extension(db.clone()),
        Path((admin_target.id, editor_role.id)),
    )
    .await;

    // Should be FORBIDDEN
    assert!(
        matches!(result, Err((StatusCode::FORBIDDEN, _))),
        "Non-superadmin admin should not be able to assign roles to other admins"
    );
}

/// SECURITY TEST: Non-superadmin cannot remove roles from other admins
/// This prevents admins from neutralizing other admins by removing their roles
#[test(tokio::test)]
async fn test_admin_cannot_remove_role_from_other_admin() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Create an admin role with admin_users:all permission
    let admin_role = db
        .create_role("user_admin_2", Some("Can manage users"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    // Create another role that gives admin permissions
    let system_admin_role = db
        .create_role("system_admin", Some("System admin"))
        .unwrap();
    db.set_role_permission(system_admin_role.id, "admin_system", "all", true)
        .unwrap();

    // Create two admin users
    let admin_actor = db
        .create_user(
            "admin_actor_2",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    let admin_target = db
        .create_user(
            "admin_target_2",
            "Password123!",
            Some(vec![system_admin_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    // Build auth context for admin_actor
    let permissions = db.get_effective_permissions(admin_actor.id).unwrap();
    let roles = db.get_user_roles(admin_actor.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: admin_actor.id,
        username: admin_actor.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Try to remove role from the other admin (should fail)
    let result = remove_role(
        AuthContextExtractor(auth_ctx.clone()),
        Extension(db.clone()),
        Path((admin_target.id, system_admin_role.id)),
    )
    .await;

    // Should be FORBIDDEN
    assert!(
        matches!(result, Err((StatusCode::FORBIDDEN, _))),
        "Non-superadmin admin should not be able to remove roles from other admins"
    );
}

/// SECURITY TEST: Admin CAN assign roles to regular users
/// This verifies that admins can still manage regular (non-admin) users
#[test(tokio::test)]
async fn test_admin_can_assign_role_to_regular_user() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Create an admin role with admin_users:all permission
    let admin_role = db
        .create_role("user_admin_3", Some("Can manage users"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    // Create a regular (non-admin) role
    let viewer_role = db.create_role("viewer", Some("Viewer role")).unwrap();
    // No admin permissions for this role

    // Create admin user
    let admin_user = db
        .create_user(
            "admin_user",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    // Create regular user (no admin permissions)
    let regular_user = db
        .create_user(
            "regular_user",
            "Password123!",
            None, // No roles = not admin
            None,
            Some(false),
        )
        .unwrap();

    // Build auth context for admin
    let permissions = db.get_effective_permissions(admin_user.id).unwrap();
    let roles = db.get_user_roles(admin_user.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: admin_user.id,
        username: admin_user.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Admin should be able to assign role to regular user
    let result = assign_role(
        AuthContextExtractor(auth_ctx.clone()),
        Extension(db.clone()),
        Path((regular_user.id, viewer_role.id)),
    )
    .await;

    // Should succeed
    assert!(
        result.is_ok(),
        "Admin should be able to assign roles to regular (non-admin) users"
    );
}

/// SECURITY TEST: Superadmin CAN assign roles to other admins
/// This verifies that superadmin has full control
#[test(tokio::test)]
async fn test_superadmin_can_assign_role_to_admin() {
    let (db, _dirs) = common::create_test_db();
    let db = Arc::new(db);

    // Get the superadmin
    let superadmin = db.verify_credentials("admin", "AdminPass123!").unwrap();

    // Create an admin role
    let admin_role = db
        .create_role("new_admin_role", Some("New admin role"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    // Create another admin user
    let other_admin = db
        .create_user(
            "other_admin",
            "Password123!",
            Some(vec![admin_role.id]),
            None,
            Some(false),
        )
        .unwrap();

    // Build auth context for superadmin
    let permissions = db.get_effective_permissions(superadmin.id).unwrap();
    let roles = db.get_user_roles(superadmin.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: superadmin.id,
        username: superadmin.username.clone(),
        roles,
        permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Superadmin should be able to assign role to other admin
    let result = assign_role(
        AuthContextExtractor(auth_ctx.clone()),
        Extension(db.clone()),
        Path((other_admin.id, admin_role.id)),
    )
    .await;

    // Should succeed
    assert!(
        result.is_ok(),
        "Superadmin should be able to assign roles to other admins"
    );
}

// =============================================================================
// PERMISSION SOURCE TRACKING TESTS
// =============================================================================

#[test(tokio::test)]
async fn test_permission_source_field_distinguishes_direct_and_role_permissions()
 {
    use ave_http::auth::admin_handlers::get_user_permissions;

    let (db, _dirs) = common::create_test_db();

    // Create superadmin
    let superadmin = db
        .create_user("superadmin", "SuperPass123!", None, None, Some(false))
        .unwrap();
    db.assign_role_to_user(superadmin.id, 1, None).unwrap(); // Assign superadmin role

    // Create a test role with specific permissions
    let test_role = db
        .create_role("test_role", Some("Role for testing permission sources"))
        .unwrap();

    // Add a role permission (admin_users:get)
    db.set_role_permission(test_role.id, "admin_users", "get", true)
        .unwrap();

    // Create a regular user
    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Assign the test_role to the user
    db.assign_role_to_user(user.id, test_role.id, None).unwrap();

    // Add a DIRECT permission to the user (admin_roles:post)
    db.set_user_permission(user.id, "admin_roles", "post", true, None)
        .unwrap();

    // Create auth context for superadmin
    let superadmin_permissions =
        db.get_effective_permissions(superadmin.id).unwrap();
    let superadmin_roles = db.get_user_roles(superadmin.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: superadmin.id,
        username: superadmin.username.clone(),
        roles: superadmin_roles,
        permissions: superadmin_permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Get user permissions via the endpoint
    let result = get_user_permissions(
        AuthContextExtractor(auth_ctx),
        Extension(Arc::new(db.clone())),
        Path(user.id),
    )
    .await;

    assert!(
        result.is_ok(),
        "Should successfully retrieve user permissions"
    );

    let Json(permissions) = result.unwrap();

    // Verify we got permissions
    assert!(!permissions.is_empty(), "User should have permissions");

    // Find the role-inherited permission (admin_users:get)
    let role_perm = permissions
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "get");

    assert!(role_perm.is_some(), "Should have admin_users:get from role");
    let role_perm = role_perm.unwrap();

    // Verify it has source = "role"
    assert_eq!(
        role_perm.source.as_deref(),
        Some("role"),
        "admin_users:get should have source='role'"
    );

    // Verify it has the role_name populated
    assert_eq!(
        role_perm.role_name.as_deref(),
        Some("test_role"),
        "admin_users:get should have role_name='test_role'"
    );

    // Find the direct permission (admin_roles:post)
    let direct_perm = permissions
        .iter()
        .find(|p| p.resource == "admin_roles" && p.action == "post");

    assert!(
        direct_perm.is_some(),
        "Should have admin_roles:post direct permission"
    );
    let direct_perm = direct_perm.unwrap();

    // Verify it has source = "direct"
    assert_eq!(
        direct_perm.source.as_deref(),
        Some("direct"),
        "admin_roles:post should have source='direct'"
    );

    // Verify role_name is None for direct permissions
    assert!(
        direct_perm.role_name.is_none(),
        "Direct permissions should not have role_name"
    );

    println!("✓ Permission source tracking works correctly:");
    println!("  - Role permission has source='role' and role_name");
    println!("  - Direct permission has source='direct' and no role_name");
}

#[test(tokio::test)]
async fn test_direct_permission_overrides_role_permission() {
    use ave_http::auth::admin_handlers::get_user_permissions;

    let (db, _dirs) = common::create_test_db();

    // Create superadmin
    let superadmin = db
        .create_user("superadmin", "SuperPass123!", None, None, Some(false))
        .unwrap();
    db.assign_role_to_user(superadmin.id, 1, None).unwrap();

    // Create a role that allows admin_system:all
    let role = db
        .create_role("system_admin", Some("System administrator"))
        .unwrap();
    db.set_role_permission(role.id, "admin_system", "all", true)
        .unwrap();

    // Create user and assign role
    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // Now add a DIRECT deny override for the same permission
    db.set_user_permission(user.id, "admin_system", "all", false, None)
        .unwrap();

    // Create auth context
    let superadmin_permissions =
        db.get_effective_permissions(superadmin.id).unwrap();
    let superadmin_roles = db.get_user_roles(superadmin.id).unwrap();

    let auth_ctx = Arc::new(AuthContext {
        user_id: superadmin.id,
        username: superadmin.username.clone(),
        roles: superadmin_roles,
        permissions: superadmin_permissions,
        api_key_id: "test-key".to_string(),
        is_management_key: true,
        ip_address: None,
    });

    // Get permissions
    let result = get_user_permissions(
        AuthContextExtractor(auth_ctx),
        Extension(Arc::new(db.clone())),
        Path(user.id),
    )
    .await;

    assert!(result.is_ok());
    let Json(permissions) = result.unwrap();

    // Find admin_system:all permission
    let perm = permissions
        .iter()
        .find(|p| p.resource == "admin_system" && p.action == "all");

    assert!(perm.is_some(), "Should have admin_system:all permission");
    let perm = perm.unwrap();

    // Should be marked as direct (not from role) since user override exists
    assert_eq!(
        perm.source.as_deref(),
        Some("direct"),
        "Direct override should take precedence, showing source='direct'"
    );

    // Should be denied
    assert_eq!(
        perm.allowed, false,
        "Direct deny should override role allow"
    );

    // Should NOT have role_name since it's a direct permission
    assert!(
        perm.role_name.is_none(),
        "Direct permission override should not have role_name"
    );

    println!(
        "✓ Direct permission override correctly takes precedence over role permission"
    );
}

/// SECURITY TEST:
/// Test that direct permission denials take precedence over role permissions
/// Scenario: User has role with "all" permission, but direct deny on specific action
/// Expected: Direct deny blocks access even though role grants it
#[test(tokio::test)]
async fn test_direct_deny_blocks_role_allow_functionally() {
    let (db, _dirs) = common::create_test_db();

    // Create a role with admin_users:all permission (grants everything)
    let admin_role = db
        .create_role("user_admin", Some("User administrator"))
        .unwrap();
    db.set_role_permission(admin_role.id, "admin_users", "all", true)
        .unwrap();

    // Create user and assign role
    let user = db
        .create_user("blocked_user", "TestPass123!", None, None, Some(false))
        .unwrap();
    db.assign_role_to_user(user.id, admin_role.id, None)
        .unwrap();

    // Verify user has role permission for admin_users:get via role
    let role_perms = db.get_role_permissions(admin_role.id).unwrap();
    assert!(
        role_perms.iter().any(|p| p.resource == "admin_users"
            && p.action == "all"
            && p.allowed),
        "Role should have admin_users:all permission"
    );

    // Now add a DIRECT DENY for admin_users:get
    // This should OVERRIDE the role's "all" permission
    db.set_user_permission(user.id, "admin_users", "get", false, None)
        .unwrap();

    // Get effective permissions (what's actually used for authorization)
    let effective_perms = db.get_effective_permissions(user.id).unwrap();

    // Find the admin_users:get permission in effective permissions
    let get_perm = effective_perms
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "get");

    assert!(
        get_perm.is_some(),
        "Should have admin_users:get in effective permissions"
    );

    let get_perm = get_perm.unwrap();

    // CRITICAL: The effective permission should be DENIED (false)
    // because direct permission overrides role permission
    assert_eq!(
        get_perm.allowed, false,
        "Direct deny should override role 'all' permission - user should be BLOCKED"
    );

    // Verify role's "all" permission still works for OTHER actions that aren't denied
    let post_perm = effective_perms
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "post");

    if let Some(post_perm) = post_perm {
        assert!(
            post_perm.allowed,
            "Other actions not explicitly denied should still be allowed via role"
        );
    }

    // Create AuthContext to test functional authorization
    let user_roles = db.get_user_roles(user.id).unwrap();
    let auth_ctx = AuthContext {
        user_id: user.id,
        username: user.username.clone(),
        roles: user_roles,
        permissions: effective_perms,
        api_key_id: "test-key".to_string(),
        is_management_key: false,
        ip_address: None,
    };

    // Verify that has_permission returns FALSE (blocked)
    assert!(
        !auth_ctx.has_permission("admin_users", "get"),
        "User should be BLOCKED from admin_users:get despite role having 'all' permission"
    );

    println!(
        "✓ Direct deny successfully blocks access despite role granting 'all' permission"
    );
    println!("  - Role grants admin_users:all (should allow everything)");
    println!(
        "  - Direct deny on admin_users:get (blocks this specific action)"
    );
    println!("  - Result: User CANNOT access admin_users:get ✓");
}

/// SECURITY TEST:
/// Test that service API keys CANNOT manage (create/revoke) other API keys
/// Only management keys (from login) can manage API keys
#[test(tokio::test)]
async fn test_service_key_cannot_manage_api_keys() {
    use ave_http::auth::apikey_handlers::{
        create_my_api_key, revoke_my_api_key,
    };
    use ave_http::auth::models::CreateApiKeyRequest;

    let (db, _dirs) = common::create_test_db();

    // Create a user with permission to manage their own API keys
    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Give user permission to manage personal API keys
    db.set_user_permission(user.id, "user_api_key", "post", true, None)
        .unwrap();
    db.set_user_permission(user.id, "user_api_key", "delete", true, None)
        .unwrap();

    // Create a MANAGEMENT key (simulating login)
    let (_management_key, management_info) = db
        .create_api_key(user.id, Some("management_session"), None, None, true)
        .unwrap();

    assert!(management_info.is_management, "Should be a management key");

    // Create a SERVICE key using the management key
    let user_roles = db.get_user_roles(user.id).unwrap();
    let user_perms = db.get_effective_permissions(user.id).unwrap();

    let management_ctx = Arc::new(AuthContext {
        user_id: user.id,
        username: "testuser".to_string(),
        roles: user_roles.clone(),
        permissions: user_perms.clone(),
        api_key_id: management_info.id.clone(),
        is_management_key: true,
        ip_address: None,
    });

    let create_req = CreateApiKeyRequest {
        name: "service_key".to_string(),
        description: Some("Service key for automation".to_string()),
        expires_in_seconds: None,
    };

    let result = create_my_api_key(
        AuthContextExtractor(management_ctx.clone()),
        Extension(Arc::new(db.clone())),
        Json(create_req),
    )
    .await;

    assert!(
        result.is_ok(),
        "Management key should be able to create service keys"
    );
    let (status, Json(response)) = result.unwrap();
    assert_eq!(status, StatusCode::CREATED);
    let _service_key = response.api_key;
    let service_info = response.key_info;

    assert!(
        !service_info.is_management,
        "Created key should be a service key"
    );

    // Now try to use the SERVICE key to create another API key
    // This should FAIL because service keys cannot manage API keys
    let service_ctx = Arc::new(AuthContext {
        user_id: user.id,
        username: "testuser".to_string(),
        roles: user_roles.clone(),
        permissions: user_perms.clone(),
        api_key_id: service_info.id.clone(),
        is_management_key: false, // This is a service key
        ip_address: None,
    });

    let create_req2 = CreateApiKeyRequest {
        name: "another_service_key".to_string(),
        description: Some("Trying to create another key".to_string()),
        expires_in_seconds: None,
    };

    let result = create_my_api_key(
        AuthContextExtractor(service_ctx.clone()),
        Extension(Arc::new(db.clone())),
        Json(create_req2),
    )
    .await;

    // Should FAIL - service keys cannot create other API keys
    assert!(
        result.is_err(),
        "Service key should NOT be able to create API keys"
    );
    let (status, Json(err)) = result.unwrap_err();
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert!(
        err.error.contains("management API key"),
        "Error should mention management key requirement"
    );

    // Also test that service key cannot revoke other keys
    let result = revoke_my_api_key(
        AuthContextExtractor(service_ctx),
        Extension(Arc::new(db.clone())),
        Path(service_info.name.clone()),
        None,
    )
    .await;

    // Should FAIL - service keys cannot revoke API keys
    assert!(
        result.is_err(),
        "Service key should NOT be able to revoke API keys"
    );
    let (status, Json(err)) = result.unwrap_err();
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert!(
        err.error.contains("management API key"),
        "Error should mention management key requirement"
    );

    println!("✓ Service keys correctly blocked from managing API keys");
    println!("  - Service key CANNOT create new API keys");
    println!("  - Service key CANNOT revoke API keys");
    println!("  - Only management keys (from login) can manage API keys");
}

/// SECURITY TEST:
/// Test that "all" permission prevents individual permissions and vice versa
/// Only applies to DIRECT user permissions, NOT role permissions
#[test(tokio::test)]
async fn test_all_permission_validation() {
    let (db, _dirs) = common::create_test_db();

    let user = db
        .create_user("testuser", "TestPass123!", None, None, Some(false))
        .unwrap();

    // Test 1: Assign individual permissions first, then "all" should remove them
    db.set_user_permission(user.id, "admin_users", "get", true, None)
        .unwrap();
    db.set_user_permission(user.id, "admin_users", "post", true, None)
        .unwrap();
    db.set_user_permission(user.id, "admin_users", "put", true, None)
        .unwrap();

    // Verify individual permissions exist
    let all_perms_before = db.get_user_permissions(user.id).unwrap();
    let perms_before: Vec<_> = all_perms_before
        .iter()
        .filter(|p| p.source.as_deref() == Some("direct"))
        .collect();
    let get_perm = perms_before
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "get");
    let post_perm = perms_before
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "post");
    assert!(get_perm.is_some(), "Should have get permission");
    assert!(post_perm.is_some(), "Should have post permission");

    // Assign "all" - should automatically remove individual permissions
    db.set_user_permission(user.id, "admin_users", "all", true, None)
        .unwrap();

    // Verify individual permissions were removed, only "all" remains
    let all_perms_after = db.get_user_permissions(user.id).unwrap();
    let perms_after: Vec<_> = all_perms_after
        .iter()
        .filter(|p| p.source.as_deref() == Some("direct"))
        .collect();
    let get_perm_after = perms_after
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "get");
    let post_perm_after = perms_after
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "post");
    let all_perm = perms_after
        .iter()
        .find(|p| p.resource == "admin_users" && p.action == "all");

    assert!(
        get_perm_after.is_none(),
        "Individual 'get' permission should be removed"
    );
    assert!(
        post_perm_after.is_none(),
        "Individual 'post' permission should be removed"
    );
    assert!(all_perm.is_some(), "Should have 'all' permission");

    println!("✓ Test 1 passed: Assigning 'all' removes individual permissions");

    // Test 2: Try to assign individual permission when "all" exists - should fail
    let result =
        db.set_user_permission(user.id, "admin_users", "delete", true, None);
    assert!(
        result.is_err(),
        "Should not allow individual permission when 'all' exists"
    );

    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(
            msg.contains("already has 'all' permission"),
            "Error message should mention 'all' permission"
        );
    } else {
        panic!("Expected ValidationError, got: {:?}", result);
    }

    println!(
        "✓ Test 2 passed: Cannot assign individual permission when 'all' exists"
    );

    // Test 3: Role permissions should NOT be affected
    // Create a role with individual permissions
    let role = db.create_role("test_role", Some("Test role")).unwrap();
    db.set_role_permission(role.id, "admin_roles", "get", true)
        .unwrap();
    db.set_role_permission(role.id, "admin_roles", "post", true)
        .unwrap();
    db.assign_role_to_user(user.id, role.id, None).unwrap();

    // User should be able to have "all" direct permission even though role has individual permissions
    let result =
        db.set_user_permission(user.id, "admin_roles", "all", false, None);
    assert!(
        result.is_ok(),
        "Should allow direct 'all' permission even when role has individual permissions"
    );

    // Verify role permissions still exist and user has direct "all" override
    let all_perms = db.get_user_permissions(user.id).unwrap();

    // Should have role permissions (get, post)
    let role_get = all_perms.iter().find(|p| {
        p.resource == "admin_roles"
            && p.action == "get"
            && p.source.as_deref() == Some("role")
    });
    let role_post = all_perms.iter().find(|p| {
        p.resource == "admin_roles"
            && p.action == "post"
            && p.source.as_deref() == Some("role")
    });

    // Should have direct "all" override
    let direct_all = all_perms.iter().find(|p| {
        p.resource == "admin_roles"
            && p.action == "all"
            && p.source.as_deref() == Some("direct")
    });

    assert!(
        role_get.is_some(),
        "Role 'get' permission should still exist"
    );
    assert!(
        role_post.is_some(),
        "Role 'post' permission should still exist"
    );
    assert!(direct_all.is_some(), "Direct 'all' override should exist");
    assert!(
        !direct_all.unwrap().allowed,
        "Direct 'all' should be denied (override)"
    );

    println!(
        "✓ Test 3 passed: Role permissions are not affected by direct permission validation"
    );
    println!("✓ All permission validation works correctly:");
    println!("  - Assigning 'all' removes individual direct permissions");
    println!("  - Cannot assign individual when 'all' exists");
    println!("  - Role permissions remain independent");
}

#[test(tokio::test)]
async fn test_system_config_ttl_validation() {
    use ave_bridge::auth::{
        ApiKeyConfig, AuthConfig, LockoutConfig, RateLimitConfig, SessionConfig,
    };

    let tmp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let config = AuthConfig {
        durability: false,
        enable: true,
        database_path: tmp_dir.path().join("auth.db"),
        superadmin: "admin".to_string(),
        api_key: ApiKeyConfig::default(),
        lockout: LockoutConfig::default(),
        rate_limit: RateLimitConfig::default(),
        session: SessionConfig::default(),
    };

    let db = AuthDatabase::new(config, "TestPass123!", None)
        .expect("Failed to create database");

    // ========== API Key TTL Tests ==========
    println!("Testing api_key_default_ttl_seconds validation:");

    // Test 1: Valid positive TTL should be accepted
    let result =
        db.update_system_config("api_key_default_ttl_seconds", "3600", Some(1));
    assert!(result.is_ok(), "Valid positive TTL should be accepted");
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(3600));

    // Test 2: Zero TTL (no expiration) should be accepted
    let result =
        db.update_system_config("api_key_default_ttl_seconds", "0", Some(1));
    assert!(
        result.is_ok(),
        "Zero TTL (no expiration) should be accepted"
    );
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(0));

    // Test 3: Negative TTL should be rejected
    let result =
        db.update_system_config("api_key_default_ttl_seconds", "-1", Some(1));
    assert!(result.is_err(), "Negative TTL should be rejected");
    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(msg.contains("must be >= 0"));
    } else {
        panic!("Expected ValidationError for negative TTL");
    }

    // Test 4: Invalid integer should be rejected
    let result = db.update_system_config(
        "api_key_default_ttl_seconds",
        "not_a_number",
        Some(1),
    );
    assert!(result.is_err(), "Invalid integer should be rejected");

    // ========== Max Login Attempts Tests ==========
    println!("Testing max_login_attempts validation:");

    // Valid positive value
    let result = db.update_system_config("max_login_attempts", "5", Some(1));
    assert!(
        result.is_ok(),
        "Valid max_login_attempts should be accepted"
    );
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(5));

    // Zero should be rejected (must be > 0)
    let result = db.update_system_config("max_login_attempts", "0", Some(1));
    assert!(
        result.is_err(),
        "Zero max_login_attempts should be rejected"
    );
    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(msg.contains("must be > 0"));
    } else {
        panic!("Expected ValidationError for zero max_login_attempts");
    }

    // Invalid value
    let result =
        db.update_system_config("max_login_attempts", "invalid", Some(1));
    assert!(
        result.is_err(),
        "Invalid max_login_attempts should be rejected"
    );

    // ========== Lockout Duration Tests ==========
    println!("Testing lockout_duration_seconds validation:");

    // Valid positive value
    let result =
        db.update_system_config("lockout_duration_seconds", "300", Some(1));
    assert!(result.is_ok(), "Valid lockout_duration should be accepted");
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(300));

    // Zero should be rejected (must be > 0)
    let result =
        db.update_system_config("lockout_duration_seconds", "0", Some(1));
    assert!(result.is_err(), "Zero lockout_duration should be rejected");
    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(msg.contains("must be > 0"));
    } else {
        panic!("Expected ValidationError for zero lockout_duration");
    }

    // Negative should be rejected
    let result =
        db.update_system_config("lockout_duration_seconds", "-100", Some(1));
    assert!(
        result.is_err(),
        "Negative lockout_duration should be rejected"
    );

    // ========== Rate Limit Window Tests ==========
    println!("Testing rate_limit_window_seconds validation:");

    // Valid positive value
    let result =
        db.update_system_config("rate_limit_window_seconds", "60", Some(1));
    assert!(result.is_ok(), "Valid rate_limit_window should be accepted");
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(60));

    // Zero should be rejected (must be > 0)
    let result =
        db.update_system_config("rate_limit_window_seconds", "0", Some(1));
    assert!(result.is_err(), "Zero rate_limit_window should be rejected");
    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(msg.contains("must be > 0"));
    } else {
        panic!("Expected ValidationError for zero rate_limit_window");
    }

    // Negative should be rejected
    let result =
        db.update_system_config("rate_limit_window_seconds", "-60", Some(1));
    assert!(
        result.is_err(),
        "Negative rate_limit_window should be rejected"
    );

    // ========== Rate Limit Max Requests Tests ==========
    println!("Testing rate_limit_max_requests validation:");

    // Valid positive value
    let result =
        db.update_system_config("rate_limit_max_requests", "100", Some(1));
    assert!(
        result.is_ok(),
        "Valid rate_limit_max_requests should be accepted"
    );
    assert_eq!(result.unwrap().value, SystemConfigValue::Integer(100));

    // Zero should be rejected (must be > 0)
    let result =
        db.update_system_config("rate_limit_max_requests", "0", Some(1));
    assert!(
        result.is_err(),
        "Zero rate_limit_max_requests should be rejected"
    );
    if let Err(DatabaseError::Validation(msg)) = result {
        assert!(msg.contains("must be > 0"));
    } else {
        panic!("Expected ValidationError for zero rate_limit_max_requests");
    }

    // Invalid value
    let result =
        db.update_system_config("rate_limit_max_requests", "invalid", Some(1));
    assert!(
        result.is_err(),
        "Invalid rate_limit_max_requests should be rejected"
    );

    // ========== Unknown Config Key ==========
    println!("Testing unknown config key:");

    // Unknown keys should fail (key not found), but not due to validation
    let result = db.update_system_config("some_other_config", "-1", Some(1));
    assert!(result.is_err(), "Non-existent key should fail");

    println!("✓ All system config validations work correctly:");
    println!(
        "  - api_key_default_ttl_seconds: >= 0 (allows 0 for no expiration)"
    );
    println!("  - max_login_attempts: > 0");
    println!("  - lockout_duration_seconds: > 0");
    println!("  - rate_limit_window_seconds: > 0");
    println!("  - rate_limit_max_requests: > 0");
}