wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
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
//! 路径权限校验中间件(路由守卫 + 配置规则联合校验)
//!
//! 规则匹配采用确定性优先级(与审计层共用 [`best_rule`]):
//! 1. 路由守卫(`#[wordval::get(path, permission = "...")]`)规则优先于配置文件
//!    规则——路由自身声明的策略不能被普通配置规则静默削弱;
//! 2. 同一来源内取**最具体**的匹配规则(静态段数越多越具体);
//! 3. 同具体程度按注册顺序取第一条。

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 {
    /// URL 路径(支持 `{param}` 单段、`{*rest}` / `/*` 尾部通配)
    pub path: String,
    /// 适用的 HTTP 方法列表(空表示所有方法)
    pub methods: Vec<String>,
    /// 所需权限标识
    pub permission: String,
    /// 是否来自路由守卫(守卫规则优先于配置规则)
    pub is_guard: bool,
}

/// 装配期预编译的权限规则(请求期匹配零规则分配)
struct CompiledRule {
    /// 预编译路径模式
    pattern: PathPattern,
    /// 适用的 HTTP 方法(空 = 所有方法)
    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
    }
}

/// 单次遍历选出最优规则(委托给共用的 [`best_rule`]:守卫优先 + 最具体优先)
fn match_compiled<'a>(rules: &'a [CompiledRule], path: &str, method: &str) -> Option<&'a CompiledRule> {
    best_rule(rules, path, method)
}

/// 路径级权限校验中间件(路由守卫 + 配置规则联合校验)
///
/// 合并 `config.toml` 中 `[middleware.permission.rules]` 的静态规则
/// 和路由守卫声明的权限要求。
#[derive(Clone)]
pub struct PermissionCheckLayer {
    /// 权限规则列表。
    /// Arc 共享:axum 的 `Router::layer` 对每个路由端点 clone 本层
    /// (path_router.rs:297 `endpoint.layer(layer.clone())`),裸 Vec 会被
    /// 深拷贝出 E×R 份规则字符串(R≈E 时为启动期 O(N²) 分配);Arc 使
    /// 逐端点 clone 退化为引用计数 +1,全端点共享同一份规则。
    pub rules: Arc<Vec<PermissionRule>>,
    /// 首次 layer() 编译一次,此后 rules 不得再变更。
    /// OnceLock 本体经 Arc 包裹,理由同上——裸 OnceLock 的 clone 在未初始化
    /// 时产生空副本,会被击穿为逐端点重编译;Arc 共享后全部端点复用同一
    /// 缓存单元格,编译恰好一次。
    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 {
        // 构建期引用计数仍为 1,make_mut 零拷贝;仅当 clone 后再构建才 COW
        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
    }

    /// 从已注册路由的守卫元数据派生权限规则
    ///
    /// `routes` 来自 `WordvalRouter::list_routes()`,路径已含 `group` / `merge`
    /// 的前缀,这里只再拼接全局前缀,因此规则路径与实际请求路径必然同源。
    pub fn with_route_guards(mut self, routes: &[RouteEntry], prefix: &str) -> Self {
        // 预留容量一次到位,避免 push 增容反复 realloc
        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 {
        // 编译一次、全端点共享:OnceLock 本体经 Arc 跨端点 clone 共享(见字段文档),
        // 避免原实现 O(路由数×规则数) 的逐端点重编译与 N 份独立内存副本
        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,
    /// 预编译的权限规则(Arc 共享,克隆廉价)
    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 {
        // 每请求仅 normalize 一次(规范路径零分配借用);规则匹配与授权判定均为借用,零克隆
        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 => {
                            // 匿名请求打受保护路径是常态(未登录探测、会话过期),
                            // 响应 403 已携带结论,降为 debug 防止日志刷屏
                            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;

    /// 与生产路径一致:编译规则后按 normalize 路径匹配,返回 (permission, is_guard)
    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() {
        // 守卫规则始终注册(is_guard 标记独立于配置开关),
        // App 构建时仅配置规则受 cfg.middleware.permission.enabled 控制
        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());
    }
}