udb 0.4.21

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
//! Device, session, token-revocation, MFA-challenge, factor, and WebAuthn
//! credential lifecycle handlers (Phase 3 / I2.3, I2.4, I2.6, I2.7).
//!
//! All state is Postgres-backed via the proto-driven `native_model` descriptors
//! (no hand-maintained schema). Credential-shaped values (jti, fingerprint) are
//! stored only as keyed-HMAC digests; IPs are masked to a network prefix.

use super::*;
use crate::runtime::native_catalog::{NativeModel, native_model};
use crate::runtime::service::native_helpers::{
    native_next_page_token_for_total, native_offset_page_window,
};
use sqlx::Row;

fn lifecycle_invalid_fields<I, F, D>(message: impl Into<String>, fields: I) -> Status
where
    I: IntoIterator<Item = (F, D)>,
    F: Into<String>,
    D: Into<String>,
{
    crate::runtime::executor_utils::invalid_argument_fields(message, fields)
}

fn lifecycle_policy_status_with_code(
    operation: impl Into<String>,
    policy_decision_id: impl Into<String>,
    message: impl Into<String>,
) -> Status {
    crate::runtime::executor_utils::policy_status_with_code(
        tonic::Code::PermissionDenied,
        operation,
        policy_decision_id,
        message,
    )
}

fn lifecycle_internal_status(operation: impl Into<String>, message: impl Into<String>) -> Status {
    crate::runtime::executor_utils::internal_status("authn", operation, message)
}

fn revoke_device_tenant_scope_required_status() -> Status {
    lifecycle_policy_status_with_code(
        "revoke_device",
        "tenant_scoped_bearer_required",
        "device revoke requires a tenant-scoped bearer token or a cross-tenant admin role",
    )
}

fn device_model() -> NativeModel {
    native_model(
        "udb.core.authn.entity.v1.Device",
        &[
            "device_id",
            "user_id",
            "tenant_id",
            "project_id",
            "device_name",
            "device_type",
            "fingerprint_hash",
            "last_ip_masked",
            "last_user_agent_hash",
            "last_seen_at",
            "created_at",
            "revoked_at",
            "revoked_by",
        ],
    )
}

fn revocation_model() -> NativeModel {
    native_model(
        "udb.core.authn.entity.v1.TokenRevocation",
        &[
            "jti_hash",
            "token_type",
            "tenant_id",
            "expires_at",
            "revoked_at",
            "revoked_by",
            "reason",
        ],
    )
}

fn token_family_model() -> NativeModel {
    native_model(
        "udb.core.authn.entity.v1.TokenFamily",
        &[
            "family_id",
            "session_id",
            "user_id",
            "principal_id",
            "tenant_id",
            "project_id",
            "device_id",
            "current_refresh_jti_hash",
            "previous_refresh_jti_hash",
            "reuse_detected_at",
            "revoked_at",
            "revocation_reason",
        ],
    )
}

fn mfa_challenge_model() -> NativeModel {
    native_model(
        "udb.core.authn.entity.v1.MfaChallenge",
        &[
            "challenge_id",
            "user_id",
            "tenant_id",
            "project_id",
            "factor_kind",
            "purpose",
            "device_fingerprint_hash",
            "ip_address_masked",
            "attempt_count",
            "expires_at",
            "consumed_at",
            "created_at",
        ],
    )
}

/// Mask a source IP to a network prefix (IPv4 /24, IPv6 /48) so the full client
/// address never lands in the device/challenge rows. Returns the input trimmed
/// for non-IP strings.
pub(super) fn mask_ip(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    if let Ok(std::net::IpAddr::V4(v4)) = trimmed.parse::<std::net::IpAddr>() {
        let o = v4.octets();
        return format!("{}.{}.{}.0/24", o[0], o[1], o[2]);
    }
    if let Ok(std::net::IpAddr::V6(v6)) = trimmed.parse::<std::net::IpAddr>() {
        let s = v6.segments();
        return format!("{:x}:{:x}:{:x}::/48", s[0], s[1], s[2]);
    }
    trimmed.chars().take(64).collect()
}

impl AuthnServiceImpl {
    pub(super) fn require_pool(&self) -> Result<&PgPool, Status> {
        self.pg_pool.as_ref().ok_or_else(|| {
            authn_capability_status(
                "postgres_auth_store",
                "native_postgres_auth_store",
                "this operation requires the native Postgres auth store",
            )
        })
    }

    fn device_fingerprint_hash(&self, fingerprint: &str) -> String {
        authn::hash_secret(&format!("device:{fingerprint}"), &self.hash_key())
    }

    /// D3 — authorize a per-user device/credential operation against the VALIDATED
    /// bearer claim (never the request body): the caller may target `user_id` only
    /// when the target user belongs to the caller's claim tenant, OR the caller IS
    /// that user, OR the caller holds a genuine cross-tenant/platform-admin role.
    /// Fails closed so a tenant-A admin token cannot list/revoke devices for a
    /// tenant-B user by passing that user's id. The DENY is auditable (subject +
    /// target tenant) via the shared body-tenant guard's tracing.
    async fn authorize_target_user(&self, user_id: &str) -> Result<(), Status> {
        // No claim context (in-process / trusted caller, not over the wire): the
        // shared guards bypass too, so there is nothing to enforce here.
        if !crate::runtime::service::method_security::claim_context_present() {
            return Ok(());
        }
        let ctx = crate::runtime::service::method_security::current_claim_context();
        if ctx.is_cross_tenant_admin() {
            return Ok(());
        }
        // The caller acting on their own account is always allowed.
        if !ctx.subject.trim().is_empty() && ctx.subject.trim() == user_id.trim() {
            return Ok(());
        }
        // Otherwise the target user must live in the caller's claim tenant. Resolve
        // the user's tenant and compare it to the validated claim tenant via the
        // shared D1 guard (which also denies a tenantless non-admin caller).
        let target = self
            .users
            .get_user_by_id(user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("authorize_target_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        crate::runtime::service::method_security::enforce_body_tenant_matches_claim(
            &ctx,
            &target.tenant_id,
            &target.project_id,
        )
    }

    fn jti_hash(&self, jti: &str) -> String {
        authn::hash_secret(&format!("jti:{jti}"), &self.hash_key())
    }

    /// Best-effort SET of a revoked `jti_hash` onto the short-TTL cluster denylist
    /// (Redis). The TTL is the token's own remaining lifetime (`expires_at_unix -
    /// now`) so the entry expires exactly when the token would — no unbounded
    /// growth; when no expiry is known the denylist's default (access-token max
    /// lifetime) is used. A Redis failure is logged but NEVER fails the revoke —
    /// the durable `token_revocations` row remains the source of truth. No-op
    /// when Redis is not configured (`jti_denylist` is `None`) or in the slim
    /// (no-`redis`) build.
    async fn denylist_revoked_jti(&self, jti_hash: &str, expires_at_unix: u64) {
        #[cfg(feature = "redis")]
        {
            let Some(denylist) = self.jti_denylist.as_ref() else {
                return;
            };
            // Token's remaining life → TTL. `0` lets `JtiDenylist::add` fall back
            // to its default (access-token max lifetime), covering tokens revoked
            // without a known expiry (e.g. session handles).
            let ttl = if expires_at_unix > 0 {
                expires_at_unix.saturating_sub(now_unix())
            } else {
                0
            };
            if let Err(err) = denylist.add(jti_hash, ttl).await {
                // Best-effort: the durable DB row already committed; the denylist
                // is only an accelerator, so a Redis miss degrades to DB-only.
                tracing::warn!(
                    error = %err,
                    "jti denylist SET failed; revocation still durable in token_revocations"
                );
            }
        }
        #[cfg(not(feature = "redis"))]
        {
            let _ = (jti_hash, expires_at_unix);
        }
    }

    // ── Cluster-wide revocation (I2.3) ──────────────────────────────────────

    /// Durably revoke a token by jti: insert its keyed digest into the
    /// `token_revocations` deny list so every node rejects it before expiry.
    pub(super) async fn revoke_token_jti(
        &self,
        jti: &str,
        token_type: &str,
        tenant_id: &str,
        expires_at_unix: u64,
        revoked_by: &str,
        reason: &str,
    ) -> Result<(), Status> {
        if jti.trim().is_empty() {
            return Ok(());
        }
        let propagation_started = std::time::Instant::now();
        let pool = self.require_pool()?;
        let m = revocation_model();
        let sql = format!(
            "INSERT INTO {rel} ({jti}, {ttype}, {tenant}, {expires}, {by}, {reason}) \
             VALUES ($1, $2, $3, CASE WHEN $4::BIGINT > 0 THEN to_timestamp($4::DOUBLE PRECISION) ELSE NULL END, $5, $6) \
             ON CONFLICT ({jti}) DO NOTHING",
            rel = m.relation,
            jti = m.q("jti_hash"),
            ttype = m.q("token_type"),
            tenant = m.q("tenant_id"),
            expires = m.q("expires_at"),
            by = m.q("revoked_by"),
            reason = m.q("reason"),
        );
        let event = AuthEvent::new(
            topics::TOKEN_REVOKED,
            format!("revocation:{}", Uuid::new_v4().simple()),
            tenant_id.to_string(),
            serde_json::json!({
                "token_type": token_type,
                "tenant_id": tenant_id,
                "reason": reason,
            }),
        );
        // The keyed-HMAC digest is computed once: it is both the durable row key
        // and the cluster denylist key (NEVER the raw jti).
        let jti_hash = self.jti_hash(jti);
        // Atomicity (§7): the revocation insert and its audit/outbox event land in
        // ONE transaction — either both commit or neither does. A failed audit
        // write aborts the revocation rather than leaving it without its event.
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "token_revocation_tx_begin",
                format!("token revocation tx begin failed: {err}"),
            )
        })?;
        sqlx::query(&sql)
            .bind(&jti_hash)
            .bind(token_type)
            .bind(tenant_id)
            .bind(expires_at_unix as i64)
            .bind(revoked_by)
            .bind(reason)
            .execute(&mut *tx)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "token_revocation_insert",
                    format!("token revocation insert failed: {err}"),
                )
            })?;
        self.emit_event_in_tx(&mut *tx, event).await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "token_revocation_commit",
                format!("token revocation commit failed: {err}"),
            )
        })?;
        // Populate the fast cluster denylist AFTER the durable row commits, so
        // every node can reject this jti immediately (before its DB read). Best-
        // effort: a Redis failure never fails the revoke (the DB row stands).
        self.denylist_revoked_jti(&jti_hash, expires_at_unix).await;
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());
        Ok(())
    }

    /// Is this jti on the revocation deny list? Returns (revoked, reason).
    ///
    /// Tier-1 #13 — fast cross-node revocation: the short-TTL cluster denylist
    /// (Redis) is consulted FIRST. A denylist HIT short-circuits to revoked
    /// (skipping the DB read). A MISS falls through to the durable
    /// `token_revocations` read (the source of truth). The denylist is purely an
    /// accelerator: when Redis is absent the behavior is the unchanged DB-only
    /// lookup.
    ///
    /// Phase 5 fail-closed hardening (applies to BOTH layers): on a denylist OR a
    /// DB **lookup error** the outcome depends on
    /// [`crate::runtime::security::fail_closed_mode`]. In a hardened/production
    /// posture the token is treated as revoked (deny) so a store outage cannot
    /// silently let a possibly-revoked token through; in dev/test the legacy
    /// fail-open+warn behavior is kept (a denylist error falls through to the DB
    /// read). The happy path (found revoked / not revoked) is unchanged. A
    /// missing pool (no deny list wired at all) still returns `(false, _)`.
    ///
    /// Cluster-wide token kill 3.3 — TENANT-level half: alongside the per-jti
    /// denylist this also consults the tenant denylist (`tenant_denied_after`).
    /// When the token's `tenant_id` has a recorded kill cutoff and the token's
    /// `iat` is at/before that cutoff, the token is revoked. `tenant_id` and `iat`
    /// MUST come from the VALIDATED claim, never a request body. `iat == 0` (issue
    /// time unknown) or an empty `tenant_id` skips the tenant comparison so a
    /// tenant kill never spuriously denies a token whose age we can't establish —
    /// the per-jti and durable layers still apply. Both fast-path consultations
    /// (jti, then tenant) run BEFORE the durable `token_revocations` read; a miss
    /// or (in dev) a Redis outage falls through to that durable PG read
    /// (availability-first — Postgres stays authoritative).
    pub(super) async fn is_token_revoked(
        &self,
        jti: &str,
        tenant_id: &str,
        principal_id: &str,
        iat: u64,
    ) -> (bool, String) {
        if jti.trim().is_empty() {
            return (false, String::new());
        }
        // The keyed-HMAC digest keys both the cluster denylist and the DB row.
        let jti_hash = self.jti_hash(jti);
        // ── Fast path: consult the cluster denylist first ──────────────────
        #[cfg(feature = "redis")]
        if let Some(denylist) = self.jti_denylist.as_ref() {
            let fail_closed = crate::runtime::security::fail_closed_mode();
            // (a) Per-jti denylist.
            let decision = denylist.check(&jti_hash).await;
            if matches!(
                decision,
                crate::runtime::authn::revocation::DenylistDecision::Error
            ) {
                self.metrics.inc_revocation_lookup_failure();
                if fail_closed {
                    tracing::error!(
                        "jti denylist lookup failed; failing closed (treating token as revoked)"
                    );
                } else {
                    tracing::warn!(
                        "jti denylist lookup failed; falling through to durable DB read"
                    );
                }
            }
            if let Some(outcome) =
                crate::runtime::authn::revocation::denylist_check_outcome(decision, fail_closed)
            {
                // Denylist alone decided: a hit (revoked), or an error under
                // fail-closed. A miss / dev-mode error returns None → fall through.
                return outcome;
            }
            // (b) Tenant-level denylist. Skipped when the tenant or issue time is
            // unknown (iat == 0) so a tenant kill only acts on a token whose age
            // can actually be compared to the cutoff.
            if !tenant_id.trim().is_empty() && iat > 0 {
                let tenant_decision = denylist.tenant_denied_after(tenant_id).await;
                if matches!(
                    tenant_decision,
                    crate::runtime::authn::revocation::TenantDenylistDecision::Error
                ) {
                    self.metrics.inc_revocation_lookup_failure();
                    if fail_closed {
                        tracing::error!(
                            "tenant denylist lookup failed; failing closed (treating token as revoked)"
                        );
                    } else {
                        tracing::warn!(
                            "tenant denylist lookup failed; falling through to durable DB read"
                        );
                    }
                }
                if let Some(outcome) =
                    crate::runtime::authn::revocation::tenant_denylist_check_outcome(
                        tenant_decision,
                        iat,
                        fail_closed,
                    )
                {
                    // Tenant denylist alone decided: a cutoff >= iat (revoked), or
                    // an error under fail-closed. A miss, a strictly-newer token,
                    // or a dev-mode error returns None → durable DB read.
                    return outcome;
                }
            }
            // (c) Principal-level denylist (account hard-delete). Same cutoff-vs-iat
            // semantics as the tenant kill — reuses `tenant_denylist_check_outcome`.
            // Skipped when the principal or issue time is unknown.
            if !principal_id.trim().is_empty() && iat > 0 {
                let principal_decision = denylist.principal_denied_after(principal_id).await;
                if matches!(
                    principal_decision,
                    crate::runtime::authn::revocation::TenantDenylistDecision::Error
                ) {
                    self.metrics.inc_revocation_lookup_failure();
                    if fail_closed {
                        tracing::error!(
                            "principal denylist lookup failed; failing closed (treating token as revoked)"
                        );
                    } else {
                        tracing::warn!(
                            "principal denylist lookup failed; falling through to durable DB read"
                        );
                    }
                }
                if let Some(outcome) =
                    crate::runtime::authn::revocation::tenant_denylist_check_outcome(
                        principal_decision,
                        iat,
                        fail_closed,
                    )
                {
                    return outcome;
                }
            }
        }
        #[cfg(not(feature = "redis"))]
        let _ = (tenant_id, principal_id, iat);
        // ── Source of truth: durable `token_revocations` read ──────────────
        let Some(pool) = self.pg_pool.as_ref() else {
            return (false, String::new());
        };
        let m = revocation_model();
        let sql = format!(
            "SELECT COALESCE({reason}, '')::TEXT AS reason FROM {rel} WHERE {jti} = $1 LIMIT 1",
            reason = m.q("reason"),
            rel = m.relation,
            jti = m.q("jti_hash"),
        );
        match sqlx::query(&sql).bind(&jti_hash).fetch_optional(pool).await {
            Ok(Some(row)) => {
                let reason: String = row.try_get("reason").unwrap_or_default();
                (true, reason)
            }
            Ok(None) => (false, String::new()),
            Err(err) => {
                self.metrics.inc_revocation_lookup_failure();
                let fail_closed = crate::runtime::security::fail_closed_mode();
                if fail_closed {
                    tracing::error!(
                        error = %err,
                        "token revocation lookup failed; failing closed (treating token as revoked)"
                    );
                } else {
                    tracing::warn!(error = %err, "token revocation lookup failed; failing open");
                }
                crate::runtime::authn::revocation::revocation_lookup_error_outcome(fail_closed)
            }
        }
    }

    // ── Devices (I2.4) ──────────────────────────────────────────────────────

    /// P3 (bug_report.md): register (or refresh) the caller's device at login so
    /// the device lifecycle is reachable — without this NO RPC ever inserts a
    /// `devices` row, so ListDevices is always empty and the client can never get
    /// a `device_id` to pass to RevokeDevice. Idempotent per (user, fingerprint):
    /// returns the existing non-revoked device's id when the same fingerprint has
    /// logged in before (refreshing `last_seen_at`), else inserts a new row.
    /// `fingerprint` is the client `LoginRequest.device_id`; only its keyed-HMAC
    /// digest is stored. Best-effort: any failure returns `None` and never blocks
    /// login (so a missing/legacy `devices` table can't break auth).
    pub(super) async fn register_login_device(
        &self,
        user_id: &str,
        tenant_id: &str,
        project_id: &str,
        fingerprint: &str,
        device_name: &str,
        ip_raw: &str,
    ) -> Option<String> {
        if fingerprint.trim().is_empty() {
            return None;
        }
        let pool = self.require_pool().ok()?;
        let m = device_model();
        let fp_hash = self.device_fingerprint_hash(fingerprint);
        let ip_masked = mask_ip(ip_raw);
        let existing: Option<String> = sqlx::query_scalar(&format!(
            "SELECT {id}::TEXT FROM {rel} WHERE {user} = $1 AND {fp} = $2 AND {revoked} IS NULL \
             ORDER BY {created} DESC LIMIT 1",
            id = m.q("device_id"),
            rel = m.relation,
            user = m.q("user_id"),
            fp = m.q("fingerprint_hash"),
            revoked = m.q("revoked_at"),
            created = m.q("created_at"),
        ))
        .bind(user_id)
        .bind(&fp_hash)
        .fetch_optional(pool)
        .await
        .ok()
        .flatten();
        if let Some(id) = existing {
            let _ = sqlx::query(&format!(
                "UPDATE {rel} SET {seen} = NOW(), {ip} = $2 WHERE {id} = $1::UUID",
                rel = m.relation,
                seen = m.q("last_seen_at"),
                ip = m.q("last_ip_masked"),
                id = m.q("device_id"),
            ))
            .bind(&id)
            .bind(ip_masked)
            .execute(pool)
            .await;
            return Some(id);
        }
        let new_id = uuid::Uuid::new_v4().to_string();
        sqlx::query_scalar(&format!(
            "INSERT INTO {rel} ({id}, {user}, {tenant}, {project}, {name}, {fp}, {ip}, {seen}) \
             VALUES ($1::UUID, $2, $3, $4, $5, $6, $7, NOW()) RETURNING {id}::TEXT",
            rel = m.relation,
            id = m.q("device_id"),
            user = m.q("user_id"),
            tenant = m.q("tenant_id"),
            project = m.q("project_id"),
            name = m.q("device_name"),
            fp = m.q("fingerprint_hash"),
            ip = m.q("last_ip_masked"),
            seen = m.q("last_seen_at"),
        ))
        .bind(&new_id)
        .bind(user_id)
        .bind(tenant_id)
        .bind(project_id)
        .bind(device_name)
        .bind(&fp_hash)
        .bind(ip_masked)
        .fetch_optional(pool)
        .await
        .ok()
        .flatten()
    }

    pub(super) async fn list_devices_impl(
        &self,
        request: Request<authn_pb::ListDevicesRequest>,
    ) -> Result<Response<authn_pb::ListDevicesResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id is required",
                [("user_id", "must be a non-empty user id")],
            ));
        }
        // D3: bind the target user to the validated bearer claim — a tenant-A token
        // cannot enumerate a tenant-B user's devices by passing that user's id.
        self.authorize_target_user(&req.user_id).await?;
        let pool = self.require_pool()?;
        let m = device_model();
        let (limit, offset, _) = bounded_page_window(req.page.as_ref());
        let sql = format!(
            "SELECT {id}::TEXT AS device_id, {user}::TEXT AS user_id, \
                    COALESCE({tenant}::TEXT,'') AS tenant_id, COALESCE({project}::TEXT,'') AS project_id, \
                    COALESCE({name}::TEXT,'') AS device_name, COALESCE({dtype}::TEXT,'') AS device_type, \
                    COALESCE({ip}::TEXT,'') AS last_ip_masked, \
                    {seen}, {created}, {revoked} AS revoked_at \
             FROM {rel} WHERE {user} = $1 AND {revoked} IS NULL \
             ORDER BY {created_col} DESC OFFSET $2 LIMIT $3",
            id = m.q("device_id"),
            user = m.q("user_id"),
            tenant = m.q("tenant_id"),
            project = m.q("project_id"),
            name = m.q("device_name"),
            dtype = m.q("device_type"),
            ip = m.q("last_ip_masked"),
            seen = m.timestamp_unix_as("last_seen_at", "last_seen_at"),
            created = m.timestamp_unix_as("created_at", "created_at"),
            // ORDER BY must use the BARE column, NOT the `{created}` projection — that
            // one ends in `AS "created_at"`, and an `AS alias` inside ORDER BY is a
            // syntax error ("at or near AS"). This is the §1 ListDevices bug.
            created_col = m.q("created_at"),
            revoked = m.q("revoked_at"),
            rel = m.relation,
        );
        let rows = sqlx::query(&sql)
            .bind(&req.user_id)
            .bind(offset as i64)
            .bind(limit as i64)
            .fetch_all(pool)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "list_devices_query",
                    format!("list devices failed: {err}"),
                )
            })?;
        let devices = rows
            .iter()
            .map(|row| authn_entity_pb::Device {
                device_id: row.try_get("device_id").unwrap_or_default(),
                user_id: row.try_get("user_id").unwrap_or_default(),
                tenant_id: row.try_get("tenant_id").unwrap_or_default(),
                project_id: row.try_get("project_id").unwrap_or_default(),
                device_name: row.try_get("device_name").unwrap_or_default(),
                device_type: authn_entity_pb::DeviceType::try_from(parse_device_type(
                    &row.try_get::<String, _>("device_type").unwrap_or_default(),
                ))
                .unwrap_or(authn_entity_pb::DeviceType::Web) as i32,
                // Fingerprint digest is STORAGE_ONLY: never surfaced through reads.
                fingerprint_hash: String::new(),
                last_ip_masked: row.try_get("last_ip_masked").unwrap_or_default(),
                last_user_agent_hash: String::new(),
                last_seen_at: timestamp_from_unix(
                    row.try_get::<i64, _>("last_seen_at").unwrap_or(0).max(0) as u64,
                ),
                created_at: timestamp_from_unix(
                    row.try_get::<i64, _>("created_at").unwrap_or(0).max(0) as u64,
                ),
                revoked_at: None,
                revoked_by: String::new(),
            })
            .collect();
        Ok(Response::new(authn_pb::ListDevicesResponse {
            devices,
            page: Some(bounded_page_response(rows.len(), req.page.as_ref())),
        }))
    }

    pub(super) async fn revoke_device_impl(
        &self,
        request: Request<authn_pb::RevokeDeviceRequest>,
    ) -> Result<Response<authn_pb::RevokeDeviceResponse>, Status> {
        let req = request.into_inner();
        // bug_report.md B1: validate device_id is a UUID at the boundary so a
        // malformed id never reaches the `WHERE {id} = $1::UUID` query (which
        // would leak a raw Postgres `22P02` error as Internal).
        Self::require_uuid_arg(&req.device_id, "device_id")?;
        let propagation_started = std::time::Instant::now();
        // D3: derive the authorized tenant from the VALIDATED bearer claim, never
        // from the request. A tenant-scoped caller may only revoke devices owned by
        // its own claim tenant; a genuine cross-tenant/platform admin may revoke any
        // device. The tenant predicate is pushed into the UPDATE/lookup so a
        // tenant-A token revoking a tenant-B device simply matches no row (fails
        // closed → not_found) rather than crossing the boundary. When no claim
        // context is installed (in-process / trusted caller, not over the wire) the
        // gate is bypassed — real transport requests always carry a context.
        let claim_ctx = crate::runtime::service::method_security::current_claim_context();
        let context_present = crate::runtime::service::method_security::claim_context_present();
        let cross_tenant_admin = !context_present || claim_ctx.is_cross_tenant_admin();
        let claim_tenant = claim_ctx.tenant_id.trim().to_string();
        if context_present && !cross_tenant_admin && claim_tenant.is_empty() {
            return Err(revoke_device_tenant_scope_required_status());
        }
        let pool = self.require_pool()?;
        let m = device_model();
        let actor = req
            .context
            .as_ref()
            .and_then(|c| {
                [
                    c.user_id.as_str(),
                    c.principal_id.as_str(),
                    c.service_identity.as_str(),
                ]
                .into_iter()
                .find(|value| !value.trim().is_empty())
                .map(str::to_string)
            })
            .unwrap_or_else(|| crate::runtime::otel::current_actor());
        let auth_method = crate::runtime::otel::current_auth_method();
        let trace = req
            .context
            .as_ref()
            .map(|c| {
                (
                    c.trace_id.clone(),
                    c.span_id.clone(),
                    c.ip_address.clone(),
                    c.user_agent.clone(),
                )
            })
            .unwrap_or_default();
        // Mark the device revoked and revoke every token family bound to it so
        // future refresh + session validation is blocked. D3: the tenant predicate
        // (`{tenant} = $3 OR $4`) binds the revoke to the caller's CLAIM tenant for
        // a non-admin — a cross-tenant device id matches no row → not_found.
        let sql = format!(
            "UPDATE {rel} SET {revoked} = NOW(), {by} = $2 WHERE {id} = $1::UUID AND {revoked} IS NULL \
             AND ({tenant} = $3 OR $4) \
             RETURNING {tenant}::TEXT AS tenant_id",
            rel = m.relation,
            revoked = m.q("revoked_at"),
            by = m.q("revoked_by"),
            id = m.q("device_id"),
            tenant = m.q("tenant_id"),
        );
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "revoke_device_tx_begin",
                format!("revoke device tx begin failed: {err}"),
            )
        })?;
        let row = sqlx::query(&sql)
            .bind(&req.device_id)
            .bind(&actor)
            .bind(&claim_tenant)
            .bind(cross_tenant_admin)
            .fetch_optional(&mut *tx)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "revoke_device_update",
                    format!("revoke device failed: {err}"),
                )
            })?;
        let Some(row) = row else {
            return Err(super::authn_device_not_found_status());
        };
        let tenant_id: String = row.try_get("tenant_id").unwrap_or_default();
        let families = self
            .revoke_families_for_device(&mut *tx, &req.device_id, "device_revoked")
            .await?;
        // Atomicity (§7): the device-revoke UPDATE, the family revokes, and the
        // audit event all commit together — or the transaction rolls back.
        // Device revocation is a security-sensitive operation (I2.7): attach the
        // full compliance envelope (resolved actor, auth method, source IP, UA, and
        // trace/span correlation) so the audit record identifies WHO revoked the
        // device, HOW they authenticated, and from WHERE — the same provenance the
        // emergency-revoke path records.
        self.emit_event_in_tx(
            &mut *tx,
            AuthEvent::new(
                topics::DEVICE_REVOKED,
                req.device_id.clone(),
                tenant_id.clone(),
                serde_json::json!({
                    "device_id": req.device_id.clone(),
                    "reason": req.reason.clone(),
                    "families_revoked": families,
                }),
            )
            .with_correlation(format!("device-revoke:{}", req.device_id))
            .with_compliance(ComplianceEnvelope {
                actor,
                target_resource: format!("device:{}", req.device_id),
                target_tenant: tenant_id,
                operation: "device_revoke".to_string(),
                outcome: "success".to_string(),
                reason_code: if req.reason.trim().is_empty() {
                    "device_revoked".to_string()
                } else {
                    req.reason.clone()
                },
                auth_method,
                source_ip: trace.2,
                user_agent: trace.3,
                trace_id: trace.0,
                span_id: trace.1,
                ..ComplianceEnvelope::default()
            }),
        )
        .await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "revoke_device_commit",
                format!("revoke device commit failed: {err}"),
            )
        })?;
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());
        Ok(Response::new(authn_pb::RevokeDeviceResponse {
            revoked: true,
            device_id: req.device_id,
            sessions_revoked: families as i64,
        }))
    }

    async fn revoke_families_for_device<'c, E>(
        &self,
        executor: E,
        device_id: &str,
        reason: &str,
    ) -> Result<u64, Status>
    where
        E: sqlx::Executor<'c, Database = sqlx::Postgres>,
    {
        let m = token_family_model();
        let sql = format!(
            "UPDATE {rel} SET {revoked} = NOW(), {reason_col} = $2 WHERE {device} = $1 AND {revoked} IS NULL",
            rel = m.relation,
            revoked = m.q("revoked_at"),
            reason_col = m.q("revocation_reason"),
            device = m.q("device_id"),
        );
        let res = sqlx::query(&sql)
            .bind(device_id)
            .bind(reason)
            .execute(executor)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "revoke_device_families",
                    format!("revoke device families failed: {err}"),
                )
            })?;
        Ok(res.rows_affected())
    }

    // ── Admin session revocation (I2.4) ─────────────────────────────────────

    pub(super) async fn admin_revoke_session_impl(
        &self,
        request: Request<authn_pb::AdminRevokeSessionRequest>,
    ) -> Result<Response<authn_pb::AdminRevokeSessionResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id is required",
                [("user_id", "must be a non-empty user id")],
            ));
        }
        let propagation_started = std::time::Instant::now();
        // Revoking by user id revokes the user's sessions (the public session
        // handle is one-way, so a specific-session revoke targets the principal).
        let now = now_unix();
        let event = AuthEvent::new(
            topics::SESSION_REVOKED,
            format!("admin-revoke:{}", Uuid::new_v4().simple()),
            String::new(),
            serde_json::json!({ "user_id": req.user_id.clone(), "reason": req.reason.clone() }),
        );
        // Atomicity (§7): session revoke + family revoke + audit event commit together.
        let pool = self.require_pool()?;
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "admin_revoke_session_tx_begin",
                format!("admin revoke tx begin failed: {err}"),
            )
        })?;
        let count = self
            .sessions
            .revoke_all_for_principal_in_tx(&mut *tx, &req.user_id, now)
            .await
            .map_err(|err| {
                lifecycle_internal_status("admin_revoke_session_store", err.to_string())
            })?;
        self.revoke_all_user_families_on(&mut *tx, &req.user_id, "admin_revoke")
            .await?;
        self.emit_event_in_tx(&mut *tx, event).await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "admin_revoke_session_commit",
                format!("admin revoke commit failed: {err}"),
            )
        })?;
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());
        Ok(Response::new(authn_pb::AdminRevokeSessionResponse {
            revoked: count > 0,
            sessions_revoked: count as i64,
        }))
    }

    pub(super) async fn admin_revoke_all_user_sessions_impl(
        &self,
        request: Request<authn_pb::AdminRevokeAllUserSessionsRequest>,
    ) -> Result<Response<authn_pb::AdminRevokeAllUserSessionsResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id is required",
                [("user_id", "must be a non-empty user id")],
            ));
        }
        let propagation_started = std::time::Instant::now();
        let now = now_unix();
        let event = AuthEvent::new(
            topics::SESSION_REVOKED,
            format!("admin-revoke-all:{}", Uuid::new_v4().simple()),
            String::new(),
            serde_json::json!({ "user_id": req.user_id.clone(), "reason": req.reason.clone() }),
        );
        // Atomicity (§7): session revoke + family revoke + audit event commit together.
        let pool = self.require_pool()?;
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "admin_revoke_all_sessions_tx_begin",
                format!("admin revoke-all tx begin failed: {err}"),
            )
        })?;
        let count = self
            .sessions
            .revoke_all_for_principal_in_tx(&mut *tx, &req.user_id, now)
            .await
            .map_err(|err| {
                lifecycle_internal_status("admin_revoke_all_sessions_store", err.to_string())
            })?;
        self.revoke_all_user_families_on(&mut *tx, &req.user_id, "admin_revoke_all")
            .await?;
        self.emit_event_in_tx(&mut *tx, event).await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "admin_revoke_all_sessions_commit",
                format!("admin revoke-all commit failed: {err}"),
            )
        })?;
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());
        Ok(Response::new(
            authn_pb::AdminRevokeAllUserSessionsResponse {
                sessions_revoked: count as i64,
            },
        ))
    }

    pub(super) async fn admin_revoke_all_tenant_sessions_impl(
        &self,
        request: Request<authn_pb::AdminRevokeAllTenantSessionsRequest>,
    ) -> Result<Response<authn_pb::AdminRevokeAllTenantSessionsResponse>, Status> {
        let req = request.into_inner();
        if req.tenant_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "tenant_id is required",
                [("tenant_id", "must be a non-empty tenant id")],
            ));
        }
        let propagation_started = std::time::Instant::now();
        // D3: the bulk tenant revoke targets `req.tenant_id`. Without this guard a
        // tenant-A admin token could revoke tenant B simply by setting body
        // `tenant_id=B`. Bind the target to the VALIDATED bearer tenant: a
        // tenant-scoped caller may only revoke its own tenant; only a genuine
        // cross-tenant/platform admin may target an arbitrary tenant. Fails closed.
        let claim_ctx = crate::runtime::service::method_security::current_claim_context();
        crate::runtime::service::method_security::enforce_body_tenant_matches_claim(
            &claim_ctx,
            &req.tenant_id,
            "",
        )?;
        let pool = self.require_pool()?;
        // Bulk-revoke sessions + token families for the tenant in two scoped
        // UPDATEs (proto-driven relations).
        let session_m = native_model(
            "udb.core.authn.entity.v1.Session",
            &["tenant_id", "is_active", "revoked_by", "revoke_reason"],
        );
        let session_sql = format!(
            "UPDATE {rel} SET {active} = FALSE, {reason} = 'admin_revoke_tenant' \
             WHERE {tenant} = $1 AND {active} = TRUE",
            rel = session_m.relation,
            active = session_m.q("is_active"),
            reason = session_m.q("revoke_reason"),
            tenant = session_m.q("tenant_id"),
        );
        let fam = token_family_model();
        let fam_sql = format!(
            "UPDATE {rel} SET {revoked} = NOW(), {reason} = 'admin_revoke_tenant' \
             WHERE {tenant} = $1 AND {revoked} IS NULL",
            rel = fam.relation,
            revoked = fam.q("revoked_at"),
            reason = fam.q("revocation_reason"),
            tenant = fam.q("tenant_id"),
        );
        let event = AuthEvent::new(
            topics::SESSION_REVOKED,
            format!("admin-revoke-tenant:{}", Uuid::new_v4().simple()),
            req.tenant_id.clone(),
            serde_json::json!({ "tenant_id": req.tenant_id.clone(), "reason": req.reason.clone() }),
        );
        // Atomicity (§7): both bulk revokes and the audit event commit together —
        // either all land or the transaction rolls back.
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "revoke_tenant_tx_begin",
                format!("revoke tenant tx begin failed: {err}"),
            )
        })?;
        let sessions = sqlx::query(&session_sql)
            .bind(&req.tenant_id)
            .execute(&mut *tx)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "revoke_tenant_sessions",
                    format!("revoke tenant sessions failed: {err}"),
                )
            })?
            .rows_affected();
        sqlx::query(&fam_sql)
            .bind(&req.tenant_id)
            .execute(&mut *tx)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "revoke_tenant_families",
                    format!("revoke tenant families failed: {err}"),
                )
            })?;
        self.emit_event_in_tx(&mut *tx, event).await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "revoke_tenant_commit",
                format!("revoke tenant commit failed: {err}"),
            )
        })?;
        // Cluster-wide fast-path kill: the durable bulk-revoke above is the source
        // of truth; publishing the tenant cutoff to the denylist propagates the
        // kill to every replica's hot-path token check immediately (a token with
        // `iat <= now` is denied, mirroring the `tenant_denied_after` check in
        // `is_token_revoked`). Best-effort / availability-first — a denylist error
        // must NEVER fail the revoke that already durably committed.
        #[cfg(feature = "redis")]
        if let Some(denylist) = self.jti_denylist.as_ref() {
            if let Err(err) = denylist.deny_tenant_after(&req.tenant_id, now_unix()).await {
                tracing::warn!(
                    tenant_id = %req.tenant_id,
                    error = %err,
                    "tenant denylist cutoff publish failed after durable tenant revoke \
                     (availability-first; durable revoke already committed)"
                );
            }
        }
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());
        Ok(Response::new(
            authn_pb::AdminRevokeAllTenantSessionsResponse {
                sessions_revoked: sessions as i64,
            },
        ))
    }

    /// `revoke_all_user_families` over any executor — `pool` for a standalone
    /// revoke, or a `&mut PgConnection` so it commits in the caller's transaction.
    async fn revoke_all_user_families_on<'c, E>(
        &self,
        executor: E,
        user_id: &str,
        reason: &str,
    ) -> Result<u64, Status>
    where
        E: sqlx::Executor<'c, Database = sqlx::Postgres>,
    {
        let m = token_family_model();
        let sql = format!(
            "UPDATE {rel} SET {revoked} = NOW(), {reason_col} = $2 \
             WHERE ({user} = $1 OR {principal} = $1) AND {revoked} IS NULL",
            rel = m.relation,
            revoked = m.q("revoked_at"),
            reason_col = m.q("revocation_reason"),
            user = m.q("user_id"),
            principal = m.q("principal_id"),
        );
        let res = sqlx::query(&sql)
            .bind(user_id)
            .bind(reason)
            .execute(executor)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "revoke_user_families",
                    format!("revoke user families failed: {err}"),
                )
            })?;
        Ok(res.rows_affected())
    }

    pub(super) async fn emergency_revoke_impl(
        &self,
        request: Request<authn_pb::EmergencyRevokeRequest>,
    ) -> Result<Response<authn_pb::EmergencyRevokeResponse>, Status> {
        let req = request.into_inner();
        let has_selector = !req.signing_key_id.trim().is_empty()
            || !req.token_family_id.trim().is_empty()
            || !req.tenant_id.trim().is_empty()
            || !req.principal_id.trim().is_empty();
        if !has_selector {
            return Err(lifecycle_invalid_fields(
                "at least one selector is required (signing_key_id/token_family_id/tenant_id/principal_id)",
                [(
                    "selectors",
                    "must include at least one of signing_key_id, token_family_id, tenant_id, or principal_id",
                )],
            ));
        }
        let propagation_started = std::time::Instant::now();
        let actor = req
            .context
            .as_ref()
            .and_then(|c| {
                [
                    c.user_id.as_str(),
                    c.principal_id.as_str(),
                    c.service_identity.as_str(),
                ]
                .into_iter()
                .find(|value| !value.trim().is_empty())
                .map(str::to_string)
            })
            .unwrap_or_else(|| crate::runtime::otel::current_actor());
        let auth_method = crate::runtime::otel::current_auth_method();
        let trace = req
            .context
            .as_ref()
            .map(|c| {
                (
                    c.trace_id.clone(),
                    c.span_id.clone(),
                    c.ip_address.clone(),
                    c.user_agent.clone(),
                )
            })
            .unwrap_or_default();
        let now = now_unix();
        let mut families_revoked = 0u64;
        let mut sessions_revoked = 0u64;
        let mut keys_compromised = 0u64;

        // Atomicity (§7): every durable emergency mutation (signing-key compromise,
        // family revokes, principal session+family revokes, and the tenant-wide
        // bulk revoke) plus the emergency audit/outbox event commit in ONE
        // transaction — a partial break-glass that is not fully durable, or whose
        // audit event cannot be written, rolls the whole operation back rather than
        // leaving the system in a half-revoked state without its event.
        let pool = self.require_pool()?;
        let mut tx = pool.begin().await.map_err(|err| {
            lifecycle_internal_status(
                "emergency_revoke_tx_begin",
                format!("emergency revoke tx begin failed: {err}"),
            )
        })?;

        if !req.signing_key_id.trim().is_empty() {
            keys_compromised = self
                .compromise_signing_key_on(&mut *tx, req.signing_key_id.trim(), &actor)
                .await?;
        }
        if !req.token_family_id.trim().is_empty() {
            families_revoked += self
                .revoke_family_by_id_on(&mut *tx, req.token_family_id.trim(), "emergency_revoke")
                .await?;
        }
        if !req.principal_id.trim().is_empty() {
            families_revoked += self
                .revoke_all_user_families_on(&mut *tx, req.principal_id.trim(), "emergency_revoke")
                .await?;
            sessions_revoked += self
                .sessions
                .revoke_all_for_principal_in_tx(&mut *tx, req.principal_id.trim(), now)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "emergency_revoke_principal_sessions",
                        err.to_string(),
                    )
                })? as u64;
        }
        if !req.tenant_id.trim().is_empty() {
            // Inline the tenant-wide bulk revoke (mirrors
            // `admin_revoke_all_tenant_sessions_impl`) onto THIS emergency tx so the
            // whole break-glass is one atomic unit (rather than recursing into a
            // handler with its own independent transaction).
            let session_m = native_model(
                "udb.core.authn.entity.v1.Session",
                &["tenant_id", "is_active", "revoked_by", "revoke_reason"],
            );
            let session_sql = format!(
                "UPDATE {rel} SET {active} = FALSE, {reason} = 'emergency_revoke_tenant' \
                 WHERE {tenant} = $1 AND {active} = TRUE",
                rel = session_m.relation,
                active = session_m.q("is_active"),
                reason = session_m.q("revoke_reason"),
                tenant = session_m.q("tenant_id"),
            );
            let fam = token_family_model();
            let fam_sql = format!(
                "UPDATE {rel} SET {revoked} = NOW(), {reason} = 'emergency_revoke_tenant' \
                 WHERE {tenant} = $1 AND {revoked} IS NULL",
                rel = fam.relation,
                revoked = fam.q("revoked_at"),
                reason = fam.q("revocation_reason"),
                tenant = fam.q("tenant_id"),
            );
            let tenant_sessions = sqlx::query(&session_sql)
                .bind(req.tenant_id.trim())
                .execute(&mut *tx)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "emergency_revoke_tenant_sessions",
                        format!("emergency revoke tenant sessions failed: {err}"),
                    )
                })?
                .rows_affected();
            let tenant_families = sqlx::query(&fam_sql)
                .bind(req.tenant_id.trim())
                .execute(&mut *tx)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "emergency_revoke_tenant_families",
                        format!("emergency revoke tenant families failed: {err}"),
                    )
                })?
                .rows_affected();
            sessions_revoked += tenant_sessions;
            families_revoked += tenant_families;
        }

        let operation_id = Uuid::new_v4().to_string();
        let reason_code = if req.reason.trim().is_empty() {
            "emergency_revoke".to_string()
        } else {
            req.reason.clone()
        };
        // Shared compliance envelope for the umbrella event and every operation-
        // plane facet event below — same actor/trace/outcome, only the
        // operation/target/reason differ. Cloned per-event so trace material is
        // reused (it is consumed by the final umbrella event).
        let ops_envelope =
            |operation: &str, target_resource: String, reason: &str| ComplianceEnvelope {
                actor: actor.clone(),
                actor_project: String::new(),
                target_resource,
                target_tenant: req.tenant_id.clone(),
                target_project: String::new(),
                operation: operation.to_string(),
                outcome: "success".to_string(),
                reason_code: reason.to_string(),
                auth_method: auth_method.clone(),
                source_ip: trace.2.clone(),
                user_agent: trace.3.clone(),
                trace_id: trace.0.clone(),
                span_id: trace.1.clone(),
                ..ComplianceEnvelope::default()
            };

        // ── Operation-plane facet events ────────────────────────────────────────
        // The break-glass umbrella event (OPS_EMERGENCY_REVOKE) records the whole
        // operation; these facets name the specific operations that actually fired
        // so the ops/audit stream carries the distinct, individually-subscribable
        // signals. Emitted in the SAME tx as the mutations (§7 atomicity).

        // A compromised signing key was rotated OUT of the signing registry — that
        // is a key-rotation event (the registry's ACTIVE/VERIFYING set changes, and
        // tokens signed by the compromised key stop verifying). Emit both the
        // ops-plane rotation signal and the authn signing-key-rotated event.
        if keys_compromised > 0 {
            let key_target = format!("signing_key:{}", req.signing_key_id.trim());
            self.emit_event_in_tx(
                &mut *tx,
                AuthEvent::new(
                    topics::OPS_KEY_ROTATION,
                    operation_id.clone(),
                    req.tenant_id.clone(),
                    serde_json::json!({
                        "operation_id": operation_id,
                        "signing_key_id": req.signing_key_id.clone(),
                        "keys_compromised": keys_compromised,
                        "trigger": "emergency_revoke",
                    }),
                )
                .with_correlation(operation_id.clone())
                .with_compliance(ops_envelope(
                    "key_rotation",
                    key_target.clone(),
                    "signing_key_compromised",
                )),
            )
            .await?;
            self.emit_event_in_tx(
                &mut *tx,
                AuthEvent::new(
                    topics::SIGNING_KEY_ROTATED,
                    req.signing_key_id.trim().to_string(),
                    req.tenant_id.clone(),
                    serde_json::json!({
                        "signing_key_id": req.signing_key_id.clone(),
                        "new_state": "compromised",
                        "rotation_reason": "emergency_revoke",
                    }),
                )
                .with_correlation(operation_id.clone())
                .with_compliance(ops_envelope(
                    "signing_key_rotated",
                    key_target,
                    "signing_key_compromised",
                )),
            )
            .await?;
        }

        // A tenant-wide revoke denied every active session + token family in the
        // tenant — the tenant is effectively suspended (no live credentials remain
        // until re-provisioned). Emit the tenant-suspension lifecycle event AND the
        // fleet-scope emergency deny-all signal (a tenant is the broadest blast
        // radius this RPC supports — "deny everything for this tenant").
        if !req.tenant_id.trim().is_empty() {
            let tenant_target = format!("tenant:{}", req.tenant_id.trim());
            self.emit_event_in_tx(
                &mut *tx,
                AuthEvent::new(
                    topics::OPS_TENANT_SUSPENDED,
                    operation_id.clone(),
                    req.tenant_id.clone(),
                    serde_json::json!({
                        "operation_id": operation_id,
                        "tenant_id": req.tenant_id.clone(),
                        "sessions_revoked": sessions_revoked,
                        "families_revoked": families_revoked,
                        "trigger": "emergency_revoke",
                    }),
                )
                .with_correlation(operation_id.clone())
                .with_compliance(ops_envelope(
                    "tenant_suspended",
                    tenant_target.clone(),
                    &reason_code,
                )),
            )
            .await?;
            self.emit_event_in_tx(
                &mut *tx,
                AuthEvent::new(
                    topics::OPS_EMERGENCY_DENY_ALL,
                    operation_id.clone(),
                    req.tenant_id.clone(),
                    serde_json::json!({
                        "operation_id": operation_id,
                        "tenant_id": req.tenant_id.clone(),
                        "sessions_revoked": sessions_revoked,
                        "families_revoked": families_revoked,
                        "scope": "tenant",
                    }),
                )
                .with_correlation(operation_id.clone())
                .with_compliance(ops_envelope(
                    "emergency_deny_all",
                    tenant_target,
                    &reason_code,
                )),
            )
            .await?;
        }

        let event = AuthEvent::new(
            topics::OPS_EMERGENCY_REVOKE,
            operation_id.clone(),
            req.tenant_id.clone(),
            serde_json::json!({
                "operation_id": operation_id,
                "signing_key_id": req.signing_key_id.clone(),
                "token_family_id": req.token_family_id.clone(),
                "tenant_id": req.tenant_id.clone(),
                "principal_id": req.principal_id.clone(),
                "reason": req.reason.clone(),
                "families_revoked": families_revoked,
                "sessions_revoked": sessions_revoked,
                "keys_compromised": keys_compromised,
            }),
        )
        .with_correlation(operation_id.clone())
        .with_compliance(ops_envelope(
            "emergency_revoke",
            if req.tenant_id.trim().is_empty() {
                req.principal_id.clone()
            } else {
                format!("tenant:{}", req.tenant_id)
            },
            &reason_code,
        ));
        self.emit_event_in_tx(&mut *tx, event).await?;
        tx.commit().await.map_err(|err| {
            lifecycle_internal_status(
                "emergency_revoke_commit",
                format!("emergency revoke commit failed: {err}"),
            )
        })?;
        self.metrics
            .observe_revocation_propagation_seconds(propagation_started.elapsed().as_secs_f64());

        Ok(Response::new(authn_pb::EmergencyRevokeResponse {
            families_revoked: families_revoked as i64,
            sessions_revoked: sessions_revoked as i64,
            keys_compromised: keys_compromised as i64,
            operation_id,
        }))
    }

    /// `revoke_family_by_id` over any executor — `pool` for a standalone revoke,
    /// or a `&mut PgConnection` so it commits in the caller's transaction (used
    /// by `emergency_revoke_impl` for §7 atomicity).
    async fn revoke_family_by_id_on<'c, E>(
        &self,
        executor: E,
        family_id: &str,
        reason: &str,
    ) -> Result<u64, Status>
    where
        E: sqlx::Executor<'c, Database = sqlx::Postgres>,
    {
        let m = token_family_model();
        let sql = format!(
            "UPDATE {rel} SET {revoked} = NOW(), {reason_col} = $2 WHERE {id} = $1::UUID AND {revoked} IS NULL",
            rel = m.relation,
            revoked = m.q("revoked_at"),
            reason_col = m.q("revocation_reason"),
            id = m.q("family_id"),
        );
        let res = sqlx::query(&sql)
            .bind(family_id)
            .bind(reason)
            .execute(executor)
            .await
            .map_err(|err| {
                lifecycle_internal_status("revoke_family", format!("revoke family failed: {err}"))
            })?;
        Ok(res.rows_affected())
    }

    // ── MFA challenge lifecycle (I2.6) ──────────────────────────────────────

    pub(super) async fn issue_mfa_challenge_impl(
        &self,
        request: Request<authn_pb::IssueMfaChallengeRequest>,
    ) -> Result<Response<authn_pb::IssueMfaChallengeResponse>, Status> {
        let req = request.into_inner();
        let user = self
            .users
            .get_user_by_id(&req.user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("issue_mfa_challenge_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        let pool = self.require_pool()?;
        let m = mfa_challenge_model();
        let factor = if req.factor_kind == 0 {
            authn_entity_pb::AuthFactorKind::Totp as i32
        } else {
            req.factor_kind
        };
        let purpose = if req.purpose == 0 {
            authn_entity_pb::MfaChallengePurpose::LoginStepUp as i32
        } else {
            req.purpose
        };
        let ttl = std::env::var("UDB_MFA_CHALLENGE_TTL_SECONDS")
            .ok()
            .and_then(|v| v.parse::<u64>().ok())
            .filter(|t| *t > 0)
            .unwrap_or(300);
        let now = now_unix();
        let expires = now.saturating_add(ttl);
        let challenge_id = Uuid::new_v4().to_string();
        let fp_hash = if req.device_fingerprint.trim().is_empty() {
            String::new()
        } else {
            self.device_fingerprint_hash(&req.device_fingerprint)
        };
        if let Ok(runtime) = self.authn_runtime() {
            let expires_at = unix_to_utc(expires).ok_or_else(|| {
                lifecycle_internal_status(
                    "issue_mfa_challenge_expiry",
                    "invalid MFA challenge expiry",
                )
            })?;
            let context = self.authn_context(&user.tenant_id, &user.project_id);
            let record = authn_record([
                ("challenge_id", LogicalValue::String(challenge_id.clone())),
                ("user_id", LogicalValue::String(user.user_id.clone())),
                ("tenant_id", LogicalValue::String(user.tenant_id.clone())),
                ("project_id", LogicalValue::String(user.project_id.clone())),
                ("factor_kind", LogicalValue::String(auth_factor_db(factor))),
                ("purpose", LogicalValue::String(mfa_purpose_db(purpose))),
                (
                    "device_fingerprint_hash",
                    LogicalValue::String(fp_hash.clone()),
                ),
                (
                    "ip_address_masked",
                    LogicalValue::String(mask_ip(&req.ip_address)),
                ),
                ("expires_at", LogicalValue::Timestamp(expires_at)),
            ]);
            runtime
                .native_entity_write_for_service(
                    "authn",
                    &context,
                    "udb.core.authn.entity.v1.MfaChallenge",
                    record,
                    crate::ir::ConflictStrategy::Error,
                )
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "issue_mfa_challenge_runtime_write",
                        format!("issue MFA challenge failed: {err}"),
                    )
                })?;
            return Ok(Response::new(authn_pb::IssueMfaChallengeResponse {
                challenge_id,
                expires_at_unix: expires as i64,
                factor_kind: factor,
            }));
        }
        let sql = format!(
            "INSERT INTO {rel} ({id}, {user}, {tenant}, {project}, {factor}, {purpose}, {fp}, {ip}, {expires}) \
             VALUES ($1::UUID, $2, $3, $4, $5, $6, $7, $8, to_timestamp($9::DOUBLE PRECISION))",
            rel = m.relation,
            id = m.q("challenge_id"),
            user = m.q("user_id"),
            tenant = m.q("tenant_id"),
            project = m.q("project_id"),
            factor = m.q("factor_kind"),
            purpose = m.q("purpose"),
            fp = m.q("device_fingerprint_hash"),
            ip = m.q("ip_address_masked"),
            expires = m.q("expires_at"),
        );
        sqlx::query(&sql)
            .bind(&challenge_id)
            .bind(&user.user_id)
            .bind(&user.tenant_id)
            .bind(&user.project_id)
            .bind(auth_factor_db(factor))
            .bind(mfa_purpose_db(purpose))
            .bind(&fp_hash)
            .bind(mask_ip(&req.ip_address))
            .bind(expires as f64)
            .execute(pool)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "issue_mfa_challenge_pg_insert",
                    format!("issue MFA challenge failed: {err}"),
                )
            })?;
        Ok(Response::new(authn_pb::IssueMfaChallengeResponse {
            challenge_id,
            expires_at_unix: expires as i64,
            factor_kind: factor,
        }))
    }

    pub(super) async fn verify_mfa_challenge_impl(
        &self,
        request: Request<authn_pb::VerifyMfaChallengeRequest>,
    ) -> Result<Response<authn_pb::VerifyMfaChallengeResponse>, Status> {
        let req = request.into_inner();
        // bug_report.md B1/B4: validate the id is a UUID at the boundary so a
        // malformed challenge_id never reaches native dispatch / the
        // `WHERE {id} = $1::UUID` query (whose inner InvalidArgument was being
        // re-wrapped as Internal).
        Self::require_uuid_arg(&req.challenge_id, "challenge_id")?;
        if let Ok(runtime) = self.authn_runtime() {
            let now = unix_to_utc(now_unix()).ok_or_else(|| {
                lifecycle_internal_status(
                    "verify_mfa_challenge_time",
                    "invalid MFA verification time",
                )
            })?;
            let context = self.authn_context("", "");
            let mut assignments = std::collections::BTreeMap::new();
            assignments.insert("consumed_at".to_string(), LogicalAssignment::ServerNow);
            assignments.insert(
                "attempt_count".to_string(),
                LogicalAssignment::Increment {
                    by: LogicalValue::Int(1),
                },
            );
            let op = LogicalUpdate {
                message_type: "udb.core.authn.entity.v1.MfaChallenge".to_string(),
                filter: authn_and(vec![
                    authn_eq(
                        "challenge_id",
                        LogicalValue::String(req.challenge_id.clone()),
                    ),
                    LogicalFilter::IsNull("consumed_at".to_string()),
                    authn_cmp("expires_at", ComparisonOp::Gt, LogicalValue::Timestamp(now)),
                    authn_cmp("attempt_count", ComparisonOp::Lt, LogicalValue::Int(5)),
                ]),
                assignments,
                return_fields: vec![
                    "user_id".to_string(),
                    "factor_kind".to_string(),
                    "device_fingerprint_hash".to_string(),
                ],
                require_affected: false,
            };
            let (_, rows) = runtime
                .native_entity_update_for_service("authn", &context, op)
                .await
                .map_err(|err| {
                    crate::runtime::executor_utils::prefix_status(
                        "verify MFA challenge failed",
                        err,
                    )
                })?;
            let Some(row) = rows.first() else {
                return Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
                    verified: false,
                    user_id: String::new(),
                }));
            };
            let user_id = row
                .get("user_id")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let fp_stored = row
                .get("device_fingerprint_hash")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            if !fp_stored.is_empty() {
                let presented = if req.device_fingerprint.trim().is_empty() {
                    String::new()
                } else {
                    self.device_fingerprint_hash(&req.device_fingerprint)
                };
                if presented != fp_stored {
                    return Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
                        verified: false,
                        user_id: String::new(),
                    }));
                }
            }
            let factor_db = row
                .get("factor_kind")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let verified = self
                .verify_mfa_proof(&user_id, &factor_db, &req.code, now_unix())
                .await?;
            return Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
                verified,
                user_id: if verified { user_id } else { String::new() },
            }));
        }
        let pool = self.require_pool()?;
        let m = mfa_challenge_model();
        // Atomically consume the challenge: the UPDATE matches only an unexpired,
        // unconsumed, under-attempt-limit row and stamps consumed_at in the same
        // statement, so a replay or concurrent verify loses the race (single-use).
        let consume_sql = format!(
            "UPDATE {rel} SET {consumed} = NOW(), {attempts} = {attempts} + 1 \
             WHERE {id} = $1::UUID AND {consumed} IS NULL AND {expires} > NOW() AND {attempts} < 5 \
             RETURNING {user}::TEXT AS user_id, {factor}::TEXT AS factor_kind, \
                       COALESCE({fp}::TEXT,'') AS fp",
            rel = m.relation,
            consumed = m.q("consumed_at"),
            attempts = m.q("attempt_count"),
            id = m.q("challenge_id"),
            expires = m.q("expires_at"),
            user = m.q("user_id"),
            factor = m.q("factor_kind"),
            fp = m.q("device_fingerprint_hash"),
        );
        let Some(row) = sqlx::query(&consume_sql)
            .bind(&req.challenge_id)
            .fetch_optional(pool)
            .await
            .map_err(|err| {
                crate::runtime::executor_utils::sqlx_error_to_status(
                    "verify MFA challenge failed",
                    &err,
                )
            })?
        else {
            // Either expired, already consumed (replay), or over the attempt cap.
            return Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
                verified: false,
                user_id: String::new(),
            }));
        };
        let user_id: String = row.try_get("user_id").unwrap_or_default();
        let fp_stored: String = row.try_get("fp").unwrap_or_default();
        // Device binding: when a fingerprint was bound at issuance, the verifier
        // must present the same device.
        if !fp_stored.is_empty() {
            let presented = if req.device_fingerprint.trim().is_empty() {
                String::new()
            } else {
                self.device_fingerprint_hash(&req.device_fingerprint)
            };
            if presented != fp_stored {
                return Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
                    verified: false,
                    user_id: String::new(),
                }));
            }
        }
        let factor_db: String = row.try_get("factor_kind").unwrap_or_default();
        // Verify the proof against the user's factor. TOTP and recovery codes are
        // checked against the stored secret / code hashes (reusing existing
        // helpers); email/SMS OTP challenges verify against the OTP store via code.
        let now = now_unix();
        let verified = self
            .verify_mfa_proof(&user_id, &factor_db, &req.code, now)
            .await?;
        Ok(Response::new(authn_pb::VerifyMfaChallengeResponse {
            verified,
            user_id: if verified { user_id } else { String::new() },
        }))
    }

    async fn verify_mfa_proof(
        &self,
        user_id: &str,
        factor_db: &str,
        code: &str,
        now: u64,
    ) -> Result<bool, Status> {
        let user = self
            .users
            .get_user_by_id(user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("verify_mfa_proof_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        let upper = factor_db.to_ascii_uppercase();
        if upper.contains("TOTP") {
            let ok = authn::totp::decrypt_secret(&user.totp_secret_hash, &self.otp_hash_key())
                .map(|secret| authn::totp::verify(&secret, code, now))
                .unwrap_or(false);
            return Ok(ok);
        }
        if upper.contains("RECOVERY") {
            let hash = authn::hash_recovery_code(code, &self.otp_hash_key());
            return self
                .users
                .consume_recovery_code(user_id, &hash, now)
                .await
                .map_err(|err| {
                    lifecycle_internal_status("verify_mfa_recovery_code", err.to_string())
                });
        }
        // For OTP-style factors the `code` is treated as a previously-issued OTP
        // id+code is out of band; without that we cannot verify here.
        Ok(false)
    }

    // ── MFA factor management (I2.6) ────────────────────────────────────────

    pub(super) async fn list_mfa_factors_impl(
        &self,
        request: Request<authn_pb::ListMfaFactorsRequest>,
    ) -> Result<Response<authn_pb::ListMfaFactorsResponse>, Status> {
        let req = request.into_inner();
        let user = self
            .users
            .get_user_by_id(&req.user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("list_mfa_factors_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        let mut factors = Vec::new();
        factors.push(authn_pb::MfaFactorSummary {
            factor_kind: authn_entity_pb::AuthFactorKind::Totp as i32,
            enabled: !user.totp_secret_hash.is_empty() && user.mfa_enabled,
            label: "Authenticator app".to_string(),
        });
        // WebAuthn factor presence (best-effort count of registered credentials).
        let passkeys = self.count_webauthn_credentials(&user.user_id).await;
        factors.push(authn_pb::MfaFactorSummary {
            factor_kind: authn_entity_pb::AuthFactorKind::Webauthn as i32,
            enabled: passkeys > 0,
            label: format!("{passkeys} passkey(s)"),
        });
        let page_window = native_offset_page_window(1, req.page_size, &req.page_token, 50);
        let total = factors.len() as i64;
        let factors = factors
            .into_iter()
            .skip(page_window.offset)
            .take(page_window.limit)
            .collect();
        Ok(Response::new(authn_pb::ListMfaFactorsResponse {
            factors,
            next_page_token: native_next_page_token_for_total(
                page_window.offset,
                page_window.limit,
                total,
            ),
        }))
    }

    pub(super) async fn disable_mfa_factor_impl(
        &self,
        request: Request<authn_pb::DisableMfaFactorRequest>,
    ) -> Result<Response<authn_pb::DisableMfaFactorResponse>, Status> {
        let req = request.into_inner();
        let mut user = self
            .users
            .get_user_by_id(&req.user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("disable_mfa_factor_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        let now = now_unix();
        if req.factor_kind == authn_entity_pb::AuthFactorKind::Totp as i32 {
            user.totp_secret_hash = String::new();
            user.mfa_enabled = false;
            user.updated_at_unix = now;
            self.users.put_user(user.clone()).await.map_err(|err| {
                lifecycle_internal_status("disable_mfa_factor_store", err.to_string())
            })?;
        } else if req.factor_kind == authn_entity_pb::AuthFactorKind::Webauthn as i32 {
            self.delete_all_webauthn_credentials(&req.user_id).await?;
        }
        self.emit_event(
            AuthEvent::new(
                topics::MFA_FACTOR_DISABLED,
                req.user_id.clone(),
                user.tenant_id.clone(),
                serde_json::json!({ "user_id": req.user_id.clone(), "factor_kind": req.factor_kind }),
            )
            .with_correlation(format!("mfa_disable:{}", req.user_id))
            .with_compliance(ComplianceEnvelope {
                actor: req.user_id.clone(),
                target_resource: req.user_id.clone(),
                operation: "mfa_disable".to_string(),
                outcome: "success".to_string(),
                reason_code: "factor_disabled".to_string(),
                auth_method: "mfa".to_string(),
                ..ComplianceEnvelope::default()
            }),
        )
        .await;
        Ok(Response::new(authn_pb::DisableMfaFactorResponse {
            disabled: true,
        }))
    }

    pub(super) async fn revoke_recovery_codes_impl(
        &self,
        request: Request<authn_pb::RevokeRecoveryCodesRequest>,
    ) -> Result<Response<authn_pb::RevokeRecoveryCodesResponse>, Status> {
        let req = request.into_inner();
        let user = self
            .users
            .get_user_by_id(&req.user_id)
            .await
            .map_err(|err| {
                lifecycle_internal_status("revoke_recovery_codes_user_load", err.to_string())
            })?
            .ok_or_else(super::authn_user_not_found_status)?;
        // Replace with an empty set → all prior codes invalidated.
        self.users
            .replace_recovery_codes(&req.user_id, &user.tenant_id, &[])
            .await
            .map_err(|err| {
                lifecycle_internal_status("revoke_recovery_codes_replace", err.to_string())
            })?;
        Ok(Response::new(authn_pb::RevokeRecoveryCodesResponse {
            revoked_count: 0,
        }))
    }

    pub(super) async fn admin_reset_mfa_impl(
        &self,
        request: Request<authn_pb::AdminResetMfaRequest>,
    ) -> Result<Response<authn_pb::AdminResetMfaResponse>, Status> {
        let req = request.into_inner();
        let mut user = self
            .users
            .get_user_by_id(&req.user_id)
            .await
            .map_err(|err| lifecycle_internal_status("admin_reset_mfa_user_load", err.to_string()))?
            .ok_or_else(super::authn_user_not_found_status)?;
        let now = now_unix();
        // Clear all factors: TOTP secret, recovery codes, WebAuthn credentials.
        user.totp_secret_hash = String::new();
        user.mfa_enabled = false;
        user.updated_at_unix = now;
        let tenant = user.tenant_id.clone();
        self.users
            .put_user(user)
            .await
            .map_err(|err| lifecycle_internal_status("admin_reset_mfa_store", err.to_string()))?;
        let _ = self
            .users
            .replace_recovery_codes(&req.user_id, &tenant, &[])
            .await;
        self.delete_all_webauthn_credentials(&req.user_id)
            .await
            .ok();
        // Admin recovery path is audited (does not bypass audit, I2.7).
        let admin_actor = req
            .context
            .as_ref()
            .map(|c| c.user_id.clone())
            .filter(|a| !a.trim().is_empty())
            .unwrap_or_else(|| req.user_id.clone());
        self.emit_event(
            AuthEvent::new(
                topics::MFA_RESET,
                req.user_id.clone(),
                tenant,
                serde_json::json!({
                    "user_id": req.user_id.clone(),
                    "actor": req.context.as_ref().map(|c| c.user_id.clone()).unwrap_or_default(),
                    "reason": req.reason.clone(),
                }),
            )
            .with_correlation(format!("mfa_reset:{}", req.user_id))
            .with_compliance(ComplianceEnvelope {
                actor: admin_actor,
                target_resource: req.user_id.clone(),
                operation: "mfa_reset".to_string(),
                outcome: "success".to_string(),
                reason_code: if req.reason.trim().is_empty() {
                    "admin_mfa_reset".to_string()
                } else {
                    req.reason.clone()
                },
                auth_method: "admin".to_string(),
                ..ComplianceEnvelope::default()
            }),
        )
        .await;
        Ok(Response::new(authn_pb::AdminResetMfaResponse {
            reset: true,
        }))
    }

    // ── WebAuthn credential lifecycle (I2.7) ────────────────────────────────

    async fn count_webauthn_credentials(&self, user_id: &str) -> i64 {
        let Some(pool) = self.pg_pool.as_ref() else {
            return 0;
        };
        let m = native_model(
            "udb.core.authn.entity.v1.WebAuthnCredential",
            &["credential_id", "user_id"],
        );
        sqlx::query_scalar::<_, i64>(&format!(
            "SELECT COUNT(*)::bigint FROM {rel} WHERE {user} = $1::UUID",
            rel = m.relation,
            user = m.q("user_id"),
        ))
        .bind(user_id)
        .fetch_one(pool)
        .await
        .unwrap_or(0)
    }

    async fn delete_all_webauthn_credentials(&self, user_id: &str) -> Result<u64, Status> {
        if let Ok(runtime) = self.authn_runtime() {
            let context = self.authn_context("", "");
            let op = LogicalDelete {
                message_type: "udb.core.authn.entity.v1.WebAuthnCredential".to_string(),
                filter: authn_eq("user_id", LogicalValue::String(user_id.to_string())),
                return_fields: vec!["credential_id".to_string()],
            };
            let rows = runtime
                .native_entity_delete_rows_for_service("authn", &context, op)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "delete_webauthn_credentials_runtime",
                        format!("delete WebAuthn credentials failed: {err}"),
                    )
                })?;
            return Ok(rows.len() as u64);
        }
        let pool = self.require_pool()?;
        let m = native_model(
            "udb.core.authn.entity.v1.WebAuthnCredential",
            &["credential_id", "user_id"],
        );
        let res = sqlx::query(&format!(
            "DELETE FROM {rel} WHERE {user} = $1::UUID",
            rel = m.relation,
            user = m.q("user_id"),
        ))
        .bind(user_id)
        .execute(pool)
        .await
        .map_err(|err| {
            lifecycle_internal_status(
                "delete_webauthn_credentials_pg",
                format!("delete WebAuthn credentials failed: {err}"),
            )
        })?;
        Ok(res.rows_affected())
    }

    pub(super) async fn list_web_authn_credentials_impl(
        &self,
        request: Request<authn_pb::ListWebAuthnCredentialsRequest>,
    ) -> Result<Response<authn_pb::ListWebAuthnCredentialsResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id is required",
                [("user_id", "must be a non-empty user id")],
            ));
        }
        let pool = self.require_pool()?;
        let m = native_model(
            "udb.core.authn.entity.v1.WebAuthnCredential",
            &[
                "credential_id",
                "user_id",
                "label",
                "created_at",
                "last_used_at",
            ],
        );
        let sql = format!(
            "SELECT {id}::TEXT AS credential_id, COALESCE({label}::TEXT,'') AS label, \
                    {created}, {last} \
             FROM {rel} WHERE {user} = $1::UUID ORDER BY {created_col} ASC",
            id = m.q("credential_id"),
            label = m.q("label"),
            created = m.timestamp_unix_as("created_at", "created_at"),
            created_col = m.q("created_at"),
            last = m.timestamp_unix_as("last_used_at", "last_used_at"),
            rel = m.relation,
            user = m.q("user_id"),
        );
        let rows = sqlx::query(&sql)
            .bind(&req.user_id)
            .fetch_all(pool)
            .await
            .map_err(|err| {
                lifecycle_internal_status(
                    "list_webauthn_credentials",
                    format!("list WebAuthn credentials failed: {err}"),
                )
            })?;
        let page_window = native_offset_page_window(1, req.page_size, &req.page_token, 50);
        let total = rows.len() as i64;
        let credentials = rows
            .iter()
            .skip(page_window.offset)
            .take(page_window.limit)
            .map(|row| authn_pb::WebAuthnCredentialSummary {
                credential_id: row.try_get("credential_id").unwrap_or_default(),
                label: row.try_get("label").unwrap_or_default(),
                created_at_unix: row.try_get::<i64, _>("created_at").unwrap_or(0),
                last_used_at_unix: row.try_get::<i64, _>("last_used_at").unwrap_or(0),
            })
            .collect();
        Ok(Response::new(authn_pb::ListWebAuthnCredentialsResponse {
            credentials,
            next_page_token: native_next_page_token_for_total(
                page_window.offset,
                page_window.limit,
                total,
            ),
        }))
    }

    pub(super) async fn delete_web_authn_credential_impl(
        &self,
        request: Request<authn_pb::DeleteWebAuthnCredentialRequest>,
    ) -> Result<Response<authn_pb::DeleteWebAuthnCredentialResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() || req.credential_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id and credential_id are required",
                [
                    ("user_id", "must be a non-empty user id"),
                    (
                        "credential_id",
                        "must be a non-empty WebAuthn credential id",
                    ),
                ],
            ));
        }
        if let Ok(runtime) = self.authn_runtime() {
            let context = self.authn_context("", "");
            let op = LogicalDelete {
                message_type: "udb.core.authn.entity.v1.WebAuthnCredential".to_string(),
                filter: authn_and(vec![
                    authn_eq(
                        "credential_id",
                        LogicalValue::String(req.credential_id.clone()),
                    ),
                    authn_eq("user_id", LogicalValue::String(req.user_id.clone())),
                ]),
                return_fields: vec!["credential_id".to_string()],
            };
            let rows = runtime
                .native_entity_delete_rows_for_service("authn", &context, op)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "delete_webauthn_credential_runtime",
                        format!("delete WebAuthn credential failed: {err}"),
                    )
                })?;
            return Ok(Response::new(authn_pb::DeleteWebAuthnCredentialResponse {
                deleted: !rows.is_empty(),
            }));
        }
        let pool = self.require_pool()?;
        let m = native_model(
            "udb.core.authn.entity.v1.WebAuthnCredential",
            &["credential_id", "user_id"],
        );
        let res = sqlx::query(&format!(
            "DELETE FROM {rel} WHERE {id} = $1 AND {user} = $2::UUID",
            rel = m.relation,
            id = m.q("credential_id"),
            user = m.q("user_id"),
        ))
        .bind(&req.credential_id)
        .bind(&req.user_id)
        .execute(pool)
        .await
        .map_err(|err| {
            lifecycle_internal_status(
                "delete_webauthn_credential_pg",
                format!("delete WebAuthn credential failed: {err}"),
            )
        })?;
        Ok(Response::new(authn_pb::DeleteWebAuthnCredentialResponse {
            deleted: res.rows_affected() > 0,
        }))
    }

    pub(super) async fn rename_passkey_impl(
        &self,
        request: Request<authn_pb::RenamePasskeyRequest>,
    ) -> Result<Response<authn_pb::RenamePasskeyResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() || req.credential_id.trim().is_empty() {
            return Err(lifecycle_invalid_fields(
                "user_id and credential_id are required",
                [
                    ("user_id", "must be a non-empty user id"),
                    (
                        "credential_id",
                        "must be a non-empty WebAuthn credential id",
                    ),
                ],
            ));
        }
        if let Ok(runtime) = self.authn_runtime() {
            let context = self.authn_context("", "");
            let mut assignments = std::collections::BTreeMap::new();
            assignments.insert(
                "label".to_string(),
                authn_set(LogicalValue::String(req.new_label.clone())),
            );
            assignments.insert("updated_at".to_string(), LogicalAssignment::ServerNow);
            let op = LogicalUpdate {
                message_type: "udb.core.authn.entity.v1.WebAuthnCredential".to_string(),
                filter: authn_and(vec![
                    authn_eq(
                        "credential_id",
                        LogicalValue::String(req.credential_id.clone()),
                    ),
                    authn_eq("user_id", LogicalValue::String(req.user_id.clone())),
                ]),
                assignments,
                return_fields: vec!["credential_id".to_string()],
                require_affected: false,
            };
            let (_, rows) = runtime
                .native_entity_update_for_service("authn", &context, op)
                .await
                .map_err(|err| {
                    lifecycle_internal_status(
                        "rename_passkey_runtime",
                        format!("rename passkey failed: {err}"),
                    )
                })?;
            return Ok(Response::new(authn_pb::RenamePasskeyResponse {
                renamed: !rows.is_empty(),
            }));
        }
        let pool = self.require_pool()?;
        let m = native_model(
            "udb.core.authn.entity.v1.WebAuthnCredential",
            &["credential_id", "user_id", "label", "updated_at"],
        );
        let res = sqlx::query(&format!(
            "UPDATE {rel} SET {label} = $3, {updated} = NOW() WHERE {id} = $1 AND {user} = $2::UUID",
            rel = m.relation,
            label = m.q("label"),
            updated = m.q("updated_at"),
            id = m.q("credential_id"),
            user = m.q("user_id"),
        ))
        .bind(&req.credential_id)
        .bind(&req.user_id)
        .bind(&req.new_label)
        .execute(pool)
        .await
        .map_err(|err| lifecycle_internal_status("rename_passkey_pg", format!("rename passkey failed: {err}")))?;
        Ok(Response::new(authn_pb::RenamePasskeyResponse {
            renamed: res.rows_affected() > 0,
        }))
    }
}

/// DB string form of an `AuthFactorKind` enum value.
fn auth_factor_db(kind: i32) -> String {
    authn_entity_pb::AuthFactorKind::try_from(kind)
        .unwrap_or(authn_entity_pb::AuthFactorKind::Unspecified)
        .as_str_name()
        .to_string()
}

/// DB string form of an `MfaChallengePurpose` enum value.
fn mfa_purpose_db(purpose: i32) -> String {
    authn_entity_pb::MfaChallengePurpose::try_from(purpose)
        .unwrap_or(authn_entity_pb::MfaChallengePurpose::Unspecified)
        .as_str_name()
        .to_string()
}

/// Parse the DB device-type string back to the proto enum tag.
fn parse_device_type(value: &str) -> i32 {
    authn_entity_pb::DeviceType::from_str_name(&value.to_ascii_uppercase())
        .or_else(|| {
            authn_entity_pb::DeviceType::from_str_name(&format!(
                "DEVICE_TYPE_{}",
                value.to_ascii_uppercase()
            ))
        })
        .unwrap_or(authn_entity_pb::DeviceType::Web) as i32
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::udb::core::authn::services::v1::authn_service_server::AuthnService;
    use crate::proto::{ErrorDetail, ErrorKind};
    use crate::runtime::executor_utils::ERROR_DETAIL_METADATA_KEY;

    #[test]
    fn mask_ip_truncates_v4_to_24() {
        assert_eq!(mask_ip("203.0.113.42"), "203.0.113.0/24");
        // Masked output never contains the final host octet.
        assert!(!mask_ip("203.0.113.42").contains("42"));
    }

    #[test]
    fn mask_ip_truncates_v6_to_48() {
        let masked = mask_ip("2001:db8:abcd:1234::1");
        assert!(masked.ends_with("::/48"));
        assert!(masked.starts_with("2001:db8:abcd"));
    }

    #[test]
    fn mask_ip_handles_empty_and_nonip() {
        assert_eq!(mask_ip(""), "");
        assert_eq!(mask_ip("not-an-ip"), "not-an-ip");
    }

    #[test]
    fn device_type_parse_accepts_short_and_full_forms() {
        assert_eq!(
            parse_device_type("WEB"),
            authn_entity_pb::DeviceType::Web as i32
        );
        assert_eq!(
            parse_device_type("MOBILE"),
            authn_entity_pb::DeviceType::Mobile as i32
        );
        assert_eq!(
            parse_device_type("DEVICE_TYPE_API"),
            authn_entity_pb::DeviceType::Api as i32
        );
        // Unknown falls back to WEB rather than panicking.
        assert_eq!(
            parse_device_type("???"),
            authn_entity_pb::DeviceType::Web as i32
        );
    }

    fn deny_test_service() -> AuthnServiceImpl {
        // No-pool service: the D3 body-tenant guard fires BEFORE `require_pool`, so
        // a cross-tenant call is denied without a live Postgres.
        let config = crate::runtime::authn::AuthnConfig {
            session_hash_secret: "deny-test-secret".to_string(),
            ..crate::runtime::authn::AuthnConfig::default()
        };
        AuthnServiceImpl::new(config, crate::runtime::security::SecurityConfig::default())
    }

    fn decode_detail(status: &Status) -> ErrorDetail {
        let raw = status
            .metadata()
            .get_bin(ERROR_DETAIL_METADATA_KEY)
            .expect("typed detail trailer is present")
            .to_bytes()
            .expect("typed detail trailer decodes to bytes");
        crate::runtime::executor_utils::decode_error_detail_from_raw(&raw)
    }

    fn assert_validation_fields(status: &Status, expected: &[(&str, &str)]) {
        assert_eq!(status.code(), tonic::Code::InvalidArgument);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Validation as i32);
        assert_eq!(detail.field_violations.len(), expected.len());
        for (actual, (field, description)) in detail.field_violations.iter().zip(expected) {
            assert_eq!(actual.field, *field);
            assert_eq!(actual.description, *description);
        }
    }

    fn assert_capability_detail(
        status: &Status,
        operation: &str,
        capability_required: &str,
        message: &str,
    ) {
        assert_eq!(status.code(), tonic::Code::FailedPrecondition);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Capability as i32);
        assert_eq!(detail.backend, "authn");
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.capability_required, capability_required);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
    }

    fn assert_policy_detail(
        status: &Status,
        operation: &str,
        policy_decision_id: &str,
        message: &str,
    ) {
        assert_eq!(status.code(), tonic::Code::PermissionDenied);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Policy as i32);
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.policy_decision_id, policy_decision_id);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
        assert!(detail.field_violations.is_empty());
    }

    fn assert_internal_detail(status: &Status, operation: &str, message: &str) {
        assert_eq!(status.code(), tonic::Code::Internal);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Internal as i32);
        assert_eq!(detail.backend, "authn");
        assert_eq!(detail.operation, operation);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
        assert!(detail.field_violations.is_empty());
    }

    #[test]
    fn lifecycle_internal_status_carries_typed_detail() {
        let status = lifecycle_internal_status("list_devices_query", "list devices failed");
        assert_internal_detail(&status, "list_devices_query", "list devices failed");
    }

    #[test]
    fn authn_missing_postgres_store_capability_carries_typed_detail() {
        let svc = deny_test_service();
        let err = match svc.require_pool() {
            Err(status) => status,
            Ok(_) => panic!("pool-less authn service must fail closed"),
        };

        assert_capability_detail(
            &err,
            "postgres_auth_store",
            "native_postgres_auth_store",
            "this operation requires the native Postgres auth store",
        );
    }

    #[tokio::test]
    async fn list_devices_missing_user_id_carries_field_violation() {
        let err = deny_test_service()
            .list_devices(Request::new(authn_pb::ListDevicesRequest::default()))
            .await
            .expect_err("missing user_id must fail before pool access");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn admin_revoke_session_missing_user_id_carries_field_violation() {
        let err = deny_test_service()
            .admin_revoke_session(Request::new(authn_pb::AdminRevokeSessionRequest::default()))
            .await
            .expect_err("missing user_id must fail before pool access");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn admin_revoke_all_user_sessions_missing_user_id_carries_field_violation() {
        let err = deny_test_service()
            .admin_revoke_all_user_sessions(Request::new(
                authn_pb::AdminRevokeAllUserSessionsRequest::default(),
            ))
            .await
            .expect_err("missing user_id must fail before pool access");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn admin_revoke_all_tenant_sessions_missing_tenant_id_carries_field_violation() {
        let err = deny_test_service()
            .admin_revoke_all_tenant_sessions(Request::new(
                authn_pb::AdminRevokeAllTenantSessionsRequest::default(),
            ))
            .await
            .expect_err("missing tenant_id must fail before claim or pool access");

        assert_eq!(err.message(), "tenant_id is required");
        assert_validation_fields(&err, &[("tenant_id", "must be a non-empty tenant id")]);
    }

    #[tokio::test]
    async fn emergency_revoke_missing_selector_carries_field_violation() {
        let err = deny_test_service()
            .emergency_revoke(Request::new(authn_pb::EmergencyRevokeRequest::default()))
            .await
            .expect_err("missing selector must fail before pool access");

        assert_eq!(
            err.message(),
            "at least one selector is required (signing_key_id/token_family_id/tenant_id/principal_id)"
        );
        assert_validation_fields(
            &err,
            &[(
                "selectors",
                "must include at least one of signing_key_id, token_family_id, tenant_id, or principal_id",
            )],
        );
    }

    #[tokio::test]
    async fn list_webauthn_credentials_missing_user_id_carries_field_violation() {
        let err = deny_test_service()
            .list_web_authn_credentials(Request::new(
                authn_pb::ListWebAuthnCredentialsRequest::default(),
            ))
            .await
            .expect_err("missing user_id must fail before pool access");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn delete_webauthn_credential_missing_identity_carries_field_violations() {
        let err = deny_test_service()
            .delete_web_authn_credential(Request::new(
                authn_pb::DeleteWebAuthnCredentialRequest::default(),
            ))
            .await
            .expect_err("missing credential identity must fail before runtime/pool access");

        assert_eq!(err.message(), "user_id and credential_id are required");
        assert_validation_fields(
            &err,
            &[
                ("user_id", "must be a non-empty user id"),
                (
                    "credential_id",
                    "must be a non-empty WebAuthn credential id",
                ),
            ],
        );
    }

    #[tokio::test]
    async fn rename_passkey_missing_identity_carries_field_violations() {
        let err = deny_test_service()
            .rename_passkey(Request::new(authn_pb::RenamePasskeyRequest::default()))
            .await
            .expect_err("missing credential identity must fail before runtime/pool access");

        assert_eq!(err.message(), "user_id and credential_id are required");
        assert_validation_fields(
            &err,
            &[
                ("user_id", "must be a non-empty user id"),
                (
                    "credential_id",
                    "must be a non-empty WebAuthn credential id",
                ),
            ],
        );
    }

    #[tokio::test]
    async fn revoke_device_tenantless_non_admin_carries_policy_detail() {
        let svc = deny_test_service();
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "reader-a",
            "",
            "",
            &["udb:authn:write"],
            &[],
        );
        let req = Request::new(authn_pb::RevokeDeviceRequest {
            device_id: "11111111-1111-4111-8111-111111111111".to_string(),
            reason: "lost".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc.revoke_device_impl(req),
        )
        .await
        .expect_err("tenantless non-admin device revoke must fail before pool access");

        assert_policy_detail(
            &err,
            "revoke_device",
            "tenant_scoped_bearer_required",
            "device revoke requires a tenant-scoped bearer token or a cross-tenant admin role",
        );
    }

    #[tokio::test]
    async fn admin_revoke_all_tenant_sessions_denies_cross_tenant_body() {
        // D3: a tenant-A admin token cannot revoke tenant B by setting body
        // tenant_id=tenant-b. The claim-bound guard denies before any DB access.
        let svc = deny_test_service();
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "admin-a",
            "tenant-a",
            "",
            &["udb:authn:write"],
            &[],
        );
        let req = Request::new(authn_pb::AdminRevokeAllTenantSessionsRequest {
            tenant_id: "tenant-b".to_string(),
            reason: "attack".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc.admin_revoke_all_tenant_sessions_impl(req),
        )
        .await
        .expect_err("cross-tenant tenant-revoke must be denied");
        assert_eq!(err.code(), tonic::Code::PermissionDenied);
    }

    #[tokio::test]
    async fn cross_tenant_admin_may_revoke_other_tenant_sessions() {
        // A genuine platform admin is allowed past the D3 guard; it then proceeds to
        // the DB stage (no pool wired → failed_precondition, NOT permission_denied),
        // which proves the guard did not block the legitimate cross-tenant admin.
        let svc = deny_test_service();
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "ops-1",
            "tenant-a",
            "",
            &[],
            &["platform_admin"],
        );
        let req = Request::new(authn_pb::AdminRevokeAllTenantSessionsRequest {
            tenant_id: "tenant-b".to_string(),
            reason: "legit".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc.admin_revoke_all_tenant_sessions_impl(req),
        )
        .await
        .expect_err("no pool wired → reaches DB stage and fails precondition");
        assert_eq!(err.code(), tonic::Code::FailedPrecondition);
    }

    #[test]
    fn auth_factor_and_purpose_db_roundtrip_through_proto_names() {
        // The DB string is the canonical proto enum name; verify it parses back.
        let factor = auth_factor_db(authn_entity_pb::AuthFactorKind::Totp as i32);
        assert_eq!(factor, "AUTH_FACTOR_KIND_TOTP");
        assert_eq!(
            authn_entity_pb::AuthFactorKind::from_str_name(&factor),
            Some(authn_entity_pb::AuthFactorKind::Totp)
        );
        let purpose = mfa_purpose_db(authn_entity_pb::MfaChallengePurpose::LoginStepUp as i32);
        assert_eq!(purpose, "MFA_CHALLENGE_PURPOSE_LOGIN_STEP_UP");
        assert_eq!(
            authn_entity_pb::MfaChallengePurpose::from_str_name(&purpose),
            Some(authn_entity_pb::MfaChallengePurpose::LoginStepUp)
        );
    }
}