用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/huiali/rust-skills --skill rust-xacml命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Actor model expert covering message passing, state isolation, supervision trees, deadlock prevention, fault tolerance, Actix framework, and Erlang-style concurrency patterns.
Rust anti-patterns and common mistakes expert. Handles code review issues with clone abuse, unwrap in production, String misuse, index loops, and refactoring guidance.
Advanced async patterns expert covering Stream implementation, zero-copy buffers, tokio::spawn lifetimes, plugin system scheduling, tonic streaming, and async lifetime management.
正在显示 SKILL.md
基于 SOC 职业分类
| name | rust-xacml |
| description | 策略引擎、权限决策、RBAC、策略模式、责任链--- |
//! 策略评估器
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, // Deny 优先
PermitOverrides, // Permit 优先
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 {
// 检查 Subjects
let subject_matches = policy.target.subjects.is_empty() ||
policy.target.subjects.iter().any(|roles| {
roles.iter().all(|r| context.subject.roles.contains(r))
});
// 检查 Resources
let resource_matches = policy.target.resources.is_empty() ||
policy.target.resources.contains(&context.resource.r#type);
// 检查 Actions
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
}
}
//! RBAC 权限检查
use std::collections::HashMap;
/// RBAC 配置
#[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>,
}
/// RBAC 检查器
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.().()
}
}
//! 策略缓存
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.();
}
}
//! 策略构建器
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 - 性能优化