Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ gem 'bunny-pub-sub', '0.5.2'
gem 'ci_reporter'
gem 'dotenv'
gem 'rack-cors', require: 'rack/cors'
gem 'rack-attack'
gem 'require_all', '>=1.3.3'

# Excel support
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,8 @@ GEM
raabro (1.4.0)
racc (1.8.1)
rack (3.1.12)
rack-attack (6.8.0)
rack (>= 1.0, < 4)
rack-cors (2.0.2)
rack (>= 2.0.0)
rack-session (2.1.0)
Expand Down Expand Up @@ -593,6 +595,7 @@ DEPENDENCIES
oauth2
pdf-reader
puma
rack-attack
rack-cors
rails (~> 8.0)
rails-latex
Expand Down
1 change: 1 addition & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ def self.fetch_boolean_env(name)
resource '*', headers: :any, methods: %i(get post put delete options)
end
end
config.middleware.use Rack::Attack

config.active_support.to_time_preserves_timezone = :zone

Expand Down
32 changes: 32 additions & 0 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Rack::Attack
# Rack::Attack depends on cache to persist counters.
# In development/test the app cache can be NullStore, which disables throttling.
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new

# Limit repeated login attempts against the API auth endpoint.
throttle('auth/ip', limit: 5, period: 20.seconds) do |req|
req.ip if req.path.start_with?('/api/auth') && req.post?
end

# Return a consistent API-friendly throttling response.
self.throttled_responder = lambda do |request|
rack_env =
if request.respond_to?(:env)
request.env
elsif request.respond_to?(:[])
request
else
{}
end

match_data = rack_env['rack.attack.match_data'] || {}
now = match_data[:epoch_time] || Time.now.to_i
retry_after = match_data[:period].to_i - (now % match_data[:period].to_i) if match_data[:period].to_i.positive?

body = { error: 'Too many login attempts. Please try again shortly.' }.to_json
headers = { 'Content-Type' => 'application/json' }
headers['Retry-After'] = retry_after.to_s if retry_after

[429, headers, [body]]
end
end