Module: CloudflareRails::CheckTrustedProxies

Defined in:
lib/cloudflare_rails/check_trusted_proxies.rb

Overview

patch rack::request::helpers to use our cloudflare ips - this way request.ip is correct inside of rack and rails

Instance Method Summary collapse

Instance Method Details

#cloudflare?Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cloudflare_rails/check_trusted_proxies.rb', line 18

def cloudflare?
  remote_addresses = split_header(get_header('REMOTE_ADDR'))
  forwarded_for = self.forwarded_for || []

  # Select only the trusted prefix of REMOTE_ADDR + X_HTTP_FORWARDED_FOR
  trusted_proxies = (remote_addresses + forwarded_for).take_while do |ip|
    trusted_proxy?(ip)
  end

  trusted_proxies.any? do |ip|
    cloudflare_ip?(ip)
  end
end

#cloudflare_ip?(ip) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
10
11
12
# File 'lib/cloudflare_rails/check_trusted_proxies.rb', line 7

def cloudflare_ip?(ip)
  Importer.cloudflare_ips.any? do |proxy|
    proxy === ip
  rescue IPAddr::InvalidAddressError
  end
end

#trusted_proxy?(ip) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/cloudflare_rails/check_trusted_proxies.rb', line 14

def trusted_proxy?(ip)
  cloudflare_ip?(ip) || super
end