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(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
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/// Rate limiting strategies
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
58pub enum RateLimitStrategy {
59    /// Token bucket algorithm (allows bursts)
60    TokenBucket,
61    /// Fixed window (resets at fixed intervals)
62    FixedWindow,
63    /// Sliding window (smooth rate limiting)
64    SlidingWindow,
65    /// Adaptive (adjusts based on system load)
66    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)), // 5 minutes
80        }
81    }
82}
83
84impl RateLimitConfig {
85    /// Create strict rate limiting for authentication attempts
86    pub fn strict_auth() -> Self {
87        Self {
88            max_requests: 5,
89            window_duration: Duration::from_secs(300), // 5 minutes
90            strategy: RateLimitStrategy::FixedWindow,
91            distributed: true,
92            redis_url: None,       // Must be set externally
93            burst_allowance: None, // No burst for auth
94            adaptive: false,
95            penalty_duration: Some(Duration::from_secs(3600)), // 1 hour penalty
96        }
97    }
98
99    /// Create lenient rate limiting for general API usage
100    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    /// Create balanced rate limiting for production
114    pub fn balanced() -> Self {
115        Self::default()
116    }
117}
118
119/// Rate limit check result
120#[derive(Debug, Clone, PartialEq)]
121pub enum RateLimitResult {
122    /// Request is allowed
123    Allowed { remaining: u32, reset_at: Instant },
124    /// Request is denied due to rate limit
125    Denied {
126        retry_after: Duration,
127        total_hits: u32,
128    },
129    /// Request is temporarily blocked due to previous violations
130    Blocked { unblock_at: Instant, reason: String },
131}
132
133/// Source of the current time; injectable so window and penalty expiry can be tested without sleeping.
134type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
135
136/// Comprehensive rate limiter supporting multiple strategies
137pub 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    /// Penalty tracking for repeat violators
144    penalties: Arc<RwLock<HashMap<String, Instant>>>,
145}
146
147impl DistributedRateLimiter {
148    /// Create a new distributed rate limiter
149    pub async fn new(config: RateLimitConfig) -> Result<Self> {
150        Self::with_clock(config, Instant::now).await
151    }
152
153    /// Create a rate limiter whose in-memory windows and penalties read `now` instead of the system
154    /// clock. A testing seam: advancing a controlled clock asserts expiry without racing real sleeps
155    /// against scheduler delay. The Redis path keeps the server's own clock.
156    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            // When Redis is not available, use enhanced in-memory limiting with warnings
180            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    /// Check if a request should be rate limited
199    pub async fn check_rate_limit(&self, key: &str) -> Result<RateLimitResult> {
200        // First check for active penalties
201        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                // Penalty expired, remove it
209                self.remove_penalty(key);
210            }
211        }
212
213        // Perform rate limit check based on configuration
214        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                // Fallback to in-memory if Redis is not available
220                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        // Apply penalty for violations if configured
231        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    /// Check multiple keys (e.g., IP + user) with different limits
241    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 any check fails, return the failure
250            if !matches!(result, RateLimitResult::Allowed { .. }) {
251                return Ok(result);
252            }
253        }
254
255        // All checks passed
256        Ok(RateLimitResult::Allowed {
257            remaining: u32::MAX, // Aggregate remaining not meaningful
258            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        // Create a temporary in-memory limiter for fallback
279        let limiter = InMemoryRateLimiter::with_clock(&self.config, self.now.clone())?;
280        limiter.check_rate_limit(key).await
281    }
282}
283
284/// In-memory rate limiter with basic token bucket implementation
285pub 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        // Refill tokens based on time elapsed
309        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, // Exceeded by 1
355            })
356        }
357    }
358}
359
360/// Redis-based distributed rate limiter
361#[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        // Redis Lua script for atomic sliding window
409        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        // Increment counter and set expiry
467        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            // First request in window, set expiry
474            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        // Redis Lua script for token bucket algorithm
510        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) // Cost per request
544            .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        // For now, use sliding window with adaptive threshold
568        // In production, this could adjust based on system metrics
569        self.sliding_window_check(conn, key).await
570    }
571}
572
573/// Rate limiting middleware helper
574pub 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    /// Add a rate limiter for a specific endpoint or operation
592    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    /// Check rate limit for a specific operation
599    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    /// Check multiple rate limits (e.g., per-IP and per-user)
608    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
623/// Rate limiting utilities for common patterns
624pub struct RateLimitUtils;
625
626impl RateLimitUtils {
627    /// Generate rate limit key for IP address
628    pub fn ip_key(ip: &str) -> String {
629        format!("ip:{}", ip)
630    }
631
632    /// Generate rate limit key for user
633    pub fn user_key(user_id: &str) -> String {
634        format!("user:{}", user_id)
635    }
636
637    /// Generate rate limit key for API endpoint
638    pub fn endpoint_key(endpoint: &str, ip: &str) -> String {
639        format!("endpoint:{}:{}", endpoint, ip)
640    }
641
642    /// Generate rate limit key for authentication attempts
643    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    /// Calculate backoff duration for repeated violations
651    pub fn exponential_backoff(attempt: u32, base_duration: Duration) -> Duration {
652        let multiplier = 2_u64.pow(attempt.min(10)); // Cap at 2^10
653        Duration::from_millis(base_duration.as_millis() as u64 * multiplier)
654    }
655
656    /// Apply jitter to retry duration to prevent thundering herd
657    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), // Shorter window for testing
675            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        // First 3 requests should be allowed
686        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        // 4th request should be denied
696        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        // Wait for window to reset
703        sleep(Duration::from_millis(150)).await;
704
705        // Should be allowed again
706        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        // First request allowed
733        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
734        assert!(matches!(result, RateLimitResult::Allowed { .. }));
735
736        // Second request denied (triggers penalty)
737        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
738        assert!(matches!(result, RateLimitResult::Denied { .. }));
739
740        // Wait a bit for penalty to be applied
741        sleep(Duration::from_millis(10)).await;
742
743        // Third request should be blocked due to penalty (not just denied)
744        let result = limiter.check_rate_limit("penalty_test").await.unwrap();
745        assert!(matches!(result, RateLimitResult::Blocked { .. }));
746
747        // Wait for penalty to expire
748        sleep(Duration::from_millis(250)).await;
749
750        // Should be allowed again
751        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        // Should cap at 2^10
795        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}