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