|
| 1 | +/// Rate limiter for OAuth2 authentication attempts |
| 2 | +/// Implements exponential backoff to prevent abuse and brute force attacks |
| 3 | +class OAuth2RateLimiter { |
| 4 | + static final Map<String, _RateLimitState> _states = {}; |
| 5 | + |
| 6 | + // Maximum attempts before lockout |
| 7 | + static const int _maxAttempts = 5; |
| 8 | + |
| 9 | + // Initial delay after first failure (in seconds) |
| 10 | + static const int _initialDelay = 2; |
| 11 | + |
| 12 | + // Maximum delay (in seconds) |
| 13 | + static const int _maxDelay = 300; // 5 minutes |
| 14 | + |
| 15 | + // Time window for reset (in minutes) |
| 16 | + static const int _resetWindow = 30; |
| 17 | + |
| 18 | + /// Check if an OAuth operation can proceed |
| 19 | + /// Returns null if allowed, or DateTime when the operation can be retried |
| 20 | + static DateTime? canProceed(String key) { |
| 21 | + final state = _states[key]; |
| 22 | + |
| 23 | + if (state == null) { |
| 24 | + // First attempt, no restrictions |
| 25 | + return null; |
| 26 | + } |
| 27 | + |
| 28 | + final now = DateTime.now(); |
| 29 | + |
| 30 | + // Check if we should reset the counter (time window passed) |
| 31 | + if (now.difference(state.firstAttempt).inMinutes >= _resetWindow) { |
| 32 | + _states.remove(key); |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + // Check if we're in cooldown period |
| 37 | + if (state.nextAttemptAt != null && now.isBefore(state.nextAttemptAt!)) { |
| 38 | + return state.nextAttemptAt; |
| 39 | + } |
| 40 | + |
| 41 | + // Check if max attempts exceeded |
| 42 | + if (state.attemptCount >= _maxAttempts) { |
| 43 | + // Calculate next allowed attempt with exponential backoff |
| 44 | + final delaySeconds = _calculateDelay(state.attemptCount); |
| 45 | + final nextAttempt = state.lastAttempt.add(Duration(seconds: delaySeconds)); |
| 46 | + |
| 47 | + if (now.isBefore(nextAttempt)) { |
| 48 | + return nextAttempt; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + /// Record a failed authentication attempt |
| 56 | + static void recordFailure(String key) { |
| 57 | + final now = DateTime.now(); |
| 58 | + final state = _states[key]; |
| 59 | + |
| 60 | + if (state == null) { |
| 61 | + _states[key] = _RateLimitState( |
| 62 | + firstAttempt: now, |
| 63 | + lastAttempt: now, |
| 64 | + attemptCount: 1, |
| 65 | + nextAttemptAt: null, |
| 66 | + ); |
| 67 | + } else { |
| 68 | + final delaySeconds = _calculateDelay(state.attemptCount + 1); |
| 69 | + |
| 70 | + _states[key] = _RateLimitState( |
| 71 | + firstAttempt: state.firstAttempt, |
| 72 | + lastAttempt: now, |
| 73 | + attemptCount: state.attemptCount + 1, |
| 74 | + nextAttemptAt: now.add(Duration(seconds: delaySeconds)), |
| 75 | + ); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /// Record a successful authentication (clears the rate limit) |
| 80 | + static void recordSuccess(String key) { |
| 81 | + _states.remove(key); |
| 82 | + } |
| 83 | + |
| 84 | + /// Calculate delay with exponential backoff |
| 85 | + static int _calculateDelay(int attemptCount) { |
| 86 | + if (attemptCount <= 1) return 0; |
| 87 | + |
| 88 | + // Exponential backoff: 2^(n-1) seconds, capped at _maxDelay |
| 89 | + final delay = _initialDelay * (1 << (attemptCount - 2)); |
| 90 | + return delay > _maxDelay ? _maxDelay : delay; |
| 91 | + } |
| 92 | + |
| 93 | + /// Generate rate limit key from client credentials |
| 94 | + static String generateKey(String clientId, String tokenUrl) { |
| 95 | + return '$clientId:$tokenUrl'; |
| 96 | + } |
| 97 | + |
| 98 | + /// Get remaining cooldown time in seconds |
| 99 | + static int? getCooldownSeconds(String key) { |
| 100 | + final canProceedAt = canProceed(key); |
| 101 | + if (canProceedAt == null) return null; |
| 102 | + |
| 103 | + final now = DateTime.now(); |
| 104 | + final diff = canProceedAt.difference(now); |
| 105 | + return diff.inSeconds > 0 ? diff.inSeconds : null; |
| 106 | + } |
| 107 | + |
| 108 | + /// Clear all rate limiting states (for testing or admin purposes) |
| 109 | + static void clearAll() { |
| 110 | + _states.clear(); |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +class _RateLimitState { |
| 115 | + final DateTime firstAttempt; |
| 116 | + final DateTime lastAttempt; |
| 117 | + final int attemptCount; |
| 118 | + final DateTime? nextAttemptAt; |
| 119 | + |
| 120 | + _RateLimitState({ |
| 121 | + required this.firstAttempt, |
| 122 | + required this.lastAttempt, |
| 123 | + required this.attemptCount, |
| 124 | + this.nextAttemptAt, |
| 125 | + }); |
| 126 | +} |
0 commit comments