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
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
//! 会话认证中间件:身份解析(SessionResolver)与强制登录(RequireAuth)分离
//!
//! 两个职责拆成两层,避免公开路径、OptionalUser、租户 bootstrap 互相耦合:
//! - `session_resolver`(需启用 `cache` feature):**可选**身份解析。有 Bearer token 就尝试解析并注入
//!   `CurrentUser`,无 token / 解析失败一律放行(由后续 RequireAuth 决定是否拒绝);
//! - [`AuthLayer`]:**强制登录**。仅检查请求是否已认证(extensions 中有
//!   `CurrentUser`),未认证且不属于 ignore/页面路径时返回 401。

use super::CurrentUser;
#[cfg(feature = "cache")]
use axum::extract::State;
#[cfg(feature = "cache")]
use axum::middleware::Next;
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;

/// 规范化 URL 路径:解析 `.` 和 `..` 段后用于路由匹配。
///
/// 已是规范形式(无 `.` / `..` 段、无重复斜杠、无结尾斜杠)时零分配借用返回
/// ——这是请求热路径的常态;仅确需改写时才分配。
pub(crate) fn normalize_path(path: &str) -> std::borrow::Cow<'_, str> {
    // 快路径判定与慢路径同源:首字符必须为 `/`,任一段为 "." / ".."、
    // 出现 "//" 或以 "/" 结尾都需要改写
    let canonical = path == "/"
        || (path.starts_with('/')
            && !path.ends_with('/')
            && !path.contains("//")
            && path.split('/').all(|s| s != "." && s != ".."));
    if canonical {
        return std::borrow::Cow::Borrowed(path);
    }
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "." | "" => continue,
            ".." => {
                segments.pop();
            }
            s => segments.push(s),
        }
    }
    let mut result = String::with_capacity(path.len() + 1);
    result.push('/');
    result.push_str(&segments.join("/"));
    std::borrow::Cow::Owned(result)
}

/// 统一拼接全局路由前缀与路由路径。
///
/// 无论 prefix 是否带 `/`、path 是否带 `/`,结果都保持单一规范形式 `/a/b`;
/// 路由元数据、权限规则、no-auth 规则、日志排除都必须使用同一结果,
/// 避免"日志用 `prefix+path`、auth 用 `/prefix+path`"式的拼接不一致。
pub(crate) fn join_route_path(prefix: &str, path: &str) -> String {
    let p = prefix.trim_matches('/');
    let path = path.trim_start_matches('/');
    if p.is_empty() {
        if path.is_empty() {
            "/".to_string()
        } else {
            format!("/{}", path)
        }
    } else if path.is_empty() {
        format!("/{}", p)
    } else {
        format!("/{}/{}", p, path)
    }
}

/// 路径模式匹配,与 axum 路由语义保持同段数:
/// - 精确匹配;
/// - `{param}` 匹配任意**单个**段(不会扩大为整棵路径前缀);
/// - `{*rest}` / `/*` 匹配尾部任意数量段;
/// - 其余段必须逐段相等。
///
/// 该实现每次调用都重新 normalize 两个路径,仅供启动期/低频路径使用;
/// 中间件热路径请使用预编译的 [`PathPattern`]。
pub(crate) fn match_path_pattern(pattern: &str, path: &str) -> bool {
    let p = normalize_path(pattern);
    let q = normalize_path(path);
    if p == q {
        return true;
    }
    PathPattern::compile_normalized(&p).matches_normalized(&q)
}

/// 预编译路径段
#[derive(Debug, Clone)]
pub(crate) enum Seg {
    /// 字面段(精确相等)
    Lit(String),
    /// `{param}` 参数段(匹配任意单段)
    Param,
}

/// 预编译路径模式:normalize + 分段在装配期一次性完成,请求期匹配零分配。
///
/// 语义与 [`match_path_pattern`] 完全等价(输入均需为已 normalize 路径)。
#[derive(Debug, Clone)]
pub(crate) enum PathPattern {
    /// 精确 / 参数段匹配(段数必须相等)
    Segments(Vec<Seg>),
    /// 尾部通配(`{*rest}` / `/*`):保存通配前的规范化前缀字符串,
    /// 按字符串前缀 + `/` 边界匹配(与历史实现逐字节等价)
    TailWildcard(String),
}

impl PathPattern {
    /// 编译模式(内部先 normalize)
    pub(crate) fn compile(pattern: &str) -> Self {
        Self::compile_normalized(&normalize_path(pattern))
    }

    /// 从已 normalize 的模式编译
    pub(crate) fn compile_normalized(p: &str) -> Self {
        if let Some(prefix) = p.strip_suffix("{*rest}").or_else(|| p.strip_suffix("/*")) {
            return Self::TailWildcard(prefix.trim_end_matches('/').to_string());
        }
        Self::Segments(
            p.split('/')
                .filter(|s| !s.is_empty())
                .map(|s| {
                    if s.starts_with('{') && s.ends_with('}') {
                        Seg::Param
                    } else {
                        Seg::Lit(s.to_string())
                    }
                })
                .collect(),
        )
    }

    /// 匹配**已 normalize** 的请求路径(零分配)
    pub(crate) fn matches_normalized(&self, q: &str) -> bool {
        match self {
            Self::Segments(segs) => {
                let mut q_segs = q.split('/').filter(|s| !s.is_empty());
                for seg in segs {
                    let Some(qs) = q_segs.next() else { return false };
                    match seg {
                        Seg::Lit(l) => {
                            if l != qs {
                                return false;
                            }
                        }
                        Seg::Param => {}
                    }
                }
                // 段数必须相等:模式段耗尽后请求段不得有剩余
                q_segs.next().is_none()
            }
            Self::TailWildcard(prefix) => {
                if prefix.is_empty() {
                    return true;
                }
                q == prefix || (q.starts_with(prefix.as_str()) && q.as_bytes().get(prefix.len()) == Some(&b'/'))
            }
        }
    }
}

/// 从 `Authorization: Bearer <token>` 提取 token
#[cfg(feature = "cache")]
fn extract_bearer_token(req: &Request) -> Option<String> {
    req.headers()
        .get(axum::http::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.to_string())
}

/// 判断路径是否为 API 路径(命中任一前缀;前缀为空视为全部路径)
pub(crate) fn is_api_path(normalized: &str, prefixes: &[String]) -> bool {
    prefixes.is_empty() || prefixes.iter().any(|p| normalized.starts_with(p.as_str()))
}

// ── 身份解析层:可选认证(SessionResolver)────────────────────────

/// 会话解析中间件的运行时状态
#[cfg(feature = "cache")]
pub struct SessionResolverState {
    /// 会话缓存
    pub cache: wordval_cache::SharedCache,
}

/// 会话解析中间件(可选认证)
///
/// 有 `Authorization: Bearer` token 时尝试从缓存解析 `CurrentUser` 并注入
/// extensions;解析失败仅记录日志,不拒绝请求——是否需要登录由
/// [`AuthLayer`](RequireAuth)按路由策略决定,无效 token 是否放行
/// 由调用方(OptionalUser 提取器 / ignore 规则)明确处理。
#[cfg(feature = "cache")]
pub async fn session_resolver(
    State(state): State<Arc<SessionResolverState>>,
    mut req: Request,
    next: Next,
) -> Response {
    let Some(token) = extract_bearer_token(&req) else {
        return next.run(req).await;
    };

    use wordval_cache::Cache;
    match state
        .cache
        .get::<CurrentUser>(&format!("session:{}", token))
        .await
    {
        Ok(Some(session)) => {
            req.extensions_mut().insert(session);
        }
        Ok(None) => {
            tracing::debug!("会话不存在或已过期: token={}", token);
        }
        Err(e) => {
            // 缓存故障与 token 无效区分记录,避免伪装成用户 token 过期
            tracing::warn!("会话查询失败(缓存故障): {}", e);
        }
    }
    next.run(req).await
}

// ── 强制登录层:RequireAuth ──────────────────────────────────────

/// 强制登录中间件层(RequireAuth)
///
/// 仅检查请求是否已认证(extensions 中存在 `CurrentUser`),不负责解析身份。
/// 未认证时对 API 路径返回 401;ignore 规则与页面路径放行。
///
/// 身份解析由 `session_resolver`(需启用 `cache` feature)完成,本层必须位于其内侧。
#[derive(Clone)]
pub struct AuthLayer {
    /// 免认证路径模式列表(所有方法均免认证),支持 `{param}` / `{*rest}` / `/*`
    ///
    /// 以下三个 Vec 字段均经 Arc 共享:axum 的 `Router::layer` 对每个路由端点
    /// clone 本层(path_router.rs:297 `endpoint.layer(layer.clone())`),裸 Vec
    /// 会被深拷贝出 E×R 份字符串(规则数 R 随路由数 E 增长时为启动期 O(N²)
    /// 分配);Arc 使逐端点 clone 退化为引用计数 +1,全端点共享同一份数据。
    pub ignore_paths: Arc<Vec<String>>,
    /// 免认证的 `(method, path pattern)` 规则:仅该方法免认证
    pub method_ignore_rules: Arc<Vec<(String, String)>>,
    /// 视为 API 路径的前缀列表(仅此前缀下的路径强制鉴权,空 = 全部路径)
    pub api_prefixes: Arc<Vec<String>>,
    /// 首次 layer() 编译一次,此后上述字段不得再变更。
    /// OnceLock 本体经 Arc 包裹:而 `OnceLock::clone`
    /// 在未初始化时产生空副本——裸 OnceLock 会被击穿为逐端点重编译;
    /// Arc 共享后全部端点复用同一缓存单元格,编译恰好一次。
    ///
    /// crate 内可直接字面量构造,构造点必须初始化为空单元格
    /// (`compiled: Arc::new(OnceLock::new())`),由首次 layer() 惰性填充。
    pub(crate) compiled: Arc<OnceLock<Arc<CompiledAuth>>>,
}

/// 装配期预编译的认证规则(请求期匹配零规则分配)
///
/// 类型随 [`AuthLayer::compiled`] 对 crate 内可见;字段仅 auth 模块内部读写。
pub(crate) struct CompiledAuth {
    /// 预编译的全方法免认证模式
    ignore: Vec<PathPattern>,
    /// 预编译的 (method, pattern) 免认证规则
    method_ignore: Vec<(String, PathPattern)>,
    /// API 前缀(空 = 全部路径),Arc 直接共享 AuthLayer 的数据
    api_prefixes: Arc<Vec<String>>,
}

impl CompiledAuth {
    fn compile(layer: &AuthLayer) -> Self {
        Self {
            ignore: layer.ignore_paths.iter().map(|p| PathPattern::compile(p)).collect(),
            method_ignore: layer
                .method_ignore_rules
                .iter()
                .map(|(m, p)| (m.clone(), PathPattern::compile(p)))
                .collect(),
            api_prefixes: layer.api_prefixes.clone(),
        }
    }
}

impl<S> Layer<S> for AuthLayer {
    type Service = AuthService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        // 编译一次、全端点共享:OnceLock 本体经 Arc 跨端点 clone 共享(见字段文档),
        // 避免原实现 O(路由数×规则数) 的逐端点重编译与 N 份独立内存副本
        let compiled = self
            .compiled
            .get_or_init(|| Arc::new(CompiledAuth::compile(self)))
            .clone();
        AuthService { inner, compiled }
    }
}

#[derive(Clone)]
pub struct AuthService<S> {
    inner: S,
    /// 预编译规则(Arc 共享,克隆廉价)
    compiled: Arc<CompiledAuth>,
}

impl<S> Service<Request<Body>> for AuthService<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 normalized_path = normalize_path(req.uri().path());
        let compiled = &self.compiled;
        let method = req.method().as_str();
        // HEAD 优先使用显式规则;Axum GET 路由自动接受 HEAD,因此未命中时回退 GET
        let is_ignore = compiled
            .method_ignore
            .iter()
            .any(|(m, p)| m.eq_ignore_ascii_case(method) && p.matches_normalized(&normalized_path))
            || (method.eq_ignore_ascii_case("HEAD")
                && compiled.method_ignore.iter().any(|(m, p)| {
                    m.eq_ignore_ascii_case("GET") && p.matches_normalized(&normalized_path)
                }))
            || compiled
                .ignore
                .iter()
                .any(|p| p.matches_normalized(&normalized_path));
        // is_page = !is_api_path:前缀列表非空且不在任一前缀内
        let is_page = !compiled.api_prefixes.is_empty()
            && !compiled
                .api_prefixes
                .iter()
                .any(|p| normalized_path.starts_with(p.as_str()));
        let is_authenticated = req.extensions().get::<CurrentUser>().is_some();

        let replacement = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, replacement);

        Box::pin(async move {
            // ignore 路径或页面请求:无论是否登录都放行(身份已在 SessionResolver 注入)
            if is_ignore || is_page || is_authenticated {
                return inner.call(req).await;
            }
            Ok(super::error_response(ApiError::unauthorized(
                "未授权访问,请先登录",
            )))
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{join_route_path, match_path_pattern, normalize_path};

    #[test]
    fn normalize_path_borrows_canonical_and_resolves_dots() {
        use std::borrow::Cow;
        // 已规范路径零分配借用(热路径常态)
        assert!(matches!(normalize_path("/a/b"), Cow::Borrowed("/a/b")));
        assert!(matches!(normalize_path("/"), Cow::Borrowed("/")));
        // 需要改写:点段、重复斜杠、结尾斜杠
        assert_eq!(&*normalize_path("/a/./b"), "/a/b");
        assert_eq!(&*normalize_path("/a/../b"), "/b");
        assert_eq!(&*normalize_path("//a//b//"), "/a/b");
        assert_eq!(&*normalize_path("/a/"), "/a");
        // 无前导斜杠/空串仍补齐(与历史行为一致,配置路径可能这样写)
        assert_eq!(&*normalize_path("users"), "/users");
        assert_eq!(&*normalize_path(""), "/");
    }

    #[test]
    fn join_route_path_normalizes_prefix_and_path() {
        assert_eq!(join_route_path("", "/users"), "/users");
        assert_eq!(join_route_path("/", "/users"), "/users");
        assert_eq!(join_route_path("/api", "/users"), "/api/users");
        assert_eq!(join_route_path("api", "users"), "/api/users");
        assert_eq!(join_route_path("/api/", "/users"), "/api/users");
        assert_eq!(join_route_path("/api/", "users"), "/api/users");
        assert_eq!(join_route_path("/api", ""), "/api");
        assert_eq!(join_route_path("", ""), "/");
        // 与 nest 后的最终请求路径一致:/api + /users = /api/users
        assert_eq!(join_route_path("/api", "/users"), "/api/users");
    }

    #[test]
    fn match_path_exact_and_single_param_segment() {
        // {param} 只匹配单个动态段,不得扩大为整棵路径前缀
        assert!(match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/token/123"
        ));
        assert!(match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/token/abc"
        ));
        // 后代路径不匹配:/token/123 之后还有段
        assert!(!match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/token/123/delete"
        ));
        assert!(!match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/token/123/456"
        ));
        // 段数不足不匹配
        assert!(!match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/token"
        ));
        // 静态段必须相等
        assert!(!match_path_pattern(
            "/api/public/token/{id}",
            "/api/public/admin/123"
        ));
        // 多参数段
        assert!(match_path_pattern("/api/{a}/{b}", "/api/x/y"));
        assert!(!match_path_pattern("/api/{a}/{b}", "/api/x/y/z"));
    }

    #[test]
    fn match_path_tail_wildcard() {
        // {*rest} / /* 只匹配尾部任意段
        assert!(match_path_pattern("/api/public/{*rest}", "/api/public"));
        assert!(match_path_pattern("/api/public/{*rest}", "/api/public/a"));
        assert!(match_path_pattern(
            "/api/public/{*rest}",
            "/api/public/a/b/c"
        ));
        assert!(match_path_pattern("/api/public/*", "/api/public/a/b"));
        // 前缀边界:/api/public 不能误匹配 /api/publicSecret
        assert!(!match_path_pattern("/api/public/*", "/api/publicSecret"));
        assert!(!match_path_pattern("/api/public/{*rest}", "/api/other"));
    }

    #[test]
    fn match_path_normalizes_dot_segments() {
        assert!(match_path_pattern("/api/users", "/api/./users"));
        assert!(match_path_pattern("/api/users", "/api/x/../users"));
    }
}