dbnexus 0.3.0

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
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
// Copyright (c) 2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! 可插拔权限引擎模块
//!
//! 提供灵活的权限引擎架构,支持多种权限提供者实现:
//! - 基于 YAML 配置的权限提供者
//! - 基于 RBAC (Role-Based Access Control) 的权限提供者
//! - 自定义权限提供者
//!
//! # 核心组件
//!
//! - [`PermissionProvider`] - 权限提供者 trait,定义权限检查接口
//! - [`PolicyDecisionPoint`] - 策略决策点,统一处理权限决策
//! - [`YamlPermissionProvider`] - 基于 YAML 文件的权限提供者
//! - [`RbacPermissionProvider`] - 基于角色的权限提供者
//!
//! # 使用示例
//!
//! ```rust,no_run
//! use std::sync::Arc;
//!
//! use dbnexus::access::permission_engine::{PolicyDecisionPoint, YamlPermissionProvider};
//!
//! fn main() -> Result<(), String> {
//!     let provider = YamlPermissionProvider::new("permissions.yaml")?;
//!     let pdp = PolicyDecisionPoint::new(Arc::new(provider));
//!
//!     let rt = tokio::runtime::Runtime::new().unwrap();
//!     let _decision = rt.block_on(async { pdp.check("admin", "users", "SELECT").await });
//!
//!     Ok(())
//! }
//! ```

pub use crate::access::permission::PermissionAction;
use async_trait::async_trait;
use dashmap::DashMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::{Duration, Instant};

/// 预编译的正则表达式,用于检测路径遍历攻击模式
/// 使用 once_cell 确保线程安全的单次初始化
static PATH_TRAVERSAL_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\.\.|%2e%2e|%252e%252e|\\/|\\\\").expect("Regex pattern should be valid"));

/// 检查配置路径是否安全
///
/// 防止路径遍历攻击,确保路径不会访问预期目录之外的文件
fn is_safe_config_path(path: &str) -> bool {
    // 检查空路径
    if path.is_empty() {
        return false;
    }

    // 检查路径遍历攻击模式
    if PATH_TRAVERSAL_REGEX.is_match(path) {
        return false;
    }

    // 检查绝对路径是否在允许的目录内
    let path_buf = std::path::Path::new(path);
    if path_buf.is_absolute() {
        // 允许的配置目录前缀
        let allowed_prefixes = ["/etc/dbnexus/", "/opt/dbnexus/config/", "./config/", "./"];
        if allowed_prefixes.iter().any(|prefix| path.starts_with(prefix)) {
            return true;
        }
        // 也允许系统临时目录(用于测试场景)
        let temp_dir = std::env::temp_dir();
        return path.starts_with(temp_dir.to_str().unwrap_or(""));
    }

    // 相对路径检查
    !path.contains("..") && !path.contains('\\')
}

/// 权限资源
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PermissionResource {
    /// 资源名称(如表名)
    pub name: String,
    /// 资源类型
    #[serde(default)]
    pub resource_type: String,
}

impl PermissionResource {
    /// 创建新资源
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            resource_type: "table".to_string(),
        }
    }

    /// 创建带类型的资源
    pub fn with_type(name: &str, resource_type: &str) -> Self {
        Self {
            name: name.to_string(),
            resource_type: resource_type.to_string(),
        }
    }
}

/// 权限主体(用户或角色)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PermissionSubject {
    /// 主体 ID(用户 ID 或角色名称)
    pub id: String,
    /// 主体类型
    #[serde(default)]
    pub subject_type: SubjectType,
}

impl PermissionSubject {
    /// 创建用户主体
    pub fn user(id: &str) -> Self {
        Self {
            id: id.to_string(),
            subject_type: SubjectType::User,
        }
    }

    /// 创建角色主体
    pub fn role(id: &str) -> Self {
        Self {
            id: id.to_string(),
            subject_type: SubjectType::Role,
        }
    }
}

/// 主体类型
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubjectType {
    /// 用户类型
    #[default]
    User,
    /// 角色类型
    Role,
    /// 组类型
    Group,
}

/// 权限决策结果
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionDecision {
    /// 允许
    Allow,
    /// 拒绝
    Deny,
    /// 不适用(未找到相关策略)
    NotApplicable,
    /// 错误
    Error(String),
}

/// 权限上下文
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionContext {
    /// 主体
    pub subject: PermissionSubject,
    /// 资源
    pub resource: PermissionResource,
    /// 操作
    pub action: PermissionAction,
    /// 额外属性
    #[serde(default)]
    pub attributes: HashMap<String, String>,
    /// 环境信息
    #[serde(default)]
    pub environment: HashMap<String, String>,
}

impl PermissionContext {
    /// 创建权限上下文
    pub fn new(subject: PermissionSubject, resource: PermissionResource, action: PermissionAction) -> Self {
        Self {
            subject,
            resource,
            action,
            attributes: HashMap::new(),
            environment: HashMap::new(),
        }
    }

    /// 添加属性
    pub fn with_attribute(mut self, key: &str, value: &str) -> Self {
        self.attributes.insert(key.to_string(), value.to_string());
        self
    }

    /// 添加环境信息
    pub fn with_environment(mut self, key: &str, value: &str) -> Self {
        self.environment.insert(key.to_string(), value.to_string());
        self
    }
}

/// 权限规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionRule {
    /// 规则名称
    pub name: String,
    /// 优先级(数值越大优先级越高)
    #[serde(default)]
    pub priority: i32,
    /// 目标主体(支持通配符 *)
    pub subject: String,
    /// 目标资源(支持通配符 *)
    pub resource: String,
    /// 允许的操作
    pub allow: Vec<PermissionAction>,
    /// 拒绝的操作
    #[serde(default)]
    pub deny: Vec<PermissionAction>,
    /// 条件表达式
    #[serde(default)]
    pub condition: Option<String>,
    /// 规则是否启用
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

fn default_enabled() -> bool {
    true
}

/// 检查规则是否匹配当前上下文
///
/// 通用匹配逻辑:检查主体、资源以及操作是否在 allow/deny 列表中。
/// 若操作既不在 allow 也不在 deny,则规则不匹配(提前过滤,避免无谓排序)。
fn matches_rule(rule: &PermissionRule, context: &PermissionContext) -> bool {
    // 检查主体匹配
    if rule.subject != "*" && rule.subject != context.subject.id {
        return false;
    }

    // 检查资源匹配
    if rule.resource != "*" && rule.resource != context.resource.name {
        return false;
    }

    // 检查操作匹配(允许列表或拒绝列表)
    let in_allow = rule.allow.contains(&context.action);
    let in_deny = rule.deny.contains(&context.action);

    // 如果操作既不在 allow 也不在 deny 中,则不匹配
    if !in_allow && !in_deny {
        return false;
    }

    true
}

/// 获取主体的所有角色(含继承)
///
/// 优先从角色映射表中获取;若无映射,检查主体本身是否是预定义的角色
/// (确保只返回预定义角色,防止安全问题)。
fn get_subject_roles<V>(
    mapping: &HashMap<String, Vec<String>>,
    roles: &HashMap<String, V>,
    subject: &str,
) -> Vec<String> {
    // 优先从角色映射中获取
    if let Some(roles_list) = mapping.get(subject) {
        return roles_list.clone();
    }
    // 如果没有映射,检查 subject 本身是否是预定义的角色
    if roles.contains_key(subject) {
        return vec![subject.to_string()];
    }
    Vec::new()
}

/// 权限提供者 trait
/// 定义权限检查的标准接口
#[async_trait]
pub trait PermissionProvider: Send + Sync + Debug {
    /// 检查权限
    ///
    /// # 参数
    ///
    /// * `context` - 权限上下文
    ///
    /// # 返回
    ///
    /// 权限决策结果
    async fn check_permission(&self, context: &PermissionContext) -> PermissionDecision;

    /// 获取主体可访问的资源列表
    async fn get_allowed_resources(&self, subject: &str) -> Vec<PermissionResource>;

    /// 获取主体可执行的操作列表
    async fn get_allowed_actions(&self, subject: &str, resource: &str) -> Vec<PermissionAction>;

    /// 刷新权限缓存
    async fn refresh(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;

    /// 获取提供者名称
    fn name(&self) -> &str;
}

/// 缓存的权限决策(包含时间戳)
#[derive(Debug, Clone)]
struct CachedDecision {
    decision: PermissionDecision,
    cached_at: Instant,
}

impl CachedDecision {
    fn new(decision: PermissionDecision) -> Self {
        Self {
            decision,
            cached_at: Instant::now(),
        }
    }

    fn is_expired(&self, ttl_seconds: u64) -> bool {
        self.cached_at.elapsed().as_secs() >= ttl_seconds
    }
}

/// 速率限制器条目
#[derive(Debug, Clone)]
struct RateLimitEntry {
    count: u32,
    window_start: Instant,
}

/// 默认缓存 TTL(5 分钟)
const DEFAULT_CACHE_TTL_SECONDS: u64 = 300;
/// 默认速率限制最大请求数(每分钟 100 次)
const DEFAULT_RATE_LIMIT_MAX_REQUESTS: u32 = 100;
/// 默认速率限制窗口(1 分钟)
const DEFAULT_RATE_LIMIT_WINDOW_SECONDS: u32 = 60;

/// 策略决策点
/// 统一处理权限决策,支持多种权限提供者
#[derive(Debug)]
pub struct PolicyDecisionPoint {
    /// 权限提供者
    provider: Arc<dyn PermissionProvider>,
    /// 缓存(使用 DashMap 实现细粒度锁)
    cache: DashMap<String, CachedDecision>,
    /// 缓存配置
    cache_ttl_seconds: u64,
    /// 是否启用缓存
    cache_enabled: bool,
    /// 速率限制:最大请求数(每分钟)
    rate_limit_max_requests: u32,
    /// 速率限制:时间窗口(秒)
    rate_limit_window_seconds: u32,
    /// 速率限制器存储
    rate_limit_store: DashMap<String, RateLimitEntry>,
    /// 默认决策(当提供者返回 NotApplicable 时使用)
    default_decision: PermissionDecision,
    /// 是否记录拒绝的决策到 stderr
    log_denied: bool,
}

/// PolicyDecisionPoint 构建器
///
/// 支持部分依赖注入和自定义配置
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use dbnexus::{PolicyDecisionPoint, RbacPermissionProvider};
///
/// let provider = Arc::new(RbacPermissionProvider::new());
/// let pdp = PolicyDecisionPoint::builder()
///     .provider(provider)
///     .cache_ttl_seconds(600)
///     .rate_limit(200, 60)
///     .build();
/// ```
pub struct PolicyDecisionPointBuilder {
    provider: Option<Arc<dyn PermissionProvider>>,
    cache_ttl_seconds: Option<u64>,
    cache_enabled: Option<bool>,
    rate_limit_max_requests: Option<u32>,
    rate_limit_window_seconds: Option<u32>,
    default_decision: Option<PermissionDecision>,
    log_denied: Option<bool>,
}

impl PolicyDecisionPointBuilder {
    /// 创建新的构建器
    fn new() -> Self {
        Self {
            provider: None,
            cache_ttl_seconds: None,
            cache_enabled: None,
            rate_limit_max_requests: None,
            rate_limit_window_seconds: None,
            default_decision: None,
            log_denied: None,
        }
    }

    /// 设置权限提供者
    ///
    /// # Arguments
    ///
    /// * `provider` - 权限提供者实例
    pub fn provider(mut self, provider: Arc<dyn PermissionProvider>) -> Self {
        self.provider = Some(provider);
        self
    }

    /// 设置缓存 TTL(秒)
    ///
    /// # Arguments
    ///
    /// * `seconds` - 缓存过期时间(秒)
    pub fn cache_ttl_seconds(mut self, seconds: u64) -> Self {
        self.cache_ttl_seconds = Some(seconds);
        self
    }

    /// 设置是否启用缓存
    ///
    /// # Arguments
    ///
    /// * `enabled` - 是否启用缓存
    pub fn cache_enabled(mut self, enabled: bool) -> Self {
        self.cache_enabled = Some(enabled);
        self
    }

    /// 设置速率限制
    ///
    /// # Arguments
    ///
    /// * `max_requests` - 时间窗口内最大请求数
    /// * `window_seconds` - 时间窗口(秒)
    pub fn rate_limit(mut self, max_requests: u32, window_seconds: u32) -> Self {
        self.rate_limit_max_requests = Some(max_requests);
        self.rate_limit_window_seconds = Some(window_seconds);
        self
    }

    /// 设置默认决策(当提供者返回 NotApplicable 时使用)
    ///
    /// # Arguments
    ///
    /// * `decision` - 默认决策
    pub fn default_decision(mut self, decision: PermissionDecision) -> Self {
        self.default_decision = Some(decision);
        self
    }

    /// 设置是否记录拒绝的决策到 stderr
    ///
    /// # Arguments
    ///
    /// * `enabled` - 是否记录拒绝的决策
    pub fn log_denied(mut self, enabled: bool) -> Self {
        self.log_denied = Some(enabled);
        self
    }

    /// 构建策略决策点
    ///
    /// # Panics
    ///
    /// 如果未设置权限提供者,将 panic
    pub fn build(self) -> PolicyDecisionPoint {
        let provider = self.provider.expect("Provider is required for PolicyDecisionPoint");

        PolicyDecisionPoint {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds: self.cache_ttl_seconds.unwrap_or(DEFAULT_CACHE_TTL_SECONDS),
            cache_enabled: self.cache_enabled.unwrap_or(true),
            rate_limit_max_requests: self.rate_limit_max_requests.unwrap_or(DEFAULT_RATE_LIMIT_MAX_REQUESTS),
            rate_limit_window_seconds: self
                .rate_limit_window_seconds
                .unwrap_or(DEFAULT_RATE_LIMIT_WINDOW_SECONDS),
            rate_limit_store: DashMap::new(),
            default_decision: self.default_decision.unwrap_or(PermissionDecision::NotApplicable),
            log_denied: self.log_denied.unwrap_or(false),
        }
    }
}

impl PolicyDecisionPoint {
    /// 创建策略决策点(默认 TTL 5 分钟,速率限制 100 请求/分钟)
    pub fn new(provider: Arc<dyn PermissionProvider>) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds: DEFAULT_CACHE_TTL_SECONDS,
            cache_enabled: true,
            rate_limit_max_requests: DEFAULT_RATE_LIMIT_MAX_REQUESTS,
            rate_limit_window_seconds: DEFAULT_RATE_LIMIT_WINDOW_SECONDS,
            rate_limit_store: DashMap::new(),
            default_decision: PermissionDecision::NotApplicable,
            log_denied: false,
        }
    }

    /// 创建构建器
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use dbnexus::{PolicyDecisionPoint, RbacPermissionProvider};
    ///
    /// let provider = Arc::new(RbacPermissionProvider::new());
    /// let pdp = PolicyDecisionPoint::builder()
    ///     .provider(provider)
    ///     .cache_ttl_seconds(600)
    ///     .build();
    /// ```
    pub fn builder() -> PolicyDecisionPointBuilder {
        PolicyDecisionPointBuilder::new()
    }

    /// 完全依赖注入:由调用方提供权限提供者
    ///
    /// # Arguments
    ///
    /// * `provider` - 权限提供者实例
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use dbnexus::{PolicyDecisionPoint, RbacPermissionProvider};
    ///
    /// let provider = Arc::new(RbacPermissionProvider::new());
    /// let pdp = PolicyDecisionPoint::with_dependencies(provider);
    /// ```
    pub fn with_dependencies(provider: Arc<dyn PermissionProvider>) -> Self {
        Self::new(provider)
    }

    /// 创建带缓存配置的策略决策点
    pub fn with_cache(provider: Arc<dyn PermissionProvider>, cache_ttl_seconds: u64) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds,
            cache_enabled: true,
            rate_limit_max_requests: DEFAULT_RATE_LIMIT_MAX_REQUESTS,
            rate_limit_window_seconds: DEFAULT_RATE_LIMIT_WINDOW_SECONDS,
            rate_limit_store: DashMap::new(),
            default_decision: PermissionDecision::NotApplicable,
            log_denied: false,
        }
    }

    /// 创建带速率限制配置的策略决策点
    pub fn with_rate_limit(provider: Arc<dyn PermissionProvider>, max_requests: u32, window_seconds: u32) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds: DEFAULT_CACHE_TTL_SECONDS,
            cache_enabled: true,
            rate_limit_max_requests: max_requests,
            rate_limit_window_seconds: window_seconds,
            rate_limit_store: DashMap::new(),
            default_decision: PermissionDecision::NotApplicable,
            log_denied: false,
        }
    }

    /// 创建带完整配置的策略决策点
    ///
    /// 正确应用 `PolicyDecisionPointConfig` 中的所有字段,包括:
    /// - `default_decision`:当提供者返回 `NotApplicable` 时使用的默认决策
    /// - `log_denied`:是否记录拒绝的决策到 stderr
    /// - `cache_ttl_seconds`:缓存 TTL
    /// - `cache_enabled`:是否启用缓存
    pub fn with_config(provider: Arc<dyn PermissionProvider>, config: PolicyDecisionPointConfig) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds: config.cache_ttl_seconds,
            cache_enabled: config.cache_enabled,
            rate_limit_max_requests: DEFAULT_RATE_LIMIT_MAX_REQUESTS,
            rate_limit_window_seconds: DEFAULT_RATE_LIMIT_WINDOW_SECONDS,
            rate_limit_store: DashMap::new(),
            default_decision: config.default_decision,
            log_denied: config.log_denied,
        }
    }

    /// 检查速率限制
    fn check_rate_limit(&self, subject_id: &str) -> bool {
        let key = subject_id.to_string();
        let now = Instant::now();
        let window_duration = Duration::from_secs(self.rate_limit_window_seconds as u64);

        // 获取或创建速率限制条目
        let mut entry = self.rate_limit_store.entry(key.clone()).or_insert(RateLimitEntry {
            count: 0,
            window_start: now,
        });

        // 检查窗口是否过期
        if now.duration_since(entry.window_start) >= window_duration {
            entry.count = 0;
            entry.window_start = now;
        }

        // 检查是否超过限制
        if entry.count >= self.rate_limit_max_requests {
            false
        } else {
            entry.count += 1;
            true
        }
    }

    /// 检查权限(带 TTL 缓存和速率限制)
    pub async fn check_permission(&self, context: &PermissionContext) -> PermissionDecision {
        // 检查速率限制
        if !self.check_rate_limit(&context.subject.id) {
            return PermissionDecision::Deny;
        }

        // 生成缓存键
        let cache_key = self.generate_cache_key(context);

        // 检查缓存(带 TTL 验证)
        if self.cache_enabled {
            if let Some(decision) = self.get_cached_decision(&cache_key) {
                self.maybe_log_denied(&decision, context);
                return decision;
            }
        }

        // 获取权限决策
        let decision = self.provider.check_permission(context).await;

        // 应用默认决策:当提供者返回 NotApplicable 时,使用配置的默认决策
        let decision = match decision {
            PermissionDecision::NotApplicable => self.default_decision.clone(),
            other => other,
        };

        // 更新缓存(带时间戳)
        if self.cache_enabled {
            self.update_cache(&cache_key, decision.clone());
        }

        self.maybe_log_denied(&decision, context);

        decision
    }

    /// 记录拒绝的决策到 stderr(当 log_denied 为 true 且决策为 Deny 时)
    fn maybe_log_denied(&self, decision: &PermissionDecision, context: &PermissionContext) {
        if self.log_denied && matches!(decision, PermissionDecision::Deny) {
            eprintln!(
                "[permission] 拒绝访问: subject={}, resource={}, action={:?}",
                context.subject.id, context.resource.name, context.action
            );
        }
    }

    /// 检查用户是否有权限执行操作
    pub async fn check(&self, subject: &str, resource: &str, action: &str) -> PermissionDecision {
        let action = match action.to_uppercase().as_str() {
            "SELECT" => PermissionAction::Select,
            "INSERT" => PermissionAction::Insert,
            "UPDATE" => PermissionAction::Update,
            "DELETE" => PermissionAction::Delete,
            // 未知操作返回错误,拒绝访问(安全考虑)
            _ => return PermissionDecision::Error(format!("Unknown action: {}", action)),
        };

        let context = PermissionContext::new(
            PermissionSubject::user(subject),
            PermissionResource::new(resource),
            action,
        );

        self.check_permission(&context).await
    }

    /// 批量检查权限
    pub async fn check_batch(&self, contexts: Vec<PermissionContext>) -> Vec<(PermissionContext, PermissionDecision)> {
        let mut results = Vec::with_capacity(contexts.len());

        for context in contexts {
            let decision = self.check_permission(&context).await;
            results.push((context, decision));
        }

        results
    }

    /// 获取主体可访问的资源
    pub async fn get_allowed_resources(&self, subject: &str) -> Vec<PermissionResource> {
        self.provider.get_allowed_resources(subject).await
    }

    /// 刷新缓存
    pub async fn refresh_cache(&self) {
        self.provider.refresh().await.ok();
        // DashMap 清空
        self.cache.clear();
    }

    /// 启用/禁用缓存
    pub fn set_cache_enabled(&mut self, enabled: bool) {
        self.cache_enabled = enabled;
        if !enabled {
            // DashMap 清空
            self.cache.clear();
        }
    }

    /// 生成缓存键
    fn generate_cache_key(&self, context: &PermissionContext) -> String {
        format!(
            "{}:{}:{}:{}",
            context.subject.id,
            context.resource.name,
            context.action,
            context
                .attributes
                .iter()
                .fold(String::new(), |acc, (k, v)| format!("{}:{}={}", acc, k, v))
        )
    }

    /// 获取缓存的决策(带 TTL 检查)
    fn get_cached_decision(&self, key: &str) -> Option<PermissionDecision> {
        // DashMap 直接读取,无需锁
        if let Some(cached) = self.cache.get(key) {
            // 检查是否过期
            if !cached.is_expired(self.cache_ttl_seconds) {
                return Some(cached.decision.clone());
            }
        }
        None
    }

    /// 更新缓存(带时间戳)
    fn update_cache(&self, key: &str, decision: PermissionDecision) {
        // DashMap 直接写入,无需锁
        self.cache.insert(key.to_string(), CachedDecision::new(decision));
    }
}

/// 基于 YAML 配置的权限提供者
#[derive(Debug)]
pub struct YamlPermissionProvider {
    /// 配置文件路径
    config_path: String,
    /// 角色权限映射
    roles: RwLock<HashMap<String, Vec<PermissionRule>>>,
    /// 缓存时间
    last_refresh: RwLock<Instant>,
    /// 提供者名称
    name: String,
    /// 角色映射表(禁止用户名直接作为角色)
    role_mapping: RwLock<HashMap<String, Vec<String>>>,
}

impl Default for YamlPermissionProvider {
    fn default() -> Self {
        Self {
            config_path: String::new(),
            roles: RwLock::new(HashMap::new()),
            last_refresh: RwLock::new(Instant::now()),
            name: "yaml".to_string(),
            role_mapping: RwLock::new(HashMap::new()),
        }
    }
}

impl YamlPermissionProvider {
    /// 创建 YAML 权限提供者
    ///
    /// # Arguments
    ///
    /// * `config_path` - 权限配置文件路径
    ///
    /// # Errors
    ///
    /// 如果路径无效或不在允许的目录内,返回错误
    pub fn new(config_path: &str) -> Result<Self, String> {
        // 验证配置文件路径安全性

        // 1. 检查空路径
        if config_path.is_empty() {
            return Err("Config path cannot be empty".to_string());
        }

        // 2. 检查路径是否包含父目录引用(防止路径遍历攻击)
        // 使用预编译的正则表达式进行检测
        if PATH_TRAVERSAL_REGEX.is_match(config_path) {
            return Err("Config path contains invalid parent directory reference".to_string());
        }

        if !is_safe_config_path(config_path) {
            return Err("Config path failed safety validation".to_string());
        }

        Ok(Self {
            config_path: config_path.to_string(),
            roles: RwLock::new(HashMap::new()),
            last_refresh: RwLock::new(Instant::now()),
            name: "yaml".to_string(),
            role_mapping: RwLock::new(HashMap::new()),
        })
    }

    /// 加载配置
    async fn load_config(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use serde::Deserialize;

        let content = tokio::fs::read_to_string(&self.config_path).await?;

        // 解析配置
        #[derive(Debug, Deserialize)]
        struct YamlConfig {
            roles: HashMap<String, Vec<PermissionRule>>,
        }

        // 直接使用 JSON 解析
        #[cfg(feature = "json")]
        {
            let config: YamlConfig = serde_json::from_str(&content)?;

            // 更新角色权限
            if let Ok(mut roles) = self.roles.write() {
                *roles = config.roles;
            }
        }
        #[cfg(not(feature = "json"))]
        {
            // 如果没有 json feature,使用 serde_yaml_ng 直接解析
            #[cfg(feature = "yaml")]
            {
                let config: YamlConfig = serde_yaml_ng::from_str(&content)?;

                // 更新角色权限
                if let Ok(mut roles) = self.roles.write() {
                    *roles = config.roles;
                }
            }
            #[cfg(not(feature = "yaml"))]
            {
                return Err("Cannot parse permission config: neither JSON nor YAML support available".into());
            }
        }

        // 初始化角色映射(从角色定义中提取)
        if let Ok(mut role_mapping) = self.role_mapping.write() {
            role_mapping.clear();
        }

        if let Ok(mut last_refresh) = self.last_refresh.write() {
            *last_refresh = Instant::now();
        }

        Ok(())
    }
}

#[async_trait]
impl PermissionProvider for YamlPermissionProvider {
    async fn check_permission(&self, context: &PermissionContext) -> PermissionDecision {
        // 加载配置(如果需要)
        let age = self.last_refresh.read().map(|r| r.elapsed()).unwrap_or_default();
        if age.as_secs() > 60 {
            if let Err(e) = self.load_config().await {
                return PermissionDecision::Error(format!("Failed to load config: {}", e));
            }
        }

        let roles = match self.roles.read() {
            Ok(r) => r,
            Err(_) => return PermissionDecision::Error("Lock error".to_string()),
        };
        let subject_roles = self.get_subject_roles(&context.subject.id);

        // 优化:收集所有匹配的规则
        let mut matched_rules: Vec<(i32, &PermissionRule)> = Vec::new();

        for role_name in &subject_roles {
            if let Some(rules) = roles.get(role_name) {
                for rule in rules {
                    if rule.enabled && matches_rule(rule, context) {
                        matched_rules.push((rule.priority, rule));
                    }
                }
            }
        }

        // 按优先级从高到低排序
        matched_rules.sort_by(|a, b| b.0.cmp(&a.0));

        // 评估规则:按优先级从高到低,一旦找到决策立即返回
        for (_, rule) in matched_rules {
            // 检查 Allow 规则(优先级最高)
            if rule.allow.contains(&context.action) {
                return PermissionDecision::Allow;
            }
            // 检查 Deny 规则
            if rule.deny.contains(&context.action) {
                return PermissionDecision::Deny;
            }
        }

        PermissionDecision::NotApplicable
    }

    async fn get_allowed_resources(&self, subject: &str) -> Vec<PermissionResource> {
        let roles = match self.roles.read() {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        let subject_roles = self.get_subject_roles(subject);
        let mut resources = std::collections::HashSet::new();

        for role_name in &subject_roles {
            if let Some(rules) = roles.get(role_name) {
                for rule in rules {
                    if rule.enabled && (rule.subject == "*" || rule.subject == subject) {
                        resources.insert(PermissionResource::new(&rule.resource));
                    }
                }
            }
        }

        resources.into_iter().collect()
    }

    async fn get_allowed_actions(&self, subject: &str, resource: &str) -> Vec<PermissionAction> {
        let roles = match self.roles.read() {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        let subject_roles = self.get_subject_roles(subject);
        let mut actions = std::collections::HashSet::new();

        for role_name in &subject_roles {
            if let Some(rules) = roles.get(role_name) {
                for rule in rules {
                    if rule.enabled
                        && (rule.subject == "*" || rule.subject == subject)
                        && (rule.resource == "*" || rule.resource == resource)
                    {
                        for action in &rule.allow {
                            actions.insert(action.clone());
                        }
                    }
                }
            }
        }

        actions.into_iter().collect()
    }

    async fn refresh(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.load_config().await
    }

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

impl YamlPermissionProvider {
    fn get_subject_roles(&self, subject: &str) -> Vec<String> {
        let mapping = match self.role_mapping.read() {
            Ok(m) => m,
            Err(_) => return Vec::new(),
        };
        let roles = match self.roles.read() {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        get_subject_roles(&mapping, &roles, subject)
    }
}

/// 基于 RBAC 的权限提供者
#[derive(Debug)]
pub struct RbacPermissionProvider {
    /// 角色层次结构
    roles: RwLock<HashMap<String, Role>>,
    /// 权限规则
    permissions: RwLock<HashMap<String, Vec<PermissionRule>>>,
    /// 角色继承
    role_hierarchy: RwLock<HashMap<String, Vec<String>>>,
    /// 缓存时间
    last_refresh: RwLock<Instant>,
    /// 提供者名称
    name: String,
    /// 角色映射表(禁止用户名直接作为角色)
    role_mapping: RwLock<HashMap<String, Vec<String>>>,
}

impl Default for RbacPermissionProvider {
    fn default() -> Self {
        Self {
            roles: RwLock::new(HashMap::new()),
            permissions: RwLock::new(HashMap::new()),
            role_hierarchy: RwLock::new(HashMap::new()),
            last_refresh: RwLock::new(Instant::now()),
            name: "rbac".to_string(),
            role_mapping: RwLock::new(HashMap::new()),
        }
    }
}

/// RBAC 角色
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    /// 角色名称
    pub name: String,
    /// 角色描述
    #[serde(default)]
    pub description: String,
    /// 角色是否启用
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    /// 继承的角色
    #[serde(default)]
    pub extends: Vec<String>,
}

impl Default for Role {
    fn default() -> Self {
        Self {
            name: String::new(),
            description: String::new(),
            enabled: true,
            extends: Vec::new(),
        }
    }
}

impl RbacPermissionProvider {
    /// 创建 RBAC 权限提供者
    pub fn new() -> Self {
        Self {
            roles: RwLock::new(HashMap::new()),
            permissions: RwLock::new(HashMap::new()),
            role_hierarchy: RwLock::new(HashMap::new()),
            last_refresh: RwLock::new(Instant::now()),
            name: "rbac".to_string(),
            role_mapping: RwLock::new(HashMap::new()),
        }
    }

    /// 添加角色
    pub fn add_role(&self, role: Role) {
        if let Ok(mut roles) = self.roles.write() {
            roles.insert(role.name.clone(), role.clone());
        }
        if let Ok(mut hierarchy) = self.role_hierarchy.write() {
            hierarchy.insert(role.name, role.extends);
        }
    }

    /// 添加权限规则
    pub fn add_permission(&self, role: &str, rule: PermissionRule) {
        if let Ok(mut permissions) = self.permissions.write() {
            permissions.entry(role.to_string()).or_default().push(rule);
        }
    }

    /// 将角色分配给主体(用户)
    pub fn add_role_to_subject(&self, subject: &str, role: &str) {
        if let Ok(mut mapping) = self.role_mapping.write() {
            mapping.entry(subject.to_string()).or_default().push(role.to_string());
        }
    }

    /// 获取角色的所有权限(包括继承的)
    async fn get_role_permissions(&self, role: &str) -> Vec<PermissionRule> {
        let mut all_permissions = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let mut to_visit = vec![role.to_string()];

        let permissions = if let Ok(p) = self.permissions.read() {
            p
        } else {
            return Vec::new();
        };
        let hierarchy = if let Ok(h) = self.role_hierarchy.read() {
            h
        } else {
            return Vec::new();
        };

        while let Some(current_role) = to_visit.pop() {
            if visited.contains(&current_role) {
                continue;
            }
            visited.insert(current_role.clone());

            // 添加当前角色的权限
            if let Some(rules) = permissions.get(&current_role) {
                all_permissions.extend(rules.iter().cloned());
            }

            // 添加继承角色的权限
            if let Some(extends) = hierarchy.get(&current_role) {
                for parent_role in extends {
                    if !visited.contains(parent_role) {
                        to_visit.push(parent_role.clone());
                    }
                }
            }
        }

        all_permissions
    }
}

#[async_trait]
impl PermissionProvider for RbacPermissionProvider {
    async fn check_permission(&self, context: &PermissionContext) -> PermissionDecision {
        let subject_roles = self.get_subject_roles(&context.subject.id);

        // 获取所有角色的权限
        let mut all_rules = Vec::new();
        for role in &subject_roles {
            let rules = self.get_role_permissions(role).await;
            all_rules.extend(rules);
        }

        // 按优先级排序
        all_rules.sort_by(|a, b| b.priority.cmp(&a.priority));

        // 评估规则
        for rule in all_rules {
            if rule.enabled && matches_rule(&rule, context) {
                if rule.allow.contains(&context.action) {
                    return PermissionDecision::Allow;
                }
                if rule.deny.contains(&context.action) {
                    return PermissionDecision::Deny;
                }
            }
        }

        PermissionDecision::NotApplicable
    }

    async fn get_allowed_resources(&self, subject: &str) -> Vec<PermissionResource> {
        let subject_roles = self.get_subject_roles(subject);
        let mut resources = std::collections::HashSet::new();

        for role in &subject_roles {
            let rules = self.get_role_permissions(role).await;
            for rule in rules {
                if rule.enabled {
                    resources.insert(PermissionResource::new(&rule.resource));
                }
            }
        }

        resources.into_iter().collect()
    }

    async fn get_allowed_actions(&self, subject: &str, resource: &str) -> Vec<PermissionAction> {
        let subject_roles = self.get_subject_roles(subject);
        let mut actions = std::collections::HashSet::new();

        for role in &subject_roles {
            let rules = self.get_role_permissions(role).await;
            for rule in rules {
                if rule.enabled && (rule.resource == "*" || rule.resource == resource) {
                    for action in &rule.allow {
                        actions.insert(action.clone());
                    }
                }
            }
        }

        actions.into_iter().collect()
    }

    async fn refresh(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if let Ok(mut last_refresh) = self.last_refresh.write() {
            *last_refresh = Instant::now();
        }
        Ok(())
    }

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

impl RbacPermissionProvider {
    /// 获取主体的角色列表
    fn get_subject_roles(&self, subject: &str) -> Vec<String> {
        let mapping = match self.role_mapping.read() {
            Ok(m) => m,
            Err(_) => return Vec::new(),
        };
        let roles = match self.roles.read() {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        get_subject_roles(&mapping, &roles, subject)
    }

    /// 检查角色是否存在
    pub fn has_role(&self, role: &str) -> bool {
        if let Ok(roles) = self.roles.read() {
            roles.contains_key(role) || self.get_subject_roles(role).contains(&role.to_string())
        } else {
            false
        }
    }
}

/// 策略决策点配置
///
/// 用于 `PolicyDecisionPoint::with_config` 构造器,正确应用所有配置字段。
#[derive(Debug, Clone)]
pub struct PolicyDecisionPointConfig {
    /// 默认决策(当没有匹配规则时)
    pub default_decision: PermissionDecision,
    /// 是否记录拒绝的决策
    pub log_denied: bool,
    /// 缓存配置
    pub cache_ttl_seconds: u64,
    /// 是否启用缓存
    pub cache_enabled: bool,
}

impl Default for PolicyDecisionPointConfig {
    fn default() -> Self {
        Self {
            default_decision: PermissionDecision::Deny,
            log_denied: true,
            cache_ttl_seconds: 300,
            cache_enabled: true,
        }
    }
}

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

    #[tokio::test]
    async fn test_yaml_permission_provider() {
        // 使用 RBAC 提供者进行测试,因为它不需要配置文件
        let provider = Arc::new(RbacPermissionProvider::new());

        // 添加角色和权限
        provider.add_role(Role {
            name: "admin".to_string(),
            description: "管理员角色".to_string(),
            enabled: true,
            extends: vec![],
        });

        provider.add_permission(
            "admin",
            PermissionRule {
                name: "admin_select".to_string(),
                priority: 100,
                subject: "*".to_string(),
                resource: "users".to_string(),
                allow: vec![PermissionAction::Select],
                deny: vec![],
                condition: None,
                enabled: true,
            },
        );

        // 将用户 "admin" 映射到角色 "admin"
        provider.add_role_to_subject("admin", "admin");

        let pdp = PolicyDecisionPoint::new(provider);

        // 测试权限检查
        let result = pdp.check("admin", "users", "SELECT").await;
        assert_eq!(result, PermissionDecision::Allow);
    }

    #[tokio::test]
    async fn test_rbac_permission_provider() {
        let provider = Arc::new(RbacPermissionProvider::new());

        // 添加角色
        provider.add_role(Role {
            name: "admin".to_string(),
            description: "管理员角色".to_string(),
            enabled: true,
            extends: vec![],
        });

        // 添加权限规则
        provider.add_permission(
            "admin",
            PermissionRule {
                name: "admin_all".to_string(),
                priority: 100,
                subject: "*".to_string(),
                resource: "*".to_string(),
                allow: vec![
                    PermissionAction::Select,
                    PermissionAction::Insert,
                    PermissionAction::Update,
                    PermissionAction::Delete,
                ],
                deny: vec![],
                condition: None,
                enabled: true,
            },
        );

        // 将用户 "admin" 映射到角色 "admin"
        provider.add_role_to_subject("admin", "admin");

        let pdp = PolicyDecisionPoint::new(provider);

        // 测试权限检查
        let result = pdp.check("admin", "users", "SELECT").await;
        assert_eq!(result, PermissionDecision::Allow);

        let result = pdp.check("admin", "users", "DELETE").await;
        assert_eq!(result, PermissionDecision::Allow);
    }

    #[tokio::test]
    async fn test_permission_engine() {
        let provider = Arc::new(RbacPermissionProvider::new());

        // 添加角色
        provider.add_role(Role {
            name: "admin".to_string(),
            description: "管理员角色".to_string(),
            enabled: true,
            extends: vec![],
        });

        // 添加权限规则
        provider.add_permission(
            "admin",
            PermissionRule {
                name: "admin_all".to_string(),
                priority: 100,
                subject: "*".to_string(),
                resource: "*".to_string(),
                allow: vec![
                    PermissionAction::Select,
                    PermissionAction::Insert,
                    PermissionAction::Update,
                    PermissionAction::Delete,
                ],
                deny: vec![],
                condition: None,
                enabled: true,
            },
        );

        // 将用户 "admin" 映射到角色 "admin"
        provider.add_role_to_subject("admin", "admin");

        let pdp = PolicyDecisionPoint::new(provider);

        // 测试权限检查
        let decision = pdp.check("admin", "users", "SELECT").await;
        assert_eq!(decision, PermissionDecision::Allow);
    }

    #[tokio::test]
    async fn test_permission_context() {
        let context = PermissionContext::new(
            PermissionSubject::user("admin"),
            PermissionResource::new("users"),
            PermissionAction::Select,
        )
        .with_attribute("ip", "192.168.1.1")
        .with_environment("time", "2024-01-01");

        assert_eq!(context.subject.id, "admin");
        assert_eq!(context.resource.name, "users");
        assert_eq!(context.action, PermissionAction::Select);
        assert!(context.attributes.contains_key("ip"));
    }

    #[tokio::test]
    async fn test_policy_decision_point_with_rate_limit() {
        let provider = Arc::new(RbacPermissionProvider::new());

        // 添加角色
        provider.add_role(Role {
            name: "admin".to_string(),
            description: "管理员角色".to_string(),
            enabled: true,
            extends: vec![],
        });

        // 添加权限规则
        provider.add_permission(
            "admin",
            PermissionRule {
                name: "admin_select".to_string(),
                priority: 100,
                subject: "*".to_string(),
                resource: "users".to_string(),
                allow: vec![PermissionAction::Select],
                deny: vec![],
                condition: None,
                enabled: true,
            },
        );

        // 将用户 "admin" 映射到角色 "admin"
        provider.add_role_to_subject("admin", "admin");

        // 创建带速率限制的 PDP
        let pdp = PolicyDecisionPoint::with_rate_limit(provider, 10, 60);

        // 前 10 次请求应该成功
        for i in 0..10 {
            let result = pdp.check("admin", "users", "SELECT").await;
            assert_eq!(result, PermissionDecision::Allow, "Request {} should be allowed", i);
        }

        // 第 11 次请求应该被速率限制
        let result = pdp.check("admin", "users", "SELECT").await;
        assert_eq!(result, PermissionDecision::Deny);
    }

    #[tokio::test]
    async fn test_permission_subject_creation() {
        // 测试用户主体
        let user = PermissionSubject::user("test_user");
        assert_eq!(user.id, "test_user");
        assert_eq!(user.subject_type, SubjectType::User);

        // 测试角色主体
        let role = PermissionSubject::role("admin");
        assert_eq!(role.id, "admin");
        assert_eq!(role.subject_type, SubjectType::Role);
    }

    #[tokio::test]
    async fn test_permission_resource_creation() {
        // 测试基本资源
        let resource = PermissionResource::new("users");
        assert_eq!(resource.name, "users");
        assert_eq!(resource.resource_type, "table");

        // 测试带类型的资源
        let resource_with_type = PermissionResource::with_type("logs", "log");
        assert_eq!(resource_with_type.name, "logs");
        assert_eq!(resource_with_type.resource_type, "log");
    }

    #[tokio::test]
    async fn test_permission_decision_types() {
        assert_eq!(PermissionDecision::Allow, PermissionDecision::Allow);
        assert_eq!(PermissionDecision::Deny, PermissionDecision::Deny);
        assert_eq!(PermissionDecision::NotApplicable, PermissionDecision::NotApplicable);

        let error_decision = PermissionDecision::Error("Test error".to_string());
        assert!(matches!(error_decision, PermissionDecision::Error(msg) if msg == "Test error"));
    }

    #[tokio::test]
    async fn test_role_creation() {
        let role = Role {
            name: "test_role".to_string(),
            description: "测试角色".to_string(),
            enabled: true,
            extends: vec!["base_role".to_string()],
        };

        assert_eq!(role.name, "test_role");
        assert_eq!(role.description, "测试角色");
        assert!(role.enabled);
        assert_eq!(role.extends.len(), 1);
        assert_eq!(role.extends[0], "base_role");
    }

    #[tokio::test]
    async fn test_permission_rule_creation() {
        let rule = PermissionRule {
            name: "test_rule".to_string(),
            priority: 50,
            subject: "admin".to_string(),
            resource: "users".to_string(),
            allow: vec![PermissionAction::Select, PermissionAction::Insert],
            deny: vec![PermissionAction::Delete],
            condition: Some("active = true".to_string()),
            enabled: true,
        };

        assert_eq!(rule.name, "test_rule");
        assert_eq!(rule.priority, 50);
        assert_eq!(rule.allow.len(), 2);
        assert_eq!(rule.deny.len(), 1);
        assert!(rule.enabled);
        assert!(rule.condition.is_some());
    }

    #[tokio::test]
    async fn test_role_hierarchy() {
        let provider = RbacPermissionProvider::new();

        // 添加角色及其继承
        let base_role = Role {
            name: "base_user".to_string(),
            description: "基础用户角色".to_string(),
            enabled: true,
            extends: vec![],
        };
        provider.add_role(base_role);

        let child_role = Role {
            name: "premium_user".to_string(),
            description: "高级用户角色".to_string(),
            enabled: true,
            extends: vec!["base_user".to_string()],
        };
        provider.add_role(child_role.clone());

        // 验证角色存在
        assert!(provider.has_role("base_user"));
        assert!(provider.has_role("premium_user"));
    }
}