diff --git a/Gemfile b/Gemfile index 62add473..809bffcb 100644 --- a/Gemfile +++ b/Gemfile @@ -55,6 +55,7 @@ gem 'bibtex-ruby' gem "connection_pool", "<3.0" gem 'dalli' +gem 'rack-attack' # per-IP request limits, in config/initializers/rack_attack.rb gem 'ostruct' diff --git a/Gemfile.lock b/Gemfile.lock index 40d6bfd3..1110b4a6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -370,6 +370,8 @@ GEM raabro (1.5.0) racc (1.8.1) rack (3.2.7) + rack-attack (6.8.0) + rack (>= 1.0, < 4) rack-protection (4.2.1) base64 (>= 0.1.0) logger (>= 1.6.0) @@ -614,6 +616,7 @@ DEPENDENCIES prometheus-client propshaft puma + rack-attack rails (~> 8.0) rails-controller-testing rails-erd @@ -794,6 +797,7 @@ CHECKSUMS raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7 + rack-attack (6.8.0) sha256=f2499fdebf85bcc05573a22dff57d24305ac14ec2e4156cd3c28d47cafeeecf2 rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 rack-test (2.3.0) sha256=b118d177cc002c572fc1b6fd8d19c9ed5881a36e8d6f689f9e618f9f861241e8 diff --git a/config/environments/production.rb b/config/environments/production.rb index e1135582..2367837b 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -55,7 +55,9 @@ config.log_tags = [:request_id] # Use a different cache store in production. - config.cache_store = :mem_cache_store + # The memcached instance is shared with other apps, so every key (page fragments and the rate-limit + # counters in config/initializers/rack_attack.rb) starts with the app's name + config.cache_store = :mem_cache_store, { namespace: 'metadata' } # Jobs run in the bin/jobs process (Solid Queue; tables are in the main database) config.active_job.queue_adapter = :solid_queue diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb new file mode 100644 index 00000000..7d6bce81 --- /dev/null +++ b/config/initializers/rack_attack.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +# Per-client request limits, enforced by Rack::Attack before a request reaches Rails. +# +# The client is the request's IP (nginx passes the real one on in X-Forwarded-For; Rack ignores that header +# from anything but a trusted proxy). Counts live in Rails.cache, which is memcached in production, so every +# Puma worker shares them. If memcached is down the counts are lost and nothing is limited. +# +# requests/ip every request except assets: PER_SECOND a second +# logins/ip signing in and the password, unlock and invitation links: PER_MINUTE a minute +# costly/ip searches, file downloads and data queries: PER_MINUTE a minute +# +# The limits start here and can be changed without a deploy with RATE_LIMIT_PER_SECOND and +# RATE_LIMIT_PER_MINUTE, or switched off with RATE_LIMITING=off, in the environment of the app's service. +module RateLimits + PER_SECOND = ENV.fetch('RATE_LIMIT_PER_SECOND', 8).to_i + PER_MINUTE = ENV.fetch('RATE_LIMIT_PER_MINUTE', 15).to_i + + LOGIN_PATHS = %r{\A/users/(sign_in|password|unlock|invitation|auth)} + DOWNLOAD_PATHS = %r{\A/(pub/|(citations|abstracts|protocols)/\d+/download)} + DATA_PATHS = %r{\A(/datatables/\d+\.(csv|eml)|/datasets(/\d+)?\.eml|/visualizations/)} + SEARCH_PATHS = %r{\A/(datatables/(search|suggest)|citations/(search|filtered))} + + def self.asset?(path) + path.start_with?("#{Rails.application.config.assets.prefix}/", '/favicon.ico') + end + + def self.costly?(path) + [DOWNLOAD_PATHS, DATA_PATHS, SEARCH_PATHS].any? { |paths| paths.match?(path) } + end +end + +Rack::Attack.enabled = ENV['RATE_LIMITING'] != 'off' && !Rails.env.test? # the specs that test it turn it on +Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new if Rails.env.test? + +Rack::Attack.throttle('requests/ip', limit: RateLimits::PER_SECOND, period: 1.second) do |request| + request.ip unless RateLimits.asset?(request.path) +end + +Rack::Attack.throttle('logins/ip', limit: RateLimits::PER_MINUTE, period: 1.minute) do |request| + request.ip if RateLimits::LOGIN_PATHS.match?(request.path) +end + +Rack::Attack.throttle('costly/ip', limit: RateLimits::PER_MINUTE, period: 1.minute) do |request| + request.ip if RateLimits.costly?(request.path) +end + +Rack::Attack.throttled_responder = lambda do |request| + match = request.env['rack.attack.match_data'] + retry_after = [match[:period] - (match[:epoch_time] % match[:period]), 1].max + [429, { 'content-type' => 'text/plain', 'retry-after' => retry_after.to_s }, + ["Too many requests. Please slow down and try again in #{retry_after} seconds.\n"]] +end + +# The path only, not the query string, which can carry tokens +ActiveSupport::Notifications.subscribe('throttle.rack_attack') do |_name, _start, _finish, _id, payload| + request = payload[:request] + Rails.logger.warn "[rack-attack] #{request.env['rack.attack.matched']} limit reached: " \ + "#{request.ip} #{request.request_method} #{request.path}" +end diff --git a/spec/requests/rate_limits_spec.rb b/spec/requests/rate_limits_spec.rb new file mode 100644 index 00000000..8ece2b5a --- /dev/null +++ b/spec/requests/rate_limits_spec.rb @@ -0,0 +1,103 @@ +# frozen_string_literal: true + +require 'rails_helper' + +# Per-IP request limits (config/initializers/rack_attack.rb): 8 a second on everything but assets, and 15 a +# minute each on signing in and on searches, downloads and data queries. +RSpec.describe 'Rate limits', type: :request do + include ActiveSupport::Testing::TimeHelpers + + let(:start) { Time.zone.local(2026, 11, 7, 12, 0, 0) } # the start of a counting window + + before do + Website.create!(name: 'lter', url: 'lter.kbs.msu.edu') + Rack::Attack.enabled = true + Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new + travel_to(start) + end + + after { Rack::Attack.enabled = false } + + def visit(path, ip: '203.0.113.7', method: :get) + public_send(method, path, env: { 'REMOTE_ADDR' => ip }) + response.status + end + + # One request a second, so only the per-minute limits can be reached + def slowly(count, path, **) + Array.new(count) do + visit(path, **).tap { travel(1.second) } + end + end + + describe 'per second' do + it 'allows 8 requests in a second and refuses the 9th, saying when to come back' do + statuses = Array.new(9) { visit('/users/sign_in') } + + expect(statuses.first(8)).to all(be < 429) + expect(statuses.last).to eq 429 + expect(response.headers['Retry-After']).to eq '1' + expect(response.body).to include('Too many requests') + end + + it 'starts over in the next second' do + 9.times { visit('/users/sign_in') } + travel(1.second) + + expect(visit('/users/sign_in')).to be < 429 + end + + it 'counts each client separately' do + 9.times { visit('/users/sign_in', ip: '203.0.113.1') } + + expect(visit('/users/sign_in', ip: '203.0.113.2')).to be < 429 + end + + it 'counts the address nginx forwards, so a forged first X-Forwarded-For entry does not dodge the limit' do + statuses = (1..9).map do |n| + forwarded = "198.51.100.#{n}, 203.0.113.7" + get '/users/sign_in', env: { 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => forwarded } + response.status + end + + expect(statuses.last).to eq 429 + end + + it 'does not count assets' do + path = "#{Rails.application.config.assets.prefix}/application.css" + + expect(Array.new(20) { visit(path) }).not_to include(429) + end + end + + describe 'per minute' do + it 'allows 15 downloads, searches and data queries a minute, then refuses more' do + statuses = slowly(16, '/datatables/1.csv') + + expect(statuses.first(15)).to all(be < 429) + expect(statuses.last).to eq 429 + expect(visit('/citations/search')).to eq 429 # the same budget + end + + it 'allows 15 sign-in attempts a minute, then refuses more' do + statuses = slowly(16, '/users/sign_in', method: :post) + + expect(statuses.first(15)).to all(be < 429) + expect(statuses.last).to eq 429 + end + + it 'keeps sign-ins and costly requests on separate budgets, and leaves ordinary pages alone' do + slowly(16, '/datatables/1.csv') + + expect(visit('/users/sign_in', method: :post)).to be < 429 + expect(visit('/users/password/new')).to be < 429 + end + + it 'starts over the next minute' do + slowly(16, '/datatables/1.csv') + travel_to(start + 2.minutes) + + expect(visit('/datatables/1.csv')).to be < 429 + end + end +end