dbnexus 0.1.3

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
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
// 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::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(())
//! }
//! ```

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::Instant;

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

/// 额外的危险路径模式列表(用于白名单验证)
static DANGEROUS_PATH_PATTERNS: &[&str] = &[
    "/etc/passwd",
    "/etc/shadow",
    "/etc/sudoers",
    "/root/.ssh",
    "/proc/self",
    "/sys/kernel",
    "C:\\Windows\\System32",
    "..\\..\\",
];

/// 权限操作类型
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionAction {
    /// 查询操作
    Select,
    /// 插入操作
    Insert,
    /// 更新操作
    Update,
    /// 删除操作
    Delete,
    /// 所有操作
    All,
}

impl std::fmt::Display for PermissionAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PermissionAction::Select => write!(f, "SELECT"),
            PermissionAction::Insert => write!(f, "INSERT"),
            PermissionAction::Update => write!(f, "UPDATE"),
            PermissionAction::Delete => write!(f, "DELETE"),
            PermissionAction::All => write!(f, "*"),
        }
    }
}

/// 权限资源
#[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
}

/// 权限提供者 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)]
pub struct PolicyDecisionPoint {
    /// 权限提供者
    provider: Arc<dyn PermissionProvider>,
    /// 缓存(使用 DashMap 实现细粒度锁)
    cache: DashMap<String, CachedDecision>,
    /// 缓存配置
    cache_ttl_seconds: u64,
    /// 是否启用缓存
    cache_enabled: bool,
}

impl PolicyDecisionPoint {
    /// 创建策略决策点(默认 TTL 5 分钟)
    pub fn new(provider: Arc<dyn PermissionProvider>) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds: 300, // 5 分钟
            cache_enabled: true,
        }
    }

    /// 创建带缓存配置的策略决策点
    pub fn with_cache(provider: Arc<dyn PermissionProvider>, cache_ttl_seconds: u64) -> Self {
        Self {
            provider,
            cache: DashMap::new(),
            cache_ttl_seconds,
            cache_enabled: true,
        }
    }

    /// 检查权限(带 TTL 缓存)
    pub async fn check_permission(&self, context: &PermissionContext) -> PermissionDecision {
        // 生成缓存键
        let cache_key = self.generate_cache_key(context);

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

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

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

        decision
    }

    /// 检查用户是否有权限执行操作
    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> {
        // 验证配置文件路径安全性
        let path = std::path::Path::new(config_path);

        // 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());
        }

        // 3. 检查空字节注入
        if config_path.as_bytes().contains(&0) {
            return Err("Config path contains null byte".to_string());
        }

        // 4. 检查路径是否为绝对路径或在允许的相对路径范围内
        if !path.is_absolute() {
            // 相对路径需要进一步验证
            let canonical = std::fs::canonicalize(path)
                .map_err(|_| "Cannot resolve config path, it may not exist or is inaccessible".to_string())?;

            // 检查规范化后的路径是否包含 ..
            let canonical_str = canonical.to_string_lossy();
            if canonical_str.contains("..") {
                return Err("Config path resolves to invalid parent directory reference".to_string());
            }

            // 检查是否在允许的目录内(当前目录或 config 子目录)
            let current_dir = std::env::current_dir().map_err(|_| "Cannot determine current directory".to_string())?;
            let allowed_dirs = [
                current_dir.clone(),
                current_dir.join("config"),
                current_dir.join("permissions"),
                current_dir.join("etc"),
            ];

            let mut is_allowed = false;
            for allowed in &allowed_dirs {
                if let Ok(allowed_canonical) = std::fs::canonicalize(allowed) {
                    if canonical.starts_with(&allowed_canonical) {
                        is_allowed = true;
                        break;
                    }
                }
            }

            if !is_allowed {
                return Err("Config path is not in allowed directory".to_string());
            }
        } else {
            // 绝对路径检查
            // 检查是否在系统关键目录外
            let forbidden_prefixes = [
                std::path::Path::new("/etc"),
                std::path::Path::new("/usr"),
                std::path::Path::new("/var"),
                std::path::Path::new("/root"),
                std::path::Path::new("/boot"),
                std::path::Path::new("/sys"),
                std::path::Path::new("/proc"),
            ];

            let canonical = std::fs::canonicalize(path).map_err(|_| "Cannot resolve config path".to_string())?;

            for prefix in &forbidden_prefixes {
                if canonical.starts_with(prefix) {
                    return Err("Config path is in system directory, which is not allowed".to_string());
                }
            }
        }

        // 5. 检查是否为符号链接
        if path.is_symlink() {
            return Err("Config path cannot be a symbolic link".to_string());
        }

        // 6. 检查文件是否存在且可读
        if !path.exists() {
            return Err("Config file does not exist".to_string());
        }
        if !path.is_file() {
            return Err("Config path must point to a file".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>> {
        let content = tokio::fs::read_to_string(&self.config_path).await?;

        // 解析 YAML 配置(支持角色和主体映射)
        #[derive(Debug, Deserialize)]
        struct YamlConfig {
            roles: HashMap<String, Vec<PermissionRule>>,
            #[serde(default)]
            subjects: HashMap<String, Vec<String>>,
        }

        let config: YamlConfig = serde_yaml::from_str(&content)?;

        // 更新角色权限
        if let Ok(mut roles) = self.roles.write() {
            *roles = config.roles;
        }

        // 加载主体-角色映射
        if let Ok(mut role_mapping) = self.role_mapping.write() {
            role_mapping.clear();
            for (subject, roles_list) in config.subjects {
                role_mapping.insert(subject, roles_list);
            }
        }

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

        Ok(())
    }

    /// 检查规则是否匹配
    fn matches_rule(&self, 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) || rule.allow.contains(&PermissionAction::All);
        let in_deny = rule.deny.contains(&context.action) || rule.deny.contains(&PermissionAction::All);

        // 如果操作既不在 allow 也不在 deny 中,则不匹配
        if !in_allow && !in_deny && context.action != PermissionAction::All {
            return false;
        }

        true
    }
}

#[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 && self.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) || rule.allow.contains(&PermissionAction::All) {
                return PermissionDecision::Allow;
            }
            // 检查 Deny 规则
            if rule.deny.contains(&context.action) || rule.deny.contains(&PermissionAction::All) {
                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> {
        // 优先从角色映射中获取
        if let Ok(mapping) = self.role_mapping.read() {
            if let Some(roles) = mapping.get(subject) {
                return roles.clone();
            }
        }
        // 如果没有映射,尝试直接将主体名作为角色名(用于简单用例)
        // 但要确保只返回预定义的角色(防止安全问题)
        if let Ok(roles) = self.roles.read() {
            if roles.contains_key(subject) {
                return vec![subject.to_string()];
            }
        }
        Vec::new()
    }
}

/// 基于 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 && self.matches_rule(&rule, context) {
                if rule.allow.contains(&context.action) || rule.allow.contains(&PermissionAction::All) {
                    return PermissionDecision::Allow;
                }
                if rule.deny.contains(&context.action) || rule.deny.contains(&PermissionAction::All) {
                    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> {
        // 优先从角色映射中获取
        if let Ok(mapping) = self.role_mapping.read() {
            if let Some(roles) = mapping.get(subject) {
                return roles.clone();
            }
        }
        // 如果没有映射,检查 subject 本身是否是预定义的角色
        if let Ok(roles) = self.roles.read() {
            if roles.contains_key(subject) {
                return vec![subject.to_string()];
            }
        }
        Vec::new()
    }

    /// 检查规则是否匹配
    fn matches_rule(&self, 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;
        }
        true
    }
}

/// 权限引擎配置
#[derive(Debug, Clone)]
pub struct PermissionEngineConfig {
    /// 默认决策(当没有匹配规则时)
    pub default_decision: PermissionDecision,
    /// 是否记录拒绝的决策
    pub log_denied: bool,
    /// 缓存配置
    pub cache_ttl_seconds: u64,
    /// 是否启用缓存
    pub cache_enabled: bool,
}

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

/// 权限引擎
/// 统一的权限管理入口
#[derive(Debug)]
pub struct PermissionEngine {
    /// 策略决策点
    pdp: PolicyDecisionPoint,
    /// 配置
    config: PermissionEngineConfig,
}

impl PermissionEngine {
    /// 创建权限引擎
    pub fn new(provider: Arc<dyn PermissionProvider>) -> Self {
        let config = PermissionEngineConfig::default();
        Self {
            pdp: PolicyDecisionPoint::with_cache(provider, config.cache_ttl_seconds),
            config,
        }
    }

    /// 创建带配置的权限引擎
    pub fn with_config(provider: Arc<dyn PermissionProvider>, config: PermissionEngineConfig) -> Self {
        Self {
            pdp: PolicyDecisionPoint::with_cache(provider, config.cache_ttl_seconds),
            config,
        }
    }

    /// 检查权限
    pub async fn check(&self, subject: &str, resource: &str, action: &str) -> bool {
        let decision = self.pdp.check(subject, resource, action).await;
        decision == PermissionDecision::Allow
    }

    /// 检查权限(带详细决策)
    pub async fn check_with_decision(&self, subject: &str, resource: &str, action: &str) -> PermissionDecision {
        self.pdp.check(subject, resource, action).await
    }

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

    /// 刷新权限缓存
    pub async fn refresh(&self) {
        self.pdp.refresh_cache().await;
    }
}

#[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 engine = PermissionEngine::new(provider);

        // 测试权限检查
        let allowed = engine.check("admin", "users", "SELECT").await;
        assert!(allowed);
    }

    #[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"));
    }
}