From 60fe851301c0c1287641f6aa1a5970ac0b0a17d2 Mon Sep 17 00:00:00 2001 From: Romain Aviolat Date: Fri, 28 Aug 2020 20:44:51 +0200 Subject: [PATCH] jira: improve comments / webhook robustness Goal of this commit is to make the DDJ<->Jira comments mechanism more robust. Some notable changes that have been introduced with this commit: 1. Tracking of Jira comments IDs inside DDJ notes: To better handle loops a new field "jira_id" was added to DDJ notes so every time a new note is created, either from the UI or the API, the jira comment reference will be stored inside the DDJ note. 2. Better handling of comments loops: With the help of point 1 we can now properly track webhooks received from Jira. 3. Better control of comments creation date: We're now using the Jira comment creation time-stamp when storing a note coming from Jira inside a DDJ note, this way we avoid out-of-order messages inside DDJ notes. Also in case of issues between Jira and the DDJ webhook endpoint (network outage, ...) Jira will always retry later to resend comments that have not been posted, this way we ensure that the note creation time-stamp is always correct. 4. Better error handling: A couple of try/except were added to catch common errors, previously DDJ was stack-tracing on some function for example if some optional fields were not present in the POST of an API_V2 call. --- dojo/api_v2/views.py | 24 +++++++++++--- dojo/db_migrations/0051_notes_jira_id.py | 18 ++++++++++ dojo/jira_link/views.py | 42 ++++++++++++++---------- dojo/models.py | 1 + dojo/utils.py | 4 ++- 5 files changed, 65 insertions(+), 24 deletions(-) create mode 100644 dojo/db_migrations/0051_notes_jira_id.py diff --git a/dojo/api_v2/views.py b/dojo/api_v2/views.py index 1b7193536e5..2bd7c7663c7 100644 --- a/dojo/api_v2/views.py +++ b/dojo/api_v2/views.py @@ -1,3 +1,6 @@ +# Standard library imports +import logging + from django.http import HttpResponse, Http404 from django.shortcuts import get_object_or_404 from django.utils import timezone @@ -28,6 +31,7 @@ from dojo.api_v2 import serializers, permissions from django.db.models import Count, Q +logger = logging.getLogger(__name__) class EndPointViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, @@ -275,23 +279,33 @@ def tags(self, request, pk=None): def notes(self, request, pk=None): finding = get_object_or_404(Finding.objects, id=pk) if request.method == 'POST': + note_type = None + jira_id = -1 new_note = serializers.AddNewNoteOptionSerializer(data=request.data) if new_note.is_valid(): - entry = new_note.validated_data['entry'] - private = new_note.validated_data['private'] - note_type = new_note.validated_data['note_type'] + try: + entry = new_note.validated_data['entry'] + private = new_note.validated_data['private'] + if 'note_type' in request.data: + note_type = request.data['note_type'] + if 'jira_id' in request.data: + jira_id = request.data['jira_id'] + except Exception as e: + logger.error(e) + return Response(new_note.errors, + status=status.HTTP_400_BAD_REQUEST) else: return Response(new_note.errors, status=status.HTTP_400_BAD_REQUEST) author = request.user - note = Notes(entry=entry, author=author, private=private, note_type=note_type) + note = Notes(entry=entry, author=author, private=private, note_type=note_type, jira_id=jira_id) note.save() finding.notes.add(note) serialized_note = serializers.NoteSerializer({ "author": author, "entry": entry, - "private": private + "private": private, "jira_id": note.jira_id }) result = serializers.FindingToNotesSerializer({ "finding_id": finding, "notes": [serialized_note.data] diff --git a/dojo/db_migrations/0051_notes_jira_id.py b/dojo/db_migrations/0051_notes_jira_id.py new file mode 100644 index 00000000000..5efd843f530 --- /dev/null +++ b/dojo/db_migrations/0051_notes_jira_id.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.15 on 2020-08-31 20:36 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dojo', '0050_deduplication_on_engagement'), + ] + + operations = [ + migrations.AddField( + model_name='notes', + name='jira_id', + field=models.IntegerField(blank=True, null=True), + ), + ] diff --git a/dojo/jira_link/views.py b/dojo/jira_link/views.py index cbd1d97f92d..5c1baf7f406 100644 --- a/dojo/jira_link/views.py +++ b/dojo/jira_link/views.py @@ -91,24 +91,30 @@ def webhook(request): eng.save() """ if parsed.get('webhookEvent') == 'comment_created': - comment_text = parsed['comment']['body'] - commentor = parsed['comment']['updateAuthor']['displayName'] - jid = parsed['comment']['self'].split('/')[7] - jissue = JIRA_Issue.objects.get(jira_id=jid) - jira = JIRA_Conf.objects.values_list('username', flat=True) - for jira_userid in jira: - if jira_userid.lower() in commentor.lower(): - return HttpResponse('') - break - finding = jissue.finding - new_note = Notes() - new_note.entry = '(%s): %s' % (commentor, comment_text) - new_note.author, created = User.objects.get_or_create(username='JIRA') - new_note.save() - finding.notes.add(new_note) - finding.jira_change = timezone.now() - finding.save() - create_notification(event='other', title='JIRA Update - %s' % (jissue.finding), url=reverse("view_finding", args=(jissue.id,)), icon='check') + # Only create a note if it doesn't exist locally (to avoid loops). + jira_note_creation_date = datetime.strptime(str(parsed['comment']['created']), "%Y-%m-%dT%H:%M:%S.%f%z") + try: + note = Notes.objects.get(jira_id=parsed['comment']['id']) + logger.info('Note already created from DefectDojo, skipping creation') + except Notes.DoesNotExist: + logger.info('Note created from Jira, creating it in DefectDojo') + comment_text = parsed['comment']['body'] + commentor = parsed['comment']['updateAuthor']['displayName'] + jid = parsed['comment']['self'].split('/')[7] + jissue = JIRA_Issue.objects.get(jira_id=jid) + finding = jissue.finding + new_note = Notes() + new_note.entry = '(%s): %s' % (commentor, comment_text) + new_note.author, created = User.objects.get_or_create(username='JIRA') + new_note.date = jira_note_creation_date + new_note.save() + finding.notes.add(new_note) + finding.jira_change = timezone.now() + finding.save() + create_notification(event='other', title='JIRA Update - %s' % (jissue.finding), url=reverse("view_finding", args=(jissue.id,)), icon='check') + except Exception as e: + print("catch all") + logger.error(str(e)) if parsed.get('webhookEvent') not in ['comment_created', 'jira:issue_updated']: logger.info('Unrecognized JIRA webhook event received: {}'.format(parsed.get('webhookEvent'))) diff --git a/dojo/models.py b/dojo/models.py index e2286e09c6f..90e518f1664 100755 --- a/dojo/models.py +++ b/dojo/models.py @@ -1225,6 +1225,7 @@ class Notes(models.Model): entry = models.TextField() date = models.DateTimeField(null=False, editable=False, default=get_current_datetime) + jira_id = models.IntegerField(null=True, blank=True) author = models.ForeignKey(User, related_name='editor_notes_set', editable=False, on_delete=models.CASCADE) private = models.BooleanField(default=False) edited = models.BooleanField(default=False) diff --git a/dojo/utils.py b/dojo/utils.py index d9101fdb39b..0b15a1e7edf 100644 --- a/dojo/utils.py +++ b/dojo/utils.py @@ -1705,9 +1705,11 @@ def add_comment(find, note, force_push=False): server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password)) j_issue = JIRA_Issue.objects.get(finding=find) - jira.add_comment( + jira_comment = jira.add_comment( j_issue.jira_id, '(%s): %s' % (note.author.get_full_name(), note.entry)) + note.jira_id = int(jira_comment.id) + note.save() except Exception as e: log_jira_generic_alert('Jira Add Comment Error', str(e)) pass