Skip to content

Instantly share code, notes, and snippets.

@mrk21
Created August 31, 2019 10:07
Show Gist options
  • Select an option

  • Save mrk21/f25b22528d69d0cfdd2426e8470a8ee6 to your computer and use it in GitHub Desktop.

Select an option

Save mrk21/f25b22528d69d0cfdd2426e8470a8ee6 to your computer and use it in GitHub Desktop.

Revisions

  1. mrk21 created this gist Aug 31, 2019.
    12 changes: 12 additions & 0 deletions config-initializers-trusted_proxies.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    # @see https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html
    # @see https://morizyun.github.io/ruby/rails-controller-get-ip.html
    # @see https://dev.classmethod.jp/cloud/aws/get-ec2-public-ip-range-by-powershell/
    # @see https://github.com/rails/rails/blob/c81af6a/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L112-L150
    Rails.application.configure do
    ip_ranges_res = Faraday.get('https://ip-ranges.amazonaws.com/ip-ranges.json')
    ip_ranges = JSON.parse(ip_ranges_res.body)
    cloudfront_ips = ip_ranges['prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ip_prefix']) } +
    ip_ranges['ipv6_prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ipv6_prefix']) }

    config.action_dispatch.trusted_proxies = cloudfront_ips
    end