Skip to main content

auth_framework/distributed/
rate_limiting.rs

1//! Distributed Rate Limiting System
2//!
3//! This module provides comprehensive rate limiting capabilities with support for:
4//! - In-memory rate limiting for single-node deployments
5//! - Redis-based distributed rate limiting for multi-node deployments
6//! - Sliding window algorithms for accurate rate limiting
7//! - Adaptive rate limiting based on system load
8//! - Multiple rate limiting strategies (token bucket, sliding window, etc.)
9
10use 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/// Rate limiting configuration
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct RateLimitConfig {
20    /// Maximum requests per window
21    pub max_requests: u32,
22    /// Time window for rate limiting
23    pub window_duration: Duration,
24    /// Strategy to use for rate limiting
25    pub strategy: RateLimitStrategy,
26    /// Whether to use distributed rate limiting
27    pub distributed: bool,
28    /// Redis connection string for distributed rate limiting
29    pub redis_url: Option<String>,
30    /// Burst allowance (allows temporary spikes)
31    pub burst_allowance: Option<u32>,
32    /// Adaptive rate limiting based on system load
33    pub adaptive: bool,
34    /// Penalty duration for rate limit violations
35    pub penalty_duration: Option<Duration>,
36}
37
38/// Rate limiting strategies
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
40pub enum RateLimitStrategy {
41    /// Token bucket algorithm (allows bursts)
42    TokenBucket,
43    /// Fixed window (resets at fixed intervals)
44    FixedWindow,
45    /// Sliding window (smooth rate limiting)
46    SlidingWindow,
47    /// Adaptive (adjusts based on system load)
48    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)), // 5 minutes
62        }
63    }
64}
65
66impl RateLimitConfig {
67    /// Create strict rate limiting for authentication attempts
68    pub fn strict_auth() -> Self {
69        Self {
70            max_requests: 5,
71            window_duration: Duration::from_secs(300), // 5 minutes
72            strategy: RateLimitStrategy::FixedWindow,
73            distributed: true,
74            redis_url: None,       // Must be set externally
75            burst_allowance: None, // No burst for auth
76            adaptive: false,
77            penalty_duration: Some(Duration::from_secs(3600)), // 1 hour penalty
78        }
79    }
80
81    /// Create lenient rate limiting for general API usage
82    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    /// Create balanced rate limiting for production
96    pub fn balanced() -> Self {
97        Self::default()
98    }
99}
100
101/// Rate limit check result
102#[derive(Debug, Clone, PartialEq)]
103pub enum RateLimitResult {
104    /// Request is allowed
105    Allowed { remaining: u32, reset_at: Instant },
106    /// Request is denied due to rate limit
107    Denied {
108        retry_after: Duration,
109        total_hits: u32,
110    },
111    /// Request is temporarily blocked due to previous violations
112    Blocked { unblock_at: Instant, reason: String },
113}
114
115/// Source of the current time; injectable so window and penalty expiry can be tested without sleeping.
116type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
117
118/// Comprehensive rate limiter supporting multiple strategies
119pub 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    /// Penalty tracking for repeat violators
126    penalties: Arc<RwLock<HashMap<String, Instant>>>,
127}
128
129impl DistributedRateLimiter {
130    /// Create a new distributed rate limiter
131    pub async fn new(config: RateLimitConfig) -> Result<Self> {
132        Self::with_clock(config, Instant::now).await
133    }
134
135    /// Create a rate limiter whose in-memory windows and penalties read `now` instead of the system
136    /// clock. A testing seam: advancing a controlled clock asserts expiry without racing real sleeps
137    /// against scheduler delay. The Redis path keeps the server's own clock.
138    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            // When Redis is not available, use enhanced in-memory limiting with warnings
162            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    /// Check if a request should be rate limited
181    pub async fn check_rate_limit(&self, key: &str) -> Result<RateLimitResult> {
182        // First check for active penalties
183        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                // Penalty expired, remove it
191                self.remove_penalty(key);
192            }
193        }
194
195        // Perform rate limit check based on configuration
196        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                // Fallback to in-memory if Redis is not available
202                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        // Apply penalty for violations if configured
213        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    /// Check multiple keys (e.g., IP + user) with different limits
223    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 any check fails, return the failure
232            if !matches!(result, RateLimitResult::Allowed { .. }) {
233                return Ok(result);
234            }
235        }
236
237        // All checks passed
238        Ok(RateLimitResult::Allowed {
239            remaining: u32::MAX, // Aggregate remaining not meaningful
240            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        // Create a temporary in-memory limiter for fallback
261        let limiter = InMemoryRateLimiter::with_clock(&self.config, self.now.clone())?;
262        limiter.check_rate_limit(key).await
263    }
264}
265
266/// In-memory rate limiter with basic token bucket implementation
267pub 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        // Refill tokens based on time elapsed
291        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, // Exceeded by 1
337            })
338        }
339    }
340}
341
342/// Redis-based distributed rate limiter
343#[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        // Redis Lua script for atomic sliding window
391        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        // Increment counter and set expiry
449        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            // First request in window, set expiry
456            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        // Redis Lua script for token bucket algorithm
492        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) // Cost per request
526            .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        // For now, use sliding window with adaptive threshold
550        // In production, this could adjust based on system metrics
551        self.sliding_window_check(conn, key).await
552    }
553}
554
555/// Rate limiting middleware helper
556pub 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    /// Add a rate limiter for a specific endpoint or operation
574    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    /// Check rate limit for a specific operation
581    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    /// Check multiple rate limits (e.g., per-IP and per-user)
590    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
605/// Rate limiting utilities for common patterns
606pub struct RateLimitUtils;
607
608impl RateLimitUtils {
609    /// Generate rate limit key for IP address
610    pub fn ip_key(ip: &str) -> String {
611        format!("ip:{}", ip)
612    }
613
614    /// Generate rate limit key for user
615    pub fn user_key(user_id: &str) -> String {
616        format!("user:{}", user_id)
617    }
618
619    /// Generate rate limit key for API endpoint
620    pub fn endpoint_key(endpoint: &str, ip: &str) -> String {
621        format!("endpoint:{}:{}", endpoint, ip)
622    }
623
624    /// Generate rate limit key for authentication attempts
625    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    /// Calculate backoff duration for repeated violations
633    pub fn exponential_backoff(attempt: u32, base_duration: Duration) -> Duration {
634        let multiplier = 2_u64.pow(attempt.min(10)); // Cap at 2^10
635        Duration::from_millis(base_duration.as_millis() as u64 * multiplier)
636    }
637
638    /// Apply jitter to retry duration to prevent thundering herd
639    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), // Shorter window for testing
657            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        // First 3 requests should be allowed
668        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        // 4th request should be denied
678        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        // Wait for window to reset
685        sleep(Duration::from_millis(150)).await;
686
687        // Should be allowed again
688        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        // First request allowed
715        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
716        assert!(matches!(result, RateLimitResult::Allowed { .. }));
717
718        // Second request denied (triggers penalty)
719        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
720        assert!(matches!(result, RateLimitResult::Denied { .. }));
721
722        // Wait a bit for penalty to be applied
723        sleep(Duration::from_millis(10)).await;
724
725        // Third request should be blocked due to penalty (not just denied)
726        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
727        assert!(matches!(result, RateLimitResult::Blocked { .. }));
728
729        // Wait for penalty to expire
730        sleep(Duration::from_millis(250)).await;
731
732        // Should be allowed again
733        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        // Should cap at 2^10
777        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}