Skip to main content

yang_base/action/auth/
rate_limit.rs

1//! 认证入口的 Redis 原子限流。
2//!
3//! 登录、注册、改密、Step-up 等凭据猜测入口共用同一套限流机制:按来源 IP 与业务身份
4//! (用户名/用户 ID/指纹)双维度计数,所有计数与窗口过期在单个 Lua 脚本内原子完成,
5//! 超限返回 [`BaseError::RateLimitExceeded`] 并携带 `retry_after_seconds`。
6//! 阈值、窗口与 Redis key 前缀全部经 [`AuthRateLimitConfig`] 注入,不读取应用配置。
7
8use crate::action::ActionContext;
9use crate::transport::client_ip::client_ip_identity;
10use yang_base::BaseError;
11
12const RATE_LIMIT_SCRIPT: &str = r#"
13local exceeded = 0
14local retry_after = 0
15local window = tonumber(ARGV[1])
16
17for index, key in ipairs(KEYS) do
18    local current = redis.call('INCR', key)
19    if current == 1 then
20        redis.call('EXPIRE', key, window)
21    end
22
23    local ttl = redis.call('TTL', key)
24    if ttl < 1 then
25        redis.call('EXPIRE', key, window)
26        ttl = window
27    end
28
29    local limit = tonumber(ARGV[index + 1])
30    if current > limit then
31        exceeded = 1
32        if ttl > retry_after then
33            retry_after = ttl
34        end
35    end
36end
37
38return { exceeded, retry_after }
39"#;
40
41const FAILURE_COUNT_SCRIPT: &str = r#"
42local exceeded = 0
43local retry_after = 0
44local window = tonumber(ARGV[1])
45
46for index, key in ipairs(KEYS) do
47    local current = redis.call('INCR', key)
48    if current == 1 then
49        redis.call('EXPIRE', key, window)
50    end
51
52    local ttl = redis.call('TTL', key)
53    if ttl < 1 then
54        redis.call('EXPIRE', key, window)
55        ttl = window
56    end
57
58    local limit = tonumber(ARGV[index + 1])
59    if current > limit then
60        exceeded = 1
61        if ttl > retry_after then
62            retry_after = ttl
63        end
64    end
65end
66
67return { exceeded, retry_after }
68"#;
69
70/// 认证相关限流操作:决定 Redis key 的操作段与身份段。
71#[derive(Clone, Copy)]
72pub enum AuthOperation {
73    /// 修改密码(按用户 ID 计数)。
74    ChangePassword,
75    /// 创建密码重置凭证(按操作者-目标对计数)。
76    PasswordResetCreate,
77    /// 消费密码重置凭证(按凭证指纹计数)。
78    PasswordResetConsume,
79    /// 登录(按用户名计数)。
80    Login,
81    /// 注册(按用户名计数)。
82    Register,
83    /// 完成 Step-up 重认证(按用户名计数)。
84    StepUpComplete,
85    /// 校验 TOTP 第二因子码(按用户名计数;凭据猜测的在线入口)。
86    TotpVerify,
87    /// 生成/激活 TOTP 配置(按用户名计数;激活码重试入口)。
88    TotpSetup,
89}
90
91impl AuthOperation {
92    fn key(self) -> &'static str {
93        match self {
94            Self::ChangePassword => "change-password",
95            Self::PasswordResetCreate => "password-reset-create",
96            Self::PasswordResetConsume => "password-reset-consume",
97            Self::Login => "login",
98            Self::Register => "register",
99            Self::StepUpComplete => "step-up-complete",
100            Self::TotpVerify => "totp-verify",
101            Self::TotpSetup => "totp-setup",
102        }
103    }
104
105    fn identity_key(self) -> &'static str {
106        match self {
107            Self::ChangePassword => "user",
108            Self::PasswordResetCreate => "actor-target",
109            Self::PasswordResetConsume => "fingerprint",
110            Self::Login
111            | Self::Register
112            | Self::StepUpComplete
113            | Self::TotpVerify
114            | Self::TotpSetup => "username",
115        }
116    }
117}
118
119/// [`AuthRateLimiter`] 的独立参数结构:阈值、窗口、Redis key 前缀与指标名。
120#[derive(Clone)]
121pub struct AuthRateLimitConfig {
122    /// 计数窗口长度(秒)。
123    pub window_seconds: u64,
124    /// 窗口内单来源 IP 允许的最大尝试次数。
125    pub ip_attempts: u64,
126    /// 窗口内单身份(用户名等)允许的最大尝试次数。
127    pub username_attempts: u64,
128    /// Redis key 前缀(按应用隔离,如 `"yang-system"`)。
129    pub key_prefix: String,
130    /// 限流判定计数器指标名(`metrics` feature 启用时发出)。
131    pub metric_name: &'static str,
132}
133
134/// 认证入口限流器:来源 IP + 业务身份双维度的 Redis 原子计数。
135#[derive(Clone)]
136pub struct AuthRateLimiter {
137    config: AuthRateLimitConfig,
138}
139
140impl AuthRateLimiter {
141    /// 用独立参数结构创建限流器。
142    pub fn new(config: AuthRateLimitConfig) -> Self {
143        Self { config }
144    }
145
146    /// 记录一次尝试并判定是否超限。
147    pub async fn check(
148        &self,
149        ctx: &ActionContext,
150        operation: AuthOperation,
151        identity: &str,
152    ) -> Result<(), BaseError> {
153        let source = client_ip_identity(ctx);
154        let prefix = format!("{}:auth-rate:{}", self.config.key_prefix, operation.key());
155        let keys = [
156            format!("{prefix}:ip:{source}"),
157            format!("{prefix}:{}:{identity}", operation.identity_key()),
158        ];
159        let args = [
160            self.config.window_seconds.to_string(),
161            self.config.ip_attempts.to_string(),
162            self.config.username_attempts.to_string(),
163        ];
164        let cache = ctx.tools().cache()?;
165        let script = cache.script(RATE_LIMIT_SCRIPT);
166        let decision: Result<(i64, i64), _> = cache.eval_script(&script, &keys, &args).await;
167        match decision {
168            Ok((exceeded, retry_after)) => {
169                let result = rate_limit_result(exceeded, retry_after);
170                #[cfg(feature = "metrics")]
171                metrics::counter!(
172                    self.config.metric_name,
173                    "operation" => operation.key(),
174                    "result" => if result.is_ok() { "allowed" } else { "limited" }
175                )
176                .increment(1);
177                result
178            }
179            Err(error) => {
180                #[cfg(feature = "metrics")]
181                metrics::counter!(
182                    self.config.metric_name,
183                    "operation" => operation.key(),
184                    "result" => "unavailable"
185                )
186                .increment(1);
187                Err(error.into())
188            }
189        }
190    }
191
192    /// 记录一次认证失败;失败计数超限同样返回限流错误。
193    pub async fn record_failure(
194        &self,
195        ctx: &ActionContext,
196        operation: AuthOperation,
197        identity: &str,
198    ) -> Result<(), BaseError> {
199        let keys = self.failure_keys(ctx, operation, identity);
200        let args = [
201            self.config.window_seconds.to_string(),
202            self.config.ip_attempts.to_string(),
203            self.config.username_attempts.to_string(),
204        ];
205        let cache = ctx.tools().cache()?;
206        let script = cache.script(FAILURE_COUNT_SCRIPT);
207        let decision: (i64, i64) = cache.eval_script(&script, &keys, &args).await?;
208        rate_limit_result(decision.0, decision.1)
209    }
210
211    /// 认证成功后清除该身份的失败计数。
212    pub async fn clear_failures(
213        &self,
214        ctx: &ActionContext,
215        operation: AuthOperation,
216        identity: &str,
217    ) -> Result<(), BaseError> {
218        let keys = self.failure_keys(ctx, operation, identity);
219        ctx.tools().cache()?.del(&keys).await?;
220        Ok(())
221    }
222
223    fn failure_keys(
224        &self,
225        ctx: &ActionContext,
226        operation: AuthOperation,
227        identity: &str,
228    ) -> [String; 2] {
229        let source = client_ip_identity(ctx);
230        let prefix = format!(
231            "{}:auth-failure:{}",
232            self.config.key_prefix,
233            operation.key()
234        );
235        [
236            format!("{prefix}:ip:{source}"),
237            format!("{prefix}:{}:{identity}", operation.identity_key()),
238        ]
239    }
240}
241
242fn rate_limit_result(exceeded: i64, retry_after: i64) -> Result<(), BaseError> {
243    if exceeded == 0 {
244        return Ok(());
245    }
246    Err(BaseError::RateLimitExceeded {
247        retry_after_seconds: u64::try_from(retry_after).unwrap_or(1).max(1),
248    })
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::action::{Request, RequestMeta};
255    use crate::tools::ToolsBuilder;
256    use crate::transport::client_ip::CLIENT_IP_META_KEY;
257    use std::net::SocketAddr;
258    use std::sync::Arc;
259
260    fn test_config() -> AuthRateLimitConfig {
261        AuthRateLimitConfig {
262            window_seconds: 60,
263            ip_attempts: 10,
264            username_attempts: 5,
265            key_prefix: "yang-system".to_string(),
266            metric_name: "yang_system_auth_rate_limit_total",
267        }
268    }
269
270    #[test]
271    fn maps_redis_decision_to_standard_rate_limit_error() {
272        assert!(rate_limit_result(0, 0).is_ok());
273        assert!(matches!(
274            rate_limit_result(1, 17),
275            Err(BaseError::RateLimitExceeded {
276                retry_after_seconds: 17
277            })
278        ));
279        assert!(matches!(
280            rate_limit_result(1, -1),
281            Err(BaseError::RateLimitExceeded {
282                retry_after_seconds: 1
283            })
284        ));
285    }
286
287    #[test]
288    fn operation_keys_are_isolated() {
289        assert_ne!(AuthOperation::Login.key(), AuthOperation::Register.key());
290        assert_ne!(
291            AuthOperation::ChangePassword.key(),
292            AuthOperation::Login.key()
293        );
294        assert_eq!(AuthOperation::ChangePassword.identity_key(), "user");
295        assert_eq!(AuthOperation::Login.identity_key(), "username");
296        assert_ne!(
297            AuthOperation::StepUpComplete.key(),
298            AuthOperation::Login.key()
299        );
300        assert_eq!(AuthOperation::StepUpComplete.identity_key(), "username");
301    }
302
303    #[test]
304    fn rate_limit_identity_prefers_trusted_transport_extension() {
305        let tools = ToolsBuilder::new()
306            .build()
307            .unwrap_or_else(|error| panic!("测试 Tools 应构建成功: {error}"));
308        let peer = "10.0.0.2:443"
309            .parse::<SocketAddr>()
310            .unwrap_or_else(|error| panic!("测试对端地址应有效: {error}"));
311        let mut context =
312            ActionContext::new(Request::new(serde_json::Value::Null), Arc::new(tools))
313                .with_request_meta(RequestMeta::new().with_peer_addr(peer));
314        context
315            .request_meta
316            .extensions
317            .insert(CLIENT_IP_META_KEY.to_string(), "198.51.100.7".to_string());
318
319        assert_eq!(client_ip_identity(&context), "198.51.100.7");
320        context.request_meta.extensions.clear();
321        assert_eq!(client_ip_identity(&context), "10.0.0.2");
322        context.request_meta.peer_addr = None;
323        assert_eq!(client_ip_identity(&context), "unknown");
324    }
325
326    #[test]
327    fn step_up_failure_keys_are_separate_from_login_attempt_keys() {
328        let limiter = AuthRateLimiter::new(test_config());
329        let tools = ToolsBuilder::new()
330            .build()
331            .unwrap_or_else(|error| panic!("测试 Tools 应构建成功: {error}"));
332        let context = ActionContext::new(Request::new(serde_json::Value::Null), Arc::new(tools));
333        let keys = limiter.failure_keys(&context, AuthOperation::StepUpComplete, "alice");
334
335        assert_eq!(
336            keys,
337            [
338                "yang-system:auth-failure:step-up-complete:ip:unknown".to_string(),
339                "yang-system:auth-failure:step-up-complete:username:alice".to_string(),
340            ]
341        );
342        assert!(keys.iter().all(|key| !key.contains("auth-rate:login")));
343    }
344}