Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IPv6 in X-Forwarded-For fix #6062

Merged
merged 2 commits into from Aug 9, 2019
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

@@ -34,13 +34,19 @@ def test_anonymize_ua(self):
)

def test_get_client_ip_with_x_forwarded_for(self):

# only client's ip is present
request = RequestFactory().get('/')
request.META['HTTP_X_FORWARDED_FOR'] = '203.0.113.195'
client_ip = get_client_ip(request)
self.assertEqual(client_ip, '203.0.113.195')

# only client's ip is present
request = RequestFactory().get('/')
ip = '2001:abc:def:012:345:6789:abcd:ef12'

This comment has been minimized.

Copy link
@dojutsu-user

dojutsu-user Aug 9, 2019

Member

Where did you get the sample ip?

This comment has been minimized.

Copy link
@davidfischer

davidfischer Aug 9, 2019

Author Contributor

I just created it. You can always test if it's a valid IP (it is) with the ipaddress module.

request.META['HTTP_X_FORWARDED_FOR'] = ip
client_ip = get_client_ip(request)
self.assertEqual(client_ip, ip)

# proxy1 and proxy2 are present along with client's ip
request = RequestFactory().get('/')
request.META['HTTP_X_FORWARDED_FOR'] = '203.0.113.195, 70.41.3.18, 150.172.238.178'
@@ -53,6 +59,14 @@ def test_get_client_ip_with_x_forwarded_for(self):
client_ip = get_client_ip(request)
self.assertEqual(client_ip, '203.0.113.195')

# client ip (ipv6), other clients with port
request = RequestFactory().get('/')
ip = '2001:abc:def:012:345:6789:abcd:ef12'
x_forwarded_for = f'{ip}, 203.0.113.195:8080, 70.41.3.18'
request.META['HTTP_X_FORWARDED_FOR'] = x_forwarded_for
client_ip = get_client_ip(request)
self.assertEqual(client_ip, ip)

# client ip with port but not proxy1 and proxy2
request = RequestFactory().get('/')
request.META['HTTP_X_FORWARDED_FOR'] = '203.0.113.195:8080'
@@ -32,7 +32,9 @@ def get_client_ip(request):
client_ip = x_forwarded_for.split(',')[0].strip()

# Removing the port number (if present)
client_ip = client_ip.rsplit(':')[0]
# But be careful about IPv6 addresses
if client_ip.count(':') == 1:
client_ip = client_ip.rsplit(':', maxsplit=1)[0]
else:
client_ip = request.META.get('REMOTE_ADDR', None)

ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.