Skip to content

Commit

Permalink
Use different rate limit for authenticated users (#1963)
Browse files Browse the repository at this point in the history
Use a different rate limit for authenticated users. This limit can be set in the `api_rate_limit_authenticated` setting, and the default value is 1000.
  • Loading branch information
jayjay-w authored Jul 24, 2024
1 parent b3a8c11 commit 0be4e16
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
13 changes: 12 additions & 1 deletion config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,19 @@ def self.real_ip(req)
req.get_header('HTTP_CF_CONNECTING_IP') || req.ip
end

def self.authenticated?(req)
warden = req.env['warden']
warden && warden.user.present?
end

# Throttle all graphql requests by IP address
throttle('api/graphql', limit: proc { CheckConfig.get('api_rate_limit', 100, :integer) }, period: 60.seconds) do |req|
throttle('api/graphql', limit: proc { |req|
if authenticated?(req)
CheckConfig.get('api_rate_limit_authenticated', 1000, :integer)
else
CheckConfig.get('api_rate_limit', 100, :integer)
end
}, period: 60.seconds) do |req|
real_ip(req) if req.path == '/api/graphql'
end

Expand Down
20 changes: 20 additions & 0 deletions test/lib/check_rack_attack_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,24 @@ class ThrottlingTest < ActionDispatch::IntegrationTest

Rails.env = original_env
end

test "should apply higher rate limit for authenticated users" do
stub_configs({ 'api_rate_limit_authenticated' => 5 }) do
password = random_complex_password
user = create_user password: password
user_params = { api_user: { email: user.email, password: password } }


post api_user_session_path, params: user_params, as: :json
assert_response :success

5.times do
post api_graphql_path
assert_response :success
end

post api_graphql_path
assert_response :too_many_requests
end
end
end

0 comments on commit 0be4e16

Please sign in to comment.