trusted_proxies.rb 1.18 KB
Newer Older
1 2 3 4
# Override Rack::Request to make use of the same list of trusted_proxies
# as the ActionDispatch::Request object. This is necessary for libraries
# like rack_attack where they don't use ActionDispatch, and we want them
# to block/throttle requests on private networks.
5
# Rack Attack specific issue: https://github.com/kickstarter/rack-attack/issues/145
6 7 8 9
module Rack
  class Request
    def trusted_proxy?(ip)
      Rails.application.config.action_dispatch.trusted_proxies.any? { |proxy| proxy === ip }
10 11
    rescue IPAddr::InvalidAddressError
      false
12 13 14 15
    end
  end
end

16
gitlab_trusted_proxies = Array(Gitlab.config.gitlab.trusted_proxies).map do |proxy|
Nick Thomas's avatar
Nick Thomas committed
17 18
  IPAddr.new(proxy)
rescue IPAddr::InvalidAddressError
19 20
end.compact

21
Rails.application.config.action_dispatch.trusted_proxies = (
22
  ['127.0.0.1', '::1'] + gitlab_trusted_proxies)
blackst0ne's avatar
blackst0ne committed
23 24 25 26

# A monkey patch to make trusted proxies work with Rails 5.0.
# Inspired by https://github.com/rails/rails/issues/5223#issuecomment-263778719
# Remove this monkey patch when upstream is fixed.
27 28 29
module TrustedProxyMonkeyPatch
  def ip
    @ip ||= (get_header("action_dispatch.remote_ip") || super).to_s
blackst0ne's avatar
blackst0ne committed
30 31
  end
end
32 33

ActionDispatch::Request.send(:include, TrustedProxyMonkeyPatch)