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
//! 操作审计中间件(白名单路由的访问结论)
//!
//! 与 [`request_log`](super::request_log) 的分工:访问日志是排障用的全量流水
//! (tracing 输出,进程重启即丢),审计层是**白名单路由**的强留痕记录——批量落盘、
//! 带结论(成功/被拒/出错)与请求身份,可长期查询对账。
//!
//! 覆盖范围由挂载位置决定(优先级 85,位于身份/租户层之内、认证/权限层之外):
//!
//! - 能看到 [`CurrentUser`](super::CurrentUser) 与租户上下文(70/80 层已注入);
//! - 能看到 `require_auth` 的 401、`permission_check` 的 403、`nonce` 的 401/400
//!   ——这些短路响应由更内层产生,仍然穿过本层;
//! - **看不到** `rate_limit` 的 429(60 层在本层外侧,被限流的请求不会到达这里):
//!   限流拒绝连同 IP、路径与请求 ID 已在访问日志中留痕,属于可用性问题而非操作
//!   审计;需要精确审计限流拒绝时,把本层优先级调到限流之外即可。
//!
//! 只有命中规则的路由才产生记录(未命中零开销透传),规则来自两处:
//! `middleware.audit.routes` 配置 + 路由宏的 `audit = "action"` 守卫;
//! 匹配策略与权限层同源(守卫优先 + 最具体规则优先)。

use super::auth::{normalize_path, PathPattern};
use super::{best_rule, rule_specificity, RuleKey};
use crate::router::RouteEntry;
use axum::body::Body;
use axum::extract::Request;
use axum::http::header;
use axum::response::Response;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use std::time::Instant;
use tower::{Layer, Service};

use crate::audit::{AuditRecord, AuditResult};

/// 审计规则(一条路由 → 一个动作名)
#[derive(Debug, Clone)]
pub struct AuditRule {
    /// URL 路径(支持 `{param}` 单段、`{*rest}` / `/*` 尾部通配)
    pub path: String,
    /// 适用的 HTTP 方法列表(空表示所有方法)
    pub methods: Vec<String>,
    /// 审计动作名(如 `order.delete`)
    pub action: String,
    /// 是否来自路由守卫的 `audit = "..."`(守卫规则优先于配置规则)
    pub is_guard: bool,
}

/// 装配期预编译的审计规则(请求期匹配零分配)
///
/// 类型随 [`AuditLayer::compiled`] 对 crate 内可见;字段仅 audit 模块内部读写。
pub(crate) struct CompiledRule {
    pattern: PathPattern,
    methods: Vec<String>,
    action: String,
    specificity: (usize, usize),
    is_guard: bool,
}

impl CompiledRule {
    fn compile(rule: &AuditRule) -> Self {
        Self {
            pattern: PathPattern::compile(&rule.path),
            methods: rule.methods.clone(),
            action: rule.action.clone(),
            specificity: rule_specificity(&rule.path),
            is_guard: rule.is_guard,
        }
    }
}

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
    }
}

/// 审计层:命中规则的路由在响应返回后写一条 [`AuditRecord`]
///
/// 默认写入框架全局审计写入器(`middleware.audit.enabled` 或 `set_audit_writer`
/// 装配的那一个);`with_writer` 可指定独立写入器(测试或需要多路审计时使用)。
#[derive(Clone)]
pub struct AuditLayer {
    /// 审计规则列表。
    /// Arc 共享:axum 的 `Router::layer` 对每个路由端点 clone 本层
    /// (path_router.rs:297 `endpoint.layer(layer.clone())`),裸 Vec 会被
    /// 深拷贝出 E×R 份规则字符串(R≈E 时为启动期 O(N²) 分配);Arc 使
    /// 逐端点 clone 退化为引用计数 +1,全端点共享同一份规则(与 auth/permission 同款)。
    pub rules: Arc<Vec<AuditRule>>,
    /// 指定写入器;`None` 表示使用全局审计写入器
    pub writer: Option<Arc<crate::audit::AuditWriter>>,
    /// 首次 layer() 编译一次,此后上述字段不得再变更。
    /// OnceLock 本体经 Arc 包裹:而 `OnceLock::clone`
    /// 在未初始化时产生空副本——裸 OnceLock 会被击穿为逐端点重编译;
    /// Arc 共享后全部端点复用同一缓存单元格,编译恰好一次。
    ///
    /// crate 内可直接字面量构造,构造点必须初始化为空单元格
    /// (`compiled: Arc::new(OnceLock::new())`),由首次 layer() 惰性填充。
    pub(crate) compiled: Arc<OnceLock<Arc<Vec<CompiledRule>>>>,
}

impl AuditLayer {
    pub fn empty() -> Self {
        Self {
            rules: Arc::new(Vec::new()),
            writer: None,
            compiled: Arc::new(OnceLock::new()),
        }
    }

    /// 指定审计写入器(不依赖全局单例)
    pub fn with_writer(mut self, writer: Arc<crate::audit::AuditWriter>) -> Self {
        self.writer = Some(writer);
        self
    }

    /// 从 `middleware.audit.routes` 配置创建(规则路径不含全局前缀时自动拼接)
    pub fn from_config_with_prefix(routes: &[wordval_config::AuditRoute], prefix: &str) -> Self {
        Self::empty().with_config_routes(routes, prefix)
    }

    /// 合并配置规则
    pub fn with_config_routes(mut self, routes: &[wordval_config::AuditRoute], prefix: &str) -> Self {
        // 构建期引用计数仍为 1,make_mut 零拷贝;仅当 clone 后再构建才 COW
        let rules = Arc::make_mut(&mut self.rules);
        rules.reserve(routes.len());
        for r in routes {
            rules.push(AuditRule {
                path: super::auth::join_route_path(prefix, &r.path),
                methods: if r.method.is_empty() {
                    Vec::new()
                } else {
                    vec![r.method.clone()]
                },
                action: r.action.clone(),
                is_guard: false,
            });
        }
        self
    }

    /// 从已注册路由的守卫元数据派生审计规则(`audit = "action"`)
    ///
    /// `routes` 来自 `WordvalRouter::list_routes()`,路径已含 `group` / `merge`
    /// 前缀,这里只再拼接全局前缀,规则与最终请求路径必然同源。
    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(action) = r.guard.audit.as_deref() else {
                continue;
            };
            rules.push(AuditRule {
                path: super::auth::join_route_path(prefix, &r.path),
                methods: vec![r.method.clone()],
                action: action.to_string(),
                is_guard: true,
            });
        }
        self
    }

    pub fn has_rules(&self) -> bool {
        !self.rules.is_empty()
    }
}

impl<S> Layer<S> for AuditLayer {
    type Service = AuditService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        // 编译一次、全端点共享:OnceLock 本体经 Arc 跨端点 clone 共享(见字段文档),
        // 首个端点编译后其余端点(含 nest/merge 再克隆)直接复用同一份
        let rules = self
            .compiled
            .get_or_init(|| Arc::new(self.rules.iter().map(CompiledRule::compile).collect()))
            .clone();
        AuditService {
            inner,
            rules,
            writer: self.writer.clone(),
        }
    }
}

#[derive(Clone)]
/// 审计服务——命中规则则请求结束后落一条审计记录
pub struct AuditService<S> {
    inner: S,
    rules: Arc<Vec<CompiledRule>>,
    /// `None` = 使用全局审计写入器
    writer: Option<Arc<crate::audit::AuditWriter>>,
}

impl<S> Service<Request<Body>> for AuditService<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 = normalize_path(req.uri().path());
        let action = match best_rule(&self.rules, &normalized, req.method().as_str()) {
            Some(r) => r.action.clone(),
            None => {
                let replacement = self.inner.clone();
                let mut inner = std::mem::replace(&mut self.inner, replacement);
                return Box::pin(async move { inner.call(req).await });
            }
        };
        let method = req.method().as_str().to_string();

        // 请求侧信息在交给下游前取走(extensions 会被内层移动)
        let ctx = CapturedContext::from_request(&req);
        let writer = self.writer.clone();
        // 记录要持有自有路径字符串:Cow 借用自 req,必须在 req 移动前落地
        // (未命中规则时借用自然结束,零分配透传)
        let resource = normalized.into_owned();
        let replacement = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, replacement);

        Box::pin(async move {
            let resp = inner.call(req).await;
            // 下游错误(Router 实际为 Infallible)也要留痕:结论记为 Error
            let (status, ok) = match &resp {
                Ok(r) => (Some(r.status().as_u16()), true),
                Err(_) => (None, false),
            };
            let code = status.unwrap_or(500);
            let result = if ok {
                AuditResult::from_status(code)
            } else {
                AuditResult::Error
            };
            let record = ctx.into_record(action, resource, method, code, result);
            match &writer {
                Some(w) => w.write(record),
                // 未指定则走全局写入器(未启用审计时静默忽略)
                None => crate::resources::audit_write(record),
            }
            resp
        })
    }
}

/// 请求侧快照:审计记录需要的身份/上下文,全部在 `call` 入口取齐
struct CapturedContext {
    request_id: Option<String>,
    user_agent: Option<String>,
    ip: Option<String>,
    user_id: String,
    tenant: Option<String>,
    started: Option<Instant>,
}

impl CapturedContext {
    fn from_request(req: &Request<Body>) -> Self {
        let ext = req.extensions();
        Self {
            request_id: ext.get::<super::request_id::RequestId>().map(|r| r.0.clone()),
            user_agent: req
                .headers()
                .get(header::USER_AGENT)
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string()),
            ip: ext.get::<super::client_identity::ClientIp>().map(|c| c.0.clone()),
            user_id: ext
                .get::<super::CurrentUser>()
                .map(|u| u.id.to_string())
                .unwrap_or_default(),
            // 租户层(80)在本层(85)外侧,task-local 已建立
            tenant: crate::tenant::current_tenant_id().map(|t| t.to_string()),
            started: ext.get::<super::client_identity::RequestStart>().map(|s| s.0),
        }
    }

    fn into_record(
        self,
        action: String,
        resource: String,
        method: String,
        status: u16,
        result: AuditResult,
    ) -> AuditRecord {
        let mut rec = AuditRecord::new(action, resource, result)
            .with_user(self.user_id)
            .with_method(method)
            .with_tenant(self.tenant)
            .with_request_id(self.request_id)
            .with_user_agent(self.user_agent)
            .with_ip(self.ip)
            .with_status(status);
        if let Some(started) = self.started {
            rec = rec.with_elapsed_ms(started.elapsed().as_millis() as u64);
        }
        rec
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::router::{RouteEntry, RouteGuard};
    use wordval_config::AuditRoute;

    fn compiled(layer: &AuditLayer) -> Vec<CompiledRule> {
        layer.rules.iter().map(CompiledRule::compile).collect()
    }

    fn route(path: &str, method: &str, action: &str) -> AuditRoute {
        AuditRoute {
            method: method.to_string(),
            path: path.to_string(),
            action: action.to_string(),
        }
    }

    fn guard_route(method: &str, path: &str, action: &str) -> RouteEntry {
        RouteEntry {
            method: method.to_string(),
            path: path.to_string(),
            guard: RouteGuard::auditing(action),
        }
    }

    #[test]
    fn config_and_guard_rules_match_with_guard_priority() {
        // 守卫规则与配置规则同路径冲突时,守卫动作名生效
        let layer = AuditLayer::from_config_with_prefix(&[route("/orders", "", "cfg.order")], "")
            .with_route_guards(&[guard_route("DELETE", "/orders", "order.delete")], "");
        let rules = compiled(&layer);
        let hit = best_rule(&rules, "/orders", "DELETE").unwrap();
        assert_eq!(hit.action, "order.delete");
        // 非 DELETE 方法落到配置规则(method 空 = 全方法)
        let hit = best_rule(&rules, "/orders", "GET").unwrap();
        assert_eq!(hit.action, "cfg.order");
    }

    #[test]
    fn head_uses_explicit_rule_before_get_fallback() {
        let layer = AuditLayer::empty().with_route_guards(
            &[
                guard_route("GET", "/orders", "order.list"),
                guard_route("HEAD", "/orders", "order.head"),
                guard_route("GET", "/goods", "goods.list"),
            ],
            "",
        );
        let rules = compiled(&layer);

        assert_eq!(
            best_rule(&rules, "/orders", "HEAD").unwrap().action,
            "order.head"
        );
        assert_eq!(
            best_rule(&rules, "/goods", "HEAD").unwrap().action,
            "goods.list"
        );
    }

    #[test]
    fn guard_rule_joined_with_global_prefix() {
        let layer = AuditLayer::empty()
            .with_route_guards(&[guard_route("POST", "/orders", "order.create")], "/api");
        let rules = compiled(&layer);
        assert!(best_rule(&rules, "/api/orders", "POST").is_some());
        assert!(best_rule(&rules, "/orders", "POST").is_none());
    }

    #[test]
    fn routes_without_audit_contribute_no_rules() {
        let plain = RouteEntry {
            method: "POST".to_string(),
            path: "/orders".to_string(),
            guard: RouteGuard::default(),
        };
        let layer = AuditLayer::empty().with_route_guards(&[plain], "");
        assert!(!layer.has_rules());
    }

    #[test]
    fn most_specific_pattern_wins() {
        let layer = AuditLayer::from_config_with_prefix(
            &[route("/admin", "", "admin:any"), route("/admin/{id}", "", "admin:detail")],
            "",
        );
        let rules = compiled(&layer);
        assert_eq!(best_rule(&rules, "/admin/7", "GET").unwrap().action, "admin:detail");
    }

    #[test]
    fn global_prefix_joined_into_rule_path() {
        let layer =
            AuditLayer::from_config_with_prefix(&[route("/orders", "POST", "order.create")], "/api");
        let rules = compiled(&layer);
        assert!(best_rule(&rules, "/api/orders", "POST").is_some());
        assert!(best_rule(&rules, "/orders", "POST").is_none());
    }

    #[test]
    fn unmatched_method_produces_no_rule_hit() {
        let layer =
            AuditLayer::from_config_with_prefix(&[route("/orders", "POST", "order.create")], "");
        let rules = compiled(&layer);
        assert!(best_rule(&rules, "/orders", "GET").is_none());
        // 大小写不敏感
        assert!(best_rule(&rules, "/orders", "post").is_some());
    }
}