-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
JiraV2.py
1621 lines (1340 loc) · 65.8 KB
/
JiraV2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from requests_oauthlib import OAuth1
from dateparser import parse
from datetime import timedelta
import urllib3
urllib3.disable_warnings()
''' GLOBALS/PARAMS '''
BASE_URL = demisto.getParam('url').rstrip('/') + '/'
API_TOKEN = demisto.getParam('APItoken') or (demisto.getParam('credentials') or {}).get('password')
USERNAME = demisto.getParam('username')
PASSWORD = demisto.getParam('password')
COMMAND_NOT_IMPELEMENTED_MSG = 'Command not implemented'
HEADERS = {
'Content-Type': 'application/json',
}
JIRA_INCIDENT_TYPE_NAME = 'Jira Incident'
ISSUE_INCIDENT_FIELDS = {'issueId': 'The ID of the issue to edit',
'summary': 'The summary of the issue.',
'description': 'The description of the issue.',
'labels': 'A CSV list of labels.',
'priority': 'A priority name, for example "High" or "Medium".',
'dueDate': 'The due date for the issue (in the format 2018-03-11).',
'assignee': 'The name of the assignee.',
'status': 'The name of the status.',
'assignee_id': 'The account ID of the assignee. Use'
' the jira-get-id-by-attribute command to get the user\'s Account ID.'
}
BASIC_AUTH_ERROR_MSG = "For cloud users: As of June 2019, Basic authentication with passwords for Jira is no" \
" longer supported, please use an API Token or OAuth 1.0"
JIRA_RESOLVE_REASON = 'Issue was marked as "Done"'
USE_SSL = not demisto.params().get('insecure', False)
SESSION = requests.Session()
SESSION.mount(prefix='https://', adapter=SSLAdapter(verify=USE_SSL))
def jira_req(
method: str,
resource_url: str,
body: str = '',
link: bool = False,
resp_type: str = 'text',
headers: dict | None = None,
files: dict | None = None,
params: dict | None = None
):
url = resource_url if link else (BASE_URL + resource_url)
AUTH = get_auth()
if headers and HEADERS.get('Authorization'):
headers['Authorization'] = HEADERS.get('Authorization')
try:
result = SESSION.request(
method=method,
url=url,
data=body,
auth=AUTH,
headers=headers if headers else HEADERS,
verify=USE_SSL,
files=files,
params=params
)
except ValueError:
raise ValueError("Could not deserialize privateKey")
if not result.ok:
demisto.debug(result.text)
try:
rj = result.json()
if rj.get('errorMessages'):
raise DemistoException(f'Status code: {result.status_code}\nMessages: {", ".join(rj["errorMessages"])}')
elif errors := rj.get('errors'):
error_messages = []
if isinstance(errors, list):
for error in errors:
error_messages.append(", ".join(error.values()))
else:
error_messages.append(", ".join(errors.values()))
raise DemistoException(f'Status code: {result.status_code}\nMessages: {error_messages}')
else:
raise DemistoException(f'Status code: {result.status_code}\nError text: {result.text}')
except ValueError as ve:
demisto.debug(str(ve))
if result.status_code == 401:
raise DemistoException('Unauthorized request, please check authentication related parameters.'
f'{BASIC_AUTH_ERROR_MSG}')
elif result.status_code == 404:
raise DemistoException("Could not connect to the Jira server. Verify that the server URL is correct.")
elif result.status_code == 500 and files:
raise DemistoException(f"Failed to execute request, status code: 500\nBody: {result.text}"
f"\nMake sure file name doesn't contain any special characters")
else:
raise DemistoException(
f"Failed reaching the server. status code: {result.status_code}")
if resp_type == 'json':
return result.json()
return result
def generate_oauth1():
oauth = OAuth1(
client_key=demisto.getParam('consumerKey'),
rsa_key=demisto.getParam('privateKey'),
signature_method='RSA-SHA1',
resource_owner_key=demisto.getParam('accessToken'),
)
return oauth
def generate_basic_oauth():
return USERNAME, (API_TOKEN or PASSWORD)
def get_auth():
access_token = demisto.getParam('accessToken')
is_basic = USERNAME and (PASSWORD or API_TOKEN)
is_oauth1 = demisto.getParam('consumerKey') and access_token and demisto.getParam('privateKey')
is_bearer = access_token and not is_oauth1
if is_basic:
return generate_basic_oauth()
elif is_oauth1:
HEADERS.update({'X-Atlassian-Token': 'nocheck'})
return generate_oauth1()
elif is_bearer:
# Personal Access Token Authentication
HEADERS.update({'Authorization': f'Bearer {access_token}'})
return None
return_error(
'Please provide the required Authorization information:'
'- Basic Authentication requires user name and password or API token'
'- OAuth 1.0 requires ConsumerKey, AccessToken and PrivateKey'
'- Personal Access Tokens requires AccessToken'
)
return None
def get_custom_field_names():
"""
This function returns all custom fields.
:return: dict of custom fields: id as key and name as value.
"""
custom_id_name_mapping = {}
HEADERS['Accept'] = "application/json"
try:
res = jira_req(method='GET', resource_url='rest/api/latest/field', headers=HEADERS)
except Exception as e:
demisto.error(f'Could not get custom fields because got the next exception: {e}')
else:
if res.ok:
custom_fields_list = res.json()
custom_id_name_mapping = {field.get('id'): field.get('name') for field in custom_fields_list}
else:
demisto.error(f'Could not get custom fields. status code: {res.status_code}. reason: {res.reason}')
finally:
return custom_id_name_mapping
def run_query(query, start_at='', max_results=None, extra_fields=None, nofields=None):
# EXAMPLE
"""
request = {
"jql": "project = HSP",
"startAt": 0,
"maxResults": 15,
"fields": [ <-- not supported yet, but easily attainable
"summary",
"status",
"assignee"
]
}
"""
demisto.debug(f'querying with: {query}')
url = 'rest/api/latest/search/'
query_params = {
'jql': query,
"startAt": start_at,
"maxResults": max_results,
}
if extra_fields:
fields = extra_fields.split(",")
fields_mapping_name_id = {k.lower(): v.lower() for k, v in get_custom_field_names().items()}
query_params['fields'] = [k for y in fields for k, v in fields_mapping_name_id.items() if v == y.lower()]
nofields.update(
{fieldextra for fieldextra in fields if fieldextra.lower() not in fields_mapping_name_id.values()})
if nofields:
if len(nofields) > 1:
return_warning(f'{",".join(nofields)} do not exist')
else:
return_warning(f'{",".join(nofields)} does not exist')
try:
result = jira_req(method='GET', resource_url=url, headers=HEADERS, params=query_params)
except ValueError:
raise ValueError("Could not deserialize privateKey")
try:
rj = result.json()
if rj.get('issues'):
return rj
errors = ",".join(rj.get("errorMessages", ['could not fetch any issues, please check your query']))
if 'could not fetch any issues, please check your query' in errors:
return {}
raise Exception(f'No issues were found, error message from Jira: {errors}')
except ValueError as ve:
demisto.debug(str(ve))
raise Exception(f'Failed to send request, reason: {result.reason}')
def get_id_offset():
"""
gets the ID Offset, i.e., the first issue id. used to fetch correctly all issues
"""
query = "ORDER BY created ASC"
j_res = run_query(query=query, max_results=1)
first_issue_id = j_res.get('issues')[0].get('id')
return_outputs(
readable_output=f"ID Offset: {first_issue_id}",
outputs={'Ticket.idOffSet': first_issue_id},
)
def get_custom_fields():
"""
This function returns all custom fields.
:return: dict of custom fields: id as key and description as value.
"""
custom_id_description_mapping = {}
HEADERS['Accept'] = "application/json"
try:
res = jira_req(method='GET', resource_url=BASE_URL + 'rest/api/latest/field', headers=HEADERS)
except Exception as e:
demisto.error(f'Could not get custom fields because got the next exception: {e}')
else:
if res.status_code == 200:
custom_fields_list = res.json()
custom_id_description_mapping = {field.get('id'): field.get('description') for field in custom_fields_list}
else:
demisto.error(f'Could not get custom fields. status code: {res.status_code}. reason: {res.reason}')
finally:
return custom_id_description_mapping
def expand_urls(data, depth=0):
if isinstance(data, dict) and depth < 10:
for key, value in data.items():
if key in ['_links', 'watchers', 'sla', 'request participants']:
# dictionary of links
if isinstance(value, dict):
for link_key, link_url in value.items():
value[link_key + '_expended'] = json.dumps(
jira_req(method='GET', resource_url=link_url, link=True, resp_type='json'))
# link
else:
data[key + '_expended'] = json.dumps(jira_req(method='GET', resource_url=value,
link=True, resp_type='json'))
# search deeper
else:
if isinstance(value, dict):
return expand_urls(value, depth + 1)
return None
return None
def search_user(query: str, max_results: str = '50', is_jirav2api: bool = False):
"""
Search for user by name or email address.
Args:
query: A query string that is matched against user attributes ( displayName, and emailAddress) to find relevant users.
max_results (str): The maximum number of items to return. default by the server: 50
is_jirav2api (bool): if the instance is connecting to a Jira Server that supports only the v2 REST API. default as False
Returns:
List of users.
"""
if is_jirav2api:
"""
override user identifier for Jira v2 API
https://docs.atlassian.com/software/jira/docs/api/REST/8.13.15/#user-findUsers
"""
url = f"rest/api/latest/user/search?username={query}&maxResults={max_results}"
else:
url = f"rest/api/latest/user/search?query={query}&maxResults={max_results}"
res = jira_req('GET', url, resp_type='json')
return res
def get_account_id_from_attribute(
attribute: str,
max_results: str = '50',
is_jirav2api: str = 'false') -> CommandResults | str:
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-user-search/#api-rest-api-3-user-search-get
Args:
attribute (str): Username or Email address of a user.
max_results (str): The maximum number of items to return. default by the server: 50
is_jirav2api (str): if the instance is connecting to a Jira Server that supports only the v2 REST API. default as false
"""
if is_jirav2api == 'true':
"""
override user identifier for Jira v2 API
https://docs.atlassian.com/software/jira/docs/api/REST/8.13.15/#user-findUsers
"""
users = list(search_user(attribute, max_results, is_jirav2api=True))
account_ids = {
user.get('name') for user in users if (attribute.lower() in [user.get('displayName', '').lower(),
user.get('emailAddress', '').lower()])}
else:
users = list(search_user(attribute, max_results))
account_ids = {
user.get('accountId') for user in users if (attribute.lower() in [user.get('displayName', '').lower(),
user.get('emailAddress', '').lower()])}
if not account_ids:
# The email address is a private account field and sometimes is blank. If there is only one result,
# then it is the one. If there are more results for the query, the user should try "DisplayName" attribute.
if not users:
return f'No Account ID was found for attribute: {attribute}.'
if len(users) == 1:
account_ids = {users[0].get('name')} if is_jirav2api == 'true' else {users[0].get('accountId')}
else:
demisto.debug(f'Multiple account IDs found, but it was not possible to resolve which one of them is most '
f'relevant to attribute \"{attribute}\". Account ids: {account_ids}')
return f'Multiple account IDs found, but it was not possible to resolve which one of them is most ' \
f'relevant to attribute \"{attribute}\".Please try to provide the "DisplayName" attribute.'
if len(account_ids) > 1:
return f'Multiple account IDs were found for attribute: {attribute}.\n' \
f'Please try to provide the other attribute available - Email or DisplayName.'
account_id = next(iter(account_ids))
outputs = {
'Attribute': attribute,
'AccountID': account_id
}
return CommandResults(
outputs_prefix='Jira.User',
outputs_key_field='AccountID',
readable_output=f'Account ID for attribute: {attribute} is: {account_id}',
outputs=outputs,
)
def generate_md_context_get_issue(data, customfields=None, nofields=None, extra_fields=None):
get_issue_obj: dict = {"md": [], "context": []}
if not isinstance(data, list):
data = [data]
for element in data:
md_obj, context_obj = {}, {}
context_obj['Id'] = md_obj['id'] = demisto.get(element, 'id')
context_obj['Key'] = md_obj['key'] = demisto.get(element, 'key')
context_obj['Summary'] = md_obj['summary'] = demisto.get(element, 'fields.summary')
context_obj['Status'] = md_obj['status'] = demisto.get(element, 'fields.status.name')
context_obj['Priority'] = md_obj['priority'] = demisto.get(element, 'fields.priority.name')
context_obj['ProjectName'] = md_obj['project'] = demisto.get(element, 'fields.project.name')
context_obj['DueDate'] = md_obj['duedate'] = demisto.get(element, 'fields.duedate')
context_obj['Created'] = md_obj['created'] = demisto.get(element, 'fields.created')
context_obj['Description'] = md_obj['description'] = demisto.get(element, 'fields.description')
context_obj['Labels'] = md_obj['labels'] = demisto.get(element, 'fields.labels')
# Parse custom fields into their original names
custom_fields = [i for i in demisto.get(element, "fields") if "custom" in i]
if extra_fields:
custom_fields = extra_fields
if (custom_fields and customfields and not nofields) or extra_fields:
field_mappings = get_custom_field_names()
for field_returned in custom_fields:
readable_field_name = field_mappings.get(field_returned)
if readable_field_name:
context_obj[readable_field_name] = md_obj[readable_field_name] = \
demisto.get(element, f"fields.{field_returned}")
assignee = demisto.get(element, 'fields.assignee')
context_obj['Assignee'] = md_obj['assignee'] = "{name}({email})".format(
name=assignee.get('displayName', 'null'),
email=assignee.get('emailAddress', 'null')
) if assignee else 'null(null)'
creator = demisto.get(element, 'fields.creator')
context_obj['Creator'] = md_obj['creator'] = "{name}({email})".format(
name=creator.get('displayName', 'null'),
email=creator.get('emailAddress', 'null')
) if creator else 'null(null)'
reporter = demisto.get(element, 'fields.reporter')
md_obj['reporter'] = "{name}({email})".format(
name=reporter.get('displayName', 'null'),
email=reporter.get('emailAddress', 'null')
) if reporter else 'null(null)'
context_obj.update({
'LastSeen': demisto.get(element, 'fields.lastViewed'),
'LastUpdate': demisto.get(element, 'fields.updated'),
})
md_obj.update({
'issueType': f"{demisto.get(element, 'fields.issuetype.name')} "
f"({demisto.get(element, 'fields.issuetype.description')})",
'labels': demisto.get(element, 'fields.labels'),
'description': demisto.get(element, 'fields.description'),
'ticket_link': demisto.get(element, 'self'),
})
attachments = demisto.get(element, 'fields.attachment')
if isinstance(attachments, list):
md_obj['attachment'] = ','.join(attach.get('filename') for attach in attachments)
context_obj['attachment'] = ','.join(attach.get('filename') for attach in attachments)
get_issue_obj['md'].append(md_obj)
get_issue_obj['context'].append(context_obj)
return get_issue_obj
def generate_md_context_create_issue(data, project_name=None, project_key=None):
create_issue_obj = {"md": [], "context": {"Ticket": []}} # type: ignore
if project_name:
data["projectName"] = project_name
if project_key:
data["projectKey"] = project_key
elif demisto.getParam('projectKey'):
data["projectKey"] = demisto.getParam('projectKey')
create_issue_obj['md'].append(data) # type: ignore
create_issue_obj['context']['Ticket'].append( # type: ignore
{"Id": demisto.get(data, 'id'), "Key": demisto.get(data, 'key')}) # type: ignore
return create_issue_obj
def generate_md_upload_issue(data, issue_id):
upload_md = []
if not isinstance(data, list):
data = [data]
for element in data:
md_obj = {
'id': demisto.get(element, 'id'),
'issueId': issue_id,
'attachment_name': demisto.get(element, 'filename'),
'attachment_link': demisto.get(element, 'self')
}
upload_md.append(md_obj)
return upload_md
def get_mirror_type(should_mirror_in, should_mirror_out):
"""
This function return the type of mirror to perform on a Jira incident.
NOTE: in order to not mirror an incident, the type should be None.
:param should_mirror_in: demisto.params().get("incoming_mirror")
:param should_mirror_out: demisto.params().get('outgoing_mirror')
:return: The mirror type
"""
# Adding mirroring details
mirror_type = None
if should_mirror_in and should_mirror_out:
mirror_type = 'Both'
elif should_mirror_in:
mirror_type = 'In'
elif should_mirror_out:
mirror_type = 'Out'
return mirror_type
def create_incident_from_ticket(issue, should_get_attachments, should_get_comments, should_mirror_in, should_mirror_out,
comment_tag, attachment_tag):
labels = [
{'type': 'issue', 'value': json.dumps(issue)}, {'type': 'id', 'value': str(issue.get('id'))},
{'type': 'lastViewed', 'value': str(demisto.get(issue, 'fields.lastViewed'))},
{'type': 'priority', 'value': str(demisto.get(issue, 'fields.priority.name'))},
{'type': 'status', 'value': str(demisto.get(issue, 'fields.status.name'))},
{'type': 'project', 'value': str(demisto.get(issue, 'fields.project.name'))},
{'type': 'updated', 'value': str(demisto.get(issue, 'fields.updated'))},
{'type': 'reportername', 'value': str(demisto.get(issue, 'fields.reporter.displayName'))},
{'type': 'reporteremail', 'value': str(demisto.get(issue, 'fields.reporter.emailAddress'))},
{'type': 'created', 'value': str(demisto.get(issue, 'fields.created'))},
{'type': 'summary', 'value': str(demisto.get(issue, 'fields.summary'))},
{'type': 'description', 'value': str(demisto.get(issue, 'fields.description'))},
]
name = demisto.get(issue, 'fields.summary')
if name:
name = f"Jira issue: {issue.get('id')}"
severity = 0
if demisto.get(issue, 'fields.priority') and demisto.get(issue, 'fields.priority.name'):
if demisto.get(issue, 'fields.priority.name') == 'Highest':
severity = 4
elif demisto.get(issue, 'fields.priority.name') == 'High':
severity = 3
elif demisto.get(issue, 'fields.priority.name') == 'Medium':
severity = 2
elif demisto.get(issue, 'fields.priority.name') == 'Low':
severity = 1
file_names = []
if should_get_attachments:
for file_result in get_entries_for_fetched_incident(issue.get('id'), False, True)['attachments']:
if file_result['Type'] != entryTypes['error']:
file_names.append({
'path': file_result.get('FileID', ''),
'name': file_result.get('File', '')
})
if should_get_comments:
labels.append({'type': 'comments', 'value': str(get_entries_for_fetched_incident(issue.get('id'), True, False)
['comments'])})
else:
labels.append({'type': 'comments', 'value': '[]'})
issue['mirror_direction'] = get_mirror_type(should_mirror_in, should_mirror_out)
issue['mirror_tags'] = [
comment_tag,
attachment_tag
]
issue['mirror_instance'] = demisto.integrationInstance()
return {
"name": name,
"labels": labels,
"details": demisto.get(issue, "fields.description"),
"severity": severity,
"attachment": file_names,
"rawJSON": json.dumps(issue)
}
def get_project_id(project_key='', project_name=''):
if not project_key and not project_name:
return_error('You must provide at least one of the following: project_key or project_name')
result: dict = {}
try:
result = jira_req('GET', 'rest/api/latest/issue/createmeta', resp_type='json')
except DemistoException as de:
if 'Status code: 404' not in de.message:
raise de
demisto.debug('Exception after first api call: {de.message}')
demisto.debug(f'Could not find expected Jira endpoint: {BASE_URL}/api/latest/issue/createmeta.'
f'Trying another endpoint: {BASE_URL}/api/latest/project.')
# a new endpoint for Jira version 9.0.0 and above, so we execute another api call
result = jira_req('GET', 'rest/api/latest/project', resp_type='json')
# Jira's response changed to a list of projects from version 9.0.0
projects_lst = list(filter(
lambda x: x.get('key').lower() == project_key.lower() or x.get('name').lower() == project_name.lower(),
result))
# Filtering should give us a list with one project, only one project should match the filter's conditions
if projects_lst:
return projects_lst[0].get('id')
# Jira used to respond with a dictionary with the 'projects' key until version 9.0.0
if isinstance(result, dict):
for project in result.get('projects', []):
if project_key.lower() == project.get('key').lower() or project_name.lower() == project.get('name').lower():
return project.get('id')
return_error('Project not found')
return None
def get_issue_fields(issue_creating=False, mirroring=False, **issue_args):
"""
refactor issues's argument as received from demisto into jira acceptable format, and back.
:param issue_creating: flag that indicates this function is called when creating an issue
:param issue_args: issue argument
"""
issue = {} # type: dict
if 'issue_json' in issue_args:
try:
issue = json.loads(issue_args['issue_json'], strict=False)
except TypeError as te:
demisto.debug(str(te))
return_error("issueJson must be in a valid json format")
elif 'issueJson' in issue_args:
try:
issue = json.loads(issue_args['issueJson'], strict=False)
except TypeError as te:
demisto.debug(str(te))
return_error("issueJson must be in a valid json format")
if not issue.get('fields'):
issue['fields'] = {}
if mirroring:
for field_name in issue_args:
if field_name and field_name.startswith('customfield'):
issue['fields'][field_name] = issue_args[field_name]
if not issue['fields'].get('issuetype') and issue_creating:
issue['fields']['issuetype'] = {}
if issue_args.get('watchers'):
watchers = issue_args.get('watchers')
if isinstance(watchers, list):
issue['watchers'] = watchers
elif isinstance(watchers, str):
issue['watchers'] = argToList(watchers)
if issue_args.get('summary'):
issue['fields']['summary'] = issue_args['summary']
if not issue['fields'].get('project') and (issue_args.get('projectKey') or issue_args.get('projectName')):
issue['fields']['project'] = {}
if issue_args.get('projectKey'):
issue['fields']['project']['key'] = issue_args.get('projectKey', '')
if issue_args.get('projectName'):
issue['fields']['project']['name'] = issue_args.get('projectName', '')
if issue_creating:
# make sure the key & name are right, and get the corresponding project id & key
project_id = get_project_id(issue['fields'].get('project', {}).get('key', ''),
issue['fields'].get('project', {}).get('name', ''))
issue['fields']['project']['id'] = project_id
if issue_args.get('issueTypeName'):
issue['fields']['issuetype']['name'] = issue_args['issueTypeName']
if issue_args.get('issueTypeId'):
issue['fields']['issuetype']['id'] = issue_args['issueTypeId']
if issue_args.get('parentIssueId'):
if not issue['fields'].get('parent'):
issue['fields']['parent'] = {}
issue['fields']['parent']['id'] = issue_args['parentIssueId']
if issue_args.get('parentIssueKey'):
if not issue['fields'].get('parent'):
issue['fields']['parent'] = {}
issue['fields']['parent']['key'] = issue_args['parentIssueKey']
if issue_args.get('description'):
issue['fields']['description'] = issue_args['description']
if issue_args.get('components'):
components = [{"name": comp} for comp in argToList(issue_args["components"])]
issue['fields']['components'] = components
if issue_args.get('security'):
issue['fields']['security'] = {"name": issue_args['security']}
if issue_args.get('environment'):
issue['fields']['environment'] = issue_args['environment']
if issue_args.get('labels') and isinstance(issue_args.get('labels'), str):
issue['fields']['labels'] = issue_args['labels'].split(",")
if issue_args.get('labels') and isinstance(issue_args.get('labels'), list):
issue['fields']['labels'] = issue_args['labels']
if issue_args.get('priority'):
if not issue['fields'].get('priority'):
issue['fields']['priority'] = {}
issue['fields']['priority']['name'] = issue_args['priority']
duedate = issue_args.get('duedate') or issue_args.get('dueDate')
if duedate:
issue['fields']['duedate'] = duedate
if issue_args.get('assignee'):
if not issue['fields'].get('assignee'):
issue['fields']['assignee'] = {}
issue['fields']['assignee']['name'] = issue_args['assignee']
if issue_args.get('assignee_id'):
if not issue['fields'].get('assignee'):
issue['fields']['assignee'] = {}
issue['fields']['assignee']['accountId'] = issue_args['assignee_id']
if issue_args.get('reporter_id'):
if not issue['fields'].get('reporter'):
issue['fields']['reporter'] = {}
issue['fields']['reporter']['accountId'] = issue_args['reporter_id']
if issue_args.get('reporter'):
if not issue['fields'].get('reporter'):
issue['fields']['reporter'] = {}
issue['fields']['reporter']['name'] = issue_args['reporter']
demisto.debug(f'The issue after updating relevant fields: {issue}')
return issue
def get_issue(issue_id, headers=None, expand_links=False, is_update=False, get_attachments=False, extra_fields=None):
j_res = jira_req('GET', f'rest/api/latest/issue/{issue_id}', resp_type='json')
if expand_links == "true":
expand_urls(j_res)
attachments = demisto.get(j_res, 'fields.attachment') # list of all attachments
# handle issues were we allowed incorrect values of true
if get_attachments == "true" or get_attachments == "\"true\"":
get_attachments = True
else:
get_attachments = False
if get_attachments and attachments:
for attachment in attachments:
filename, attachments_zip = get_attachment_data(attachment)
demisto.results(fileResult(filename=filename, data=attachments_zip))
md_and_context = generate_md_context_get_issue(j_res, extra_fields=extra_fields)
human_readable = tableToMarkdown(demisto.command(), md_and_context['md'], argToList(headers))
if is_update:
human_readable += f'Issue #{issue_id} was updated successfully'
contents = j_res
outputs = {'Ticket(val.Id == obj.Id)': md_and_context['context']}
return human_readable, outputs, contents
def get_project_role_command(project_key, role_name):
j_res = get_project_roles(project_key)
url = j_res.get(role_name)
if not url:
return_error(f"Role '{role_name}' not found")
role_id = url.split('/')[-1]
url = f'rest/api/latest/project/{project_key}/role/{role_id}'
j_res = jira_req('GET', url, resp_type='json')
return j_res
def get_project_roles(project_key):
url = f'rest/api/latest/project/{project_key}/role'
j_res = jira_req('GET', url, resp_type='json')
return j_res
def issue_query_command(query, start_at='', max_results=None, headers='', extra_fields=None):
nofields: set = set()
j_res = run_query(query, start_at, max_results, extra_fields, nofields)
if not j_res:
outputs = contents = {}
human_readable = 'No issues matched the query.'
else:
issues = demisto.get(j_res, 'issues')
md_and_context = generate_md_context_get_issue(issues, extra_fields, nofields)
human_readable = tableToMarkdown(demisto.command(), t=md_and_context['md'], headers=argToList(headers))
contents = j_res
outputs = {'Ticket(val.Id == obj.Id)': md_and_context['context']}
return human_readable, outputs, contents
def create_issue_command():
url = 'rest/api/latest/issue'
issue = get_issue_fields(issue_creating=True, **demisto.args())
j_res = jira_req('POST', url, json.dumps(issue), resp_type='json')
md_and_context = generate_md_context_create_issue(j_res, project_key=demisto.getArg('projectKey'),
project_name=demisto.getArg('projectName'))
human_readable = tableToMarkdown(demisto.command(), md_and_context['md'], "")
contents = j_res
outputs = md_and_context['context']
return_outputs(readable_output=human_readable, outputs=outputs, raw_response=contents)
def add_user_to_project_command(user_email, project_key, role_name):
result = get_account_id_from_attribute(user_email)
if isinstance(result, CommandResults) and isinstance(result.raw_response, dict):
user_id = result.raw_response.get('AccountID')
else:
return_error(f'{result}')
role_id = get_project_role_command(project_key, role_name).get('id')
url = f'rest/projectconfig/latest/roles/{project_key}/{role_id}'
json_data = {'users': [user_id], "groups": []}
return jira_req('POST', url, json.dumps(json_data)).text
def edit_issue_command(issue_id, mirroring=False, headers=None, status=None, transition=None, **kwargs):
issue = get_issue_fields(mirroring=mirroring, **kwargs)
if status and transition:
return_error("Please provide only status or transition, but not both.")
elif status:
edit_status(issue_id, status, issue)
elif transition:
edit_transition(issue_id, transition, issue)
else:
url = f'rest/api/latest/issue/{issue_id}/'
jira_req('PUT', url, json.dumps(issue))
return get_issue(issue_id, headers, is_update=True)
def append_to_field_command(issue_id, field_json, headers=None):
issue = jira_req('GET', f'rest/api/latest/issue/{issue_id}', resp_type='json')
fields = json.loads(field_json, strict=False)
new_data = {}
for field in fields:
field_type = __get_field_type(field)
if not field_type:
raise DemistoException(f"field {field} could not be updated.")
if field_type == 'Field Not Found':
raise DemistoException(f'Could not identify field {field}. Make sure it was entered with correct field ID.')
current_data_in_field = issue.get('fields', {}).get(field)
if not current_data_in_field:
new_data[field] = __create_value_by_type(field_type, fields[field])
else:
new_data[field] = __add_value_by_type(field_type, current_data_in_field, fields[field])
_update_fields(issue_id, new_data)
return get_issue(issue_id, headers, is_update=True)
def _update_fields(issue_id, new_data):
url = f'rest/api/latest/issue/{issue_id}/'
if new_data:
jira_req('PUT', url, json.dumps({'fields': new_data}))
def get_organizations_command(project_key=None, start="0", limit="50", account_id=None):
if project_key:
url = f'/rest/servicedeskapi/servicedesk/{project_key}/organization'
else:
url = '/rest/servicedeskapi/organization'
body = {
'start': arg_to_number(start),
'limit': arg_to_number(limit),
}
if account_id:
body['accountId'] = account_id
if response := jira_req('GET', url, params=body, resp_type='json').get('values'):
[org.pop('_links') for org in response]
hr = tableToMarkdown(name='Organizations', t=response, headers=['name', 'id', 'created'],
json_transform_mapping={'created': JsonTransformer(func=lambda x: x.get('friendly'))})
return CommandResults(outputs=response, outputs_prefix='Jira.Organizations', outputs_key_field='id', readable_output=hr)
return CommandResults(readable_output='No results found.')
def get_field_command(issue_id, field):
fields = argToList(field)
return get_issue(issue_id, extra_fields=fields, is_update=False)
def __get_field_type(field_id):
fields = jira_req('GET', 'rest/api/2/field')
field_data_filter = filter(lambda x: x.get('id') == field_id, fields.json())
try:
field_data = next(field_data_filter)
return field_data.get('schema', {}).get('type')
except StopIteration:
return 'Field Not Found'
def __add_value_by_type(type, current_value, new_value):
if type == 'string':
new_val = current_value + " , " + new_value
elif type == 'array':
new_val = current_value + [new_value]
else:
raise DemistoException(f"Command only support string or array-typed fields. Field given is typed {type}")
return new_val
def __create_value_by_type(type, value):
if type == 'string':
return str(value)
elif type == 'array':
return [value]
else:
raise DemistoException(f"Command only support string or array-typed fields. Field given is typed {type}")
def edit_status(issue_id, status, issue):
# check for all authorized transitions available for this user
# if the requested transition is available, execute it.
if not issue:
issue = {}
j_res = list_transitions_data_for_issue(issue_id)
# When changing the status we search the transition that leads to this status
statuses = [transition.get('to', {}).get('name', '') for transition in j_res.get('transitions')]
for i, transition in enumerate(statuses):
if transition.lower() == status.lower():
url = f'rest/api/latest/issue/{issue_id}/transitions?expand=transitions.fields'
issue['transition'] = {"id": str(j_res.get('transitions')[i].get('id'))}
return jira_req('POST', url, json.dumps(issue))
return_error(f'Status "{status}" not found. \nValid statuses are: {statuses} \n')
return None
def list_transitions_data_for_issue(issue_id):
"""
This function performs the API call for getting a list of all possible transitions for a given issue.
:param issue_id: The ID of the issue.
:return: API raw response.
"""
url = f'rest/api/2/issue/{issue_id}/transitions'
return jira_req('GET', url, resp_type='json')
def edit_transition(issue_id, transition_name, issue):
"""
This function changes a transition for a given issue.
:param issue_id: The ID of the issue.
:param transition_name: The name of the new transition.
:return: None
"""
if issue is None:
issue = {}
j_res = list_transitions_data_for_issue(issue_id)
transitions_data = j_res.get('transitions')
for transition in transitions_data:
if transition.get('name') == transition_name:
url = f'rest/api/latest/issue/{issue_id}/transitions?expand=transitions.fields'
issue['transition'] = {"id": transition.get("id")}
return jira_req('POST', url, json.dumps(issue))
return_error(f'Transitions "{transition_name}" not found. \nValid transitions are: {transitions_data} \n')
return None
def list_transitions_command(args):
"""
This command list all possible transitions for a given issue.
:param args: args['issueId']: The ID of the issue.
:return: CommandResults object with the list of transitions
"""
issue_id = args.get('issueId')
transitions_data_list = list_transitions_data_for_issue(issue_id)
transitions_names = [transition.get('name') for transition in transitions_data_list.get('transitions')]
readable_output = tableToMarkdown(
'List Transitions:', transitions_names, headers=['Transition Name']
)
outputs = {'ticketId': issue_id,
'transitions': transitions_names
}
return CommandResults(raw_response=transitions_names, readable_output=readable_output,
outputs_prefix="Ticket.Transitions", outputs_key_field="ticketId", outputs=outputs)
def get_comments_command(issue_id):
url = f'rest/api/latest/issue/{issue_id}/comment'
body = jira_req('GET', url, resp_type='json')
comments = []
if body.get("comments"):
for comment in body.get("comments"):
comments.append({
'Comment': comment.get("body"),
'User': demisto.get(comment, 'updateAuthor.name'),
'Created': comment.get("created")
})
human_readable = tableToMarkdown("Comments", comments)
contents = body
outputs = {'Ticket(val.Id == obj.Id)': {'Id': issue_id, "Comment": comments}}
return human_readable, outputs, contents
else:
return 'No comments were found in the ticket', None, None
def add_comment(issue_id, comment, visibility=''):
url = f'rest/api/latest/issue/{issue_id}/comment'
comment = {
"body": comment
}
if visibility:
comment["visibility"] = {
"type": "role",