From 813b403575a1c50fe2af657c69f4c7c885e55439 Mon Sep 17 00:00:00 2001 From: Tim McCormack Date: Tue, 22 Mar 2022 15:33:35 +0000 Subject: [PATCH] fix: Use more accurate attr name for IP chain size (#30106) XFF is just part of the chain; record the length of the whole chain instead (which is always one larger). Also include junk in one of the test values for realism. --- openedx/core/lib/x_forwarded_for/middleware.py | 3 ++- .../core/lib/x_forwarded_for/tests/test_middleware.py | 10 ++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/openedx/core/lib/x_forwarded_for/middleware.py b/openedx/core/lib/x_forwarded_for/middleware.py index 7d4447a8af..162a6e3d21 100644 --- a/openedx/core/lib/x_forwarded_for/middleware.py +++ b/openedx/core/lib/x_forwarded_for/middleware.py @@ -25,7 +25,8 @@ class XForwardedForMiddleware(MiddlewareMixin): # for monitoring in case of unexpected changes, etc. xff = request.META.get('HTTP_X_FORWARDED_FOR') xff_len = xff.count(',') + 1 if xff else 0 - set_custom_attribute('header.x-forwarded-for.count', xff_len) + # IP chain is XFF + REMOTE_ADDR + set_custom_attribute('ip_chain.count', xff_len + 1) for field, header in [("HTTP_X_FORWARDED_FOR", "REMOTE_ADDR"), ("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_FORWARDED_PORT", "SERVER_PORT")]: diff --git a/openedx/core/lib/x_forwarded_for/tests/test_middleware.py b/openedx/core/lib/x_forwarded_for/tests/test_middleware.py index 52d1489eb6..8fceb2dc5a 100644 --- a/openedx/core/lib/x_forwarded_for/tests/test_middleware.py +++ b/openedx/core/lib/x_forwarded_for/tests/test_middleware.py @@ -60,9 +60,9 @@ class TestXForwardedForMiddleware(TestCase): @ddt.unpack @ddt.data( - (None, 0), - ('1.2.3.4', 1), - ('7.8.9.0, 1.2.3.4, 5.5.5.5', 3), + (None, 1), + ('1.2.3.4', 2), + ('XXXXXXXX, 1.2.3.4, 5.5.5.5', 4), ) @patch("openedx.core.lib.x_forwarded_for.middleware.set_custom_attribute") def test_xff_metrics(self, xff, expected_count, mock_set_custom_attribute): @@ -72,4 +72,6 @@ class TestXForwardedForMiddleware(TestCase): XForwardedForMiddleware().process_request(request) - mock_set_custom_attribute.assert_has_calls([call('header.x-forwarded-for.count', expected_count)]) + mock_set_custom_attribute.assert_has_calls([ + call('ip_chain.count', expected_count), + ])