Last active
October 24, 2017 06:41
-
-
Save mattheworiordan/9024372 to your computer and use it in GitHub Desktop.
Cloudflare Middleware for Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# insert within your Application | |
config.middleware.insert_before(0, Rack::CloudFlareFixup) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# CloudFlare masks the true IP | |
# This middleware ensures the Rails stack obtains the correct IP when using request.remote_ip | |
# See https://support.cloudflare.com/hc/en-us/articles/200170786 | |
module Rack | |
class CloudFlareFixup | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
if env['HTTP_CF_CONNECTING_IP'] | |
env['HTTP_X_FORWARDED_FOR'] = env['HTTP_CF_CONNECTING_IP'] | |
env['REMOTE_ADDR'] = env['HTTP_CF_CONNECTING_IP'] | |
end | |
@app.call(env) | |
end | |
end | |
end |
I've been working to solve this same problem. I wrapped my rack middleware solution into the remote_ip_proxy_scrubber gem.
My gem's weakness is that it relies on your app maintaining an up-to-date list of current CloudFlare IPs.
My gem's benefits are that it prevents IP spoofing even if part of your app's traffic is not passing through CloudFlare (with your middleware, a request that bypasses CloudFlare could spoof its IP by setting the CF_CONNECTING_IP
header). My gem also includes a patched version of Rails::Rack::Logger
so that your Rails logs show the client's remote_ip
address.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See his newer gist:
https://gist.github.com/mattheworiordan/9828493