Browse files

moved the trusted_proxy regex into a separate method to allow overrid…

…ing, added ipv6 loopback and private address ranges to the default regex

Signed-off-by: Konstantin Haase <konstantin.mailinglists@googlemail.com>
  • Loading branch information...
1 parent 250cde1 commit a9fae37b92085d17fdd9cddd9ac670acc3437e5b @martoche martoche committed with rkh Jun 20, 2011
Showing with 18 additions and 6 deletions.
  1. +6 −6 lib/rack/request.rb
  2. +12 −0 test/spec_request.rb
View
12 lib/rack/request.rb
@@ -305,13 +305,13 @@ def accept_encoding
end
end
+ def trusted_proxy?(ip)
+ ip =~ /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|^::1$|^fd[0-9a-f]{2}:.+/i
+ end
+
def ip
- # Copied from https://github.com/rails/rails/blob/master/actionpack/lib/
- # action_dispatch/middleware/remote_ip.rb
- trusted_proxies = /(^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.)/i
-
remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
- remote_addrs.reject! { |addr| addr =~ trusted_proxies }
+ remote_addrs.reject! { |addr| trusted_proxy?(addr) }
return remote_addrs.first if remote_addrs.any?
@@ -323,7 +323,7 @@ def ip
return client_ip if forwarded_ips.include?(client_ip)
end
- return forwarded_ips.reject { |ip| ip =~ trusted_proxies }.last || @env["REMOTE_ADDR"]
+ return forwarded_ips.reject { |ip| trusted_proxy?(ip) }.last || @env["REMOTE_ADDR"]
end
protected
View
12 test/spec_request.rb
@@ -811,6 +811,18 @@
res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4'
res.body.should.equal '3.4.5.6'
+ res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '::1,2620:0:1c00:0:812c:9583:754b:ca11'
+ res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'
+
+ res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,::1'
+ res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'
+
+ res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'fd5b:982e:9130:247f:0000:0000:0000:0000,2620:0:1c00:0:812c:9583:754b:ca11'
+ res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'
+
+ res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,fd5b:982e:9130:247f:0000:0000:0000:0000'
+ res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'
+
res = mock.get '/',
'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 127.0.0.1',
'HTTP_CLIENT_IP' => '1.1.1.1'

0 comments on commit a9fae37

Please sign in to comment.