diff options
author | Michael Kozono <mkozono@gmail.com> | 2017-09-15 10:31:32 -0700 |
---|---|---|
committer | Francisco Lopez <fjlopez@gitlab.com> | 2017-11-17 09:58:18 +0100 |
commit | dc9266fbeacd24446b52e4dad328c8286be40b31 (patch) | |
tree | f882ee2eac622aa6daafa71d80663d6a5014d3b9 /config/initializers | |
parent | 732b122644bf56729996b3cc239453f537a798f4 (diff) | |
download | gitlab-ce-dc9266fbeacd24446b52e4dad328c8286be40b31.tar.gz |
Add request throttles
Diffstat (limited to 'config/initializers')
-rw-r--r-- | config/initializers/rack_attack_global.rb | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/config/initializers/rack_attack_global.rb b/config/initializers/rack_attack_global.rb new file mode 100644 index 00000000000..0b51fadbd02 --- /dev/null +++ b/config/initializers/rack_attack_global.rb @@ -0,0 +1,73 @@ +class Rack::Attack + def self.settings + Gitlab::CurrentSettings.current_application_settings + end + + def self.throttle_unauthenticated_options + limit_proc = proc { |req| settings.throttle_unauthenticated_requests_per_period } + period_proc = proc { |req| settings.throttle_unauthenticated_period_in_seconds.seconds } + { limit: limit_proc, period: period_proc } + end + + def self.throttle_authenticated_api_options + limit_proc = proc { |req| settings.throttle_authenticated_api_requests_per_period } + period_proc = proc { |req| settings.throttle_authenticated_api_period_in_seconds.seconds } + { limit: limit_proc, period: period_proc } + end + + def self.throttle_authenticated_web_options + limit_proc = proc { |req| settings.throttle_authenticated_web_requests_per_period } + period_proc = proc { |req| settings.throttle_authenticated_web_period_in_seconds.seconds } + { limit: limit_proc, period: period_proc } + end + + def self.define_throttles + throttle('throttle_unauthenticated', throttle_unauthenticated_options) do |req| + settings.throttle_unauthenticated_enabled && + req.unauthenticated? && + req.ip + end + + throttle('throttle_authenticated_api', throttle_authenticated_api_options) do |req| + settings.throttle_authenticated_api_enabled && + req.api_request? && + req.authenticated_user_id + end + + throttle('throttle_authenticated_web', throttle_authenticated_web_options) do |req| + settings.throttle_authenticated_web_enabled && + req.web_request? && + req.authenticated_user_id + end + end + + define_throttles unless Rails.env.test? + + class Request + def unauthenticated? + !authenticated_user_id + end + + def authenticated_user_id + session_user_id || sessionless_user_id + end + + def api_request? + path.start_with?('/api') + end + + def web_request? + !api_request? + end + + private + + def session_user_id + Gitlab::Auth.find_session_user(self)&.id + end + + def sessionless_user_id + Gitlab::Auth.find_sessionless_user(self)&.id + end + end +end |