1use crate::errors::{AuthError, Result};
11use parking_lot::RwLock;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17#[derive(Clone, Serialize, Deserialize)]
19pub struct RateLimitConfig {
20 pub max_requests: u32,
22 pub window_duration: Duration,
24 pub strategy: RateLimitStrategy,
26 pub distributed: bool,
28 pub redis_url: Option<String>,
30 pub burst_allowance: Option<u32>,
32 pub adaptive: bool,
34 pub penalty_duration: Option<Duration>,
36}
37
38impl std::fmt::Debug for RateLimitConfig {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 let mut d = f.debug_struct("RateLimitConfig");
41 d.field("max_requests", &self.max_requests);
42 d.field("window_duration", &self.window_duration);
43 d.field("strategy", &self.strategy);
44 d.field("distributed", &self.distributed);
45 d.field(
46 "redis_url",
47 &crate::utils::redact::redacted(&self.redis_url),
48 );
49 d.field("burst_allowance", &self.burst_allowance);
50 d.field("adaptive", &self.adaptive);
51 d.field("penalty_duration", &self.penalty_duration);
52 d.finish()
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
58pub enum RateLimitStrategy {
59 TokenBucket,
61 FixedWindow,
63 SlidingWindow,
65 Adaptive,
67}
68
69impl Default for RateLimitConfig {
70 fn default() -> Self {
71 Self {
72 max_requests: 100,
73 window_duration: Duration::from_secs(60),
74 strategy: RateLimitStrategy::SlidingWindow,
75 distributed: false,
76 redis_url: None,
77 burst_allowance: Some(20),
78 adaptive: false,
79 penalty_duration: Some(Duration::from_secs(300)), }
81 }
82}
83
84impl RateLimitConfig {
85 pub fn strict_auth() -> Self {
87 Self {
88 max_requests: 5,
89 window_duration: Duration::from_secs(300), strategy: RateLimitStrategy::FixedWindow,
91 distributed: true,
92 redis_url: None, burst_allowance: None, adaptive: false,
95 penalty_duration: Some(Duration::from_secs(3600)), }
97 }
98
99 pub fn lenient_api() -> Self {
101 Self {
102 max_requests: 1000,
103 window_duration: Duration::from_secs(60),
104 strategy: RateLimitStrategy::TokenBucket,
105 distributed: false,
106 redis_url: None,
107 burst_allowance: Some(200),
108 adaptive: true,
109 penalty_duration: Some(Duration::from_secs(60)),
110 }
111 }
112
113 pub fn balanced() -> Self {
115 Self::default()
116 }
117}
118
119#[derive(Debug, Clone, PartialEq)]
121pub enum RateLimitResult {
122 Allowed { remaining: u32, reset_at: Instant },
124 Denied {
126 retry_after: Duration,
127 total_hits: u32,
128 },
129 Blocked { unblock_at: Instant, reason: String },
131}
132
133pub struct DistributedRateLimiter {
135 config: RateLimitConfig,
136 in_memory_limiter: Option<Arc<InMemoryRateLimiter>>,
137 #[cfg(feature = "redis-storage")]
138 redis_limiter: Option<Arc<RedisRateLimiter>>,
139 penalties: Arc<RwLock<HashMap<String, Instant>>>,
141}
142
143impl DistributedRateLimiter {
144 pub async fn new(config: RateLimitConfig) -> Result<Self> {
146 let in_memory_limiter = if config.distributed {
147 None
148 } else {
149 Some(Arc::new(InMemoryRateLimiter::new(&config)?))
150 };
151
152 #[cfg(feature = "redis-storage")]
153 let redis_limiter = if config.distributed && config.redis_url.is_some() {
154 Some(Arc::new(RedisRateLimiter::new(&config).await?))
155 } else {
156 None
157 };
158
159 #[cfg(not(feature = "redis-storage"))]
160 {
161 tracing::warn!(
163 "Redis storage not available for distributed rate limiting - using in-memory only"
164 );
165 tracing::warn!(
166 "For production deployments, enable 'redis-storage' feature for true distributed limiting"
167 );
168 }
169
170 Ok(Self {
171 config,
172 in_memory_limiter,
173 #[cfg(feature = "redis-storage")]
174 redis_limiter,
175 penalties: Arc::new(RwLock::new(HashMap::new())),
176 })
177 }
178
179 pub async fn check_rate_limit(&self, key: &str) -> Result<RateLimitResult> {
181 if let Some(unblock_at) = self.get_penalty_expiry(key) {
183 if Instant::now() < unblock_at {
184 return Ok(RateLimitResult::Blocked {
185 unblock_at,
186 reason: "Previous rate limit violations".to_string(),
187 });
188 } else {
189 self.remove_penalty(key);
191 }
192 }
193
194 let result = if self.config.distributed {
196 #[cfg(feature = "redis-storage")]
197 if let Some(ref redis_limiter) = self.redis_limiter {
198 redis_limiter.check_rate_limit(key).await?
199 } else {
200 self.fallback_check(key).await?
202 }
203 #[cfg(not(feature = "redis-storage"))]
204 self.fallback_check(key).await?
205 } else if let Some(ref in_memory_limiter) = self.in_memory_limiter {
206 in_memory_limiter.check_rate_limit(key).await?
207 } else {
208 return Err(AuthError::internal("No rate limiter configured"));
209 };
210
211 if matches!(result, RateLimitResult::Denied { .. })
213 && let Some(penalty_duration) = self.config.penalty_duration
214 {
215 self.apply_penalty(key, penalty_duration);
216 }
217
218 Ok(result)
219 }
220
221 pub async fn check_multiple_limits(
223 &self,
224 checks: &[(String, RateLimitConfig)],
225 ) -> Result<RateLimitResult> {
226 for (key, config) in checks {
227 let limiter = Self::new(config.clone()).await?;
228 let result = limiter.check_rate_limit(key).await?;
229
230 if !matches!(result, RateLimitResult::Allowed { .. }) {
232 return Ok(result);
233 }
234 }
235
236 Ok(RateLimitResult::Allowed {
238 remaining: u32::MAX, reset_at: Instant::now() + self.config.window_duration,
240 })
241 }
242
243 fn get_penalty_expiry(&self, key: &str) -> Option<Instant> {
244 let penalties = self.penalties.read();
245 penalties.get(key).copied()
246 }
247
248 fn apply_penalty(&self, key: &str, duration: Duration) {
249 let mut penalties = self.penalties.write();
250 penalties.insert(key.to_string(), Instant::now() + duration);
251 }
252
253 fn remove_penalty(&self, key: &str) {
254 let mut penalties = self.penalties.write();
255 penalties.remove(key);
256 }
257
258 async fn fallback_check(&self, key: &str) -> Result<RateLimitResult> {
259 let limiter = InMemoryRateLimiter::new(&self.config)?;
261 limiter.check_rate_limit(key).await
262 }
263}
264
265pub struct InMemoryRateLimiter {
267 config: RateLimitConfig,
268 buckets: std::sync::Arc<dashmap::DashMap<String, TokenBucket>>,
269}
270
271#[derive(Debug, Clone)]
272struct TokenBucket {
273 tokens: u32,
274 last_refill: Instant,
275}
276
277impl TokenBucket {
278 fn new(capacity: u32) -> Self {
279 Self {
280 tokens: capacity,
281 last_refill: Instant::now(),
282 }
283 }
284
285 fn try_consume(&mut self, config: &RateLimitConfig) -> bool {
286 let now = Instant::now();
287 let elapsed = now.duration_since(self.last_refill);
288
289 if elapsed >= config.window_duration {
291 self.tokens = config.max_requests;
292 self.last_refill = now;
293 }
294
295 if self.tokens > 0 {
296 self.tokens -= 1;
297 true
298 } else {
299 false
300 }
301 }
302}
303
304impl InMemoryRateLimiter {
305 pub fn new(config: &RateLimitConfig) -> Result<Self> {
306 Ok(Self {
307 config: config.clone(),
308 buckets: std::sync::Arc::new(dashmap::DashMap::new()),
309 })
310 }
311
312 pub async fn check_rate_limit(&self, key: &str) -> Result<RateLimitResult> {
313 let mut bucket = self
314 .buckets
315 .entry(key.to_string())
316 .or_insert_with(|| TokenBucket::new(self.config.max_requests));
317
318 if bucket.try_consume(&self.config) {
319 Ok(RateLimitResult::Allowed {
320 remaining: bucket.tokens,
321 reset_at: bucket.last_refill + self.config.window_duration,
322 })
323 } else {
324 let retry_after =
325 (bucket.last_refill + self.config.window_duration).duration_since(Instant::now());
326
327 Ok(RateLimitResult::Denied {
328 retry_after,
329 total_hits: self.config.max_requests + 1, })
331 }
332 }
333}
334
335#[cfg(feature = "redis-storage")]
337pub struct RedisRateLimiter {
338 client: redis::Client,
339 config: RateLimitConfig,
340}
341
342#[cfg(feature = "redis-storage")]
343impl RedisRateLimiter {
344 pub async fn new(config: &RateLimitConfig) -> Result<Self> {
345 let redis_url = config
346 .redis_url
347 .as_ref()
348 .ok_or_else(|| AuthError::config("Redis URL required for distributed rate limiting"))?;
349
350 let client = redis::Client::open(redis_url.as_str())
351 .map_err(|e| AuthError::internal(format!("Failed to connect to Redis: {}", e)))?;
352
353 Ok(Self {
354 client,
355 config: config.clone(),
356 })
357 }
358
359 pub async fn check_rate_limit(&self, key: &str) -> Result<RateLimitResult> {
360 let mut conn = self
361 .client
362 .get_multiplexed_tokio_connection()
363 .await
364 .map_err(|e| AuthError::internal(format!("Redis connection failed: {}", e)))?;
365
366 match self.config.strategy {
367 RateLimitStrategy::SlidingWindow => self.sliding_window_check(&mut conn, key).await,
368 RateLimitStrategy::FixedWindow => self.fixed_window_check(&mut conn, key).await,
369 RateLimitStrategy::TokenBucket => self.token_bucket_check(&mut conn, key).await,
370 RateLimitStrategy::Adaptive => self.adaptive_check(&mut conn, key).await,
371 }
372 }
373
374 async fn sliding_window_check(
375 &self,
376 conn: &mut redis::aio::MultiplexedConnection,
377 key: &str,
378 ) -> Result<RateLimitResult> {
379 let now = chrono::Utc::now().timestamp();
380 let window_start = now - self.config.window_duration.as_secs() as i64;
381 let redis_key = format!("rate_limit:sliding:{}", key);
382
383 let script = r#"
385 local key = KEYS[1]
386 local window_start = ARGV[1]
387 local now = ARGV[2]
388 local max_requests = tonumber(ARGV[3])
389 local expiry = tonumber(ARGV[4])
390
391 -- Remove expired entries
392 redis.call('ZREMRANGEBYSCORE', key, '-inf', window_start)
393
394 -- Count current requests in window
395 local current_requests = redis.call('ZCARD', key)
396
397 if current_requests < max_requests then
398 -- Add current request
399 redis.call('ZADD', key, now, now)
400 redis.call('EXPIRE', key, expiry)
401 return {1, max_requests - current_requests - 1}
402 else
403 return {0, current_requests}
404 end
405 "#;
406
407 let result: Vec<i32> = redis::Script::new(script)
408 .key(&redis_key)
409 .arg(window_start)
410 .arg(now)
411 .arg(self.config.max_requests)
412 .arg(self.config.window_duration.as_secs())
413 .invoke_async(conn)
414 .await
415 .map_err(|e| AuthError::internal(format!("Redis script error: {}", e)))?;
416
417 if result[0] == 1 {
418 Ok(RateLimitResult::Allowed {
419 remaining: result[1] as u32,
420 reset_at: Instant::now() + self.config.window_duration,
421 })
422 } else {
423 Ok(RateLimitResult::Denied {
424 retry_after: self.config.window_duration,
425 total_hits: result[1] as u32,
426 })
427 }
428 }
429
430 async fn fixed_window_check(
431 &self,
432 conn: &mut redis::aio::MultiplexedConnection,
433 key: &str,
434 ) -> Result<RateLimitResult> {
435 use redis::AsyncCommands;
436
437 let window_size = self.config.window_duration.as_secs();
438 let current_window = chrono::Utc::now().timestamp() / window_size as i64;
439 let redis_key = format!("rate_limit:fixed:{}:{}", key, current_window);
440
441 let count: u32 = conn
443 .incr(&redis_key, 1)
444 .await
445 .map_err(|e| AuthError::internal(format!("Redis incr error: {}", e)))?;
446
447 if count == 1 {
448 let _: () = conn
450 .expire(&redis_key, window_size as i64)
451 .await
452 .map_err(|e| AuthError::internal(format!("Redis expire error: {}", e)))?;
453 }
454
455 if count <= self.config.max_requests {
456 Ok(RateLimitResult::Allowed {
457 remaining: self.config.max_requests - count,
458 reset_at: Instant::now()
459 + Duration::from_secs(
460 window_size - (chrono::Utc::now().timestamp() % window_size as i64) as u64,
461 ),
462 })
463 } else {
464 Ok(RateLimitResult::Denied {
465 retry_after: Duration::from_secs(
466 window_size - (chrono::Utc::now().timestamp() % window_size as i64) as u64,
467 ),
468 total_hits: count,
469 })
470 }
471 }
472
473 async fn token_bucket_check(
474 &self,
475 conn: &mut redis::aio::MultiplexedConnection,
476 key: &str,
477 ) -> Result<RateLimitResult> {
478 let redis_key = format!("rate_limit:bucket:{}", key);
479 let now = chrono::Utc::now().timestamp_millis();
480 let refill_rate =
481 self.config.max_requests as f64 / self.config.window_duration.as_secs_f64();
482 let bucket_size = self.config.max_requests + self.config.burst_allowance.unwrap_or(0);
483
484 let script = r#"
486 local key = KEYS[1]
487 local now = tonumber(ARGV[1])
488 local refill_rate = tonumber(ARGV[2])
489 local bucket_size = tonumber(ARGV[3])
490 local cost = tonumber(ARGV[4])
491
492 local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
493 local tokens = tonumber(bucket[1]) or bucket_size
494 local last_refill = tonumber(bucket[2]) or now
495
496 -- Calculate tokens to add
497 local time_passed = (now - last_refill) / 1000.0
498 local tokens_to_add = time_passed * refill_rate
499 tokens = math.min(bucket_size, tokens + tokens_to_add)
500
501 if tokens >= cost then
502 tokens = tokens - cost
503 redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
504 redis.call('EXPIRE', key, 3600) -- 1 hour expiry
505 return {1, math.floor(tokens)}
506 else
507 redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
508 redis.call('EXPIRE', key, 3600)
509 return {0, math.floor(tokens)}
510 end
511 "#;
512
513 let result: Vec<i32> = redis::Script::new(script)
514 .key(&redis_key)
515 .arg(now)
516 .arg(refill_rate)
517 .arg(bucket_size)
518 .arg(1) .invoke_async(conn)
520 .await
521 .map_err(|e| AuthError::internal(format!("Redis script error: {}", e)))?;
522
523 if result[0] == 1 {
524 Ok(RateLimitResult::Allowed {
525 remaining: result[1] as u32,
526 reset_at: Instant::now() + self.config.window_duration,
527 })
528 } else {
529 let retry_after = Duration::from_secs_f64(1.0 / refill_rate);
530 Ok(RateLimitResult::Denied {
531 retry_after,
532 total_hits: self.config.max_requests + 1,
533 })
534 }
535 }
536
537 async fn adaptive_check(
538 &self,
539 conn: &mut redis::aio::MultiplexedConnection,
540 key: &str,
541 ) -> Result<RateLimitResult> {
542 self.sliding_window_check(conn, key).await
545 }
546}
547
548pub struct RateLimitMiddleware {
550 limiters: HashMap<String, Arc<DistributedRateLimiter>>,
551}
552
553impl Default for RateLimitMiddleware {
554 fn default() -> Self {
555 Self::new()
556 }
557}
558
559impl RateLimitMiddleware {
560 pub fn new() -> Self {
561 Self {
562 limiters: HashMap::new(),
563 }
564 }
565
566 pub async fn add_limiter(&mut self, name: &str, config: RateLimitConfig) -> Result<()> {
568 let limiter = Arc::new(DistributedRateLimiter::new(config).await?);
569 self.limiters.insert(name.to_string(), limiter);
570 Ok(())
571 }
572
573 pub async fn check_limit(&self, limiter_name: &str, key: &str) -> Result<RateLimitResult> {
575 let limiter = self.limiters.get(limiter_name).ok_or_else(|| {
576 AuthError::config(format!("No rate limiter found for '{}'", limiter_name))
577 })?;
578
579 limiter.check_rate_limit(key).await
580 }
581
582 pub async fn check_multiple(&self, checks: &[(String, String)]) -> Result<RateLimitResult> {
584 for (limiter_name, key) in checks {
585 let result = self.check_limit(limiter_name, key).await?;
586 if !matches!(result, RateLimitResult::Allowed { .. }) {
587 return Ok(result);
588 }
589 }
590
591 Ok(RateLimitResult::Allowed {
592 remaining: u32::MAX,
593 reset_at: Instant::now() + Duration::from_secs(60),
594 })
595 }
596}
597
598pub struct RateLimitUtils;
600
601impl RateLimitUtils {
602 pub fn ip_key(ip: &str) -> String {
604 format!("ip:{}", ip)
605 }
606
607 pub fn user_key(user_id: &str) -> String {
609 format!("user:{}", user_id)
610 }
611
612 pub fn endpoint_key(endpoint: &str, ip: &str) -> String {
614 format!("endpoint:{}:{}", endpoint, ip)
615 }
616
617 pub fn auth_key(ip: &str, username: Option<&str>) -> String {
619 match username {
620 Some(user) => format!("auth:{}:{}", ip, user),
621 None => format!("auth:{}", ip),
622 }
623 }
624
625 pub fn exponential_backoff(attempt: u32, base_duration: Duration) -> Duration {
627 let multiplier = 2_u64.pow(attempt.min(10)); Duration::from_millis(base_duration.as_millis() as u64 * multiplier)
629 }
630
631 pub fn add_jitter(duration: Duration, jitter_factor: f64) -> Duration {
633 use rand::Rng;
634 let jitter = rand::rng().random_range(0.0..jitter_factor);
635 let jitter_ms = (duration.as_millis() as f64 * jitter) as u64;
636 duration + Duration::from_millis(jitter_ms)
637 }
638}
639
640#[cfg(test)]
641mod tests {
642 use super::*;
643 use tokio::time::sleep;
644
645 #[tokio::test]
646 async fn test_in_memory_rate_limiter() {
647 let config = RateLimitConfig {
648 max_requests: 3,
649 window_duration: Duration::from_millis(100), strategy: RateLimitStrategy::TokenBucket,
651 distributed: false,
652 redis_url: None,
653 burst_allowance: Some(1),
654 adaptive: false,
655 penalty_duration: None,
656 };
657
658 let limiter = DistributedRateLimiter::new(config).await.unwrap();
659
660 for i in 0..3 {
662 let result = limiter.check_rate_limit("test_key").await.unwrap();
663 assert!(
664 matches!(result, RateLimitResult::Allowed { .. }),
665 "Request {} should be allowed",
666 i
667 );
668 }
669
670 let result = limiter.check_rate_limit("test_key").await.unwrap();
672 assert!(
673 matches!(result, RateLimitResult::Denied { .. }),
674 "4th request should be denied"
675 );
676
677 sleep(Duration::from_millis(150)).await;
679
680 let result = limiter.check_rate_limit("test_key").await.unwrap();
682 assert!(
683 matches!(result, RateLimitResult::Allowed { .. }),
684 "Request after window reset should be allowed"
685 );
686 assert!(
687 matches!(result, RateLimitResult::Allowed { .. }),
688 "Request after reset should be allowed"
689 );
690 }
691
692 #[tokio::test]
693 async fn test_penalty_system() {
694 let config = RateLimitConfig {
695 max_requests: 1,
696 window_duration: Duration::from_millis(50),
697 strategy: RateLimitStrategy::FixedWindow,
698 distributed: false,
699 redis_url: None,
700 burst_allowance: None,
701 adaptive: false,
702 penalty_duration: Some(Duration::from_millis(200)),
703 };
704
705 let limiter = DistributedRateLimiter::new(config).await.unwrap();
706
707 let result = limiter.check_rate_limit("penalty_test").await.unwrap();
709 assert!(matches!(result, RateLimitResult::Allowed { .. }));
710
711 let result = limiter.check_rate_limit("penalty_test").await.unwrap();
713 assert!(matches!(result, RateLimitResult::Denied { .. }));
714
715 sleep(Duration::from_millis(10)).await;
717
718 let result = limiter.check_rate_limit("penalty_test").await.unwrap();
720 assert!(matches!(result, RateLimitResult::Blocked { .. }));
721
722 sleep(Duration::from_millis(250)).await;
724
725 let result = limiter.check_rate_limit("penalty_test").await.unwrap();
727 assert!(matches!(result, RateLimitResult::Allowed { .. }));
728 }
729
730 #[tokio::test]
731 async fn test_rate_limit_key_generation() {
732 assert_eq!(RateLimitUtils::ip_key("192.168.1.1"), "ip:192.168.1.1");
733 assert_eq!(RateLimitUtils::user_key("user123"), "user:user123");
734 assert_eq!(
735 RateLimitUtils::endpoint_key("/api/login", "192.168.1.1"),
736 "endpoint:/api/login:192.168.1.1"
737 );
738 assert_eq!(
739 RateLimitUtils::auth_key("192.168.1.1", Some("user123")),
740 "auth:192.168.1.1:user123"
741 );
742 assert_eq!(
743 RateLimitUtils::auth_key("192.168.1.1", None),
744 "auth:192.168.1.1"
745 );
746 }
747
748 #[tokio::test]
749 async fn test_exponential_backoff() {
750 let base = Duration::from_millis(100);
751
752 assert_eq!(
753 RateLimitUtils::exponential_backoff(0, base),
754 Duration::from_millis(100)
755 );
756 assert_eq!(
757 RateLimitUtils::exponential_backoff(1, base),
758 Duration::from_millis(200)
759 );
760 assert_eq!(
761 RateLimitUtils::exponential_backoff(2, base),
762 Duration::from_millis(400)
763 );
764 assert_eq!(
765 RateLimitUtils::exponential_backoff(10, base),
766 Duration::from_millis(102400)
767 );
768
769 assert_eq!(
771 RateLimitUtils::exponential_backoff(15, base),
772 Duration::from_millis(102400)
773 );
774 }
775
776 #[tokio::test]
777 async fn test_rate_limit_configurations() {
778 let strict = RateLimitConfig::strict_auth();
779 assert_eq!(strict.max_requests, 5);
780 assert_eq!(strict.window_duration, Duration::from_secs(300));
781 assert!(strict.distributed);
782
783 let lenient = RateLimitConfig::lenient_api();
784 assert_eq!(lenient.max_requests, 1000);
785 assert!(lenient.adaptive);
786
787 let balanced = RateLimitConfig::balanced();
788 assert_eq!(balanced.max_requests, 100);
789 assert_eq!(balanced.strategy, RateLimitStrategy::SlidingWindow);
790 }
791}