auth-framework 0.6.0-rc45

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
use crate::errors::{AuthError, Result};
use crate::storage::{AuthStorage, SessionData};
use crate::tokens::AuthToken;
use aes_gcm::{
    Aes256Gcm, Key, KeyInit, Nonce,
    aead::{Aead, Payload},
};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::time::Duration;
use zeroize::Zeroize;

/// Serializes the tests in this crate's lib-unit-test binary that
/// EXPLICITLY read or write `AUTH_STORAGE_ENCRYPTION_KEY`/
/// `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` via this lock, since those are
/// process-global state shared across all tests running in parallel
/// threads within one `cargo test --lib` invocation. Acquire this (and
/// clean up the env var via [`EncryptionEnvGuard`], not a bare
/// `set_var`/`remove_var` pair) in any new test that touches those
/// variables.
///
/// **Not a guarantee every such test already does** -- some pre-existing
/// tests elsewhere in this crate build a persistent storage backend
/// through the real factory (and therefore read these env vars via
/// [`StorageEncryption::from_env`]) without taking this lock first; that
/// gap predates this lock and isn't closed by introducing it.
/// A `tokio::sync::Mutex`, not `std::sync::Mutex`, because several callers
/// (in `#[tokio::test]` functions) need to hold this guard across `.await`
/// points -- use `.lock().await` there, or `.blocking_lock()` in a plain
/// (non-async) `#[test]`.
#[cfg(test)]
pub(crate) static TEST_ENCRYPTION_ENV_LOCK: tokio::sync::Mutex<()> =
    tokio::sync::Mutex::const_new(());

/// RAII guard that sets `AUTH_STORAGE_ENCRYPTION_KEY` for the lifetime of
/// the guard and removes it on drop -- including on an early return or a
/// panic (e.g. from an `assert!`/`.unwrap()` failure), unlike a bare
/// `set_var` at the top of a test and a `remove_var` at the bottom, which
/// leaks the variable if the test fails before reaching that last line.
/// Callers should hold [`TEST_ENCRYPTION_ENV_LOCK`] for the guard's entire
/// lifetime.
#[cfg(test)]
pub(crate) struct EncryptionEnvGuard;

#[cfg(test)]
impl EncryptionEnvGuard {
    pub(crate) fn set(key: &str) -> Self {
        // SAFETY: sound against every caller that ALSO takes
        // `TEST_ENCRYPTION_ENV_LOCK`; NOT sound otherwise (see the
        // lock's own doc for which pre-existing tests don't).
        unsafe {
            std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", key);
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
        }
        Self
    }
}

#[cfg(test)]
impl Drop for EncryptionEnvGuard {
    fn drop(&mut self) {
        // SAFETY: see `EncryptionEnvGuard::set` -- the same lock is held
        // for this guard's entire lifetime, including this drop.
        unsafe {
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
        }
    }
}

/// Current envelope format version. Bumped whenever the envelope's fields
/// or decryption rules change in a way that needs disambiguating from
/// older data still on disk.
///
/// * `0` -- the original public `EncryptedStorage`: no `key_id`, no AAD.
/// * `1` -- versioned `key_id`; AAD is the bare storage key, so the
///   envelope's own metadata (`v`, `key_id`, `algorithm`) is NOT
///   authenticated.
/// * `2` -- AAD binds the metadata too (see [`bound_aad`]).
///
/// Versions below the current one are *legacy*: readable only behind the
/// `allow_legacy_v0` policy (the name is historical; it covers every
/// pre-current format) and upgraded by [`migrate_kv_to_encrypted`].
const CURRENT_FORMAT_VERSION: u8 = 2;

/// Format version 1, the first versioned-`key_id` format.
const FORMAT_V1: u8 = 1;

/// The only algorithm identifier this module reads or writes.
const ALGORITHM: &str = "AES-256-GCM";

/// The one error text every decryption failure returns. The specific
/// cause (bad base64, wrong nonce length, unknown key id, failed
/// authentication, ...) is logged, never returned, so the failure itself
/// is not an oracle for which check tripped.
const DECRYPT_FAILED: &str = "Decryption failed";

/// Associated data for a format-v2 envelope: the caller's record AAD
/// (the storage key) AND the envelope's own `v`, `algorithm` and `key_id`,
/// each length-prefixed so the concatenation is unambiguous. Binding the
/// metadata means relabelling an envelope's `key_id`, or rewriting `v` to
/// downgrade it to a format whose AAD ignores metadata, fails
/// authentication instead of being trusted.
fn bound_aad(v: u8, algorithm: &str, key_id: &str, record_aad: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(48 + algorithm.len() + key_id.len() + record_aad.len());
    out.extend_from_slice(b"auth-framework/storage-envelope");
    out.push(v);
    for part in [algorithm.as_bytes(), key_id.as_bytes(), record_aad] {
        out.extend_from_slice(&(part.len() as u32).to_be_bytes());
        out.extend_from_slice(part);
    }
    out
}

fn default_format_version() -> u8 {
    // Envelopes serialized before this field existed (format version 0,
    // the original public `EncryptedStorage`: fields `data`/`nonce`/
    // `algorithm`/`key_derivation`, no `key_id`, no AAD at encryption
    // time) deserialize with this field absent -- serde DOES call this
    // function in that case (per `#[serde(default = "...")]`'s actual
    // behavior), which happens to return the same `0` the bare type
    // default would. It's spelled out explicitly, rather than relying on
    // `#[serde(default)]`'s type-default shorthand, so the "absent field
    // means format version 0" rule is visible at the field's definition
    // instead of implicit in `u8::default()`.
    0
}

/// Encrypted data container with metadata.
///
/// `key_id` makes this a versioned envelope: a value encrypted under one key
/// can still be decrypted after the *current* key rotates, as long as the
/// old key is still loadable (see [`KeyProvider`]). Writers always use the
/// current key; readers look up whichever key the envelope names.
///
/// `v` and `key_derivation` exist for backward compatibility with the
/// original, pre-this-redesign public `EncryptedStorage` (format version
/// 0): that format had no `key_id` and no AAD binding at encryption time.
/// An envelope with `v == 0` (including any envelope missing the `v` field
/// entirely, since `#[serde(default)]` fills it with `0`) is decrypted
/// against every loaded key with an empty AAD, matching the old behavior;
/// see [`StorageEncryption::decrypt`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedData {
    /// Base64 encoded encrypted data
    pub data: String,
    /// Base64 encoded nonce/IV (96 bits, randomly generated per encryption)
    pub nonce: String,
    /// Algorithm identifier
    pub algorithm: String,
    /// Which key (by id) encrypted this value. Empty for format version 0
    /// (the original `EncryptedStorage`, which had no key-id concept).
    #[serde(default)]
    pub key_id: String,
    /// Envelope format version. `0` (including an absent field, which
    /// deserializes to `0`) is the original pre-redesign format; `1` is
    /// the legacy versioned-`key_id` format; `2` is the current format
    /// (metadata bound into the AAD).
    #[serde(default = "default_format_version")]
    pub v: u8,
    /// Present only for format-version-0 compatibility (the original
    /// field name was `key_derivation`); current envelopes don't set it.
    #[serde(default)]
    pub key_derivation: String,
}

/// Supplies the encryption key(s) [`StorageEncryption`] uses.
///
/// Exists as a seam so the key *source* (env var today) can be swapped for
/// a KMS or an `age`/`sops`-style file-based secret without touching
/// [`StorageEncryption`] or [`EncryptedStorage`] at all. See
/// [`EnvKeyProvider`]'s own docs for the current, deliberately narrow,
/// implementation and its known limitation.
pub trait KeyProvider: Send + Sync {
    /// Load every key this provider knows about, keyed by key id, plus
    /// which one is current (new writes use this one; any key in the map
    /// can still be used to decrypt an old envelope that names it).
    ///
    /// Returns an error if no usable key can be loaded at all -- callers
    /// must fail closed on that, never silently fall back to no
    /// encryption.
    fn load_keys(&self) -> Result<LoadedKeys>;
}

/// The result of [`KeyProvider::load_keys`]: every key this provider could
/// load, and which one is current.
pub struct LoadedKeys {
    pub current_key_id: String,
    /// All loadable keys, including the current one, by key id. A key id
    /// must not be empty -- [`StorageEncryption::new`] rejects any that
    /// are, since an empty id can't be told apart from format-version-0
    /// envelopes (which have no key id at all).
    pub keys: HashMap<String, [u8; 32]>,
}

/// Loads encryption keys from environment variables, or from a file if
/// `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` is set.
///
/// **Known limitation (tracked, per CireSnave's ruling on board item 124):**
/// env vars and files sit on the same host as the data they protect. An
/// attacker with read access to the process environment or the key file
/// can decrypt everything this encrypts. This is accepted as a starting
/// point, not an endpoint -- [`KeyProvider`] exists specifically so a
/// KMS-backed or `age`/`sops`-backed provider can replace this one later
/// without any caller-visible change. See `docs/storage-backends.md` for
/// the same note aimed at operators.
///
/// ## Format
///
/// - `AUTH_STORAGE_ENCRYPTION_KEY` (required unless the keys file sets
///   `current`): the current key, base64-encoded, 32 bytes decoded.
/// - `AUTH_STORAGE_ENCRYPTION_KEY_ID` (optional, defaults to `"1"`): the id
///   under which `AUTH_STORAGE_ENCRYPTION_KEY` is recorded in new
///   envelopes.
/// - `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` (optional): path to a JSON file
///   `{"current": "<key_id>", "keys": {"<key_id>": "<base64 key>", ...}}`
///   for rotation -- old keys stay loadable (decrypt-only in practice,
///   since `current` picks what new writes use) as long as they're listed
///   here. If set, this takes priority over the two env vars above. On
///   Unix, a keys file readable by group or other triggers a `tracing::warn!`;
///   set `AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS=1` to make that
///   a startup error instead. Not checked at all on Windows.
/// - **The single env var cannot rotate**: it holds one key, so changing it
///   makes every stored envelope undecryptable. Use the keys file for
///   anything that will outlive one key; the storage factory warns when the
///   env-var key protects data that is already encrypted.
pub struct EnvKeyProvider;

impl KeyProvider for EnvKeyProvider {
    fn load_keys(&self) -> Result<LoadedKeys> {
        if let Ok(path) = env::var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE") {
            return Self::load_from_file(&path);
        }

        let mut key_data = env::var("AUTH_STORAGE_ENCRYPTION_KEY").map_err(|_| {
            AuthError::config(
                "No storage encryption key configured: set AUTH_STORAGE_ENCRYPTION_KEY \
                 (or AUTH_STORAGE_ENCRYPTION_KEYS_FILE for multi-key rotation). \
                 Refusing to start rather than silently storing data unencrypted.",
            )
        })?;
        let key_id = env::var("AUTH_STORAGE_ENCRYPTION_KEY_ID").unwrap_or_else(|_| "1".to_string());
        let key = decode_key(&key_data);
        key_data.zeroize();
        let key = key?;

        let mut keys = HashMap::new();
        keys.insert(key_id.clone(), key);
        Ok(LoadedKeys {
            current_key_id: key_id,
            keys,
        })
    }
}

impl EnvKeyProvider {
    fn load_from_file(path: &str) -> Result<LoadedKeys> {
        #[derive(Deserialize)]
        struct KeysFile {
            current: String,
            keys: HashMap<String, String>,
        }

        check_keys_file_permissions(path, strict_permissions_requested())?;

        let mut contents = fs::read_to_string(path).map_err(|e| {
            AuthError::config(format!(
                "Failed to read AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': {e}"
            ))
        })?;
        let parsed: Result<KeysFile> = serde_json::from_str(&contents).map_err(|e| {
            AuthError::config(format!(
                "Failed to parse AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': {e}"
            ))
        });
        contents.zeroize();
        let mut parsed = parsed?;

        if !parsed.keys.contains_key(&parsed.current) {
            // Zeroize every base64 key string before returning -- this
            // early return must not be the one exit path that skips it.
            for encoded in parsed.keys.values_mut() {
                encoded.zeroize();
            }
            return Err(AuthError::config(format!(
                "AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': current key id '{}' \
                 is not present in 'keys'",
                parsed.current
            )));
        }

        // Decode every entry, zeroizing its base64 string regardless of
        // success or failure, before checking for any error -- so a
        // failure partway through doesn't leave later entries' strings
        // (never reached by a `?`-propagating loop) un-zeroized, and
        // doesn't leave already-decoded key bytes from earlier entries
        // sitting in `keys` when we return Err below. Pre-sized so
        // `insert` never triggers a reallocation that could leave a
        // decoded key copy behind in the old, freed backing array.
        let mut keys = HashMap::with_capacity(parsed.keys.len());
        let mut first_error = None;
        for (id, mut encoded) in parsed.keys {
            match decode_key(&encoded) {
                Ok(key) => {
                    keys.insert(id, key);
                }
                Err(e) if first_error.is_none() => {
                    first_error = Some(e);
                }
                Err(_) => {}
            }
            encoded.zeroize();
        }

        if let Some(error) = first_error {
            for key_bytes in keys.values_mut() {
                key_bytes.zeroize();
            }
            return Err(error);
        }

        Ok(LoadedKeys {
            current_key_id: parsed.current,
            keys,
        })
    }
}

/// Environment variable that turns the keys-file permission warning into a
/// startup error. Accepts `1`, `true` or `yes` (any case).
const STRICT_KEY_FILE_PERMISSIONS_ENV: &str = "AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS";

/// `true` when a file mode lets group or other read (or write) the file.
/// (Only the Unix permission check calls it outside tests.)
#[cfg_attr(not(unix), allow(dead_code))]
fn keys_file_mode_too_open(mode: u32) -> bool {
    mode & 0o077 != 0
}

fn strict_permissions_requested() -> bool {
    env::var(STRICT_KEY_FILE_PERMISSIONS_ENV)
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes"
            )
        })
        .unwrap_or(false)
}

/// Checks the keys file's permissions: always warns when it is readable by
/// group or other (a file-based key readable by others defeats its point),
/// and fails startup when `strict` is set
/// (`AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS=1`). The default
/// stays warn-only because permission semantics vary across containers, CI
/// and Windows; strict mode is the opt-in for deployments that control them.
/// Unix only: elsewhere there are no group/other mode bits to inspect, so
/// strict mode logs that it cannot be enforced.
fn check_keys_file_permissions(path: &str, strict: bool) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(metadata) = fs::metadata(path) {
            let mode = metadata.permissions().mode();
            if keys_file_mode_too_open(mode) {
                if strict {
                    return Err(AuthError::config(format!(
                        "AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}' has mode {:o}: it is \
                         accessible to group or other. Restrict it to the owner (chmod 600) \
                         or unset {STRICT_KEY_FILE_PERMISSIONS_ENV}.",
                        mode & 0o777
                    )));
                }
                tracing::warn!(
                    path = path,
                    mode = format!("{mode:o}"),
                    "AUTH_STORAGE_ENCRYPTION_KEYS_FILE is readable by group or other -- \
                     restrict it to the owner only (chmod 600), or set \
                     {STRICT_KEY_FILE_PERMISSIONS_ENV}=1 to make this fatal."
                );
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        if strict {
            tracing::warn!(
                "{STRICT_KEY_FILE_PERMISSIONS_ENV} is set but key-file permissions cannot be \
                 inspected on this platform; it is not enforced."
            );
        }
    }
    Ok(())
}

/// `true` when the key comes from the `AUTH_STORAGE_ENCRYPTION_KEY`
/// environment variable (no keys file). That source holds exactly one key
/// and so cannot rotate: replacing it makes every stored envelope
/// undecryptable. Use a keys file (`AUTH_STORAGE_ENCRYPTION_KEYS_FILE`) for
/// anything that will outlive one key.
pub(crate) fn env_key_source_in_use() -> bool {
    env::var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE").is_err()
        && env::var("AUTH_STORAGE_ENCRYPTION_KEY").is_ok()
}

/// Looks at up to `limit` KV entries of `storage` and reports whether any is
/// already an encryption envelope. Bounded in the number of values read; the
/// key listing itself is whatever the backend returns for the empty prefix.
pub(crate) async fn stored_envelopes_exist<S: AuthStorage + ?Sized>(
    storage: &S,
    limit: usize,
) -> Result<bool> {
    for key in storage.list_kv_keys("").await?.into_iter().take(limit) {
        if let Some(raw) = storage.get_kv(&key).await?
            && StorageEncryption::looks_like_envelope(&raw)
        {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Produces a safe-to-log identifier for a storage key, for error
/// messages, tracing, and migration reports -- **never** the raw key
/// itself. In this crate, some storage keys literally ARE bearer
/// secrets (e.g. `api_key:{raw_api_key}` in
/// `auth_modular::user_manager`, `device:{device_code}` in
/// `api::oauth_advanced`), so logging or printing a key name verbatim
/// can leak a working credential into logs or a terminal.
///
/// Keeps the portion up to (not including) the first `:` (the
/// namespace, e.g. `api_key`, assumed not secret since every KV
/// namespace convention in this crate puts a fixed literal there) plus
/// a short, one-way hash of the *full* key, so an operator with direct
/// storage access can still correlate a reported identifier back to
/// the real record (by recomputing the same hash over a candidate key)
/// without the identifier itself being usable as a credential. A key
/// with no `:` at all has no such non-secret prefix to keep -- it is
/// replaced with the literal `key`, never the raw key itself.
fn safe_log_id(key: &str) -> String {
    use sha2::{Digest, Sha256};
    let hash_hex = hex::encode(&Sha256::digest(key.as_bytes())[..8]);
    match key.split_once(':') {
        Some((namespace, _)) => format!("{namespace}:{hash_hex}"),
        None => format!("key:{hash_hex}"),
    }
}

fn decode_key(encoded: &str) -> Result<[u8; 32]> {
    let mut key_bytes = BASE64
        .decode(encoded)
        .map_err(|_| AuthError::config("Invalid base64 in storage encryption key"))?;
    if key_bytes.len() != 32 {
        key_bytes.zeroize();
        return Err(AuthError::config(
            "Storage encryption key must be 32 bytes (256 bits) once base64-decoded",
        ));
    }
    let mut key = [0u8; 32];
    key.copy_from_slice(&key_bytes);
    key_bytes.zeroize();
    Ok(key)
}

/// Storage encryption manager using AES-256-GCM, with per-record random
/// nonces and associated data (AAD) binding each ciphertext to the storage
/// key it was stored under -- so a ciphertext copied from one record to
/// another fails to decrypt instead of silently "succeeding" with the
/// wrong value.
///
/// **Known limitation (replay of an older value under the same key):** AAD
/// binds a ciphertext to *which record* it belongs to, not to *when* it was
/// written. Someone who can both read an old ciphertext for a given key and
/// write to that same key can replay the old value -- AES-GCM's
/// authentication only proves "this is a genuine envelope for this record,"
/// not "this is the most recent one." Mitigating this needs a monotonic
/// counter or timestamp bound into the AAD, not done here (most KV-layer
/// values in this crate are replaced wholesale on every write, which bounds
/// but does not eliminate the exposure).
///
/// **Zeroization scope (accurate, not aspirational):** this module
/// zeroizes raw key material and intermediate plaintext it owns on every
/// exit path it controls (success, a validation error, or an encryption
/// failure partway through), as soon as it's done with it -- the
/// `[u8; 32]` key bytes in [`LoadedKeys`] (after the AES-GCM ciphers are
/// built, or before any validation error returns, including the
/// "current key id not found" check), [`decode_key`]'s intermediate
/// decoded `Vec<u8>`, every base64-encoded key string
/// [`EnvKeyProvider`] reads (file contents and every per-key entry, even
/// ones after a failure elsewhere in the same batch, and even when the
/// file's `current` id isn't present in `keys`), and
/// [`migrate_kv_to_encrypted`]'s intermediate plaintext/raw buffers,
/// including when the subsequent re-encrypt or write-back fails. It does
/// **not** zeroize: any copy the standard library or `aes-gcm` makes
/// internally that this code doesn't control (notably `aes` 0.8.4's own
/// key-schedule storage inside the `Aes256Gcm` cipher object, which has
/// no zeroize support in the version this crate depends on; and
/// `HashMap` growth can in principle leave a stale decoded-key copy in
/// an old, freed backing allocation during a resize -- mitigated, not
/// eliminated, in `EnvKeyProvider::load_from_file`'s multi-key decoding
/// loop (the one production path that decodes a variable, potentially
/// large number of keys into a map) by pre-sizing it with
/// `with_capacity`; `EnvKeyProvider::load_keys`' single-env-var path
/// only ever inserts exactly one entry, so it can't resize at all), or
/// a plaintext value a public method (`decrypt`,
/// `decrypt_from_storage`) hands back to its caller (that's the actual
/// return value the caller needs -- it isn't leftover residue this module
/// can clean up on the caller's behalf).
pub struct StorageEncryption {
    current_key_id: String,
    ciphers: HashMap<String, Aes256Gcm>,
}

impl StorageEncryption {
    /// Create a new encryption manager, loading keys from the given
    /// provider. Fails closed: if the provider can't load a usable key,
    /// this returns `Err` rather than any fallback.
    pub fn new(provider: &dyn KeyProvider) -> Result<Self> {
        let mut loaded = provider.load_keys()?;

        // Validate first, but zeroize the raw key bytes on EVERY exit
        // path (including these early validation failures) -- not just
        // the success path -- so a rejected key never lingers in memory
        // any longer than the other branch does.
        let validation_error = if loaded.current_key_id.is_empty() {
            Some(AuthError::config(
                "Key provider's current_key_id must not be empty",
            ))
        } else if loaded.keys.keys().any(|id| id.is_empty()) {
            Some(AuthError::config(
                "Key provider returned a key with an empty id -- an empty id is reserved \
                 to mean \"format-version-0 envelope, no key id at all\"",
            ))
        } else if !loaded.keys.contains_key(&loaded.current_key_id) {
            Some(AuthError::config(format!(
                "Key provider's current_key_id '{}' is not among the keys it loaded",
                loaded.current_key_id
            )))
        } else {
            None
        };

        if let Some(error) = validation_error {
            for key_bytes in loaded.keys.values_mut() {
                key_bytes.zeroize();
            }
            return Err(error);
        }

        let ciphers = loaded
            .keys
            .iter()
            .map(|(id, key_bytes)| {
                let key = Key::<Aes256Gcm>::from_slice(key_bytes);
                (id.clone(), Aes256Gcm::new(key))
            })
            .collect();
        // The cipher objects above have their own internal copies of the
        // key material; zeroize the raw bytes we held so they don't sit
        // around in this struct any longer than necessary.
        for key_bytes in loaded.keys.values_mut() {
            key_bytes.zeroize();
        }
        Ok(Self {
            current_key_id: loaded.current_key_id,
            ciphers,
        })
    }

    /// Create a new encryption manager from the environment (see
    /// [`EnvKeyProvider`]). Convenience wrapper over `new(&EnvKeyProvider)`.
    pub fn from_env() -> Result<Self> {
        Self::new(&EnvKeyProvider)
    }

    /// Create new encryption manager for testing with a single random key.
    #[cfg(test)]
    pub fn new_random() -> Self {
        use rand::Rng;
        let mut key_bytes = [0u8; 32];
        rand::rng().fill_bytes(&mut key_bytes);
        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
        let mut ciphers = HashMap::new();
        ciphers.insert("test".to_string(), Aes256Gcm::new(key));
        key_bytes.zeroize();
        Self {
            current_key_id: "test".to_string(),
            ciphers,
        }
    }

    /// Generate a new 256-bit encryption key (base64 encoded), suitable for
    /// `AUTH_STORAGE_ENCRYPTION_KEY` or a keys-file entry.
    pub fn generate_key() -> String {
        use rand::Rng;
        let mut key_bytes = [0u8; 32];
        rand::rng().fill_bytes(&mut key_bytes);
        let encoded = BASE64.encode(key_bytes);
        key_bytes.zeroize();
        encoded
    }

    /// Encrypt raw bytes. `aad` (associated data) is authenticated but not
    /// encrypted -- callers should pass the storage key the resulting
    /// envelope will be stored under, binding the ciphertext to that
    /// specific record.
    pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Result<EncryptedData> {
        use rand::Rng;
        let cipher = self.ciphers.get(&self.current_key_id).ok_or_else(|| {
            AuthError::internal("Current encryption key missing from loaded cipher set")
        })?;

        // 96-bit nonce, freshly random every call. NIST SP 800-38D caps a
        // randomly generated 96-bit IV at 2^32 invocations under a single
        // key before the collision probability becomes unacceptable (the
        // "32-bit random IV construction" guidance) -- not the ~2^64/2
        // birthday bound a naive calculation might suggest. A given
        // deployment's key should be rotated well before approaching that
        // count; this crate does not currently track or enforce it.
        let mut nonce_bytes = [0u8; 12];
        rand::rng().fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        let bound = bound_aad(CURRENT_FORMAT_VERSION, ALGORITHM, &self.current_key_id, aad);
        let ciphertext = cipher
            .encrypt(
                nonce,
                Payload {
                    msg: plaintext,
                    aad: &bound,
                },
            )
            .map_err(|e| AuthError::internal(format!("Encryption failed: {}", e)))?;

        Ok(EncryptedData {
            data: BASE64.encode(&ciphertext),
            nonce: BASE64.encode(nonce_bytes),
            algorithm: ALGORITHM.to_string(),
            key_id: self.current_key_id.clone(),
            v: CURRENT_FORMAT_VERSION,
            key_derivation: String::new(),
        })
    }

    /// Decrypt an envelope. `aad` must match exactly what was passed to
    /// [`Self::encrypt`] (the storage key the envelope is stored under) --
    /// a mismatch (e.g. a ciphertext copied to a different record) fails
    /// decryption rather than succeeding with the wrong plaintext.
    ///
    /// A format-version-0 envelope (see [`EncryptedData`]) is decrypted
    /// with an empty AAD against every loaded key in turn, matching the
    /// original `EncryptedStorage`'s behavior (no AAD, no key id) --
    /// AES-GCM's authentication tag makes trying the wrong key safe (it
    /// just fails), so this cannot silently produce the wrong plaintext.
    pub fn decrypt(&self, encrypted: &EncryptedData, aad: &[u8]) -> Result<Vec<u8>> {
        // Every failure below returns the SAME error text (`DECRYPT_FAILED`);
        // the cause is logged only.
        let fail = |why: &str| -> AuthError {
            // `key_id` comes from the (possibly attacker-writable) store:
            // log it Debug-escaped and bounded.
            tracing::warn!(
                key_id = ?encrypted.key_id.chars().take(64).collect::<String>(),
                v = encrypted.v,
                "storage envelope decryption failed: {why}"
            );
            AuthError::internal(DECRYPT_FAILED)
        };

        if encrypted.algorithm != ALGORITHM {
            return Err(fail("unsupported algorithm"));
        }

        let ciphertext = BASE64
            .decode(&encrypted.data)
            .map_err(|_| fail("invalid base64 in data"))?;
        let nonce_bytes = BASE64
            .decode(&encrypted.nonce)
            .map_err(|_| fail("invalid base64 in nonce"))?;
        if nonce_bytes.len() != 12 {
            return Err(fail("invalid nonce length"));
        }
        let nonce = Nonce::from_slice(&nonce_bytes);

        if encrypted.v == 0 {
            // Format version 0 (the original EncryptedStorage): no key id,
            // no AAD. Try every loaded key, in a stable order; the auth tag
            // rejects wrong ones.
            for id in self.sorted_key_ids() {
                if let Some(cipher) = self.ciphers.get(&id)
                    && let Ok(plaintext) = cipher.decrypt(
                        nonce,
                        Payload {
                            msg: &ciphertext,
                            aad: b"",
                        },
                    )
                {
                    return Ok(plaintext);
                }
            }
            return Err(fail("no loaded key opens this format-version-0 envelope"));
        }

        let cipher = self
            .ciphers
            .get(&encrypted.key_id)
            .ok_or_else(|| fail("no loaded key for this key_id (rotated out?)"))?;

        // v1 authenticated only the bare record AAD; v2 also binds the
        // envelope's own metadata. Anything else is unknown to this build.
        let bound;
        let effective_aad: &[u8] = match encrypted.v {
            FORMAT_V1 => aad,
            CURRENT_FORMAT_VERSION => {
                bound = bound_aad(encrypted.v, &encrypted.algorithm, &encrypted.key_id, aad);
                &bound
            }
            _ => return Err(fail("unsupported envelope version")),
        };

        cipher
            .decrypt(
                nonce,
                Payload {
                    msg: &ciphertext,
                    aad: effective_aad,
                },
            )
            .map_err(|_| fail("authentication failed (wrong key, wrong record, or tampered)"))
    }

    /// Encrypt raw bytes for storage, serialized as a self-describing
    /// envelope. `aad` should be the storage key this will be stored
    /// under. Accepts arbitrary bytes, not just UTF-8 text.
    pub fn encrypt_for_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
        let encrypted = self.encrypt(data, aad)?;
        let serialized = serde_json::to_string(&encrypted).map_err(|e| {
            AuthError::internal(format!("Failed to serialize encrypted data: {}", e))
        })?;
        Ok(serialized.into_bytes())
    }

    /// Decrypt a storage envelope produced by [`Self::encrypt_for_storage`].
    /// `aad` must be the same storage key passed to that call.
    pub fn decrypt_from_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
        // A stored value that is not even an envelope fails with the same
        // text as every other decryption failure; the cause is logged.
        let parsed = std::str::from_utf8(data)
            .map_err(|e| e.to_string())
            .and_then(|s| serde_json::from_str::<EncryptedData>(s).map_err(|e| e.to_string()));
        let encrypted = parsed.map_err(|why| {
            tracing::warn!("stored value is not a readable envelope: {why}");
            AuthError::internal(DECRYPT_FAILED)
        })?;
        self.decrypt(&encrypted, aad)
    }

    /// Parses `data` as one of this module's own serialized envelopes --
    /// either the current format or the original format-version-0 shape
    /// (see [`EncryptedData`]) -- without attempting to decrypt it. `None`
    /// if `data` isn't valid UTF-8 JSON, doesn't name the right algorithm,
    /// or claims a post-v0 format without a `key_id`.
    ///
    /// This is a **shape** check only. A value that parses here but fails
    /// to decrypt (wrong key, corrupted, or tampered with) is a hard error
    /// from [`Self::decrypt_from_storage`], never silently treated as
    /// plaintext.
    pub fn parse_envelope(data: &[u8]) -> Option<EncryptedData> {
        let encrypted = std::str::from_utf8(data)
            .ok()
            .and_then(|s| serde_json::from_str::<EncryptedData>(s).ok())?;
        if encrypted.algorithm != ALGORITHM {
            return None;
        }
        // v0 has neither `v` nor `key_id`. Anything claiming a later
        // format must carry an explicit non-empty `key_id`; without one it
        // is just plaintext JSON that happens to resemble an envelope.
        let well_formed = if encrypted.v == 0 {
            encrypted.key_id.is_empty()
        } else {
            !encrypted.key_id.is_empty()
        };
        well_formed.then_some(encrypted)
    }

    /// Key ids in a stable (ascending) order, for deterministic trial
    /// decryption.
    fn sorted_key_ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = self.ciphers.keys().cloned().collect();
        ids.sort();
        ids
    }

    /// Returns `true` if `data` parses as one of this module's own
    /// serialized envelopes. Used by [`migrate_kv_to_encrypted`] and
    /// [`EncryptedStorage::get_kv`] to decide whether a stored value
    /// should be decrypted at all.
    pub fn looks_like_envelope(data: &[u8]) -> bool {
        Self::parse_envelope(data).is_some()
    }
}

/// Wrapper for storage backends that adds encryption at rest to the
/// generic key-value (`store_kv`/`get_kv`) layer.
///
/// **Coverage note:** this wraps `store_kv`/`get_kv` only. The dedicated
/// `store_token`/`store_session` methods (and each backend's own typed
/// columns for them) are NOT touched by this wrapper -- they delegate to
/// `inner` unchanged. Encrypting those would need changes to the
/// `AuthStorage` trait itself (their fields are typed, not opaque bytes),
/// tracked separately. This wrapper covers everything that already goes
/// through `store_kv` today: API keys, TOTP secrets, OAuth2 client
/// registries, MFA codes, and most of the other KV-backed subsystems
/// found in the storage audit (`docs/STORAGE-AUDIT.md`).
pub struct EncryptedStorage<T> {
    inner: T,
    encryption: StorageEncryption,
    /// See [`Self::get_kv`]'s doc comment for exactly what this controls.
    allow_plaintext_reads: bool,
    /// See [`Self::get_kv`]'s doc comment for exactly what this controls.
    allow_legacy_v0: bool,
}

impl<T> EncryptedStorage<T> {
    /// `allow_plaintext_reads` should be `true` only transiently, while
    /// migrating an existing deployment's plaintext data (see
    /// [`migrate_kv_to_encrypted`]) -- it is what makes [`Self::get_kv`]
    /// tolerate a value that isn't a valid envelope instead of erroring.
    /// Leaving it `true` permanently means anyone who can write to the
    /// backing store can overwrite an encrypted value with chosen
    /// plaintext (or corrupt one) and have it accepted silently, which
    /// defeats the point of encrypting at rest. Pass `false` for normal
    /// operation.
    ///
    /// `allow_legacy_v0` should likewise be `true` only transiently, while
    /// migrating pre-existing format-version-0 data: a v0 envelope has no
    /// AAD binding it to its own storage key, so with this `true`, a
    /// writer who knows one record's v0 envelope can copy it onto a
    /// different record's key and it still decrypts -- the exact swap the
    /// current format's AAD exists to prevent. This flag is independent
    /// of [`migrate_kv_to_encrypted`]'s own, separate
    /// `accept_legacy_v0` parameter (that one gates whether migration
    /// actually *rewrites* a v0 envelope; this one gates whether this
    /// wrapper's `get_kv` will *read* one at all) -- set this one `true`
    /// if something needs to read v0 data through this wrapper before,
    /// or without ever, running migration.
    pub fn new(
        storage: T,
        encryption: StorageEncryption,
        allow_plaintext_reads: bool,
        allow_legacy_v0: bool,
    ) -> Self {
        Self {
            inner: storage,
            encryption,
            allow_plaintext_reads,
            allow_legacy_v0,
        }
    }

    pub fn into_inner(self) -> T {
        self.inner
    }
}

#[async_trait::async_trait]
impl<T> AuthStorage for EncryptedStorage<T>
where
    T: AuthStorage + Send + Sync,
{
    // Token/session methods — NOT encrypted by this wrapper. See the
    // "Coverage note" on `EncryptedStorage` itself.
    async fn store_token(&self, token: &AuthToken) -> Result<()> {
        self.inner.store_token(token).await
    }

    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
        self.inner.get_token(token_id).await
    }

    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
        self.inner.get_token_by_access_token(access_token).await
    }

    async fn update_token(&self, token: &AuthToken) -> Result<()> {
        self.inner.update_token(token).await
    }

    async fn delete_token(&self, token_id: &str) -> Result<()> {
        self.inner.delete_token(token_id).await
    }

    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
        self.inner.list_user_tokens(user_id).await
    }

    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
        self.inner.store_session(session_id, data).await
    }

    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
        self.inner.get_session(session_id).await
    }

    async fn delete_session(&self, session_id: &str) -> Result<()> {
        self.inner.delete_session(session_id).await
    }

    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
        self.inner.list_user_sessions(user_id).await
    }

    async fn count_active_sessions(&self) -> Result<u64> {
        self.inner.count_active_sessions().await
    }

    // Bulk methods — delegate directly to `inner`'s own overrides (if any)
    // instead of inheriting the `AuthStorage` trait's one-at-a-time default
    // loop, so a backend that implements real batching here keeps that
    // benefit even when wrapped. Token/session bulk methods are unaffected
    // by encryption (see the coverage note above) either way.
    async fn store_tokens_bulk(&self, tokens: &[AuthToken]) -> Result<()> {
        self.inner.store_tokens_bulk(tokens).await
    }

    async fn delete_tokens_bulk(&self, token_ids: &[String]) -> Result<()> {
        self.inner.delete_tokens_bulk(token_ids).await
    }

    async fn store_sessions_bulk(&self, sessions: &[(String, SessionData)]) -> Result<()> {
        self.inner.store_sessions_bulk(sessions).await
    }

    async fn delete_sessions_bulk(&self, session_ids: &[String]) -> Result<()> {
        self.inner.delete_sessions_bulk(session_ids).await
    }

    // Key-value methods — encrypted, with the storage key itself as AAD so
    // a ciphertext can't be swapped between records.
    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
        // A TTL is storage metadata, not part of the encrypted value.
        self.inner.get_kv_ttl(key).await
    }

    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
        let encrypted_value = self.encryption.encrypt_for_storage(value, key.as_bytes())?;
        self.inner.store_kv(key, &encrypted_value, ttl).await
    }

    /// Reads back a value stored by [`Self::store_kv`], decrypting it.
    ///
    /// A value that **parses as one of this module's envelopes**
    /// ([`StorageEncryption::looks_like_envelope`]) is always decrypted;
    /// a decryption failure (wrong key, corrupted, tampered) is a hard
    /// `Err`, never silently returned as-is.
    ///
    /// A value that does **not** parse as an envelope at all is ambiguous:
    /// it could be genuine pre-encryption plaintext, or it could be a
    /// plaintext value an attacker (or a bug) overwrote the encrypted one
    /// with. This method only tolerates that ambiguity -- returning the
    /// raw bytes as-is -- when `allow_plaintext_reads` is `true`. With it
    /// `false` (the default via the storage factory once migration is
    /// done), a non-envelope value is also a hard `Err`, so overwriting an
    /// encrypted record with plaintext cannot silently succeed.
    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
        let Some(raw) = self.inner.get_kv(key).await? else {
            return Ok(None);
        };

        if let Some(envelope) = StorageEncryption::parse_envelope(&raw) {
            if envelope.v < CURRENT_FORMAT_VERSION && !self.allow_legacy_v0 {
                return Err(AuthError::internal(format!(
                    "Value for record '{}' uses legacy envelope format version {} (its \
                     metadata is not bound into the authenticated data), and \
                     storage_encryption.allow_legacy_v0 is false. Run the migration tool \
                     (`auth-framework-admin security encrypt-kv --accept-legacy-v0`) to \
                     upgrade it to the current format, or temporarily set \
                     storage_encryption.allow_legacy_v0 = true if something else needs to \
                     read it first.",
                    safe_log_id(key),
                    envelope.v
                )));
            }
            let decrypted = self.encryption.decrypt(&envelope, key.as_bytes())?;
            return Ok(Some(decrypted));
        }

        if self.allow_plaintext_reads {
            return Ok(Some(raw));
        }

        Err(AuthError::internal(format!(
            "Value for record '{}' is not a valid encrypted envelope, and \
             storage_encryption.allow_plaintext_reads is false. If this key genuinely \
             predates encryption being enabled, run the migration tool \
             (`auth-framework-admin security encrypt-kv`) or temporarily set \
             storage_encryption.allow_plaintext_reads = true while migrating.",
            safe_log_id(key)
        )))
    }

    fn tracks_kv_ttl(&self) -> bool {
        // A TTL is storage metadata, not part of the encrypted value.
        self.inner.tracks_kv_ttl()
    }

    fn encrypts_kv_at_rest(&self) -> bool {
        true
    }

    async fn delete_kv(&self, key: &str) -> Result<()> {
        self.inner.delete_kv(key).await
    }

    // Key NAMES are never encrypted (only values) -- pass through
    // unchanged so RBAC role reload, maintenance/backup, and analytics
    // (all of which call this) keep working once this wrapper is in the
    // default path. Without this override, the AuthStorage trait's
    // default implementation silently returns an empty Vec.
    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
        self.inner.list_kv_keys(prefix).await
    }

    async fn cleanup_expired(&self) -> Result<()> {
        self.inner.cleanup_expired().await
    }
}

/// Outcome of [`migrate_kv_to_encrypted`].
///
/// `#[non_exhaustive]`: this is a read-only outcome type, not something
/// a caller builds -- only this crate's own tests construct one (with
/// `..Default::default()`, which only compiles from *inside* the
/// crate), so a later field addition here can never be a breaking
/// change for an external caller.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct KvEncryptionMigrationReport {
    /// Whether this run was a dry run (no writes performed).
    pub dry_run: bool,
    /// Total keys examined under the given prefix. Always equal to
    /// `already_encrypted + legacy_v0_found + encrypted + vanished +
    /// failed.len()`.
    pub scanned: u64,
    /// Keys that were already a current-format envelope -- left
    /// untouched.
    pub already_encrypted: u64,
    /// Keys that were a LEGACY envelope (format version 0 or 1; the name
    /// is historical) that decrypted successfully -- counted here whether
    /// or not they were actually rewritten (see `upgraded_from_legacy`).
    /// A v0 envelope has no AAD binding its plaintext to this specific
    /// record, so this plaintext's association with this key could not
    /// be cryptographically verified -- it is exactly as trustworthy as
    /// it was before migration, no more, no less. A v1 envelope's AAD
    /// does bind the record key (its decryption just verified that), but
    /// not its own metadata.
    pub legacy_v0_found: u64,
    /// Keys whose legacy (v0 or v1) envelope was actually rewritten under
    /// the current format. Zero unless this was a real (non-dry) run
    /// AND `accept_legacy_v0` was `true` -- see
    /// [`migrate_kv_to_encrypted`]'s docs for why that flag exists and
    /// what rewriting a v0 envelope does and does not verify.
    pub upgraded_from_legacy: u64,
    /// Keys that were plaintext (not an envelope at all) and got
    /// encrypted (or would have, in a dry run).
    pub encrypted: u64,
    /// Keys that were read but had vanished by the time of the write-back
    /// (concurrent deletion) -- not an error, just skipped.
    pub vanished: u64,
    /// Format-version-0 records whose envelope could not be decrypted
    /// under any loaded key (wrong/missing key, or corrupted). Skipped,
    /// not treated as fatal -- the rest of the run still completes.
    /// **Only v0 envelopes are decrypt-checked by this function** --
    /// a current-format (v1) envelope that can't decrypt (e.g. its key
    /// was rotated out) is not migration's concern (it's already in the
    /// target format) and is counted in `already_encrypted`, not here.
    /// Entries are a **safe identifier** (see [`safe_log_id`]), never the
    /// raw storage key -- some keys in this crate are themselves bearer
    /// secrets (e.g. `api_key:{raw_key}`).
    pub failed: Vec<String>,
}

/// Options for [`migrate_kv_to_encrypted`]. A named struct rather than
/// two adjacent `bool` parameters, specifically so a caller can't
/// transpose them -- `(false, true)` instead of `(true, false)` would
/// otherwise silently turn an intended dry run into a real upgrade.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct MigrationOptions {
    /// Preview only; don't write anything. See
    /// [`migrate_kv_to_encrypted`]'s own docs for exactly what a dry run
    /// still does (it attempts every decrypt a real run would, for
    /// accurate reporting).
    pub dry_run: bool,
    /// Required, together with `dry_run: false`, to actually rewrite a
    /// format-version-0 envelope to the current format. See
    /// [`migrate_kv_to_encrypted`]'s own docs for why this is a separate,
    /// explicit opt-in.
    pub accept_legacy_v0: bool,
    /// A backend that cannot report KV TTLs ([`AuthStorage::tracks_kv_ttl`]
    /// is `false`) makes a real migration turn every expiring entry into a
    /// permanent one. Such a run is refused unless this is `true`.
    pub accept_ttl_loss: bool,
}

impl MigrationOptions {
    /// Builder-style setter; see [`Self::with_dry_run`].
    pub fn with_accept_ttl_loss(mut self, accept_ttl_loss: bool) -> Self {
        self.accept_ttl_loss = accept_ttl_loss;
        self
    }

    /// Builder-style setter. `#[non_exhaustive]` means `MigrationOptions {
    /// dry_run: true, ..Default::default() }` only compiles *inside*
    /// this crate -- a downstream caller needs `let mut o =
    /// MigrationOptions::default(); o.dry_run = true;` or this method
    /// chain instead: `MigrationOptions::default().with_dry_run(true)`.
    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Builder-style setter; see [`Self::with_dry_run`] for why this
    /// exists instead of a struct literal.
    pub fn with_accept_legacy_v0(mut self, accept_legacy_v0: bool) -> Self {
        self.accept_legacy_v0 = accept_legacy_v0;
        self
    }
}

/// Re-encrypts every already-plaintext value under `prefix` in the given
/// KV storage, in place.
///
/// - **Idempotent and resumable**: a value already in the *current*
///   envelope format is left untouched. Re-running this function (e.g.
///   after it was interrupted, or because some keys were skipped as
///   `failed`) only ever touches the plaintext and not-yet-upgraded v0
///   values still remaining -- there's no separate resume cursor to
///   manage.
/// - **A single undecryptable v0 envelope never aborts the run**: if one
///   key's format-version-0 envelope can't be decrypted under any
///   loaded key (wrong/missing key, or corrupted -- only v0 envelopes
///   are decrypt-checked this way, see
///   [`KvEncryptionMigrationReport::failed`]'s own docs), a safe
///   identifier for it (never the raw key) is recorded in `failed` and
///   it's skipped -- every other key is still processed. Anyone who can
///   write one envelope-shaped value under `prefix` can otherwise make
///   an `?` on the first failure block the entire run.
/// - **Dry-run is accurate, not optimistic**: `dry_run: true` actually
///   attempts every decrypt it would need for a real run (it just skips
///   the write-back), so its counts -- including `failed` -- match what
///   a real run would do, rather than assuming every v0 envelope found
///   would succeed.
/// - **Format-version-0 upgrades require `accept_legacy_v0: true` AND a
///   real (non-dry) run.** A v0 envelope has no AAD, so decrypting it
///   proves nothing about *which record* its plaintext actually belongs
///   to -- it decrypts successfully under any loaded key regardless of
///   where it's stored. **This function cannot detect a v0 envelope
///   that's been copied from one record onto another**; it can only
///   decrypt-then-re-encrypt whatever is there, inheriting that
///   plaintext's association with this key exactly as unverified as it
///   was before. `accept_legacy_v0` exists so that upgrading is never a
///   silent, implicit side effect of running this function -- an
///   operator must explicitly accept that risk. With it `false` (or in
///   a dry run), v0 envelopes are still *decrypted* for reporting
///   accuracy (see the bullet above) and counted in
///   [`KvEncryptionMigrationReport::legacy_v0_found`], but never
///   written back; `upgraded_from_legacy` only increases on an actual
///   real-run upgrade. Every real upgrade logs one `tracing::warn!` line
///   naming a safe identifier for the record (never its raw key or
///   value -- see below).
/// - **Never logs or reports the raw storage key, plaintext, or
///   ciphertext**: in this crate, some storage keys are themselves
///   bearer secrets (e.g. `api_key:{raw_api_key}`), so logging a key
///   name verbatim can leak a working credential. Everywhere this
///   function logs or reports a record (`tracing::warn!` lines,
///   [`KvEncryptionMigrationReport::failed`]), it uses a short,
///   non-reversible, safe identifier instead of the raw key; callers
///   should preserve that if they add their own logging around this.
/// - **Not safe to run concurrently with live writes to the same keys**:
///   this does a read, then a write-back, with no compare-and-swap. If
///   something else writes a fresh value to a key between this function's
///   read and write, the write-back here overwrites it with the stale
///   value it read. Run this offline, or at least pause writers to the
///   given `prefix`, before running it against a live deployment.
///
/// `storage` and `encryption` are the same values the caller would pass to
/// [`EncryptedStorage::new`] -- this function talks to the *inner*,
/// unwrapped storage directly, since [`EncryptedStorage::get_kv`] would
/// already transparently decrypt (and thus hide which rows still need
/// migrating).
///
/// **TTLs are preserved** on backends that report them
/// ([`AuthStorage::tracks_kv_ttl`]): each rewritten entry is stored with
/// the remaining TTL it had (read via [`AuthStorage::get_kv_ttl`] before the
/// value, so an entry that expires mid-run is skipped, never made
/// permanent). A backend that cannot report TTLs would turn every expiring
/// entry (OAuth codes, MFA/SMS codes, WebAuthn challenges, rate-limit
/// windows, expiring API keys) permanent, so a real (non-dry) run on one is
/// **refused** unless [`MigrationOptions::accept_ttl_loss`] is set; if it
/// is, scope `prefix` to durable-secret namespaces only. The CLI
/// (`security encrypt-kv`) exposes this as `--accept-ttl-loss`.
pub async fn migrate_kv_to_encrypted<S: AuthStorage + ?Sized>(
    storage: &S,
    encryption: &StorageEncryption,
    prefix: &str,
    options: MigrationOptions,
) -> Result<KvEncryptionMigrationReport> {
    let MigrationOptions {
        dry_run,
        accept_legacy_v0,
        accept_ttl_loss,
    } = options;

    // A backend that cannot report TTLs would have every expiring entry
    // re-stored as permanent. Refuse before touching anything unless the
    // caller accepts that; a dry run writes nothing, so it is always fine.
    if !dry_run && !accept_ttl_loss && !storage.tracks_kv_ttl() {
        return Err(AuthError::validation(
            "This storage backend does not report KV TTLs, so migrating would make every \
             expiring entry (OAuth codes, MFA/SMS codes, rate-limit windows, expiring API \
             keys, ...) permanent. Scope the prefix to durable secrets and pass \
             accept_ttl_loss (CLI: --accept-ttl-loss) to proceed anyway.",
        ));
    }
    let mut report = KvEncryptionMigrationReport {
        dry_run,
        ..Default::default()
    };

    let keys = storage.list_kv_keys(prefix).await?;
    report.scanned = keys.len() as u64;

    for key in keys {
        // The TTL is read BEFORE the value (see the maintenance snapshot
        // code): an entry that expires in between yields a TTL and no value
        // (counted as vanished), never a value whose expiry was lost.
        let ttl = storage.get_kv_ttl(&key).await?;
        let Some(mut raw) = storage.get_kv(&key).await? else {
            // Deleted concurrently between list_kv_keys and get_kv.
            report.vanished += 1;
            continue;
        };

        if let Some(envelope) = StorageEncryption::parse_envelope(&raw) {
            if envelope.v >= CURRENT_FORMAT_VERSION {
                report.already_encrypted += 1;
                continue;
            }

            // Format-version-0 envelope: always attempt the decrypt (so
            // dry-run reporting is accurate), but never let a failure
            // here abort the rest of the run.
            match encryption.decrypt(&envelope, key.as_bytes()) {
                Err(_) => {
                    tracing::warn!(
                        record = %safe_log_id(&key),
                        "migrate_kv_to_encrypted: could not decrypt format-version-0 \
                         envelope with any loaded key -- skipping, not aborting the rest \
                         of the run"
                    );
                    report.failed.push(safe_log_id(&key));
                }
                Ok(mut plaintext) => {
                    report.legacy_v0_found += 1;
                    if !dry_run && accept_legacy_v0 {
                        if envelope.v == 0 {
                            tracing::warn!(
                                record = %safe_log_id(&key),
                                "migrate_kv_to_encrypted: upgrading format-version-0 \
                                 envelope to the current format -- v0 has no AAD, so this \
                                 plaintext's association with this specific key was not \
                                 cryptographically verified by this upgrade"
                            );
                        } else {
                            tracing::info!(
                                record = %safe_log_id(&key),
                                v = envelope.v,
                                "migrate_kv_to_encrypted: upgrading legacy envelope to the \
                                 current format (its AAD bound the record key)"
                            );
                        }
                        let encrypt_result =
                            encryption.encrypt_for_storage(&plaintext, key.as_bytes());
                        plaintext.zeroize();
                        let new_envelope = encrypt_result?;
                        storage.store_kv(&key, &new_envelope, ttl).await?;
                        report.upgraded_from_legacy += 1;
                    } else {
                        plaintext.zeroize();
                    }
                }
            }
            continue;
        }

        report.encrypted += 1;
        if !dry_run {
            let encrypt_result = encryption.encrypt_for_storage(&raw, key.as_bytes());
            raw.zeroize();
            let envelope = encrypt_result?;
            storage.store_kv(&key, &envelope, ttl).await?;
        } else {
            raw.zeroize();
        }
    }

    Ok(report)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::MemoryStorage;

    #[test]
    fn test_key_generation() {
        let key = StorageEncryption::generate_key();
        assert!(!key.is_empty());
        let decoded = BASE64.decode(&key).unwrap();
        assert_eq!(decoded.len(), 32);
    }

    #[test]
    fn test_encrypt_decrypt_roundtrip() {
        let enc = StorageEncryption::new_random();
        let plaintext = b"super secret totp seed, not utf8 safe either: \xff\xfe";
        let encrypted = enc.encrypt(plaintext, b"user:alice:totp_secret").unwrap();
        let decrypted = enc.decrypt(&encrypted, b"user:alice:totp_secret").unwrap();
        assert_eq!(decrypted, plaintext);
    }

    /// Proves the AAD actually binds the ciphertext to its storage key:
    /// decrypting under a DIFFERENT aad than it was encrypted with must
    /// fail, not silently succeed with wrong-but-plausible plaintext. This
    /// is the mechanism that stops a ciphertext from being swapped between
    /// two records.
    #[test]
    fn test_decrypt_rejects_wrong_aad() {
        let enc = StorageEncryption::new_random();
        let encrypted = enc
            .encrypt(b"alice's secret", b"user:alice:totp_secret")
            .unwrap();
        let result = enc.decrypt(&encrypted, b"user:bob:totp_secret");
        assert!(
            result.is_err(),
            "decrypting with the wrong AAD (a different record's key) must fail"
        );
    }

    /// Proves nonces are actually random per call, not reused -- the
    /// security of AES-GCM depends on this. Encrypts the same plaintext
    /// many times and checks every nonce is unique.
    #[test]
    fn test_nonces_are_unique_across_many_encryptions() {
        let enc = StorageEncryption::new_random();
        let mut seen = std::collections::HashSet::new();
        for _ in 0..1000 {
            let encrypted = enc
                .encrypt(b"same plaintext every time", b"same:aad")
                .unwrap();
            assert_eq!(
                BASE64.decode(&encrypted.nonce).unwrap().len(),
                12,
                "nonce must be 96 bits"
            );
            assert!(
                seen.insert(encrypted.nonce.clone()),
                "nonce reused across encryptions -- this breaks AES-GCM's security guarantee"
            );
        }
    }

    #[test]
    fn test_storage_roundtrip_non_utf8_bytes() {
        let enc = StorageEncryption::new_random();
        let raw_salt: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0xFF, 0x80, 0x81];
        let stored = enc.encrypt_for_storage(raw_salt, b"salt:key").unwrap();
        let restored = enc.decrypt_from_storage(&stored, b"salt:key").unwrap();
        assert_eq!(restored, raw_salt);
    }

    /// A key provider that resolves to no usable key at all must make
    /// construction fail, not silently produce a `StorageEncryption` that
    /// can't actually encrypt anything (e.g. by skipping encryption).
    struct EmptyKeyProvider;
    impl KeyProvider for EmptyKeyProvider {
        fn load_keys(&self) -> Result<LoadedKeys> {
            Err(AuthError::config("no key configured (test)"))
        }
    }

    #[test]
    fn test_construction_fails_closed_with_no_key() {
        let result = StorageEncryption::new(&EmptyKeyProvider);
        assert!(
            result.is_err(),
            "StorageEncryption::new must fail, not silently construct an unusable/no-op encryptor"
        );
    }

    struct FixedKeyProvider(LoadedKeys);
    impl KeyProvider for FixedKeyProvider {
        fn load_keys(&self) -> Result<LoadedKeys> {
            Ok(LoadedKeys {
                current_key_id: self.0.current_key_id.clone(),
                keys: self.0.keys.clone(),
            })
        }
    }

    #[test]
    fn test_construction_rejects_empty_key_id() {
        // current_key_id is non-empty and present in the map (so the
        // separate, earlier checks for "current_key_id is empty" and
        // "current_key_id isn't in the map" don't fire first) -- this
        // specifically exercises the "no key in the map has an empty id"
        // check via a SECOND entry.
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [1u8; 32]);
        keys.insert(String::new(), [2u8; 32]);
        let result = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }));
        assert!(
            result.is_err(),
            "an empty key id anywhere in the loaded key set must be rejected (it's reserved \
             for format-version-0 envelopes), even when current_key_id itself is valid"
        );
    }

    /// Key rotation: an envelope encrypted under an OLD key must still
    /// decrypt once the current key id has moved on, as long as the old
    /// key is still present in the loaded key set.
    struct TwoKeyProvider {
        current_id: String,
        old_key: [u8; 32],
        new_key: [u8; 32],
        old_id: String,
    }
    impl KeyProvider for TwoKeyProvider {
        fn load_keys(&self) -> Result<LoadedKeys> {
            let mut keys = HashMap::new();
            keys.insert(self.old_id.clone(), self.old_key);
            keys.insert(self.current_id.clone(), self.new_key);
            Ok(LoadedKeys {
                current_key_id: self.current_id.clone(),
                keys,
            })
        }
    }

    #[test]
    fn test_old_key_still_decrypts_after_rotation() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [7u8; 32]);
        let enc_before_rotation = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();
        let old_envelope = enc_before_rotation
            .encrypt(b"written before rotation", b"some:key")
            .unwrap();
        assert_eq!(old_envelope.key_id, "1");

        // Now rotate: current key id moves to "2", but "1" is kept around.
        let provider = TwoKeyProvider {
            current_id: "2".to_string(),
            old_id: "1".to_string(),
            old_key: [7u8; 32],
            new_key: [9u8; 32],
        };
        let enc_after_rotation = StorageEncryption::new(&provider).unwrap();

        // New writes use the new key.
        let new_envelope = enc_after_rotation
            .encrypt(b"written after rotation", b"some:key")
            .unwrap();
        assert_eq!(new_envelope.key_id, "2");

        // The OLD envelope (key_id "1") must still decrypt.
        let decrypted_old = enc_after_rotation
            .decrypt(&old_envelope, b"some:key")
            .unwrap();
        assert_eq!(decrypted_old, b"written before rotation");
    }

    /// Format-version-0 compatibility: an envelope shaped like the
    /// original (pre-redesign) `EncryptedStorage` produced -- no `key_id`,
    /// no `v`, no AAD at encryption time -- must still decrypt under the
    /// new `StorageEncryption`, since real deployments may already hold
    /// data in that shape.
    #[test]
    fn test_decrypts_format_version_0_envelope() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [3u8; 32]);
        let enc = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        // Hand-build a format-version-0 envelope the way the original
        // `EncryptedStorage::encrypt` did: no AAD, no key_id, no v.
        let cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[3u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [5u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let ciphertext = cipher
            .encrypt(nonce, b"legacy-format plaintext".as_ref())
            .unwrap();
        let legacy_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&ciphertext),
            BASE64.encode(nonce_bytes)
        );

        assert!(StorageEncryption::looks_like_envelope(
            legacy_json.as_bytes()
        ));
        let decrypted = enc
            .decrypt_from_storage(legacy_json.as_bytes(), b"irrelevant-for-v0")
            .unwrap();
        assert_eq!(decrypted, b"legacy-format plaintext".to_vec());
    }

    /// Negative case for the v0 downgrade attack: a GENUINE current-format
    /// (v1) envelope, with its `v` and `key_id` fields stripped (so it now
    /// parses as a v0-shaped envelope), must not be accepted as that
    /// record's value. It fails for two independent reasons here -- the
    /// policy check (`allow_legacy_v0: false` by default) rejects it before
    /// any decryption is attempted, and even without that check the
    /// ciphertext itself was sealed with a real (non-empty) AAD, so the v0
    /// path's empty-AAD decrypt attempt would fail the authentication tag
    /// anyway.
    #[tokio::test]
    async fn test_wrapper_rejects_v1_envelope_downgraded_to_look_like_v0() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [4u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        let inner = MemoryStorage::new();
        let wrapped = EncryptedStorage::new(inner, encryption, false, false);

        wrapped
            .store_kv("user:alice:totp_secret", b"real secret", None)
            .await
            .unwrap();

        let inner = wrapped.into_inner();
        let real_envelope: EncryptedData = serde_json::from_slice(
            &inner
                .get_kv("user:alice:totp_secret")
                .await
                .unwrap()
                .unwrap(),
        )
        .unwrap();

        // Strip the fields a v0 envelope never had, simulating an
        // attacker (or a bug) downgrading a real v1 envelope.
        let downgraded_json = serde_json::json!({
            "data": real_envelope.data,
            "nonce": real_envelope.nonce,
            "algorithm": real_envelope.algorithm,
        })
        .to_string();
        inner
            .store_kv("user:alice:totp_secret", downgraded_json.as_bytes(), None)
            .await
            .unwrap();

        let mut keys2 = HashMap::new();
        keys2.insert("1".to_string(), [4u8; 32]);
        let encryption2 = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys: keys2,
        }))
        .unwrap();
        let wrapped = EncryptedStorage::new(inner, encryption2, false, false);

        let result = wrapped.get_kv("user:alice:totp_secret").await;
        assert!(
            result.is_err(),
            "a v1 envelope downgraded to look like v0 must not be accepted as the record's \
             value, with allow_legacy_v0 at its default (false)"
        );
    }

    #[tokio::test]
    async fn test_list_kv_keys_passes_through_unencrypted() {
        let inner = MemoryStorage::new();
        inner
            .store_kv("prefix:a", b"ignored by this test", None)
            .await
            .unwrap();
        inner
            .store_kv("prefix:b", b"ignored by this test", None)
            .await
            .unwrap();
        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);

        let mut keys = wrapped.list_kv_keys("prefix:").await.unwrap();
        keys.sort();
        assert_eq!(
            keys,
            vec!["prefix:a".to_string(), "prefix:b".to_string()],
            "list_kv_keys must pass through to the inner backend, not use the trait's \
             empty-Vec default"
        );
    }

    #[tokio::test]
    async fn test_encrypted_storage_roundtrip() {
        let inner = MemoryStorage::new();
        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);

        wrapped
            .store_kv("user:alice:totp_secret", b"JBSWY3DPEHPK3PXP", None)
            .await
            .unwrap();
        let value = wrapped.get_kv("user:alice:totp_secret").await.unwrap();
        assert_eq!(value, Some(b"JBSWY3DPEHPK3PXP".to_vec()));
    }

    /// Proves the wrapper actually changes what's on disk/in the backend
    /// -- reading through the INNER storage directly (bypassing
    /// `EncryptedStorage`) must NOT show the plaintext.
    #[tokio::test]
    async fn test_encrypted_storage_actually_encrypts_the_underlying_value() {
        let wrapped = EncryptedStorage::new(
            MemoryStorage::new(),
            StorageEncryption::new_random(),
            false,
            false,
        );

        wrapped
            .store_kv("user:alice:totp_secret", b"JBSWY3DPEHPK3PXP", None)
            .await
            .unwrap();

        let inner = wrapped.into_inner();
        let raw = inner
            .get_kv("user:alice:totp_secret")
            .await
            .unwrap()
            .unwrap();
        assert_ne!(
            raw,
            b"JBSWY3DPEHPK3PXP".to_vec(),
            "the underlying storage must not hold the plaintext value"
        );
        assert!(
            StorageEncryption::looks_like_envelope(&raw),
            "the underlying storage must hold a proper encrypted envelope"
        );
    }

    /// Proves the wrapper's own AAD wiring (not just `StorageEncryption`
    /// directly, which `test_decrypt_rejects_wrong_aad` already covers) --
    /// swapping two records' raw envelopes in the INNER backend must make
    /// both unreadable through the wrapper, because each envelope's AAD no
    /// longer matches the key it's stored under. If the wrapper passed a
    /// constant (e.g. empty) AAD instead of the real key, this swap would
    /// go undetected and both reads would "succeed" with the wrong value.
    #[tokio::test]
    async fn test_wrapper_rejects_ciphertext_swapped_between_records() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [11u8; 32]);
        let loaded = LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        };
        let encryption_for_wrapper = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: loaded.current_key_id.clone(),
            keys: loaded.keys.clone(),
        }))
        .unwrap();
        // An independent `StorageEncryption` built from the SAME key, used
        // only to verify what AAD the wrapper actually used -- never to
        // produce the envelopes under test.
        let encryption_for_verification =
            StorageEncryption::new(&FixedKeyProvider(loaded)).unwrap();

        let inner = MemoryStorage::new();
        let wrapped = EncryptedStorage::new(inner, encryption_for_wrapper, false, false);

        wrapped
            .store_kv("user:alice:totp_secret", b"alice-secret", None)
            .await
            .unwrap();

        let inner = wrapped.into_inner();
        let raw = inner
            .get_kv("user:alice:totp_secret")
            .await
            .unwrap()
            .unwrap();

        // The wrapper must have used the storage key itself as AAD: decrypting
        // with that exact AAD must succeed...
        let decrypted = encryption_for_verification
            .decrypt(
                &serde_json::from_slice(&raw).unwrap(),
                b"user:alice:totp_secret",
            )
            .unwrap();
        assert_eq!(decrypted, b"alice-secret".to_vec());

        // ...and decrypting the SAME envelope under a DIFFERENT record's key
        // name must fail. If the wrapper instead used some constant AAD (the
        // exact mutation this test exists to catch), this swap-style check
        // would succeed instead of failing.
        let wrong_aad_result = encryption_for_verification.decrypt(
            &serde_json::from_slice(&raw).unwrap(),
            b"user:bob:totp_secret",
        );
        assert!(
            wrong_aad_result.is_err(),
            "the wrapper's envelope must not decrypt under a different record's key name -- \
             if it does, the wrapper is using a constant AAD instead of the real storage key"
        );
    }

    /// A value stored by some pre-encryption version of the framework (or
    /// while `storage_encryption.enabled = false`) is readable when
    /// `allow_plaintext_reads` is explicitly true (the migration-window
    /// setting).
    #[tokio::test]
    async fn test_reads_legacy_plaintext_when_allowed() {
        let inner = MemoryStorage::new();
        inner
            .store_kv("legacy:key", b"pre-existing plaintext value", None)
            .await
            .unwrap();
        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), true, false);

        let value = wrapped.get_kv("legacy:key").await.unwrap();
        assert_eq!(value, Some(b"pre-existing plaintext value".to_vec()));
    }

    /// With `allow_plaintext_reads` false (the normal, post-migration
    /// setting), a value that isn't a valid envelope -- whether genuine
    /// untouched legacy plaintext, a corrupted envelope, or an attacker's
    /// overwrite -- must be a hard error, not silently accepted. This is
    /// the fix for the finding that an attacker able to write to the
    /// backing store could otherwise overwrite an encrypted secret with
    /// chosen plaintext and have it accepted forever.
    #[tokio::test]
    async fn test_rejects_non_envelope_value_when_plaintext_reads_disallowed() {
        let inner = MemoryStorage::new();
        inner
            .store_kv("user:alice:totp_secret", b"attacker-chosen-plaintext", None)
            .await
            .unwrap();
        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);

        let result = wrapped.get_kv("user:alice:totp_secret").await;
        assert!(
            result.is_err(),
            "a non-envelope value must be rejected, not silently treated as plaintext, \
             when allow_plaintext_reads is false"
        );
    }

    /// The real fix for the v0-downgrade finding: a format-version-0
    /// envelope must be actively rewritten to the current format by
    /// migration (not just counted as "already encrypted" and left
    /// alone), since nothing else in this crate ever upgrades one.
    #[tokio::test]
    async fn test_migration_upgrades_v0_envelope_to_current_format() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [6u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        // Hand-build a v0 envelope the way the original pre-redesign
        // `EncryptedStorage` did (no AAD, no key_id, no v).
        let cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[6u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [8u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
        let v0_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&ciphertext),
            BASE64.encode(nonce_bytes)
        );

        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:legacy", v0_json.as_bytes(), None)
            .await
            .unwrap();

        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: true,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(
            report.legacy_v0_found, 1,
            "a decryptable v0 envelope must be counted as found"
        );
        assert_eq!(
            report.upgraded_from_legacy, 1,
            "with accept_legacy_v0 true on a real run, it must actually be upgraded"
        );
        assert_eq!(report.already_encrypted, 0);
        assert!(report.failed.is_empty());

        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
        let envelope_after: EncryptedData = serde_json::from_slice(&raw_after).unwrap();
        assert_eq!(
            envelope_after.v, CURRENT_FORMAT_VERSION,
            "the stored envelope must now be the current format, not still v0"
        );
        assert!(
            !envelope_after.key_id.is_empty(),
            "the upgraded envelope must have a real key_id"
        );

        // The upgraded envelope must decrypt correctly through the
        // normal (AAD-bound) path -- not just via the v0 fallback.
        let decrypted = encryption
            .decrypt(&envelope_after, b"secret:legacy")
            .unwrap();
        assert_eq!(decrypted, b"v0 secret".to_vec());

        // Idempotent: running it again finds nothing left to upgrade.
        let report2 = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(report2.upgraded_from_legacy, 0);
        assert_eq!(report2.already_encrypted, 1);
    }

    /// Without `accept_legacy_v0`, a decryptable v0 envelope is reported
    /// (`legacy_v0_found`) but never written back as the current format --
    /// this is the fix for the laundering finding: upgrading must never be
    /// an implicit side effect of just running the migration.
    #[tokio::test]
    async fn test_migration_does_not_upgrade_legacy_v0_without_accept_flag() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [7u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        let cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[7u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [3u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
        let v0_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&ciphertext),
            BASE64.encode(nonce_bytes)
        );

        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:legacy", v0_json.as_bytes(), None)
            .await
            .unwrap();

        // Real run (not dry), but accept_legacy_v0 is false.
        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(
            report.legacy_v0_found, 1,
            "the v0 envelope must still be detected/decrypted"
        );
        assert_eq!(
            report.upgraded_from_legacy, 0,
            "without accept_legacy_v0, nothing must actually be rewritten"
        );

        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
        assert_eq!(
            raw_after,
            v0_json.as_bytes(),
            "the stored envelope must be byte-for-byte unchanged without accept_legacy_v0"
        );
    }

    /// Fix for the "one bad record aborts the whole run" finding: a v0
    /// envelope that fails to decrypt under any loaded key must be
    /// skipped and reported by name, not abort processing of the other
    /// keys in the same run.
    #[tokio::test]
    async fn test_migration_skips_undecryptable_v0_envelope_without_aborting() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [9u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        // A v0-shaped envelope with ciphertext that will NOT decrypt
        // under the loaded key (wrong key material entirely).
        let bad_cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[0u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [1u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let bad_ciphertext = bad_cipher
            .encrypt(nonce, b"undecryptable".as_ref())
            .unwrap();
        let bad_v0_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&bad_ciphertext),
            BASE64.encode(nonce_bytes)
        );

        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:bad", bad_v0_json.as_bytes(), None)
            .await
            .unwrap();
        storage
            .store_kv("secret:good_a", b"plaintext-a", None)
            .await
            .unwrap();
        storage
            .store_kv("secret:good_b", b"plaintext-b", None)
            .await
            .unwrap();

        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: true,
                ..Default::default()
            },
        )
        .await
        .expect("one undecryptable record must not abort the whole migration");

        assert_eq!(report.scanned, 3);
        assert_eq!(
            report.failed,
            vec![safe_log_id("secret:bad")],
            "the undecryptable record must be named (as a safe identifier, not the raw \
             key) in `failed`, not silently dropped"
        );
        assert_eq!(
            report.encrypted, 2,
            "the other two plaintext keys must still be processed despite the bad one"
        );

        let good_a_after = storage.get_kv("secret:good_a").await.unwrap().unwrap();
        assert!(StorageEncryption::looks_like_envelope(&good_a_after));
        let good_b_after = storage.get_kv("secret:good_b").await.unwrap().unwrap();
        assert!(StorageEncryption::looks_like_envelope(&good_b_after));

        // The bad record itself is untouched (still its original bytes).
        let bad_after = storage.get_kv("secret:bad").await.unwrap().unwrap();
        assert_eq!(bad_after, bad_v0_json.as_bytes());
    }

    /// Fix for "dry run lies": a dry run must actually attempt the v0
    /// decrypt (not just assume success), so an undecryptable v0 envelope
    /// shows up in `failed` during a dry run too, matching what a real
    /// run would report.
    #[tokio::test]
    async fn test_migration_dry_run_detects_undecryptable_v0_envelope() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [5u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        let bad_cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[0u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [2u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let bad_ciphertext = bad_cipher
            .encrypt(nonce, b"undecryptable".as_ref())
            .unwrap();
        let bad_v0_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&bad_ciphertext),
            BASE64.encode(nonce_bytes)
        );

        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:bad", bad_v0_json.as_bytes(), None)
            .await
            .unwrap();

        let dry_report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: true,
                accept_legacy_v0: true,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(
            dry_report.failed,
            vec![safe_log_id("secret:bad")],
            "a dry run must actually attempt the decrypt and report the same failure a \
             real run would, not optimistically assume every v0 envelope would succeed"
        );
        assert_eq!(dry_report.upgraded_from_legacy, 0);
        assert_eq!(dry_report.legacy_v0_found, 0);
    }

    /// Fix for the high-severity finding: some storage keys in this
    /// crate ARE bearer secrets (`api_key:{raw_key}`), so a safe log
    /// identifier must never contain the raw key material -- only the
    /// namespace and a hash.
    #[test]
    fn test_safe_log_id_never_contains_the_raw_secret() {
        let raw_secret = "ak_live_super_secret_bearer_token_12345";
        let key = format!("api_key:{raw_secret}");
        let id = safe_log_id(&key);

        assert!(
            !id.contains(raw_secret),
            "safe_log_id must never contain the raw secret portion of the key, got: {id}"
        );
        assert!(
            id.starts_with("api_key:"),
            "safe_log_id should keep the (non-secret) namespace prefix, got: {id}"
        );
        // Deterministic, so an operator with storage access can
        // recompute it to correlate a logged identifier back to a
        // specific record.
        assert_eq!(id, safe_log_id(&key));
    }

    /// A key with no `:` at all has no non-secret namespace prefix to
    /// keep -- `key.split(':').next()` on a colonless key returns the
    /// WHOLE key, which would print the raw secret verbatim. This is
    /// the fix for that gap.
    #[test]
    fn test_safe_log_id_handles_colonless_key_without_leaking_it() {
        let raw_secret = "a_bearer_token_with_no_colon_in_it_at_all";
        let id = safe_log_id(raw_secret);

        assert!(
            !id.contains(raw_secret),
            "a colonless key must not appear verbatim in its safe_log_id, got: {id}"
        );
        assert!(
            id.starts_with("key:"),
            "a colonless key should fall back to the literal 'key:' prefix, got: {id}"
        );
    }

    /// Kills the mutation `if !dry_run && accept_legacy_v0` ->
    /// `if accept_legacy_v0` (dropping the dry-run check): with
    /// accept_legacy_v0 true but dry_run also true, over a DECRYPTABLE
    /// v0 record, nothing must be written -- the only existing
    /// dry-run-with-flag test used an undecryptable record, which never
    /// reaches this branch at all.
    #[tokio::test]
    async fn test_dry_run_with_accept_legacy_v0_does_not_write_a_decryptable_v0_record() {
        let mut keys = HashMap::new();
        keys.insert("1".to_string(), [4u8; 32]);
        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
            current_key_id: "1".to_string(),
            keys,
        }))
        .unwrap();

        let cipher = {
            let key = Key::<Aes256Gcm>::from_slice(&[4u8; 32]);
            Aes256Gcm::new(key)
        };
        let nonce_bytes = [6u8; 12];
        let nonce = Nonce::from_slice(&nonce_bytes);
        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
        let v0_json = format!(
            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
            BASE64.encode(&ciphertext),
            BASE64.encode(nonce_bytes)
        );

        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:legacy", v0_json.as_bytes(), None)
            .await
            .unwrap();

        // dry_run: true AND accept_legacy_v0: true.
        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: true,
                accept_legacy_v0: true,
                ..Default::default()
            },
        )
        .await
        .unwrap();

        assert_eq!(
            report.legacy_v0_found, 1,
            "a dry run must still report a decryptable v0 record as found"
        );
        assert_eq!(
            report.upgraded_from_legacy, 0,
            "a dry run must never actually upgrade anything, even with accept_legacy_v0 true"
        );

        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
        assert_eq!(
            raw_after,
            v0_json.as_bytes(),
            "a dry run with accept_legacy_v0 true must leave the record byte-for-byte \
             unchanged"
        );
    }

    #[tokio::test]
    async fn test_migration_dry_run_reports_without_writing() {
        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:a", b"plaintext-a", None)
            .await
            .unwrap();
        storage
            .store_kv("secret:b", b"plaintext-b", None)
            .await
            .unwrap();
        let encryption = StorageEncryption::new_random();

        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: true,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();

        assert!(report.dry_run);
        assert_eq!(report.scanned, 2);
        assert_eq!(report.encrypted, 2);
        assert_eq!(report.already_encrypted, 0);

        // Dry run must not have written anything.
        let still_plaintext = storage.get_kv("secret:a").await.unwrap().unwrap();
        assert_eq!(still_plaintext, b"plaintext-a".to_vec());
    }

    #[tokio::test]
    async fn test_migration_encrypts_plaintext_values() {
        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:a", b"plaintext-a", None)
            .await
            .unwrap();
        let encryption = StorageEncryption::new_random();

        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(report.encrypted, 1);

        let raw = storage.get_kv("secret:a").await.unwrap().unwrap();
        assert!(StorageEncryption::looks_like_envelope(&raw));
        let decrypted = encryption.decrypt_from_storage(&raw, b"secret:a").unwrap();
        assert_eq!(decrypted, b"plaintext-a".to_vec());
    }

    /// Proves idempotency and resumability: running the migration a
    /// second time over a mix of already-migrated and still-plaintext
    /// keys (simulating an interrupted first run) must not re-encrypt
    /// (double-encrypt) the already-done ones, and must finish the rest.
    #[tokio::test]
    async fn test_migration_is_idempotent_and_resumable() {
        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:a", b"plaintext-a", None)
            .await
            .unwrap();
        storage
            .store_kv("secret:b", b"plaintext-b", None)
            .await
            .unwrap();
        let encryption = StorageEncryption::new_random();

        // Simulate a first run that only got through "secret:a" before
        // being interrupted.
        let envelope_a = encryption
            .encrypt_for_storage(b"plaintext-a", b"secret:a")
            .unwrap();
        storage
            .store_kv("secret:a", &envelope_a, None)
            .await
            .unwrap();

        // Resume: should skip "secret:a" (already encrypted) and finish
        // "secret:b".
        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(report.scanned, 2);
        assert_eq!(report.already_encrypted, 1);
        assert_eq!(report.encrypted, 1);

        let raw_a_after = storage.get_kv("secret:a").await.unwrap().unwrap();
        assert_eq!(
            raw_a_after, envelope_a,
            "an already-encrypted value must be left byte-for-byte unchanged, not double-encrypted"
        );
        let raw_b_after = storage.get_kv("secret:b").await.unwrap().unwrap();
        assert!(StorageEncryption::looks_like_envelope(&raw_b_after));

        // Running it again changes nothing further.
        let report2 = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(report2.already_encrypted, 2);
        assert_eq!(report2.encrypted, 0);
    }

    #[tokio::test]
    async fn test_migration_only_touches_matching_prefix() {
        let storage = MemoryStorage::new();
        storage
            .store_kv("secret:a", b"plaintext-a", None)
            .await
            .unwrap();
        storage
            .store_kv("other:b", b"plaintext-b", None)
            .await
            .unwrap();
        let encryption = StorageEncryption::new_random();

        let report = migrate_kv_to_encrypted(
            &storage,
            &encryption,
            "secret:",
            MigrationOptions {
                dry_run: false,
                accept_legacy_v0: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(report.scanned, 1);

        let other_untouched = storage.get_kv("other:b").await.unwrap().unwrap();
        assert_eq!(
            other_untouched,
            b"plaintext-b".to_vec(),
            "a key outside the given prefix must not be touched"
        );
    }

    /// The wrapper must report the inner backend's TTL: restore (#121)
    /// reads it through the wrapper the framework actually holds.
    #[tokio::test]
    async fn wrapper_passes_kv_ttl_through() {
        let wrapped = EncryptedStorage::new(
            MemoryStorage::new(),
            StorageEncryption::new_random(),
            false,
            false,
        );
        wrapped
            .store_kv("k", b"v", Some(Duration::from_secs(600)))
            .await
            .unwrap();
        let ttl = wrapped.get_kv_ttl("k").await.unwrap().unwrap();
        assert!(ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600));
    }

    // ---- envelope v2 + hardening ------------------------------------------------

    struct FixedKeys {
        current: &'static str,
        keys: Vec<(&'static str, [u8; 32])>,
    }

    impl KeyProvider for FixedKeys {
        fn load_keys(&self) -> Result<LoadedKeys> {
            Ok(LoadedKeys {
                current_key_id: self.current.to_string(),
                keys: self
                    .keys
                    .iter()
                    .map(|(id, key)| (id.to_string(), *key))
                    .collect(),
            })
        }
    }

    const KEY_A: [u8; 32] = [0x11; 32];
    const KEY_B: [u8; 32] = [0x22; 32];

    /// Builds a stored envelope by hand, the way an OLDER writer would have:
    /// `aad` is used verbatim (v1 used the bare storage key).
    fn manual_envelope(
        key: &[u8; 32],
        key_id: &str,
        v: u8,
        plaintext: &[u8],
        aad: &[u8],
    ) -> Vec<u8> {
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
        let nonce_bytes = [7u8; 12];
        let ciphertext = cipher
            .encrypt(
                Nonce::from_slice(&nonce_bytes),
                Payload {
                    msg: plaintext,
                    aad,
                },
            )
            .unwrap();
        serde_json::to_vec(&EncryptedData {
            data: BASE64.encode(ciphertext),
            nonce: BASE64.encode(nonce_bytes),
            algorithm: "AES-256-GCM".to_string(),
            key_id: key_id.to_string(),
            v,
            key_derivation: String::new(),
        })
        .unwrap()
    }

    #[test]
    fn new_envelopes_use_format_v2() {
        let enc = StorageEncryption::new_random();
        assert_eq!(enc.encrypt(b"x", b"k").unwrap().v, 2);
    }

    /// v2 binds the envelope's own metadata into the AAD: the same key
    /// loaded under two ids must NOT let an attacker relabel `key_id`, and
    /// rewriting `v` to 1 (a downgrade to the AAD that ignores metadata)
    /// must not make a v2 ciphertext verify.
    #[test]
    fn v2_aad_binds_key_id_and_version() {
        let enc = StorageEncryption::new(&FixedKeys {
            current: "a",
            keys: vec![("a", KEY_A), ("b", KEY_A)],
        })
        .unwrap();
        let envelope = enc.encrypt(b"secret", b"rec:1").unwrap();
        assert_eq!(enc.decrypt(&envelope, b"rec:1").unwrap(), b"secret");

        let mut relabelled = envelope.clone();
        relabelled.key_id = "b".to_string();
        assert!(
            enc.decrypt(&relabelled, b"rec:1").is_err(),
            "relabelling key_id must fail authentication"
        );

        let mut downgraded = envelope.clone();
        downgraded.v = 1;
        assert!(
            enc.decrypt(&downgraded, b"rec:1").is_err(),
            "rewriting v to 1 must not make a v2 ciphertext verify"
        );
    }

    /// Format v1 (AAD = the bare storage key) is a LEGACY format now: only
    /// readable behind the allow-legacy policy, and the migration tool
    /// upgrades it to v2.
    #[tokio::test]
    async fn v1_envelopes_are_legacy_and_migrate_to_v2() {
        let storage = MemoryStorage::new();
        storage
            .store_kv(
                "rec:1",
                &manual_envelope(&KEY_A, "1", 1, b"secret", b"rec:1"),
                None,
            )
            .await
            .unwrap();
        let provider = || FixedKeys {
            current: "1",
            keys: vec![("1", KEY_A)],
        };

        let strict = EncryptedStorage::new(
            storage.clone(),
            StorageEncryption::new(&provider()).unwrap(),
            false,
            false,
        );
        assert!(
            strict.get_kv("rec:1").await.is_err(),
            "v1 must need the legacy policy"
        );

        let lenient = EncryptedStorage::new(
            storage.clone(),
            StorageEncryption::new(&provider()).unwrap(),
            false,
            true,
        );
        assert_eq!(lenient.get_kv("rec:1").await.unwrap().unwrap(), b"secret");

        let report = migrate_kv_to_encrypted(
            &storage,
            &StorageEncryption::new(&provider()).unwrap(),
            "",
            MigrationOptions::default().with_accept_legacy_v0(true),
        )
        .await
        .unwrap();
        assert_eq!(report.upgraded_from_legacy, 1, "{report:?}");

        let raw = storage.get_kv("rec:1").await.unwrap().unwrap();
        assert_eq!(StorageEncryption::parse_envelope(&raw).unwrap().v, 2);
        // (`MemoryStorage::clone` copies, so re-wrap the migrated storage.)
        let strict_after = EncryptedStorage::new(
            storage,
            StorageEncryption::new(&provider()).unwrap(),
            false,
            false,
        );
        assert_eq!(
            strict_after.get_kv("rec:1").await.unwrap().unwrap(),
            b"secret"
        );
    }

    /// After the upgrade, a v2 ciphertext copied onto another record must
    /// not decrypt (the AAD still binds it to its own key).
    #[tokio::test]
    async fn upgraded_records_cannot_be_swapped_between_keys() {
        let storage = MemoryStorage::new();
        for (key, secret) in [("rec:1", &b"one"[..]), ("rec:2", b"two")] {
            storage
                .store_kv(key, &manual_envelope(&KEY_A, "1", 0, secret, b""), None)
                .await
                .unwrap();
        }
        let provider = || FixedKeys {
            current: "1",
            keys: vec![("1", KEY_A)],
        };
        migrate_kv_to_encrypted(
            &storage,
            &StorageEncryption::new(&provider()).unwrap(),
            "",
            MigrationOptions::default().with_accept_legacy_v0(true),
        )
        .await
        .unwrap();

        let swapped = storage.get_kv("rec:1").await.unwrap().unwrap();
        storage.store_kv("rec:2", &swapped, None).await.unwrap();
        let strict = EncryptedStorage::new(
            storage,
            StorageEncryption::new(&provider()).unwrap(),
            false,
            false,
        );
        assert!(strict.get_kv("rec:2").await.is_err());
    }

    /// A plaintext JSON value that merely looks like an envelope must not be
    /// classified as one: v>=1 needs an explicit non-empty key_id.
    #[test]
    fn envelope_classification_requires_version_and_key_id() {
        let shape = |extra: &str| {
            format!(
                r#"{{"data":"AAAA","nonce":"AAAAAAAAAAAAAAAA","algorithm":"AES-256-GCM"{extra}}}"#
            )
        };
        // v2 without a key_id: not an envelope.
        assert!(StorageEncryption::parse_envelope(shape(r#","v":2"#).as_bytes()).is_none());
        // v1 with an empty key_id: not an envelope.
        assert!(
            StorageEncryption::parse_envelope(shape(r#","v":1,"key_id":"""#).as_bytes()).is_none()
        );
        // v2 with a key_id: an envelope.
        assert!(
            StorageEncryption::parse_envelope(shape(r#","v":2,"key_id":"1""#).as_bytes()).is_some()
        );
        // The original (v0) shape has neither field and is still recognised.
        assert!(StorageEncryption::parse_envelope(shape("").as_bytes()).is_some());
    }

    /// Every way decryption can fail yields the same error text, so the
    /// failure itself is not an oracle for which check tripped.
    #[test]
    fn decrypt_failures_share_one_error_text() {
        let enc = StorageEncryption::new(&FixedKeys {
            current: "a",
            keys: vec![("a", KEY_A), ("b", KEY_B)],
        })
        .unwrap();
        let good = enc.encrypt(b"secret", b"rec:1").unwrap();

        let mut bad_base64 = good.clone();
        bad_base64.data = "!!not base64!!".to_string();
        let mut short_nonce = good.clone();
        short_nonce.nonce = BASE64.encode([1u8; 4]);
        let mut unknown_key = good.clone();
        unknown_key.key_id = "zzz".to_string();
        let mut wrong_algorithm = good.clone();
        wrong_algorithm.algorithm = "ROT13".to_string();
        let mut tampered = good.clone();
        let mut raw = BASE64.decode(&tampered.data).unwrap();
        raw[0] ^= 0x01;
        tampered.data = BASE64.encode(raw);

        let messages: Vec<String> = [
            (&bad_base64, &b"rec:1"[..]),
            (&short_nonce, b"rec:1"),
            (&unknown_key, b"rec:1"),
            (&wrong_algorithm, b"rec:1"),
            (&tampered, b"rec:1"),
            (&good, b"rec:OTHER"),
        ]
        .iter()
        .map(|(envelope, aad)| enc.decrypt(envelope, aad).unwrap_err().to_string())
        .collect();
        assert!(
            messages.windows(2).all(|w| w[0] == w[1]),
            "decrypt failures must be indistinguishable, got: {messages:#?}"
        );
    }

    #[test]
    fn legacy_trial_decryption_order_is_stable() {
        let enc = StorageEncryption::new(&FixedKeys {
            current: "k0",
            keys: (0..8)
                .map(|i| {
                    let id: &'static str = Box::leak(format!("k{i}").into_boxed_str());
                    (id, [i as u8 + 1; 32])
                })
                .rev()
                .collect(),
        })
        .unwrap();
        let ids = enc.sorted_key_ids();
        let mut expected = ids.clone();
        expected.sort();
        assert_eq!(ids, expected);
        assert_eq!(ids.len(), 8);
    }

    #[test]
    fn safe_log_id_keeps_eight_hash_bytes() {
        let id = safe_log_id("api_key:abc123");
        let hash = id.strip_prefix("api_key:").unwrap();
        assert_eq!(hash.len(), 16, "8 bytes = 16 hex chars, got {id}");
        let colonless = safe_log_id("rawsecret");
        assert_eq!(colonless.strip_prefix("key:").unwrap().len(), 16);
    }

    // ---- key loading fails closed (review gap) ----------------------------------

    fn load_with_env(key: Option<&str>) -> Result<LoadedKeys> {
        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK.
        unsafe {
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
            match key {
                Some(key) => std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", key),
                None => std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY"),
            }
        }
        let result = EnvKeyProvider.load_keys();
        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
        unsafe { std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY") };
        result
    }

    #[test]
    fn malformed_env_keys_fail_closed() {
        assert!(load_with_env(None).is_err(), "no key at all");
        assert!(load_with_env(Some("")).is_err(), "empty key");
        assert!(
            load_with_env(Some("!!!not base64!!!")).is_err(),
            "bad base64"
        );
        assert!(
            load_with_env(Some(&BASE64.encode([1u8; 16]))).is_err(),
            "16-byte key"
        );
        assert!(
            load_with_env(Some(&BASE64.encode([1u8; 33]))).is_err(),
            "33-byte key"
        );
        assert!(load_with_env(Some(&BASE64.encode([1u8; 32]))).is_ok());
    }

    #[test]
    fn malformed_keys_file_fails_closed() {
        let dir = tempfile::tempdir().unwrap();
        let good = BASE64.encode([3u8; 32]);
        let cases: [(&str, String); 4] = [
            ("not json", "{{{".to_string()),
            (
                "current missing from keys",
                format!(r#"{{"current":"x","keys":{{"1":"{good}"}}}}"#),
            ),
            (
                "one malformed entry",
                format!(r#"{{"current":"1","keys":{{"1":"{good}","2":"short"}}}}"#),
            ),
            ("empty keys", r#"{"current":"1","keys":{}}"#.to_string()),
        ];
        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
        for (name, body) in cases {
            let path = dir.path().join("keys.json");
            std::fs::write(&path, body).unwrap();
            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK.
            unsafe {
                std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE", &path);
            }
            let result = EnvKeyProvider.load_keys();
            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
            unsafe { std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE") };
            assert!(result.is_err(), "{name} must fail closed");
        }
    }

    // ---- migration preserves KV TTLs ---------------------------------------------

    fn ttl_provider() -> FixedKeys {
        FixedKeys {
            current: "1",
            keys: vec![("1", KEY_A)],
        }
    }

    #[tokio::test]
    async fn migration_preserves_ttl_when_encrypting_plaintext() {
        let storage = MemoryStorage::new();
        storage
            .store_kv("otp:1", b"123456", Some(Duration::from_secs(600)))
            .await
            .unwrap();
        storage.store_kv("durable:1", b"keep", None).await.unwrap();

        migrate_kv_to_encrypted(
            &storage,
            &StorageEncryption::new(&ttl_provider()).unwrap(),
            "",
            MigrationOptions::default(),
        )
        .await
        .unwrap();

        let ttl = storage.get_kv_ttl("otp:1").await.unwrap().unwrap();
        assert!(
            ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600),
            "TTL must survive migration, got {ttl:?}"
        );
        assert_eq!(storage.get_kv_ttl("durable:1").await.unwrap(), None);
        let raw = storage.get_kv("otp:1").await.unwrap().unwrap();
        assert!(
            StorageEncryption::looks_like_envelope(&raw),
            "must be encrypted"
        );
    }

    #[tokio::test]
    async fn legacy_upgrade_preserves_ttl() {
        let storage = MemoryStorage::new();
        storage
            .store_kv(
                "rec:1",
                &manual_envelope(&KEY_A, "", 0, b"secret", b""),
                Some(Duration::from_secs(600)),
            )
            .await
            .unwrap();

        migrate_kv_to_encrypted(
            &storage,
            &StorageEncryption::new(&ttl_provider()).unwrap(),
            "",
            MigrationOptions::default().with_accept_legacy_v0(true),
        )
        .await
        .unwrap();

        let ttl = storage.get_kv_ttl("rec:1").await.unwrap().unwrap();
        assert!(ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600));
        let raw = storage.get_kv("rec:1").await.unwrap().unwrap();
        assert_eq!(
            StorageEncryption::parse_envelope(&raw).unwrap().v,
            CURRENT_FORMAT_VERSION
        );
    }

    /// A backend that cannot report TTLs must not be migrated silently: a
    /// real run would make every expiring entry permanent. It needs an
    /// explicit opt-in, and a dry run (which writes nothing) is always fine.
    #[tokio::test]
    async fn migration_refuses_backend_that_cannot_report_ttl_without_opt_in() {
        let storage = crate::testing::utilities::MockStorage::new();
        let encryption = StorageEncryption::new(&ttl_provider()).unwrap();

        assert!(
            migrate_kv_to_encrypted(&storage, &encryption, "", MigrationOptions::default())
                .await
                .is_err(),
            "a real run on a TTL-blind backend must be refused"
        );
        assert!(
            migrate_kv_to_encrypted(
                &storage,
                &encryption,
                "",
                MigrationOptions::default().with_dry_run(true)
            )
            .await
            .is_ok(),
            "a dry run writes nothing, so it is allowed"
        );
        assert!(
            migrate_kv_to_encrypted(
                &storage,
                &encryption,
                "",
                MigrationOptions::default().with_accept_ttl_loss(true)
            )
            .await
            .is_ok(),
            "explicit opt-in proceeds"
        );
    }

    #[tokio::test]
    async fn backends_that_honour_ttl_say_so() {
        let memory = MemoryStorage::new();
        assert!(memory.tracks_kv_ttl());
        let wrapped = EncryptedStorage::new(
            MemoryStorage::new(),
            StorageEncryption::new_random(),
            false,
            false,
        );
        assert!(
            wrapped.tracks_kv_ttl(),
            "the wrapper forwards the inner answer"
        );
        let shared: std::sync::Arc<dyn AuthStorage> = std::sync::Arc::new(MemoryStorage::new());
        assert!(shared.tracks_kv_ttl(), "the Arc impl forwards too");
        assert!(
            !crate::testing::utilities::MockStorage::new().tracks_kv_ttl(),
            "a backend that ignores TTLs must say so"
        );
    }

    // ---- keys-file permissions (L4) and env-key rotation warning (L3) ------------

    #[test]
    fn keys_file_mode_check_flags_group_and_other_access() {
        for open in [0o644, 0o640, 0o604, 0o660, 0o666, 0o777, 0o601, 0o610] {
            assert!(keys_file_mode_too_open(open), "{open:o} must be flagged");
        }
        for closed in [0o600, 0o400, 0o700, 0o500, 0o200] {
            assert!(!keys_file_mode_too_open(closed), "{closed:o} must pass");
        }
    }

    #[test]
    fn strict_permissions_env_parsing() {
        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
        let read = |value: Option<&str>| {
            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
            unsafe {
                match value {
                    Some(v) => std::env::set_var(STRICT_KEY_FILE_PERMISSIONS_ENV, v),
                    None => std::env::remove_var(STRICT_KEY_FILE_PERMISSIONS_ENV),
                }
            }
            strict_permissions_requested()
        };
        assert!(!read(None));
        assert!(!read(Some("")));
        assert!(!read(Some("0")));
        assert!(!read(Some("no")));
        assert!(read(Some("1")));
        assert!(read(Some("true")));
        assert!(read(Some("TRUE")));
        assert!(read(Some("Yes")));
        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
        unsafe { std::env::remove_var(STRICT_KEY_FILE_PERMISSIONS_ENV) };
    }

    /// Runs on Unix CI only (Windows has no group/other mode bits).
    #[cfg(unix)]
    #[test]
    fn keys_file_permissions_strict_mode_fails_startup() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("keys.json");
        std::fs::write(&path, "{}").unwrap();
        let path_str = path.to_str().unwrap();

        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
        assert!(
            check_keys_file_permissions(path_str, true).is_err(),
            "strict + 0644"
        );
        assert!(
            check_keys_file_permissions(path_str, false).is_ok(),
            "warn-only + 0644"
        );

        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        assert!(
            check_keys_file_permissions(path_str, true).is_ok(),
            "strict + 0600"
        );
    }

    #[test]
    fn env_key_source_detection() {
        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
        unsafe {
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
        }
        assert!(!env_key_source_in_use(), "no key configured at all");
        // SAFETY: as above.
        unsafe { std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", "irrelevant") };
        assert!(
            env_key_source_in_use(),
            "no keys file => the env var is the source"
        );
        // SAFETY: as above.
        unsafe { std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE", "/some/keys.json") };
        assert!(!env_key_source_in_use(), "a keys file supports rotation");
        // SAFETY: as above.
        unsafe {
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
        }
    }

    #[tokio::test]
    async fn envelope_probe_finds_stored_envelopes_within_its_limit() {
        let enc = StorageEncryption::new_random();
        let storage = MemoryStorage::new();
        storage
            .store_kv("plain:1", b"just text", None)
            .await
            .unwrap();
        assert!(
            !stored_envelopes_exist(&storage, 10).await.unwrap(),
            "plaintext only"
        );

        let sealed = enc.encrypt_for_storage(b"secret", b"sealed:1").unwrap();
        storage.store_kv("sealed:1", &sealed, None).await.unwrap();
        assert!(
            stored_envelopes_exist(&storage, 10).await.unwrap(),
            "envelope present"
        );

        // The probe is bounded: with a limit of 0 it looks at nothing.
        assert!(!stored_envelopes_exist(&storage, 0).await.unwrap());
    }

    #[tokio::test]
    async fn encrypted_storage_says_it_encrypts() {
        let wrapped = EncryptedStorage::new(
            MemoryStorage::new(),
            StorageEncryption::new_random(),
            false,
            false,
        );
        assert!(wrapped.encrypts_kv_at_rest());
        assert!(!MemoryStorage::new().encrypts_kv_at_rest());
        let shared: std::sync::Arc<dyn AuthStorage> = std::sync::Arc::new(wrapped);
        assert!(shared.encrypts_kv_at_rest(), "the Arc impl forwards");
    }
}