rivven-core 0.0.21

Core library for Rivven distributed event streaming platform
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
//! Authentication and Authorization (RBAC/ACL) for Rivven
//!
//! This module provides production-grade security for Rivven including:
//! - SASL/PLAIN authentication (compatible with Kafka clients)
//! - SCRAM-SHA-256 authentication (more secure, salted)
//! - Role-Based Access Control (RBAC)
//! - Topic/Schema-level Access Control Lists (ACLs)
//! - Principal management (users, service accounts)
//!
//! ## Security Model
//!
//! Rivven uses a principal-based security model:
//! - **Principal**: An authenticated identity (user, service account)
//! - **Role**: A set of permissions (admin, producer, consumer)
//! - **ACL**: Fine-grained access rules for specific resources
//!
//! ## Threat Model
//!
//! This implementation defends against:
//! - Credential stuffing (rate limiting on auth failures)
//! - Timing attacks (constant-time password comparison)
//! - Replay attacks (nonce-based challenge-response)
//! - Privilege escalation (strict role hierarchy)
//! - Resource enumeration (deny by default)

use parking_lot::RwLock;
use ring::rand::{SecureRandom, SystemRandom};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use tracing::{debug, warn};

// ============================================================================
// Error Types
// ============================================================================

#[derive(Error, Debug, Clone)]
pub enum AuthError {
    #[error("Authentication failed")]
    AuthenticationFailed,

    #[error("Invalid credentials")]
    InvalidCredentials,

    #[error("Principal not found: {0}")]
    PrincipalNotFound(String),

    #[error("Principal already exists: {0}")]
    PrincipalAlreadyExists(String),

    #[error("Access denied: {0}")]
    AccessDenied(String),

    #[error("Permission denied: {principal} lacks {permission} on {resource}")]
    PermissionDenied {
        principal: String,
        permission: String,
        resource: String,
    },

    #[error("Role not found: {0}")]
    RoleNotFound(String),

    #[error("Invalid token")]
    InvalidToken,

    #[error("Token expired")]
    TokenExpired,

    #[error("Rate limited: too many authentication failures")]
    RateLimited,

    #[error("Internal error: {0}")]
    Internal(String),
}

pub type AuthResult<T> = std::result::Result<T, AuthError>;

// ============================================================================
// Resource Types for ACLs
// ============================================================================

/// Types of resources that can have ACLs
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResourceType {
    /// All cluster operations
    Cluster,
    /// Specific topic
    Topic(String),
    /// Pattern-matched topics (e.g., "orders-*")
    TopicPattern(String),
    /// Consumer group
    ConsumerGroup(String),
    /// Schema subject
    Schema(String),
    /// Transactional ID
    TransactionalId(String),
}

impl ResourceType {
    /// Check if this resource matches another (for pattern matching)
    pub fn matches(&self, other: &ResourceType) -> bool {
        match (self, other) {
            // Exact match
            (a, b) if a == b => true,

            // Topic pattern matching
            (ResourceType::TopicPattern(pattern), ResourceType::Topic(name)) => {
                Self::glob_match(pattern, name)
            }
            (ResourceType::Topic(name), ResourceType::TopicPattern(pattern)) => {
                Self::glob_match(pattern, name)
            }

            _ => false,
        }
    }

    /// Simple glob matching for patterns like "orders-*"
    fn glob_match(pattern: &str, text: &str) -> bool {
        if pattern == "*" {
            return true;
        }

        if let Some(prefix) = pattern.strip_suffix('*') {
            return text.starts_with(prefix);
        }

        if let Some(suffix) = pattern.strip_prefix('*') {
            return text.ends_with(suffix);
        }

        // Check for middle wildcard (e.g., "pre*suf")
        if let Some(idx) = pattern.find('*') {
            let prefix = &pattern[..idx];
            let suffix = &pattern[idx + 1..];
            return text.starts_with(prefix)
                && text.ends_with(suffix)
                && text.len() >= prefix.len() + suffix.len();
        }

        pattern == text
    }
}

// ============================================================================
// Permissions
// ============================================================================

/// Operations that can be performed on resources
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Permission {
    // Topic operations
    Read,     // Consume from topic
    Write,    // Produce to topic
    Create,   // Create topic
    Delete,   // Delete topic
    Alter,    // Modify topic config
    Describe, // View topic metadata

    // Consumer group operations
    GroupRead,   // Read group state
    GroupDelete, // Delete consumer group

    // Cluster operations
    ClusterAction,   // Cluster-wide actions (rebalance, etc.)
    IdempotentWrite, // Idempotent producer

    // Admin operations
    AlterConfigs,    // Modify broker configs
    DescribeConfigs, // View broker configs

    // Full access
    All, // All permissions (super admin)
}

impl Permission {
    /// Check if this permission implies another permission
    /// A permission implies itself + any subordinate permissions
    pub fn implies(&self, other: &Permission) -> bool {
        // Same permission always implies itself
        if self == other {
            return true;
        }

        match self {
            Permission::All => true, // All implies everything
            // These permissions imply Describe
            Permission::Alter | Permission::Write | Permission::Read => {
                matches!(other, Permission::Describe)
            }
            _ => false,
        }
    }
}

// ============================================================================
// Principal Types
// ============================================================================

/// Type of principal (for audit logging and quotas)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PrincipalType {
    User,
    ServiceAccount,
    Anonymous,
}

/// A security principal (identity)
///
/// # Security Note
///
/// This struct implements a custom Debug that redacts the password_hash field
/// to prevent accidental leakage to logs.
#[derive(Clone, Serialize, Deserialize)]
pub struct Principal {
    /// Principal name (unique identifier)
    pub name: String,

    /// Type of principal
    pub principal_type: PrincipalType,

    /// Hashed password (SCRAM-SHA-256 format)
    pub password_hash: PasswordHash,

    /// Roles assigned to this principal
    pub roles: HashSet<String>,

    /// Whether the principal is enabled
    pub enabled: bool,

    /// Optional metadata (tags, labels)
    pub metadata: HashMap<String, String>,

    /// Creation timestamp
    pub created_at: u64,
}

impl std::fmt::Debug for Principal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Principal")
            .field("name", &self.name)
            .field("principal_type", &self.principal_type)
            .field("password_hash", &"[REDACTED]")
            .field("roles", &self.roles)
            .field("enabled", &self.enabled)
            .field("metadata", &self.metadata)
            .field("created_at", &self.created_at)
            .finish()
    }
}

/// SCRAM-SHA-256 password hash with salt and iterations
///
/// # Security Note
///
/// This struct implements a custom Debug that redacts sensitive key material
/// to prevent accidental leakage to logs.
#[derive(Clone, Serialize, Deserialize)]
pub struct PasswordHash {
    /// Salt (32 bytes, base64 encoded for storage)
    pub salt: Vec<u8>,
    /// Number of iterations
    pub iterations: u32,
    /// Server key
    pub server_key: Vec<u8>,
    /// Stored key
    pub stored_key: Vec<u8>,
}

impl std::fmt::Debug for PasswordHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PasswordHash")
            .field("salt", &"[REDACTED]")
            .field("iterations", &self.iterations)
            .field("server_key", &"[REDACTED]")
            .field("stored_key", &"[REDACTED]")
            .finish()
    }
}

impl PasswordHash {
    /// Create a new password hash from plaintext
    pub fn new(password: &str) -> Self {
        let rng = SystemRandom::new();
        let mut salt = vec![0u8; 32];
        rng.fill(&mut salt).expect("Failed to generate salt");

        Self::with_salt(password, &salt, 600_000)
    }

    /// Create a password hash with a specific salt (for testing/migration)
    pub fn with_salt(password: &str, salt: &[u8], iterations: u32) -> Self {
        // PBKDF2-HMAC-SHA256 derivation
        let salted_password = Self::pbkdf2_sha256(password.as_bytes(), salt, iterations);

        // Derive client and server keys
        let client_key = Self::hmac_sha256(&salted_password, b"Client Key");
        let server_key = Self::hmac_sha256(&salted_password, b"Server Key");

        // Stored key = H(client_key)
        let stored_key = Sha256::digest(&client_key).to_vec();

        PasswordHash {
            salt: salt.to_vec(),
            iterations,
            server_key,
            stored_key,
        }
    }

    /// Verify a password against this hash (constant-time comparison)
    pub fn verify(&self, password: &str) -> bool {
        let salted_password = Self::pbkdf2_sha256(password.as_bytes(), &self.salt, self.iterations);
        let client_key = Self::hmac_sha256(&salted_password, b"Client Key");
        let stored_key = Sha256::digest(&client_key);

        // Constant-time comparison to prevent timing attacks
        Self::constant_time_compare(&stored_key, &self.stored_key)
    }

    /// Async version of `new` — runs PBKDF2 (600k iterations) in a blocking
    /// thread pool so the tokio runtime is not blocked.
    pub async fn new_async(password: &str) -> Self {
        let password = password.to_string();
        tokio::task::spawn_blocking(move || Self::new(&password))
            .await
            .expect("PasswordHash::new_async: spawn_blocking panicked")
    }

    /// Async version of `verify` — runs PBKDF2 (600k iterations) in a blocking
    /// thread pool so the tokio runtime is not blocked.
    pub async fn verify_async(&self, password: &str) -> bool {
        let hash = self.clone();
        let password = password.to_string();
        tokio::task::spawn_blocking(move || hash.verify(&password))
            .await
            .expect("PasswordHash::verify_async: spawn_blocking panicked")
    }

    /// Constant-time comparison to prevent timing attacks
    pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
        if a.len() != b.len() {
            return false;
        }

        // XOR all bytes and accumulate - timing is constant regardless of where mismatch occurs
        let mut result = 0u8;
        for (x, y) in a.iter().zip(b.iter()) {
            result |= x ^ y;
        }
        result == 0
    }

    /// PBKDF2-HMAC-SHA256 key derivation
    fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32) -> Vec<u8> {
        use hmac::{Hmac, Mac};
        type HmacSha256 = Hmac<Sha256>;

        let mut result = vec![0u8; 32];

        // U1 = PRF(Password, Salt || INT(1))
        let mut mac = HmacSha256::new_from_slice(password).expect("HMAC accepts any key length");
        mac.update(salt);
        mac.update(&1u32.to_be_bytes());
        let mut u = mac.finalize().into_bytes();
        result.copy_from_slice(&u);

        // Ui = PRF(Password, Ui-1)
        for _ in 1..iterations {
            let mut mac =
                HmacSha256::new_from_slice(password).expect("HMAC accepts any key length");
            mac.update(&u);
            u = mac.finalize().into_bytes();

            for (r, ui) in result.iter_mut().zip(u.iter()) {
                *r ^= ui;
            }
        }

        result
    }

    /// HMAC-SHA256
    pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
        use hmac::{Hmac, Mac};
        type HmacSha256 = Hmac<Sha256>;

        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
        mac.update(data);
        mac.finalize().into_bytes().to_vec()
    }
}

// ============================================================================
// Roles
// ============================================================================

/// A role with a set of permissions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    /// Role name
    pub name: String,

    /// Description
    pub description: String,

    /// Permissions granted by this role
    pub permissions: HashSet<(ResourceType, Permission)>,

    /// Whether this is a built-in role
    pub builtin: bool,
}

impl Role {
    /// Create a built-in admin role
    pub fn admin() -> Self {
        let mut permissions = HashSet::new();
        permissions.insert((ResourceType::Cluster, Permission::All));

        Role {
            name: "admin".to_string(),
            description: "Full administrative access to all resources".to_string(),
            permissions,
            builtin: true,
        }
    }

    /// Create a built-in producer role
    pub fn producer() -> Self {
        let mut permissions = HashSet::new();
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Write,
        ));
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Describe,
        ));
        permissions.insert((ResourceType::Cluster, Permission::IdempotentWrite));

        Role {
            name: "producer".to_string(),
            description: "Can produce to all topics".to_string(),
            permissions,
            builtin: true,
        }
    }

    /// Create a built-in consumer role
    pub fn consumer() -> Self {
        let mut permissions = HashSet::new();
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Read,
        ));
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Describe,
        ));
        permissions.insert((
            ResourceType::ConsumerGroup("*".to_string()),
            Permission::GroupRead,
        ));

        Role {
            name: "consumer".to_string(),
            description: "Can consume from all topics".to_string(),
            permissions,
            builtin: true,
        }
    }

    /// Create a built-in read-only role
    pub fn read_only() -> Self {
        let mut permissions = HashSet::new();
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Read,
        ));
        permissions.insert((
            ResourceType::TopicPattern("*".to_string()),
            Permission::Describe,
        ));

        Role {
            name: "read-only".to_string(),
            description: "Read-only access to all topics".to_string(),
            permissions,
            builtin: true,
        }
    }
}

// ============================================================================
// Access Control List (ACL)
// ============================================================================

/// An ACL entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AclEntry {
    /// Principal this ACL applies to (use "*" for all)
    pub principal: String,

    /// Resource this ACL applies to
    pub resource: ResourceType,

    /// Permission granted or denied
    pub permission: Permission,

    /// Whether this is an allow or deny rule
    pub allow: bool,

    /// Host pattern (IP or hostname, "*" for all)
    pub host: String,
}

/// Indexed ACL store for O(1) average-case lookups.
///
/// ACL entries are indexed by principal name. Wildcard (`*`) entries are
/// stored separately and consulted on every lookup to preserve deny-takes-
/// precedence semantics. For N total ACLs but only W wildcard rules, a
/// lookup scans at most `entries_for_principal + W` entries instead of N.
#[derive(Debug, Default)]
struct AclIndex {
    /// ACLs keyed by exact principal name.
    by_principal: HashMap<String, Vec<AclEntry>>,
    /// Wildcard ACLs (principal == "*"). Checked on every lookup.
    wildcard: Vec<AclEntry>,
}

impl AclIndex {
    fn new() -> Self {
        Self::default()
    }

    fn push(&mut self, entry: AclEntry) {
        if entry.principal == "*" {
            self.wildcard.push(entry);
        } else {
            self.by_principal
                .entry(entry.principal.clone())
                .or_default()
                .push(entry);
        }
    }

    fn retain<F: Fn(&AclEntry) -> bool>(&mut self, predicate: F) {
        self.wildcard.retain(&predicate);
        self.by_principal.retain(|_, entries| {
            entries.retain(&predicate);
            !entries.is_empty()
        });
    }

    /// Return all entries that could apply to the given principal.
    fn lookup(&self, principal: &str) -> impl Iterator<Item = &AclEntry> {
        let specific = self
            .by_principal
            .get(principal)
            .map(|v| v.as_slice())
            .unwrap_or(&[]);
        specific.iter().chain(self.wildcard.iter())
    }

    fn to_vec(&self) -> Vec<AclEntry> {
        self.wildcard
            .iter()
            .chain(self.by_principal.values().flatten())
            .cloned()
            .collect()
    }
}

// ============================================================================
// Session and Token
// ============================================================================

// ============================================================================
// Unified Session Trait
// ============================================================================

/// Unified session trait for all authentication mechanisms.
///
/// Provides a common interface for session handling across:
/// - `AuthSession` (RBAC/ACL with SASL authentication)
/// - `ServiceSession` (API keys, mTLS, OIDC client credentials)
///
/// This enables handler code to work with any authenticated session
/// without knowing the specific authentication mechanism.
pub trait Session: Send + Sync + std::fmt::Debug {
    /// Unique session identifier
    fn session_id(&self) -> &str;

    /// The authenticated principal/identity name
    fn principal(&self) -> &str;

    /// Whether this session has expired
    fn is_expired(&self) -> bool;

    /// Client IP address that created this session
    fn client_ip(&self) -> &str;
}

// ============================================================================
// Auth Session
// ============================================================================

/// An authenticated session
#[derive(Debug, Clone)]
pub struct AuthSession {
    /// Session ID
    pub id: String,

    /// Authenticated principal name
    pub principal_name: String,

    /// Principal type
    pub principal_type: PrincipalType,

    /// Resolved permissions (cached for performance)
    pub permissions: HashSet<(ResourceType, Permission)>,

    /// Session creation time
    pub created_at: Instant,

    /// Session expiration time
    pub expires_at: Instant,

    /// Client IP address
    pub client_ip: String,
}

impl Session for AuthSession {
    fn session_id(&self) -> &str {
        &self.id
    }

    fn principal(&self) -> &str {
        &self.principal_name
    }

    fn is_expired(&self) -> bool {
        Instant::now() >= self.expires_at
    }

    fn client_ip(&self) -> &str {
        &self.client_ip
    }
}

impl AuthSession {
    /// Check if the session has expired
    pub fn is_expired(&self) -> bool {
        <Self as Session>::is_expired(self)
    }

    /// Check if this session has a specific permission on a resource
    pub fn has_permission(&self, resource: &ResourceType, permission: &Permission) -> bool {
        // Admin has all permissions
        if self
            .permissions
            .contains(&(ResourceType::Cluster, Permission::All))
        {
            return true;
        }

        // Check direct permission
        if self.permissions.contains(&(resource.clone(), *permission)) {
            return true;
        }

        // Check pattern matches and permission implies
        for (res, perm) in &self.permissions {
            // Check if the granted resource (res) matches the requested resource
            // AND the granted permission (perm) implies the requested permission
            let resource_matches = res.matches(resource);
            let permission_implies = perm.implies(permission);
            if resource_matches && permission_implies {
                return true;
            }
        }

        false
    }
}

// ============================================================================
// Auth Manager
// ============================================================================

/// Configuration for the authentication manager
#[derive(Debug, Clone)]
pub struct AuthConfig {
    /// Session timeout
    pub session_timeout: Duration,

    /// Maximum failed auth attempts before lockout
    pub max_failed_attempts: u32,

    /// Lockout duration after max failed attempts
    pub lockout_duration: Duration,

    /// Whether to require authentication (false = anonymous access allowed)
    pub require_authentication: bool,

    /// Whether to enable ACL enforcement
    pub enable_acls: bool,

    /// Default deny (true = deny unless explicitly allowed)
    pub default_deny: bool,
}

impl Default for AuthConfig {
    fn default() -> Self {
        // Authentication is enabled by default for security.
        // Disable explicitly in development/testing via AuthConfig { require_authentication: false, .. }.
        #[cfg(not(test))]
        tracing::info!("AuthConfig::default() — authentication and ACLs ENABLED by default.");

        AuthConfig {
            session_timeout: Duration::from_secs(3600), // 1 hour
            max_failed_attempts: 5,
            lockout_duration: Duration::from_secs(300), // 5 minutes
            require_authentication: true,               // Secure by default
            enable_acls: true,                          // ACLs on by default
            default_deny: true,
        }
    }
}

/// Tracks failed authentication attempts for rate limiting
struct FailedAttemptTracker {
    attempts: HashMap<String, Vec<Instant>>,
    lockouts: HashMap<String, Instant>,
}

/// Maximum number of tracked IP/principal entries to prevent
/// unbounded memory growth from distributed brute-force attacks.
const MAX_TRACKED_IDENTIFIERS: usize = 10_000;

impl FailedAttemptTracker {
    fn new() -> Self {
        Self {
            attempts: HashMap::new(),
            lockouts: HashMap::new(),
        }
    }

    /// Check if an identifier is currently locked out
    fn is_locked_out(&self, identifier: &str, lockout_duration: Duration) -> bool {
        if let Some(lockout_time) = self.lockouts.get(identifier) {
            if lockout_time.elapsed() < lockout_duration {
                return true;
            }
        }
        false
    }

    /// Record a failed attempt
    fn record_failure(
        &mut self,
        identifier: &str,
        max_attempts: u32,
        lockout_duration: Duration,
    ) -> bool {
        let now = Instant::now();

        // Clean up old lockouts
        self.lockouts.retain(|_, t| t.elapsed() < lockout_duration);

        // enforce hard cap on tracked identifiers.
        // When the limit is reached, evict the oldest entries (by last
        // attempt time) to make room. This bounds memory usage under
        // distributed brute-force attacks targeting many IPs.
        if self.attempts.len() >= MAX_TRACKED_IDENTIFIERS && !self.attempts.contains_key(identifier)
        {
            // Evict entries with no recent attempts first
            self.attempts.retain(|_, v| !v.is_empty());

            // If still over limit, evict the oldest entries
            if self.attempts.len() >= MAX_TRACKED_IDENTIFIERS {
                let mut entries: Vec<(String, Instant)> = self
                    .attempts
                    .iter()
                    .filter_map(|(k, v)| v.last().map(|t| (k.clone(), *t)))
                    .collect();
                entries.sort_by_key(|(_, t)| *t);
                // Remove oldest 10% to amortize eviction cost
                let to_remove = entries.len() / 10;
                for (key, _) in entries.into_iter().take(to_remove.max(1)) {
                    self.attempts.remove(&key);
                    self.lockouts.remove(&key);
                }
            }
        }

        // Get or create attempt list
        let attempts = self.attempts.entry(identifier.to_string()).or_default();

        // Remove attempts older than lockout duration
        attempts.retain(|t| t.elapsed() < lockout_duration);

        // Add this attempt
        attempts.push(now);

        // Check if we've exceeded max attempts
        let exceeded = attempts.len() >= max_attempts as usize;
        if exceeded {
            warn!(
                "Principal '{}' locked out after {} failed attempts",
                identifier, max_attempts
            );
            self.lockouts.insert(identifier.to_string(), now);
        }

        // Periodic cleanup: remove entries with no recent attempts to bound memory
        if self.attempts.len() > 10_000 {
            self.attempts.retain(|_, v| !v.is_empty());
        }

        exceeded
    }

    /// Clear failures for an identifier (on successful auth)
    fn clear_failures(&mut self, identifier: &str) {
        self.attempts.remove(identifier);
        self.lockouts.remove(identifier);
    }
}

/// Validate password strength with complexity requirements
fn validate_password_strength(password: &str) -> AuthResult<()> {
    if password.len() < 8 {
        return Err(AuthError::Internal(
            "Password must be at least 8 characters".to_string(),
        ));
    }

    let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
    let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());

    if !has_uppercase {
        return Err(AuthError::Internal(
            "Password must contain at least one uppercase letter".to_string(),
        ));
    }
    if !has_lowercase {
        return Err(AuthError::Internal(
            "Password must contain at least one lowercase letter".to_string(),
        ));
    }
    if !has_digit {
        return Err(AuthError::Internal(
            "Password must contain at least one digit".to_string(),
        ));
    }
    if !has_special {
        return Err(AuthError::Internal(
            "Password must contain at least one special character".to_string(),
        ));
    }

    Ok(())
}

/// The main authentication and authorization manager
pub struct AuthManager {
    config: AuthConfig,

    /// Principals (users/service accounts)
    /// `parking_lot` — O(1) principal lookup, never held across `.await`.
    principals: RwLock<HashMap<String, Principal>>,

    /// Roles
    roles: RwLock<HashMap<String, Role>>,

    /// ACL entries (indexed by principal for fast lookup)
    acls: RwLock<AclIndex>,

    /// Active sessions
    sessions: RwLock<HashMap<String, AuthSession>>,

    /// Failed attempt tracking
    failed_attempts: RwLock<FailedAttemptTracker>,

    /// Random number generator for session IDs
    rng: SystemRandom,
}

impl AuthManager {
    /// Create a new authentication manager
    pub fn new(config: AuthConfig) -> Self {
        let manager = Self {
            config,
            principals: RwLock::new(HashMap::new()),
            roles: RwLock::new(HashMap::new()),
            acls: RwLock::new(AclIndex::new()),
            sessions: RwLock::new(HashMap::new()),
            failed_attempts: RwLock::new(FailedAttemptTracker::new()),
            rng: SystemRandom::new(),
        };

        // Initialize built-in roles
        manager.init_builtin_roles();

        manager
    }

    /// Create with default config
    pub fn new_default() -> Self {
        Self::new(AuthConfig::default())
    }

    /// Create an auth manager with authentication enabled
    pub fn with_auth_enabled() -> Self {
        Self::new(AuthConfig {
            require_authentication: true,
            enable_acls: true,
            ..Default::default()
        })
    }

    /// Initialize built-in roles
    fn init_builtin_roles(&self) {
        let mut roles = self.roles.write();
        roles.insert("admin".to_string(), Role::admin());
        roles.insert("producer".to_string(), Role::producer());
        roles.insert("consumer".to_string(), Role::consumer());
        roles.insert("read-only".to_string(), Role::read_only());
    }

    // ========================================================================
    // Principal Management
    // ========================================================================

    /// Create a new principal (user or service account)
    ///
    /// Note: `PasswordHash::new()` runs 600K PBKDF2 iterations (~100-500ms).
    /// Callers on async contexts should use `create_principal_async()` instead to
    /// avoid blocking the tokio runtime.
    pub fn create_principal(
        &self,
        name: &str,
        password: &str,
        principal_type: PrincipalType,
        roles: HashSet<String>,
    ) -> AuthResult<()> {
        // Validate principal name
        if name.is_empty() || name.len() > 255 {
            return Err(AuthError::Internal("Invalid principal name".to_string()));
        }

        // Validate password strength (minimum requirements + complexity)
        validate_password_strength(password)?;

        // Validate roles exist
        {
            let role_map = self.roles.read();
            for role in &roles {
                if !role_map.contains_key(role) {
                    return Err(AuthError::RoleNotFound(role.clone()));
                }
            }
        }

        let mut principals = self.principals.write();

        if principals.contains_key(name) {
            return Err(AuthError::PrincipalAlreadyExists(name.to_string()));
        }

        let principal = Principal {
            name: name.to_string(),
            principal_type,
            password_hash: PasswordHash::new(password),
            roles,
            enabled: true,
            metadata: HashMap::new(),
            created_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        };

        principals.insert(name.to_string(), principal);
        debug!("Created principal: {}", name);

        Ok(())
    }

    /// Delete a principal
    pub fn delete_principal(&self, name: &str) -> AuthResult<()> {
        let mut principals = self.principals.write();

        if principals.remove(name).is_none() {
            return Err(AuthError::PrincipalNotFound(name.to_string()));
        }

        // Also invalidate any active sessions for this principal
        let mut sessions = self.sessions.write();
        sessions.retain(|_, s| s.principal_name != name);

        debug!("Deleted principal: {}", name);
        Ok(())
    }

    /// Get a principal by name
    pub fn get_principal(&self, name: &str) -> Option<Principal> {
        self.principals.read().get(name).cloned()
    }

    /// List all principals
    pub fn list_principals(&self) -> Vec<String> {
        self.principals.read().keys().cloned().collect()
    }

    /// Update principal password
    ///
    /// Note: `PasswordHash::new()` runs 600K PBKDF2 iterations.
    /// Callers on async contexts should use `update_password_async()` instead.
    pub fn update_password(&self, name: &str, new_password: &str) -> AuthResult<()> {
        // Validate password strength (minimum requirements + complexity)
        validate_password_strength(new_password)?;

        let mut principals = self.principals.write();

        let principal = principals
            .get_mut(name)
            .ok_or_else(|| AuthError::PrincipalNotFound(name.to_string()))?;

        principal.password_hash = PasswordHash::new(new_password);

        // Invalidate sessions
        let mut sessions = self.sessions.write();
        sessions.retain(|_, s| s.principal_name != name);

        debug!("Updated password for principal: {}", name);
        Ok(())
    }

    /// Async variant of `create_principal` that runs PBKDF2 hashing
    /// in a blocking thread pool to avoid blocking the tokio runtime.
    pub async fn create_principal_async(
        &self,
        name: &str,
        password: &str,
        principal_type: PrincipalType,
        roles: HashSet<String>,
    ) -> AuthResult<()> {
        // Validate inputs before spawning blocking work
        if name.is_empty() || name.len() > 255 {
            return Err(AuthError::Internal("Invalid principal name".to_string()));
        }
        validate_password_strength(password)?;
        {
            let role_map = self.roles.read();
            for role in &roles {
                if !role_map.contains_key(role) {
                    return Err(AuthError::RoleNotFound(role.clone()));
                }
            }
        }
        if self.principals.read().contains_key(name) {
            return Err(AuthError::PrincipalAlreadyExists(name.to_string()));
        }

        // Run expensive PBKDF2 off the tokio thread
        let password_hash = PasswordHash::new_async(password).await;

        let mut principals = self.principals.write();
        // Re-check after async gap
        if principals.contains_key(name) {
            return Err(AuthError::PrincipalAlreadyExists(name.to_string()));
        }

        let principal = Principal {
            name: name.to_string(),
            principal_type,
            password_hash,
            roles,
            enabled: true,
            metadata: HashMap::new(),
            created_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        };

        principals.insert(name.to_string(), principal);
        debug!("Created principal: {}", name);
        Ok(())
    }

    /// Async variant of `update_password` that runs PBKDF2 hashing
    /// in a blocking thread pool to avoid blocking the tokio runtime.
    pub async fn update_password_async(&self, name: &str, new_password: &str) -> AuthResult<()> {
        validate_password_strength(new_password)?;

        // Verify principal exists before expensive hash
        if !self.principals.read().contains_key(name) {
            return Err(AuthError::PrincipalNotFound(name.to_string()));
        }

        // Run expensive PBKDF2 off the tokio thread
        let password_hash = PasswordHash::new_async(new_password).await;

        let mut principals = self.principals.write();
        let principal = principals
            .get_mut(name)
            .ok_or_else(|| AuthError::PrincipalNotFound(name.to_string()))?;

        principal.password_hash = password_hash;

        let mut sessions = self.sessions.write();
        sessions.retain(|_, s| s.principal_name != name);

        debug!("Updated password for principal: {}", name);
        Ok(())
    }

    /// Add a role to a principal
    pub fn add_role_to_principal(&self, principal_name: &str, role_name: &str) -> AuthResult<()> {
        // Validate role exists
        if !self.roles.read().contains_key(role_name) {
            return Err(AuthError::RoleNotFound(role_name.to_string()));
        }

        let mut principals = self.principals.write();

        let principal = principals
            .get_mut(principal_name)
            .ok_or_else(|| AuthError::PrincipalNotFound(principal_name.to_string()))?;

        principal.roles.insert(role_name.to_string());

        debug!(
            "Added role '{}' to principal '{}'",
            role_name, principal_name
        );
        Ok(())
    }

    /// Remove a role from a principal
    pub fn remove_role_from_principal(
        &self,
        principal_name: &str,
        role_name: &str,
    ) -> AuthResult<()> {
        let mut principals = self.principals.write();

        let principal = principals
            .get_mut(principal_name)
            .ok_or_else(|| AuthError::PrincipalNotFound(principal_name.to_string()))?;

        principal.roles.remove(role_name);

        debug!(
            "Removed role '{}' from principal '{}'",
            role_name, principal_name
        );
        Ok(())
    }

    // ========================================================================
    // Role Management
    // ========================================================================

    /// Create a custom role
    pub fn create_role(&self, role: Role) -> AuthResult<()> {
        let mut roles = self.roles.write();

        if roles.contains_key(&role.name) {
            return Err(AuthError::Internal(format!(
                "Role '{}' already exists",
                role.name
            )));
        }

        debug!("Created role: {}", role.name);
        roles.insert(role.name.clone(), role);
        Ok(())
    }

    /// Delete a custom role
    pub fn delete_role(&self, name: &str) -> AuthResult<()> {
        let mut roles = self.roles.write();

        if let Some(role) = roles.get(name) {
            if role.builtin {
                return Err(AuthError::Internal(
                    "Cannot delete built-in role".to_string(),
                ));
            }
        } else {
            return Err(AuthError::RoleNotFound(name.to_string()));
        }

        roles.remove(name);
        debug!("Deleted role: {}", name);
        Ok(())
    }

    /// Get a role by name
    pub fn get_role(&self, name: &str) -> Option<Role> {
        self.roles.read().get(name).cloned()
    }

    /// List all roles
    pub fn list_roles(&self) -> Vec<String> {
        self.roles.read().keys().cloned().collect()
    }

    // ========================================================================
    // ACL Management
    // ========================================================================

    /// Add an ACL entry
    pub fn add_acl(&self, entry: AclEntry) {
        let mut acls = self.acls.write();
        acls.push(entry);
    }

    /// Remove ACL entries matching criteria
    pub fn remove_acls(&self, principal: Option<&str>, resource: Option<&ResourceType>) {
        let mut acls = self.acls.write();
        acls.retain(|acl| {
            let principal_match =
                principal.is_none_or(|p| acl.principal == p || acl.principal == "*");
            let resource_match = resource.is_none_or(|r| &acl.resource == r);
            !(principal_match && resource_match)
        });
    }

    /// List ACL entries
    pub fn list_acls(&self) -> Vec<AclEntry> {
        self.acls.read().to_vec()
    }

    // ========================================================================
    // Authentication
    // ========================================================================

    /// Authenticate a principal and create a session
    pub fn authenticate(
        &self,
        username: &str,
        password: &str,
        client_ip: &str,
    ) -> AuthResult<AuthSession> {
        // Check rate limiting
        {
            let tracker = self.failed_attempts.read();
            if tracker.is_locked_out(username, self.config.lockout_duration) {
                warn!(
                    "Authentication attempt for locked-out principal: {}",
                    username
                );
                return Err(AuthError::RateLimited);
            }
            if tracker.is_locked_out(client_ip, self.config.lockout_duration) {
                warn!("Authentication attempt from locked-out IP: {}", client_ip);
                return Err(AuthError::RateLimited);
            }
        }

        // Look up principal
        let principal = {
            let principals = self.principals.read();
            principals.get(username).cloned()
        };

        let principal = match principal {
            Some(p) if p.enabled => p,
            Some(_) => {
                // Disabled account - don't leak this info
                self.record_auth_failure(username, client_ip);
                return Err(AuthError::AuthenticationFailed);
            }
            None => {
                // Unknown principal - still do constant-time password check
                // to prevent timing attacks that enumerate users
                let dummy = PasswordHash::new("dummy");
                let _ = dummy.verify(password);
                self.record_auth_failure(username, client_ip);
                return Err(AuthError::AuthenticationFailed);
            }
        };

        // Verify password (constant-time comparison)
        if !principal.password_hash.verify(password) {
            self.record_auth_failure(username, client_ip);
            return Err(AuthError::AuthenticationFailed);
        }

        // Clear any failed attempt tracking
        self.failed_attempts.write().clear_failures(username);
        self.failed_attempts.write().clear_failures(client_ip);

        // Build session with resolved permissions
        let permissions = self.resolve_permissions(&principal);

        // Generate session ID
        let mut session_id = vec![0u8; 32];
        self.rng
            .fill(&mut session_id)
            .map_err(|_| AuthError::Internal("RNG failed".to_string()))?;
        let session_id = hex::encode(&session_id);

        let now = Instant::now();
        let session = AuthSession {
            id: session_id.clone(),
            principal_name: principal.name.clone(),
            principal_type: principal.principal_type.clone(),
            permissions,
            created_at: now,
            expires_at: now + self.config.session_timeout,
            client_ip: client_ip.to_string(),
        };

        // Store session
        self.sessions.write().insert(session_id, session.clone());

        debug!("Authenticated principal '{}' from {}", username, client_ip);
        Ok(session)
    }

    /// Record a failed authentication attempt
    fn record_auth_failure(&self, username: &str, client_ip: &str) {
        let mut tracker = self.failed_attempts.write();
        tracker.record_failure(
            username,
            self.config.max_failed_attempts,
            self.config.lockout_duration,
        );
        tracker.record_failure(
            client_ip,
            self.config.max_failed_attempts * 2,
            self.config.lockout_duration,
        );
    }

    /// Get an active session by ID
    pub fn get_session(&self, session_id: &str) -> Option<AuthSession> {
        let sessions = self.sessions.read();
        sessions.get(session_id).and_then(|s| {
            if s.is_expired() {
                None
            } else {
                Some(s.clone())
            }
        })
    }

    /// Invalidate a session (logout)
    pub fn invalidate_session(&self, session_id: &str) {
        self.sessions.write().remove(session_id);
    }

    /// Invalidate all sessions for a principal
    pub fn invalidate_all_sessions(&self, principal_name: &str) {
        self.sessions
            .write()
            .retain(|_, s| s.principal_name != principal_name);
    }

    /// Clean up expired sessions
    pub fn cleanup_expired_sessions(&self) {
        self.sessions.write().retain(|_, s| !s.is_expired());
    }

    /// Create a session for a principal (used by SCRAM after successful auth)
    pub fn create_session(&self, principal: &Principal) -> AuthSession {
        let permissions = self.resolve_permissions(principal);

        let mut session_id = vec![0u8; 32];
        self.rng.fill(&mut session_id).expect("RNG failed");
        let session_id = hex::encode(&session_id);

        let now = Instant::now();
        let session = AuthSession {
            id: session_id.clone(),
            principal_name: principal.name.clone(),
            principal_type: principal.principal_type.clone(),
            permissions,
            created_at: now,
            expires_at: now + self.config.session_timeout,
            client_ip: "scram".to_string(),
        };

        self.sessions.write().insert(session_id, session.clone());
        session
    }

    /// Create a session for an API key authentication
    ///
    /// Creates a synthetic session for API key-based authentication.
    /// The session inherits permissions from the specified roles.
    pub fn create_api_key_session(&self, principal_name: &str, roles: &[String]) -> AuthSession {
        // Resolve permissions from roles
        let mut permissions = HashSet::new();
        {
            let roles_map = self.roles.read();
            for role_name in roles {
                if let Some(role) = roles_map.get(role_name) {
                    permissions.extend(role.permissions.iter().cloned());
                }
            }
        }

        let mut session_id = vec![0u8; 32];
        self.rng.fill(&mut session_id).expect("RNG failed");
        let session_id = hex::encode(&session_id);

        let now = Instant::now();
        let session = AuthSession {
            id: session_id.clone(),
            principal_name: principal_name.to_string(),
            principal_type: PrincipalType::ServiceAccount,
            permissions,
            created_at: now,
            expires_at: now + self.config.session_timeout,
            client_ip: "api-key".to_string(),
        };

        self.sessions.write().insert(session_id, session.clone());
        debug!(principal = %principal_name, "Created API key session");
        session
    }

    /// Create a session for JWT/OIDC authentication
    ///
    /// Creates a synthetic session for JWT-authenticated users.
    /// The session inherits permissions from the specified groups/roles.
    pub fn create_jwt_session(&self, principal_name: &str, groups: &[String]) -> AuthSession {
        // Resolve permissions from groups (treated as roles)
        let mut permissions = HashSet::new();
        {
            let roles_map = self.roles.read();
            for group in groups {
                if let Some(role) = roles_map.get(group) {
                    permissions.extend(role.permissions.iter().cloned());
                }
            }
        }

        let mut session_id = vec![0u8; 32];
        self.rng.fill(&mut session_id).expect("RNG failed");
        let session_id = hex::encode(&session_id);

        let now = Instant::now();
        let session = AuthSession {
            id: session_id.clone(),
            principal_name: principal_name.to_string(),
            principal_type: PrincipalType::User,
            permissions,
            created_at: now,
            expires_at: now + self.config.session_timeout,
            client_ip: "jwt".to_string(),
        };

        self.sessions.write().insert(session_id, session.clone());
        debug!(principal = %principal_name, groups = ?groups, "Created JWT session");
        session
    }

    /// Get a session by principal name (for API key validation)
    pub fn get_session_by_principal(&self, principal_name: &str) -> Option<AuthSession> {
        let sessions = self.sessions.read();
        sessions
            .values()
            .find(|s| s.principal_name == principal_name && !s.is_expired())
            .cloned()
    }

    // ========================================================================
    // Authorization
    // ========================================================================

    /// Resolve all permissions for a principal
    fn resolve_permissions(&self, principal: &Principal) -> HashSet<(ResourceType, Permission)> {
        let mut permissions = HashSet::new();

        let roles = self.roles.read();

        // Collect permissions from all roles
        for role_name in &principal.roles {
            if let Some(role) = roles.get(role_name) {
                permissions.extend(role.permissions.iter().cloned());
            }
        }

        permissions
    }

    /// Check if a session/principal has permission on a resource
    pub fn authorize(
        &self,
        session: &AuthSession,
        resource: &ResourceType,
        permission: Permission,
        client_ip: &str,
    ) -> AuthResult<()> {
        // If auth is not required and no ACLs, allow everything
        if !self.config.require_authentication && !self.config.enable_acls {
            return Ok(());
        }

        // Check session expiration
        if session.is_expired() {
            return Err(AuthError::TokenExpired);
        }

        // Check role-based permissions
        if session.has_permission(resource, &permission) {
            return Ok(());
        }

        // Check ACL entries
        if self.config.enable_acls
            && self.check_acls(&session.principal_name, resource, permission, client_ip)
        {
            return Ok(());
        }

        // Default deny
        if self.config.default_deny {
            warn!(
                "Access denied: {} attempted {} on {:?} from {}",
                session.principal_name,
                format!("{:?}", permission),
                resource,
                client_ip
            );
            return Err(AuthError::PermissionDenied {
                principal: session.principal_name.clone(),
                permission: format!("{:?}", permission),
                resource: format!("{:?}", resource),
            });
        }

        Ok(())
    }

    /// Check ACL entries for authorization (indexed lookup — O(W + P) instead of O(N))
    fn check_acls(
        &self,
        principal: &str,
        resource: &ResourceType,
        permission: Permission,
        client_ip: &str,
    ) -> bool {
        let acls = self.acls.read();

        // Only iterate entries for this principal + wildcard entries
        // Check deny rules first (deny takes precedence)
        for acl in acls.lookup(principal) {
            if !acl.allow
                && (acl.host == client_ip || acl.host == "*")
                && acl.resource.matches(resource)
                && (acl.permission == permission || acl.permission == Permission::All)
            {
                return false; // Explicit deny
            }
        }

        // Check allow rules
        for acl in acls.lookup(principal) {
            if acl.allow
                && (acl.host == client_ip || acl.host == "*")
                && acl.resource.matches(resource)
                && (acl.permission == permission || acl.permission == Permission::All)
            {
                return true;
            }
        }

        false
    }

    /// Simple authorization check without session (for internal use)
    #[allow(unused_variables)]
    pub fn authorize_anonymous(
        &self,
        resource: &ResourceType,
        permission: Permission,
    ) -> AuthResult<()> {
        if !self.config.require_authentication {
            return Ok(());
        }

        Err(AuthError::AuthenticationFailed)
    }
}

// ============================================================================
// SASL/PLAIN Support (Kafka-compatible)
// ============================================================================

/// SASL/PLAIN authentication handler
pub struct SaslPlainAuth {
    auth_manager: Arc<AuthManager>,
}

impl SaslPlainAuth {
    pub fn new(auth_manager: Arc<AuthManager>) -> Self {
        Self { auth_manager }
    }

    /// Parse and authenticate a SASL/PLAIN request
    /// Format: \[authzid\] NUL authcid NUL passwd
    pub fn authenticate(&self, sasl_bytes: &[u8], client_ip: &str) -> AuthResult<AuthSession> {
        // Parse SASL/PLAIN format: [authzid] \0 authcid \0 password
        let parts: Vec<&[u8]> = sasl_bytes.split(|&b| b == 0).collect();

        if parts.len() < 2 {
            return Err(AuthError::InvalidCredentials);
        }

        // Handle both 2-part (authcid, passwd) and 3-part (authzid, authcid, passwd)
        let (username, password) = if parts.len() == 2 {
            (
                std::str::from_utf8(parts[0]).map_err(|_| AuthError::InvalidCredentials)?,
                std::str::from_utf8(parts[1]).map_err(|_| AuthError::InvalidCredentials)?,
            )
        } else {
            // 3-part format - authzid is ignored, use authcid
            (
                std::str::from_utf8(parts[1]).map_err(|_| AuthError::InvalidCredentials)?,
                std::str::from_utf8(parts[2]).map_err(|_| AuthError::InvalidCredentials)?,
            )
        };

        self.auth_manager
            .authenticate(username, password, client_ip)
    }
}

// ============================================================================
// SCRAM-SHA-256 Support (RFC 5802 / RFC 7677)
// ============================================================================

/// SCRAM-SHA-256 authentication state machine
///
/// Implements the full SCRAM protocol for secure password-based authentication.
/// This is significantly more secure than PLAIN because:
/// 1. The password is never sent over the wire (even encrypted)
/// 2. The server stores derived keys, not the password
/// 3. Mutual authentication (server proves it knows the password too)
/// 4. Protection against replay attacks via nonces
#[derive(Debug, Clone)]
pub enum ScramState {
    /// Waiting for client-first-message
    Initial,
    /// Waiting for client-final-message
    ServerFirstSent {
        username: String,
        client_nonce: String,
        server_nonce: String,
        salt: Vec<u8>,
        iterations: u32,
        auth_message: String,
    },
    /// Authentication complete (success or failure pending verification)
    Complete,
}

/// SCRAM-SHA-256 authentication handler
pub struct SaslScramAuth {
    auth_manager: Arc<AuthManager>,
}

impl SaslScramAuth {
    pub fn new(auth_manager: Arc<AuthManager>) -> Self {
        Self { auth_manager }
    }

    /// Process client-first-message and return server-first-message
    ///
    /// Client-first-message format: `n,,n=<username>,r=<client-nonce>`
    /// Server-first-message format: `r=<combined-nonce>,s=<salt>,i=<iterations>`
    pub fn process_client_first(
        &self,
        client_first: &[u8],
        client_ip: &str,
    ) -> AuthResult<(ScramState, Vec<u8>)> {
        let client_first_str =
            std::str::from_utf8(client_first).map_err(|_| AuthError::InvalidCredentials)?;

        // Parse client-first-message
        // Format: gs2-header,client-first-message-bare
        // gs2-header: n,, (no channel binding)
        // client-first-message-bare: n=<user>,r=<nonce>

        let parts: Vec<&str> = client_first_str.splitn(3, ',').collect();
        if parts.len() < 3 {
            return Err(AuthError::InvalidCredentials);
        }

        // Skip gs2-header (parts[0] and parts[1])
        let client_first_bare = if parts[0] == "n" || parts[0] == "y" || parts[0] == "p" {
            // gs2-header present, skip first two parts
            &client_first_str[parts[0].len() + 1 + parts[1].len() + 1..]
        } else {
            // No gs2-header, message is just client-first-message-bare
            client_first_str
        };

        // Parse client-first-message-bare
        let mut username = None;
        let mut client_nonce = None;

        for attr in client_first_bare.split(',') {
            if let Some(value) = attr.strip_prefix("n=") {
                username = Some(Self::unescape_username(value));
            } else if let Some(value) = attr.strip_prefix("r=") {
                client_nonce = Some(value.to_string());
            }
        }

        let username = username.ok_or(AuthError::InvalidCredentials)?;
        let client_nonce = client_nonce.ok_or(AuthError::InvalidCredentials)?;

        // Look up principal to get salt and iterations
        let (salt, iterations) = match self.auth_manager.get_principal(&username) {
            Some(principal) => (
                principal.password_hash.salt.clone(),
                principal.password_hash.iterations,
            ),
            None => {
                // User not found - generate fake salt to prevent enumeration
                // Still continue with the protocol to not leak timing info
                warn!(
                    "SCRAM auth for unknown user '{}' from {}",
                    username, client_ip
                );
                let rng = SystemRandom::new();
                let mut fake_salt = vec![0u8; 32];
                rng.fill(&mut fake_salt).expect("Failed to generate salt");
                // Use the same iteration count as real users (600000)
                // to prevent leaking user existence via timing differences.
                (fake_salt, 600_000)
            }
        };

        // Generate server nonce (random bytes, base64 encoded)
        let rng = SystemRandom::new();
        let mut server_nonce_bytes = vec![0u8; 24];
        rng.fill(&mut server_nonce_bytes)
            .expect("Failed to generate nonce");
        let server_nonce = base64_encode(&server_nonce_bytes);
        let combined_nonce = format!("{}{}", client_nonce, server_nonce);

        // Build server-first-message
        let salt_b64 = base64_encode(&salt);
        let server_first = format!("r={},s={},i={}", combined_nonce, salt_b64, iterations);

        // Store auth message for later verification
        let auth_message = format!(
            "{},{},c=biws,r={}",
            client_first_bare, server_first, combined_nonce
        );

        let state = ScramState::ServerFirstSent {
            username,
            client_nonce,
            server_nonce,
            salt,
            iterations,
            auth_message,
        };

        Ok((state, server_first.into_bytes()))
    }

    /// Process client-final-message and return server-final-message
    ///
    /// Client-final-message format: `c=<channel-binding>,r=<nonce>,p=<proof>`
    /// Server-final-message format: `v=<verifier>` (on success) or `e=<error>`
    pub fn process_client_final(
        &self,
        state: &ScramState,
        client_final: &[u8],
        client_ip: &str,
    ) -> AuthResult<(AuthSession, Vec<u8>)> {
        let ScramState::ServerFirstSent {
            username,
            client_nonce,
            server_nonce,
            salt: _,       // Not needed for verification, stored in principal
            iterations: _, // Not needed for verification, stored in principal
            auth_message,
        } = state
        else {
            return Err(AuthError::Internal("Invalid SCRAM state".to_string()));
        };

        let client_final_str =
            std::str::from_utf8(client_final).map_err(|_| AuthError::InvalidCredentials)?;

        // Parse client-final-message
        let mut channel_binding = None;
        let mut nonce = None;
        let mut proof = None;

        for attr in client_final_str.split(',') {
            if let Some(value) = attr.strip_prefix("c=") {
                channel_binding = Some(value.to_string());
            } else if let Some(value) = attr.strip_prefix("r=") {
                nonce = Some(value.to_string());
            } else if let Some(value) = attr.strip_prefix("p=") {
                proof = Some(value.to_string());
            }
        }

        let _channel_binding = channel_binding.ok_or(AuthError::InvalidCredentials)?;
        let nonce = nonce.ok_or(AuthError::InvalidCredentials)?;
        let proof_b64 = proof.ok_or(AuthError::InvalidCredentials)?;

        // Verify nonce
        let expected_nonce = format!("{}{}", client_nonce, server_nonce);
        if nonce != expected_nonce {
            warn!("SCRAM nonce mismatch for '{}' from {}", username, client_ip);
            return Err(AuthError::InvalidCredentials);
        }

        // Get principal
        let principal = self
            .auth_manager
            .get_principal(username)
            .ok_or(AuthError::AuthenticationFailed)?;

        // Verify client proof
        // ClientProof = ClientKey XOR ClientSignature
        // ClientSignature = HMAC(StoredKey, AuthMessage)
        // We need to verify: H(ClientKey) == StoredKey

        let client_proof = base64_decode(&proof_b64).map_err(|_| AuthError::InvalidCredentials)?;

        // Compute expected client signature
        let client_signature =
            PasswordHash::hmac_sha256(&principal.password_hash.stored_key, auth_message.as_bytes());

        // Recover ClientKey = ClientProof XOR ClientSignature
        if client_proof.len() != client_signature.len() {
            return Err(AuthError::InvalidCredentials);
        }

        let client_key: Vec<u8> = client_proof
            .iter()
            .zip(client_signature.iter())
            .map(|(p, s)| p ^ s)
            .collect();

        // Verify: H(ClientKey) == StoredKey (constant-time comparison)
        let computed_stored_key = Sha256::digest(&client_key);
        if !PasswordHash::constant_time_compare(
            &computed_stored_key,
            &principal.password_hash.stored_key,
        ) {
            warn!(
                "SCRAM authentication failed for '{}' from {}",
                username, client_ip
            );
            return Err(AuthError::AuthenticationFailed);
        }

        // Compute server signature for mutual authentication
        let server_signature =
            PasswordHash::hmac_sha256(&principal.password_hash.server_key, auth_message.as_bytes());
        let server_final = format!("v={}", base64_encode(&server_signature));

        // Create session
        let session = self.auth_manager.create_session(&principal);
        debug!(
            "SCRAM authentication successful for '{}' from {}",
            username, client_ip
        );

        Ok((session, server_final.into_bytes()))
    }

    /// Unescape SCRAM username (=2C -> , and =3D -> =)
    fn unescape_username(s: &str) -> String {
        s.replace("=2C", ",").replace("=3D", "=")
    }
}

/// Base64 encode (standard alphabet)
fn base64_encode(data: &[u8]) -> String {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    STANDARD.encode(data)
}

/// Base64 decode (standard alphabet)
fn base64_decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    STANDARD.decode(s)
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_password_hash_verify() {
        let hash = PasswordHash::new("Test@Pass123");
        assert!(hash.verify("Test@Pass123"));
        assert!(!hash.verify("Wrong@Pass1"));
        assert!(!hash.verify(""));
        assert!(!hash.verify("Test@Pass12")); // Off by one
    }

    #[test]
    fn test_password_hash_timing_attack_resistant() {
        // Both wrong passwords should take similar time
        // (This is more of a design assertion than a precise timing test)
        let hash = PasswordHash::new("Correct@Pass1");

        // Wrong but similar length
        assert!(!hash.verify("Wrong@Pass1"));

        // Wrong and very different
        assert!(!hash.verify("x"));

        // Both should still return false (constant-time)
    }

    #[test]
    fn test_create_principal() {
        let auth = AuthManager::new_default();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());

        auth.create_principal(
            "alice",
            "Secure@Pass123",
            PrincipalType::User,
            roles.clone(),
        )
        .expect("Failed to create principal");

        // Duplicate should fail
        assert!(auth
            .create_principal("alice", "Other@Pass1", PrincipalType::User, roles.clone())
            .is_err());

        // Verify principal exists
        let principal = auth.get_principal("alice").expect("Principal not found");
        assert_eq!(principal.name, "alice");
        assert!(principal.roles.contains("producer"));
    }

    #[test]
    fn test_authentication_success() {
        let auth = AuthManager::new_default();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());

        auth.create_principal("bob", "Bob@Pass123", PrincipalType::User, roles)
            .unwrap();

        let session = auth
            .authenticate("bob", "Bob@Pass123", "127.0.0.1")
            .expect("Authentication should succeed");

        assert_eq!(session.principal_name, "bob");
        assert!(!session.is_expired());
    }

    #[test]
    fn test_authentication_failure() {
        let auth = AuthManager::new_default();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());

        auth.create_principal("charlie", "Correct@Pass1", PrincipalType::User, roles)
            .unwrap();

        // Wrong password
        let result = auth.authenticate("charlie", "Wrong@Pass1", "127.0.0.1");
        assert!(matches!(result, Err(AuthError::AuthenticationFailed)));

        // Unknown user
        let result = auth.authenticate("unknown", "password", "127.0.0.1");
        assert!(matches!(result, Err(AuthError::AuthenticationFailed)));
    }

    #[test]
    fn test_rate_limiting() {
        let config = AuthConfig {
            max_failed_attempts: 3,
            // Use a long lockout so it doesn't expire during slow debug-mode PBKDF2 ops
            lockout_duration: Duration::from_secs(120),
            ..Default::default()
        };
        let auth = AuthManager::new(config);

        let mut roles = HashSet::new();
        roles.insert("consumer".to_string());
        auth.create_principal("eve", "Eve@Pass123", PrincipalType::User, roles)
            .unwrap();

        // Fail 3 times
        for _ in 0..3 {
            let _ = auth.authenticate("eve", "wrong", "192.168.1.1");
        }

        // Now should be rate limited
        let result = auth.authenticate("eve", "Eve@Pass123", "192.168.1.1");
        assert!(matches!(result, Err(AuthError::RateLimited)));

        // Clear lockout manually (instead of sleeping, which is unreliable in debug builds
        // where PBKDF2 at 600k iterations can exceed short lockout durations)
        {
            let mut tracker = auth.failed_attempts.write();
            tracker.clear_failures("eve");
            tracker.clear_failures("192.168.1.1");
        }

        // Should work now
        let result = auth.authenticate("eve", "Eve@Pass123", "192.168.1.1");
        assert!(result.is_ok());
    }

    #[test]
    fn test_role_permissions() {
        let auth = AuthManager::with_auth_enabled();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("producer_user", "Prod@Pass123", PrincipalType::User, roles)
            .unwrap();

        let session = auth
            .authenticate("producer_user", "Prod@Pass123", "127.0.0.1")
            .unwrap();

        // Producer should have write permission on topics
        assert!(session.has_permission(
            &ResourceType::Topic("orders".to_string()),
            &Permission::Write
        ));

        // Producer should not have delete permission
        assert!(!session.has_permission(
            &ResourceType::Topic("orders".to_string()),
            &Permission::Delete
        ));
    }

    #[test]
    fn test_admin_has_all_permissions() {
        let auth = AuthManager::with_auth_enabled();

        let mut roles = HashSet::new();
        roles.insert("admin".to_string());
        auth.create_principal("admin_user", "Admin@Pass1", PrincipalType::User, roles)
            .unwrap();

        let session = auth
            .authenticate("admin_user", "Admin@Pass1", "127.0.0.1")
            .unwrap();

        // Admin should have all permissions
        assert!(session.has_permission(&ResourceType::Cluster, &Permission::All));
        assert!(session.has_permission(
            &ResourceType::Topic("any_topic".to_string()),
            &Permission::Delete
        ));
    }

    #[test]
    fn test_resource_pattern_matching() {
        assert!(ResourceType::TopicPattern("*".to_string())
            .matches(&ResourceType::Topic("anything".to_string())));

        assert!(ResourceType::TopicPattern("orders-*".to_string())
            .matches(&ResourceType::Topic("orders-us".to_string())));

        assert!(ResourceType::TopicPattern("orders-*".to_string())
            .matches(&ResourceType::Topic("orders-eu".to_string())));

        assert!(!ResourceType::TopicPattern("orders-*".to_string())
            .matches(&ResourceType::Topic("events-us".to_string())));
    }

    #[test]
    fn test_acl_enforcement() {
        let auth = AuthManager::new(AuthConfig {
            require_authentication: true,
            enable_acls: true,
            default_deny: true,
            ..Default::default()
        });

        let mut roles = HashSet::new();
        roles.insert("read-only".to_string());
        auth.create_principal("reader", "Read@Pass123", PrincipalType::User, roles)
            .unwrap();

        // Add ACL allowing write to specific topic
        auth.add_acl(AclEntry {
            principal: "reader".to_string(),
            resource: ResourceType::Topic("special-topic".to_string()),
            permission: Permission::Write,
            allow: true,
            host: "*".to_string(),
        });

        let session = auth
            .authenticate("reader", "Read@Pass123", "127.0.0.1")
            .unwrap();

        // Should be able to write to special-topic via ACL
        let result = auth.authorize(
            &session,
            &ResourceType::Topic("special-topic".to_string()),
            Permission::Write,
            "127.0.0.1",
        );
        assert!(result.is_ok());

        // Should NOT be able to write to other topics
        let result = auth.authorize(
            &session,
            &ResourceType::Topic("other-topic".to_string()),
            Permission::Write,
            "127.0.0.1",
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_sasl_plain_authentication() {
        let auth = Arc::new(AuthManager::new_default());

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("sasl_user", "Sasl@Pass123", PrincipalType::User, roles)
            .unwrap();

        let sasl = SaslPlainAuth::new(auth);

        // Test 2-part format: username\0password
        let two_part = b"sasl_user\0Sasl@Pass123";
        let result = sasl.authenticate(two_part, "127.0.0.1");
        assert!(result.is_ok());

        // Test 3-part format: authzid\0username\0password
        let three_part = b"\0sasl_user\0Sasl@Pass123";
        let result = sasl.authenticate(three_part, "127.0.0.1");
        assert!(result.is_ok());
    }

    #[test]
    fn test_session_expiration() {
        let config = AuthConfig {
            session_timeout: Duration::from_millis(100),
            ..Default::default()
        };
        let auth = AuthManager::new(config);

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("expiring", "Expiry@Pass1", PrincipalType::User, roles)
            .unwrap();

        let session = auth
            .authenticate("expiring", "Expiry@Pass1", "127.0.0.1")
            .unwrap();
        assert!(!session.is_expired());

        // Wait for session to expire
        std::thread::sleep(Duration::from_millis(150));

        // Session should be expired
        let session = AuthSession {
            expires_at: session.expires_at,
            ..session
        };
        assert!(session.is_expired());
    }

    #[test]
    fn test_delete_principal_invalidates_sessions() {
        let auth = AuthManager::new_default();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("deleteme", "Delete@Pass1", PrincipalType::User, roles)
            .unwrap();

        let session = auth
            .authenticate("deleteme", "Delete@Pass1", "127.0.0.1")
            .unwrap();

        // Session should exist
        assert!(auth.get_session(&session.id).is_some());

        // Delete principal
        auth.delete_principal("deleteme").unwrap();

        // Session should be gone
        assert!(auth.get_session(&session.id).is_none());
    }

    #[test]
    fn test_disabled_principal_cannot_authenticate() {
        let auth = AuthManager::new_default();

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("disabled_user", "Disable@Pass1", PrincipalType::User, roles)
            .unwrap();

        // Disable the principal
        {
            let mut principals = auth.principals.write();
            if let Some(p) = principals.get_mut("disabled_user") {
                p.enabled = false;
            }
        }

        // Should fail to authenticate
        let result = auth.authenticate("disabled_user", "Disable@Pass1", "127.0.0.1");
        assert!(matches!(result, Err(AuthError::AuthenticationFailed)));
    }

    #[test]
    fn test_password_hash_debug_redacts_sensitive_data() {
        let hash = PasswordHash::new("super_secret_password");
        let debug_output = format!("{:?}", hash);

        // Should contain REDACTED markers
        assert!(
            debug_output.contains("[REDACTED]"),
            "Debug output should contain [REDACTED]"
        );

        // Should NOT contain actual salt or key material
        // Salt and keys are binary data, but let's ensure no suspicious patterns
        assert!(
            !debug_output.contains("super_secret_password"),
            "Debug output should not contain password"
        );

        // Should show iterations (not sensitive)
        assert!(
            debug_output.contains("iterations"),
            "Debug output should show iterations field"
        );
    }

    #[test]
    fn test_principal_debug_redacts_password_hash() {
        let principal = Principal {
            name: "test_user".to_string(),
            principal_type: PrincipalType::User,
            password_hash: PasswordHash::new("secret_password"),
            roles: HashSet::from(["admin".to_string()]),
            enabled: true,
            metadata: HashMap::new(),
            created_at: 1234567890,
        };

        let debug_output = format!("{:?}", principal);

        // Should contain REDACTED for password_hash
        assert!(
            debug_output.contains("[REDACTED]"),
            "Debug output should contain [REDACTED]: {}",
            debug_output
        );

        // Should still show non-sensitive fields
        assert!(
            debug_output.contains("test_user"),
            "Debug output should show name"
        );
        assert!(
            debug_output.contains("admin"),
            "Debug output should show roles"
        );
    }

    // ========================================================================
    // SCRAM-SHA-256 Tests
    // ========================================================================

    #[test]
    fn test_scram_full_handshake() {
        use sha2::{Digest, Sha256};

        let auth = Arc::new(AuthManager::new_default());

        // Create a user
        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("scram_user", "Scram@Pass123", PrincipalType::User, roles)
            .expect("Failed to create principal");

        let scram = SaslScramAuth::new(auth.clone());

        // Step 1: Client sends client-first-message
        let client_nonce = "rOprNGfwEbeRWgbNEkqO";
        let client_first = format!("n,,n=scram_user,r={}", client_nonce);

        let (state, server_first) = scram
            .process_client_first(client_first.as_bytes(), "127.0.0.1")
            .expect("client-first processing should succeed");

        // Verify server-first-message format
        let server_first_str = std::str::from_utf8(&server_first).expect("valid UTF-8");
        assert!(server_first_str.starts_with(&format!("r={}", client_nonce)));
        assert!(server_first_str.contains(",s="));
        assert!(server_first_str.contains(",i="));

        // Parse server-first-message to build client-final
        let ScramState::ServerFirstSent {
            username: _,
            client_nonce: _,
            server_nonce: _,
            salt,
            iterations,
            auth_message: _,
        } = &state
        else {
            panic!("Expected ServerFirstSent state");
        };

        // Step 2: Client computes proof and sends client-final-message
        // ClientProof = ClientKey XOR ClientSignature
        let salted_password = compute_salted_password("Scram@Pass123", salt, *iterations);
        let client_key = PasswordHash::hmac_sha256(&salted_password, b"Client Key");
        let stored_key = Sha256::digest(&client_key);

        // Build auth message
        let client_first_bare = format!("n=scram_user,r={}", client_nonce);
        let combined_nonce: String = server_first_str
            .split(',')
            .find(|s| s.starts_with("r="))
            .map(|s| &s[2..])
            .unwrap()
            .to_string();

        let auth_message = format!(
            "{},{},c=biws,r={}",
            client_first_bare, server_first_str, combined_nonce
        );

        let client_signature = PasswordHash::hmac_sha256(&stored_key, auth_message.as_bytes());
        let client_proof: Vec<u8> = client_key
            .iter()
            .zip(client_signature.iter())
            .map(|(k, s)| k ^ s)
            .collect();

        let client_final = format!(
            "c=biws,r={},p={}",
            combined_nonce,
            base64_encode(&client_proof)
        );

        // Step 3: Server verifies and responds
        let (session, server_final) = scram
            .process_client_final(&state, client_final.as_bytes(), "127.0.0.1")
            .expect("client-final processing should succeed");

        // Verify session was created
        assert_eq!(session.principal_name, "scram_user");
        assert!(!session.is_expired());

        // Verify server-final-message (mutual authentication)
        let server_final_str = std::str::from_utf8(&server_final).expect("valid UTF-8");
        assert!(server_final_str.starts_with("v="));
    }

    #[test]
    fn test_scram_wrong_password() {
        let auth = Arc::new(AuthManager::new_default());

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("scram_user2", "Correct@Pass1", PrincipalType::User, roles)
            .expect("Failed to create principal");

        let scram = SaslScramAuth::new(auth.clone());

        // Client-first with correct username
        let client_nonce = "test_nonce_12345";
        let client_first = format!("n,,n=scram_user2,r={}", client_nonce);

        let (state, server_first) = scram
            .process_client_first(client_first.as_bytes(), "127.0.0.1")
            .expect("client-first processing should succeed");

        // Parse server response
        let server_first_str = std::str::from_utf8(&server_first).expect("valid UTF-8");
        let combined_nonce: String = server_first_str
            .split(',')
            .find(|s| s.starts_with("r="))
            .map(|s| &s[2..])
            .unwrap()
            .to_string();

        // Compute proof with WRONG password
        let ScramState::ServerFirstSent {
            salt, iterations, ..
        } = &state
        else {
            panic!("Expected ServerFirstSent state");
        };

        let salted_password = compute_salted_password("Wrong@Pass1", salt, *iterations);
        let client_key = PasswordHash::hmac_sha256(&salted_password, b"Client Key");
        let stored_key = sha2::Sha256::digest(&client_key);

        let client_first_bare = format!("n=scram_user2,r={}", client_nonce);
        let auth_message = format!(
            "{},{},c=biws,r={}",
            client_first_bare, server_first_str, combined_nonce
        );

        let client_signature = PasswordHash::hmac_sha256(&stored_key, auth_message.as_bytes());
        let client_proof: Vec<u8> = client_key
            .iter()
            .zip(client_signature.iter())
            .map(|(k, s)| k ^ s)
            .collect();

        let client_final = format!(
            "c=biws,r={},p={}",
            combined_nonce,
            base64_encode(&client_proof)
        );

        // Should fail
        let result = scram.process_client_final(&state, client_final.as_bytes(), "127.0.0.1");
        assert!(result.is_err());
        assert!(matches!(result, Err(AuthError::AuthenticationFailed)));
    }

    #[test]
    fn test_scram_nonexistent_user() {
        let auth = Arc::new(AuthManager::new_default());
        let scram = SaslScramAuth::new(auth.clone());

        // Client-first for nonexistent user
        let client_first = "n,,n=nonexistent_user,r=test_nonce";

        // Should still return a server-first (to prevent enumeration)
        let result = scram.process_client_first(client_first.as_bytes(), "127.0.0.1");
        assert!(
            result.is_ok(),
            "Should return fake server-first to prevent enumeration"
        );

        let (state, server_first) = result.unwrap();
        let server_first_str = std::str::from_utf8(&server_first).expect("valid UTF-8");

        // Should have valid format (fake salt/iterations)
        assert!(server_first_str.contains("r=test_nonce"));
        assert!(server_first_str.contains(",s="));
        assert!(server_first_str.contains(",i="));

        // Final step should fail
        let combined_nonce: String = server_first_str
            .split(',')
            .find(|s| s.starts_with("r="))
            .map(|s| &s[2..])
            .unwrap()
            .to_string();

        let client_final = format!("c=biws,r={},p=dW5rbm93bg==", combined_nonce);
        let result = scram.process_client_final(&state, client_final.as_bytes(), "127.0.0.1");
        assert!(result.is_err());
    }

    #[test]
    fn test_scram_nonce_mismatch() {
        let auth = Arc::new(AuthManager::new_default());

        let mut roles = HashSet::new();
        roles.insert("producer".to_string());
        auth.create_principal("scram_user3", "Scram3@Pass1", PrincipalType::User, roles)
            .expect("Failed to create principal");

        let scram = SaslScramAuth::new(auth.clone());

        let client_first = "n,,n=scram_user3,r=original_nonce";
        let (state, _server_first) = scram
            .process_client_first(client_first.as_bytes(), "127.0.0.1")
            .expect("client-first should succeed");

        // Client-final with different nonce prefix (attack attempt)
        let client_final = "c=biws,r=tampered_nonce_plus_server,p=dW5rbm93bg==";
        let result = scram.process_client_final(&state, client_final.as_bytes(), "127.0.0.1");
        assert!(result.is_err());
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    /// Helper: Compute salted password (PBKDF2)
    fn compute_salted_password(password: &str, salt: &[u8], iterations: u32) -> Vec<u8> {
        use hmac::{Hmac, Mac};
        type HmacSha256 = Hmac<sha2::Sha256>;

        let mut result = vec![0u8; 32];

        let mut mac =
            HmacSha256::new_from_slice(password.as_bytes()).expect("HMAC accepts any key length");
        mac.update(salt);
        mac.update(&1u32.to_be_bytes());
        let mut u = mac.finalize().into_bytes();
        result.copy_from_slice(&u);

        for _ in 1..iterations {
            let mut mac = HmacSha256::new_from_slice(password.as_bytes())
                .expect("HMAC accepts any key length");
            mac.update(&u);
            u = mac.finalize().into_bytes();

            for (r, ui) in result.iter_mut().zip(u.iter()) {
                *r ^= ui;
            }
        }

        result
    }
}