use super::auth::{normalize_path, PathPattern};
use super::{best_rule, rule_specificity, CurrentUser, RuleKey};
use crate::router::RouteEntry;
use axum::{body::Body, extract::Request, response::Response};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use tower::{Layer, Service};
use wordval_core::api::ApiError;
#[derive(Debug, Clone)]
pub struct PermissionRule {
pub path: String,
pub methods: Vec<String>,
pub permission: String,
pub is_guard: bool,
}
struct CompiledRule {
pattern: PathPattern,
methods: Vec<String>,
permission: String,
is_guard: bool,
specificity: (usize, usize),
}
impl CompiledRule {
fn compile(rule: &PermissionRule) -> Self {
Self {
pattern: PathPattern::compile(&rule.path),
methods: rule.methods.clone(),
permission: rule.permission.clone(),
is_guard: rule.is_guard,
specificity: rule_specificity(&rule.path),
}
}
}
impl RuleKey for CompiledRule {
fn pattern(&self) -> &PathPattern {
&self.pattern
}
fn methods(&self) -> &[String] {
&self.methods
}
fn is_guard(&self) -> bool {
self.is_guard
}
fn specificity(&self) -> (usize, usize) {
self.specificity
}
}
fn match_compiled<'a>(rules: &'a [CompiledRule], path: &str, method: &str) -> Option<&'a CompiledRule> {
best_rule(rules, path, method)
}
#[derive(Clone)]
pub struct PermissionCheckLayer {
pub rules: Arc<Vec<PermissionRule>>,
compiled: Arc<OnceLock<Arc<Vec<CompiledRule>>>>,
}
impl PermissionCheckLayer {
pub fn empty() -> Self {
Self {
rules: Arc::new(Vec::new()),
compiled: Arc::new(OnceLock::new()),
}
}
pub fn from_config(config_rules: &[wordval_config::PermissionRule]) -> Self {
Self::empty().with_config_rules(config_rules, "")
}
pub fn from_config_with_prefix(
config_rules: &[wordval_config::PermissionRule],
prefix: &str,
) -> Self {
Self::empty().with_config_rules(config_rules, prefix)
}
pub fn with_config_rules(
mut self,
config_rules: &[wordval_config::PermissionRule],
prefix: &str,
) -> Self {
Arc::make_mut(&mut self.rules).extend(config_rules.iter().map(|r| PermissionRule {
path: super::auth::join_route_path(prefix, &r.path),
methods: r.methods.clone(),
permission: r.permission.clone(),
is_guard: false,
}));
self
}
pub fn with_route_guards(mut self, routes: &[RouteEntry], prefix: &str) -> Self {
let rules = Arc::make_mut(&mut self.rules);
rules.reserve(routes.len());
for r in routes {
let Some(permission) = r.guard.permission.as_deref() else {
continue;
};
rules.push(PermissionRule {
path: super::auth::join_route_path(prefix, &r.path),
methods: vec![r.method.clone()],
permission: permission.to_string(),
is_guard: true,
});
}
self
}
pub fn has_rules(&self) -> bool {
!self.rules.is_empty()
}
pub fn has_guard_rules(&self) -> bool {
self.rules.iter().any(|r| r.is_guard)
}
}
impl<S> Layer<S> for PermissionCheckLayer {
type Service = PermissionCheckService<S>;
fn layer(&self, inner: S) -> Self::Service {
let rules = self
.compiled
.get_or_init(|| Arc::new(self.rules.iter().map(CompiledRule::compile).collect()))
.clone();
PermissionCheckService { inner, rules }
}
}
#[derive(Clone)]
pub struct PermissionCheckService<S> {
inner: S,
rules: Arc<Vec<CompiledRule>>,
}
impl<S> Service<Request<Body>> for PermissionCheckService<S>
where
S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let rejection: Option<ApiError> = {
let normalized_path = normalize_path(req.uri().path());
let method = req.method().as_str();
match match_compiled(&self.rules, &normalized_path, method) {
Some(rule) => {
let has_perm = match req.extensions().get::<CurrentUser>() {
Some(s) => {
tracing::debug!(
"权限检查: path={}, required={}, user_perms={:?}",
normalized_path,
rule.permission,
s.permissions
);
s.is_authorized(&rule.permission)
}
None => {
tracing::debug!(
"权限检查: path={}, required={}, CurrentUser 未注入 (auth 中间件未执行)",
normalized_path,
rule.permission
);
false
}
};
if has_perm {
None
} else {
Some(ApiError::forbidden("无权限访问"))
}
}
None => None,
}
};
let replacement = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, replacement);
match rejection {
Some(err) => {
let resp = super::error_response(err);
Box::pin(async move { Ok(resp) })
}
None => Box::pin(async move { inner.call(req).await }),
}
}
}
#[cfg(test)]
mod tests {
use super::{match_compiled, normalize_path, CompiledRule, PermissionCheckLayer};
use crate::router::{RouteEntry, RouteGuard};
use wordval_config::PermissionRule;
fn match_rule(
layer: &PermissionCheckLayer,
path: &str,
method: &str,
) -> Option<(String, bool)> {
let compiled: Vec<CompiledRule> =
layer.rules.iter().map(CompiledRule::compile).collect();
let normalized = normalize_path(path);
match_compiled(&compiled, &normalized, method)
.map(|r| (r.permission.clone(), r.is_guard))
}
fn config_rule(path: &str, methods: &[&str], permission: &str) -> PermissionRule {
PermissionRule {
path: path.to_string(),
methods: methods.iter().map(|s| s.to_string()).collect(),
permission: permission.to_string(),
}
}
fn guard_route(method: &str, path: &str, permission: &str) -> RouteEntry {
RouteEntry {
method: method.to_string(),
path: path.to_string(),
guard: RouteGuard::permission(permission),
}
}
#[test]
fn guard_rule_wins_over_config_rule() {
let layer =
PermissionCheckLayer::from_config(&[config_rule("/users", &["GET"], "config:weak")])
.with_route_guards(&[guard_route("GET", "/users", "guard:strong")], "");
let (perm, is_guard) = match_rule(&layer, "/users", "GET").unwrap();
assert!(is_guard);
assert_eq!(perm, "guard:strong");
}
#[test]
fn head_uses_explicit_rule_before_get_fallback() {
let layer = PermissionCheckLayer::empty().with_route_guards(
&[
guard_route("GET", "/users", "user:list"),
guard_route("HEAD", "/users", "user:head"),
guard_route("GET", "/orders", "order:list"),
],
"",
);
assert_eq!(
match_rule(&layer, "/users", "HEAD").unwrap().0,
"user:head"
);
assert_eq!(
match_rule(&layer, "/orders", "HEAD").unwrap().0,
"order:list"
);
let layer = PermissionCheckLayer::from_config(&[config_rule(
"/orders",
&[],
"config:weak",
)])
.with_route_guards(&[guard_route("GET", "/orders", "guard:strong")], "");
assert_eq!(
match_rule(&layer, "/orders", "HEAD").unwrap().0,
"guard:strong"
);
}
#[test]
fn most_specific_rule_wins_within_same_source() {
let layer = PermissionCheckLayer::from_config(&[
config_rule("/admin", &[], "admin:any"),
config_rule("/admin/{id}", &[], "admin:detail"),
config_rule("/admin/{id}/delete", &[], "admin:delete"),
]);
let (perm, _) = match_rule(&layer, "/admin/5/delete", "GET").unwrap();
assert_eq!(perm, "admin:delete");
let (perm, _) = match_rule(&layer, "/admin/5", "GET").unwrap();
assert_eq!(perm, "admin:detail");
}
#[test]
fn method_binding_respected() {
let layer =
PermissionCheckLayer::from_config(&[config_rule("/orders", &["POST"], "order:create")]);
assert!(match_rule(&layer, "/orders", "POST").is_some());
assert!(match_rule(&layer, "/orders", "GET").is_none());
assert!(match_rule(&layer, "/orders", "post").is_some()); }
#[test]
fn guard_rules_not_disabled_by_config_switch() {
let layer = PermissionCheckLayer::empty()
.with_route_guards(&[guard_route("GET", "/users", "user:list")], "");
assert!(layer.has_rules());
assert!(layer.has_guard_rules());
}
#[test]
fn prefix_joined_rules_match_final_path() {
let layer = PermissionCheckLayer::from_config_with_prefix(
&[config_rule("/users", &["GET"], "user:list")],
"/api",
);
assert!(match_rule(&layer, "/api/users", "GET").is_some());
assert!(match_rule(&layer, "/users", "GET").is_none());
}
#[test]
fn guard_rule_joined_with_prefix_matches_final_path() {
let layer = PermissionCheckLayer::empty()
.with_route_guards(&[guard_route("GET", "/admin/stats", "admin:read")], "/api");
let (perm, is_guard) = match_rule(&layer, "/api/admin/stats", "GET").unwrap();
assert!(is_guard);
assert_eq!(perm, "admin:read");
assert!(match_rule(&layer, "/admin/stats", "GET").is_none());
}
#[test]
fn routes_without_permission_contribute_no_rules() {
let plain = RouteEntry {
method: "GET".to_string(),
path: "/health".to_string(),
guard: RouteGuard::default(),
};
let layer = PermissionCheckLayer::empty().with_route_guards(
&[plain, guard_route("GET", "/admin", "admin:read")],
"",
);
assert_eq!(layer.rules.len(), 1);
assert!(match_rule(&layer, "/health", "GET").is_none());
}
}