Skip to content

Saleor Core: the high performance, composable, headless commerce API.

No longer accept invalid IP addresses in core's get_client_ip

NyanKiyoshia8ab73b897a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c371f60942..8a96108971 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix MUI warnings - #4588 by @dominik-zeglen
- Disabled unneeded reports from uWSGI about broken pipe and write errors from disconnected clients. Preventing from spamming sentry users. - #4596 by @NyanKiyoshi
- Upgraded to django 2.2.4 - #4603 by @NyanKiyoshi
+- Invalid IP address in HTTP requests now fallback to the requester's IP address. - #4597 by @NyanKiyoshi
## 2.8.0
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 75bab72734..61ddb96d53 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -1,5 +1,6 @@
import decimal
import logging
+import socket
from json import JSONEncoder
from urllib.parse import urljoin
@@ -51,10 +52,38 @@ def build_absolute_uri(location):
return iri_to_uri(location)
+def is_valid_ipv4(ip: str) -> bool:
+ """Check whether the passed IP is a valid V4 IP address."""
+ try:
+ socket.inet_pton(socket.AF_INET, ip)
+ except socket.error:
+ return False
+ return True
+
+
+def is_valid_ipv6(ip: str) -> bool:
+ """Check whether the passed IP is a valid V6 IP address."""
+ try:
+ socket.inet_pton(socket.AF_INET6, ip)
+ except socket.error:
+ return False
+ return True
+
+
def get_client_ip(request):
- ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
- if ip:
- return ip.split(",")[0].strip()
+ """Retrieve the IP address from the request data.
+
+ Tries to get a valid IP address from X-Forwarded-For, if the user is hiding behind
+ a transparent proxy or if the server is behind a proxy.
+
+ If no forwarded IP was provided or all of them are invalid,
+ it fallback to the requester IP.
+ """
+ ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
+ ips = ip.split(",")
+ for ip in ips:
+ if is_valid_ipv4(ip) or is_valid_ipv6(ip):
+ return ip
return request.META.get("REMOTE_ADDR", None)
diff --git a/tests/test_core.py b/tests/test_core.py
index 8240bdc914..818a232eda 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -6,7 +6,7 @@ from urllib.parse import urljoin
import pytest
from django.shortcuts import reverse
from django.templatetags.static import static
-from django.test import Client, override_settings
+from django.test import Client, RequestFactory, override_settings
from django.urls import translate_url
from measurement.measures import Weight
from prices import Money
@@ -19,6 +19,7 @@ from saleor.core.utils import (
create_superuser,
create_thumbnails,
format_money,
+ get_client_ip,
get_country_by_ip,
get_country_name_by_code,
get_currency_for_country,
@@ -67,6 +68,27 @@ def test_get_country_by_ip(ip_data, expected_country, monkeypatch):
assert country == expected_country
+ "ip_address, expected_ip",
+ [
+ ("83.0.0.1", "83.0.0.1"),
+ ("::1", "::1"),
+ ("256.0.0.1", "127.0.0.1"),
+ ("1:1:1", "127.0.0.1"),
+ ("invalid,8.8.8.8", "8.8.8.8"),
+ (None, "127.0.0.1"),
+ ],
+)
+def test_get_client_ip(ip_address, expected_ip):
+ """Test providing a valid IP in X-Forwarded-For returns the valid IP.
+ Otherwise, if no valid IP were found, returns the requester's IP.
+ """
+ expected_ip = expected_ip
+ headers = {"HTTP_X_FORWARDED_FOR": ip_address} if ip_address else {}
+ request = RequestFactory(**headers).get("/")
+ assert get_client_ip(request) == expected_ip
+
+
@pytest.mark.parametrize(
"country, expected_currency",
[(Country("PL"), "PLN"), (Country("US"), "USD"), (Country("GB"), "GBP")],