wisegate-core 0.12.0

Core library for WiseGate reverse proxy - rate limiting, IP filtering, and request handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Rate limiting implementation for WiseGate.
//!
//! Provides per-IP rate limiting using a sliding window log algorithm with
//! automatic cleanup of expired entries to prevent memory exhaustion.
//!
//! # Algorithm
//!
//! Uses a sliding window log approach:
//! - Each IP tracks individual request timestamps in a deque
//! - On each check, expired timestamps (outside the window) are evicted
//! - If the remaining count is under the limit, the request is allowed
//! - This prevents the boundary-burst problem of fixed windows
//!
//! # Memory Management
//!
//! To prevent memory exhaustion from tracking many unique IPs, the rate limiter
//! performs automatic cleanup when:
//! - Entry count exceeds the configured threshold
//! - Minimum interval since last cleanup has passed
//!
//! # Thread Safety
//!
//! Uses `tokio::sync::Mutex` for async-friendly locking that won't block
//! the Tokio thread pool.
//!
//! # Example
//!
//! ```ignore
//! use wisegate_core::{rate_limiter, RateLimiter};
//!
//! let limiter = RateLimiter::new();
//!
//! if rate_limiter::check_rate_limit(&limiter, "192.168.1.1", &config).await {
//!     // Request allowed
//! } else {
//!     // Rate limit exceeded
//! }
//! ```

use std::time::Instant;
use tracing::debug;

use crate::types::{ConfigProvider, RateLimitEntry, RateLimiter};

/// Checks if a request from the given IP should be allowed based on rate limits.
///
/// Returns `true` if the request is allowed, `false` if rate limited.
///
/// # Algorithm
///
/// 1. If the time window has expired for this IP, reset the counter
/// 2. If the request count is under the limit, increment and allow
/// 3. If the request count exceeds the limit, deny
///
/// # Cleanup
///
/// Automatically cleans up expired entries when:
/// - Entry count exceeds `RATE_LIMIT_CLEANUP_THRESHOLD`
/// - At least `RATE_LIMIT_CLEANUP_INTERVAL_SECS` since last cleanup
///
/// # Arguments
///
/// * `limiter` - Shared rate limiter state
/// * `ip` - Client IP address to check
/// * `config` - Configuration provider for rate limit settings
///
/// # Returns
///
/// - `true` - Request is allowed
/// - `false` - Request is rate limited (should return 429)
///
/// # Example
///
/// ```ignore
/// use wisegate_core::rate_limiter::check_rate_limit;
///
/// if !check_rate_limit(&limiter, &client_ip, &config).await {
///     return Err(StatusCode::TOO_MANY_REQUESTS);
/// }
/// ```
pub async fn check_rate_limit(
    limiter: &RateLimiter,
    ip: &str,
    config: &impl ConfigProvider,
) -> bool {
    let rate_config = config.rate_limit_config();
    let cleanup_config = config.rate_limit_cleanup_config();
    let now = Instant::now();

    let mut state = limiter.state().lock().await;

    // Cleanup expired entries if threshold exceeded and interval elapsed
    if cleanup_config.is_enabled() && state.entries.len() > cleanup_config.threshold {
        let should_cleanup = match state.last_cleanup {
            None => true,
            Some(last) => now.duration_since(last) >= cleanup_config.interval,
        };
        if should_cleanup {
            state.last_cleanup = Some(now);
            let before_count = state.entries.len();
            state.entries.retain(|_, entry| {
                entry
                    .oldest()
                    .is_some_and(|t| now.duration_since(t) < rate_config.window_duration * 2)
            });
            let removed = before_count - state.entries.len();
            if removed > 0 {
                debug!(
                    removed_entries = removed,
                    remaining_entries = state.entries.len(),
                    "Rate limiter cleanup completed"
                );
            }
        }
    }

    let entry = state
        .entries
        .entry(ip.to_string())
        .or_insert_with(|| RateLimitEntry {
            timestamps: std::collections::VecDeque::new(),
        });

    // Evict timestamps outside the current window (true sliding window)
    while entry
        .timestamps
        .front()
        .is_some_and(|&t| now.duration_since(t) >= rate_config.window_duration)
    {
        entry.timestamps.pop_front();
    }

    if (entry.timestamps.len() as u32) < rate_config.max_requests {
        entry.timestamps.push_back(now);
        true
    } else {
        // Rate limit exceeded
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::TestConfig;

    // ===========================================
    // Basic rate limiting tests
    // ===========================================

    #[tokio::test]
    async fn test_first_request_allowed() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(5, 60);

        let allowed = check_rate_limit(&limiter, "192.168.1.1", &config).await;
        assert!(allowed);
    }

    #[tokio::test]
    async fn test_requests_within_limit_allowed() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(5, 60);

        for i in 0..5 {
            let allowed = check_rate_limit(&limiter, "192.168.1.1", &config).await;
            assert!(allowed, "Request {} should be allowed", i + 1);
        }
    }

    #[tokio::test]
    async fn test_request_exceeding_limit_blocked() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(3, 60);

        // First 3 requests should be allowed
        for _ in 0..3 {
            assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        }

        // 4th request should be blocked
        let blocked = check_rate_limit(&limiter, "192.168.1.1", &config).await;
        assert!(!blocked, "Request exceeding limit should be blocked");
    }

    #[tokio::test]
    async fn test_different_ips_independent() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(2, 60);

        // IP 1 makes 2 requests
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // IP 2 should still have its full quota
        assert!(check_rate_limit(&limiter, "192.168.1.2", &config).await);
        assert!(check_rate_limit(&limiter, "192.168.1.2", &config).await);
        assert!(!check_rate_limit(&limiter, "192.168.1.2", &config).await);
    }

    #[tokio::test]
    async fn test_counter_increments_correctly() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(5, 60);

        // Make some requests
        check_rate_limit(&limiter, "192.168.1.1", &config).await;
        check_rate_limit(&limiter, "192.168.1.1", &config).await;
        check_rate_limit(&limiter, "192.168.1.1", &config).await;

        // Check the counter
        let state = limiter.state().lock().await;
        let entry = state.entries.get("192.168.1.1").unwrap();
        assert_eq!(entry.request_count(), 3);
    }

    // ===========================================
    // Edge case tests
    // ===========================================

    #[tokio::test]
    async fn test_limit_of_one() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(1, 60);

        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);
    }

    #[tokio::test]
    async fn test_ipv6_addresses() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(2, 60);

        assert!(check_rate_limit(&limiter, "::1", &config).await);
        assert!(check_rate_limit(&limiter, "::1", &config).await);
        assert!(!check_rate_limit(&limiter, "::1", &config).await);

        // Different IPv6 should be independent
        assert!(check_rate_limit(&limiter, "2001:db8::1", &config).await);
    }

    #[tokio::test]
    async fn test_multiple_blocked_requests() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(1, 60);

        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Multiple blocked requests should all return false
        for _ in 0..5 {
            assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);
        }

        // Counter should not increase beyond limit
        let state = limiter.state().lock().await;
        let entry = state.entries.get("192.168.1.1").unwrap();
        assert_eq!(entry.request_count(), 1);
    }

    // ===========================================
    // Concurrent access tests
    // ===========================================

    #[tokio::test]
    async fn test_limiter_clone_shares_state() {
        let limiter1 = RateLimiter::new();
        let limiter2 = limiter1.clone();
        let config = TestConfig::new().with_rate_limit(2, 60);

        // Use limiter1 for first request
        assert!(check_rate_limit(&limiter1, "192.168.1.1", &config).await);

        // Use limiter2 for second request - should share state
        assert!(check_rate_limit(&limiter2, "192.168.1.1", &config).await);

        // Third request on either should be blocked
        assert!(!check_rate_limit(&limiter1, "192.168.1.1", &config).await);
    }

    // ===========================================
    // Cleanup tests
    // ===========================================

    #[tokio::test]
    async fn test_cleanup_disabled_when_threshold_zero() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(100, 60); // Cleanup disabled (threshold = 0)

        // Add many entries
        for i in 0..100 {
            check_rate_limit(&limiter, &format!("192.168.1.{}", i), &config).await;
        }

        // All entries should remain (no cleanup)
        let state = limiter.state().lock().await;
        assert_eq!(state.entries.len(), 100);
    }

    #[tokio::test]
    async fn test_entries_tracked_per_ip() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(10, 60);

        // Make requests from 5 different IPs
        for i in 0..5 {
            check_rate_limit(&limiter, &format!("10.0.0.{}", i), &config).await;
        }

        let state = limiter.state().lock().await;
        assert_eq!(state.entries.len(), 5);
    }

    // ===========================================
    // Time-based / Window expiration tests
    // ===========================================

    #[tokio::test]
    async fn test_window_reset_after_expiration() {
        use crate::types::{RateLimitCleanupConfig, RateLimitConfig};
        use std::time::Duration;

        let limiter = RateLimiter::new();
        // Use very short window for testing - need direct struct for milliseconds
        let config = TestConfig {
            rate_limit: RateLimitConfig {
                max_requests: 2,
                window_duration: Duration::from_millis(1),
            },
            cleanup: RateLimitCleanupConfig {
                threshold: 0,
                interval: Duration::from_secs(60),
            },
            ..TestConfig::default()
        };

        // First two requests allowed
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Third blocked
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Wait for window to expire
        tokio::time::sleep(Duration::from_millis(5)).await;

        // Should be allowed again after window expires
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
    }

    #[tokio::test]
    async fn test_window_reset_resets_counter() {
        use crate::types::{RateLimitCleanupConfig, RateLimitConfig};
        use std::time::Duration;

        let limiter = RateLimiter::new();
        let config = TestConfig {
            rate_limit: RateLimitConfig {
                max_requests: 3,
                window_duration: Duration::from_millis(1),
            },
            cleanup: RateLimitCleanupConfig {
                threshold: 0,
                interval: Duration::from_secs(60),
            },
            ..TestConfig::default()
        };

        // Use full quota
        for _ in 0..3 {
            assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        }
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Wait for window to expire
        tokio::time::sleep(Duration::from_millis(5)).await;

        // Counter should reset, full quota available again
        for _ in 0..3 {
            assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        }
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);
    }

    #[tokio::test]
    async fn test_window_not_expired_keeps_count() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(5, 3600); // 1 hour window

        // Make 3 requests
        for _ in 0..3 {
            assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        }

        // Verify counter is 3
        {
            let state = limiter.state().lock().await;
            assert_eq!(state.entries.get("192.168.1.1").unwrap().request_count(), 3);
        }

        // Make 2 more requests (still within limit)
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Now should be blocked (5 requests made)
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Counter should still be 5 (not increased when blocked)
        let state = limiter.state().lock().await;
        assert_eq!(state.entries.get("192.168.1.1").unwrap().request_count(), 5);
    }

    #[tokio::test]
    async fn test_different_ips_different_windows() {
        use crate::types::{RateLimitCleanupConfig, RateLimitConfig};
        use std::time::Duration;

        let limiter = RateLimiter::new();
        let config = TestConfig {
            rate_limit: RateLimitConfig {
                max_requests: 2,
                window_duration: Duration::from_millis(50),
            },
            cleanup: RateLimitCleanupConfig {
                threshold: 0,
                interval: Duration::from_secs(60),
            },
            ..TestConfig::default()
        };

        // IP1: exhaust quota
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // Wait a bit (not enough for window to expire)
        tokio::time::sleep(Duration::from_millis(10)).await;

        // IP2: start fresh
        assert!(check_rate_limit(&limiter, "192.168.1.2", &config).await);

        // Wait for IP1's window to expire
        tokio::time::sleep(Duration::from_millis(50)).await;

        // IP1 should be allowed again
        assert!(check_rate_limit(&limiter, "192.168.1.1", &config).await);

        // IP2 still within its window, should have 1 request counted
        let state = limiter.state().lock().await;
        // IP2 might have had its window expire too, depends on timing
        // Just verify both IPs are tracked
        assert!(state.entries.contains_key("192.168.1.1"));
        assert!(state.entries.contains_key("192.168.1.2"));
    }

    // ===========================================
    // Cleanup with expiration tests
    // ===========================================

    #[tokio::test]
    async fn test_cleanup_removes_expired_entries() {
        use crate::types::{RateLimitCleanupConfig, RateLimitConfig};
        use std::time::Duration;

        let limiter = RateLimiter::new();
        let config = TestConfig {
            rate_limit: RateLimitConfig {
                max_requests: 100,
                window_duration: Duration::from_millis(1), // Very short window
            },
            cleanup: RateLimitCleanupConfig {
                threshold: 1,                       // Trigger cleanup when > 1 entry
                interval: Duration::from_millis(1), // Allow frequent cleanup
            },
            ..TestConfig::default()
        };

        // Add first entry
        check_rate_limit(&limiter, "192.168.1.1", &config).await;

        // Wait for it to expire (2x window duration for cleanup)
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Add second entry - this should trigger cleanup
        check_rate_limit(&limiter, "192.168.1.2", &config).await;

        // Wait a bit more and add third to trigger another cleanup check
        tokio::time::sleep(Duration::from_millis(10)).await;
        check_rate_limit(&limiter, "192.168.1.3", &config).await;

        // The first entry should have been cleaned up (expired > 2x window)
        let state = limiter.state().lock().await;
        assert!(
            !state.entries.contains_key("192.168.1.1"),
            "Expired entry should have been cleaned up"
        );
        // At least the most recent entry should remain
        assert!(
            state.entries.contains_key("192.168.1.3"),
            "Recent entry should still exist"
        );
    }

    // ===========================================
    // Concurrent request tests
    // ===========================================

    #[tokio::test]
    async fn test_concurrent_requests_same_ip() {
        let limiter = RateLimiter::new();
        let config = TestConfig::new().with_rate_limit(10, 60);

        // Spawn multiple concurrent requests
        let mut handles = vec![];
        for _ in 0..10 {
            let limiter_clone = limiter.clone();
            let handle = tokio::spawn(async move {
                let config = TestConfig::new().with_rate_limit(10, 60);
                check_rate_limit(&limiter_clone, "192.168.1.1", &config).await
            });
            handles.push(handle);
        }

        // Wait for all to complete
        let results: Vec<bool> = futures::future::join_all(handles)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // All 10 should be allowed
        assert_eq!(results.iter().filter(|&&r| r).count(), 10);

        // 11th request should be blocked
        assert!(!check_rate_limit(&limiter, "192.168.1.1", &config).await);
    }

    #[tokio::test]
    async fn test_concurrent_requests_different_ips() {
        let limiter = RateLimiter::new();

        // Spawn requests from different IPs concurrently
        let mut handles = vec![];
        for i in 0..50 {
            let limiter_clone = limiter.clone();
            let ip = format!("192.168.1.{}", i);
            let handle = tokio::spawn(async move {
                let config = TestConfig::new().with_rate_limit(5, 60);
                check_rate_limit(&limiter_clone, &ip, &config).await
            });
            handles.push(handle);
        }

        // Wait for all to complete
        let results: Vec<bool> = futures::future::join_all(handles)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // All should be allowed (first request from each IP)
        assert!(results.iter().all(|&r| r));

        // Verify all IPs are tracked
        let state = limiter.state().lock().await;
        assert_eq!(state.entries.len(), 50);
    }
}