Skip to content

Commit

Permalink
Throttling fix & Add protection against login brute forcing (#2685)
Browse files Browse the repository at this point in the history
  • Loading branch information
pglombardo authored Oct 25, 2024
1 parent 08830c8 commit ff39442
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ gem "mysql2"
gem "pg"
gem "sqlite3", force_ruby_platform: true

group :production do
group :production, :development do
gem "rack-attack"
end

Expand Down
34 changes: 18 additions & 16 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,16 @@ class Rack::Attack
unless Rails.env.test?
# Throttle all requests by IP
#
throttle("req/ip", limit: Settings.throttling.minute, period: 1.minute) do |req|
req.ip # unless req.path.start_with?('/assets')
if Settings.throttling&.minute.present?
throttle("req/minute/ip", limit: Settings.throttling.minute, period: 1.minute) do |req|
req.ip unless req.path.start_with?("/assets")
end
end

# Throttle API requests by IP address
#
throttle("api/ip", limit: Settings.throttling.second, period: 1.second) do |req|
if req.path == "/api"
if Settings.throttling&.second.present?
throttle("req/second/ip", limit: Settings.throttling.second, period: 1.second) do |req|
req.ip
end
end
Expand All @@ -55,11 +57,11 @@ class Rack::Attack

# Throttle POST requests to /users/sign_in by IP address
#
# throttle("logins/ip", limit: 5, period: 20.seconds) do |req|
# if req.path == "/users/sign_in" && req.post?
# req.ip
# end
# end
throttle("logins/ip", limit: 5, period: 20.seconds) do |req|
if req.path == "/users/sign_in" && req.post?
req.ip
end
end

# Throttle POST requests to /users/sign_in by email param
#
Expand All @@ -68,12 +70,12 @@ class Rack::Attack
# denied, but that's not very common and shouldn't happen to you. (Knock
# on wood!)
#
# throttle("logins/email", limit: 5, period: 20.seconds) do |req|
# if req.path == "/users/sign_in" && req.post?
# # Normalize the email, using the same logic as your authentication process, to
# # protect against rate limit bypasses. Return the normalized email if present, nil otherwise.
# req.params["email"].to_s.downcase.gsub(/\s+/, "").presence
# end
# end
throttle("logins/email", limit: 5, period: 20.seconds) do |req|
if req.path == "/users/sign_in" && req.post?
# Normalize the email, using the same logic as your authentication process, to
# protect against rate limit bypasses. Return the normalized email if present, nil otherwise.
req.params["email"].to_s.downcase.gsub(/\s+/, "").presence
end
end
end
end

0 comments on commit ff39442

Please sign in to comment.