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}
86
87impl AuthOperation {
88 fn key(self) -> &'static str {
89 match self {
90 Self::ChangePassword => "change-password",
91 Self::PasswordResetCreate => "password-reset-create",
92 Self::PasswordResetConsume => "password-reset-consume",
93 Self::Login => "login",
94 Self::Register => "register",
95 Self::StepUpComplete => "step-up-complete",
96 }
97 }
98
99 fn identity_key(self) -> &'static str {
100 match self {
101 Self::ChangePassword => "user",
102 Self::PasswordResetCreate => "actor-target",
103 Self::PasswordResetConsume => "fingerprint",
104 Self::Login | Self::Register | Self::StepUpComplete => "username",
105 }
106 }
107}
108
109#[derive(Clone)]
111pub struct AuthRateLimitConfig {
112 pub window_seconds: u64,
114 pub ip_attempts: u64,
116 pub username_attempts: u64,
118 pub key_prefix: String,
120 pub metric_name: &'static str,
122}
123
124#[derive(Clone)]
126pub struct AuthRateLimiter {
127 config: AuthRateLimitConfig,
128}
129
130impl AuthRateLimiter {
131 pub fn new(config: AuthRateLimitConfig) -> Self {
133 Self { config }
134 }
135
136 pub async fn check(
138 &self,
139 ctx: &ActionContext,
140 operation: AuthOperation,
141 identity: &str,
142 ) -> Result<(), BaseError> {
143 let source = client_ip_identity(ctx);
144 let prefix = format!("{}:auth-rate:{}", self.config.key_prefix, operation.key());
145 let keys = [
146 format!("{prefix}:ip:{source}"),
147 format!("{prefix}:{}:{identity}", operation.identity_key()),
148 ];
149 let args = [
150 self.config.window_seconds.to_string(),
151 self.config.ip_attempts.to_string(),
152 self.config.username_attempts.to_string(),
153 ];
154 let cache = ctx.tools().cache()?;
155 let script = cache.script(RATE_LIMIT_SCRIPT);
156 let decision: Result<(i64, i64), _> = cache.eval_script(&script, &keys, &args).await;
157 match decision {
158 Ok((exceeded, retry_after)) => {
159 let result = rate_limit_result(exceeded, retry_after);
160 #[cfg(feature = "metrics")]
161 metrics::counter!(
162 self.config.metric_name,
163 "operation" => operation.key(),
164 "result" => if result.is_ok() { "allowed" } else { "limited" }
165 )
166 .increment(1);
167 result
168 }
169 Err(error) => {
170 #[cfg(feature = "metrics")]
171 metrics::counter!(
172 self.config.metric_name,
173 "operation" => operation.key(),
174 "result" => "unavailable"
175 )
176 .increment(1);
177 Err(error.into())
178 }
179 }
180 }
181
182 pub async fn record_failure(
184 &self,
185 ctx: &ActionContext,
186 operation: AuthOperation,
187 identity: &str,
188 ) -> Result<(), BaseError> {
189 let keys = self.failure_keys(ctx, operation, identity);
190 let args = [
191 self.config.window_seconds.to_string(),
192 self.config.ip_attempts.to_string(),
193 self.config.username_attempts.to_string(),
194 ];
195 let cache = ctx.tools().cache()?;
196 let script = cache.script(FAILURE_COUNT_SCRIPT);
197 let decision: (i64, i64) = cache.eval_script(&script, &keys, &args).await?;
198 rate_limit_result(decision.0, decision.1)
199 }
200
201 pub async fn clear_failures(
203 &self,
204 ctx: &ActionContext,
205 operation: AuthOperation,
206 identity: &str,
207 ) -> Result<(), BaseError> {
208 let keys = self.failure_keys(ctx, operation, identity);
209 ctx.tools().cache()?.del(&keys).await?;
210 Ok(())
211 }
212
213 fn failure_keys(
214 &self,
215 ctx: &ActionContext,
216 operation: AuthOperation,
217 identity: &str,
218 ) -> [String; 2] {
219 let source = client_ip_identity(ctx);
220 let prefix = format!(
221 "{}:auth-failure:{}",
222 self.config.key_prefix,
223 operation.key()
224 );
225 [
226 format!("{prefix}:ip:{source}"),
227 format!("{prefix}:{}:{identity}", operation.identity_key()),
228 ]
229 }
230}
231
232fn rate_limit_result(exceeded: i64, retry_after: i64) -> Result<(), BaseError> {
233 if exceeded == 0 {
234 return Ok(());
235 }
236 Err(BaseError::RateLimitExceeded {
237 retry_after_seconds: u64::try_from(retry_after).unwrap_or(1).max(1),
238 })
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use crate::action::{Request, RequestMeta};
245 use crate::tools::ToolsBuilder;
246 use crate::transport::client_ip::CLIENT_IP_META_KEY;
247 use std::net::SocketAddr;
248 use std::sync::Arc;
249
250 fn test_config() -> AuthRateLimitConfig {
251 AuthRateLimitConfig {
252 window_seconds: 60,
253 ip_attempts: 10,
254 username_attempts: 5,
255 key_prefix: "yang-system".to_string(),
256 metric_name: "yang_system_auth_rate_limit_total",
257 }
258 }
259
260 #[test]
261 fn maps_redis_decision_to_standard_rate_limit_error() {
262 assert!(rate_limit_result(0, 0).is_ok());
263 assert!(matches!(
264 rate_limit_result(1, 17),
265 Err(BaseError::RateLimitExceeded {
266 retry_after_seconds: 17
267 })
268 ));
269 assert!(matches!(
270 rate_limit_result(1, -1),
271 Err(BaseError::RateLimitExceeded {
272 retry_after_seconds: 1
273 })
274 ));
275 }
276
277 #[test]
278 fn operation_keys_are_isolated() {
279 assert_ne!(AuthOperation::Login.key(), AuthOperation::Register.key());
280 assert_ne!(
281 AuthOperation::ChangePassword.key(),
282 AuthOperation::Login.key()
283 );
284 assert_eq!(AuthOperation::ChangePassword.identity_key(), "user");
285 assert_eq!(AuthOperation::Login.identity_key(), "username");
286 assert_ne!(
287 AuthOperation::StepUpComplete.key(),
288 AuthOperation::Login.key()
289 );
290 assert_eq!(AuthOperation::StepUpComplete.identity_key(), "username");
291 }
292
293 #[test]
294 fn rate_limit_identity_prefers_trusted_transport_extension() {
295 let tools = ToolsBuilder::new()
296 .build()
297 .unwrap_or_else(|error| panic!("测试 Tools 应构建成功: {error}"));
298 let peer = "10.0.0.2:443"
299 .parse::<SocketAddr>()
300 .unwrap_or_else(|error| panic!("测试对端地址应有效: {error}"));
301 let mut context =
302 ActionContext::new(Request::new(serde_json::Value::Null), Arc::new(tools))
303 .with_request_meta(RequestMeta::new().with_peer_addr(peer));
304 context
305 .request_meta
306 .extensions
307 .insert(CLIENT_IP_META_KEY.to_string(), "198.51.100.7".to_string());
308
309 assert_eq!(client_ip_identity(&context), "198.51.100.7");
310 context.request_meta.extensions.clear();
311 assert_eq!(client_ip_identity(&context), "10.0.0.2");
312 context.request_meta.peer_addr = None;
313 assert_eq!(client_ip_identity(&context), "unknown");
314 }
315
316 #[test]
317 fn step_up_failure_keys_are_separate_from_login_attempt_keys() {
318 let limiter = AuthRateLimiter::new(test_config());
319 let tools = ToolsBuilder::new()
320 .build()
321 .unwrap_or_else(|error| panic!("测试 Tools 应构建成功: {error}"));
322 let context = ActionContext::new(Request::new(serde_json::Value::Null), Arc::new(tools));
323 let keys = limiter.failure_keys(&context, AuthOperation::StepUpComplete, "alice");
324
325 assert_eq!(
326 keys,
327 [
328 "yang-system:auth-failure:step-up-complete:ip:unknown".to_string(),
329 "yang-system:auth-failure:step-up-complete:username:alice".to_string(),
330 ]
331 );
332 assert!(keys.iter().all(|key| !key.contains("auth-rate:login")));
333 }
334}