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