diff --git a/openedx/core/lib/x_forwarded_for/middleware.py b/openedx/core/lib/x_forwarded_for/middleware.py index a45aed8bce22..9682f14bbe2d 100644 --- a/openedx/core/lib/x_forwarded_for/middleware.py +++ b/openedx/core/lib/x_forwarded_for/middleware.py @@ -48,6 +48,8 @@ def process_request(self, request): # Only used to support ip.legacy switch. request.META['ORIGINAL_REMOTE_ADDR'] = request.META['REMOTE_ADDR'] + safest_client_ip = ip.get_safest_client_ip(request) + try: # Give some observability into IP chain length and composition. Useful # for monitoring in case of unexpected network config changes, etc. @@ -66,6 +68,8 @@ def process_request(self, request): external_chain = ip.get_all_client_ips(request) set_custom_attribute('ip_chain.external.count', len(external_chain)) set_custom_attribute('ip_chain.external.types', '-'.join(_ip_type(s) for s in external_chain)) + + set_custom_attribute('ip_chain.safest_client_ip', safest_client_ip) except BaseException: warnings.warn('Error while computing IP chain metrics') @@ -107,4 +111,4 @@ def process_request(self, request): if legacy_ip.USE_LEGACY_IP.is_enabled(): request.META['REMOTE_ADDR'] = legacy_ip.get_legacy_ip(request) else: - request.META['REMOTE_ADDR'] = ip.get_safest_client_ip(request) + request.META['REMOTE_ADDR'] = safest_client_ip 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 cf5814b0ab24..f669e183a2ad 100644 --- a/openedx/core/lib/x_forwarded_for/tests/test_middleware.py +++ b/openedx/core/lib/x_forwarded_for/tests/test_middleware.py @@ -60,12 +60,20 @@ def test_overrides(self, add_meta, expected_meta_include): @ddt.unpack @ddt.data( - (None, '127.0.0.1', 1, 'priv'), - ('1.2.3.4', '1.2.3.4, 127.0.0.1', 2, 'pub-priv'), - ('XXXXXXXX, 1.2.3.4, 5.5.5.5', 'XXXXXXXX, 1.2.3.4, 5.5.5.5, 127.0.0.1', 4, 'unknown-pub-pub-priv'), + (None, '127.0.0.1', 1, 'priv', '127.0.0.1'), + ('1.2.3.4', '1.2.3.4, 127.0.0.1', 2, 'pub-priv', '1.2.3.4'), + ('XXXXXXXX, 1.2.3.4, 5.5.5.5', 'XXXXXXXX, 1.2.3.4, 5.5.5.5, 127.0.0.1', 4, 'unknown-pub-pub-priv', '5.5.5.5'), ) @patch("openedx.core.lib.x_forwarded_for.middleware.set_custom_attribute") - def test_xff_metrics(self, xff, expected_raw, expected_count, expected_types, mock_set_custom_attribute): + def test_xff_metrics( + self, + xff, + expected_raw, + expected_count, + expected_types, + expected_safest_client_ip, + mock_set_custom_attribute, + ): request = RequestFactory().get('/somewhere') if xff is not None: request.META['HTTP_X_FORWARDED_FOR'] = xff @@ -76,4 +84,5 @@ def test_xff_metrics(self, xff, expected_raw, expected_count, expected_types, mo call('ip_chain.raw', expected_raw), call('ip_chain.count', expected_count), call('ip_chain.types', expected_types), - ]) + call('ip_chain.safest_client_ip', expected_safest_client_ip), + ], any_order=True)