Module: OmniauthOpenidFederation::RateLimiter

Defined in:
lib/omniauth_openid_federation/rate_limiter.rb

Constant Summary collapse

DEFAULT_MAX_REQUESTS =

Default rate limiting configuration

10
DEFAULT_WINDOW_SECONDS =
60

Class Method Summary collapse

Class Method Details

.allow?(key, max_requests: DEFAULT_MAX_REQUESTS, window: DEFAULT_WINDOW_SECONDS) ⇒ Boolean

Check if request should be throttled



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
# File 'lib/omniauth_openid_federation/rate_limiter.rb', line 18

def self.allow?(key, max_requests: DEFAULT_MAX_REQUESTS, window: DEFAULT_WINDOW_SECONDS)
  return true unless defined?(Rails) && Rails.cache

  cache_key = "omniauth_openid_federation:rate_limit:#{Digest::SHA256.hexdigest(key)}"
  current_time = Time.now.to_i
  window_start = current_time - window

  # Get existing request timestamps
  timestamps = Rails.cache.read(cache_key) || []

  # Filter out timestamps outside the current window
  timestamps = timestamps.select { |ts| ts > window_start }

  # Check if we've exceeded the limit
  if timestamps.length >= max_requests
    OmniauthOpenidFederation::Logger.warn("[RateLimiter] Rate limit exceeded for #{Utils.sanitize_uri(key)}: #{timestamps.length}/#{max_requests} requests in #{window}s")
    return false
  end

  # Add current request timestamp
  timestamps << current_time

  # Store updated timestamps (expires after window)
  Rails.cache.write(cache_key, timestamps, expires_in: window)

  true
end

.reset!(key) ⇒ Object

Reset rate limit for a key (useful for testing or manual override)



49
50
51
52
53
# File 'lib/omniauth_openid_federation/rate_limiter.rb', line 49

def self.reset!(key)
  return unless defined?(Rails) && Rails.cache
  cache_key = "omniauth_openid_federation:rate_limit:#{Digest::SHA256.hexdigest(key)}"
  Rails.cache.delete(cache_key)
end