use super::waf::{WafContext, WafHook, WafVerdict};
use crate::i18n::translate_detail;
use async_trait::async_trait;
pub struct WhitePathHook {
paths: Vec<String>,
}
impl WhitePathHook {
pub fn new(paths: Vec<String>) -> Self {
Self { paths }
}
}
fn path_matches(prefix: &str, path: &str) -> bool {
path == prefix || path.starts_with(&format!("{}/", prefix))
}
#[async_trait]
impl WafHook for WhitePathHook {
fn name(&self) -> &'static str {
"white_path"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
let lower = ctx.path.to_lowercase();
if lower.contains("..")
|| lower.contains("//")
|| lower.contains("%2e")
|| lower.contains("%2f")
|| lower.contains("%5c")
|| lower.contains("%25")
{
return WafVerdict::Allow;
}
if self.paths.iter().any(|p| path_matches(p, ctx.path)) {
return WafVerdict::AllowAndSkip;
}
WafVerdict::Allow
}
}
pub struct BlackPathHook {
paths: Vec<String>,
}
impl BlackPathHook {
pub fn new(paths: Vec<String>) -> Self {
Self { paths }
}
}
#[async_trait]
impl WafHook for BlackPathHook {
fn name(&self) -> &'static str {
"black_path"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
if self.paths.is_empty() {
return WafVerdict::Allow;
}
if self.paths.iter().any(|p| ctx.path.starts_with(p)) {
return WafVerdict::Deny {
reason: format!("waf-blacklist-path::{}", ctx.path),
hook: "black_path",
};
}
WafVerdict::Allow
}
}
pub struct DangerCharacterHook;
impl DangerCharacterHook {
pub fn new() -> Self {
Self
}
}
impl Default for DangerCharacterHook {
fn default() -> Self {
Self::new()
}
}
fn check_danger_chars(lower: &str) -> Option<&'static str> {
const PATTERNS: &[(&str, &str)] = &[
("//", "double-slash"),
("\\", "backslash"),
(";", "semicolon"),
("\0", "null-byte"),
("\n", "newline"),
("\r", "carriage-return"),
("%2e", "pct-2e"),
("%2f", "pct-2f"),
("%00", "pct-00"),
("%5c", "pct-5c"),
("%3b", "pct-3b"),
("%0a", "pct-0a"),
("%0d", "pct-0d"),
];
for &(pattern, id) in PATTERNS {
if lower.contains(pattern) {
return Some(id);
}
}
if lower.contains("%25") {
let mut decoded = lower.to_string();
const MAX_DECODE_ROUNDS: usize = 5;
let mut rounds = 0;
while decoded.contains("%25") && rounds < MAX_DECODE_ROUNDS {
decoded = decoded.replace("%25", "%");
rounds += 1;
}
for &(pattern, id) in PATTERNS {
if decoded.contains(pattern) {
return Some(id);
}
}
}
None
}
fn danger_char_i18n(pattern_id: &str) -> String {
let key = match pattern_id {
"double-slash" => "waf-danger-desc-double-slash",
"backslash" => "waf-danger-desc-backslash",
"semicolon" => "waf-danger-desc-semicolon",
"null-byte" => "waf-danger-desc-null-byte",
"newline" => "waf-danger-desc-newline",
"carriage-return" => "waf-danger-desc-carriage-return",
"pct-2e" => "waf-danger-desc-pct-2e",
"pct-2f" => "waf-danger-desc-pct-2f",
"pct-00" => "waf-danger-desc-pct-00",
"pct-5c" => "waf-danger-desc-pct-5c",
"pct-3b" => "waf-danger-desc-pct-3b",
"pct-0a" => "waf-danger-desc-pct-0a",
"pct-0d" => "waf-danger-desc-pct-0d",
_ => pattern_id,
};
translate_detail(key, &[])
}
#[async_trait]
impl WafHook for DangerCharacterHook {
fn name(&self) -> &'static str {
"danger_char"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
let path = ctx.path;
let lower = path.to_lowercase();
if let Some(desc_id) = check_danger_chars(&lower) {
let desc = danger_char_i18n(desc_id);
let combined = format!("{}: {}", ctx.path, desc);
return WafVerdict::Deny {
reason: format!("waf-danger-char-path::{}", combined),
hook: "danger_char",
};
}
for (_, value) in ctx.params {
let lower = value.to_lowercase();
if let Some(desc_id) = check_danger_chars(&lower) {
let desc = danger_char_i18n(desc_id);
let combined = format!("{}: {}", value, desc);
return WafVerdict::Deny {
reason: format!("waf-danger-char-param::{}", combined),
hook: "danger_char",
};
}
}
for (_, value) in ctx.headers {
let lower = value.to_lowercase();
if let Some(desc_id) = check_danger_chars(&lower) {
let desc = danger_char_i18n(desc_id);
let combined = format!("{}: {}", value, desc);
return WafVerdict::Deny {
reason: format!("waf-danger-char-header::{}", combined),
hook: "danger_char",
};
}
}
WafVerdict::Allow
}
}
pub struct BannedCharacterHook;
impl BannedCharacterHook {
pub fn new() -> Self {
Self
}
}
impl Default for BannedCharacterHook {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl WafHook for BannedCharacterHook {
fn name(&self) -> &'static str {
"banned_char"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
for &b in ctx.path.as_bytes() {
if !(0x20..=0x7E).contains(&b) {
return WafVerdict::Deny {
reason: format!("waf-banned-char::(0x{:02X})", b),
hook: "banned_char",
};
}
}
WafVerdict::Allow
}
}
pub struct DirectoryTraversalHook;
impl DirectoryTraversalHook {
pub fn new() -> Self {
Self
}
}
impl Default for DirectoryTraversalHook {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl WafHook for DirectoryTraversalHook {
fn name(&self) -> &'static str {
"dir_traversal"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
const PATTERNS: &[&str] = &["../", "./", "//"];
for &pattern in PATTERNS {
if ctx.path.contains(pattern) {
return WafVerdict::Deny {
reason: format!("waf-dir-traversal::{}", pattern),
hook: "dir_traversal",
};
}
}
WafVerdict::Allow
}
}
pub struct HostHook {
hosts: Vec<String>,
}
impl HostHook {
pub fn new(hosts: Vec<String>) -> Self {
Self { hosts }
}
}
#[async_trait]
impl WafHook for HostHook {
fn name(&self) -> &'static str {
"host"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
if self.hosts.is_empty() {
return WafVerdict::Allow;
}
match ctx.host {
None => WafVerdict::Deny {
reason: "waf-host-missing::".to_string(),
hook: "host",
},
Some(host) => {
if self.hosts.iter().any(|h| h == host) {
WafVerdict::Allow
} else {
WafVerdict::Deny {
reason: format!("waf-host-not-allowed::{}", host),
hook: "host",
}
}
},
}
}
}
pub struct HttpMethodHook {
methods: Vec<String>,
}
impl HttpMethodHook {
pub fn new(methods: Vec<String>) -> Self {
Self { methods }
}
}
#[async_trait]
impl WafHook for HttpMethodHook {
fn name(&self) -> &'static str {
"http_method"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
if self.methods.is_empty() {
return WafVerdict::Allow;
}
if self.methods.iter().any(|m| m == ctx.method) {
WafVerdict::Allow
} else {
WafVerdict::Deny {
reason: format!("waf-method-not-allowed::{}", ctx.method),
hook: "http_method",
}
}
}
}
pub struct HeaderHook {
headers: Vec<String>,
}
impl HeaderHook {
pub fn new(headers: Vec<String>) -> Self {
Self { headers }
}
}
#[async_trait]
impl WafHook for HeaderHook {
fn name(&self) -> &'static str {
"header"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
if self.headers.is_empty() {
return WafVerdict::Allow;
}
for banned in &self.headers {
let banned_lower = banned.to_lowercase();
for (name, _) in ctx.headers {
if name.to_lowercase() == banned_lower {
return WafVerdict::Deny {
reason: format!("waf-header-banned::{}", name),
hook: "header",
};
}
}
}
WafVerdict::Allow
}
}
pub struct ParameterHook {
params: Vec<String>,
}
impl ParameterHook {
pub fn new(params: Vec<String>) -> Self {
Self { params }
}
}
#[async_trait]
impl WafHook for ParameterHook {
fn name(&self) -> &'static str {
"parameter"
}
async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
if self.params.is_empty() {
return WafVerdict::Allow;
}
for banned in &self.params {
for (name, _) in ctx.params {
if name == banned {
return WafVerdict::Deny {
reason: format!("waf-param-banned::{}", name),
hook: "parameter",
};
}
}
}
WafVerdict::Allow
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::strategy::firewall::WafHookChain;
use std::sync::{Arc, Mutex};
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
}
}
fn make_ctx<'a>(
path: &'a str,
method: &'a str,
host: Option<&'a str>,
headers: &'a [(String, String)],
params: &'a [(String, String)],
) -> WafContext<'a> {
WafContext {
path,
method,
host,
headers,
params,
}
}
fn default_ctx<'a>() -> WafContext<'a> {
make_ctx("/api/test", "GET", Some("example.com"), &[], &[])
}
#[tokio::test]
async fn white_path_match_returns_allow_and_skip() {
let hook = WhitePathHook::new(vec!["/api".to_string()]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::AllowAndSkip));
}
#[tokio::test]
async fn white_path_no_match_returns_allow() {
let hook = WhitePathHook::new(vec!["/admin".to_string()]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn white_path_empty_returns_allow() {
let hook = WhitePathHook::new(vec![]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn black_path_match_returns_deny() {
let hook = BlackPathHook::new(vec!["/admin".to_string()]);
let ctx = make_ctx("/admin/secret", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn black_path_no_match_returns_allow() {
let hook = BlackPathHook::new(vec!["/admin".to_string()]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn black_path_empty_returns_allow() {
let hook = BlackPathHook::new(vec![]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn danger_char_double_slash_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn danger_char_backslash_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api\\test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn danger_char_normal_path_returns_allow() {
let hook = DangerCharacterHook::new();
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn banned_char_non_printable_returns_deny() {
let hook = BannedCharacterHook::new();
let ctx = make_ctx("/api\x01test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn banned_char_normal_path_returns_allow() {
let hook = BannedCharacterHook::new();
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn dir_traversal_dot_dot_slash_returns_deny() {
let hook = DirectoryTraversalHook::new();
let ctx = make_ctx("/api/../etc/passwd", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn dir_traversal_dot_slash_returns_deny() {
let hook = DirectoryTraversalHook::new();
let ctx = make_ctx("/api/./test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn dir_traversal_normal_path_returns_allow() {
let hook = DirectoryTraversalHook::new();
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn host_not_in_whitelist_returns_deny() {
let hook = HostHook::new(vec!["allowed.com".to_string()]);
let ctx = make_ctx("/api/test", "GET", Some("evil.com"), &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn host_in_whitelist_returns_allow() {
let hook = HostHook::new(vec!["example.com".to_string()]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn host_none_returns_deny_fail_closed() {
let hook = HostHook::new(vec!["example.com".to_string()]);
let ctx = make_ctx("/api/test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"白名单非空且无 Host 头应 Deny(fail-closed)"
);
}
#[tokio::test]
async fn http_method_not_allowed_returns_deny() {
let hook = HttpMethodHook::new(vec!["GET".to_string()]);
let ctx = make_ctx("/api/test", "POST", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn http_method_allowed_returns_allow() {
let hook = HttpMethodHook::new(vec!["GET".to_string(), "POST".to_string()]);
let ctx = default_ctx();
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn header_banned_returns_deny() {
let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
let headers = vec![("X-Forbidden".to_string(), "value".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn header_not_banned_returns_allow() {
let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
let headers = vec![("Content-Type".to_string(), "application/json".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn parameter_banned_returns_deny() {
let hook = ParameterHook::new(vec!["password".to_string()]);
let params = vec![("password".to_string(), "secret".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &[], ¶ms);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Deny { .. }));
}
#[tokio::test]
async fn parameter_not_banned_returns_allow() {
let hook = ParameterHook::new(vec!["password".to_string()]);
let params = vec![("username".to_string(), "admin".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &[], ¶ms);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn danger_char_percent_00_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%00test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"path 含 %00 应被拦截"
);
}
#[tokio::test]
async fn danger_char_percent_5c_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%5ctest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"path 含 %5c 应被拦截"
);
}
#[tokio::test]
async fn danger_char_percent_3b_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%3btest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"path 含 %3b 应被拦截"
);
}
#[tokio::test]
async fn danger_char_percent_0a_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%0atest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"path 含 %0a 应被拦截"
);
}
#[tokio::test]
async fn danger_char_percent_0d_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%0dtest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"path 含 %0d 应被拦截"
);
}
#[tokio::test]
async fn danger_char_uppercase_percent_encoded_returns_deny() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%2Etest", "GET", None, &[], &[]);
assert!(
matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
"path 含 %2E 应被拦截"
);
let ctx = make_ctx("/api/%2Ftest", "GET", None, &[], &[]);
assert!(
matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
"path 含 %2F 应被拦截"
);
let ctx = make_ctx("/api/%00test", "GET", None, &[], &[]);
assert!(
matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
"path 含 %00 应被拦截"
);
}
#[tokio::test]
async fn danger_char_query_param_value_returns_deny() {
let hook = DangerCharacterHook::new();
let params = vec![("q".to_string(), "a//b".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &[], ¶ms);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"参数值含 // 应被拦截"
);
}
#[tokio::test]
async fn danger_char_header_value_returns_deny() {
let hook = DangerCharacterHook::new();
let headers = vec![("X-Custom".to_string(), "a\\b".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"header 值含 \\ 应被拦截"
);
}
#[tokio::test]
async fn white_path_match_short_circuits_chain() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = default_ctx(); let result = chain.check(&ctx).await;
assert!(result.is_ok(), "WhitePathHook 匹配时应放行");
let executed = log.lock().unwrap();
assert!(
executed.is_empty(),
"WhitePathHook 匹配时应短路,后续 Hook 不应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_no_match_continues_chain() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/admin".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = default_ctx(); let result = chain.check(&ctx).await;
assert!(result.is_ok());
let executed = log.lock().unwrap();
assert_eq!(
executed.len(),
1,
"WhitePathHook 不匹配时后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_traversal_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api/../admin", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(result.is_ok(), "含 .. 的路径应放行(不短路)");
let executed = log.lock().unwrap();
assert!(
!executed.is_empty(),
"含 .. 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_double_slash_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(result.is_ok(), "含 // 的路径应放行(不短路)");
let executed = log.lock().unwrap();
assert!(
!executed.is_empty(),
"含 // 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_url_encoded_traversal_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api/%2e%2e/admin", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(result.is_ok(), "含 %2e%2e 的路径应放行(不短路)");
let executed = log.lock().unwrap();
assert!(
!executed.is_empty(),
"含 %2e%2e 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_url_encoded_slash_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api%2ftest", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(result.is_ok(), "含 %2f 的路径应放行(不短路)");
let executed = log.lock().unwrap();
assert!(
!executed.is_empty(),
"含 %2f 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn white_path_exact_match_returns_allow_and_skip() {
let hook = WhitePathHook::new(vec!["/api".to_string()]);
let ctx = make_ctx("/api", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::AllowAndSkip),
"精确匹配 /api 应返回 AllowAndSkip"
);
}
#[tokio::test]
async fn white_path_segment_match_returns_allow_and_skip() {
let hook = WhitePathHook::new(vec!["/api".to_string()]);
let ctx = make_ctx("/api/test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::AllowAndSkip),
"段前缀匹配 /api/test 应返回 AllowAndSkip"
);
}
#[tokio::test]
async fn white_path_prefix_confusion_not_matched() {
let hook = WhitePathHook::new(vec!["/api".to_string()]);
let ctx = make_ctx("/api-v2/secret", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Allow),
"前缀混淆 /api-v2/secret 不应命中 /api 白名单"
);
}
#[tokio::test]
async fn double_encoding_percent_252e_detected() {
let mut chain = WafHookChain::new();
chain.register(Box::new(DangerCharacterHook::new()));
let ctx = crate::strategy::firewall::WafContext {
path: "/api/%252e%252e/admin",
method: "GET",
host: Some("example.com"),
headers: &[],
params: &[],
};
let result = chain.check(&ctx).await;
assert!(result.is_err(), "%252e 双重编码应被拦截");
}
#[tokio::test]
async fn white_path_percent_5c_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api%5ctest", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(result.is_ok(), "含 %5c 的路径应放行(不短路)");
let executed = log.lock().unwrap();
assert!(
!executed.is_empty(),
"含 %5c 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
executed
);
}
#[tokio::test]
async fn banned_char_high_ascii_returns_deny() {
let hook = BannedCharacterHook::new();
let ctx = make_ctx("/api\u{80}test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"高于 0x7E 的字符应被拦截"
);
}
#[tokio::test]
async fn dir_traversal_double_slash_returns_deny() {
let hook = DirectoryTraversalHook::new();
let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"含 // 的路径应被拦截"
);
}
#[tokio::test]
async fn host_empty_list_returns_allow() {
let hook = HostHook::new(vec![]);
let ctx = make_ctx("/api/test", "GET", Some("evil.com"), &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn http_method_empty_list_returns_allow() {
let hook = HttpMethodHook::new(vec![]);
let ctx = make_ctx("/api/test", "DELETE", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn header_empty_list_returns_allow() {
let hook = HeaderHook::new(vec![]);
let headers = vec![("X-Any".to_string(), "v".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn parameter_empty_list_returns_allow() {
let hook = ParameterHook::new(vec![]);
let params = vec![("any".to_string(), "v".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &[], ¶ms);
let verdict = hook.check(&ctx).await;
assert!(matches!(verdict, WafVerdict::Allow));
}
#[tokio::test]
async fn header_case_insensitive_match_returns_deny() {
let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
let headers = vec![("x-forbidden".to_string(), "value".to_string())];
let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"大小写不敏感匹配应命中黑名单"
);
}
#[tokio::test]
async fn danger_char_double_encoding_percent_25_2f_detected() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%252ftest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"%252f 双重编码应被拦截"
);
}
#[tokio::test]
async fn danger_char_triple_encoding_percent_25252e_detected() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%25252e%25252e/admin", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"%25252e 三重编码应被拦截"
);
}
#[tokio::test]
async fn danger_char_quadruple_encoding_detected() {
let hook = DangerCharacterHook::new();
let ctx = make_ctx("/api/%2525252ftest", "GET", None, &[], &[]);
let verdict = hook.check(&ctx).await;
assert!(
matches!(verdict, WafVerdict::Deny { .. }),
"%2525252f 四重编码应被拦截"
);
}
#[tokio::test]
async fn white_path_double_encoded_traversal_not_short_circuited() {
let log = Arc::new(Mutex::new(Vec::new()));
let mut chain = WafHookChain::new();
chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
chain.register(Box::new(DangerCharacterHook::new()));
chain.register(Box::new(RecordingHook {
hook_name: "recorder",
log: log.clone(),
}));
let ctx = make_ctx("/api/%252e%252e/admin", "GET", None, &[], &[]);
let result = chain.check(&ctx).await;
assert!(
result.is_err(),
"含 %252e 的白名单路径不应被短路放行,应被 danger_char 拦截"
);
}
}