Skip to content

Commit

Permalink
fix: added parsing for IPv6 x-forwarded-for headers
Browse files Browse the repository at this point in the history
  • Loading branch information
aqeelat committed Nov 21, 2022
1 parent e23b091 commit c552192
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
19 changes: 13 additions & 6 deletions auditlog/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,21 @@ def __init__(self, get_response=None):

@staticmethod
def _get_remote_addr(request):
if request.headers.get("X-Forwarded-For"):
# In case of proxy, set 'original' address
remote_addr = request.headers.get("X-Forwarded-For").split(",")[0]
# Remove port number from remote_addr
return remote_addr.split(":")[0]
else:
# In case there is no proxy, return the original address
if not request.headers.get("X-Forwarded-For"):
return request.META.get("REMOTE_ADDR")

# In case of proxy, set 'original' address
remote_addr: str = request.headers.get("X-Forwarded-For").split(",")[0]

# Remove port number from remote_addr
if "." in remote_addr and ":" in remote_addr: # IPv4 with port (`x.x.x.x:x`)
remote_addr = remote_addr.split(":")[0]
elif "[" in remote_addr: # IPv6 with port (`[:::]:x`)
remote_addr = remote_addr[1:].split("]")[0]

return remote_addr

def __call__(self, request):
remote_addr = self._get_remote_addr(request)

Expand Down
5 changes: 5 additions & 0 deletions auditlog_tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,11 @@ def test_get_remote_addr(self):
({}, "127.0.0.1"),
({"HTTP_X_FORWARDED_FOR": "127.0.0.2"}, "127.0.0.2"),
({"HTTP_X_FORWARDED_FOR": "127.0.0.3:1234"}, "127.0.0.3"),
({"HTTP_X_FORWARDED_FOR": "2606:4700:4700::1111"}, "2606:4700:4700::1111"),
(
{"HTTP_X_FORWARDED_FOR": "[2606:4700:4700::1001]:1234"},
"2606:4700:4700::1001",
),
]
for headers, expected_remote_addr in tests:
with self.subTest(headers=headers):
Expand Down

0 comments on commit c552192

Please sign in to comment.