Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
webhooks: Move the extra logging information into a formatter.
Alex Vandiver3f6e4ff30353
diff --git a/zerver/decorator.py b/zerver/decorator.pyindex b49092cb20a..b76beae8708 100644--- a/zerver/decorator.py+++ b/zerver/decorator.py@@ -7,7 +7,6 @@ from io import BytesIOfrom typing import Callable, Dict, Optional, Tuple, TypeVar, Union, castimport django_otp-import orjsonfrom django.conf import settingsfrom django.contrib.auth import REDIRECT_FIELD_NAMEfrom django.contrib.auth import login as django_login@@ -259,57 +258,13 @@ def access_user_by_api_key(request: HttpRequest, api_key: str, email: Optional[sreturn user_profiledef log_exception_to_webhook_logger(- request: HttpRequest,summary: str,unsupported_event: bool,) -> None:- if request.content_type == 'application/json':- payload = request.body- else:- payload = request.POST.get('payload')-- try:- payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode()- except orjson.JSONDecodeError:- pass-- custom_header_template = "{header}: {value}\n"-- header_text = ""- for header in request.META.keys():- if header.lower().startswith('http_x'):- header_text += custom_header_template.format(- header=header, value=request.META[header])-- header_message = header_text if header_text else None-- message = """-summary: {summary}-user: {email} ({realm})-client: {client_name}-URL: {path_info}-content_type: {content_type}-custom_http_headers:-{custom_headers}-body:--{body}- """.format(- summary=summary,- email=request.user.delivery_email,- realm=request.user.realm.string_id,- client_name=request.client.name,- body=payload,- path_info=request.META.get('PATH_INFO', None),- content_type=request.content_type,- custom_headers=header_message,- )- message = message.strip(' ')-if unsupported_event:- webhook_unsupported_events_logger.exception(message, stack_info=True)+ webhook_unsupported_events_logger.exception(summary, stack_info=True)else:- webhook_logger.exception(message, stack_info=True)+ webhook_logger.exception(summary, stack_info=True)def full_webhook_client_name(raw_client_name: Optional[str]=None) -> Optional[str]:if raw_client_name is None:@@ -348,7 +303,6 @@ def webhook_view(if isinstance(err, UnsupportedWebhookEventType):err.webhook_name = webhook_client_namelog_exception_to_webhook_logger(- request=request,summary=str(err),unsupported_event=isinstance(err, UnsupportedWebhookEventType),)@@ -599,7 +553,6 @@ def authenticated_rest_api_view(request_body = request.POST.get('payload')if request_body is not None:log_exception_to_webhook_logger(- request=request,summary=str(err),unsupported_event=isinstance(err, UnsupportedWebhookEventType),)diff --git a/zerver/lib/logging_util.py b/zerver/lib/logging_util.pyindex 187840885c5..b4d669b708f 100644--- a/zerver/lib/logging_util.py+++ b/zerver/lib/logging_util.py@@ -7,6 +7,7 @@ from datetime import datetime, timedelta, timezonefrom logging import Loggerfrom typing import Optional, Tuple+import orjsonfrom django.conf import settingsfrom django.core.cache import cachefrom django.utils.timezone import now as timezone_now@@ -210,6 +211,62 @@ class ZulipFormatter(logging.Formatter):setattr(record, 'zulip_decorated', True)return super().format(record)+class ZulipWebhookFormatter(ZulipFormatter):+ def _compute_fmt(self) -> str:+ basic = super()._compute_fmt()+ multiline = [+ basic,+ "user: %(user)s",+ "client: %(client)s",+ "url: %(url)s",+ "content_type: %(content_type)s",+ "custom_headers:",+ "%(custom_headers)s",+ "payload:",+ "%(payload)s",+ ]+ return "\n".join(multiline)++ def format(self, record: logging.LogRecord) -> str:+ from zerver.lib.request import get_current_request+ request = get_current_request()+ if not request:+ setattr(record, 'user', None)+ setattr(record, 'client', None)+ setattr(record, 'url', None)+ setattr(record, 'content_type', None)+ setattr(record, 'custom_headers', None)+ setattr(record, 'payload', None)+ return super().format(record)++ if request.content_type == 'application/json':+ payload = request.body+ else:+ payload = request.POST.get('payload')++ try:+ payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode()+ except orjson.JSONDecodeError:+ pass++ custom_header_template = "{header}: {value}\n"++ header_text = ""+ for header in request.META.keys():+ if header.lower().startswith('http_x'):+ header_text += custom_header_template.format(+ header=header, value=request.META[header])++ header_message = header_text if header_text else None++ setattr(record, 'user', f"{request.user.delivery_email} (request.user.realm.string_id)")+ setattr(record, 'client', request.client.name)+ setattr(record, 'url', request.META.get('PATH_INFO', None))+ setattr(record, 'content_type', request.content_type)+ setattr(record, 'custom_headers', header_message)+ setattr(record, 'payload', payload)+ return super().format(record)+def log_to_file(logger: Logger,filename: str,log_format: str="%(asctime)s %(levelname)-8s %(message)s",diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.pyindex 8034db2067c..0d6cda0438f 100644--- a/zerver/tests/test_decorators.py+++ b/zerver/tests/test_decorators.py@@ -277,7 +277,6 @@ class DecoratorTestCase(ZulipTestCase):webhook_bot_realm = get_realm('zulip')webhook_bot = get_user(webhook_bot_email, webhook_bot_realm)webhook_bot_api_key = get_api_key(webhook_bot)- webhook_client_name = "ZulipClientNameWebhook"request = HostRequestMock()request.POST['api_key'] = 'X'*32@@ -337,29 +336,7 @@ class DecoratorTestCase(ZulipTestCase):request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value'my_webhook_raises_exception(request)- message = """-summary: {summary}-user: {email} ({realm})-client: {client_name}-URL: {path_info}-content_type: {content_type}-custom_http_headers:-{custom_headers}-body:--{body}- """- message = message.strip(' ')- mock_exception.assert_called_with(message.format(- summary="raised by webhook function",- email=webhook_bot_email,- realm=webhook_bot_realm.string_id,- client_name=webhook_client_name,- path_info=request.META.get('PATH_INFO'),- content_type=request.content_type,- custom_headers="HTTP_X_CUSTOM_HEADER: custom_value\n",- body=request.body,- ), stack_info=True)+ mock_exception.assert_called_with("raised by webhook function", stack_info=True)# Test when an unsupported webhook event occurswith mock.patch('zerver.decorator.webhook_unsupported_events_logger.exception') as mock_exception:@@ -370,29 +347,7 @@ body:request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value'my_webhook_raises_exception_unsupported_event(request)- message = """-summary: {summary}-user: {email} ({realm})-client: {client_name}-URL: {path_info}-content_type: {content_type}-custom_http_headers:-{custom_headers}-body:--{body}- """- message = message.strip(' ')- mock_exception.assert_called_with(message.format(- summary=exception_msg,- email=webhook_bot_email,- realm=webhook_bot_realm.string_id,- client_name=webhook_client_name,- path_info=request.META.get('PATH_INFO'),- content_type=request.content_type,- custom_headers="HTTP_X_CUSTOM_HEADER: custom_value\n",- body=request.body,- ), stack_info=True)+ mock_exception.assert_called_with(exception_msg, stack_info=True)with self.settings(RATE_LIMITING=True):with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock:@@ -501,7 +456,6 @@ class DecoratorLoggingTestCase(ZulipTestCase):raise Exception("raised by webhook function")webhook_bot_email = '[email protected]'- webhook_bot_realm = get_realm('zulip')request = HostRequestMock()request.META['HTTP_AUTHORIZATION'] = self.encode_email(webhook_bot_email)@@ -516,29 +470,7 @@ class DecoratorLoggingTestCase(ZulipTestCase):with self.assertRaisesRegex(Exception, "raised by webhook function"):my_webhook_raises_exception(request)- message = """-summary: {summary}-user: {email} ({realm})-client: {client_name}-URL: {path_info}-content_type: {content_type}-custom_http_headers:-{custom_headers}-body:--{body}- """- message = message.strip(' ')- mock_exception.assert_called_with(message.format(- summary="raised by webhook function",- email=webhook_bot_email,- realm=webhook_bot_realm.string_id,- client_name='ZulipClientNameWebhook',- path_info=request.META.get('PATH_INFO'),- content_type=request.content_type,- custom_headers=None,- body=request.body,- ), stack_info=True)+ mock_exception.assert_called_with("raised by webhook function", stack_info=True)def test_authenticated_rest_api_view_logging_unsupported_event(self) -> None:@authenticated_rest_api_view(webhook_client_name="ClientName")@@ -546,7 +478,6 @@ body:raise UnsupportedWebhookEventType("test_event")webhook_bot_email = '[email protected]'- webhook_bot_realm = get_realm('zulip')request = HostRequestMock()request.META['HTTP_AUTHORIZATION'] = self.encode_email(webhook_bot_email)@@ -562,29 +493,7 @@ body:with self.assertRaisesRegex(UnsupportedWebhookEventType, exception_msg):my_webhook_raises_exception(request)- message = """-summary: {summary}-user: {email} ({realm})-client: {client_name}-URL: {path_info}-content_type: {content_type}-custom_http_headers:-{custom_headers}-body:--{body}- """- message = message.strip(' ')- mock_exception.assert_called_with(message.format(- summary=exception_msg,- email=webhook_bot_email,- realm=webhook_bot_realm.string_id,- client_name='ZulipClientNameWebhook',- path_info=request.META.get('PATH_INFO'),- content_type=request.content_type,- custom_headers=None,- body=request.body,- ), stack_info=True)+ mock_exception.assert_called_with(exception_msg, stack_info=True)def test_authenticated_rest_api_view_with_non_webhook_view(self) -> None:@authenticated_rest_api_view()diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.pyindex 5bd95f08ed9..132e6ff5076 100644--- a/zerver/webhooks/github/tests.py+++ b/zerver/webhooks/github/tests.py@@ -461,9 +461,8 @@ A temporary team so that I can get some webhook fixtures!msg = m.call_args[0][0]stack_info = m.call_args[1]["stack_info"]- self.assertIn("content_type: application/json", msg)self.assertIn(- "summary: The 'team/edited (changes: bogus_key1/bogus_key2)' event isn't currently supported by the GitHub webhook",+ "The 'team/edited (changes: bogus_key1/bogus_key2)' event isn't currently supported by the GitHub webhook",msg,)self.assertTrue(stack_info)diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.pyindex bc654558117..62664ac7a37 100644--- a/zerver/webhooks/github/view.py+++ b/zerver/webhooks/github/view.py@@ -32,19 +32,15 @@ fixture_to_headers = get_http_headers_from_filename("HTTP_X_GITHUB_EVENT")class Helper:def __init__(self,- request: HttpRequest,payload: Dict[str, Any],include_title: bool,) -> None:self.payload = payloadself.include_title = include_title- self._request = requestdef log_unsupported(self, event: str) -> None:summary = f"The '{event}' event isn't currently supported by the GitHub webhook"- request = self._requestlog_exception_to_webhook_logger(- request=request,summary=summary,unsupported_event=True,)@@ -630,7 +626,6 @@ def api_github_webhook(body_function = EVENT_FUNCTION_MAPPER[event]helper = Helper(- request=request,payload=payload,include_title=user_specified_topic is not None,)diff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex 2409066c808..76dc85af14f 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -716,6 +716,9 @@ LOGGING: Dict[str, Any] = {'default': {'()': 'zerver.lib.logging_util.ZulipFormatter',},+ 'webhook_request_data': {+ '()': 'zerver.lib.logging_util.ZulipWebhookFormatter',+ },},'filters': {'ZulipLimiter': {@@ -794,13 +797,13 @@ LOGGING: Dict[str, Any] = {'webhook_file': {'level': 'DEBUG','class': 'logging.handlers.WatchedFileHandler',- 'formatter': 'default',+ 'formatter': 'webhook_request_data','filename': WEBHOOK_LOG_PATH,},'webhook_unsupported_file': {'level': 'DEBUG','class': 'logging.handlers.WatchedFileHandler',- 'formatter': 'default',+ 'formatter': 'webhook_request_data','filename': WEBHOOK_UNSUPPORTED_EVENTS_LOG_PATH,},},