2018-12-13 13:39:08 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
module Gitlab
|
|
|
|
module Auth
|
|
|
|
class IpRateLimiter
|
2019-09-30 21:07:59 +05:30
|
|
|
include ::Gitlab::Utils::StrongMemoize
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
attr_reader :ip
|
|
|
|
|
|
|
|
def initialize(ip)
|
|
|
|
@ip = ip
|
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
def reset!
|
2020-01-01 13:55:28 +05:30
|
|
|
return if skip_rate_limit?
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
Rack::Attack::Allow2Ban.reset(ip, config)
|
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
def register_fail!
|
2020-01-01 13:55:28 +05:30
|
|
|
return false if skip_rate_limit?
|
2019-12-26 22:10:19 +05:30
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
# Allow2Ban.filter will return false if this IP has not failed too often yet
|
2020-01-01 13:55:28 +05:30
|
|
|
Rack::Attack::Allow2Ban.filter(ip, config) do
|
2019-12-26 22:10:19 +05:30
|
|
|
# We return true to increment the count for this IP
|
|
|
|
true
|
2016-06-16 23:09:34 +05:30
|
|
|
end
|
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
def banned?
|
2020-01-01 13:55:28 +05:30
|
|
|
return false if skip_rate_limit?
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2020-01-01 13:55:28 +05:30
|
|
|
Rack::Attack::Allow2Ban.banned?(ip)
|
2019-12-26 22:10:19 +05:30
|
|
|
end
|
|
|
|
|
2022-08-27 11:52:29 +05:30
|
|
|
def trusted_ip?
|
|
|
|
trusted_ips.any? { |netmask| netmask.include?(ip) }
|
|
|
|
end
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
private
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2020-01-01 13:55:28 +05:30
|
|
|
def skip_rate_limit?
|
|
|
|
!enabled? || trusted_ip?
|
|
|
|
end
|
|
|
|
|
|
|
|
def enabled?
|
|
|
|
config.enabled
|
|
|
|
end
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
def config
|
|
|
|
Gitlab.config.rack_attack.git_basic_auth
|
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2019-09-30 21:07:59 +05:30
|
|
|
def trusted_ips
|
|
|
|
strong_memoize(:trusted_ips) do
|
|
|
|
config.ip_whitelist.map do |proxy|
|
|
|
|
IPAddr.new(proxy)
|
|
|
|
rescue IPAddr::InvalidAddressError
|
|
|
|
end.compact
|
|
|
|
end
|
2016-06-16 23:09:34 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|