rack_attack_global.rb 2.11 KB
Newer Older
1
module Gitlab::Throttle
Michael Kozono's avatar
Michael Kozono committed
2 3 4 5
  def self.settings
    Gitlab::CurrentSettings.current_application_settings
  end

6
  def self.unauthenticated_options
Michael Kozono's avatar
Michael Kozono committed
7 8 9 10 11
    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

12
  def self.authenticated_api_options
Michael Kozono's avatar
Michael Kozono committed
13 14 15 16 17
    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

18
  def self.authenticated_web_options
Michael Kozono's avatar
Michael Kozono committed
19 20 21 22
    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
23
end
Michael Kozono's avatar
Michael Kozono committed
24

25 26 27
class Rack::Attack
  throttle('throttle_unauthenticated', Gitlab::Throttle.unauthenticated_options) do |req|
    Gitlab::Throttle.settings.throttle_unauthenticated_enabled &&
28
      req.unauthenticated? &&
29
      !req.should_be_skipped? &&
30 31
      req.ip
  end
Michael Kozono's avatar
Michael Kozono committed
32

33 34
  throttle('throttle_authenticated_api', Gitlab::Throttle.authenticated_api_options) do |req|
    Gitlab::Throttle.settings.throttle_authenticated_api_enabled &&
35
      req.api_request? &&
36
      req.authenticated_user_id([:api])
Michael Kozono's avatar
Michael Kozono committed
37 38
  end

39 40
  throttle('throttle_authenticated_web', Gitlab::Throttle.authenticated_web_options) do |req|
    Gitlab::Throttle.settings.throttle_authenticated_web_enabled &&
41
      req.web_request? &&
42
      req.authenticated_user_id([:api, :rss, :ics])
43
  end
Michael Kozono's avatar
Michael Kozono committed
44 45 46

  class Request
    def unauthenticated?
47
      !authenticated_user_id([:api, :rss, :ics])
Michael Kozono's avatar
Michael Kozono committed
48 49
    end

50 51
    def authenticated_user_id(request_formats)
      Gitlab::Auth::RequestAuthenticator.new(self).user(request_formats)&.id
Michael Kozono's avatar
Michael Kozono committed
52 53 54 55 56 57
    end

    def api_request?
      path.start_with?('/api')
    end

58 59 60 61
    def api_internal_request?
      path =~ %r{^/api/v\d+/internal/}
    end

62 63 64 65
    def should_be_skipped?
      api_internal_request?
    end

Michael Kozono's avatar
Michael Kozono committed
66 67 68 69 70
    def web_request?
      !api_request?
    end
  end
end