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.
This commit is contained in:
Tim McCormack
2022-03-22 15:33:35 +00:00
committed by GitHub
parent 9b59b5e92a
commit 813b403575
2 changed files with 8 additions and 5 deletions

View File

@@ -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")]:

View File

@@ -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),
])