garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! WAF 级防火墙(策略层 Hook 链):提供 `WafContext`(请求内容快照,path / method / host / headers / params 借用引用零拷贝)、
//! `WafVerdict`(Allow / AllowAndSkip / Deny)、`WafHook` trait(每种校验规则一个 Hook)与 `WafHookChain`
//! (按注册顺序执行,任一 Deny 则短路返回 `GarrisonError::FirewallBlocked`)。
//!
//! 与 `web-waf`(web 层 `WafRule` trait + `WafConfig`,返回 `GarrisonError::Config`(400))区分:本模块在 strategy 层,返回 `FirewallBlocked`(403)。
//! 错误适配:`FirewallBlocked(String)` 为单字段变体,Hook 链将 hook 名与 reason 编码为 `format!("[{}] {}", hook, reason)`。

use crate::config::GarrisonConfig;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::collections::HashSet;

/// WAF 校验上下文,包含请求内容快照(借用引用,零拷贝)。
#[derive(Debug, Clone, Copy)]
pub struct WafContext<'a> {
    /// 请求路径(如 `/api/users/1`)。
    pub path: &'a str,
    /// HTTP 方法(如 `GET`、`POST`)。
    pub method: &'a str,
    /// Host 头(可选)。
    pub host: Option<&'a str>,
    /// 请求头列表(key, value 元组)。
    pub headers: &'a [(String, String)],
    /// 请求参数列表(key, value 元组)。
    pub params: &'a [(String, String)],
}

/// WAF 校验结果。
#[derive(Debug, Clone)]
pub enum WafVerdict {
    /// 放行,继续执行后续 Hook。
    Allow,
    /// 放行并短路,跳过后续所有 Hook(用于白名单匹配)。
    AllowAndSkip,
    /// 拒绝,短路返回 `FirewallBlocked` 错误。
    Deny {
        /// 拒绝原因(写入错误消息)。
        reason: String,
        /// 触发拒绝的 Hook 名称(写入 tracing 日志)。
        hook: &'static str,
    },
}

/// WAF Hook trait,每种校验规则实现一个 Hook:返回 `Allow` 放行(继续后续 Hook)、`AllowAndSkip` 放行并短路(跳过后续 Hook)、`Deny` 拒绝。
#[async_trait]
pub trait WafHook: Send + Sync {
    /// 返回 Hook 名称(用于日志和错误追踪)。
    fn name(&self) -> &'static str;

    /// 校验请求上下文,返回 [`WafVerdict`]。
    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict;
}

/// WAF Hook 链,按注册顺序执行,任一 Deny 则短路返回。
pub struct WafHookChain {
    hooks: Vec<Box<dyn WafHook>>,
}

impl WafHookChain {
    /// 创建空的 Hook 链。
    pub fn new() -> Self {
        Self { hooks: Vec::new() }
    }

    /// 追加 Hook 到链尾。
    ///
    /// # 注册顺序约束
    ///
    /// **安全关键 Hook(`DangerCharacterHook` / `BannedCharacterHook` / `DirectoryTraversalHook`)必须先于 `WhitePathHook` 注册**:
    /// 链按注册顺序执行,`WhitePathHook` 先注册时其 `AllowAndSkip` 会短路跳过全部安全校验(`WhitePathHook` 内的可疑模式兜底守卫仅是辅助防线)。
    /// [`WafHookChain::from_config`](Self::from_config) 已按此顺序注册。
    pub fn register(&mut self, hook: Box<dyn WafHook>) {
        self.hooks.push(hook);
    }

    /// 按注册顺序执行所有 Hook:任一 `Deny` 短路返回 `FirewallBlocked` 错误,`AllowAndSkip` 短路返回 `Ok(())` 跳过后续 Hook。
    ///
    /// Deny 时将 reason 直接编码为结构化 i18n key,复用 `GarrisonError::FirewallBlocked(String)` 变体;
    /// hook 名仅记录于 tracing 日志,不编码进错误消息(避免破坏 `parse_keyed_detail` 解析)。
    pub async fn check(&self, ctx: &WafContext<'_>) -> GarrisonResult<()> {
        for hook in &self.hooks {
            match hook.check(ctx).await {
                WafVerdict::Allow => continue,
                WafVerdict::AllowAndSkip => {
                    tracing::debug!(hook = hook.name(), "WAF whitelist allowed");
                    return Ok(());
                },
                WafVerdict::Deny { reason, hook: name } => {
                    tracing::warn!(hook = name, reason = %reason, "WAF blocked request");
                    return Err(GarrisonError::FirewallBlocked(reason));
                },
            }
        }
        Ok(())
    }

    /// 根据配置创建 WAF Hook 链:`waf_enabled_hooks` 为空时注册所有可用 Hook。
    ///
    /// 注册顺序:**字符检测类安全 Hook(`danger_char` / `banned_char` / `dir_traversal`,仅按 `waf_enabled_hooks` 开关门控)先注册**,
    /// 配置门控 Hook(路径/主机/方法/头/参数,需对应配置非空)后注册——确保安全校验先于可能 `AllowAndSkip` 短路的白名单 Hook 执行。
    pub fn from_config(config: &GarrisonConfig) -> Self {
        let mut chain = Self::new();

        let enabled: HashSet<&str> = config
            .waf_enabled_hooks
            .iter()
            .map(|s| s.as_str())
            .collect();
        let all_enabled = enabled.is_empty();
        let is_enabled = |name: &str| all_enabled || enabled.contains(name);

        // 安全关键 Hook 先注册:白名单匹配会 AllowAndSkip 短路后续 Hook,若 white_path 先注册,双编码路径(旧守卫漏检)可绕过全部安全校验。
        Self::register_unconditional_hooks(&mut chain, &is_enabled);
        Self::register_config_gated_hooks(&mut chain, config, &is_enabled);

        chain
    }

    /// 注册需要配置非空前置条件的 Hook(路径/主机/方法/头/参数)。
    fn register_config_gated_hooks(
        chain: &mut Self,
        config: &GarrisonConfig,
        is_enabled: &dyn Fn(&str) -> bool,
    ) {
        type GatedHook = (&'static str, fn(Vec<String>) -> Box<dyn WafHook>);
        let gated: &[GatedHook] = &[
            ("white_path", |v| {
                Box::new(super::waf_hooks::WhitePathHook::new(v))
            }),
            ("black_path", |v| {
                Box::new(super::waf_hooks::BlackPathHook::new(v))
            }),
            ("host", |v| Box::new(super::waf_hooks::HostHook::new(v))),
            ("http_method", |v| {
                Box::new(super::waf_hooks::HttpMethodHook::new(v))
            }),
            ("header", |v| Box::new(super::waf_hooks::HeaderHook::new(v))),
            ("parameter", |v| {
                Box::new(super::waf_hooks::ParameterHook::new(v))
            }),
        ];
        let config_slices: &[(&str, &[String])] = &[
            ("white_path", &config.waf_white_paths),
            ("black_path", &config.waf_black_paths),
            ("host", &config.waf_allowed_hosts),
            ("http_method", &config.waf_allowed_methods),
            ("header", &config.waf_banned_headers),
            ("parameter", &config.waf_banned_params),
        ];
        for (name, items) in config_slices {
            if is_enabled(name) && !items.is_empty() {
                let ctor = gated.iter().find(|(n, _)| n == name).unwrap().1;
                chain.register(ctor(items.to_vec()));
            }
        }
    }

    /// 注册无需配置前置条件的 Hook(字符检测类)。
    fn register_unconditional_hooks(chain: &mut Self, is_enabled: &dyn Fn(&str) -> bool) {
        type UncondHook = (&'static str, fn() -> Box<dyn WafHook>);
        let unconditional: &[UncondHook] = &[
            ("danger_char", || {
                Box::new(super::waf_hooks::DangerCharacterHook::new())
            }),
            ("banned_char", || {
                Box::new(super::waf_hooks::BannedCharacterHook::new())
            }),
            ("dir_traversal", || {
                Box::new(super::waf_hooks::DirectoryTraversalHook::new())
            }),
        ];
        for &(name, ctor) in unconditional {
            if is_enabled(name) {
                chain.register(ctor());
            }
        }
    }
}

impl Default for WafHookChain {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    // 测试用 Mock Hook

    /// 始终返回 Allow 的 Mock Hook。
    struct AllowHook {
        hook_name: &'static str,
    }

    #[async_trait]
    impl WafHook for AllowHook {
        fn name(&self) -> &'static str {
            self.hook_name
        }
        async fn check(&self, _ctx: &WafContext<'_>) -> WafVerdict {
            WafVerdict::Allow
        }
    }

    /// 始终返回 Deny 的 Mock Hook。
    struct DenyHook {
        hook_name: &'static str,
        deny_reason: String,
    }

    #[async_trait]
    impl WafHook for DenyHook {
        fn name(&self) -> &'static str {
            self.hook_name
        }
        async fn check(&self, _ctx: &WafContext<'_>) -> WafVerdict {
            WafVerdict::Deny {
                reason: self.deny_reason.clone(),
                hook: self.hook_name,
            }
        }
    }

    /// 记录执行顺序的 Mock Hook。
    struct RecordingHook {
        hook_name: &'static str,
        log: Arc<Mutex<Vec<&'static str>>>,
    }

    #[async_trait]
    impl WafHook for RecordingHook {
        fn name(&self) -> &'static str {
            self.hook_name
        }
        async fn check(&self, _ctx: &WafContext<'_>) -> WafVerdict {
            self.log.lock().unwrap().push(self.hook_name);
            WafVerdict::Allow
        }
    }

    /// 构造测试用 WafContext。
    fn make_ctx<'a>() -> WafContext<'a> {
        WafContext {
            path: "/api/test",
            method: "GET",
            host: Some("example.com"),
            headers: &[],
            params: &[],
        }
    }

    // register / check 基础行为测试

    /// 验证空 chain 的 check() 返回 Ok(())。
    #[tokio::test]
    async fn empty_chain_returns_ok() {
        let chain = WafHookChain::new();
        let ctx = make_ctx();
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "空 chain 应返回 Ok(())");
    }

    /// 验证全部 Allow 时遍历所有 Hook 后返回 Ok(())。
    #[tokio::test]
    async fn all_allow_returns_ok() {
        let mut chain = WafHookChain::new();
        chain.register(Box::new(AllowHook { hook_name: "a" }));
        chain.register(Box::new(AllowHook { hook_name: "b" }));
        let ctx = make_ctx();
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "全部 Allow 时应返回 Ok(())");
    }

    /// 验证任一 Deny 时短路返回 Err,后续 Hook 不执行。
    #[tokio::test]
    async fn deny_short_circuits() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(RecordingHook {
            hook_name: "first",
            log: log.clone(),
        }));
        chain.register(Box::new(DenyHook {
            hook_name: "deny",
            deny_reason: "blocked".to_string(),
        }));
        chain.register(Box::new(RecordingHook {
            hook_name: "third",
            log: log.clone(),
        }));
        let ctx = make_ctx();
        let result = chain.check(&ctx).await;
        assert!(result.is_err(), "Deny 时应返回 Err");
        let executed = log.lock().unwrap();
        assert!(
            executed.contains(&"first") && !executed.contains(&"third"),
            "短路后第三个 Hook 不应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证多 Hook 按注册顺序执行。
    #[tokio::test]
    async fn multiple_hooks_execute_in_order() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(RecordingHook {
            hook_name: "first",
            log: log.clone(),
        }));
        chain.register(Box::new(RecordingHook {
            hook_name: "second",
            log: log.clone(),
        }));
        chain.register(Box::new(RecordingHook {
            hook_name: "third",
            log: log.clone(),
        }));
        let ctx = make_ctx();
        chain.check(&ctx).await.unwrap();
        let executed = log.lock().unwrap();
        assert_eq!(
            *executed,
            vec!["first", "second", "third"],
            "Hook 应按注册顺序执行"
        );
    }

    /// 验证 WafContext 字段可直接访问。
    #[test]
    fn waf_context_fields_accessible() {
        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];
        let params = vec![("id".to_string(), "123".to_string())];
        let ctx = WafContext {
            path: "/api/test",
            method: "GET",
            host: Some("example.com"),
            headers: &headers,
            params: &params,
        };
        assert_eq!(ctx.path, "/api/test");
        assert_eq!(ctx.method, "GET");
        assert_eq!(ctx.host, Some("example.com"));
        assert_eq!(ctx.headers.len(), 1);
        assert_eq!(ctx.params.len(), 1);
        assert_eq!(ctx.headers[0].0, "Content-Type");
        assert_eq!(ctx.params[0].1, "123");
    }

    /// 验证 WafVerdict::Allow 可构造。
    #[test]
    fn waf_verdict_allow_constructable() {
        let verdict = WafVerdict::Allow;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证 WafVerdict::Deny { reason, hook } 可构造。
    #[test]
    fn waf_verdict_deny_constructable() {
        let verdict = WafVerdict::Deny {
            reason: "test reason".to_string(),
            hook: "test_hook",
        };
        match verdict {
            WafVerdict::Deny { reason, hook } => {
                assert_eq!(reason, "test reason");
                assert_eq!(hook, "test_hook");
            },
            WafVerdict::Allow => panic!("应为 Deny"),
            WafVerdict::AllowAndSkip => panic!("应为 Deny"),
        }
    }

    /// 验证 hook.name() 返回 &'static str。
    #[test]
    fn hook_name_returns_static_str() {
        let hook = AllowHook { hook_name: "test" };
        let name: &'static str = hook.name();
        assert_eq!(name, "test");
    }

    /// 验证 Deny 时错误信息含 reason。
    #[tokio::test]
    async fn deny_error_contains_reason() {
        let mut chain = WafHookChain::new();
        chain.register(Box::new(DenyHook {
            hook_name: "test_hook",
            deny_reason: "suspicious_path".to_string(),
        }));
        let ctx = make_ctx();
        let result = chain.check(&ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let err_msg = err.to_string();
        assert!(
            err_msg.contains("suspicious_path"),
            "错误消息应含 reason,实际: {}",
            err_msg
        );
    }

    /// 验证 register() 追加 Hook 到 chain。
    #[tokio::test]
    async fn register_appends_hook() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(RecordingHook {
            hook_name: "first",
            log: log.clone(),
        }));
        chain.register(Box::new(RecordingHook {
            hook_name: "second",
            log: log.clone(),
        }));
        let ctx = make_ctx();
        chain.check(&ctx).await.unwrap();
        let executed = log.lock().unwrap();
        assert_eq!(executed.len(), 2, "应执行 2 个 Hook");
        assert_eq!(executed[0], "first", "第一个 Hook 应先执行");
        assert_eq!(executed[1], "second", "第二个 Hook 应后执行");
    }

    // WafHookChain::from_config 测试

    /// 验证空配置不注册任何 Hook。
    #[tokio::test]
    async fn from_config_empty_registers_none() {
        let mut config = GarrisonConfig::default_config();
        config.waf_enabled_hooks = Vec::new();
        config.waf_white_paths = Vec::new();
        config.waf_black_paths = Vec::new();
        config.waf_allowed_hosts = Vec::new();
        config.waf_allowed_methods = Vec::new();
        config.waf_banned_headers = Vec::new();
        config.waf_banned_params = Vec::new();

        let chain = WafHookChain::from_config(&config);
        let ctx = make_ctx();
        assert!(chain.check(&ctx).await.is_ok(), "空配置应不注册任何 Hook");
    }

    /// 验证全量 Hook 注册(空 enabled_hooks = 全部启用)。
    #[tokio::test]
    async fn from_config_all_enabled_registers_all_hooks() {
        let mut config = GarrisonConfig::default_config();
        config.waf_enabled_hooks = Vec::new();
        config.waf_white_paths = vec!["/api".to_string()];
        config.waf_black_paths = vec!["/admin".to_string()];
        config.waf_allowed_hosts = vec!["example.com".to_string()];
        config.waf_allowed_methods = vec!["GET".to_string()];
        config.waf_banned_headers = vec!["X-Blocked".to_string()];
        config.waf_banned_params = vec!["secret".to_string()];

        let chain = WafHookChain::from_config(&config);

        // 白名单路径 → AllowAndSkip 短路放行
        let ctx = make_ctx();
        assert!(chain.check(&ctx).await.is_ok(), "白名单路径应放行");

        // 黑名单路径 → Deny
        let ctx = WafContext {
            path: "/admin/secret",
            method: "GET",
            host: Some("example.com"),
            headers: &[],
            params: &[],
        };
        assert!(chain.check(&ctx).await.is_err(), "黑名单路径应拦截");
    }

    /// 验证选择性启用 Hook(仅 danger_char + host)。
    #[tokio::test]
    async fn from_config_selective_hooks() {
        let mut config = GarrisonConfig::default_config();
        config.waf_enabled_hooks = vec!["danger_char".to_string(), "host".to_string()];
        config.waf_allowed_hosts = vec!["example.com".to_string()];

        let chain = WafHookChain::from_config(&config);

        // danger_char 应拦截 //
        let ctx = WafContext {
            path: "/api//test",
            method: "GET",
            host: Some("example.com"),
            headers: &[],
            params: &[],
        };
        assert!(chain.check(&ctx).await.is_err(), "danger_char 应拦截 //");

        // host 应拦截非白名单域名
        let ctx = WafContext {
            path: "/api/test",
            method: "GET",
            host: Some("evil.com"),
            headers: &[],
            params: &[],
        };
        assert!(chain.check(&ctx).await.is_err(), "host 应拦截非白名单域名");

        // 正常请求应放行
        let ctx = make_ctx();
        assert!(chain.check(&ctx).await.is_ok(), "正常请求应放行");
    }

    /// 验证 banned_char + dir_traversal 接线正确。
    #[tokio::test]
    async fn from_config_banned_char_and_dir_traversal() {
        let mut config = GarrisonConfig::default_config();
        config.waf_enabled_hooks = vec!["banned_char".to_string(), "dir_traversal".to_string()];

        let chain = WafHookChain::from_config(&config);

        // dir_traversal 应拦截 ../
        let ctx = WafContext {
            path: "/api/../etc",
            method: "GET",
            host: Some("example.com"),
            headers: &[],
            params: &[],
        };
        assert!(chain.check(&ctx).await.is_err(), "dir_traversal 应拦截 ../");

        // 正常路径应放行
        let ctx = make_ctx();
        assert!(chain.check(&ctx).await.is_ok(), "正常路径应放行");
    }
}