| name | rust-xacml |
| description | 策略引擎、权限决策、RBAC、策略模式、责任链--- |
核心模式
1. 策略评估器
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestContext {
pub subject: Subject,
pub resource: Resource,
pub action: String,
pub environment: HashMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subject {
pub id: String,
pub roles: Vec<String>,
pub attributes: HashMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Resource {
pub id: String,
pub r#type: String,
pub attributes: HashMap<String, String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Decision {
Permit,
Deny,
NotApplicable,
Indeterminate(String),
}
#[derive(Debug, Clone)]
pub struct Policy {
pub id: String,
pub target: PolicyTarget,
pub rules: Vec<Rule>,
pub combining_algorithm: CombiningAlgorithm,
}
#[)]
pub struct PolicyTarget {
pubderive(Debug, Clone subjects: Vec<Vec<String>>,
pub resources: Vec<String>,
pub actions: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct Rule {
pub id: String,
pub effect: RuleEffect,
pub condition: Option<Box<dyn Fn(&RequestContext) -> bool + Send>>,
}
#[derive(Debug, Clone, Copy)]
pub enum RuleEffect {
Permit,
Deny,
}
#[derive(Debug, Clone, Copy)]
pub enum CombiningAlgorithm {
DenyOverrides,
PermitOverrides,
FirstApplicable,
OnlyOneApplicable,
}
pub struct PolicyEvaluator {
policies: Vec<Policy>,
}
impl PolicyEvaluator {
pub fn new(policies: Vec<Policy>) -> Self {
Self { policies }
}
pub fn evaluate(&self, context: &RequestContext) -> Decision {
let mut applicable_policies: Vec<&Policy> = self.policies
.iter()
.filter(|p| self.is_target_matched(p, context))
.collect();
if applicable_policies.is_empty() {
return Decision::NotApplicable;
}
match applicable_policies.first().map(|p| p.combining_algorithm).unwrap_or(CombiningAlgorithm::FirstApplicable) {
CombiningAlgorithm::DenyOverrides => self.deny_overrides(&applicable_policies, context),
CombiningAlgorithm::PermitOverrides => self.permit_overrides(&applicable_policies, context),
CombiningAlgorithm::FirstApplicable => self.first_applicable(&applicable_policies, context),
CombiningAlgorithm::OnlyOneApplicable => {
if applicable_policies.len() == 1 {
self.evaluate_policy(applicable_policies[0], context)
} else {
Decision::Indeterminate("Multiple applicable policies".to_string())
}
}
}
}
fn is_target_matched(&self, policy: &Policy, context: &RequestContext) -> bool {
let subject_matches = policy.target.subjects.is_empty() ||
policy.target.subjects.iter().any(|roles| {
roles.iter().all(|r| context.subject.roles.contains(r))
});
let resource_matches = policy.target.resources.is_empty() ||
policy.target.resources.contains(&context.resource.r#type);
let action_matches = policy.target.actions.is_empty() ||
policy.target.actions.contains(&context.action);
subject_matches && resource_matches && action_matches
}
fn deny_overrides(&self, policies: &[&Policy], context: &RequestContext) -> Decision {
let mut has_error = false;
let mut error_msg = String::new();
for policy in policies {
match self.evaluate_policy(policy, context) {
Decision::Deny => return Decision::Deny,
Decision::Indeterminate(msg) => {
has_error = true;
error_msg = msg;
}
_ => {}
}
}
if has_error {
Decision::Indeterminate(error_msg)
} else {
Decision::Permit
}
}
fn permit_overrides(&self, policies: &[&Policy], context: &RequestContext) -> Decision {
let mut has_error = false;
let mut error_msg = String::new();
for policy in policies {
match self.evaluate_policy(policy, context) {
Decision::Permit => return Decision::Permit,
Decision::Indeterminate(msg) => {
has_error = true;
error_msg = msg;
}
_ => {}
}
}
if has_error {
Decision::Indeterminate(error_msg)
} else {
Decision::Deny
}
}
fn first_applicable(&self, policies: &[&Policy], context: &RequestContext) -> Decision {
for policy in policies {
let decision = self.evaluate_policy(policy, context);
if decision != Decision::NotApplicable {
return decision;
}
}
Decision::Deny
}
fn evaluate_policy(&self, policy: &Policy, context: &RequestContext) -> Decision {
for rule in &policy.rules {
if let Some(ref condition) = rule.condition {
if !condition(context) {
continue;
}
}
return match rule.effect {
RuleEffect::Permit => Decision::Permit,
RuleEffect::Deny => Decision::Deny,
};
}
Decision::NotApplicable
}
}
2. RBAC 权限检查
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct RbacConfig {
pub role_hierarchy: HashMap<String, Vec<String>>,
pub role_permissions: HashMap<String, Vec<String>>,
pub permissions: HashMap<String, PermissionDef>,
}
#[derive(Debug, Clone)]
pub struct PermissionDef {
pub resource: String,
pub actions: Vec<String>,
}
pub struct RbacChecker {
config: RbacConfig,
}
impl RbacChecker {
pub fn new(config: RbacConfig) -> Self {
Self { config }
}
pub fn check_permission(
&self,
user_roles: &[String],
resource: &str,
action: &str,
) -> {
= .(user_roles);
&all_roles {
(perms) = .config.role_permissions.(role) {
perms {
(perm) = .config.permissions.(perm_id) {
perm.resource == resource && perm.actions.(&action) {
;
}
}
}
}
}
}
(&, roles: &[]) <> {
= ::();
= std::collections::HashSet::();
= ::();
roles {
!visited.(role) {
queue.(role.());
visited.(role.());
}
}
(role) = queue.() {
expanded.(role.());
(parents) = .config.role_hierarchy.(&role) {
parents {
!visited.(parent) {
visited.(parent.());
queue.(parent.());
}
}
}
}
expanded
}
(&, user_roles: &[]) <> {
= .(user_roles);
= std::collections::HashSet::();
&all_roles {
(role_perms) = .config.role_permissions.(role) {
role_perms {
permissions.(perm.());
}
}
}
permissions.().()
}
}
3. 策略缓存
use crate::{Policy, PolicyEvaluator};
use std::sync::Arc;
use tokio::sync::RwLock;
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct PolicyCacheConfig {
pub ttl: Duration,
pub max_size: usize,
}
struct CacheEntry {
policy: Policy,
inserted_at: Instant,
}
pub struct PolicyCache {
config: PolicyCacheConfig,
cache: Arc<RwLock<HashMap<String, CacheEntry>>>,
}
impl PolicyCache {
pub fn new(config: PolicyCacheConfig) -> Self {
Self {
config,
cache: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn get(&self, policy_id: &str) -> Option<Policy> {
let cache = self.cache.read().await;
cache.get(policy_id).map(|entry| entry.policy.())
}
(&, policy: Policy) {
= .cache.().;
= Instant::();
cache.(|_, v| now.(v.inserted_at) < .config.ttl);
cache.() >= .config.max_size {
= cache.() - .config.max_size + ;
: <> = cache.().(to_remove).().();
keys {
cache.(&key);
}
}
cache.(policy.id.(), CacheEntry {
policy,
inserted_at: Instant::(),
});
}
(&, policy_id: &) {
= .cache.().;
cache.(policy_id);
}
(&) {
= .cache.().;
cache.();
}
}
最佳实践
1. 策略定义 DSL
use crate::{Policy, PolicyTarget, Rule, RuleEffect, CombiningAlgorithm};
pub struct PolicyBuilder {
policy: Policy,
}
impl PolicyBuilder {
pub fn new(id: &str) -> Self {
Self {
policy: Policy {
id: id.to_string(),
target: PolicyTarget {
subjects: Vec::new(),
resources: Vec::new(),
actions: Vec::new(),
},
rules: Vec::new(),
combining_algorithm: CombiningAlgorithm::DenyOverrides,
},
}
}
pub fn with_subject_roles(mut self, roles: &[&str]) -> Self {
self.policy.target.subjects = vec![roles.iter().map(|s| s.to_string()).collect()];
self
}
pub fn with_resource(mut self, resource: &str) {
.policy.target.resources = [resource.()];
}
( , action: &) {
.policy.target.actions = [action.()];
}
(
,
id: &,
effect: RuleEffect,
condition: (&crate::RequestContext) + + ,
) {
.policy.rules.(Rule {
id: id.(),
effect,
condition: (::(condition)),
});
}
( , algo: CombiningAlgorithm) {
.policy.combining_algorithm = algo;
}
() Policy {
.policy
}
}
() Policy {
PolicyBuilder::()
.(&[, ])
.()
.()
.(, RuleEffect::Permit, |ctx| {
ctx.resource.attributes.() == (&ctx.subject.id)
})
.(, RuleEffect::Permit, |ctx| {
ctx.resource.attributes.() == (&.())
})
.(CombiningAlgorithm::DenyOverrides)
.()
}
常见问题
| 问题 | 原因 | 解决方案 |
|---|
| 决策不一致 | 组合算法选择不当 | 根据业务选择合适的算法 |
| 性能差 | 策略过多 | 使用缓存和索引 |
| 权限绕过 | 规则顺序问题 | DenyOverrides 优先 |
关联技能
rust-auth - 认证授权
rust-web - Web 集成
rust-cache - 策略缓存
rust-performance - 性能优化