fraiseql-core 2.12.0

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

#![allow(clippy::panic)] // Reason: test code, panics acceptable
mod audit_tests {
    use chrono::Utc;

    use crate::security::audit::{AuditEntry, AuditError, AuditExportConfig, AuditLevel};

    #[test]
    fn test_audit_entry_integrity_hash() {
        let entry = AuditEntry {
            id:             Some(1),
            timestamp:      Utc::now(),
            level:          AuditLevel::INFO,
            user_id:        123,
            tenant_id:      456,
            operation:      "query".to_string(),
            query:          "{ users { id name } }".to_string(),
            variables:      serde_json::json!({}),
            ip_address:     "192.168.1.1".to_string(),
            user_agent:     "Mozilla/5.0".to_string(),
            error:          None,
            duration_ms:    Some(100),
            previous_hash:  None,
            integrity_hash: None,
        };

        let hash = entry.calculate_hash();
        assert!(!hash.is_empty());
        assert_eq!(hash.len(), 64); // SHA256 hex is 64 chars
    }

    #[test]
    fn test_audit_integrity_verification() {
        let mut entry = AuditEntry {
            id:             Some(1),
            timestamp:      Utc::now(),
            level:          AuditLevel::INFO,
            user_id:        123,
            tenant_id:      456,
            operation:      "query".to_string(),
            query:          "{ users { id name } }".to_string(),
            variables:      serde_json::json!({}),
            ip_address:     "192.168.1.1".to_string(),
            user_agent:     "Mozilla/5.0".to_string(),
            error:          None,
            duration_ms:    Some(100),
            previous_hash:  None,
            integrity_hash: None,
        };

        // Calculate hash and store it
        let calculated_hash = entry.calculate_hash();
        entry.integrity_hash = Some(calculated_hash);

        // Verify should pass
        assert!(entry.verify_integrity());

        // Tamper with data
        entry.user_id = 999;

        // Verify should fail
        assert!(!entry.verify_integrity());
    }

    #[test]
    fn test_audit_hash_chain() {
        let timestamp = Utc::now();

        let mut entry1 = AuditEntry {
            id: Some(1),
            timestamp,
            level: AuditLevel::INFO,
            user_id: 123,
            tenant_id: 456,
            operation: "query".to_string(),
            query: "{ users { id } }".to_string(),
            variables: serde_json::json!({}),
            ip_address: "192.168.1.1".to_string(),
            user_agent: "Mozilla/5.0".to_string(),
            error: None,
            duration_ms: Some(100),
            previous_hash: None,
            integrity_hash: None,
        };

        let hash1 = entry1.calculate_hash();
        entry1.integrity_hash = Some(hash1.clone());

        // Create second entry with chain
        let mut entry2 = AuditEntry {
            id: Some(2),
            timestamp,
            level: AuditLevel::INFO,
            user_id: 123,
            tenant_id: 456,
            operation: "query".to_string(),
            query: "{ posts { id } }".to_string(),
            variables: serde_json::json!({}),
            ip_address: "192.168.1.1".to_string(),
            user_agent: "Mozilla/5.0".to_string(),
            error: None,
            duration_ms: Some(50),
            previous_hash: Some(hash1),
            integrity_hash: None,
        };

        let hash2 = entry2.calculate_hash();
        entry2.integrity_hash = Some(hash2);

        // Both should verify
        assert!(entry1.verify_integrity());
        assert!(entry2.verify_integrity());

        // Breaking the chain should be detected
        entry1.user_id = 999;
        assert!(!entry1.verify_integrity());
    }

    #[test]
    fn test_audit_level_parsing() {
        assert_eq!(AuditLevel::parse("WARN"), AuditLevel::WARN);
        assert_eq!(AuditLevel::parse("ERROR"), AuditLevel::ERROR);
        assert_eq!(AuditLevel::parse("INFO"), AuditLevel::INFO);
        assert_eq!(AuditLevel::parse("UNKNOWN"), AuditLevel::INFO);
    }

    #[test]
    fn test_audit_export_config_deserialization() {
        let json = r#"{
            "syslog": { "address": "syslog.internal", "port": 514, "protocol": "tcp" },
            "webhook": { "url": "https://logs.example.com/ingest" }
        }"#;
        let config: AuditExportConfig =
            serde_json::from_str(json).expect("should deserialize AuditExportConfig");
        assert!(config.syslog.is_some());
        assert!(config.webhook.is_some());

        let syslog = config.syslog.expect("syslog should be Some");
        assert_eq!(syslog.address, "syslog.internal");
        assert_eq!(syslog.port, 514);
        assert_eq!(syslog.protocol, "tcp");

        let webhook = config.webhook.expect("webhook should be Some");
        assert_eq!(webhook.url, "https://logs.example.com/ingest");
        assert_eq!(webhook.batch_size, 100);
        assert_eq!(webhook.flush_interval_secs, 30);
    }

    #[test]
    fn test_audit_export_config_empty() {
        let config: AuditExportConfig =
            serde_json::from_str("{}").expect("should deserialize empty config");
        assert!(config.syslog.is_none());
        assert!(config.webhook.is_none());
    }

    #[test]
    fn test_audit_error_export_variant() {
        let err = AuditError::Export("connection refused".to_string());
        assert!(err.to_string().contains("connection refused"));
    }
}

#[cfg(feature = "audit-syslog")]
mod audit_export_syslog_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::{io::Read, net::UdpSocket};

    use chrono::Utc;
    use parking_lot::Mutex;

    use crate::security::{
        audit::{AuditEntry, AuditExporter, AuditLevel, SyslogExportConfig},
        audit_export_syslog::{SyslogAuditExporter, Transport, escape_sd_value},
    };

    fn test_entry() -> AuditEntry {
        AuditEntry {
            id:             Some(1),
            timestamp:      Utc::now(),
            level:          AuditLevel::INFO,
            user_id:        123,
            tenant_id:      456,
            operation:      "query".to_string(),
            query:          "{ users { id name } }".to_string(),
            variables:      serde_json::json!({}),
            ip_address:     "192.168.1.1".to_string(),
            user_agent:     "Mozilla/5.0".to_string(),
            error:          None,
            duration_ms:    Some(42),
            previous_hash:  None,
            integrity_hash: None,
        }
    }

    #[test]
    fn test_format_message_rfc5424() {
        let exporter = SyslogAuditExporter {
            transport: Mutex::new(Transport::Udp(UdpSocket::bind("0.0.0.0:0").unwrap())),
            hostname:  "test-host".to_string(),
        };

        let msg = exporter.format_message(&test_entry());

        // Priority = authpriv(10) * 8 + severity(6) = 86
        assert!(msg.starts_with("<86>1 "), "should start with priority 86, got: {msg}");
        assert!(msg.contains("test-host"));
        assert!(msg.contains("fraiseql"));
        assert!(msg.contains("AUDIT"));
        assert!(msg.contains(r#"user="123""#));
        assert!(msg.contains(r#"tenant="456""#));
        assert!(msg.contains(r#"operation="query""#));
        assert!(msg.contains(r#"level="INFO""#));
        assert!(msg.contains("{ users { id name } }"));
    }

    #[test]
    fn test_format_message_with_error() {
        let exporter = SyslogAuditExporter {
            transport: Mutex::new(Transport::Udp(UdpSocket::bind("0.0.0.0:0").unwrap())),
            hostname:  "test-host".to_string(),
        };

        let mut entry = test_entry();
        entry.level = AuditLevel::ERROR;
        entry.error = Some("timeout".to_string());

        let msg = exporter.format_message(&entry);

        // Priority = authpriv(10) * 8 + severity(3) = 83
        assert!(msg.starts_with("<83>1 "), "error priority should be 83");
        assert!(msg.contains(r#"error="timeout""#));
        assert!(msg.contains(r#"level="ERROR""#));
    }

    #[test]
    fn test_severity_mapping() {
        assert_eq!(SyslogAuditExporter::severity(AuditLevel::INFO), 6);
        assert_eq!(SyslogAuditExporter::severity(AuditLevel::WARN), 4);
        assert_eq!(SyslogAuditExporter::severity(AuditLevel::ERROR), 3);
    }

    #[test]
    fn test_syslog_udp_export() {
        let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
        let recv_addr = receiver.local_addr().unwrap();
        receiver.set_read_timeout(Some(std::time::Duration::from_secs(1))).unwrap();

        let config = SyslogExportConfig {
            address:  "127.0.0.1".to_string(),
            port:     recv_addr.port(),
            protocol: "udp".to_string(),
        };

        let exporter = SyslogAuditExporter::new(&config).unwrap();
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        rt.block_on(exporter.export(&test_entry())).unwrap();

        let mut buf = [0u8; 4096];
        let n = receiver.recv(&mut buf).unwrap();
        let received = std::str::from_utf8(&buf[..n]).unwrap();

        assert!(received.contains("AUDIT"));
        assert!(received.contains(r#"user="123""#));
    }

    #[test]
    fn test_syslog_tcp_export() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let listen_addr = listener.local_addr().unwrap();

        let config = SyslogExportConfig {
            address:  "127.0.0.1".to_string(),
            port:     listen_addr.port(),
            protocol: "tcp".to_string(),
        };

        let exporter = SyslogAuditExporter::new(&config).unwrap();
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        rt.block_on(exporter.export(&test_entry())).unwrap();

        let (mut conn, _) = listener.accept().unwrap();
        conn.set_read_timeout(Some(std::time::Duration::from_secs(1))).unwrap();

        let mut buf = [0u8; 4096];
        let n = conn.read(&mut buf).unwrap();
        let received = std::str::from_utf8(&buf[..n]).unwrap();

        assert!(received.contains("AUDIT"));
        assert!(received.ends_with('\n'), "TCP syslog should end with newline");
    }

    #[test]
    fn test_escape_sd_value() {
        assert_eq!(escape_sd_value(r#"a"b"#), r#"a\"b"#);
        assert_eq!(escape_sd_value(r"a\b"), r"a\\b");
        assert_eq!(escape_sd_value("a]b"), r"a\]b");
    }

    #[test]
    fn test_long_query_truncated() {
        let exporter = SyslogAuditExporter {
            transport: Mutex::new(Transport::Udp(UdpSocket::bind("0.0.0.0:0").unwrap())),
            hostname:  "test-host".to_string(),
        };

        let mut entry = test_entry();
        entry.query = "x".repeat(500);

        let msg = exporter.format_message(&entry);
        // Query should be truncated to 200 chars + "..."
        assert!(msg.len() < 600, "message should be bounded");
        assert!(msg.contains("..."));
    }
}

#[cfg(feature = "audit-webhook")]
mod audit_export_webhook_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use chrono::Utc;

    use crate::security::{
        audit::{AuditEntry, AuditExporter, AuditLevel, WebhookExportConfig},
        audit_export_webhook::WebhookAuditExporter,
    };

    fn test_entry() -> AuditEntry {
        AuditEntry {
            id:             Some(1),
            timestamp:      Utc::now(),
            level:          AuditLevel::INFO,
            user_id:        123,
            tenant_id:      456,
            operation:      "query".to_string(),
            query:          "{ users { id name } }".to_string(),
            variables:      serde_json::json!({}),
            ip_address:     "192.168.1.1".to_string(),
            user_agent:     "Mozilla/5.0".to_string(),
            error:          None,
            duration_ms:    Some(42),
            previous_hash:  None,
            integrity_hash: None,
        }
    }

    #[test]
    fn test_buffer_accumulates_entries() {
        let config = WebhookExportConfig {
            url:                 "https://example.com/audit".to_string(),
            headers:             std::collections::HashMap::new(),
            batch_size:          10,
            flush_interval_secs: 30,
        };

        let exporter = WebhookAuditExporter::new(&config).unwrap();

        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

        // Add entries below batch_size — should not flush.
        for _ in 0..5 {
            // Export will buffer but not flush (no server, so flush would fail).
            rt.block_on(exporter.export(&test_entry())).unwrap();
        }

        assert_eq!(exporter.buffer.lock().len(), 5);
    }

    #[test]
    fn test_flush_empties_buffer() {
        let config = WebhookExportConfig {
            url:                 "https://example.com/audit".to_string(),
            headers:             std::collections::HashMap::new(),
            batch_size:          100,
            flush_interval_secs: 30,
        };

        let exporter = WebhookAuditExporter::new(&config).unwrap();

        // Manually push entries into buffer.
        {
            let mut buf = exporter.buffer.lock();
            for _ in 0..5 {
                buf.push(test_entry());
            }
        }

        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

        // Flush will fail (no server) but should still drain the buffer.
        let _ = rt.block_on(exporter.flush());

        // Buffer should be empty even though send failed.
        assert_eq!(exporter.buffer.lock().len(), 0);
    }

    #[test]
    fn test_config_defaults() {
        let json = r#"{"url": "https://example.com/audit"}"#;
        let config: WebhookExportConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.batch_size, 100);
        assert_eq!(config.flush_interval_secs, 30);
        assert!(config.headers.is_empty());
    }

    #[test]
    fn test_syslog_config_defaults() {
        use crate::security::audit::SyslogExportConfig;
        let json = r#"{"address": "syslog.internal"}"#;
        let config: SyslogExportConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.port, 514);
        assert_eq!(config.protocol, "udp");
    }

    #[test]
    fn test_export_config_optional_fields() {
        use crate::security::audit::AuditExportConfig;
        let json = "{}";
        let config: AuditExportConfig = serde_json::from_str(json).unwrap();

        assert!(config.syslog.is_none());
        assert!(config.webhook.is_none());
    }
}

mod error_formatter_tests {
    use crate::security::{error_formatter::SanitizationConfig, *};

    // ============================================================================
    // Helper Functions
    // ============================================================================

    fn db_error_msg() -> &'static str {
        "Database error: connection refused to postgresql://user:password@db.example.com:5432/mydb"
    }

    fn sql_error_msg() -> &'static str {
        "SQL Error: SELECT * FROM users WHERE id = 123; failed at db.example.com"
    }

    fn network_error_msg() -> &'static str {
        "Connection failed to 192.168.1.100 (admin@example.com)"
    }

    // ============================================================================
    // Check 1: Detail Level Tests
    // ============================================================================

    #[test]
    fn test_development_shows_full_details() {
        let formatter = ErrorFormatter::development();
        let formatted = formatter.format_error(db_error_msg());
        assert!(formatted.contains("postgresql"));
        assert!(formatted.contains("user:password"));
    }

    #[test]
    fn test_staging_shows_limited_details() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error(db_error_msg());
        // Staging should hide the database URL pattern
        assert!(!formatted.contains("postgresql://"));
        // Specific credentials may still appear but URL pattern is hidden
        let _ = formatted;
    }

    #[test]
    fn test_production_shows_generic_error() {
        let formatter = ErrorFormatter::production();
        let formatted = formatter.format_error(db_error_msg());
        assert!(!formatted.contains("postgresql"));
        assert!(!formatted.contains("password"));
        assert!(formatted.contains("error") || formatted.contains("request"));
    }

    // ============================================================================
    // Check 2: Sanitization Tests
    // ============================================================================

    #[test]
    fn test_database_url_sanitization() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error(db_error_msg());
        // The URL pattern should be replaced
        assert!(!formatted.contains("postgresql://"));
        // Verify something was replaced
        assert!(formatted.contains("**hidden**") || !formatted.contains("postgresql://"));
    }

    #[test]
    fn test_sql_sanitization() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error(sql_error_msg());
        assert!(!formatted.contains("SELECT"));
    }

    #[test]
    fn test_ip_sanitization() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error(network_error_msg());
        assert!(!formatted.contains("192.168"));
    }

    #[test]
    fn test_email_sanitization() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error(network_error_msg());
        assert!(!formatted.contains("admin@example"));
    }

    // ============================================================================
    // Check 3: SecurityError Formatting Tests
    // ============================================================================

    #[test]
    fn test_security_error_development() {
        let formatter = ErrorFormatter::development();
        let error = SecurityError::AuthRequired;
        let formatted = formatter.format_security_error(&error);
        assert!(formatted.contains("Authentication"));
    }

    #[test]
    fn test_security_error_production() {
        let formatter = ErrorFormatter::production();
        let error = SecurityError::AuthRequired;
        let formatted = formatter.format_security_error(&error);
        assert!(!formatted.is_empty());
        assert!(formatted.len() < 100); // Generic, short message
    }

    #[test]
    fn test_token_expired_error_production() {
        let formatter = ErrorFormatter::production();
        let error = SecurityError::TokenExpired {
            expired_at: chrono::Utc::now(),
        };
        let formatted = formatter.format_security_error(&error);
        assert!(!formatted.contains("expired_at"));
        assert!(formatted.contains("Invalid") || formatted.contains("Authentication"));
    }

    #[test]
    fn test_query_too_deep_error_production() {
        let formatter = ErrorFormatter::production();
        let error = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };
        let formatted = formatter.format_security_error(&error);
        assert!(!formatted.contains("20"));
        assert!(!formatted.contains("10"));
    }

    // ============================================================================
    // Configuration Tests
    // ============================================================================

    #[test]
    fn test_detail_level_display() {
        assert_eq!(DetailLevel::Development.to_string(), "Development");
        assert_eq!(DetailLevel::Staging.to_string(), "Staging");
        assert_eq!(DetailLevel::Production.to_string(), "Production");
    }

    #[test]
    fn test_sanitization_config_permissive() {
        let config = SanitizationConfig::permissive();
        assert!(!config.hide_database_urls);
        assert!(!config.hide_sql);
    }

    #[test]
    fn test_sanitization_config_standard() {
        let config = SanitizationConfig::standard();
        assert!(config.hide_database_urls);
        assert!(config.hide_sql);
        assert!(!config.hide_paths);
    }

    #[test]
    fn test_sanitization_config_strict() {
        let config = SanitizationConfig::strict();
        assert!(config.hide_database_urls);
        assert!(config.hide_sql);
        assert!(config.hide_paths);
    }

    #[test]
    fn test_formatter_helpers() {
        let dev = ErrorFormatter::development();
        assert_eq!(dev.detail_level(), DetailLevel::Development);

        let prod = ErrorFormatter::production();
        assert_eq!(prod.detail_level(), DetailLevel::Production);
    }

    // ============================================================================
    // Edge Cases
    // ============================================================================

    #[test]
    fn test_empty_error_message() {
        let formatter = ErrorFormatter::staging();
        let formatted = formatter.format_error("");
        assert!(formatted.is_empty() || !formatted.is_empty()); // Either is fine
    }

    #[test]
    fn test_multiple_sensitive_elements() {
        let formatter = ErrorFormatter::staging();
        let msg = "Failed to connect to postgresql://admin@192.168.1.1 with email user@example.com";
        let formatted = formatter.format_error(msg);

        assert!(!formatted.contains("postgresql"));
        assert!(!formatted.contains("192.168"));
        assert!(!formatted.contains("user@example"));
    }

    #[test]
    fn test_security_error_categorization() {
        let formatter = ErrorFormatter::production();

        // Auth errors
        let auth_error = SecurityError::AuthRequired;
        let formatted = formatter.format_security_error(&auth_error);
        assert!(formatted.contains("Authentication"));

        // Introspection error
        let intro_error = SecurityError::IntrospectionDisabled {
            detail: "test".to_string(),
        };
        let formatted = formatter.format_security_error(&intro_error);
        assert!(formatted.contains("introspection"));
    }

    #[test]
    fn test_custom_sanitization_config() {
        let config = SanitizationConfig {
            hide_database_urls: false,
            hide_sql:           false,
            hide_paths:         true,
            hide_ips:           false,
            hide_emails:        false,
            hide_credentials:   false,
        };

        let formatter = ErrorFormatter::with_config(DetailLevel::Staging, config);
        let msg = "Error at /home/user/project: connection to 192.168.1.1 failed";
        let formatted = formatter.format_error(msg);

        // Paths should be hidden when that config is true
        // IPs should not be hidden when that config is false
        assert!(formatted.contains("192.168"));
        // Paths may be redacted or contain the redacted version
        let _ = formatted;
    }

    #[test]
    fn test_long_error_truncation() {
        let formatter = ErrorFormatter::staging();
        let long_msg = "a".repeat(200);
        let formatted = formatter.format_error(&long_msg);

        // Should be truncated in some cases
        assert!(formatted.len() <= 200 + 10); // Allow some buffer
    }
}

mod errors_tests {
    use crate::security::*;

    #[test]
    fn test_rate_limit_error_display() {
        let err = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };

        assert!(err.to_string().contains("Rate limit exceeded"));
        assert!(err.to_string().contains("100"));
        assert!(err.to_string().contains("60"));
    }

    #[test]
    fn test_query_too_deep_display() {
        let err = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };

        assert!(err.to_string().contains("Query too deep"));
        assert!(err.to_string().contains("20"));
        assert!(err.to_string().contains("10"));
    }

    #[test]
    fn test_query_too_complex_display() {
        let err = SecurityError::QueryTooComplex {
            complexity:     500,
            max_complexity: 100,
        };

        assert!(err.to_string().contains("Query too complex"));
        assert!(err.to_string().contains("500"));
        assert!(err.to_string().contains("100"));
    }

    #[test]
    fn test_query_too_large_display() {
        let err = SecurityError::QueryTooLarge {
            size:     100_000,
            max_size: 10_000,
        };

        assert!(err.to_string().contains("Query too large"));
        assert!(err.to_string().contains("100000"));
        assert!(err.to_string().contains("10000"));
    }

    #[test]
    fn test_cors_errors() {
        let origin_err = SecurityError::OriginNotAllowed("https://evil.com".to_string());
        assert!(origin_err.to_string().contains("CORS origin"));

        let method_err = SecurityError::MethodNotAllowed("DELETE".to_string());
        assert!(method_err.to_string().contains("CORS method"));

        let header_err = SecurityError::HeaderNotAllowed("X-Custom".to_string());
        assert!(header_err.to_string().contains("CORS header"));
    }

    #[test]
    fn test_csrf_errors() {
        let invalid = SecurityError::InvalidCSRFToken("expired".to_string());
        assert!(invalid.to_string().contains("Invalid CSRF token"));

        let mismatch = SecurityError::CSRFSessionMismatch;
        assert!(mismatch.to_string().contains("session mismatch"));
    }

    #[test]
    fn test_audit_error() {
        let err = SecurityError::AuditLogFailure("connection timeout".to_string());
        assert!(err.to_string().contains("Audit logging failed"));
    }

    #[test]
    fn test_config_error() {
        let err = SecurityError::SecurityConfigError("missing config key".to_string());
        assert!(err.to_string().contains("Security configuration error"));
    }

    #[test]
    fn test_error_equality() {
        let err1 = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };
        let err2 = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::QueryTooDeep {
            depth:     30,
            max_depth: 10,
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_rate_limit_equality() {
        let err1 = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };
        let err2 = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };
        assert_eq!(err1, err2);
    }

    // ============================================================================
    // TLS Error Tests
    // ============================================================================

    #[test]
    fn test_tls_required_error_display() {
        let err = SecurityError::TlsRequired {
            detail: "HTTPS required".to_string(),
        };

        assert!(err.to_string().contains("TLS/HTTPS required"));
        assert!(err.to_string().contains("HTTPS required"));
    }

    #[test]
    fn test_tls_version_too_old_error_display() {
        use crate::security::tls_enforcer::TlsVersion;

        let err = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };

        assert!(err.to_string().contains("TLS version too old"));
        assert!(err.to_string().contains("1.2"));
        assert!(err.to_string().contains("1.3"));
    }

    #[test]
    fn test_mtls_required_error_display() {
        let err = SecurityError::MtlsRequired {
            detail: "Client certificate required".to_string(),
        };

        assert!(err.to_string().contains("Mutual TLS required"));
        assert!(err.to_string().contains("Client certificate"));
    }

    #[test]
    fn test_invalid_client_cert_error_display() {
        let err = SecurityError::InvalidClientCert {
            detail: "Certificate validation failed".to_string(),
        };

        assert!(err.to_string().contains("Invalid client certificate"));
        assert!(err.to_string().contains("validation failed"));
    }

    #[test]
    fn test_auth_required_error_display() {
        let err = SecurityError::AuthRequired;
        assert!(err.to_string().contains("Authentication required"));
    }

    #[test]
    fn test_invalid_token_error_display() {
        let err = SecurityError::InvalidToken;
        assert!(err.to_string().contains("Invalid authentication token"));
    }

    #[test]
    fn test_token_expired_error_display() {
        use chrono::{Duration, Utc};

        let expired_at = Utc::now() - Duration::hours(1);
        let err = SecurityError::TokenExpired { expired_at };

        assert!(err.to_string().contains("Token expired"));
    }

    #[test]
    fn test_token_missing_claim_error_display() {
        let err = SecurityError::TokenMissingClaim {
            claim: "sub".to_string(),
        };

        assert!(err.to_string().contains("Token missing required claim"));
        assert!(err.to_string().contains("sub"));
    }

    #[test]
    fn test_invalid_token_algorithm_error_display() {
        let err = SecurityError::InvalidTokenAlgorithm {
            algorithm: "HS256".to_string(),
        };

        assert!(err.to_string().contains("Invalid token algorithm"));
        assert!(err.to_string().contains("HS256"));
    }

    #[test]
    fn test_introspection_disabled_error_display() {
        let err = SecurityError::IntrospectionDisabled {
            detail: "Introspection not allowed in production".to_string(),
        };

        assert!(err.to_string().contains("Introspection disabled"));
        assert!(err.to_string().contains("production"));
    }

    // ============================================================================
    // TLS Error Equality Tests
    // ============================================================================

    #[test]
    fn test_tls_required_equality() {
        let err1 = SecurityError::TlsRequired {
            detail: "test".to_string(),
        };
        let err2 = SecurityError::TlsRequired {
            detail: "test".to_string(),
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::TlsRequired {
            detail: "different".to_string(),
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_tls_version_too_old_equality() {
        use crate::security::tls_enforcer::TlsVersion;

        let err1 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };
        let err2 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_1,
            required: TlsVersion::V1_3,
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_mtls_required_equality() {
        let err1 = SecurityError::MtlsRequired {
            detail: "test".to_string(),
        };
        let err2 = SecurityError::MtlsRequired {
            detail: "test".to_string(),
        };
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_invalid_token_equality() {
        assert_eq!(SecurityError::InvalidToken, SecurityError::InvalidToken);
    }

    #[test]
    fn test_auth_required_equality() {
        assert_eq!(SecurityError::AuthRequired, SecurityError::AuthRequired);
    }
}

mod field_filter_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
    use crate::security::*;

    // ========================================================================
    // Test Suite 1: Basic Configuration
    // ========================================================================

    #[test]
    fn test_empty_config_allows_all() {
        let filter = FieldFilter::permissive();
        let scopes: Vec<String> = vec![];

        filter
            .can_access("User", "name", &scopes)
            .unwrap_or_else(|e| panic!("expected access to User.name: {e}"));
        filter
            .can_access("User", "email", &scopes)
            .unwrap_or_else(|e| panic!("expected access to User.email: {e}"));
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected access to User.salary: {e}"));
    }

    #[test]
    fn test_protect_single_field() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        // Unprotected fields are allowed
        let no_scopes: Vec<String> = vec![];
        filter
            .can_access("User", "name", &no_scopes)
            .unwrap_or_else(|e| panic!("expected access to User.name: {e}"));
        filter
            .can_access("User", "email", &no_scopes)
            .unwrap_or_else(|e| panic!("expected access to User.email: {e}"));

        // Protected field is denied without scope
        let result = filter.can_access("User", "salary", &no_scopes);
        assert_eq!(result.unwrap_err(), FieldAccessError::new("User", "salary"));
    }

    #[test]
    fn test_protect_multiple_fields() {
        let config = FieldFilterConfig::new().protect_fields("User", &["salary", "ssn", "bonus"]);
        let filter = FieldFilter::new(config);

        let no_scopes: Vec<String> = vec![];
        filter
            .can_access("User", "name", &no_scopes)
            .unwrap_or_else(|e| panic!("expected access to User.name: {e}"));
        assert_eq!(
            filter.can_access("User", "salary", &no_scopes).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
        assert_eq!(
            filter.can_access("User", "ssn", &no_scopes).unwrap_err(),
            FieldAccessError::new("User", "ssn")
        );
        assert_eq!(
            filter.can_access("User", "bonus", &no_scopes).unwrap_err(),
            FieldAccessError::new("User", "bonus")
        );
    }

    #[test]
    fn test_protect_entire_type() {
        let config = FieldFilterConfig::new().protect_type("Secret");
        let filter = FieldFilter::new(config);

        let no_scopes: Vec<String> = vec![];
        // All fields on Secret type require authorization
        assert_eq!(
            filter.can_access("Secret", "anything", &no_scopes).unwrap_err(),
            FieldAccessError::new("Secret", "anything")
        );
        assert_eq!(
            filter.can_access("Secret", "data", &no_scopes).unwrap_err(),
            FieldAccessError::new("Secret", "data")
        );

        // Other types are fine
        filter
            .can_access("User", "name", &no_scopes)
            .unwrap_or_else(|e| panic!("expected access to User.name: {e}"));
    }

    // ========================================================================
    // Test Suite 2: Scope Matching
    // ========================================================================

    #[test]
    fn test_exact_scope_match() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        let scopes = vec!["read:User.salary".to_string()];
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected exact scope match: {e}"));
    }

    #[test]
    fn test_type_wildcard_scope() {
        let config = FieldFilterConfig::new()
            .protect_field("User", "salary")
            .protect_field("User", "ssn");
        let filter = FieldFilter::new(config);

        let scopes = vec!["read:User.*".to_string()];
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected type wildcard to grant access to salary: {e}"));
        filter
            .can_access("User", "ssn", &scopes)
            .unwrap_or_else(|e| panic!("expected type wildcard to grant access to ssn: {e}"));
    }

    #[test]
    fn test_global_wildcard_scope() {
        let config = FieldFilterConfig::new()
            .protect_field("User", "salary")
            .protect_field("Employee", "compensation");
        let filter = FieldFilter::new(config);

        let scopes = vec!["read:*".to_string()];
        filter.can_access("User", "salary", &scopes).unwrap_or_else(|e| {
            panic!("expected global wildcard to grant access to User.salary: {e}")
        });
        filter.can_access("Employee", "compensation", &scopes).unwrap_or_else(|e| {
            panic!("expected global wildcard to grant access to Employee.compensation: {e}")
        });
    }

    #[test]
    fn test_admin_scope_bypasses_all() {
        let config = FieldFilterConfig::new()
            .protect_field("User", "salary")
            .protect_field("User", "ssn")
            .protect_type("Secret");
        let filter = FieldFilter::new(config);

        let scopes = vec!["admin".to_string()];
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected admin to bypass User.salary: {e}"));
        filter
            .can_access("User", "ssn", &scopes)
            .unwrap_or_else(|e| panic!("expected admin to bypass User.ssn: {e}"));
        filter
            .can_access("Secret", "data", &scopes)
            .unwrap_or_else(|e| panic!("expected admin to bypass Secret.data: {e}"));
    }

    #[test]
    fn test_custom_admin_scope() {
        let config = FieldFilterConfig::new()
            .protect_field("User", "salary")
            .add_admin_scope("superuser");
        let filter = FieldFilter::new(config);

        let scopes = vec!["superuser".to_string()];
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected custom admin scope to bypass: {e}"));
    }

    #[test]
    fn test_wrong_scope_denied() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        // Wrong type
        let scopes = vec!["read:Employee.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &scopes).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        // Wrong field
        let scopes = vec!["read:User.name".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &scopes).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        // Wrong action (write instead of read)
        let scopes = vec!["write:User.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &scopes).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
    }

    // ========================================================================
    // Test Suite 3: Explicit Scope Requirements
    // ========================================================================

    #[test]
    fn test_explicit_scope_requirement() {
        let config = FieldFilterConfig::new().protect_field("User", "salary").require_scope(
            "User",
            "salary",
            "hr:view_compensation",
        );
        let filter = FieldFilter::new(config);

        // Default pattern doesn't work
        let wrong_scope = vec!["read:User.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &wrong_scope).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        // Explicit scope works
        let right_scope = vec!["hr:view_compensation".to_string()];
        filter
            .can_access("User", "salary", &right_scope)
            .unwrap_or_else(|e| panic!("expected explicit scope to grant access: {e}"));
    }

    #[test]
    fn test_admin_still_bypasses_explicit() {
        let config = FieldFilterConfig::new().protect_field("User", "salary").require_scope(
            "User",
            "salary",
            "hr:view_compensation",
        );
        let filter = FieldFilter::new(config);

        let admin_scope = vec!["admin".to_string()];
        filter
            .can_access("User", "salary", &admin_scope)
            .unwrap_or_else(|e| panic!("expected admin to bypass explicit scope: {e}"));
    }

    // ========================================================================
    // Test Suite 4: Error Messages
    // ========================================================================

    #[test]
    fn test_error_contains_field_info() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        let no_scopes: Vec<String> = vec![];
        let err = filter.can_access("User", "salary", &no_scopes).unwrap_err();

        assert_eq!(err.type_name, "User");
        assert_eq!(err.field_name, "salary");
        assert!(err.message.contains("salary"));
        assert!(err.message.contains("User"));
    }

    #[test]
    fn test_error_display() {
        let err = FieldAccessError::new("User", "salary");
        let display = err.to_string();

        assert!(display.contains("Access denied"));
        assert!(display.contains("salary"));
        assert!(display.contains("User"));
    }

    // ========================================================================
    // Test Suite 5: Batch Validation
    // ========================================================================

    #[test]
    fn test_validate_multiple_fields() {
        let config = FieldFilterConfig::new()
            .protect_field("User", "salary")
            .protect_field("User", "ssn");
        let filter = FieldFilter::new(config);

        let fields = ["name", "email", "salary", "ssn"];
        let no_scopes: Vec<String> = vec![];

        let errors = filter.validate_fields("User", &fields, &no_scopes);
        assert_eq!(errors.len(), 2);

        let error_fields: Vec<&str> = errors.iter().map(|e| e.field_name.as_str()).collect();
        assert!(error_fields.contains(&"salary"));
        assert!(error_fields.contains(&"ssn"));
    }

    #[test]
    fn test_validate_all_allowed() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        let fields = ["name", "email", "salary"];
        let scopes = vec!["read:User.salary".to_string()];

        let errors = filter.validate_fields("User", &fields, &scopes);
        assert!(errors.is_empty(), "expected no validation errors, got: {errors:?}");
    }

    // ========================================================================
    // Test Suite 6: Builder Pattern
    // ========================================================================

    #[test]
    fn test_builder_basic() {
        let mut builder = FieldFilterBuilder::new();
        builder.add_protected_field("User", "salary");
        builder.add_protected_field("User", "ssn");

        let filter = builder.build();
        let no_scopes: Vec<String> = vec![];

        assert_eq!(
            filter.can_access("User", "salary", &no_scopes).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
        assert_eq!(
            filter.can_access("User", "ssn", &no_scopes).unwrap_err(),
            FieldAccessError::new("User", "ssn")
        );
        filter
            .can_access("User", "name", &no_scopes)
            .unwrap_or_else(|e| panic!("expected access to unprotected User.name: {e}"));
    }

    #[test]
    fn test_builder_with_explicit_scopes() {
        let mut builder = FieldFilterBuilder::new();
        builder.add_scope_requirement("User", "salary", "hr:compensation");

        let filter = builder.build();

        let wrong = vec!["read:User.salary".to_string()];
        let right = vec!["hr:compensation".to_string()];

        assert_eq!(
            filter.can_access("User", "salary", &wrong).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
        filter
            .can_access("User", "salary", &right)
            .unwrap_or_else(|e| panic!("expected explicit scope to grant access: {e}"));
    }

    #[test]
    fn test_builder_custom_admin_scopes() {
        let mut builder = FieldFilterBuilder::new();
        builder.add_protected_field("User", "salary");
        builder.set_admin_scopes(vec!["root".to_string(), "superadmin".to_string()]);

        let filter = builder.build();

        // Default admin scope no longer works
        let admin = vec!["admin".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &admin).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        // Custom admin scopes work
        let root = vec!["root".to_string()];
        filter
            .can_access("User", "salary", &root)
            .unwrap_or_else(|e| panic!("expected root admin scope to bypass: {e}"));

        let superadmin = vec!["superadmin".to_string()];
        filter
            .can_access("User", "salary", &superadmin)
            .unwrap_or_else(|e| panic!("expected superadmin scope to bypass: {e}"));
    }

    // ========================================================================
    // Test Suite 7: Config Inspection
    // ========================================================================

    #[test]
    fn test_is_protected() {
        let config =
            FieldFilterConfig::new().protect_field("User", "salary").protect_type("Secret");

        assert!(config.is_protected("User", "salary"));
        assert!(!config.is_protected("User", "name"));
        assert!(config.is_protected("Secret", "anything"));
        assert!(!config.is_protected("Public", "data"));
    }

    #[test]
    fn test_config_default_action() {
        let config = FieldFilterConfig::new()
            .with_default_action("view")
            .protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        // "read" action doesn't work
        let read_scope = vec!["read:User.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &read_scope).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        // "view" action works
        let view_scope = vec!["view:User.salary".to_string()];
        filter
            .can_access("User", "salary", &view_scope)
            .unwrap_or_else(|e| panic!("expected view action to grant access: {e}"));
    }

    // ========================================================================
    // Test Suite 8: Edge Cases
    // ========================================================================

    #[test]
    fn test_empty_scopes() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        let empty: Vec<String> = vec![];
        assert_eq!(
            filter.can_access("User", "salary", &empty).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
    }

    #[test]
    fn test_multiple_scopes_one_match() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        let scopes = vec![
            "read:Product.*".to_string(),
            "write:Order.status".to_string(),
            "read:User.salary".to_string(), // This one matches
            "other:scope".to_string(),
        ];
        filter
            .can_access("User", "salary", &scopes)
            .unwrap_or_else(|e| panic!("expected one matching scope to suffice: {e}"));
    }

    #[test]
    fn test_case_sensitive_scopes() {
        let config = FieldFilterConfig::new().protect_field("User", "salary");
        let filter = FieldFilter::new(config);

        // Scopes are case-sensitive
        let wrong_case = vec!["READ:User.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &wrong_case).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );

        let wrong_type_case = vec!["read:user.salary".to_string()];
        assert_eq!(
            filter.can_access("User", "salary", &wrong_type_case).unwrap_err(),
            FieldAccessError::new("User", "salary")
        );
    }

    #[test]
    fn test_special_characters_in_names() {
        let config =
            FieldFilterConfig::new().protect_field("UserProfile", "social_security_number");
        let filter = FieldFilter::new(config);

        let scopes = vec!["read:UserProfile.social_security_number".to_string()];
        filter
            .can_access("UserProfile", "social_security_number", &scopes)
            .unwrap_or_else(|e| panic!("expected access with special characters in names: {e}"));
    }
}

mod field_masking_tests {
    use crate::security::*;

    // ========================================================================
    // Test Suite 1: Field Sensitivity Detection - Public Fields
    // ========================================================================

    #[test]
    fn test_id_is_public() {
        assert_eq!(FieldMasker::detect_sensitivity("id"), FieldSensitivity::Public);
    }

    #[test]
    fn test_name_is_public() {
        assert_eq!(FieldMasker::detect_sensitivity("name"), FieldSensitivity::Public);
    }

    #[test]
    fn test_title_is_public() {
        assert_eq!(FieldMasker::detect_sensitivity("title"), FieldSensitivity::Public);
    }

    #[test]
    fn test_description_is_public() {
        assert_eq!(FieldMasker::detect_sensitivity("description"), FieldSensitivity::Public);
    }

    #[test]
    fn test_created_at_is_public() {
        assert_eq!(FieldMasker::detect_sensitivity("created_at"), FieldSensitivity::Public);
    }

    // ========================================================================
    // Test Suite 2: Field Sensitivity Detection - Sensitive Fields
    // ========================================================================

    #[test]
    fn test_email_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("email"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_email_address_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("email_address"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_user_email_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("user_email"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_phone_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("phone"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_phone_number_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("phone_number"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_mobile_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("mobile"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_mobile_phone_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("mobile_phone"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_ip_address_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("ip_address"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_mac_address_is_sensitive() {
        assert_eq!(FieldMasker::detect_sensitivity("mac_address"), FieldSensitivity::Sensitive);
    }

    // ========================================================================
    // Test Suite 3: Field Sensitivity Detection - PII Fields
    // ========================================================================

    #[test]
    fn test_ssn_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("ssn"), FieldSensitivity::PII);
    }

    #[test]
    fn test_social_security_is_pii() {
        assert_eq!(
            FieldMasker::detect_sensitivity("social_security_number"),
            FieldSensitivity::PII
        );
    }

    #[test]
    fn test_credit_card_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("credit_card"), FieldSensitivity::PII);
    }

    #[test]
    fn test_card_number_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("card_number"), FieldSensitivity::PII);
    }

    #[test]
    fn test_cvv_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("cvv"), FieldSensitivity::PII);
    }

    #[test]
    fn test_cvc_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("cvc"), FieldSensitivity::PII);
    }

    #[test]
    fn test_bank_account_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("bank_account"), FieldSensitivity::PII);
    }

    #[test]
    fn test_pin_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("pin"), FieldSensitivity::PII);
    }

    #[test]
    fn test_driver_license_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("driver_license"), FieldSensitivity::PII);
    }

    #[test]
    fn test_passport_is_pii() {
        assert_eq!(FieldMasker::detect_sensitivity("passport"), FieldSensitivity::PII);
    }

    // ========================================================================
    // Test Suite 4: Field Sensitivity Detection - Secret Fields
    // ========================================================================

    #[test]
    fn test_password_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("password"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_password_hash_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("password_hash"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_secret_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("secret"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_secret_key_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("secret_key"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_token_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("token"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_refresh_token_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("refresh_token"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_api_key_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("api_key"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_auth_token_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("auth_token"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_jwt_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("jwt"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_jwt_prefixed_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("jwt_token"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_id_jwt_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("id_jwt"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_nonce_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("nonce"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_nonce_value_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("nonce_value"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_bearer_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("bearer"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_client_secret_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("client_secret"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_oauth_client_secret_is_secret() {
        assert_eq!(
            FieldMasker::detect_sensitivity("oauth_client_secret"),
            FieldSensitivity::Secret
        );
    }

    #[test]
    fn test_hash_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("hash"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_signature_is_secret() {
        assert_eq!(FieldMasker::detect_sensitivity("signature"), FieldSensitivity::Secret);
    }

    // ========================================================================
    // Test Suite 5: Case Insensitivity
    // ========================================================================

    #[test]
    fn test_case_insensitive_email() {
        assert_eq!(FieldMasker::detect_sensitivity("EMAIL"), FieldSensitivity::Sensitive);
    }

    #[test]
    fn test_case_insensitive_password() {
        assert_eq!(FieldMasker::detect_sensitivity("PASSWORD"), FieldSensitivity::Secret);
    }

    #[test]
    fn test_mixed_case_ssn() {
        assert_eq!(FieldMasker::detect_sensitivity("SSN"), FieldSensitivity::PII);
    }

    // ========================================================================
    // Test Suite 6: Value Masking - Public
    // ========================================================================

    #[test]
    fn test_public_value_unmasked() {
        let result = FieldMasker::mask_value("value", FieldSensitivity::Public);
        assert_eq!(result, "value");
    }

    #[test]
    fn test_public_empty_string_unmasked() {
        let result = FieldMasker::mask_value("", FieldSensitivity::Public);
        assert_eq!(result, "");
    }

    // ========================================================================
    // Test Suite 7: Value Masking - Sensitive
    // ========================================================================

    #[test]
    fn test_sensitive_email_masked() {
        let result = FieldMasker::mask_value("user@example.com", FieldSensitivity::Sensitive);
        assert_eq!(result, "u***");
    }

    #[test]
    fn test_sensitive_phone_masked() {
        let result = FieldMasker::mask_value("555-1234", FieldSensitivity::Sensitive);
        assert_eq!(result, "5***");
    }

    #[test]
    fn test_sensitive_single_char_masked() {
        let result = FieldMasker::mask_value("a", FieldSensitivity::Sensitive);
        assert_eq!(result, "a***");
    }

    #[test]
    fn test_sensitive_empty_masked() {
        let result = FieldMasker::mask_value("", FieldSensitivity::Sensitive);
        assert_eq!(result, "***");
    }

    // ========================================================================
    // Test Suite 8: Value Masking - PII
    // ========================================================================

    #[test]
    fn test_pii_ssn_masked() {
        let result = FieldMasker::mask_value("123-45-6789", FieldSensitivity::PII);
        assert_eq!(result, "[PII]");
    }

    #[test]
    fn test_pii_credit_card_masked() {
        let result = FieldMasker::mask_value("4111-1111-1111-1111", FieldSensitivity::PII);
        assert_eq!(result, "[PII]");
    }

    #[test]
    fn test_pii_empty_masked() {
        let result = FieldMasker::mask_value("", FieldSensitivity::PII);
        assert_eq!(result, "[PII]");
    }

    // ========================================================================
    // Test Suite 9: Value Masking - Secret
    // ========================================================================

    #[test]
    fn test_secret_password_masked() {
        let result = FieldMasker::mask_value("mypassword123", FieldSensitivity::Secret);
        assert_eq!(result, "****");
    }

    #[test]
    fn test_secret_token_masked() {
        let result = FieldMasker::mask_value("token_abc123xyz", FieldSensitivity::Secret);
        assert_eq!(result, "****");
    }

    #[test]
    fn test_secret_empty_masked() {
        let result = FieldMasker::mask_value("", FieldSensitivity::Secret);
        assert_eq!(result, "****");
    }

    #[test]
    fn test_secret_any_value_masked() {
        let result = FieldMasker::mask_value("anything", FieldSensitivity::Secret);
        assert_eq!(result, "****");
    }

    // ========================================================================
    // Test Suite 10: Profile-Based Masking Decision
    // ========================================================================

    #[test]
    fn test_standard_profile_no_masking() {
        let standard = SecurityProfile::standard();
        assert!(!FieldMasker::should_mask(FieldSensitivity::Public, &standard));
        assert!(!FieldMasker::should_mask(FieldSensitivity::Sensitive, &standard));
        assert!(!FieldMasker::should_mask(FieldSensitivity::PII, &standard));
        assert!(!FieldMasker::should_mask(FieldSensitivity::Secret, &standard));
    }

    #[test]
    fn test_regulated_profile_public_no_masking() {
        let regulated = SecurityProfile::regulated();
        assert!(!FieldMasker::should_mask(FieldSensitivity::Public, &regulated));
    }

    #[test]
    fn test_regulated_profile_sensitive_masked() {
        let regulated = SecurityProfile::regulated();
        assert!(FieldMasker::should_mask(FieldSensitivity::Sensitive, &regulated));
    }

    #[test]
    fn test_regulated_profile_pii_masked() {
        let regulated = SecurityProfile::regulated();
        assert!(FieldMasker::should_mask(FieldSensitivity::PII, &regulated));
    }

    #[test]
    fn test_regulated_profile_secret_masked() {
        let regulated = SecurityProfile::regulated();
        assert!(FieldMasker::should_mask(FieldSensitivity::Secret, &regulated));
    }

    // ========================================================================
    // Test Suite 11: Edge Cases
    // ========================================================================

    #[test]
    fn test_very_long_email_masked() {
        let long_email = "a".repeat(1000) + "@example.com";
        let result = FieldMasker::mask_value(&long_email, FieldSensitivity::Sensitive);
        assert_eq!(result, "a***");
        assert!(result.len() < long_email.len());
    }

    #[test]
    fn test_unicode_email_masked() {
        let result = FieldMasker::mask_value("émail@example.com", FieldSensitivity::Sensitive);
        assert_eq!(result, "é***");
    }

    #[test]
    fn test_sensitivity_display() {
        assert_eq!(FieldSensitivity::Public.to_string(), "public");
        assert_eq!(FieldSensitivity::Sensitive.to_string(), "sensitive");
        assert_eq!(FieldSensitivity::PII.to_string(), "pii");
        assert_eq!(FieldSensitivity::Secret.to_string(), "secret");
    }
}

mod headers_tests {
    use crate::security::*;

    #[test]
    fn test_default_security_headers() {
        let headers = SecurityHeaders::default();
        assert!(headers.has("X-XSS-Protection"));
        assert!(headers.has("X-Content-Type-Options"));
        assert!(headers.has("X-Frame-Options"));
        assert!(headers.has("Referrer-Policy"));
        assert!(headers.has("Permissions-Policy"));
    }

    #[test]
    fn test_production_security_headers() {
        let headers = SecurityHeaders::production();
        assert!(headers.has("Content-Security-Policy"));
        assert!(headers.has("Strict-Transport-Security"));
        assert!(headers.has("X-XSS-Protection")); // Should inherit from default
    }

    #[test]
    fn test_custom_header_operations() {
        let mut headers = SecurityHeaders::default();

        // Add custom header
        headers.add("X-Custom-Header".to_string(), "custom-value".to_string());
        assert_eq!(headers.get("X-Custom-Header"), Some(&"custom-value".to_string()));

        // Remove header
        headers.remove("X-Custom-Header");
        assert!(!headers.has("X-Custom-Header"));
    }

    #[test]
    fn test_header_merge() {
        let mut headers1 = SecurityHeaders::default();
        let mut headers2 = SecurityHeaders::default();

        headers2.add("X-Custom".to_string(), "value".to_string());
        headers1.merge(&headers2);

        assert!(headers1.has("X-Custom"));
        assert_eq!(headers1.get("X-Custom"), Some(&"value".to_string()));
    }
}

mod introspection_enforcer_tests {
    use crate::security::{introspection_enforcer::IntrospectionConfig, *};

    // ============================================================================
    // Helper Functions
    // ============================================================================

    fn introspection_schema_query() -> &'static str {
        "{ __schema { types { name } } }"
    }

    fn introspection_type_query() -> &'static str {
        "{ __type(name: \"User\") { name fields { name } } }"
    }

    fn normal_query() -> &'static str {
        "{ user { id name email } }"
    }

    // ============================================================================
    // Check 1: Introspection Detection Tests
    // ============================================================================

    #[test]
    fn test_detect_schema_introspection() {
        let enforcer = IntrospectionEnforcer::allowed();
        let is_introspection = enforcer.is_introspection_query(introspection_schema_query());
        assert!(is_introspection);
    }

    #[test]
    fn test_detect_type_introspection() {
        let enforcer = IntrospectionEnforcer::allowed();
        let is_introspection = enforcer.is_introspection_query(introspection_type_query());
        assert!(is_introspection);
    }

    #[test]
    fn test_normal_query_not_introspection() {
        let enforcer = IntrospectionEnforcer::allowed();
        let is_introspection = enforcer.is_introspection_query(normal_query());
        assert!(!is_introspection);
    }

    #[test]
    fn test_detection_is_case_sensitive() {
        // GraphQL is case-sensitive: `__SCHEMA` is an ordinary (invalid) field
        // name, not the `__schema` meta-field, so it is not introspection.
        let enforcer = IntrospectionEnforcer::allowed();
        let uppercase_query = "{ __SCHEMA { types { name } } }";
        let is_introspection = enforcer.is_introspection_query(uppercase_query);
        assert!(!is_introspection);
    }

    // ============================================================================
    // Check 2: Authentication Check Tests
    // ============================================================================

    #[test]
    fn test_internal_only_allows_authenticated_user() {
        let enforcer = IntrospectionEnforcer::internal_only();
        enforcer
            .validate_query(introspection_schema_query(), Some("user123"))
            .unwrap_or_else(|e| panic!("expected authenticated user to be allowed: {e}"));
    }

    #[test]
    fn test_internal_only_rejects_anonymous_user() {
        let enforcer = IntrospectionEnforcer::internal_only();
        let result = enforcer.validate_query(introspection_schema_query(), None);
        assert!(matches!(result, Err(SecurityError::IntrospectionDisabled { .. })));
    }

    // ============================================================================
    // Check 3: Policy Enforcement Tests
    // ============================================================================

    #[test]
    fn test_allowed_policy_permits_introspection() {
        let enforcer = IntrospectionEnforcer::allowed();
        enforcer
            .validate_query(introspection_schema_query(), None)
            .unwrap_or_else(|e| panic!("expected Allowed policy to permit introspection: {e}"));
    }

    #[test]
    fn test_allowed_policy_permits_anonymous_introspection() {
        let enforcer = IntrospectionEnforcer::allowed();
        enforcer.validate_query(introspection_schema_query(), None).unwrap_or_else(|e| {
            panic!("expected Allowed policy to permit anonymous introspection: {e}")
        });
    }

    #[test]
    fn test_disabled_policy_blocks_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        let result = enforcer.validate_query(introspection_schema_query(), None);
        assert!(matches!(result, Err(SecurityError::IntrospectionDisabled { .. })));
    }

    #[test]
    fn test_disabled_policy_blocks_authenticated_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        let result = enforcer.validate_query(introspection_schema_query(), Some("user123"));
        assert!(matches!(result, Err(SecurityError::IntrospectionDisabled { .. })));
    }

    #[test]
    fn test_policy_allows_normal_queries_always() {
        let disabled_enforcer = IntrospectionEnforcer::disabled();
        disabled_enforcer.validate_query(normal_query(), None).unwrap_or_else(|e| {
            panic!("expected normal queries to pass even with Disabled policy: {e}")
        });
    }

    // ============================================================================
    // Configuration Tests
    // ============================================================================

    #[test]
    fn test_introspection_config_all() {
        let config = IntrospectionConfig::all();
        assert!(config.detect_schema);
        assert!(config.detect_type);
    }

    #[test]
    fn test_introspection_config_strict_coincides_with_all() {
        // Post-#454 (`__typename` / `__directive` knobs removed) the two
        // configs detect the same meta-fields.
        let config = IntrospectionConfig::strict();
        assert!(config.detect_schema);
        assert!(config.detect_type);
    }

    #[test]
    fn test_policy_display() {
        assert_eq!(IntrospectionPolicy::Allowed.to_string(), "Allowed");
        assert_eq!(IntrospectionPolicy::Disabled.to_string(), "Disabled");
        assert_eq!(IntrospectionPolicy::InternalOnly.to_string(), "InternalOnly");
    }

    #[test]
    fn test_policy_from_config_truth_table() {
        // The single source of truth shared by the GraphQL gate and the REST
        // `/introspection` mount decision (#453).
        assert_eq!(IntrospectionPolicy::from_config(false, true), IntrospectionPolicy::Disabled);
        assert_eq!(IntrospectionPolicy::from_config(false, false), IntrospectionPolicy::Disabled);
        assert_eq!(IntrospectionPolicy::from_config(true, true), IntrospectionPolicy::InternalOnly);
        assert_eq!(IntrospectionPolicy::from_config(true, false), IntrospectionPolicy::Allowed);
    }

    #[test]
    fn test_enforcer_helpers() {
        let allowed = IntrospectionEnforcer::allowed();
        assert_eq!(allowed.policy(), IntrospectionPolicy::Allowed);

        let disabled = IntrospectionEnforcer::disabled();
        assert_eq!(disabled.policy(), IntrospectionPolicy::Disabled);

        let internal = IntrospectionEnforcer::internal_only();
        assert_eq!(internal.policy(), IntrospectionPolicy::InternalOnly);
    }

    // ============================================================================
    // Custom Configuration Tests
    // ============================================================================

    #[test]
    fn test_custom_config_with_selective_detection() {
        let config = IntrospectionConfig {
            detect_schema: true,
            detect_type:   false,
        };

        let enforcer = IntrospectionEnforcer::with_config(IntrospectionPolicy::Disabled, config);

        // __schema should be detected and blocked
        let schema_query = "{ __schema { types { name } } }";
        assert!(matches!(
            enforcer.validate_query(schema_query, None),
            Err(SecurityError::IntrospectionDisabled { .. })
        ));

        // __type should NOT be detected (allowed through)
        let type_query = "{ __type(name: \"User\") { name } }";
        enforcer.validate_query(type_query, None).unwrap_or_else(|e| {
            panic!("expected __type to pass through when detect_type=false: {e}")
        });
    }

    // ============================================================================
    // Edge Cases
    // ============================================================================

    #[test]
    fn test_introspection_in_string_literal_not_detected() {
        let enforcer = IntrospectionEnforcer::disabled();
        // `__schema` here is a string argument value, not a root field. AST-based
        // detection (#454) keys on the root field name, so this is not flagged.
        let query = r#"{ user(filter: "__schema") { name } }"#;
        let is_introspection = enforcer.is_introspection_query(query);
        assert!(!is_introspection);
    }

    #[test]
    fn test_empty_query_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        enforcer.validate_query("", None).unwrap_or_else(|e| {
            panic!("expected empty query to be allowed (not introspection): {e}")
        });
    }

    #[test]
    fn test_whitespace_handled_correctly() {
        let enforcer = IntrospectionEnforcer::allowed();
        let query = "{\n  __schema {\n    types { name }\n  }\n}";
        let is_introspection = enforcer.is_introspection_query(query);
        assert!(is_introspection);
    }

    #[test]
    fn test_multiple_introspection_patterns() {
        let enforcer = IntrospectionEnforcer::allowed();
        let query = "{ __schema { types { name } } __type(name: \"Query\") { name } }";
        let is_introspection = enforcer.is_introspection_query(query);
        assert!(is_introspection);
    }

    // ========================================================================
    // #454: AST-accurate detection truth table
    //
    // `__typename` is never introspection (GraphQL spec §"Type Name
    // Introspection" — it is queryable on every type regardless of policy);
    // aliases, string-argument values, and comments must not false-positive;
    // `__schema` / `__type` are matched as real root fields by *name* (not
    // response alias), including in multi-root documents.
    // ========================================================================

    #[test]
    fn test_root_typename_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query("{ __typename }"));
        // ...and is allowed through even under the strictest policy.
        enforcer
            .validate_query("{ __typename }", None)
            .unwrap_or_else(|e| panic!("__typename must never be blocked: {e}"));
    }

    #[test]
    fn test_nested_typename_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query("{ user { __typename } }"));
    }

    #[test]
    fn test_aliased_typename_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query("{ x: __typename }"));
    }

    #[test]
    fn test_schema_in_string_argument_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query(r#"{ search(q: "__schema") }"#));
    }

    #[test]
    fn test_type_in_comment_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        let query = "query Foo { a: user { name } }  # mentions __type in a comment";
        assert!(!enforcer.is_introspection_query(query));
    }

    #[test]
    fn test_aliased_normal_field_is_not_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query("{ alias: users { id } }"));
    }

    #[test]
    fn test_aliased_schema_is_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(enforcer.is_introspection_query("{ foo: __schema { queryType { name } } }"));
    }

    #[test]
    fn test_multi_root_schema_is_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        let query = "{ users { id } __schema { types { name } } }";
        assert!(enforcer.is_introspection_query(query));
    }

    #[test]
    fn test_type_field_query_is_introspection() {
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(enforcer.is_introspection_query(r#"{ __type(name: "X") { name } }"#));
    }

    #[test]
    fn test_malformed_query_is_not_introspection() {
        // Parse errors must not fail-open into a 500 nor double-error: the
        // executor/handler rejects malformed queries on the normal parse path.
        let enforcer = IntrospectionEnforcer::disabled();
        assert!(!enforcer.is_introspection_query("{ this is not valid graphql"));
    }
}

mod profiles_tests {
    use crate::security::*;

    // ========================================================================
    // Test Suite 1: Profile Creation and Basic Properties
    // ========================================================================

    #[test]
    fn test_create_standard_profile() {
        let profile = SecurityProfile::standard();
        assert!(profile.is_standard());
        assert!(!profile.is_regulated());
        assert_eq!(profile.name(), "STANDARD");
    }

    #[test]
    fn test_create_regulated_profile() {
        let profile = SecurityProfile::regulated();
        assert!(!profile.is_standard());
        assert!(profile.is_regulated());
        assert_eq!(profile.name(), "REGULATED");
    }

    #[test]
    fn test_default_profile_is_standard() {
        let profile = SecurityProfile::default();
        assert!(profile.is_standard());
    }

    #[test]
    fn test_profile_display() {
        assert_eq!(SecurityProfile::Standard.to_string(), "STANDARD");
        assert_eq!(SecurityProfile::Regulated.to_string(), "REGULATED");
    }

    // ========================================================================
    // Test Suite 2: Common Features (Both Profiles)
    // ========================================================================

    #[test]
    fn test_standard_has_rate_limiting() {
        let profile = SecurityProfile::standard();
        assert!(profile.rate_limit_enabled());
    }

    #[test]
    fn test_regulated_has_rate_limiting() {
        let profile = SecurityProfile::regulated();
        assert!(profile.rate_limit_enabled());
    }

    #[test]
    fn test_standard_has_audit_logging() {
        let profile = SecurityProfile::standard();
        assert!(profile.audit_logging_enabled());
    }

    #[test]
    fn test_regulated_has_audit_logging() {
        let profile = SecurityProfile::regulated();
        assert!(profile.audit_logging_enabled());
    }

    // ========================================================================
    // Test Suite 3: STANDARD Profile Features
    // ========================================================================

    #[test]
    fn test_standard_no_field_audit() {
        let profile = SecurityProfile::standard();
        assert!(!profile.audit_field_access());
    }

    #[test]
    fn test_standard_no_field_masking() {
        let profile = SecurityProfile::standard();
        assert!(!profile.sensitive_field_masking());
    }

    #[test]
    fn test_standard_no_error_redaction() {
        let profile = SecurityProfile::standard();
        assert!(!profile.error_detail_reduction());
    }

    #[test]
    fn test_standard_no_query_logging_compliance() {
        let profile = SecurityProfile::standard();
        assert!(!profile.query_logging_for_compliance());
    }

    #[test]
    fn test_standard_no_response_limits() {
        let profile = SecurityProfile::standard();
        assert!(!profile.response_size_limits());
    }

    #[test]
    fn test_standard_no_strict_filtering() {
        let profile = SecurityProfile::standard();
        assert!(!profile.field_filtering_strict());
    }

    #[test]
    fn test_standard_unlimited_response_size() {
        let profile = SecurityProfile::standard();
        assert_eq!(profile.max_response_size_bytes(), usize::MAX);
    }

    #[test]
    fn test_standard_rate_limit_rps() {
        let profile = SecurityProfile::standard();
        assert_eq!(profile.rate_limit_rps(), 100);
    }

    // ========================================================================
    // Test Suite 4: REGULATED Profile Features
    // ========================================================================

    #[test]
    fn test_regulated_has_field_audit() {
        let profile = SecurityProfile::regulated();
        assert!(profile.audit_field_access());
    }

    #[test]
    fn test_regulated_has_field_masking() {
        let profile = SecurityProfile::regulated();
        assert!(profile.sensitive_field_masking());
    }

    #[test]
    fn test_regulated_has_error_redaction() {
        let profile = SecurityProfile::regulated();
        assert!(profile.error_detail_reduction());
    }

    #[test]
    fn test_regulated_has_query_logging_compliance() {
        let profile = SecurityProfile::regulated();
        assert!(profile.query_logging_for_compliance());
    }

    #[test]
    fn test_regulated_has_response_limits() {
        let profile = SecurityProfile::regulated();
        assert!(profile.response_size_limits());
    }

    #[test]
    fn test_regulated_has_strict_filtering() {
        let profile = SecurityProfile::regulated();
        assert!(profile.field_filtering_strict());
    }

    #[test]
    fn test_regulated_response_size_limit() {
        let profile = SecurityProfile::regulated();
        assert_eq!(profile.max_response_size_bytes(), 1_000_000);
    }

    #[test]
    fn test_regulated_rate_limit_stricter() {
        let standard = SecurityProfile::standard();
        let regulated = SecurityProfile::regulated();
        assert!(regulated.rate_limit_rps() < standard.rate_limit_rps());
    }

    #[test]
    fn test_regulated_query_complexity_stricter() {
        let standard = SecurityProfile::standard();
        let regulated = SecurityProfile::regulated();
        assert!(regulated.max_query_complexity() < standard.max_query_complexity());
    }

    #[test]
    fn test_regulated_query_depth_stricter() {
        let standard = SecurityProfile::standard();
        let regulated = SecurityProfile::regulated();
        assert!(regulated.max_query_depth() < standard.max_query_depth());
    }

    // ========================================================================
    // Test Suite 5: Limits and Thresholds
    // ========================================================================

    #[test]
    fn test_standard_query_limits() {
        let profile = SecurityProfile::standard();
        assert!(profile.max_query_complexity() > 0);
        assert!(profile.max_query_depth() > 0);
    }

    #[test]
    fn test_regulated_query_limits() {
        let profile = SecurityProfile::regulated();
        assert!(profile.max_query_complexity() > 0);
        assert!(profile.max_query_depth() > 0);
    }

    #[test]
    fn test_response_size_reasonable() {
        let profile = SecurityProfile::regulated();
        assert!(profile.max_response_size_bytes() > 100_000); // At least 100KB
        assert!(profile.max_response_size_bytes() < 100_000_000); // Less than 100MB
    }

    // ========================================================================
    // Test Suite 6: Feature Descriptions
    // ========================================================================

    #[test]
    fn test_standard_description() {
        let profile = SecurityProfile::standard();
        let desc = profile.description();
        assert!(!desc.is_empty());
        assert!(desc.contains("rate limiting"));
    }

    #[test]
    fn test_regulated_description() {
        let profile = SecurityProfile::regulated();
        let desc = profile.description();
        assert!(!desc.is_empty());
        assert!(desc.contains("compliance"));
    }

    #[test]
    fn test_standard_enforced_features() {
        let profile = SecurityProfile::standard();
        let features = profile.enforced_features();
        assert!(features.contains(&"Rate Limiting"));
        assert!(features.contains(&"Audit Logging"));
        assert_eq!(features.len(), 2);
    }

    #[test]
    fn test_regulated_enforced_features() {
        let profile = SecurityProfile::regulated();
        let features = profile.enforced_features();
        assert!(features.len() > 2);
        assert!(features.contains(&"Rate Limiting"));
        assert!(features.contains(&"Audit Logging"));
        assert!(features.contains(&"Sensitive Field Masking"));
        assert!(features.contains(&"Error Detail Reduction"));
    }

    // ========================================================================
    // Test Suite 7: Profile Comparison
    // ========================================================================

    #[test]
    fn test_profile_equality() {
        let standard1 = SecurityProfile::standard();
        let standard2 = SecurityProfile::standard();
        let regulated = SecurityProfile::regulated();

        assert_eq!(standard1, standard2);
        assert_ne!(standard1, regulated);
    }

    #[test]
    fn test_profile_clone() {
        let original = SecurityProfile::regulated();
        let cloned = original;
        assert_eq!(original, cloned);
    }

    // ========================================================================
    // Test Suite 8: Edge Cases
    // ========================================================================

    #[test]
    fn test_profile_features_are_superset() {
        // REGULATED should have everything STANDARD has, plus more
        let standard = SecurityProfile::standard();
        let regulated = SecurityProfile::regulated();

        assert_eq!(standard.rate_limit_enabled(), regulated.rate_limit_enabled());
        assert_eq!(standard.audit_logging_enabled(), regulated.audit_logging_enabled());
        // But REGULATED should have additional features
        assert!(regulated.audit_field_access() || !standard.audit_field_access());
    }

    #[test]
    fn test_all_features_documented() {
        let profile = SecurityProfile::standard();
        assert!(!profile.name().is_empty());
        assert!(!profile.description().is_empty());

        let profile = SecurityProfile::regulated();
        assert!(!profile.name().is_empty());
        assert!(!profile.description().is_empty());
    }

    #[test]
    fn test_rate_limits_are_positive() {
        for profile in &[SecurityProfile::Standard, SecurityProfile::Regulated] {
            assert!(
                profile.rate_limit_rps() > 0,
                "Profile {profile} should have positive rate limit"
            );
        }
    }
}

mod query_validator_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
    use crate::security::*;

    // ============================================================================
    // Check 1: Query Size Validation Tests
    // ============================================================================

    fn large_query(size: usize) -> String {
        "{ ".to_string() + "field ".repeat(size).as_str() + "}"
    }

    #[test]
    fn test_query_size_within_limit() {
        let validator = QueryValidator::standard();
        validator
            .validate("{ user { id name } }")
            .unwrap_or_else(|e| panic!("expected Ok for small query: {e}"));
    }

    #[test]
    fn test_query_size_exceeds_limit() {
        let validator = QueryValidator::standard();
        let q = large_query(100_000);
        let result = validator.validate(&q);
        assert!(matches!(result, Err(SecurityError::QueryTooLarge { .. })));
    }

    // ============================================================================
    // Check 2: Malformed query
    // ============================================================================

    #[test]
    fn test_malformed_query_returns_error() {
        let validator = QueryValidator::standard();
        let result = validator.validate("this is not graphql {{{}}}");
        assert!(
            matches!(result, Err(SecurityError::MalformedQuery(_))),
            "malformed query must return MalformedQuery error, got {result:?}"
        );
    }

    // ============================================================================
    // Check 3: Query Depth Validation Tests
    // ============================================================================

    #[test]
    fn test_valid_query_depth() {
        let validator = QueryValidator::standard();
        let metrics = validator
            .validate("{ user { id name } }")
            .unwrap_or_else(|e| panic!("expected Ok for shallow query: {e}"));
        assert!(metrics.depth <= validator.config().max_depth);
    }

    #[test]
    fn test_query_depth_exceeds_limit() {
        let validator = QueryValidator::strict(); // max_depth = 5
        // depth = 7 (a→b→c→d→e→f→g)
        let deep = "{ a { b { c { d { e { f { g } } } } } } }";
        let result = validator.validate(deep);
        assert!(
            matches!(result, Err(SecurityError::QueryTooDeep { .. })),
            "depth-7 query must be rejected with strict (max=5), got {result:?}"
        );
    }

    #[test]
    fn test_very_deep_query_rejected() {
        let validator = QueryValidator::strict(); // max_depth = 5
        // depth = 8 (a→b→c→d→e→f→g→h)
        let deep = "{ a { b { c { d { e { f { g { h } } } } } } } }";
        let result = validator.validate(deep);
        assert!(
            matches!(result, Err(SecurityError::QueryTooDeep { .. })),
            "depth-8 query must be rejected, got {result:?}"
        );
    }

    // ============================================================================
    // Check 4: Query Complexity Validation Tests
    // ============================================================================

    #[test]
    fn test_valid_query_complexity() {
        let validator = QueryValidator::standard();
        let metrics = validator
            .validate("{ user { id name } }")
            .unwrap_or_else(|e| panic!("expected Ok for simple query: {e}"));
        assert!(metrics.complexity <= validator.config().max_complexity);
    }

    #[test]
    fn test_complexity_calculated() {
        let validator = QueryValidator::standard();
        let metrics = validator.validate("{ user { id } }").unwrap();
        assert!(metrics.complexity > 0);
    }

    // ============================================================================
    // Check 5: Alias amplification protection
    // ============================================================================

    #[test]
    fn test_alias_amplification_rejected() {
        let validator = QueryValidator::standard(); // max_aliases = 30
        let aliases: String =
            (0..31).map(|i| ["a", &i.to_string(), ": user { id } "].concat()).collect();
        let query = format!("{{ {aliases} }}");
        let result = validator.validate(&query);
        assert!(
            matches!(
                result,
                Err(SecurityError::TooManyAliases {
                    alias_count: 31,
                    max_aliases: 30,
                })
            ),
            "31-alias query must be rejected with TooManyAliases, got {result:?}"
        );
    }

    #[test]
    fn test_alias_within_limit_allowed() {
        let validator = QueryValidator::standard(); // max_aliases = 30
        let aliases: String =
            (0..5).map(|i| ["a", &i.to_string(), ": user { id } "].concat()).collect();
        let query = format!("{{ {aliases} }}");
        let result = validator.validate(&query);
        assert!(result.is_ok(), "5 aliases should be allowed, got {result:?}");
    }

    // ============================================================================
    // Configuration Tests
    // ============================================================================

    #[test]
    fn test_permissive_config() {
        let config = QueryValidatorConfig::permissive();
        assert_eq!(config.max_depth, 20);
        assert_eq!(config.max_complexity, 5000);
        assert_eq!(config.max_size_bytes, 1_000_000);
        assert_eq!(config.max_aliases, 100);
    }

    #[test]
    fn test_standard_config() {
        let config = QueryValidatorConfig::standard();
        assert_eq!(config.max_depth, 10);
        assert_eq!(config.max_complexity, 1000);
        assert_eq!(config.max_size_bytes, 256_000);
        assert_eq!(config.max_aliases, 30);
    }

    #[test]
    fn test_strict_config() {
        let config = QueryValidatorConfig::strict();
        assert_eq!(config.max_depth, 5);
        assert_eq!(config.max_complexity, 500);
        assert_eq!(config.max_size_bytes, 64_000);
        assert_eq!(config.max_aliases, 10);
    }

    #[test]
    fn test_validator_helpers() {
        let permissive = QueryValidator::permissive();
        assert_eq!(permissive.config().max_depth, 20);

        let standard = QueryValidator::standard();
        assert_eq!(standard.config().max_depth, 10);

        let strict = QueryValidator::strict();
        assert_eq!(strict.config().max_depth, 5);
    }

    // ============================================================================
    // Metrics Tests
    // ============================================================================

    #[test]
    fn test_metrics_returned_on_valid_query() {
        let validator = QueryValidator::standard();
        let query = "{ user { id name } }";
        let metrics = validator.validate(query).unwrap();
        assert!(metrics.depth >= 2); // user → (id, name)
        assert!(metrics.complexity > 0);
        assert_eq!(metrics.alias_count, 0);
    }

    #[test]
    fn test_alias_count_in_metrics() {
        let validator = QueryValidator::standard();
        let query = "{ a: user { id } b: user { id } }";
        let metrics = validator.validate(query).unwrap();
        assert_eq!(metrics.alias_count, 2);
    }
}

mod rls_policy_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::collections::HashMap;

    use crate::{
        db::WhereClause,
        security::{
            rls_policy::{RLSRule, extract_user_value},
            *,
        },
        utils::clock::Clock,
    };

    // ── helpers ──────────────────────────────────────────────────────────────

    fn make_context(user_id: &str, roles: Vec<&str>, tenant_id: Option<&str>) -> SecurityContext {
        SecurityContext {
            user_id:          user_id.into(),
            roles:            roles.into_iter().map(String::from).collect(),
            tenant_id:        tenant_id.map(Into::into),
            scopes:           vec![],
            attributes:       HashMap::new(),
            request_id:       "req1".to_string(),
            ip_address:       None,
            authenticated_at: chrono::Utc::now(),
            expires_at:       chrono::Utc::now() + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    #[test]
    fn trace_id_is_none_without_a_stamp() {
        let ctx = make_context("u1", vec![], None);
        assert_eq!(ctx.trace_id(), None);
    }

    #[test]
    fn with_trace_id_round_trips_through_the_attribute_bag() {
        let tid = "4bf92f3577b34da6a3ce929d0e0e4736";
        let ctx = make_context("u1", vec![], None).with_trace_id(tid);
        assert_eq!(ctx.trace_id(), Some(tid));
        // Stored under the documented key so the server (writer) and the change-log
        // stamp (reader) agree.
        assert_eq!(
            ctx.get_attribute(SecurityContext::TRACE_ID_ATTRIBUTE)
                .and_then(serde_json::Value::as_str),
            Some(tid),
        );
    }

    #[test]
    fn trace_context_is_none_without_a_stamp() {
        let ctx = make_context("u1", vec![], None);
        assert_eq!(ctx.trace_context(), None);
    }

    #[test]
    fn with_trace_context_round_trips_through_the_attribute_bag() {
        let tc = serde_json::json!({
            "version": "00",
            "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
            "parent_id": "00f067aa0ba902b7",
            "trace_flags": "01"
        });
        let ctx = make_context("u1", vec![], None).with_trace_context(tc.clone());
        assert_eq!(ctx.trace_context(), Some(&tc));
        // Stored under the documented key (as a real JSON object, not double-encoded)
        // so the server (writer) and the change-log stamp (reader) agree.
        assert_eq!(ctx.get_attribute(SecurityContext::TRACE_CONTEXT_ATTRIBUTE), Some(&tc));
    }

    fn cacheable_owner_rule() -> RLSRule {
        RLSRule {
            name:              "owner_only".to_string(),
            expression:        "user.id == object.author_id".to_string(),
            cacheable:         true,
            cache_ttl_seconds: Some(300),
        }
    }

    fn policy_with_rule(rule: RLSRule) -> CompiledRLSPolicy {
        let mut rules_by_type = std::collections::HashMap::new();
        rules_by_type.insert("Post".to_string(), vec![rule]);
        CompiledRLSPolicy::new(rules_by_type, None)
    }

    fn policy_with_rule_and_clock(
        rule: RLSRule,
        clock: std::sync::Arc<dyn crate::utils::clock::Clock>,
    ) -> CompiledRLSPolicy {
        let mut rules_by_type = std::collections::HashMap::new();
        rules_by_type.insert("Post".to_string(), vec![rule]);
        CompiledRLSPolicy::new_with_clock(rules_by_type, None, clock)
    }

    // ── DefaultRLSPolicy ─────────────────────────────────────────────────────

    #[test]
    fn test_with_tenant_field_sets_field_name() {
        // Kills mutation: with_tenant_field → Default::default() (line 225).
        // Default::default() returns a policy with tenant_field = "tenant_id";
        // after with_tenant_field("org_id") it must be "org_id".
        let policy = DefaultRLSPolicy::new().with_tenant_field("org_id".to_string());
        assert_eq!(policy.tenant_field, "org_id", "with_tenant_field must update tenant_field");

        // Verify the custom field name appears in the generated WHERE clause
        let context = make_context("user1", vec!["viewer"], Some("org42"));
        let result = policy.evaluate(&context, "Post").unwrap().unwrap();
        let sql = format!("{:?}", result.into_where_clause());
        assert!(sql.contains("org_id"), "custom tenant field must appear in WHERE clause: {sql}");
        assert!(!sql.contains("\"tenant_id\""), "default field name must not appear: {sql}");
    }

    #[test]
    fn test_with_owner_field_sets_field_name() {
        // Kills mutation: with_owner_field → Default::default() (line 231).
        // Default::default() returns a policy with owner_field = "author_id".
        let policy = DefaultRLSPolicy::new().with_owner_field("creator_id".to_string());
        assert_eq!(policy.owner_field, "creator_id", "with_owner_field must update owner_field");

        // Verify the custom field appears in the generated WHERE clause
        let context = make_context("user1", vec!["viewer"], None);
        let result = policy.evaluate(&context, "Post").unwrap().unwrap();
        let sql = format!("{:?}", result.into_where_clause());
        assert!(
            sql.contains("creator_id"),
            "custom owner field must appear in WHERE clause: {sql}"
        );
        assert!(!sql.contains("author_id"), "default field name must not appear: {sql}");
    }

    #[test]
    fn test_default_rls_policy_admin_bypass() {
        let policy = DefaultRLSPolicy::new();
        let context = make_context("user123", vec!["admin"], Some("tenant1"));
        let result = policy.evaluate(&context, "Post").unwrap();
        assert_eq!(result, None, "Admins should bypass RLS");
    }

    #[test]
    fn test_default_rls_policy_tenant_isolation() {
        let policy = DefaultRLSPolicy::new();
        let context = make_context("user123", vec!["user"], Some("tenant1"));
        let result = policy.evaluate(&context, "Post").unwrap();
        assert!(result.is_some(), "Non-admin users should have RLS filter applied");
    }

    #[test]
    fn test_no_rls_policy() {
        let policy = NoRLSPolicy;
        let context = make_context("user123", vec![], None);
        let result = policy.evaluate(&context, "Post").unwrap();
        assert_eq!(result, None, "NoRLSPolicy should never apply filters");
    }

    // ── Cache TTL correctness (kills lines 399, 414) ─────────────────────────

    #[test]
    fn test_compiled_rls_cache_entry_has_correct_ttl() {
        // Verifies: expires_at = clock.now_secs() + ttl_secs  (line 414)
        // Mutation `+ → -` would give expires_at already in the past; `+ → *` gives huge value.
        use crate::utils::clock::ManualClock;
        let clock = std::sync::Arc::new(ManualClock::new());
        let t0 = clock.now_secs();
        // Move clock into policy (t0 already captured — clock not needed afterwards)
        let policy = policy_with_rule_and_clock(cacheable_owner_rule(), clock);
        let context = make_context("user1", vec!["viewer"], Some("t1"));

        // First evaluation populates cache
        policy.evaluate(&context, "Post").unwrap();

        let cache = policy.cache.read();
        let entry =
            cache.get("user1:Post").expect("cache should be populated after first evaluate");
        assert_eq!(entry.expires_at, t0 + 300, "expires_at must be now_secs + ttl_secs (300)");
    }

    #[test]
    fn test_compiled_rls_cache_hit_does_not_refresh_expiry() {
        // Verifies: when now < expires_at, cache is read and expiry is NOT updated (line 399: <).
        // Mutation `< → ==` would cause cache miss at any time ≠ expires_at.
        // Mutation `< → >` would cause hit AFTER expiry (backward).
        use crate::utils::clock::ManualClock;
        let clock = std::sync::Arc::new(ManualClock::new());
        let t0 = clock.now_secs();

        let policy = policy_with_rule_and_clock(cacheable_owner_rule(), clock.clone());
        let context = make_context("user1", vec!["viewer"], Some("t1"));

        // Populate cache at T
        policy.evaluate(&context, "Post").unwrap();
        let first_expires_at = policy.cache.read().get("user1:Post").unwrap().expires_at;
        assert_eq!(first_expires_at, t0 + 300);

        // Advance to 1 second before expiry — still within TTL
        clock.advance(std::time::Duration::from_secs(299));

        // Should hit cache, NOT re-calculate expiry
        policy.evaluate(&context, "Post").unwrap();
        let second_expires_at = policy.cache.read().get("user1:Post").unwrap().expires_at;
        assert_eq!(
            second_expires_at, first_expires_at,
            "Cache hit must not update expires_at (would indicate a miss + re-cache)"
        );
    }

    #[test]
    fn test_compiled_rls_cache_miss_after_expiry_refreshes_entry() {
        // Verifies: when now >= expires_at, cache is NOT used and entry is refreshed (line 399: <).
        // Mutation `< → >` would use the stale entry (no refresh), so expires_at stays at T+300.
        use crate::utils::clock::ManualClock;
        let clock = std::sync::Arc::new(ManualClock::new());
        let t0 = clock.now_secs();

        let policy = policy_with_rule_and_clock(cacheable_owner_rule(), clock.clone());
        let context = make_context("user1", vec!["viewer"], Some("t1"));

        // Populate cache at T → expires_at = T+300
        policy.evaluate(&context, "Post").unwrap();

        // Advance 301 seconds — clearly past expiry
        clock.advance(std::time::Duration::from_secs(301));

        // Cache miss: re-evaluates and re-caches with new expiry = (T+301)+300 = T+601
        policy.evaluate(&context, "Post").unwrap();
        let new_expires = policy.cache.read().get("user1:Post").unwrap().expires_at;
        assert_eq!(
            new_expires,
            t0 + 601,
            "After TTL expiry, cache must be refreshed with updated expires_at"
        );
    }

    #[test]
    fn test_compiled_rls_cache_expires_exactly_at_ttl_boundary() {
        // Verifies: at exactly expires_at (now == expires_at), cache is expired (line 399: <).
        // Mutation `< → <=` would treat the exact boundary as still valid (off-by-one).
        use crate::utils::clock::ManualClock;
        let clock = std::sync::Arc::new(ManualClock::new());
        let t0 = clock.now_secs();

        let policy = policy_with_rule_and_clock(cacheable_owner_rule(), clock.clone());
        let context = make_context("user1", vec!["viewer"], Some("t1"));

        // Populate cache at T → expires_at = T+300
        policy.evaluate(&context, "Post").unwrap();

        // Advance to EXACTLY the expiry second
        clock.advance(std::time::Duration::from_secs(300));
        assert_eq!(clock.now_secs(), t0 + 300);

        // At exactly expires_at, the entry must be considered expired (now < expires_at is false)
        policy.evaluate(&context, "Post").unwrap();
        let refreshed_expires = policy.cache.read().get("user1:Post").unwrap().expires_at;
        assert_eq!(
            refreshed_expires,
            t0 + 600,
            "At exact TTL boundary, cache must expire and refresh (< not <=)"
        );
    }

    // ── cache_result (kills line 432) ─────────────────────────────────────────

    #[test]
    fn test_cache_result_stores_with_300s_default_ttl() {
        // Verifies: cache_result uses 300s TTL (line 432: +).
        // Mutation `+ → -` gives expires_at already past; `+ → *` gives huge value.
        // Mutation "delete entire method" would leave cache empty.
        use crate::utils::clock::ManualClock;
        let clock = std::sync::Arc::new(ManualClock::new());
        let t0 = clock.now_secs();

        let policy =
            CompiledRLSPolicy::new_with_clock(std::collections::HashMap::new(), None, clock);

        let result = Some(WhereClause::Field {
            path:     vec!["author_id".to_string()],
            operator: crate::db::WhereOperator::Eq,
            value:    serde_json::json!("user_x"),
        });

        policy.cache_result("user_x:Post", &result);

        let cache = policy.cache.read();
        let entry = cache.get("user_x:Post").expect("cache_result must insert entry");
        assert_eq!(entry.expires_at, t0 + 300, "cache_result must use 300s TTL");
        assert_eq!(entry.result, result, "cache_result must store the provided result");
    }

    #[test]
    fn test_cache_result_stores_none_result() {
        // Verifies cache_result stores None (bypass) results correctly.
        use crate::utils::clock::ManualClock;
        let policy = CompiledRLSPolicy::new_with_clock(
            std::collections::HashMap::new(),
            None,
            std::sync::Arc::new(ManualClock::new()),
        );

        policy.cache_result("user1:Post", &None);

        let cache = policy.cache.read();
        let entry = cache.get("user1:Post").expect("cache_result must store even None result");
        assert!(entry.result.is_none(), "cached None result must remain None");
    }

    // ── extract_user_value (kills line 518) ──────────────────────────────────

    #[test]
    fn test_extract_user_value_id_field() {
        // Mutation `→ None` gives None; `→ Some(Default)` gives Some(Null). Both fail.
        let ctx = make_context("user_abc_123", vec![], None);
        assert_eq!(
            extract_user_value("id", &ctx),
            Some(serde_json::json!("user_abc_123")),
            "'id' must return the actual user_id"
        );
    }

    #[test]
    fn test_extract_user_value_user_id_alias() {
        let ctx = make_context("user_abc_123", vec![], None);
        assert_eq!(
            extract_user_value("user_id", &ctx),
            Some(serde_json::json!("user_abc_123")),
            "'user_id' must return the same user_id as 'id'"
        );
    }

    #[test]
    fn test_extract_user_value_tenant_id_present() {
        let ctx = make_context("u1", vec![], Some("tenant_xyz"));
        assert_eq!(
            extract_user_value("tenant_id", &ctx),
            Some(serde_json::json!("tenant_xyz")),
            "'tenant_id' must return the tenant id when present"
        );
    }

    #[test]
    fn test_extract_user_value_tenant_id_absent() {
        let ctx = make_context("u1", vec![], None);
        assert_eq!(
            extract_user_value("tenant_id", &ctx),
            None,
            "'tenant_id' must return None when absent, not Some(null)"
        );
    }

    #[test]
    fn test_extract_user_value_roles_field() {
        let ctx = make_context("u1", vec!["editor", "viewer"], None);
        assert_eq!(
            extract_user_value("roles", &ctx),
            Some(serde_json::json!(["editor", "viewer"])),
            "'roles' must return the full roles array"
        );
    }

    #[test]
    fn test_extract_user_value_custom_attribute() {
        let mut attrs = HashMap::new();
        attrs.insert("department".to_string(), serde_json::json!("engineering"));
        let ctx = SecurityContext {
            user_id:          "u1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       attrs,
            request_id:       "r1".to_string(),
            ip_address:       None,
            authenticated_at: chrono::Utc::now(),
            expires_at:       chrono::Utc::now() + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };
        assert_eq!(
            extract_user_value("department", &ctx),
            Some(serde_json::json!("engineering")),
            "Custom attribute must be returned by name"
        );
    }

    #[test]
    fn test_extract_user_value_unknown_returns_none() {
        let ctx = make_context("u1", vec![], None);
        assert_eq!(
            extract_user_value("nonexistent_field", &ctx),
            None,
            "Unknown field must return None, not Some(null)"
        );
    }

    // ── extract_user_value integration: user_id flows to WHERE clause ─────────

    #[test]
    fn test_user_id_propagated_to_rls_where_clause() {
        // Ensures extract_user_value("id") result reaches the generated WhereClause.
        // Kills mutations → None and → Some(Default) on line 518.
        let policy = policy_with_rule(RLSRule {
            name:              "owner_only".to_string(),
            expression:        "user.id == object.author_id".to_string(),
            cacheable:         false,
            cache_ttl_seconds: None,
        });

        let context = make_context("specific_user_42", vec!["viewer"], None);
        let result = policy.evaluate(&context, "Post").unwrap();

        let clause = result.expect("non-admin user must receive an RLS filter").into_where_clause();
        match clause {
            WhereClause::Field { value, .. } => {
                assert_eq!(
                    value,
                    serde_json::json!("specific_user_42"),
                    "RLS WhereClause must embed the actual user_id, not null"
                );
            },
            other => panic!("Expected Field clause, got {other:?}"),
        }
    }
}

mod security_context_tests {
    use std::collections::HashMap;

    use chrono::Utc;

    use crate::security::*;

    #[test]
    fn test_has_role() {
        let context = SecurityContext {
            user_id:          "user123".into(),
            roles:            vec!["admin".to_string(), "moderator".to_string()],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::new(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            authenticated_at: Utc::now(),
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };

        assert!(context.has_role("admin"));
        assert!(context.has_role("moderator"));
        assert!(!context.has_role("superadmin"));
    }

    #[test]
    fn test_has_scope() {
        let context = SecurityContext {
            user_id:          "user123".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec!["read:user".to_string(), "write:post".to_string()],
            attributes:       HashMap::new(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            authenticated_at: Utc::now(),
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };

        assert!(context.has_scope("read:user"));
        assert!(context.has_scope("write:post"));
        assert!(!context.has_scope("admin:*"));
    }

    #[test]
    fn test_wildcard_scopes() {
        let context = SecurityContext {
            user_id:          "user123".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec!["admin:*".to_string()],
            attributes:       HashMap::new(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            authenticated_at: Utc::now(),
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };

        assert!(context.has_scope("admin:read"));
        assert!(context.has_scope("admin:write"));
        assert!(!context.has_scope("user:read"));
    }

    #[test]
    fn test_builder_pattern() {
        use crate::types::TenantId;
        let now = Utc::now();
        let context = SecurityContext {
            user_id:          "user123".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::new(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            authenticated_at: now,
            expires_at:       now + chrono::Duration::hours(1),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
        .with_role("admin".to_string())
        .with_scopes(vec!["read:user".to_string()])
        .with_tenant("tenant-1".to_string());

        assert!(context.has_role("admin"));
        assert!(context.has_scope("read:user"));
        assert_eq!(context.tenant_id, Some(TenantId::new("tenant-1")));
    }
}

mod tls_enforcer_tests {
    use crate::security::*;

    // ============================================================================
    // Check 1: HTTPS Requirement Tests
    // ============================================================================

    #[test]
    fn test_http_allowed_when_tls_not_required() {
        let enforcer = TlsEnforcer::permissive();
        let conn = TlsConnection::new_http();

        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected HTTP allowed when TLS not required: {e}"));
    }

    #[test]
    fn test_http_rejected_when_tls_required() {
        let enforcer = TlsEnforcer::standard();
        let conn = TlsConnection::new_http();

        let result = enforcer.validate_connection(&conn);
        assert!(matches!(result, Err(SecurityError::TlsRequired { .. })));
    }

    #[test]
    fn test_https_allowed_when_tls_required() {
        let enforcer = TlsEnforcer::standard();
        let conn = TlsConnection::new_secure(TlsVersion::V1_3);

        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected HTTPS allowed when TLS required: {e}"));
    }

    // ============================================================================
    // Check 2: TLS Version Minimum Tests
    // ============================================================================

    #[test]
    fn test_tls_1_0_rejected_when_min_1_3() {
        let enforcer = TlsEnforcer::strict(); // min_version = TLS 1.3
        let conn = TlsConnection::new_secure(TlsVersion::V1_0);

        let result = enforcer.validate_connection(&conn);
        assert!(matches!(result, Err(SecurityError::TlsVersionTooOld { .. })));
    }

    #[test]
    fn test_tls_1_2_rejected_when_min_1_3() {
        let enforcer = TlsEnforcer::strict(); // min_version = TLS 1.3
        let conn = TlsConnection::new_secure(TlsVersion::V1_2);

        let result = enforcer.validate_connection(&conn);
        assert!(matches!(result, Err(SecurityError::TlsVersionTooOld { .. })));
    }

    #[test]
    fn test_tls_1_3_allowed_when_min_1_2() {
        let enforcer = TlsEnforcer::standard(); // min_version = TLS 1.2
        let conn = TlsConnection::new_secure(TlsVersion::V1_3);

        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected TLS 1.3 allowed when min 1.2: {e}"));
    }

    #[test]
    fn test_tls_1_2_allowed_when_min_1_2() {
        let enforcer = TlsEnforcer::standard(); // min_version = TLS 1.2
        let conn = TlsConnection::new_secure(TlsVersion::V1_2);

        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected TLS 1.2 allowed when min 1.2: {e}"));
    }

    #[test]
    fn test_tls_version_check_skipped_for_http() {
        // When connection is HTTP, version check is irrelevant
        let enforcer = TlsEnforcer::permissive();
        let conn = TlsConnection::new_http();

        // Even though version is V1_2, this passes because is_secure=false
        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected version check skipped for HTTP: {e}"));
    }

    // ============================================================================
    // Check 3: mTLS Requirement Tests
    // ============================================================================

    #[test]
    fn test_client_cert_optional_when_mtls_not_required() {
        let enforcer = TlsEnforcer::standard(); // mtls_required = false
        let conn = TlsConnection::new_secure(TlsVersion::V1_3);

        enforcer.validate_connection(&conn).unwrap_or_else(|e| {
            panic!("expected no client cert needed when mTLS not required: {e}")
        });
    }

    #[test]
    fn test_client_cert_required_when_mtls_required() {
        let enforcer = TlsEnforcer::strict(); // mtls_required = true
        let conn = TlsConnection::new_secure(TlsVersion::V1_3);

        let result = enforcer.validate_connection(&conn);
        assert!(matches!(result, Err(SecurityError::MtlsRequired { .. })));
    }

    #[test]
    fn test_client_cert_allowed_when_mtls_required() {
        let enforcer = TlsEnforcer::strict(); // mtls_required = true
        let conn = TlsConnection::new_secure_with_client_cert(TlsVersion::V1_3);

        enforcer.validate_connection(&conn).unwrap_or_else(|e| {
            panic!("expected valid client cert accepted when mTLS required: {e}")
        });
    }

    // ============================================================================
    // Check 4: Client Certificate Validity Tests
    // ============================================================================

    #[test]
    fn test_invalid_cert_rejected() {
        let enforcer = TlsEnforcer::strict();
        let conn = TlsConnection {
            is_secure:         true,
            version:           TlsVersion::V1_3,
            has_client_cert:   true,
            client_cert_valid: false, // Invalid!
        };

        let result = enforcer.validate_connection(&conn);
        assert!(matches!(result, Err(SecurityError::InvalidClientCert { .. })));
    }

    #[test]
    fn test_valid_cert_accepted() {
        let enforcer = TlsEnforcer::strict();
        let conn = TlsConnection::new_secure_with_client_cert(TlsVersion::V1_3);

        enforcer
            .validate_connection(&conn)
            .unwrap_or_else(|e| panic!("expected valid cert accepted: {e}"));
    }

    // ============================================================================
    // Combination Tests (Multiple Checks)
    // ============================================================================

    #[test]
    fn test_all_3_tls_settings_enforced_together() {
        let enforcer = TlsEnforcer::strict();
        // strict: tls_required=true, mtls_required=true, min_version=V1_3

        // This should pass all checks
        let valid_conn = TlsConnection::new_secure_with_client_cert(TlsVersion::V1_3);
        enforcer
            .validate_connection(&valid_conn)
            .unwrap_or_else(|e| panic!("expected all checks to pass: {e}"));

        // Fails check 1: HTTP when TLS required
        let http_conn = TlsConnection::new_http();
        assert!(matches!(
            enforcer.validate_connection(&http_conn),
            Err(SecurityError::TlsRequired { .. })
        ));

        // Fails check 2: TLS 1.2 when min 1.3 required
        let old_tls_conn = TlsConnection::new_secure(TlsVersion::V1_2);
        assert!(matches!(
            enforcer.validate_connection(&old_tls_conn),
            Err(SecurityError::TlsVersionTooOld { .. })
        ));

        // Fails check 3: No client cert when mTLS required
        let no_cert_conn = TlsConnection::new_secure(TlsVersion::V1_3);
        assert!(matches!(
            enforcer.validate_connection(&no_cert_conn),
            Err(SecurityError::MtlsRequired { .. })
        ));
    }

    // ============================================================================
    // Error Message Tests
    // ============================================================================

    #[test]
    fn test_error_messages_clear_and_loggable() {
        let enforcer = TlsEnforcer::strict();

        let tls_required_err = enforcer.validate_connection(&TlsConnection::new_http());
        if let Err(SecurityError::TlsRequired { detail }) = tls_required_err {
            assert!(!detail.is_empty());
            assert!(detail.contains("HTTP") || detail.contains("HTTPS"));
        } else {
            panic!("Expected TlsRequired error");
        }

        let tls_version_err =
            enforcer.validate_connection(&TlsConnection::new_secure(TlsVersion::V1_0));
        if let Err(SecurityError::TlsVersionTooOld { current, required }) = tls_version_err {
            assert_eq!(current, TlsVersion::V1_0);
            assert_eq!(required, TlsVersion::V1_3);
        } else {
            panic!("Expected TlsVersionTooOld error");
        }
    }

    // ============================================================================
    // Configuration Tests
    // ============================================================================

    #[test]
    fn test_permissive_config() {
        let config = TlsConfig::permissive();
        assert!(!config.tls_required);
        assert!(!config.mtls_required);
        assert_eq!(config.min_version, TlsVersion::V1_2);
    }

    #[test]
    fn test_standard_config() {
        let config = TlsConfig::standard();
        assert!(config.tls_required);
        assert!(!config.mtls_required);
        assert_eq!(config.min_version, TlsVersion::V1_2);
    }

    #[test]
    fn test_strict_config() {
        let config = TlsConfig::strict();
        assert!(config.tls_required);
        assert!(config.mtls_required);
        assert_eq!(config.min_version, TlsVersion::V1_3);
    }

    #[test]
    fn test_enforcer_helpers() {
        let permissive = TlsEnforcer::permissive();
        assert!(!permissive.config().tls_required);

        let standard = TlsEnforcer::standard();
        assert!(standard.config().tls_required);

        let strict = TlsEnforcer::strict();
        assert!(strict.config().mtls_required);
    }

    // ============================================================================
    // TlsVersion Tests
    // ============================================================================

    #[test]
    fn test_tls_version_display() {
        assert_eq!(TlsVersion::V1_0.to_string(), "TLS 1.0");
        assert_eq!(TlsVersion::V1_1.to_string(), "TLS 1.1");
        assert_eq!(TlsVersion::V1_2.to_string(), "TLS 1.2");
        assert_eq!(TlsVersion::V1_3.to_string(), "TLS 1.3");
    }

    #[test]
    fn test_tls_version_ordering() {
        assert!(TlsVersion::V1_0 < TlsVersion::V1_1);
        assert!(TlsVersion::V1_1 < TlsVersion::V1_2);
        assert!(TlsVersion::V1_2 < TlsVersion::V1_3);
        assert!(TlsVersion::V1_3 > TlsVersion::V1_2);
    }

    #[test]
    fn test_tls_connection_helpers() {
        let http_conn = TlsConnection::new_http();
        assert!(!http_conn.is_secure);

        let secure_conn = TlsConnection::new_secure(TlsVersion::V1_3);
        assert!(secure_conn.is_secure);
        assert!(!secure_conn.has_client_cert);

        let mtls_conn = TlsConnection::new_secure_with_client_cert(TlsVersion::V1_3);
        assert!(mtls_conn.is_secure);
        assert!(mtls_conn.has_client_cert);
        assert!(mtls_conn.client_cert_valid);
    }

    // ============================================================================
    // Edge Case Tests
    // ============================================================================

    #[test]
    fn test_custom_config_from_individual_settings() {
        let config = TlsConfig {
            tls_required:  true,
            mtls_required: false,
            min_version:   TlsVersion::V1_2,
        };

        let enforcer = TlsEnforcer::from_config(config);

        // HTTP should fail (tls_required=true)
        let http_conn = TlsConnection::new_http();
        assert!(matches!(
            enforcer.validate_connection(&http_conn),
            Err(SecurityError::TlsRequired { .. })
        ));

        // HTTPS with TLS 1.2 should pass
        let secure_conn = TlsConnection::new_secure(TlsVersion::V1_2);
        enforcer
            .validate_connection(&secure_conn)
            .unwrap_or_else(|e| panic!("expected HTTPS with TLS 1.2 to pass: {e}"));

        // HTTPS without client cert should pass (mtls_required=false)
        let no_cert_conn = TlsConnection::new_secure(TlsVersion::V1_3);
        enforcer
            .validate_connection(&no_cert_conn)
            .unwrap_or_else(|e| panic!("expected HTTPS without client cert to pass: {e}"));
    }

    #[test]
    fn test_http_with_certificate_info_still_fails_when_tls_required() {
        let enforcer = TlsEnforcer::standard(); // tls_required=true

        // Even with client cert info, HTTP should fail
        let http_with_cert_info = TlsConnection {
            is_secure:         false, // Still HTTP
            version:           TlsVersion::V1_2,
            has_client_cert:   true,
            client_cert_valid: true,
        };

        assert!(matches!(
            enforcer.validate_connection(&http_with_cert_info),
            Err(SecurityError::TlsRequired { .. })
        ));
    }
}

mod validation_audit_tests {
    use chrono::Utc;

    use crate::security::*;

    #[test]
    fn test_redaction_policy_default() {
        let policy = RedactionPolicy::default();
        match policy {
            RedactionPolicy::Conservative => {},
            _ => panic!("Default should be Conservative"),
        }
    }

    #[test]
    fn test_config_default() {
        let config = ValidationAuditLoggerConfig::default();
        assert!(config.enabled);
        assert!(config.capture_successful_validations);
        assert!(config.capture_query_strings);
    }

    #[test]
    fn test_logger_enabled_disabled() {
        let config = ValidationAuditLoggerConfig {
            enabled: false,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        assert!(!logger.is_enabled());

        let config2 = ValidationAuditLoggerConfig::default();
        let logger2 = ValidationAuditLogger::new(config2);
        assert!(logger2.is_enabled());
    }

    #[test]
    fn test_logger_entry_logging() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);

        let entry = ValidationAuditEntry {
            timestamp:         Utc::now(),
            user_id:           Some("user:1".to_string()),
            tenant_id:         Some("tenant:1".to_string()),
            ip_address:        "192.168.1.1".to_string(),
            query_string:      "{ user { id } }".to_string(),
            mutation_name:     None,
            field:             "email".to_string(),
            validation_rule:   "pattern".to_string(),
            valid:             false,
            failure_reason:    Some("Invalid format".to_string()),
            duration_us:       100,
            execution_context: "pattern_validator".to_string(),
        };

        logger.log_entry(entry);
        assert_eq!(logger.entry_count(), 1);
    }

    #[test]
    fn test_logger_filter_by_user() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);

        let entry1 = ValidationAuditEntry {
            timestamp:         Utc::now(),
            user_id:           Some("user:1".to_string()),
            tenant_id:         None,
            ip_address:        "192.168.1.1".to_string(),
            query_string:      String::new(),
            mutation_name:     None,
            field:             "field1".to_string(),
            validation_rule:   "required".to_string(),
            valid:             false,
            failure_reason:    None,
            duration_us:       0,
            execution_context: "validator".to_string(),
        };

        let mut entry2 = entry1.clone();
        entry2.user_id = Some("user:2".to_string());

        logger.log_entry(entry1);
        logger.log_entry(entry2);

        let user1_entries = logger.entries_by_user("user:1");
        assert_eq!(user1_entries.len(), 1);
    }

    #[test]
    fn test_logger_failure_count() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);

        let entry = ValidationAuditEntry {
            timestamp:         Utc::now(),
            user_id:           None,
            tenant_id:         None,
            ip_address:        "192.168.1.1".to_string(),
            query_string:      String::new(),
            mutation_name:     None,
            field:             "field".to_string(),
            validation_rule:   "pattern".to_string(),
            valid:             false,
            failure_reason:    Some("error".to_string()),
            duration_us:       0,
            execution_context: "validator".to_string(),
        };

        logger.log_entry(entry.clone());

        let mut entry_success = entry;
        entry_success.valid = true;
        logger.log_entry(entry_success);

        assert_eq!(logger.failure_count(), 1);
    }
}

mod actor_context_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
    #![allow(clippy::doc_markdown)] // Reason: informal test doc comments

    use std::collections::HashMap;

    use chrono::Utc;
    use serde_json::json;
    use uuid::Uuid;

    use crate::{
        security::{ActorType, AuthenticatedUser, SecurityContext},
        types::UserId,
    };

    fn user(
        sub: &str,
        scopes: &[&str],
        extra: HashMap<String, serde_json::Value>,
    ) -> AuthenticatedUser {
        AuthenticatedUser {
            user_id:      UserId::new(sub),
            scopes:       scopes.iter().map(ToString::to_string).collect(),
            expires_at:   Utc::now() + chrono::Duration::hours(1),
            email:        None,
            display_name: None,
            extra_claims: extra,
        }
    }

    /// A delegated agent JWT (`act` claim) derives AiAgent + acting_for = the
    /// underlying human subject.
    #[test]
    fn from_user_derives_ai_agent_acting_for_subject() {
        let sub = "550e8400-e29b-41d4-a716-446655440000";
        let mut extra = HashMap::new();
        extra.insert("act".to_string(), json!({ "sub": "agent-7" }));

        let ctx = SecurityContext::from_user(&user(sub, &[], extra), "req-1".to_string());

        assert_eq!(ctx.actor_type(), ActorType::AiAgent);
        assert_eq!(ctx.acting_for(), Some(Uuid::parse_str(sub).unwrap()));
    }

    /// An ordinary user JWT derives HumanUser with no delegated user.
    #[test]
    fn from_user_derives_human_user_by_default() {
        let ctx = SecurityContext::from_user(
            &user("user-1", &["read:user"], HashMap::new()),
            "req-2".to_string(),
        );

        assert_eq!(ctx.actor_type(), ActorType::HumanUser);
        assert_eq!(ctx.acting_for(), None);
    }

    /// A `service_account` scope derives ServiceAccount.
    #[test]
    fn from_user_derives_service_account_from_scope() {
        let ctx = SecurityContext::from_user(
            &user("svc-1", &["service_account"], HashMap::new()),
            "req-3".to_string(),
        );

        assert_eq!(ctx.actor_type(), ActorType::ServiceAccount);
    }

    /// `with_actor_type` overrides the derived classification (the API-key path).
    #[test]
    fn with_actor_type_overrides_and_round_trips() {
        let ctx = SecurityContext::from_user(&user("u", &[], HashMap::new()), "r".to_string())
            .with_actor_type(ActorType::ServiceAccount);

        assert_eq!(ctx.actor_type(), ActorType::ServiceAccount);
    }

    /// `with_acting_for(None)` clears a previously stamped delegated user.
    #[test]
    fn with_acting_for_none_clears() {
        let uuid = Uuid::new_v4();
        let ctx = SecurityContext::from_user(&user("u", &[], HashMap::new()), "r".to_string())
            .with_acting_for(Some(uuid))
            .with_acting_for(None);

        assert_eq!(ctx.acting_for(), None);
    }

    /// A context built without delegation reports the default actor type.
    #[test]
    fn unset_actor_type_defaults_to_human_user() {
        let ctx = SecurityContext::from_user(&user("u", &[], HashMap::new()), "r".to_string());
        assert_eq!(ctx.actor_type(), ActorType::HumanUser);
    }

    /// A scalar `role` claim populates `roles` so `requires_role` gates are
    /// reachable over every transport that builds a context via `from_user` (#503).
    #[test]
    fn from_user_populates_roles_from_scalar_role_claim() {
        let mut extra = HashMap::new();
        extra.insert("role".to_string(), json!("report_reader"));

        let ctx = SecurityContext::from_user(&user("u", &[], extra), "r".to_string());

        assert_eq!(ctx.roles, vec!["report_reader".to_string()]);
        assert!(ctx.has_role("report_reader"));
    }

    /// A `roles` array claim populates `roles` (sorted, deduplicated).
    #[test]
    fn from_user_populates_roles_from_roles_array_claim() {
        let mut extra = HashMap::new();
        extra.insert("roles".to_string(), json!(["moderator", "admin", "moderator"]));

        let ctx = SecurityContext::from_user(&user("u", &[], extra), "r".to_string());

        assert_eq!(ctx.roles, vec!["admin".to_string(), "moderator".to_string()]);
    }

    /// The `fraiseql_roles` array claim is also honoured.
    #[test]
    fn from_user_populates_roles_from_fraiseql_roles_claim() {
        let mut extra = HashMap::new();
        extra.insert("fraiseql_roles".to_string(), json!(["report_reader"]));

        let ctx = SecurityContext::from_user(&user("u", &[], extra), "r".to_string());

        assert_eq!(ctx.roles, vec!["report_reader".to_string()]);
    }

    /// `role` and `roles` claims are merged and de-duplicated across sources.
    #[test]
    fn from_user_merges_and_dedups_role_sources() {
        let mut extra = HashMap::new();
        extra.insert("role".to_string(), json!("admin"));
        extra.insert("roles".to_string(), json!(["admin", "editor"]));

        let ctx = SecurityContext::from_user(&user("u", &[], extra), "r".to_string());

        assert_eq!(ctx.roles, vec!["admin".to_string(), "editor".to_string()]);
    }

    /// No role claims → empty `roles` (gated operations stay denied, as before).
    #[test]
    fn from_user_roles_empty_without_role_claims() {
        let ctx =
            SecurityContext::from_user(&user("u", &["read:user"], HashMap::new()), "r".to_string());
        assert!(ctx.roles.is_empty());
    }
}

/// `SecurityContext::system_job` — the background/system identity for scheduled
/// sources and other server-initiated work (#573). The first (and, at
/// introduction, only) construction of [`ActorType::SystemJob`].
mod system_job_tests {
    use crate::{
        security::{ActorType, SecurityContext},
        types::TenantId,
    };

    #[test]
    fn system_job_carries_granted_authority_and_actor_type() {
        let ctx = SecurityContext::system_job(
            "orders",
            "fire-1",
            vec!["ingest_writer".to_string()],
            vec!["write:order".to_string()],
            Some(TenantId::from("acme")),
        );
        assert_eq!(ctx.actor_type(), ActorType::SystemJob);
        assert!(ctx.has_role("ingest_writer"));
        assert!(ctx.has_scope("write:order"));
        assert_eq!(ctx.tenant_id.as_ref().map(TenantId::as_str), Some("acme"));
        assert!(ctx.is_multi_tenant());
        assert!(!ctx.is_expired(), "a fresh system-job context is not expired");
        // The principal reads as an internal job, mirroring the `apikey:` convention.
        assert_eq!(ctx.user_id.as_str(), "system_job:orders");
    }

    #[test]
    fn system_job_without_grants_is_fail_closed() {
        // No roles, no scopes, no tenant → the identity grants nothing: every
        // authz/RLS decision denies. This is the fail-closed default a source with
        // no `run_as` runs under.
        let ctx = SecurityContext::system_job("orders", "fire-1", vec![], vec![], None);
        assert_eq!(ctx.actor_type(), ActorType::SystemJob);
        assert!(!ctx.has_role("admin"));
        assert!(!ctx.has_scope("write:order"));
        assert!(!ctx.is_multi_tenant(), "no tenant → scoped to nothing");
    }
}