Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ip_rate_limiter.rb « auth « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f301a2ec2e8bfb0284fa31c7011d178c7edeb235 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true

module Gitlab
  module Auth
    class IpRateLimiter
      include ::Gitlab::Utils::StrongMemoize

      attr_reader :ip

      def initialize(ip)
        @ip = ip
      end

      def reset!
        return if skip_rate_limit?

        Rack::Attack::Allow2Ban.reset(ip, config)
      end

      def register_fail!
        return false if skip_rate_limit?

        # Allow2Ban.filter will return false if this IP has not failed too often yet
        Rack::Attack::Allow2Ban.filter(ip, config) do
          # We return true to increment the count for this IP
          true
        end
      end

      def banned?
        return false if skip_rate_limit?

        Rack::Attack::Allow2Ban.banned?(ip)
      end

      private

      def skip_rate_limit?
        !enabled? || trusted_ip?
      end

      def enabled?
        config.enabled
      end

      def config
        Gitlab.config.rack_attack.git_basic_auth
      end

      def trusted_ip?
        trusted_ips.any? { |netmask| netmask.include?(ip) }
      end

      def trusted_ips
        strong_memoize(:trusted_ips) do
          config.ip_whitelist.map do |proxy|
            IPAddr.new(proxy)
          rescue IPAddr::InvalidAddressError
          end.compact
        end
      end
    end
  end
end