Skip to content

Commit

Permalink
Reduce the number of api calls when testing rate limiting
Browse files Browse the repository at this point in the history
Reduce the number of actual api calls to 2 per test when testing
rate limiting.
  • Loading branch information
jayjay-w committed Jan 24, 2024
1 parent 44de8b7 commit 4b03a98
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
8 changes: 4 additions & 4 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
class Rack::Attack
# Throttle login attempts by IP address
throttle('logins/ip', limit: CheckConfig.get('login_rate_limit', 10, :integer), period: 60.seconds) do |req|
throttle('logins/ip', limit: proc { CheckConfig.get('login_rate_limit', 10, :integer) }, period: 60.seconds) do |req|
if req.path == '/api/users/sign_in' && req.post?
req.ip
end
end

# Throttle login attempts by email address
throttle('logins/email', limit: CheckConfig.get('login_rate_limit', 10, :integer), period: 60.seconds) do |req|
throttle('logins/email', limit: proc { CheckConfig.get('login_rate_limit', 10, :integer) }, period: 60.seconds) do |req|
if req.path == '/api/users/sign_in' && req.post?
# Return the email if present, nil otherwise
req.params['user']['email'].presence if req.params['user']
end
end

# Throttle all graphql requests by IP address
throttle('api/graphql', limit: CheckConfig.get('api_rate_limit', 100, :integer), period: 60.seconds) do |req|
# Throttle all graphql requests by IP address
throttle('api/graphql', limit: proc { CheckConfig.get('api_rate_limit', 100, :integer) }, period: 60.seconds) do |req|
req.ip if req.path == '/api/graphql'
end
end
25 changes: 13 additions & 12 deletions test/lib/check_rack_attack_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,27 @@ class ThrottlingTest < ActionDispatch::IntegrationTest
end

test "should throttle excessive requests to /api/graphql" do
limit = 100
stub_configs({ 'api_rate_limit' => 2 }) do
2.times do
post api_graphql_path
assert_response :unauthorized
end

limit.times do
post api_graphql_path
assert_response :unauthorized
assert_response :too_many_requests
end

get api_graphql_path
assert_response :too_many_requests
end

test "should throttle excessive requests to /api/users/sign_in" do
limit = 10
user_params = { api_user: { email: '[email protected]', password: 'password' } }
stub_configs({ 'login_rate_limit' => 2 }) do
user_params = { api_user: { email: '[email protected]', password: 'password' } }

2.times do
post api_user_session_path, params: user_params, as: :json
end

limit.times do
post api_user_session_path, params: user_params, as: :json
assert_response :too_many_requests
end

post api_user_session_path, params: user_params, as: :json
assert_response :too_many_requests
end
end

0 comments on commit 4b03a98

Please sign in to comment.