From 19f80c0a26c2c636dc1f29884deb914737c8b493 Mon Sep 17 00:00:00 2001 From: David O Neill Date: Fri, 2 Feb 2024 15:48:17 +0000 Subject: [PATCH] GH13983 - Add additional check for bad templates --- awx/main/models/notifications.py | 24 +++++++++++++++---- .../test/awx/test_notification_template.py | 2 +- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/awx/main/models/notifications.py b/awx/main/models/notifications.py index aa72f98293..77f8032ce5 100644 --- a/awx/main/models/notifications.py +++ b/awx/main/models/notifications.py @@ -5,6 +5,7 @@ from copy import deepcopy import datetime import logging import json +import traceback from django.db import models from django.conf import settings @@ -484,14 +485,29 @@ class JobNotificationMixin(object): if msg_template: try: msg = env.from_string(msg_template).render(**context) - except (TemplateSyntaxError, UndefinedError, SecurityError): - msg = '' + except (TemplateSyntaxError, UndefinedError, SecurityError) as e: + msg = '\r\n'.join([e.message, ''.join(traceback.format_exception(None, e, e.__traceback__).replace('\n', '\r\n'))]) if body_template: try: body = env.from_string(body_template).render(**context) - except (TemplateSyntaxError, UndefinedError, SecurityError): - body = '' + except (TemplateSyntaxError, UndefinedError, SecurityError) as e: + body = '\r\n'.join([e.message, ''.join(traceback.format_exception(None, e, e.__traceback__).replace('\n', '\r\n'))]) + + # https://datatracker.ietf.org/doc/html/rfc2822#section-2.2 + # Body should have at least 2 CRLF, some clients will interpret + # the email incorrectly with blank body. So we will check that + + if len(body.strip().splitlines()) <= 2: + # blank body + body = '\r\n'.join( + [ + "The template rendering return a blank body.", + "Please check the template.", + "Refer to https://github.com/ansible/awx/issues/13983", + "for further information.", + ] + ) return (msg, body) diff --git a/awx_collection/test/awx/test_notification_template.py b/awx_collection/test/awx/test_notification_template.py index 8bd2647b02..346ac41058 100644 --- a/awx_collection/test/awx/test_notification_template.py +++ b/awx_collection/test/awx/test_notification_template.py @@ -155,4 +155,4 @@ def test_build_notification_message_undefined(run_module, admin_user, organizati nt = NotificationTemplate.objects.get(id=result['id']) body = job.build_notification_message(nt, 'running') - assert '{"started_by": "My Placeholder"}' in body[1] + assert 'The template rendering return a blank body' in body[1]