feat: add monitoring for users across requests (#30795)

We already add the user id (imperfectly) to many requests.
However, when a user starts off unauthenticated, it is not
possible to correlate to those requests. Adding the raw
IP chain provides that possibility. See new custom attribute
ip_chain.raw.
This commit is contained in:
Robert Raposa
2022-07-28 13:45:34 -04:00
committed by GitHub
parent cd18f48ad7
commit 2af65d1b77
2 changed files with 11 additions and 4 deletions

View File

@@ -51,6 +51,12 @@ class XForwardedForMiddleware(MiddlewareMixin):
# Give some observability into IP chain length and composition. Useful
# for monitoring in case of unexpected network config changes, etc.
ip_chain = ip.get_raw_ip_chain(request)
# .. custom_attribute_name: ip_chain.raw
# .. custom_attribute_description: The actual contents of the raw IP chain. Could
# be used to correlate authenticated and unauthenticated requests for the same
# user.
set_custom_attribute('ip_chain.raw', ', '.join(ip_chain))
set_custom_attribute('ip_chain.count', len(ip_chain))
set_custom_attribute('ip_chain.types', '-'.join(_ip_type(s) for s in ip_chain))

View File

@@ -60,12 +60,12 @@ class TestXForwardedForMiddleware(TestCase):
@ddt.unpack
@ddt.data(
(None, 1, 'priv'),
('1.2.3.4', 2, 'pub-priv'),
('XXXXXXXX, 1.2.3.4, 5.5.5.5', 4, 'unknown-pub-pub-priv'),
(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'),
)
@patch("openedx.core.lib.x_forwarded_for.middleware.set_custom_attribute")
def test_xff_metrics(self, xff, expected_count, expected_types, mock_set_custom_attribute):
def test_xff_metrics(self, xff, expected_raw, expected_count, expected_types, mock_set_custom_attribute):
request = RequestFactory().get('/somewhere')
if xff is not None:
request.META['HTTP_X_FORWARDED_FOR'] = xff
@@ -73,6 +73,7 @@ class TestXForwardedForMiddleware(TestCase):
XForwardedForMiddleware().process_request(request)
mock_set_custom_attribute.assert_has_calls([
call('ip_chain.raw', expected_raw),
call('ip_chain.count', expected_count),
call('ip_chain.types', expected_types),
])