feat: add ip_chain.safest_client_ip to emitted XForwardedForMiddleware metrics (#33720)

This commit adds the result of get_safest_client_ip() to the emitted metrics of
XForwardedForMiddleware.
This commit is contained in:
Phillip Shiu
2023-11-15 19:13:32 -03:00
committed by GitHub
parent dcd6786112
commit 94658f5890
2 changed files with 19 additions and 6 deletions

View File

@@ -48,6 +48,8 @@ class XForwardedForMiddleware(MiddlewareMixin):
# 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 @@ class XForwardedForMiddleware(MiddlewareMixin):
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 @@ class XForwardedForMiddleware(MiddlewareMixin):
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

View File

@@ -60,12 +60,20 @@ class TestXForwardedForMiddleware(TestCase):
@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 @@ class TestXForwardedForMiddleware(TestCase):
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)