openbao 0.13.0

Secure, typed, async Rust SDK for OpenBao
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
//! Identity secrets engine support.
//!
//! The identity engine manages OpenBao entities, groups, and aliases. These
//! helpers cover the core lifecycle endpoints and keep returned lists and
//! metadata maps bounded before allocation can grow without limit.

use std::collections::BTreeMap;
use std::fmt;

use reqwest::{Method, StatusCode};
use secrecy::{ExposeSecret, SecretString};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;

use crate::{
    Authenticated, Client, Error, Result,
    path::{validate_endpoint_path, validate_mount_path},
    response::{
        Empty, ListEntries, ResponseEnvelope, deserialize_bounded_string_map_or_default,
        deserialize_bounded_string_vec,
    },
    validation::validate_duration_parameter,
};

const IDENTITY_LIST_LIMIT: usize = crate::response::MAX_RESPONSE_STRINGS;

/// Handle for the identity secrets engine.
#[derive(Debug)]
pub struct Identity<'a> {
    client: &'a Client<Authenticated>,
    mount: Vec<String>,
}

/// Entity create/update request.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityEntityRequest {
    /// Entity name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Entity metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, String>,
    /// Entity policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub policies: Vec<String>,
    /// Whether the entity is disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
}

impl IdentityEntityRequest {
    /// Creates an entity request with a name.
    pub fn named(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Adds a policy.
    #[must_use]
    pub fn with_policy(mut self, policy: impl Into<String>) -> Self {
        self.policies.push(policy.into());
        self
    }

    /// Adds a metadata key/value pair.
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(self.policies.len(), "identity entity policies")?;
        validate_string_count(self.metadata.len(), "identity entity metadata")?;
        Ok(())
    }
}

/// Entity information returned by OpenBao.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityEntityInfo {
    /// Entity ID.
    #[serde(default)]
    pub id: String,
    /// Entity name.
    #[serde(default)]
    pub name: Option<String>,
    /// Entity metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub metadata: BTreeMap<String, String>,
    /// Entity policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub policies: Vec<String>,
    /// Direct group IDs that contain this entity.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub direct_group_ids: Vec<String>,
    /// Inherited group IDs for this entity.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub inherited_group_ids: Vec<String>,
    /// Whether the entity is disabled.
    #[serde(default)]
    pub disabled: bool,
}

/// Entity create/update response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityEntityUpsert {
    /// Entity ID.
    #[serde(default)]
    pub id: String,
    /// Entity name, when returned.
    #[serde(default)]
    pub name: Option<String>,
}

/// Entity list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityEntityList {
    /// Entity IDs or names returned by OpenBao.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityEntityList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to delete multiple entities by ID.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityEntityBatchDeleteRequest {
    /// Entity IDs to delete.
    pub entity_ids: Vec<String>,
}

impl IdentityEntityBatchDeleteRequest {
    /// Creates a batch delete request.
    pub fn new(entity_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            entity_ids: entity_ids.into_iter().map(Into::into).collect(),
        }
    }

    fn validate(&self) -> Result<()> {
        if self.entity_ids.is_empty() {
            return Err(Error::InvalidParameter(
                "identity entity batch delete requires at least one entity ID".into(),
            ));
        }
        validate_string_count(self.entity_ids.len(), "identity entity IDs")?;
        Ok(())
    }
}

/// Entity lookup request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityEntityLookupRequest {
    /// Entity ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Entity name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Alias ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_id: Option<String>,
    /// Alias name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_name: Option<String>,
    /// Alias mount accessor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_mount_accessor: Option<String>,
}

impl IdentityEntityLookupRequest {
    /// Looks up an entity by ID.
    pub fn by_id(id: impl Into<String>) -> Self {
        Self {
            id: Some(id.into()),
            ..Self::default()
        }
    }

    /// Looks up an entity by name.
    pub fn by_name(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Looks up an entity by alias name and mount accessor.
    pub fn by_alias(
        alias_name: impl Into<String>,
        alias_mount_accessor: impl Into<String>,
    ) -> Self {
        Self {
            alias_name: Some(alias_name.into()),
            alias_mount_accessor: Some(alias_mount_accessor.into()),
            ..Self::default()
        }
    }

    fn validate(&self) -> Result<()> {
        let identifiers = [
            self.id.as_ref(),
            self.name.as_ref(),
            self.alias_id.as_ref(),
            self.alias_name.as_ref(),
        ]
        .into_iter()
        .flatten()
        .count();
        if identifiers == 0 {
            return Err(Error::InvalidParameter(
                "identity entity lookup requires an id, name, alias_id, or alias_name".into(),
            ));
        }
        if [
            self.id.as_ref(),
            self.name.as_ref(),
            self.alias_id.as_ref(),
            self.alias_name.as_ref(),
            self.alias_mount_accessor.as_ref(),
        ]
        .into_iter()
        .flatten()
        .any(|value| value.trim().is_empty())
        {
            return Err(Error::InvalidParameter(
                "identity entity lookup fields must not be empty".into(),
            ));
        }
        if self.alias_name.is_some() && self.alias_mount_accessor.is_none() {
            return Err(Error::InvalidParameter(
                "identity alias lookup requires alias_mount_accessor".into(),
            ));
        }
        Ok(())
    }
}

/// Entity merge request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityEntityMergeRequest {
    /// Entity ID that remains after merge.
    pub to_entity_id: String,
    /// Entity IDs merged into `to_entity_id`.
    pub from_entity_ids: Vec<String>,
    /// Whether conflicting aliases are forced into the target entity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub force: Option<bool>,
}

impl IdentityEntityMergeRequest {
    /// Creates an entity merge request.
    pub fn new(
        to_entity_id: impl Into<String>,
        from_entity_ids: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            to_entity_id: to_entity_id.into(),
            from_entity_ids: from_entity_ids.into_iter().map(Into::into).collect(),
            force: None,
        }
    }

    /// Forces the merge when OpenBao allows it.
    #[must_use]
    pub fn force(mut self) -> Self {
        self.force = Some(true);
        self
    }

    fn validate(&self) -> Result<()> {
        if self.to_entity_id.trim().is_empty() {
            return Err(Error::InvalidParameter(
                "identity merge target entity ID must not be empty".into(),
            ));
        }
        if self.from_entity_ids.is_empty() {
            return Err(Error::InvalidParameter(
                "identity merge requires at least one source entity ID".into(),
            ));
        }
        validate_string_count(
            self.from_entity_ids.len(),
            "identity merge source entity IDs",
        )
    }
}

/// Identity group type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IdentityGroupType {
    /// Internal group.
    Internal,
    /// External group.
    External,
}

impl IdentityGroupType {
    fn as_str(self) -> &'static str {
        match self {
            Self::Internal => "internal",
            Self::External => "external",
        }
    }
}

impl Serialize for IdentityGroupType {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for IdentityGroupType {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            "internal" => Ok(Self::Internal),
            "external" => Ok(Self::External),
            _ => Err(serde::de::Error::custom("unsupported identity group type")),
        }
    }
}

/// Group create/update request.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityGroupRequest {
    /// Group name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Group type.
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub group_type: Option<IdentityGroupType>,
    /// Group policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub policies: Vec<String>,
    /// Member entity IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub member_entity_ids: Vec<String>,
    /// Member group IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub member_group_ids: Vec<String>,
    /// Group metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, String>,
}

impl IdentityGroupRequest {
    /// Creates a named internal group request.
    pub fn internal(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            group_type: Some(IdentityGroupType::Internal),
            ..Self::default()
        }
    }

    /// Creates a named external group request.
    pub fn external(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            group_type: Some(IdentityGroupType::External),
            ..Self::default()
        }
    }

    /// Adds a policy.
    #[must_use]
    pub fn with_policy(mut self, policy: impl Into<String>) -> Self {
        self.policies.push(policy.into());
        self
    }

    /// Adds a member entity ID.
    #[must_use]
    pub fn with_member_entity_id(mut self, entity_id: impl Into<String>) -> Self {
        self.member_entity_ids.push(entity_id.into());
        self
    }

    /// Adds a metadata key/value pair.
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(self.policies.len(), "identity group policies")?;
        validate_string_count(
            self.member_entity_ids.len(),
            "identity group member entity IDs",
        )?;
        validate_string_count(
            self.member_group_ids.len(),
            "identity group member group IDs",
        )?;
        validate_string_count(self.metadata.len(), "identity group metadata")?;
        Ok(())
    }
}

/// Group information returned by OpenBao.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityGroupInfo {
    /// Group ID.
    #[serde(default)]
    pub id: String,
    /// Group name.
    #[serde(default)]
    pub name: Option<String>,
    /// Group type.
    #[serde(default, rename = "type")]
    pub group_type: Option<IdentityGroupType>,
    /// Group policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub policies: Vec<String>,
    /// Member entity IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub member_entity_ids: Vec<String>,
    /// Member group IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub member_group_ids: Vec<String>,
    /// Parent group IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub parent_group_ids: Vec<String>,
    /// Group metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub metadata: BTreeMap<String, String>,
}

/// Group create/update response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityGroupUpsert {
    /// Group ID.
    #[serde(default)]
    pub id: String,
    /// Group name, when returned.
    #[serde(default)]
    pub name: Option<String>,
}

/// Group list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityGroupList {
    /// Group IDs or names returned by OpenBao.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

/// Group lookup request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityGroupLookupRequest {
    /// Group ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Group name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Alias ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_id: Option<String>,
    /// Alias name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_name: Option<String>,
    /// Alias mount accessor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_mount_accessor: Option<String>,
}

impl IdentityGroupLookupRequest {
    /// Looks up a group by ID.
    pub fn by_id(id: impl Into<String>) -> Self {
        Self {
            id: Some(id.into()),
            ..Self::default()
        }
    }

    /// Looks up a group by name.
    pub fn by_name(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Looks up a group by alias name and mount accessor.
    pub fn by_alias(
        alias_name: impl Into<String>,
        alias_mount_accessor: impl Into<String>,
    ) -> Self {
        Self {
            alias_name: Some(alias_name.into()),
            alias_mount_accessor: Some(alias_mount_accessor.into()),
            ..Self::default()
        }
    }

    fn validate(&self) -> Result<()> {
        let identifiers = [
            self.id.as_ref(),
            self.name.as_ref(),
            self.alias_id.as_ref(),
            self.alias_name.as_ref(),
        ]
        .into_iter()
        .flatten()
        .count();
        if identifiers == 0 {
            return Err(Error::InvalidParameter(
                "identity group lookup requires an id, name, alias_id, or alias_name".into(),
            ));
        }
        if [
            self.id.as_ref(),
            self.name.as_ref(),
            self.alias_id.as_ref(),
            self.alias_name.as_ref(),
            self.alias_mount_accessor.as_ref(),
        ]
        .into_iter()
        .flatten()
        .any(|value| value.trim().is_empty())
        {
            return Err(Error::InvalidParameter(
                "identity group lookup fields must not be empty".into(),
            ));
        }
        if self.alias_name.is_some() && self.alias_mount_accessor.is_none() {
            return Err(Error::InvalidParameter(
                "identity group alias lookup requires alias_mount_accessor".into(),
            ));
        }
        Ok(())
    }
}

impl ListEntries for IdentityGroupList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Entity alias create/update request.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityEntityAliasRequest {
    /// Alias name.
    pub name: String,
    /// Canonical entity ID.
    pub canonical_id: String,
    /// Auth mount accessor.
    pub mount_accessor: String,
    /// Alias ID when updating an existing alias.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Alias custom metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub custom_metadata: BTreeMap<String, String>,
}

impl IdentityEntityAliasRequest {
    /// Creates an entity alias request.
    pub fn new(
        name: impl Into<String>,
        canonical_id: impl Into<String>,
        mount_accessor: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            canonical_id: canonical_id.into(),
            mount_accessor: mount_accessor.into(),
            id: None,
            custom_metadata: BTreeMap::new(),
        }
    }

    /// Sets the alias ID for updates.
    #[must_use]
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Adds alias custom metadata.
    #[must_use]
    pub fn with_custom_metadata(
        mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.custom_metadata.insert(key.into(), value.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(self.custom_metadata.len(), "identity entity alias metadata")?;
        Ok(())
    }
}

/// Group alias create/update request.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityGroupAliasRequest {
    /// Alias name.
    pub name: String,
    /// Canonical group ID.
    pub canonical_id: String,
    /// Auth mount accessor.
    pub mount_accessor: String,
    /// Alias ID when updating an existing alias.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
}

impl IdentityGroupAliasRequest {
    /// Creates a group alias request.
    pub fn new(
        name: impl Into<String>,
        canonical_id: impl Into<String>,
        mount_accessor: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            canonical_id: canonical_id.into(),
            mount_accessor: mount_accessor.into(),
            id: None,
        }
    }

    /// Sets the alias ID for updates.
    #[must_use]
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }
}

/// Alias information returned by OpenBao.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityAliasInfo {
    /// Alias ID.
    #[serde(default)]
    pub id: String,
    /// Alias name.
    #[serde(default)]
    pub name: Option<String>,
    /// Canonical entity or group ID.
    #[serde(default)]
    pub canonical_id: Option<String>,
    /// Auth mount accessor.
    #[serde(default)]
    pub mount_accessor: Option<String>,
    /// Auth mount path.
    #[serde(default)]
    pub mount_path: Option<String>,
    /// Auth mount type.
    #[serde(default)]
    pub mount_type: Option<String>,
    /// Entity alias custom metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub custom_metadata: BTreeMap<String, String>,
}

/// Alias create/update response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityAliasUpsert {
    /// Alias ID.
    #[serde(default)]
    pub id: String,
}

/// Alias list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityAliasList {
    /// Alias IDs returned by OpenBao.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityAliasList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Identity OIDC token backend configuration request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcConfigRequest {
    /// Issuer URL used in the `iss` claim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer: Option<String>,
}

impl IdentityOidcConfigRequest {
    /// Creates an OIDC config request.
    pub fn new(issuer: impl Into<String>) -> Self {
        Self {
            issuer: Some(issuer.into()),
        }
    }
}

/// Identity OIDC token backend configuration.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcConfig {
    /// Issuer URL used in the `iss` claim.
    #[serde(default)]
    pub issuer: Option<String>,
}

/// Request to create or update an Identity OIDC signing key.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcKeyRequest {
    /// Signing-key rotation period.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rotation_period: Option<String>,
    /// Public verification key lifetime after rotation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verification_ttl: Option<String>,
    /// Role client IDs allowed to use this key. Use `"*"` to allow all clients.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_client_ids: Vec<String>,
    /// Signing algorithm, such as `RS256`, `ES256`, or `EdDSA`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algorithm: Option<String>,
}

impl IdentityOidcKeyRequest {
    /// Creates an empty OIDC signing-key request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the signing-key rotation period.
    #[must_use]
    pub fn with_rotation_period(mut self, rotation_period: impl Into<String>) -> Self {
        self.rotation_period = Some(rotation_period.into());
        self
    }

    /// Sets the public verification key lifetime after rotation.
    #[must_use]
    pub fn with_verification_ttl(mut self, verification_ttl: impl Into<String>) -> Self {
        self.verification_ttl = Some(verification_ttl.into());
        self
    }

    /// Adds an allowed client ID.
    #[must_use]
    pub fn with_allowed_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.allowed_client_ids.push(client_id.into());
        self
    }

    /// Sets the signing algorithm.
    #[must_use]
    pub fn with_algorithm(mut self, algorithm: impl Into<String>) -> Self {
        self.algorithm = Some(algorithm.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if let Some(rotation_period) = &self.rotation_period {
            validate_duration_parameter(rotation_period, "identity OIDC key rotation_period")?;
        }
        if let Some(verification_ttl) = &self.verification_ttl {
            validate_duration_parameter(verification_ttl, "identity OIDC key verification_ttl")?;
        }
        validate_string_count(
            self.allowed_client_ids.len(),
            "identity OIDC allowed client IDs",
        )
    }
}

/// Identity OIDC signing-key rotation request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcKeyRotateRequest {
    /// Optional verification lifetime override for the rotated key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verification_ttl: Option<String>,
}

impl IdentityOidcKeyRotateRequest {
    /// Creates a key-rotation request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the verification TTL override for this rotation.
    #[must_use]
    pub fn with_verification_ttl(mut self, verification_ttl: impl Into<String>) -> Self {
        self.verification_ttl = Some(verification_ttl.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if let Some(verification_ttl) = &self.verification_ttl {
            validate_duration_parameter(
                verification_ttl,
                "identity OIDC key rotation verification_ttl",
            )?;
        }
        Ok(())
    }
}

/// Identity OIDC signing-key information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcKeyInfo {
    /// Signing algorithm.
    #[serde(default)]
    pub algorithm: Option<String>,
    /// Signing-key rotation period in seconds.
    #[serde(default)]
    pub rotation_period: Option<u64>,
    /// Public verification key lifetime in seconds.
    #[serde(default)]
    pub verification_ttl: Option<u64>,
    /// Role client IDs allowed to use this key.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub allowed_client_ids: Vec<String>,
}

/// Identity OIDC signing-key list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityOidcKeyList {
    /// OIDC signing-key names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityOidcKeyList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to create or update an Identity OIDC role.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcRoleRequest {
    /// Configured named key used to sign generated ID tokens.
    pub key: String,
    /// Optional token template string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
    /// Optional client ID. OpenBao generates one when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    /// Token TTL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
}

impl IdentityOidcRoleRequest {
    /// Creates an OIDC role request for the given signing key.
    pub fn new(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            ..Self::default()
        }
    }

    /// Sets the token template.
    #[must_use]
    pub fn with_template(mut self, template: impl Into<String>) -> Self {
        self.template = Some(template.into());
        self
    }

    /// Sets the client ID.
    #[must_use]
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Sets the token TTL.
    #[must_use]
    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Self {
        self.ttl = Some(ttl.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if self.key.trim().is_empty() {
            return Err(Error::InvalidParameter(
                "identity OIDC role key must not be empty".into(),
            ));
        }
        if let Some(ttl) = &self.ttl {
            validate_duration_parameter(ttl, "identity OIDC role ttl")?;
        }
        Ok(())
    }
}

/// Identity OIDC role information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcRoleInfo {
    /// Client ID.
    #[serde(default)]
    pub client_id: Option<String>,
    /// Signing key name.
    #[serde(default)]
    pub key: Option<String>,
    /// Token template.
    #[serde(default)]
    pub template: Option<String>,
    /// Token TTL in seconds.
    #[serde(default)]
    pub ttl: Option<u64>,
}

/// Identity OIDC role list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityOidcRoleList {
    /// OIDC role names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityOidcRoleList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Signed Identity OIDC token generated by OpenBao.
#[derive(Clone, Deserialize)]
pub struct IdentityOidcToken {
    /// Client ID associated with the generated token.
    #[serde(default)]
    pub client_id: Option<String>,
    /// Signed OIDC ID token.
    pub token: SecretString,
    /// Token TTL in seconds.
    #[serde(default)]
    pub ttl: Option<u64>,
}

impl fmt::Debug for IdentityOidcToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityOidcToken")
            .field("client_id", &self.client_id)
            .field("token", &"<redacted>")
            .field("ttl", &self.ttl)
            .finish()
    }
}

/// Request to introspect a signed Identity OIDC token.
#[derive(Clone)]
pub struct IdentityOidcIntrospectRequest {
    /// Signed OIDC token to verify.
    pub token: SecretString,
    /// Optional audience/client ID requirement.
    pub client_id: Option<String>,
}

impl IdentityOidcIntrospectRequest {
    /// Creates an introspection request.
    pub fn new(token: SecretString) -> Self {
        Self {
            token,
            client_id: None,
        }
    }

    /// Requires the token audience to match `client_id`.
    #[must_use]
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }
}

impl fmt::Debug for IdentityOidcIntrospectRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityOidcIntrospectRequest")
            .field("token", &"<redacted>")
            .field("client_id", &self.client_id)
            .finish()
    }
}

/// Identity OIDC introspection response.
#[derive(Clone, Debug, Default)]
pub struct IdentityOidcIntrospection {
    /// Whether OpenBao considers the token active.
    pub active: bool,
    /// Additional RFC 7662/OpenBao claims returned by the endpoint.
    pub extra: BTreeMap<String, JsonValue>,
}

impl<'de> Deserialize<'de> for IdentityOidcIntrospection {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut extra = deserialize_bounded_json_map(deserializer)?;
        let active = extra
            .remove("active")
            .map(serde_json::from_value::<bool>)
            .transpose()
            .map_err(serde::de::Error::custom)?
            .unwrap_or(false);
        Ok(Self { active, extra })
    }
}

/// OIDC discovery metadata returned by OpenBao.
#[derive(Clone, Debug, Default)]
pub struct IdentityOidcDiscovery {
    /// Issuer URL.
    pub issuer: Option<String>,
    /// Authorization endpoint.
    pub authorization_endpoint: Option<String>,
    /// Token endpoint.
    pub token_endpoint: Option<String>,
    /// JWKS URI.
    pub jwks_uri: Option<String>,
    /// Supported response types.
    pub response_types_supported: Option<Vec<String>>,
    /// Supported subject types.
    pub subject_types_supported: Option<Vec<String>>,
    /// Supported ID-token signing algorithms.
    pub id_token_signing_alg_values_supported: Option<Vec<String>>,
    /// Supported scopes.
    pub scopes_supported: Option<Vec<String>>,
    /// Supported token endpoint authentication methods.
    pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
    /// Supported claims.
    pub claims_supported: Option<Vec<String>>,
    /// Additional provider metadata claims.
    pub extra: BTreeMap<String, JsonValue>,
}

impl<'de> Deserialize<'de> for IdentityOidcDiscovery {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut extra = deserialize_bounded_json_map(deserializer)?;
        Ok(Self {
            issuer: take_optional_string::<D::Error>(&mut extra, "issuer")?,
            authorization_endpoint: take_optional_string::<D::Error>(
                &mut extra,
                "authorization_endpoint",
            )?,
            token_endpoint: take_optional_string::<D::Error>(&mut extra, "token_endpoint")?,
            jwks_uri: take_optional_string::<D::Error>(&mut extra, "jwks_uri")?,
            response_types_supported: take_optional_string_vec::<D::Error>(
                &mut extra,
                "response_types_supported",
            )?,
            subject_types_supported: take_optional_string_vec::<D::Error>(
                &mut extra,
                "subject_types_supported",
            )?,
            id_token_signing_alg_values_supported: take_optional_string_vec::<D::Error>(
                &mut extra,
                "id_token_signing_alg_values_supported",
            )?,
            scopes_supported: take_optional_string_vec::<D::Error>(&mut extra, "scopes_supported")?,
            token_endpoint_auth_methods_supported: take_optional_string_vec::<D::Error>(
                &mut extra,
                "token_endpoint_auth_methods_supported",
            )?,
            claims_supported: take_optional_string_vec::<D::Error>(&mut extra, "claims_supported")?,
            extra,
        })
    }
}

/// OIDC JSON Web Key Set returned by OpenBao.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcJwks {
    /// Public JWK entries.
    #[serde(default, deserialize_with = "deserialize_bounded_json_vec")]
    pub keys: Vec<JsonValue>,
}

/// Request to create or update an Identity OIDC provider.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcProviderRequest {
    /// Issuer URL override for provider-issued tokens.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer: Option<String>,
    /// Client IDs permitted to use the provider. Use `"*"` to allow all clients.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_client_ids: Vec<String>,
    /// Scopes available for requesting on the provider.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub scopes_supported: Vec<String>,
}

impl IdentityOidcProviderRequest {
    /// Creates an empty provider request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the issuer URL override.
    #[must_use]
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Adds an allowed client ID.
    #[must_use]
    pub fn with_allowed_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.allowed_client_ids.push(client_id.into());
        self
    }

    /// Adds a supported scope.
    #[must_use]
    pub fn with_scope_supported(mut self, scope: impl Into<String>) -> Self {
        self.scopes_supported.push(scope.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(
            self.allowed_client_ids.len(),
            "identity OIDC provider allowed client IDs",
        )?;
        validate_string_count(
            self.scopes_supported.len(),
            "identity OIDC provider supported scopes",
        )
    }
}

/// Identity OIDC provider information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcProviderInfo {
    /// Issuer URL override.
    #[serde(default)]
    pub issuer: Option<String>,
    /// Client IDs permitted to use the provider.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub allowed_client_ids: Vec<String>,
    /// Scopes available for requesting on the provider.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub scopes_supported: Vec<String>,
}

/// Identity OIDC provider list response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcProviderList {
    /// Provider names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
    /// Provider metadata keyed by provider name.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_oidc_provider_info_map"
    )]
    pub key_info: BTreeMap<String, IdentityOidcProviderInfo>,
}

impl ListEntries for IdentityOidcProviderList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to create or update an Identity OIDC scope.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcScopeRequest {
    /// JSON or base64-encoded JSON template for the scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
    /// Human-readable scope description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl IdentityOidcScopeRequest {
    /// Creates an empty scope request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the scope template.
    #[must_use]
    pub fn with_template(mut self, template: impl Into<String>) -> Self {
        self.template = Some(template.into());
        self
    }

    /// Sets the scope description.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Identity OIDC scope information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcScopeInfo {
    /// Scope template.
    #[serde(default)]
    pub template: Option<String>,
    /// Scope description.
    #[serde(default)]
    pub description: Option<String>,
}

/// Identity OIDC scope list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityOidcScopeList {
    /// Scope names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityOidcScopeList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Identity OIDC client type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IdentityOidcClientType {
    /// Confidential client with a client secret.
    Confidential,
    /// Public client requiring PKCE for authorization-code flow.
    Public,
}

impl IdentityOidcClientType {
    fn as_str(self) -> &'static str {
        match self {
            Self::Confidential => "confidential",
            Self::Public => "public",
        }
    }
}

impl Serialize for IdentityOidcClientType {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for IdentityOidcClientType {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            "confidential" => Ok(Self::Confidential),
            "public" => Ok(Self::Public),
            _ => Err(serde::de::Error::custom(
                "unsupported identity OIDC client type",
            )),
        }
    }
}

/// Request to create or update an Identity OIDC client.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcClientRequest {
    /// Signing key name. OpenBao defaults to `default` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// Redirect URIs accepted by the client.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub redirect_uris: Vec<String>,
    /// Assignment resources associated with the client.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub assignments: Vec<String>,
    /// Client type. This cannot be modified after creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_type: Option<IdentityOidcClientType>,
    /// ID token TTL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id_token_ttl: Option<String>,
    /// Access token TTL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub access_token_ttl: Option<String>,
}

impl IdentityOidcClientRequest {
    /// Creates an empty client request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the signing key.
    #[must_use]
    pub fn with_key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Adds a redirect URI.
    #[must_use]
    pub fn with_redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
        self.redirect_uris.push(redirect_uri.into());
        self
    }

    /// Adds an assignment name.
    #[must_use]
    pub fn with_assignment(mut self, assignment: impl Into<String>) -> Self {
        self.assignments.push(assignment.into());
        self
    }

    /// Sets the client type.
    #[must_use]
    pub fn with_client_type(mut self, client_type: IdentityOidcClientType) -> Self {
        self.client_type = Some(client_type);
        self
    }

    /// Sets the ID token TTL.
    #[must_use]
    pub fn with_id_token_ttl(mut self, ttl: impl Into<String>) -> Self {
        self.id_token_ttl = Some(ttl.into());
        self
    }

    /// Sets the access token TTL.
    #[must_use]
    pub fn with_access_token_ttl(mut self, ttl: impl Into<String>) -> Self {
        self.access_token_ttl = Some(ttl.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(
            self.redirect_uris.len(),
            "identity OIDC client redirect URIs",
        )?;
        validate_string_count(self.assignments.len(), "identity OIDC client assignments")?;
        if let Some(ttl) = &self.id_token_ttl {
            validate_duration_parameter(ttl, "identity OIDC client id_token_ttl")?;
        }
        if let Some(ttl) = &self.access_token_ttl {
            validate_duration_parameter(ttl, "identity OIDC client access_token_ttl")?;
        }
        Ok(())
    }
}

/// Identity OIDC client information.
#[derive(Clone, Default, Deserialize)]
pub struct IdentityOidcClientInfo {
    /// Access token TTL in seconds.
    #[serde(default)]
    pub access_token_ttl: Option<u64>,
    /// Client assignments.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub assignments: Vec<String>,
    /// Generated client ID.
    #[serde(default)]
    pub client_id: Option<String>,
    /// Generated client secret for confidential clients.
    #[serde(default)]
    pub client_secret: Option<SecretString>,
    /// Client type.
    #[serde(default)]
    pub client_type: Option<IdentityOidcClientType>,
    /// ID token TTL in seconds.
    #[serde(default)]
    pub id_token_ttl: Option<u64>,
    /// Signing key name.
    #[serde(default)]
    pub key: Option<String>,
    /// Redirect URIs accepted by the client.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub redirect_uris: Vec<String>,
}

impl fmt::Debug for IdentityOidcClientInfo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityOidcClientInfo")
            .field("access_token_ttl", &self.access_token_ttl)
            .field("assignments", &self.assignments)
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "<redacted>"),
            )
            .field("client_type", &self.client_type)
            .field("id_token_ttl", &self.id_token_ttl)
            .field("key", &self.key)
            .field("redirect_uris", &self.redirect_uris)
            .finish()
    }
}

/// Identity OIDC client list response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcClientList {
    /// Client names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
    /// Client metadata keyed by client name.
    #[serde(default, deserialize_with = "deserialize_bounded_oidc_client_info_map")]
    pub key_info: BTreeMap<String, IdentityOidcClientInfo>,
}

impl ListEntries for IdentityOidcClientList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to create or update an Identity OIDC assignment.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityOidcAssignmentRequest {
    /// Entity IDs allowed by the assignment.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub entity_ids: Vec<String>,
    /// Group IDs allowed by the assignment.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub group_ids: Vec<String>,
}

impl IdentityOidcAssignmentRequest {
    /// Creates an empty assignment request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an entity ID.
    #[must_use]
    pub fn with_entity_id(mut self, entity_id: impl Into<String>) -> Self {
        self.entity_ids.push(entity_id.into());
        self
    }

    /// Adds a group ID.
    #[must_use]
    pub fn with_group_id(mut self, group_id: impl Into<String>) -> Self {
        self.group_ids.push(group_id.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_string_count(self.entity_ids.len(), "identity OIDC assignment entity IDs")?;
        validate_string_count(self.group_ids.len(), "identity OIDC assignment group IDs")
    }
}

/// Identity OIDC assignment information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityOidcAssignmentInfo {
    /// Entity IDs allowed by the assignment.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub entity_ids: Vec<String>,
    /// Group IDs allowed by the assignment.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub group_ids: Vec<String>,
}

/// Identity OIDC assignment list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityOidcAssignmentList {
    /// Assignment names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityOidcAssignmentList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to create or update a Duo MFA method.
#[derive(Clone)]
pub struct IdentityMfaDuoMethodRequest {
    /// Unique method name.
    pub method_name: String,
    /// Identity username template.
    pub username_format: Option<String>,
    /// Duo secret key.
    pub secret_key: SecretString,
    /// Duo integration key.
    pub integration_key: SecretString,
    /// Duo API hostname.
    pub api_hostname: String,
    /// Duo push information.
    pub push_info: Option<String>,
    /// Whether passcode validation is used.
    pub use_passcode: Option<bool>,
}

impl IdentityMfaDuoMethodRequest {
    /// Creates a Duo MFA method request.
    pub fn new(
        method_name: impl Into<String>,
        secret_key: SecretString,
        integration_key: SecretString,
        api_hostname: impl Into<String>,
    ) -> Self {
        Self {
            method_name: method_name.into(),
            username_format: None,
            secret_key,
            integration_key,
            api_hostname: api_hostname.into(),
            push_info: None,
            use_passcode: None,
        }
    }

    /// Sets the Identity username template.
    #[must_use]
    pub fn with_username_format(mut self, username_format: impl Into<String>) -> Self {
        self.username_format = Some(username_format.into());
        self
    }

    /// Sets Duo push information.
    #[must_use]
    pub fn with_push_info(mut self, push_info: impl Into<String>) -> Self {
        self.push_info = Some(push_info.into());
        self
    }

    /// Sets whether passcode validation is used.
    #[must_use]
    pub fn with_use_passcode(mut self, use_passcode: bool) -> Self {
        self.use_passcode = Some(use_passcode);
        self
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_name, "identity MFA Duo method_name")?;
        validate_required(&self.api_hostname, "identity MFA Duo api_hostname")
    }
}

impl fmt::Debug for IdentityMfaDuoMethodRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaDuoMethodRequest")
            .field("method_name", &self.method_name)
            .field("username_format", &self.username_format)
            .field("secret_key", &"<redacted>")
            .field("integration_key", &"<redacted>")
            .field("api_hostname", &self.api_hostname)
            .field("push_info", &self.push_info)
            .field("use_passcode", &self.use_passcode)
            .finish()
    }
}

impl Serialize for IdentityMfaDuoMethodRequest {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("method_name", &self.method_name)?;
        serialize_optional_entry(&mut map, "username_format", self.username_format.as_deref())?;
        map.serialize_entry("secret_key", self.secret_key.expose_secret())?;
        map.serialize_entry("integration_key", self.integration_key.expose_secret())?;
        map.serialize_entry("api_hostname", &self.api_hostname)?;
        serialize_optional_entry(&mut map, "push_info", self.push_info.as_deref())?;
        if let Some(use_passcode) = self.use_passcode {
            map.serialize_entry("use_passcode", &use_passcode)?;
        }
        map.end()
    }
}

/// Duo MFA method information.
#[derive(Clone, Deserialize)]
pub struct IdentityMfaDuoMethodInfo {
    /// Method ID.
    #[serde(default)]
    pub id: Option<String>,
    /// Method name.
    #[serde(default, alias = "name")]
    pub method_name: Option<String>,
    /// Identity username template.
    #[serde(default)]
    pub username_format: Option<String>,
    /// Duo secret key.
    #[serde(default)]
    pub secret_key: Option<SecretString>,
    /// Duo integration key.
    #[serde(default)]
    pub integration_key: Option<SecretString>,
    /// Duo API hostname.
    #[serde(default)]
    pub api_hostname: Option<String>,
    /// Duo push information.
    #[serde(default, alias = "pushinfo")]
    pub push_info: Option<String>,
    /// Whether passcode validation is used.
    #[serde(default)]
    pub use_passcode: Option<bool>,
    /// Method type.
    #[serde(default, rename = "type")]
    pub method_type: Option<String>,
}

impl fmt::Debug for IdentityMfaDuoMethodInfo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaDuoMethodInfo")
            .field("id", &self.id)
            .field("method_name", &self.method_name)
            .field("username_format", &self.username_format)
            .field(
                "secret_key",
                &self.secret_key.as_ref().map(|_| "<redacted>"),
            )
            .field(
                "integration_key",
                &self.integration_key.as_ref().map(|_| "<redacted>"),
            )
            .field("api_hostname", &self.api_hostname)
            .field("push_info", &self.push_info)
            .field("use_passcode", &self.use_passcode)
            .field("method_type", &self.method_type)
            .finish()
    }
}

/// Request to create or update an Okta MFA method.
#[derive(Clone)]
pub struct IdentityMfaOktaMethodRequest {
    /// Unique method name.
    pub method_name: String,
    /// Identity username template.
    pub username_format: Option<String>,
    /// Okta organization name.
    pub org_name: String,
    /// Okta API token.
    pub api_token: SecretString,
    /// Okta base URL.
    pub base_url: Option<String>,
    /// Whether usernames must match primary email.
    pub primary_email: Option<bool>,
}

impl IdentityMfaOktaMethodRequest {
    /// Creates an Okta MFA method request.
    pub fn new(
        method_name: impl Into<String>,
        org_name: impl Into<String>,
        api_token: SecretString,
    ) -> Self {
        Self {
            method_name: method_name.into(),
            username_format: None,
            org_name: org_name.into(),
            api_token,
            base_url: None,
            primary_email: None,
        }
    }

    /// Sets the Identity username template.
    #[must_use]
    pub fn with_username_format(mut self, username_format: impl Into<String>) -> Self {
        self.username_format = Some(username_format.into());
        self
    }

    /// Sets the Okta base URL.
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Sets whether primary email matching is required.
    #[must_use]
    pub fn with_primary_email(mut self, primary_email: bool) -> Self {
        self.primary_email = Some(primary_email);
        self
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_name, "identity MFA Okta method_name")?;
        validate_required(&self.org_name, "identity MFA Okta org_name")
    }
}

impl fmt::Debug for IdentityMfaOktaMethodRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaOktaMethodRequest")
            .field("method_name", &self.method_name)
            .field("username_format", &self.username_format)
            .field("org_name", &self.org_name)
            .field("api_token", &"<redacted>")
            .field("base_url", &self.base_url)
            .field("primary_email", &self.primary_email)
            .finish()
    }
}

impl Serialize for IdentityMfaOktaMethodRequest {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("method_name", &self.method_name)?;
        serialize_optional_entry(&mut map, "username_format", self.username_format.as_deref())?;
        map.serialize_entry("org_name", &self.org_name)?;
        map.serialize_entry("api_token", self.api_token.expose_secret())?;
        serialize_optional_entry(&mut map, "base_url", self.base_url.as_deref())?;
        if let Some(primary_email) = self.primary_email {
            map.serialize_entry("primary_email", &primary_email)?;
        }
        map.end()
    }
}

/// Okta MFA method information.
#[derive(Clone, Deserialize)]
pub struct IdentityMfaOktaMethodInfo {
    /// Method ID.
    #[serde(default)]
    pub id: Option<String>,
    /// Method name.
    #[serde(default, alias = "name")]
    pub method_name: Option<String>,
    /// Identity username template.
    #[serde(default)]
    pub username_format: Option<String>,
    /// Okta organization name.
    #[serde(default)]
    pub org_name: Option<String>,
    /// Okta API token.
    #[serde(default)]
    pub api_token: Option<SecretString>,
    /// Okta base URL.
    #[serde(default)]
    pub base_url: Option<String>,
    /// Whether usernames must match primary email.
    #[serde(default)]
    pub primary_email: Option<bool>,
    /// Method type.
    #[serde(default, rename = "type")]
    pub method_type: Option<String>,
}

impl fmt::Debug for IdentityMfaOktaMethodInfo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaOktaMethodInfo")
            .field("id", &self.id)
            .field("method_name", &self.method_name)
            .field("username_format", &self.username_format)
            .field("org_name", &self.org_name)
            .field("api_token", &self.api_token.as_ref().map(|_| "<redacted>"))
            .field("base_url", &self.base_url)
            .field("primary_email", &self.primary_email)
            .field("method_type", &self.method_type)
            .finish()
    }
}

/// Request to create or update a PingID MFA method.
#[derive(Clone)]
pub struct IdentityMfaPingIdMethodRequest {
    /// Unique method name.
    pub method_name: String,
    /// Identity username template.
    pub username_format: Option<String>,
    /// Base64-encoded PingID settings file.
    pub settings_file_base64: SecretString,
}

impl IdentityMfaPingIdMethodRequest {
    /// Creates a PingID MFA method request.
    pub fn new(method_name: impl Into<String>, settings_file_base64: SecretString) -> Self {
        Self {
            method_name: method_name.into(),
            username_format: None,
            settings_file_base64,
        }
    }

    /// Sets the Identity username template.
    #[must_use]
    pub fn with_username_format(mut self, username_format: impl Into<String>) -> Self {
        self.username_format = Some(username_format.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_name, "identity MFA PingID method_name")
    }
}

impl fmt::Debug for IdentityMfaPingIdMethodRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaPingIdMethodRequest")
            .field("method_name", &self.method_name)
            .field("username_format", &self.username_format)
            .field("settings_file_base64", &"<redacted>")
            .finish()
    }
}

impl Serialize for IdentityMfaPingIdMethodRequest {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("method_name", &self.method_name)?;
        serialize_optional_entry(&mut map, "username_format", self.username_format.as_deref())?;
        map.serialize_entry(
            "settings_file_base64",
            self.settings_file_base64.expose_secret(),
        )?;
        map.end()
    }
}

/// PingID MFA method information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityMfaPingIdMethodInfo {
    /// Method ID.
    #[serde(default)]
    pub id: Option<String>,
    /// Method name.
    #[serde(default, alias = "name")]
    pub method_name: Option<String>,
    /// Identity username template.
    #[serde(default)]
    pub username_format: Option<String>,
    /// PingID identity provider URL.
    #[serde(default)]
    pub idp_url: Option<String>,
    /// PingID admin URL.
    #[serde(default)]
    pub admin_url: Option<String>,
    /// PingID authenticator URL.
    #[serde(default)]
    pub authenticator_url: Option<String>,
    /// PingID organization alias.
    #[serde(default)]
    pub org_alias: Option<String>,
    /// Whether signatures are used.
    #[serde(default)]
    pub use_signature: Option<bool>,
    /// Method type.
    #[serde(default, rename = "type")]
    pub method_type: Option<String>,
}

/// Request to create or update a TOTP MFA method.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityMfaTotpMethodRequest {
    /// Unique method name.
    pub method_name: String,
    /// TOTP issuer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer: Option<String>,
    /// TOTP period in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<u64>,
    /// Generated key size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_size: Option<u64>,
    /// QR code size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qr_size: Option<u64>,
    /// Hash algorithm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algorithm: Option<String>,
    /// Number of TOTP digits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digits: Option<u64>,
    /// Accepted skew.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skew: Option<u64>,
    /// Maximum validation attempts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_validation_attempts: Option<u64>,
}

impl IdentityMfaTotpMethodRequest {
    /// Creates a TOTP MFA method request.
    pub fn new(method_name: impl Into<String>) -> Self {
        Self {
            method_name: method_name.into(),
            ..Self::default()
        }
    }

    /// Sets the TOTP issuer.
    #[must_use]
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_name, "identity MFA TOTP method_name")
    }
}

/// TOTP MFA method information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityMfaTotpMethodInfo {
    /// Method ID.
    #[serde(default)]
    pub id: Option<String>,
    /// Method name.
    #[serde(default, alias = "name")]
    pub method_name: Option<String>,
    /// TOTP issuer.
    #[serde(default)]
    pub issuer: Option<String>,
    /// TOTP period in seconds.
    #[serde(default)]
    pub period: Option<u64>,
    /// Generated key size.
    #[serde(default)]
    pub key_size: Option<u64>,
    /// QR code size.
    #[serde(default)]
    pub qr_size: Option<u64>,
    /// Hash algorithm.
    #[serde(default)]
    pub algorithm: Option<String>,
    /// Number of TOTP digits.
    #[serde(default)]
    pub digits: Option<u64>,
    /// Accepted skew.
    #[serde(default)]
    pub skew: Option<u64>,
    /// Maximum validation attempts.
    #[serde(default)]
    pub max_validation_attempts: Option<u64>,
    /// Method type.
    #[serde(default, rename = "type")]
    pub method_type: Option<String>,
}

/// Identity MFA method list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityMfaMethodList {
    /// MFA method IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityMfaMethodList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Request to generate a TOTP MFA secret.
#[derive(Clone, Debug, Serialize)]
pub struct IdentityMfaTotpGenerateRequest {
    /// TOTP MFA method ID.
    pub method_id: String,
}

impl IdentityMfaTotpGenerateRequest {
    /// Creates a TOTP generation request.
    pub fn new(method_id: impl Into<String>) -> Self {
        Self {
            method_id: method_id.into(),
        }
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_id, "identity MFA TOTP method_id")
    }
}

/// Request to administratively generate or destroy a TOTP MFA secret.
#[derive(Clone, Debug, Serialize)]
pub struct IdentityMfaTotpAdminRequest {
    /// TOTP MFA method ID.
    pub method_id: String,
    /// Entity ID whose TOTP secret is managed.
    pub entity_id: String,
}

impl IdentityMfaTotpAdminRequest {
    /// Creates an administrative TOTP request.
    pub fn new(method_id: impl Into<String>, entity_id: impl Into<String>) -> Self {
        Self {
            method_id: method_id.into(),
            entity_id: entity_id.into(),
        }
    }

    fn validate(&self) -> Result<()> {
        validate_required(&self.method_id, "identity MFA TOTP method_id")?;
        validate_required(&self.entity_id, "identity MFA TOTP entity_id")
    }
}

/// Generated TOTP MFA secret material.
#[derive(Clone, Deserialize)]
pub struct IdentityMfaTotpSecret {
    /// Base64-encoded QR barcode image. This embeds the generated TOTP secret.
    pub barcode: SecretString,
    /// otpauth URL. This embeds the generated TOTP secret.
    pub url: SecretString,
}

impl fmt::Debug for IdentityMfaTotpSecret {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdentityMfaTotpSecret")
            .field("barcode", &"<redacted>")
            .field("url", &"<redacted>")
            .finish()
    }
}

/// Request to create or update an MFA login enforcement.
#[derive(Clone, Debug, Default, Serialize)]
pub struct IdentityMfaLoginEnforcementRequest {
    /// MFA method IDs. Any one listed method can satisfy this enforcement.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub mfa_method_ids: Vec<String>,
    /// Auth mount accessors to which this enforcement applies.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub auth_method_accessors: Vec<String>,
    /// Auth method types to which this enforcement applies.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub auth_method_types: Vec<String>,
    /// Identity group IDs to which this enforcement applies.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub identity_group_ids: Vec<String>,
    /// Identity entity IDs to which this enforcement applies.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub identity_entity_ids: Vec<String>,
}

impl IdentityMfaLoginEnforcementRequest {
    /// Creates an empty login-enforcement request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an MFA method ID.
    #[must_use]
    pub fn with_mfa_method_id(mut self, method_id: impl Into<String>) -> Self {
        self.mfa_method_ids.push(method_id.into());
        self
    }

    /// Adds an auth method accessor condition.
    #[must_use]
    pub fn with_auth_method_accessor(mut self, accessor: impl Into<String>) -> Self {
        self.auth_method_accessors.push(accessor.into());
        self
    }

    /// Adds an auth method type condition.
    #[must_use]
    pub fn with_auth_method_type(mut self, method_type: impl Into<String>) -> Self {
        self.auth_method_types.push(method_type.into());
        self
    }

    /// Adds an identity group ID condition.
    #[must_use]
    pub fn with_identity_group_id(mut self, group_id: impl Into<String>) -> Self {
        self.identity_group_ids.push(group_id.into());
        self
    }

    /// Adds an identity entity ID condition.
    #[must_use]
    pub fn with_identity_entity_id(mut self, entity_id: impl Into<String>) -> Self {
        self.identity_entity_ids.push(entity_id.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if self.mfa_method_ids.is_empty() {
            return Err(Error::InvalidParameter(
                "identity MFA login enforcement requires at least one MFA method ID".into(),
            ));
        }
        if self.auth_method_accessors.is_empty()
            && self.auth_method_types.is_empty()
            && self.identity_group_ids.is_empty()
            && self.identity_entity_ids.is_empty()
        {
            return Err(Error::InvalidParameter(
                "identity MFA login enforcement requires at least one auth or identity condition"
                    .into(),
            ));
        }
        validate_string_count(
            self.mfa_method_ids.len(),
            "identity MFA login enforcement method IDs",
        )?;
        validate_string_count(
            self.auth_method_accessors.len(),
            "identity MFA login enforcement auth method accessors",
        )?;
        validate_string_count(
            self.auth_method_types.len(),
            "identity MFA login enforcement auth method types",
        )?;
        validate_string_count(
            self.identity_group_ids.len(),
            "identity MFA login enforcement group IDs",
        )?;
        validate_string_count(
            self.identity_entity_ids.len(),
            "identity MFA login enforcement entity IDs",
        )
    }
}

/// MFA login enforcement information.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct IdentityMfaLoginEnforcementInfo {
    /// Enforcement ID.
    #[serde(default)]
    pub id: Option<String>,
    /// Enforcement name.
    #[serde(default)]
    pub name: Option<String>,
    /// Namespace ID.
    #[serde(default)]
    pub namespace_id: Option<String>,
    /// MFA method IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub mfa_method_ids: Vec<String>,
    /// Auth mount accessors.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub auth_method_accessors: Vec<String>,
    /// Auth method types.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub auth_method_types: Vec<String>,
    /// Identity group IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub identity_group_ids: Vec<String>,
    /// Identity entity IDs.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub identity_entity_ids: Vec<String>,
}

/// Identity MFA login enforcement list response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IdentityMfaLoginEnforcementList {
    /// Login-enforcement names.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for IdentityMfaLoginEnforcementList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

impl Client<Authenticated> {
    /// Uses the identity engine mounted at `identity`.
    pub fn identity(&self) -> Result<Identity<'_>> {
        self.identity_at("identity")
    }

    /// Uses the identity engine mounted at `mount`.
    pub fn identity_at(&self, mount: impl Into<String>) -> Result<Identity<'_>> {
        let mount = mount.into();
        Ok(Identity {
            client: self,
            mount: validate_mount_path(&mount)?,
        })
    }
}

impl Identity<'_> {
    /// Creates or updates an entity.
    pub async fn write_entity(
        &self,
        request: &IdentityEntityRequest,
    ) -> Result<IdentityEntityUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityEntityUpsert> = self
            .client
            .request_json(Method::POST, &self.path(&["entity"])?, Some(request))
            .await?;
        Ok(envelope.data)
    }

    /// Reads an entity by ID.
    pub async fn read_entity_by_id(&self, id: &str) -> Result<IdentityEntityInfo> {
        let envelope: ResponseEnvelope<IdentityEntityInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["entity", "id", id])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Updates an entity by ID.
    pub async fn update_entity_by_id(
        &self,
        id: &str,
        request: &IdentityEntityRequest,
    ) -> Result<IdentityEntityUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityEntityUpsert> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["entity", "id", id])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes an entity by ID.
    pub async fn delete_entity_by_id(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["entity", "id", id]).await
    }

    /// Deletes multiple entities by ID.
    pub async fn batch_delete_entities(
        &self,
        request: &IdentityEntityBatchDeleteRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["entity", "batch-delete"])?,
                Some(request),
            )
            .await
    }

    /// Looks up an entity by ID, name, or alias fields.
    pub async fn lookup_entity(
        &self,
        request: &IdentityEntityLookupRequest,
    ) -> Result<IdentityEntityInfo> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityEntityInfo> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["lookup", "entity"])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Merges one or more source entities into a target entity.
    pub async fn merge_entities(&self, request: &IdentityEntityMergeRequest) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["entity", "merge"])?,
                Some(request),
            )
            .await
    }

    /// Lists entity IDs.
    pub async fn list_entity_ids(&self) -> Result<IdentityEntityList> {
        self.list_at(&["entity", "id"]).await
    }

    /// Creates or updates an entity by name.
    pub async fn write_entity_by_name(
        &self,
        name: &str,
        request: &IdentityEntityRequest,
    ) -> Result<IdentityEntityUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityEntityUpsert> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["entity", "name", name])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Reads an entity by name.
    pub async fn read_entity_by_name(&self, name: &str) -> Result<IdentityEntityInfo> {
        let envelope: ResponseEnvelope<IdentityEntityInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["entity", "name", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes an entity by name.
    pub async fn delete_entity_by_name(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["entity", "name", name]).await
    }

    /// Lists entity names.
    pub async fn list_entity_names(&self) -> Result<IdentityEntityList> {
        self.list_at(&["entity", "name"]).await
    }

    /// Creates or updates a group.
    pub async fn write_group(&self, request: &IdentityGroupRequest) -> Result<IdentityGroupUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityGroupUpsert> = self
            .client
            .request_json(Method::POST, &self.path(&["group"])?, Some(request))
            .await?;
        Ok(envelope.data)
    }

    /// Reads a group by ID.
    pub async fn read_group_by_id(&self, id: &str) -> Result<IdentityGroupInfo> {
        let envelope: ResponseEnvelope<IdentityGroupInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["group", "id", id])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Updates a group by ID.
    pub async fn update_group_by_id(
        &self,
        id: &str,
        request: &IdentityGroupRequest,
    ) -> Result<IdentityGroupUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityGroupUpsert> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["group", "id", id])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes a group by ID.
    pub async fn delete_group_by_id(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["group", "id", id]).await
    }

    /// Lists group IDs.
    pub async fn list_group_ids(&self) -> Result<IdentityGroupList> {
        self.list_at(&["group", "id"]).await
    }

    /// Looks up a group by ID, name, or alias fields.
    pub async fn lookup_group(
        &self,
        request: &IdentityGroupLookupRequest,
    ) -> Result<IdentityGroupInfo> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityGroupInfo> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["lookup", "group"])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Creates or updates a group by name.
    pub async fn write_group_by_name(
        &self,
        name: &str,
        request: &IdentityGroupRequest,
    ) -> Result<IdentityGroupUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityGroupUpsert> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["group", "name", name])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Reads a group by name.
    pub async fn read_group_by_name(&self, name: &str) -> Result<IdentityGroupInfo> {
        let envelope: ResponseEnvelope<IdentityGroupInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["group", "name", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes a group by name.
    pub async fn delete_group_by_name(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["group", "name", name]).await
    }

    /// Lists group names.
    pub async fn list_group_names(&self) -> Result<IdentityGroupList> {
        self.list_at(&["group", "name"]).await
    }

    /// Creates or updates an entity alias.
    pub async fn write_entity_alias(
        &self,
        request: &IdentityEntityAliasRequest,
    ) -> Result<IdentityAliasUpsert> {
        request.validate()?;
        let envelope: ResponseEnvelope<IdentityAliasUpsert> = self
            .client
            .request_json(Method::POST, &self.path(&["entity-alias"])?, Some(request))
            .await?;
        Ok(envelope.data)
    }

    /// Reads an entity alias by ID.
    pub async fn read_entity_alias_by_id(&self, id: &str) -> Result<IdentityAliasInfo> {
        let envelope: ResponseEnvelope<IdentityAliasInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["entity-alias", "id", id])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes an entity alias by ID.
    pub async fn delete_entity_alias_by_id(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["entity-alias", "id", id]).await
    }

    /// Lists entity alias IDs.
    pub async fn list_entity_alias_ids(&self) -> Result<IdentityAliasList> {
        self.list_at(&["entity-alias", "id"]).await
    }

    /// Creates or updates a group alias.
    pub async fn write_group_alias(
        &self,
        request: &IdentityGroupAliasRequest,
    ) -> Result<IdentityAliasUpsert> {
        let envelope: ResponseEnvelope<IdentityAliasUpsert> = self
            .client
            .request_json(Method::POST, &self.path(&["group-alias"])?, Some(request))
            .await?;
        Ok(envelope.data)
    }

    /// Reads a group alias by ID.
    pub async fn read_group_alias_by_id(&self, id: &str) -> Result<IdentityAliasInfo> {
        let envelope: ResponseEnvelope<IdentityAliasInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["group-alias", "id", id])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes a group alias by ID.
    pub async fn delete_group_alias_by_id(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["group-alias", "id", id]).await
    }

    /// Lists group alias IDs.
    pub async fn list_group_alias_ids(&self) -> Result<IdentityAliasList> {
        self.list_at(&["group-alias", "id"]).await
    }

    /// Writes Identity OIDC token backend configuration.
    pub async fn write_oidc_config(&self, request: &IdentityOidcConfigRequest) -> Result<Empty> {
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "config"])?,
                Some(request),
            )
            .await
    }

    /// Reads Identity OIDC token backend configuration.
    pub async fn read_oidc_config(&self) -> Result<IdentityOidcConfig> {
        let envelope: ResponseEnvelope<IdentityOidcConfig> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "config"])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Creates or updates an Identity OIDC signing key.
    pub async fn write_oidc_key(
        &self,
        name: &str,
        request: &IdentityOidcKeyRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "key", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC signing key.
    pub async fn read_oidc_key(&self, name: &str) -> Result<IdentityOidcKeyInfo> {
        let envelope: ResponseEnvelope<IdentityOidcKeyInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "key", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes an Identity OIDC signing key.
    pub async fn delete_oidc_key(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "key", name]).await
    }

    /// Lists Identity OIDC signing keys.
    pub async fn list_oidc_keys(&self) -> Result<IdentityOidcKeyList> {
        self.list_at(&["oidc", "key"]).await
    }

    /// Rotates an Identity OIDC signing key.
    pub async fn rotate_oidc_key(
        &self,
        name: &str,
        request: &IdentityOidcKeyRotateRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "key", name, "rotate"])?,
                Some(request),
            )
            .await
    }

    /// Creates or updates an Identity OIDC role.
    pub async fn write_oidc_role(
        &self,
        name: &str,
        request: &IdentityOidcRoleRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "role", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC role.
    pub async fn read_oidc_role(&self, name: &str) -> Result<IdentityOidcRoleInfo> {
        let envelope: ResponseEnvelope<IdentityOidcRoleInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "role", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes an Identity OIDC role.
    pub async fn delete_oidc_role(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "role", name]).await
    }

    /// Lists Identity OIDC roles.
    pub async fn list_oidc_roles(&self) -> Result<IdentityOidcRoleList> {
        self.list_at(&["oidc", "role"]).await
    }

    /// Generates a signed Identity OIDC ID token for `name`.
    pub async fn generate_oidc_token(&self, name: &str) -> Result<IdentityOidcToken> {
        let envelope: ResponseEnvelope<IdentityOidcToken> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "token", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Introspects a signed Identity OIDC token.
    ///
    /// The token is exposed only while serializing the request body.
    pub async fn introspect_oidc_token(
        &self,
        request: &IdentityOidcIntrospectRequest,
    ) -> Result<IdentityOidcIntrospection> {
        let payload = IdentityOidcIntrospectPayload {
            token: request.token.expose_secret(),
            client_id: request.client_id.as_deref(),
        };
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "introspect"])?,
                Some(&payload),
            )
            .await
    }

    /// Reads OIDC provider discovery metadata for the identity token backend.
    ///
    /// OpenBao serves this as a plain OIDC response, not a `data` envelope.
    pub async fn read_oidc_discovery(&self) -> Result<IdentityOidcDiscovery> {
        self.client
            .request_json(
                Method::GET,
                &self.path(&["oidc", ".well-known", "openid-configuration"])?,
                Option::<&Empty>::None,
            )
            .await
    }

    /// Reads public OIDC JSON Web Keys for the identity token backend.
    ///
    /// The returned keys are public verification material. The list is still
    /// bounded during deserialization to avoid disproportionate allocations.
    pub async fn read_oidc_jwks(&self) -> Result<IdentityOidcJwks> {
        self.client
            .request_json(
                Method::GET,
                &self.path(&["oidc", ".well-known", "keys"])?,
                Option::<&Empty>::None,
            )
            .await
    }

    /// Creates or updates an Identity OIDC provider.
    pub async fn write_oidc_provider(
        &self,
        name: &str,
        request: &IdentityOidcProviderRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "provider", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC provider.
    pub async fn read_oidc_provider(&self, name: &str) -> Result<IdentityOidcProviderInfo> {
        let envelope: ResponseEnvelope<IdentityOidcProviderInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "provider", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists Identity OIDC providers.
    pub async fn list_oidc_providers(&self) -> Result<IdentityOidcProviderList> {
        self.list_oidc_providers_with_client_id(None).await
    }

    /// Lists Identity OIDC providers available to `client_id`.
    pub async fn list_oidc_providers_for_client_id(
        &self,
        client_id: &str,
    ) -> Result<IdentityOidcProviderList> {
        if client_id.trim().is_empty() {
            return Err(Error::InvalidParameter(
                "identity OIDC provider client_id must not be empty".into(),
            ));
        }
        self.list_oidc_providers_with_client_id(Some(client_id))
            .await
    }

    /// Deletes an Identity OIDC provider.
    pub async fn delete_oidc_provider(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "provider", name]).await
    }

    /// Creates or updates an Identity OIDC scope.
    pub async fn write_oidc_scope(
        &self,
        name: &str,
        request: &IdentityOidcScopeRequest,
    ) -> Result<Empty> {
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "scope", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC scope.
    pub async fn read_oidc_scope(&self, name: &str) -> Result<IdentityOidcScopeInfo> {
        let envelope: ResponseEnvelope<IdentityOidcScopeInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "scope", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists Identity OIDC scopes.
    pub async fn list_oidc_scopes(&self) -> Result<IdentityOidcScopeList> {
        self.list_at(&["oidc", "scope"]).await
    }

    /// Deletes an Identity OIDC scope.
    pub async fn delete_oidc_scope(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "scope", name]).await
    }

    /// Creates or updates an Identity OIDC client.
    pub async fn write_oidc_client(
        &self,
        name: &str,
        request: &IdentityOidcClientRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "client", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC client.
    pub async fn read_oidc_client(&self, name: &str) -> Result<IdentityOidcClientInfo> {
        let envelope: ResponseEnvelope<IdentityOidcClientInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "client", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists Identity OIDC clients.
    pub async fn list_oidc_clients(&self) -> Result<IdentityOidcClientList> {
        self.list_at(&["oidc", "client"]).await
    }

    /// Deletes an Identity OIDC client.
    pub async fn delete_oidc_client(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "client", name]).await
    }

    /// Creates or updates an Identity OIDC assignment.
    pub async fn write_oidc_assignment(
        &self,
        name: &str,
        request: &IdentityOidcAssignmentRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["oidc", "assignment", name])?,
                Some(request),
            )
            .await
    }

    /// Reads an Identity OIDC assignment.
    pub async fn read_oidc_assignment(&self, name: &str) -> Result<IdentityOidcAssignmentInfo> {
        let envelope: ResponseEnvelope<IdentityOidcAssignmentInfo> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "assignment", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists Identity OIDC assignments.
    pub async fn list_oidc_assignments(&self) -> Result<IdentityOidcAssignmentList> {
        self.list_at(&["oidc", "assignment"]).await
    }

    /// Deletes an Identity OIDC assignment.
    pub async fn delete_oidc_assignment(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["oidc", "assignment", name]).await
    }

    /// Reads OIDC discovery metadata for a named provider.
    ///
    /// The named-provider `/authorize`, `/token`, and `/userinfo` protocol
    /// flows are intentionally outside this SDK; pass this metadata to a real
    /// OIDC client library for browser-based flows.
    pub async fn read_oidc_provider_discovery(&self, name: &str) -> Result<IdentityOidcDiscovery> {
        self.client
            .request_json(
                Method::GET,
                &self.path(&[
                    "oidc",
                    "provider",
                    name,
                    ".well-known",
                    "openid-configuration",
                ])?,
                Option::<&Empty>::None,
            )
            .await
    }

    /// Reads public OIDC JSON Web Keys for a named provider.
    pub async fn read_oidc_provider_jwks(&self, name: &str) -> Result<IdentityOidcJwks> {
        self.client
            .request_json(
                Method::GET,
                &self.path(&["oidc", "provider", name, ".well-known", "keys"])?,
                Option::<&Empty>::None,
            )
            .await
    }

    /// Creates a Duo MFA method with a generated method ID.
    pub async fn create_mfa_duo_method(
        &self,
        request: &IdentityMfaDuoMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "duo"], request).await
    }

    /// Creates or updates a Duo MFA method by method ID.
    pub async fn write_mfa_duo_method(
        &self,
        method_id: &str,
        request: &IdentityMfaDuoMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "duo", method_id], request)
            .await
    }

    /// Reads a Duo MFA method by ID.
    pub async fn read_mfa_duo_method(&self, id: &str) -> Result<IdentityMfaDuoMethodInfo> {
        self.read_at(&["mfa", "method", "duo", id]).await
    }

    /// Deletes a Duo MFA method by ID.
    pub async fn delete_mfa_duo_method(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["mfa", "method", "duo", id]).await
    }

    /// Lists Duo MFA methods.
    pub async fn list_mfa_duo_methods(&self) -> Result<IdentityMfaMethodList> {
        self.list_at(&["mfa", "method", "duo"]).await
    }

    /// Creates an Okta MFA method with a generated method ID.
    pub async fn create_mfa_okta_method(
        &self,
        request: &IdentityMfaOktaMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "okta"], request).await
    }

    /// Creates or updates an Okta MFA method by method ID.
    pub async fn write_mfa_okta_method(
        &self,
        method_id: &str,
        request: &IdentityMfaOktaMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "okta", method_id], request)
            .await
    }

    /// Reads an Okta MFA method by ID.
    pub async fn read_mfa_okta_method(&self, id: &str) -> Result<IdentityMfaOktaMethodInfo> {
        self.read_at(&["mfa", "method", "okta", id]).await
    }

    /// Deletes an Okta MFA method by ID.
    pub async fn delete_mfa_okta_method(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["mfa", "method", "okta", id]).await
    }

    /// Lists Okta MFA methods.
    pub async fn list_mfa_okta_methods(&self) -> Result<IdentityMfaMethodList> {
        self.list_at(&["mfa", "method", "okta"]).await
    }

    /// Creates a PingID MFA method with a generated method ID.
    pub async fn create_mfa_pingid_method(
        &self,
        request: &IdentityMfaPingIdMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "pingid"], request).await
    }

    /// Creates or updates a PingID MFA method by method ID.
    pub async fn write_mfa_pingid_method(
        &self,
        method_id: &str,
        request: &IdentityMfaPingIdMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "pingid", method_id], request)
            .await
    }

    /// Reads a PingID MFA method by ID.
    pub async fn read_mfa_pingid_method(&self, id: &str) -> Result<IdentityMfaPingIdMethodInfo> {
        self.read_at(&["mfa", "method", "pingid", id]).await
    }

    /// Deletes a PingID MFA method by ID.
    pub async fn delete_mfa_pingid_method(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["mfa", "method", "pingid", id]).await
    }

    /// Lists PingID MFA methods.
    pub async fn list_mfa_pingid_methods(&self) -> Result<IdentityMfaMethodList> {
        self.list_at(&["mfa", "method", "pingid"]).await
    }

    /// Creates a TOTP MFA method with a generated method ID.
    pub async fn create_mfa_totp_method(
        &self,
        request: &IdentityMfaTotpMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "totp"], request).await
    }

    /// Creates or updates a TOTP MFA method by method ID.
    pub async fn write_mfa_totp_method(
        &self,
        method_id: &str,
        request: &IdentityMfaTotpMethodRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "totp", method_id], request)
            .await
    }

    /// Reads a TOTP MFA method by ID.
    pub async fn read_mfa_totp_method(&self, id: &str) -> Result<IdentityMfaTotpMethodInfo> {
        self.read_at(&["mfa", "method", "totp", id]).await
    }

    /// Deletes a TOTP MFA method by ID.
    pub async fn delete_mfa_totp_method(&self, id: &str) -> Result<Empty> {
        self.delete_at(&["mfa", "method", "totp", id]).await
    }

    /// Lists TOTP MFA methods.
    pub async fn list_mfa_totp_methods(&self) -> Result<IdentityMfaMethodList> {
        self.list_at(&["mfa", "method", "totp"]).await
    }

    /// Generates a TOTP MFA secret for the calling token entity.
    pub async fn generate_mfa_totp_secret(
        &self,
        request: &IdentityMfaTotpGenerateRequest,
    ) -> Result<IdentityMfaTotpSecret> {
        request.validate()?;
        self.post_data(&["mfa", "method", "totp", "generate"], request)
            .await
    }

    /// Administratively generates a TOTP MFA secret for an entity.
    pub async fn admin_generate_mfa_totp_secret(
        &self,
        request: &IdentityMfaTotpAdminRequest,
    ) -> Result<IdentityMfaTotpSecret> {
        request.validate()?;
        self.post_data(&["mfa", "method", "totp", "admin-generate"], request)
            .await
    }

    /// Administratively destroys a TOTP MFA secret for an entity.
    pub async fn admin_destroy_mfa_totp_secret(
        &self,
        request: &IdentityMfaTotpAdminRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "method", "totp", "admin-destroy"], request)
            .await
    }

    /// Creates or updates an MFA login enforcement.
    pub async fn write_mfa_login_enforcement(
        &self,
        name: &str,
        request: &IdentityMfaLoginEnforcementRequest,
    ) -> Result<Empty> {
        request.validate()?;
        self.post_empty(&["mfa", "login-enforcement", name], request)
            .await
    }

    /// Reads an MFA login enforcement by name.
    pub async fn read_mfa_login_enforcement(
        &self,
        name: &str,
    ) -> Result<IdentityMfaLoginEnforcementInfo> {
        self.read_at(&["mfa", "login-enforcement", name]).await
    }

    /// Deletes an MFA login enforcement by name.
    pub async fn delete_mfa_login_enforcement(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["mfa", "login-enforcement", name]).await
    }

    /// Lists MFA login enforcements.
    pub async fn list_mfa_login_enforcements(&self) -> Result<IdentityMfaLoginEnforcementList> {
        self.list_at(&["mfa", "login-enforcement"]).await
    }

    async fn read_at<T>(&self, tail: &[&str]) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let envelope: ResponseEnvelope<T> = self
            .client
            .request_json(Method::GET, &self.path(tail)?, Option::<&Empty>::None)
            .await?;
        Ok(envelope.data)
    }

    async fn post_empty<T>(&self, tail: &[&str], request: &T) -> Result<Empty>
    where
        T: Serialize + ?Sized,
    {
        self.client
            .request_json(Method::POST, &self.path(tail)?, Some(request))
            .await
    }

    async fn post_data<T, U>(&self, tail: &[&str], request: &T) -> Result<U>
    where
        T: Serialize + ?Sized,
        U: serde::de::DeserializeOwned,
    {
        let envelope: ResponseEnvelope<U> = self
            .client
            .request_json(Method::POST, &self.path(tail)?, Some(request))
            .await?;
        Ok(envelope.data)
    }

    async fn list_at<T>(&self, tail: &[&str]) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let method =
            Method::from_bytes(b"LIST").map_err(|error| Error::InvalidHeader(error.to_string()))?;
        let envelope: ResponseEnvelope<T> = self
            .client
            .request_json_query_accepting(
                method,
                &self.path(tail)?,
                &[],
                Option::<&Empty>::None,
                &[StatusCode::OK],
            )
            .await?;
        Ok(envelope.data)
    }

    async fn list_oidc_providers_with_client_id(
        &self,
        client_id: Option<&str>,
    ) -> Result<IdentityOidcProviderList> {
        let method =
            Method::from_bytes(b"LIST").map_err(|error| Error::InvalidHeader(error.to_string()))?;
        let mut query = Vec::new();
        if let Some(client_id) = client_id {
            query.push(("client_id", client_id.to_owned()));
        }
        let envelope: ResponseEnvelope<IdentityOidcProviderList> = self
            .client
            .request_json_query_accepting(
                method,
                &self.path(&["oidc", "provider"])?,
                &query,
                Option::<&Empty>::None,
                &[StatusCode::OK],
            )
            .await?;
        Ok(envelope.data)
    }

    async fn delete_at(&self, tail: &[&str]) -> Result<Empty> {
        self.client
            .request_json_accepting(
                Method::DELETE,
                &self.path(tail)?,
                Option::<&Empty>::None,
                &[StatusCode::OK, StatusCode::NO_CONTENT],
            )
            .await
    }

    fn path(&self, tail: &[&str]) -> Result<String> {
        let mut segments = self.mount.clone();
        for segment in tail {
            segments.extend(validate_endpoint_path(segment)?);
        }
        Ok(segments.join("/"))
    }
}

fn validate_string_count(count: usize, field: &'static str) -> Result<()> {
    if count <= IDENTITY_LIST_LIMIT {
        return Ok(());
    }
    Err(Error::InvalidParameter(format!(
        "{field} exceeds maximum item count"
    )))
}

fn validate_required(value: &str, field: &'static str) -> Result<()> {
    if value.trim().is_empty() {
        return Err(Error::InvalidParameter(format!(
            "{field} must not be empty"
        )));
    }
    Ok(())
}

fn serialize_optional_entry<S>(
    map: &mut S,
    key: &'static str,
    value: Option<&str>,
) -> core::result::Result<(), S::Error>
where
    S: SerializeMap,
{
    if let Some(value) = value {
        map.serialize_entry(key, value)?;
    }
    Ok(())
}

fn take_optional_string<E>(
    map: &mut BTreeMap<String, JsonValue>,
    key: &'static str,
) -> core::result::Result<Option<String>, E>
where
    E: serde::de::Error,
{
    match map.remove(key) {
        None | Some(JsonValue::Null) => Ok(None),
        Some(value) => serde_json::from_value::<String>(value)
            .map(Some)
            .map_err(E::custom),
    }
}

fn take_optional_string_vec<E>(
    map: &mut BTreeMap<String, JsonValue>,
    key: &'static str,
) -> core::result::Result<Option<Vec<String>>, E>
where
    E: serde::de::Error,
{
    let Some(value) = map.remove(key) else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let JsonValue::Array(values) = value else {
        return Err(E::custom(format!("expected array for field {key}")));
    };
    if values.len() > IDENTITY_LIST_LIMIT {
        return Err(E::custom(
            "identity OIDC discovery string list exceeds item limit",
        ));
    }
    values
        .into_iter()
        .map(serde_json::from_value::<String>)
        .collect::<core::result::Result<Vec<_>, _>>()
        .map(Some)
        .map_err(E::custom)
}

#[derive(Serialize)]
struct IdentityOidcIntrospectPayload<'a> {
    token: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_id: Option<&'a str>,
}

fn deserialize_bounded_json_vec<'de, D>(
    deserializer: D,
) -> core::result::Result<Vec<JsonValue>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct Visitor;

    impl<'de> serde::de::Visitor<'de> for Visitor {
        type Value = Vec<JsonValue>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a bounded JSON array")
        }

        fn visit_none<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_unit<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_some<D>(self, deserializer: D) -> core::result::Result<Self::Value, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            deserializer.deserialize_seq(self)
        }

        fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
        where
            A: serde::de::SeqAccess<'de>,
        {
            let mut values = Vec::new();
            while values.len() < IDENTITY_LIST_LIMIT {
                let Some(value) = seq.next_element::<JsonValue>()? else {
                    return Ok(values);
                };
                values.push(value);
            }
            if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
                return Err(serde::de::Error::custom(
                    "identity OIDC JWKS key list exceeds item limit",
                ));
            }
            Ok(values)
        }
    }

    deserializer.deserialize_option(Visitor)
}

fn deserialize_bounded_json_map<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, JsonValue>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct Visitor;

    impl<'de> serde::de::Visitor<'de> for Visitor {
        type Value = BTreeMap<String, JsonValue>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a bounded JSON object")
        }

        fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
        where
            A: serde::de::MapAccess<'de>,
        {
            let mut values = BTreeMap::new();
            while values.len() < IDENTITY_LIST_LIMIT {
                let Some((key, value)) = map.next_entry::<String, JsonValue>()? else {
                    return Ok(values);
                };
                values.insert(key, value);
            }
            if map
                .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
                .is_some()
            {
                return Err(serde::de::Error::custom(
                    "identity OIDC JSON object exceeds item limit",
                ));
            }
            Ok(values)
        }
    }

    deserializer.deserialize_map(Visitor)
}

fn deserialize_bounded_oidc_provider_info_map<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, IdentityOidcProviderInfo>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct Visitor;

    impl<'de> serde::de::Visitor<'de> for Visitor {
        type Value = BTreeMap<String, IdentityOidcProviderInfo>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a bounded Identity OIDC provider info map")
        }

        fn visit_none<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(BTreeMap::new())
        }

        fn visit_unit<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(BTreeMap::new())
        }

        fn visit_some<D>(self, deserializer: D) -> core::result::Result<Self::Value, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            deserializer.deserialize_map(self)
        }

        fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
        where
            A: serde::de::MapAccess<'de>,
        {
            let mut values = BTreeMap::new();
            while values.len() < IDENTITY_LIST_LIMIT {
                let Some((key, value)) = map.next_entry::<String, IdentityOidcProviderInfo>()?
                else {
                    return Ok(values);
                };
                values.insert(key, value);
            }
            if map
                .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
                .is_some()
            {
                return Err(serde::de::Error::custom(
                    "identity OIDC provider info map exceeds item limit",
                ));
            }
            Ok(values)
        }
    }

    deserializer.deserialize_option(Visitor)
}

fn deserialize_bounded_oidc_client_info_map<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, IdentityOidcClientInfo>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct Visitor;

    impl<'de> serde::de::Visitor<'de> for Visitor {
        type Value = BTreeMap<String, IdentityOidcClientInfo>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a bounded Identity OIDC client info map")
        }

        fn visit_none<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(BTreeMap::new())
        }

        fn visit_unit<E>(self) -> core::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(BTreeMap::new())
        }

        fn visit_some<D>(self, deserializer: D) -> core::result::Result<Self::Value, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            deserializer.deserialize_map(self)
        }

        fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
        where
            A: serde::de::MapAccess<'de>,
        {
            let mut values = BTreeMap::new();
            while values.len() < IDENTITY_LIST_LIMIT {
                let Some((key, value)) = map.next_entry::<String, IdentityOidcClientInfo>()? else {
                    return Ok(values);
                };
                values.insert(key, value);
            }
            if map
                .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
                .is_some()
            {
                return Err(serde::de::Error::custom(
                    "identity OIDC client info map exceeds item limit",
                ));
            }
            Ok(values)
        }
    }

    deserializer.deserialize_option(Visitor)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]
    #![allow(deprecated)]

    use secrecy::SecretString;

    use crate::{Client, OpenBaoConfig};

    use super::{
        IdentityAliasList, IdentityEntityBatchDeleteRequest, IdentityEntityList,
        IdentityEntityRequest, IdentityGroupList, IdentityGroupRequest, IdentityMfaDuoMethodInfo,
        IdentityMfaDuoMethodRequest, IdentityMfaLoginEnforcementList,
        IdentityMfaLoginEnforcementRequest, IdentityMfaMethodList, IdentityMfaOktaMethodInfo,
        IdentityMfaOktaMethodRequest, IdentityMfaPingIdMethodRequest, IdentityMfaTotpSecret,
        IdentityOidcAssignmentList, IdentityOidcClientInfo, IdentityOidcClientList,
        IdentityOidcDiscovery, IdentityOidcIntrospectRequest, IdentityOidcIntrospection,
        IdentityOidcJwks, IdentityOidcKeyList, IdentityOidcProviderList, IdentityOidcRoleList,
        IdentityOidcScopeList, IdentityOidcToken,
    };

    #[test]
    fn identity_paths_are_validated() {
        let config = OpenBaoConfig::new("http://127.0.0.1:8200")
            .and_then(OpenBaoConfig::allow_localhost_http)
            .unwrap_or_else(|error| panic!("{error}"));
        let client = Client::from_config(config)
            .unwrap_or_else(|error| panic!("{error}"))
            .with_token(SecretString::from("token"));
        let identity = client
            .identity_at("identity")
            .unwrap_or_else(|error| panic!("{error}"));

        assert_eq!(
            identity
                .path(&["entity", "name", "app"])
                .unwrap_or_else(|error| panic!("{error}")),
            "identity/entity/name/app"
        );
        assert!(client.identity_at("../identity").is_err());
        assert!(identity.path(&["entity", "name", "../app"]).is_err());
    }

    #[test]
    fn identity_lists_are_bounded() {
        let mut keys = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            keys.push(format!("identity-{index}"));
        }
        let value = serde_json::json!({ "keys": keys });

        assert!(serde_json::from_value::<IdentityEntityList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityGroupList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityAliasList>(value).is_err());
    }

    #[test]
    fn identity_request_counts_are_bounded() {
        let mut entity = IdentityEntityRequest::named("app");
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            entity.policies.push(format!("policy-{index}"));
        }
        assert!(entity.validate().is_err());

        let mut group = IdentityGroupRequest::internal("app");
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            group.member_entity_ids.push(format!("entity-{index}"));
        }
        assert!(group.validate().is_err());

        let batch = IdentityEntityBatchDeleteRequest::new(Vec::<String>::new());
        assert!(batch.validate().is_err());
    }

    #[test]
    fn identity_oidc_secret_debug_is_redacted() {
        let token = IdentityOidcToken {
            client_id: Some("client-id".to_owned()),
            token: SecretString::from("signed-id-token"),
            ttl: Some(3600),
        };
        let debug = format!("{token:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("signed-id-token"));

        let request = IdentityOidcIntrospectRequest::new(SecretString::from("signed-id-token"))
            .with_client_id("client-id");
        let debug = format!("{request:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("signed-id-token"));

        let client = IdentityOidcClientInfo {
            client_secret: Some(SecretString::from("client-secret")),
            ..IdentityOidcClientInfo::default()
        };
        let debug = format!("{client:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("client-secret"));
    }

    #[test]
    fn identity_mfa_secret_debug_is_redacted_and_validated() {
        let duo = IdentityMfaDuoMethodRequest::new(
            "duo-main",
            SecretString::from("fixture-a"),
            SecretString::from("fixture-b"),
            "api.example.com",
        );
        let debug = format!("{duo:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("fixture-a"));
        assert!(!debug.contains("fixture-b"));

        let okta = IdentityMfaOktaMethodRequest::new(
            "okta-main",
            "dev-org",
            SecretString::from("fixture-c"),
        );
        let debug = format!("{okta:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("fixture-c"));

        let ping =
            IdentityMfaPingIdMethodRequest::new("ping-main", SecretString::from("fixture-d"));
        let debug = format!("{ping:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("fixture-d"));

        let duo_info = serde_json::from_value::<IdentityMfaDuoMethodInfo>(serde_json::json!({
            "secret_key": "fixture-a",
            "integration_key": "fixture-b"
        }))
        .unwrap_or_else(|error| panic!("{error}"));
        let debug = format!("{duo_info:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("fixture-a"));
        assert!(!debug.contains("fixture-b"));

        let okta_info = serde_json::from_value::<IdentityMfaOktaMethodInfo>(serde_json::json!({
            "api_token": "fixture-c"
        }))
        .unwrap_or_else(|error| panic!("{error}"));
        let debug = format!("{okta_info:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("fixture-c"));

        let totp_secret = serde_json::from_value::<IdentityMfaTotpSecret>(serde_json::json!({
            "barcode": "barcode-data",
            "url": "otpauth://totp/example?secret=value"
        }))
        .unwrap_or_else(|error| panic!("{error}"));
        let debug = format!("{totp_secret:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("barcode-data"));
        assert!(!debug.contains("value"));

        assert!(
            IdentityMfaLoginEnforcementRequest::new()
                .with_mfa_method_id("totp-id")
                .validate()
                .is_err()
        );
        assert!(
            IdentityMfaLoginEnforcementRequest::new()
                .with_mfa_method_id("totp-id")
                .with_auth_method_accessor("auth-userpass")
                .validate()
                .is_ok()
        );
    }

    #[test]
    fn identity_oidc_lists_are_bounded() {
        let mut keys = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            keys.push(format!("identity-oidc-{index}"));
        }
        let value = serde_json::json!({ "keys": keys });

        assert!(serde_json::from_value::<IdentityOidcKeyList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityOidcRoleList>(value.clone()).is_err());
        assert!(
            serde_json::from_value::<IdentityOidcProviderList>(serde_json::json!({
                "keys": value["keys"].clone(),
                "key_info": {}
            }))
            .is_err()
        );

        assert!(serde_json::from_value::<IdentityOidcScopeList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityOidcClientList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityOidcAssignmentList>(value).is_err());

        let mut jwks = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            jwks.push(serde_json::json!({ "kid": format!("key-{index}") }));
        }
        assert!(
            serde_json::from_value::<IdentityOidcJwks>(serde_json::json!({
                "keys": jwks
            }))
            .is_err()
        );

        let mut key_info = serde_json::Map::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            key_info.insert(format!("client-{index}"), serde_json::json!({}));
        }
        assert!(
            serde_json::from_value::<IdentityOidcClientList>(serde_json::json!({
                "keys": [],
                "key_info": key_info
            }))
            .is_err()
        );
    }

    #[test]
    fn identity_oidc_extra_maps_are_bounded() {
        let mut extra = serde_json::Map::new();
        extra.insert("active".to_owned(), serde_json::json!(true));
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            extra.insert(format!("claim-{index}"), serde_json::json!("value"));
        }
        assert!(serde_json::from_value::<IdentityOidcIntrospection>(extra.clone().into()).is_err());
        assert!(serde_json::from_value::<IdentityOidcDiscovery>(extra.into()).is_err());
    }

    #[test]
    fn identity_oidc_discovery_string_lists_are_bounded() {
        let values = (0..=crate::response::MAX_RESPONSE_STRINGS)
            .map(|index| serde_json::json!(format!("claim-{index}")))
            .collect::<Vec<_>>();
        assert!(
            serde_json::from_value::<IdentityOidcDiscovery>(serde_json::json!({
                "claims_supported": values
            }))
            .is_err()
        );
    }

    #[test]
    fn identity_oidc_jwks_exact_limit_is_accepted() {
        let mut keys = Vec::new();
        for index in 0..crate::response::MAX_RESPONSE_STRINGS {
            keys.push(serde_json::json!({ "kid": format!("key-{index}") }));
        }
        let jwks = serde_json::from_value::<IdentityOidcJwks>(serde_json::json!({
            "keys": keys
        }))
        .unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(jwks.keys.len(), crate::response::MAX_RESPONSE_STRINGS);
    }

    #[test]
    fn identity_mfa_lists_are_bounded() {
        let mut keys = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            keys.push(format!("identity-mfa-{index}"));
        }
        let value = serde_json::json!({ "keys": keys });

        assert!(serde_json::from_value::<IdentityMfaMethodList>(value.clone()).is_err());
        assert!(serde_json::from_value::<IdentityMfaLoginEnforcementList>(value).is_err());
    }
}