1use 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#[derive(Clone, Copy)]
72pub enum AuthOperation {
73 ChangePassword,
75 PasswordResetCreate,
77 PasswordResetConsume,
79 Login,
81 Register,
83 StepUpComplete,
85 TotpVerify,
87 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#[derive(Clone)]
121pub struct AuthRateLimitConfig {
122 pub window_seconds: u64,
124 pub ip_attempts: u64,
126 pub username_attempts: u64,
128 pub key_prefix: String,
130 pub metric_name: &'static str,
132}
133
134#[derive(Clone)]
136pub struct AuthRateLimiter {
137 config: AuthRateLimitConfig,
138}
139
140impl AuthRateLimiter {
141 pub fn new(config: AuthRateLimitConfig) -> Self {
143 Self { config }
144 }
145
146 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 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 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}