use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::GarrisonDaoStorage;
use crate::strategy::firewall::{CaptchaChallenge, FirewallContext, GarrisonFirewallStrategy};
use async_trait::async_trait;
use limiteron::storage::Storage;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex;
const RATE_LIMIT_SLIDING_WINDOW_LUA: &str = "-- rate_limit_sliding_window\n\
local raw = redis.call('GET', KEYS[1]) or ''\n\
local timestamps = {}\n\
for ts in string.gmatch(raw, '[^,]+') do\n\
local t = tonumber(ts)\n\
if t and t > tonumber(ARGV[2]) then\n\
table.insert(timestamps, t)\n\
end\n\
end\n\
if #timestamps >= tonumber(ARGV[3]) then\n\
return 0\n\
end\n\
table.insert(timestamps, tonumber(ARGV[1]))\n\
local new_raw = table.concat(timestamps, ',')\n\
redis.call('SETEX', KEYS[1], tonumber(ARGV[4]), new_raw)\n\
return 1";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RateLimitScope {
Ip,
User,
Tenant,
}
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
pub max_requests: u32,
pub window_seconds: u64,
pub scope: RateLimitScope,
pub dynamic_threshold: Option<usize>,
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self {
max_requests: 100,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
}
}
}
pub struct RateLimitStrategy {
config: RateLimitConfig,
storage: Arc<dyn Storage>,
dao: Arc<dyn GarrisonDao>,
atomic_lock: Mutex<()>,
}
impl RateLimitStrategy {
pub fn new(config: RateLimitConfig, dao: Arc<dyn GarrisonDao>) -> Self {
let storage = Arc::new(GarrisonDaoStorage::new(dao.clone()));
Self {
config,
storage,
dao,
atomic_lock: Mutex::new(()),
}
}
pub async fn set_expected_answer(
&self,
ctx: &FirewallContext,
answer: &str,
) -> GarrisonResult<()> {
let (key, _) = self.build_key(ctx)?;
let answer_key = format!("{}:answer", key);
self.storage
.set(&answer_key, answer, Some(self.config.window_seconds))
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))
}
pub async fn current_threshold(&self, ctx: &FirewallContext) -> GarrisonResult<usize> {
let max = self.config.max_requests as usize;
let Some(upper) = self.config.dynamic_threshold else {
return Ok(max);
};
let (key, _) = self.build_key(ctx)?;
let threshold_key = format!("{}:threshold", key);
let stored = self
.storage
.get(&threshold_key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
let raw: usize = stored
.as_deref()
.and_then(|s| s.parse().ok())
.unwrap_or(max);
Ok(raw.clamp(max, upper))
}
pub async fn adjust_threshold(
&self,
ctx: &FirewallContext,
traffic_count: usize,
) -> GarrisonResult<usize> {
let max = self.config.max_requests as usize;
let Some(upper) = self.config.dynamic_threshold else {
return Ok(max);
};
let (key, _) = self.build_key(ctx)?;
let threshold_key = format!("{}:threshold", key);
let current = self.current_threshold(ctx).await?;
let step = (max / 10).max(1);
let new_threshold = if traffic_count.saturating_mul(5) >= current.saturating_mul(4) {
(current + step).min(upper)
} else if traffic_count.saturating_mul(5) < current {
current.saturating_sub(step).max(max)
} else {
current
};
self.storage
.set(
&threshold_key,
&new_threshold.to_string(),
Some(self.config.window_seconds),
)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
Ok(new_threshold)
}
fn build_key(&self, ctx: &FirewallContext) -> GarrisonResult<(String, String)> {
match self.config.scope {
RateLimitScope::Ip => Ok((format!("rl:ip:{}", ctx.ip), ctx.ip.clone())),
RateLimitScope::User => match &ctx.login_id {
Some(id) => Ok((format!("rl:user:{}", id), id.clone())),
None => Err(GarrisonError::InvalidParam(
"RateLimit scope=User 但 ctx.login_id 为 None".to_string(),
)),
},
RateLimitScope::Tenant => match ctx.tenant_id {
Some(id) => Ok((format!("rl:tenant:{}", id), id.to_string())),
None => Err(GarrisonError::InvalidParam(
"RateLimit scope=Tenant 但 ctx.tenant_id 为 None".to_string(),
)),
},
}
}
}
#[async_trait]
impl GarrisonFirewallStrategy for RateLimitStrategy {
async fn check(&self, ctx: &FirewallContext) -> GarrisonResult<()> {
let (key, scope_id) = self.build_key(ctx)?;
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| GarrisonError::Dao(format!("strategy-system-time::{}", e)))?
.as_millis() as u64;
let window_start = now_ms.saturating_sub(self.config.window_seconds * 1000);
let threshold = self.current_threshold(ctx).await?;
let lua_result = self
.dao
.eval_lua(
RATE_LIMIT_SLIDING_WINDOW_LUA,
vec![key.clone()],
vec![
now_ms.to_string(),
window_start.to_string(),
threshold.to_string(),
self.config.window_seconds.to_string(),
],
)
.await;
match lua_result {
Ok(vals) => {
let allowed = vals.first().map(|s| s == "1").unwrap_or(false);
if allowed {
return Ok(());
}
return Err(GarrisonError::FirewallBlocked(format!(
"strategy-firewall-ratelimit-blocked::{}::{}::lua::{}",
scope_id,
format!("{:?}", self.config.scope).to_lowercase(),
threshold
)));
},
Err(GarrisonError::NotImplemented(_)) => {
tracing::debug!(
"rate_limit: eval_lua unavailable, falling back to atomic_lock path (in-process atomic only)"
);
self.check_fallback(&key, &scope_id, now_ms, window_start, threshold)
.await
},
Err(e) => {
Err(GarrisonError::Dao(format!(
"strategy-limiter-eval-lua::{}",
e
)))
},
}
}
}
impl RateLimitStrategy {
async fn check_fallback(
&self,
key: &str,
scope_id: &str,
now_ms: u64,
window_start: u64,
threshold: usize,
) -> GarrisonResult<()> {
let _guard = self.atomic_lock.lock().await;
let stored = self
.storage
.get(key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
let mut timestamps: Vec<u64> = stored
.as_deref()
.unwrap_or("")
.split(',')
.filter(|s| !s.is_empty())
.filter_map(|s| match s.parse::<u64>() {
Ok(v) => Some(v),
Err(_) => {
tracing::warn!(key = %key, raw = %s, "rate_limit: timestamp parse failed, skipping entry (possible storage layer concurrent write truncation)");
None
}
})
.collect();
timestamps.retain(|&t| t > window_start);
if timestamps.len() >= threshold {
return Err(GarrisonError::FirewallBlocked(format!(
"strategy-firewall-ratelimit-blocked::{}::{}::{}::{}",
scope_id,
format!("{:?}", self.config.scope).to_lowercase(),
timestamps.len(),
threshold
)));
}
timestamps.push(now_ms);
let serialized: String = timestamps
.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>()
.join(",");
self.storage
.set(key, &serialized, Some(self.config.window_seconds))
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
Ok(())
}
}
#[async_trait]
impl CaptchaChallenge for RateLimitStrategy {
async fn should_challenge(&self, ctx: &FirewallContext) -> GarrisonResult<bool> {
let (key, _) = self.build_key(ctx)?;
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| GarrisonError::Dao(format!("strategy-system-time::{}", e)))?
.as_millis() as u64;
let window_start = now_ms.saturating_sub(self.config.window_seconds * 1000);
let stored = self
.storage
.get(&key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
let count: usize = stored
.as_deref()
.unwrap_or("")
.split(',')
.filter(|s| !s.is_empty())
.filter_map(|s| s.parse::<u64>().ok())
.filter(|&t| t > window_start)
.count();
let threshold = self.current_threshold(ctx).await?;
Ok(count.saturating_mul(5) >= threshold.saturating_mul(4))
}
async fn verify_challenge(&self, ctx: &FirewallContext, answer: &str) -> GarrisonResult<bool> {
let (key, _) = self.build_key(ctx)?;
let answer_key = format!("{}:answer", key);
let stored = self
.storage
.get(&answer_key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
let matched = stored.as_deref() == Some(answer);
if matched {
self.storage
.delete(&answer_key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
}
Ok(matched)
}
}
inventory::submit! {
crate::strategy::firewall::StrategyRegistration {
name: "ratelimit",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
use crate::error::GarrisonError;
#[tokio::test]
async fn ratelimit_blocks_after_max_requests() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 1,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
for i in 1..=10 {
assert!(strategy.check(&ctx).await.is_ok(), "第 {} 次应通过", i);
}
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"第 11 次应返回 FirewallBlocked,实际: {:?}",
result
);
}
#[tokio::test]
async fn ratelimit_scope_user_isolates_by_login_id() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 2,
window_seconds: 60,
scope: RateLimitScope::User,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx_a = FirewallContext::new("192.168.1.1").with_login_id("1001");
let ctx_b = FirewallContext::new("192.168.1.2").with_login_id("1002");
assert!(strategy.check(&ctx_a).await.is_ok());
assert!(strategy.check(&ctx_a).await.is_ok());
assert!(matches!(
strategy.check(&ctx_a).await,
Err(GarrisonError::FirewallBlocked(_))
));
assert!(strategy.check(&ctx_b).await.is_ok());
}
#[tokio::test]
async fn ratelimit_scope_user_without_login_id_fails() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::User,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"scope=User 且 login_id=None 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn captcha_challenge_should_trigger_when_rate_limit_near() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
for _ in 0..8 {
assert!(strategy.check(&ctx).await.is_ok());
}
let should = strategy
.should_challenge(&ctx)
.await
.expect("should_challenge 不应报错");
assert!(should, "达到 80% 阈值时应触发验证码挑战,实际: {}", should);
}
#[tokio::test]
async fn captcha_challenge_should_not_trigger_when_below_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy.check(&ctx).await.expect("check 不应报错");
let should = strategy
.should_challenge(&ctx)
.await
.expect("should_challenge 不应报错");
assert!(!should, "远低于阈值时不应触发挑战,实际: {}", should);
}
#[tokio::test]
async fn captcha_challenge_verify_correct_answer() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let ok = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("verify_challenge 不应报错");
assert!(ok, "正确答案应通过验证");
}
#[tokio::test]
async fn captcha_challenge_verify_incorrect_answer() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let ok = strategy
.verify_challenge(&ctx, "wrong-answer")
.await
.expect("verify_challenge 不应报错");
assert!(!ok, "错误答案应验证失败");
}
#[tokio::test]
async fn captcha_challenge_verify_deletes_answer_after_success() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let first = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("首次 verify_challenge 不应报错");
assert!(first, "首次正确答案应通过");
let second = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("二次 verify_challenge 不应报错");
assert!(
!second,
"验证码验证通过后应被删除,二次使用同一答案应失败(C-6)"
);
}
#[tokio::test]
async fn dynamic_threshold_increases_when_traffic_high() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let initial = strategy
.current_threshold(&ctx)
.await
.expect("current_threshold 不应报错");
assert_eq!(initial, 10, "初始阈值应为 max_requests");
let after_high = strategy
.adjust_threshold(&ctx, 9)
.await
.expect("adjust_threshold 不应报错");
assert!(after_high > 10, "高流量后阈值应上调,实际: {}", after_high);
assert!(
after_high <= 20,
"阈值不应超过 dynamic_threshold 上限,实际: {}",
after_high
);
let mut current = after_high;
for i in 0..20 {
current = strategy
.adjust_threshold(&ctx, current)
.await
.expect("adjust_threshold 不应报错");
if current >= 20 {
break;
}
assert!(current <= 20, "第 {} 次调整后阈值越界: {}", i, current);
}
assert_eq!(
current, 20,
"持续高流量应封顶到 dynamic_threshold,实际: {}",
current
);
}
#[tokio::test]
async fn dynamic_threshold_decreases_when_traffic_low() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let mut current = strategy
.current_threshold(&ctx)
.await
.expect("current_threshold 不应报错");
for _ in 0..20 {
current = strategy
.adjust_threshold(&ctx, current)
.await
.expect("adjust_threshold 不应报错");
if current >= 20 {
break;
}
}
let peaked = current;
assert_eq!(peaked, 20, "高流量应将阈值推到上限");
let after_low = strategy
.adjust_threshold(&ctx, 0)
.await
.expect("adjust_threshold 不应报错");
assert!(
after_low < peaked,
"低流量后阈值应下调,实际: {}",
after_low
);
assert!(
after_low >= 10,
"阈值不应低于 max_requests,实际: {}",
after_low
);
let mut current = after_low;
for _ in 0..20 {
current = strategy
.adjust_threshold(&ctx, 0)
.await
.expect("adjust_threshold 不应报错");
if current <= 10 {
break;
}
}
assert_eq!(
current, 10,
"持续低流量应触底到 max_requests,实际: {}",
current
);
}
#[tokio::test]
async fn check_uses_dynamic_threshold_not_max_requests() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let mut current = strategy
.current_threshold(&ctx)
.await
.expect("current_threshold 不应报错");
for _ in 0..20 {
current = strategy
.adjust_threshold(&ctx, current)
.await
.expect("adjust_threshold 不应报错");
if current >= 20 {
break;
}
}
assert_eq!(current, 20, "阈值应已上调到 20");
for i in 1..=16 {
assert!(
strategy.check(&ctx).await.is_ok(),
"动态阈值=20 时第 {} 次 check 应通过(旧 bug 会在此拦截)",
i
);
}
for i in 17..=20 {
assert!(
strategy.check(&ctx).await.is_ok(),
"动态阈值=20 时第 {} 次 check 应通过",
i
);
}
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"动态阈值=20 时第 21 次 check 应被拦截,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn check_concurrent_only_max_requests_allowed_lua_path() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 5,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = Arc::new(RateLimitStrategy::new(config, dao));
let ctx = Arc::new(FirewallContext::new("10.0.0.1"));
let mut handles = Vec::new();
for _ in 0..20 {
let s = strategy.clone();
let c = ctx.clone();
handles.push(tokio::spawn(async move { s.check(&c).await }));
}
let mut allowed = 0;
let mut blocked = 0;
for handle in handles {
match handle.await.expect("tokio task panicked") {
Ok(()) => allowed += 1,
Err(GarrisonError::FirewallBlocked(_)) => blocked += 1,
Err(e) => {
panic!("check 不应返回非 FirewallBlocked 错误: {:?}", e);
},
}
}
assert_eq!(
allowed, 5,
"Lua 路径:并发 check 仅 max_requests=5 个返回 Ok(防 TOCTOU 绕过),实际: {}",
allowed
);
assert_eq!(blocked, 15, "其余 15 个应被拦截");
}
#[tokio::test(flavor = "multi_thread")]
async fn check_concurrent_only_max_requests_allowed_fallback_path() {
use crate::dao::tests::MinimalDao;
let dao: Arc<dyn GarrisonDao> = Arc::new(MinimalDao::new());
let config = RateLimitConfig {
max_requests: 5,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = Arc::new(RateLimitStrategy::new(config, dao));
let ctx = Arc::new(FirewallContext::new("10.0.0.2"));
let mut handles = Vec::new();
for _ in 0..20 {
let s = strategy.clone();
let c = ctx.clone();
handles.push(tokio::spawn(async move { s.check(&c).await }));
}
let mut allowed = 0;
let mut blocked = 0;
for handle in handles {
match handle.await.expect("tokio task panicked") {
Ok(()) => allowed += 1,
Err(GarrisonError::FirewallBlocked(_)) => blocked += 1,
Err(e) => {
panic!("check 不应返回非 FirewallBlocked 错误: {:?}", e);
},
}
}
assert_eq!(
allowed, 5,
"降级路径:atomic_lock 保护下并发 check 仅 max_requests=5 个返回 Ok,实际: {}",
allowed
);
assert_eq!(blocked, 15, "其余 15 个应被拦截");
}
#[tokio::test]
async fn check_lua_path_preserves_serial_semantics() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 3,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("10.0.0.3");
assert!(strategy.check(&ctx).await.is_ok(), "第 1 次 check 应通过");
assert!(strategy.check(&ctx).await.is_ok(), "第 2 次 check 应通过");
assert!(strategy.check(&ctx).await.is_ok(), "第 3 次 check 应通过");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"第 4 次 check 应被拦截,实际: {:?}",
result
);
}
}