-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathservicenow_connector.py
2221 lines (1706 loc) · 91.4 KB
/
servicenow_connector.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
# File: servicenow_connector.py
#
# Copyright (c) 2016-2025 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
# Phantom imports
import phantom.app as phantom
try:
import phantom.rules as phrules
except:
pass
import ast
import json
import re
import sys
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import encryption_helper
import magic
import requests
from bs4 import BeautifulSoup
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
from servicenow_consts import *
DT_STR_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
class UnauthorizedOAuthTokenException(Exception):
pass
class RetVal(tuple):
def __new__(cls, status, data):
return tuple.__new__(RetVal, (status, data))
class ServicenowConnector(BaseConnector):
# actions supported by this script
ACTION_ID_LIST_TICKETS = "list_tickets"
ACTION_ID_ADD_COMMENT = "add_comment"
ACTION_ID_ORDER_ITEM = "request_catalog_item"
ACTION_ID_ADD_WORK_NOTE = "add_work_note"
ACTION_ID_DESCRIBE_CATALOG_ITEM = "describe_catalog_item"
ACTION_ID_DESCRIBE_SERVICE_CATALOG = "describe_service_catalog"
ACTION_ID_LIST_SERVICES = "list_services"
ACTION_ID_LIST_SERVICE_CATALOGS = "list_service_catalogs"
ACTION_ID_LIST_CATEGORIES = "list_categories"
ACTION_ID_CREATE_TICKET = "create_ticket"
ACTION_ID_GET_TICKET = "get_ticket"
ACTION_ID_UPDATE_TICKET = "update_ticket"
ACTION_ID_GET_VARIABLES = "get_variables"
ACTION_ID_ON_POLL = "on_poll"
ACTION_ID_RUN_QUERY = "run_query"
ACTION_ID_QUERY_USERS = "query_users"
ACTION_ID_SEARCH_SOURCES = "search_sources"
def csv_to_list(self, data):
"""Comma separated values to list"""
data = [x.strip() for x in data.split(",")]
data = list(dict.fromkeys(filter(None, data)))
return data
def __init__(self):
# Call the BaseConnectors init first
super(ServicenowConnector, self).__init__()
self._state_file_path = None
self._try_oauth = False
self._use_token = False
self._state = {}
self._response_headers = {}
def encrypt_state(self, encrypt_var, token_name):
"""Handle encryption of token.
:param encrypt_var: Variable needs to be encrypted
:return: encrypted variable
"""
self.debug_print(SERVICENOW_ENCRYPT_TOKEN.format(token_name)) # nosemgrep
return encryption_helper.encrypt(encrypt_var, self.get_asset_id())
def decrypt_state(self, decrypt_var, token_name):
"""Handle decryption of token.
:param decrypt_var: Variable needs to be decrypted
:return: decrypted variable
"""
self.debug_print(SERVICENOW_DECRYPT_TOKEN.format(token_name)) # nosemgrep
return encryption_helper.decrypt(decrypt_var, self.get_asset_id())
def initialize(self):
# Load all the asset configuration in global variables
self._state = self.load_state()
config = self.get_config()
sn_sc_actions = ["describe_catalog_item", "request_catalog_item"]
# Check if state file is not corrupted, if it is reset the state file
if not isinstance(self._state, dict):
self.debug_print("Resetting the state file with the default format")
self._state = {"app_version": self.get_app_json().get("app_version")}
# Base URL
self._base_url = config[SERVICENOW_JSON_DEVICE_URL]
if self._base_url.endswith("/"):
self._base_url = self._base_url[:-1]
ret_val, self._first_run_container = self._validate_integers(
self, config.get("first_run_container", SERVICENOW_DEFAULT_LIMIT), "first_run_container"
)
if phantom.is_fail(ret_val):
return self.get_status()
ret_val, self._max_container = self._validate_integers(self, config.get("max_container", DEFAULT_MAX_RESULTS), "max_container")
if phantom.is_fail(ret_val):
return self.get_status()
if config.get("severity"):
severity = config.get("severity", "medium").lower()
if len(severity) > 20:
return self.set_status(phantom.APP_ERROR, "Severity length must be less than equal to 20 characters")
self._host = self._base_url[self._base_url.find("//") + 2 :]
self._headers = {"Accept": "application/json"}
# self._headers.update({'X-no-response-body': 'true'})
self._api_uri = "/api/now"
if self.get_action_identifier() in sn_sc_actions:
self._api_uri = "/api/sn_sc"
self._client_id = config.get(SERVICENOW_JSON_CLIENT_ID, None)
if self._client_id:
try:
self._client_secret = config[SERVICENOW_JSON_CLIENT_SECRET]
self._use_token = True
except KeyError:
self.save_progress("Missing Client Secret")
return phantom.APP_ERROR
if self._use_token:
self._access_token = self._state.get(SERVICENOW_TOKEN_STRING, {}).get(SERVICENOW_ACCESS_TOKEN_STRING)
self._refresh_token = self._state.get(SERVICENOW_TOKEN_STRING, {}).get(SERVICENOW_REFRESH_TOKEN_STRING)
if self._state.get(SERVICENOW_STATE_IS_ENCRYPTED):
try:
if self._access_token:
self._access_token = self.decrypt_state(self._access_token, "access")
except Exception as e:
self._dump_error_log(e, SERVICENOW_DECRYPTION_ERROR)
return self.set_status(phantom.APP_ERROR, SERVICENOW_DECRYPTION_ERROR)
try:
if self._refresh_token:
self._refresh_token = self.decrypt_state(self._refresh_token, "refresh")
except Exception as e:
self._dump_error_log(e, SERVICENOW_DECRYPTION_ERROR)
return self.set_status(phantom.APP_ERROR, SERVICENOW_DECRYPTION_ERROR)
return phantom.APP_SUCCESS
def finalize(self):
if self._use_token:
try:
if self._access_token:
self._state[SERVICENOW_TOKEN_STRING][SERVICENOW_ACCESS_TOKEN_STRING] = self.encrypt_state(self._access_token, "access")
except Exception as e:
self._dump_error_log(e, SERVICENOW_ENCRYPTION_ERROR)
return self.set_status(phantom.APP_ERROR, SERVICENOW_ENCRYPTION_ERROR)
try:
if self._refresh_token:
self._state[SERVICENOW_TOKEN_STRING][SERVICENOW_REFRESH_TOKEN_STRING] = self.encrypt_state(self._refresh_token, "refresh")
except Exception as e:
self._dump_error_log(e, SERVICENOW_ENCRYPTION_ERROR)
return self.set_status(phantom.APP_ERROR, SERVICENOW_ENCRYPTION_ERROR)
self._state[SERVICENOW_STATE_IS_ENCRYPTED] = True
self.save_state(self._state)
return phantom.APP_SUCCESS
def _validate_integers(self, action_result, parameter, key, allow_zero=False):
"""This method is to check if the provided input parameter value
is a non-zero positive integer and returns the integer value of the parameter itself.
:param action_result: Action result or BaseConnector object
:param parameter: input parameter
:return: integer value of the parameter or None in case of failure
"""
if parameter is not None:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_VALIDATE_INTEGER_MESSAGE.format(param=key)), None
parameter = int(parameter)
except Exception:
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_VALIDATE_INTEGER_MESSAGE.format(param=key)), None
if parameter < 0:
return (
action_result.set_status(
phantom.APP_ERROR, "Please provide a valid non-negative integer value in the {} parameter".format(key)
),
None,
)
if not allow_zero and parameter == 0:
return (
action_result.set_status(phantom.APP_ERROR, "Please provide a positive integer value in the {} parameter".format(key)),
None,
)
return phantom.APP_SUCCESS, parameter
def _get_error_message_from_exception(self, e):
"""This method is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_message = SERVICENOW_ERROR_MESSAGE
error_code = None
self._dump_error_log(e, "Error occurred.")
try:
if hasattr(e, "args"):
if len(e.args) > 1:
error_code = e.args[0]
error_message = e.args[1]
elif len(e.args) == 1:
error_code = SERVICENOW_ERROR_CODE_MESSAGE
error_message = e.args[0]
except Exception as e:
self.error_print("Error occurred while fetching exception information. Details: {}".format(str(e)))
if not error_code:
error_text = "Error Message: {}".format(error_message)
else:
error_text = "Error Code: {}. Error Message: {}".format(error_code, error_message)
return error_text
def _dump_error_log(self, error, message="Exception occurred."):
self.error_print(message, dump_object=error)
def _get_error_details(self, resp_json):
# Initialize the default error_details
error_details = {"message": "Not Found", "detail": "Not supplied"}
# Handle if resp_json unavailable
if not resp_json:
return error_details
# Handle if resp_json contains "error" key and corresponding non-none and non-empty value or not
error_info = resp_json.get("error")
if not error_info:
return error_details
else:
if isinstance(error_info, dict):
error_details = error_info
else:
if isinstance(resp_json, dict):
error_details["message"] = error_info if error_info else "Not Found"
error_description = resp_json.get("error_description", "Not supplied")
error_details["detail"] = error_description
return error_details
# Handle the scenario of "message" and "detail" keys not in the required format
if "message" not in error_details:
error_details["message"] = "Not Found"
if "detail" not in error_details:
error_details["detail"] = "Not supplied"
return error_details
def _process_empty_response(self, response, action_result):
# this function will parse the header and create the response that the callers
# of the app expect
location = response.headers.get("Location")
if not location:
if 200 <= response.status_code < 205:
return RetVal(phantom.APP_SUCCESS, {})
else:
return RetVal(action_result.set_status(phantom.APP_ERROR, "Empty response and no information in the header"), None)
location_name = "{}{}/table".format(self._base_url, self._api_uri)
if location.startswith(location_name):
resp_json = dict()
try:
sys_id = location.rsplit("/", 1)[-1]
resp_json = {"result": {"sys_id": sys_id}}
except Exception as e:
self._dump_error_log(e, "Unable to process empty response for 'table'")
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to process empty response for 'table'"), None)
return RetVal(phantom.APP_SUCCESS, resp_json)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to process empty response"), None)
def _process_html_response(self, response, action_result):
# An html response, is bound to be an error
status_code = response.status_code
try:
soup = BeautifulSoup(response.text, "html.parser")
# Remove the script, style, footer and navigation part from the HTML message
for element in soup(["script", "style", "footer", "nav"]):
element.extract()
error_text = soup.text
split_lines = error_text.split("\n")
split_lines = [x.strip() for x in split_lines if x.strip()]
error_text = "\n".join(split_lines)
except Exception:
error_text = "Cannot parse error details"
message = "Status Code: {0}. Data from server:\n{1}\n".format(status_code, error_text)
message = message.replace("{", " ").replace("}", " ")
return RetVal(action_result.set_status(phantom.APP_ERROR, message), None)
def _process_json_response(self, r, action_result):
# Try a json parse
try:
resp_json = r.json()
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to parse response as JSON. {}".format(error_message)), None)
# What's with the special case 201?
if 200 <= r.status_code < 205:
return RetVal(phantom.APP_SUCCESS, resp_json)
if r.status_code == 401 and self._try_oauth:
if resp_json.get("error") == "invalid_token":
raise UnauthorizedOAuthTokenException
if r.status_code != requests.codes.ok: # pylint: disable=E1101
error_details = self._get_error_details(resp_json)
return RetVal(
action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_FROM_SERVER.format(status=r.status_code, **error_details)),
resp_json,
)
return RetVal(phantom.APP_SUCCESS, resp_json)
def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if an error occurs
if hasattr(action_result, "add_debug_data"):
if r is not None:
action_result.add_debug_data({"r_text": r.text})
action_result.add_debug_data({"r_headers": r.headers})
action_result.add_debug_data({"r_status_code": r.status_code})
else:
action_result.add_debug_data({"r_text": "r is None"})
# There are just too many differences in the response to handle all of them in the same function
if "json" in r.headers.get("Content-Type", ""):
return self._process_json_response(r, action_result)
if "html" in r.headers.get("Content-Type", ""):
return self._process_html_response(r, action_result)
# it's not an html or json, handle if it is a successfull empty response
if (200 <= r.status_code < 205) and (not r.text):
return self._process_empty_response(r, action_result)
# everything else is actually an error at this point
message = "Can't process response from server. Status Code: {0} Data from server: {1}".format(
r.status_code, r.text.replace("{", " ").replace("}", " ")
)
return RetVal(action_result.set_status(phantom.APP_ERROR, message), None)
def _upload_file(self, action_result, endpoint, headers=None, params=None, data=None, auth=None):
if headers is None:
headers = {}
# Create the headers
headers.update(self._headers)
resp_json = None
try:
r = requests.post(
"{}{}{}".format(self._base_url, self._api_uri, endpoint), # nosemgrep: python.requests.best-practice.use-timeout.use-timeout
auth=auth,
data=data,
headers=headers,
params=params,
)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return RetVal(
action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_SERVER_CONNECTION.format(error_message=error_message)), resp_json
)
return self._process_response(r, action_result)
def _make_rest_call_oauth(self, action_result, headers={}, data={}):
"""The API for retrieving the OAuth token is different enough to where its just easier to make a new function"""
resp_json = None
try:
request_url = "{}{}".format(self._base_url, "/oauth_token.do")
r = requests.post(request_url, data=data) # nosemgrep
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return (
action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_SERVER_CONNECTION.format(error_message=error_message)),
resp_json,
)
return self._process_response(r, action_result)
def _make_rest_call(self, action_result, endpoint, headers=None, params=None, data=None, auth=None, method="get"):
if headers is None:
headers = {}
# Create the headers
headers.update(self._headers)
if "Content-Type" not in headers:
headers.update({"Content-Type": "application/json"})
resp_json = None
request_func = getattr(requests, method)
if not request_func:
action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_API_UNSUPPORTED_METHOD, method=method)
try:
r = request_func("{}{}{}".format(self._base_url, self._api_uri, endpoint), auth=auth, json=data, headers=headers, params=params)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return (
action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_SERVER_CONNECTION.format(error_message=error_message)),
resp_json,
)
self._response_headers = r.headers
return self._process_response(r, action_result)
def _make_rest_call_helper(self, action_result, endpoint, params={}, data={}, headers={}, method="get", auth=None):
try:
return self._make_rest_call(action_result, endpoint, params=params, data=data, headers=headers, method=method, auth=auth)
except UnauthorizedOAuthTokenException:
# We should only be here if we didn't generate a new token, and if the old token wasn't valid
# (Hopefully) this should only happen rarely
self.debug_print("UnauthorizedOAuthTokenException")
if self._try_oauth:
self._try_oauth = False
ret_val, auth, headers = self._get_authorization_credentials(action_result, force_new=True)
if phantom.is_fail(ret_val):
return RetVal(phantom.APP_ERROR, None)
return self._make_rest_call_helper(action_result, endpoint, params=params, data=data, headers=headers, method=method, auth=auth)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to authorize with OAuth token"), None)
def _upload_file_helper(self, action_result, endpoint, params={}, data={}, headers={}, auth=None):
try:
return self._upload_file(action_result, endpoint, params=params, data=data, headers=headers, auth=auth)
except UnauthorizedOAuthTokenException:
# We should only be here if we didn't generate a new token, and if the old token wasn't valid
# (Hopefully) this should only happen rarely
self.debug_print("UnauthorizedOAuthTokenException")
if self._try_oauth:
self._try_oauth = False
ret_val, auth, headers = self._get_authorization_credentials(action_result, force_new=True)
if phantom.is_fail(ret_val):
return RetVal(phantom.APP_ERROR, None)
return self._upload_file_helper(action_result, endpoint, params=params, data=data, headers=headers, auth=auth)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to authorize with OAuth token"), None)
def _get_new_oauth_token(self, action_result, first_try=True):
"""Generate a new oauth token using the refresh token, if available"""
params = {}
params["client_id"] = self._client_id
params["client_secret"] = self._client_secret
if self._refresh_token:
params["refresh_token"] = self._refresh_token
params["grant_type"] = "refresh_token"
else:
config = self.get_config()
if config.get(SERVICENOW_JSON_USERNAME) and config.get(SERVICENOW_JSON_PASSWORD):
params["username"] = config[SERVICENOW_JSON_USERNAME]
params["password"] = config[SERVICENOW_JSON_PASSWORD]
params["grant_type"] = "password"
else:
return RetVal(action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_BASIC_AUTH_NOT_GIVEN_FIRST_TIME), None)
ret_val, response_json = self._make_rest_call_oauth(action_result, data=params)
if phantom.is_fail(ret_val) and params["grant_type"] == "refresh_token" and first_try:
self.debug_print("Unable to generate new key with refresh token")
if "first_run" in self._state:
if "last_time" in self._state:
self._state = {"first_run": self._state.get("first_run"), "last_time": self._state.get("last_time")}
else:
self._state = {"first_run": self._state.get("first_run")}
else:
self._state = {}
# Try again, using a password
return self._get_new_oauth_token(action_result, first_try=False)
if phantom.is_fail(ret_val):
error_message = action_result.get_message()
self._access_token, self._refresh_token = None, None
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error in token request. Error: {}".format(error_message)), None)
self._access_token = response_json[SERVICENOW_ACCESS_TOKEN_STRING]
self._refresh_token = response_json[SERVICENOW_REFRESH_TOKEN_STRING]
self._state["oauth_token"] = response_json
self._state["retrieval_time"] = datetime.now().strftime(DT_STR_FORMAT)
try:
return RetVal(phantom.APP_SUCCESS, response_json["access_token"])
except Exception as e:
if "first_run" in self._state:
if "last_time" in self._state:
self._state = {"first_run": self._state.get("first_run"), "last_time": self._state.get("last_time")}
else:
self._state = {"first_run": self._state.get("first_run")}
else:
self._state = {}
error_message = self._get_error_message_from_exception(e)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to parse access token. {}".format(error_message)), None)
def _get_oauth_token(self, action_result, force_new=False):
if self._state.get("oauth_token") and not force_new:
expires_in = self._state.get("oauth_token", {}).get("expires_in", 0)
try:
diff = (datetime.now() - datetime.strptime(self._state["retrieval_time"], DT_STR_FORMAT)).total_seconds()
self.debug_print(diff)
if diff < expires_in:
self.debug_print("Using old OAuth Token")
return RetVal(action_result.set_status(phantom.APP_SUCCESS), self._access_token)
except KeyError:
self.debug_print("Key Error")
self.debug_print("Generating new OAuth Token")
return self._get_new_oauth_token(action_result)
def _get_authorization_credentials(self, action_result, force_new=False):
auth = None
headers = {}
if self._use_token:
self.save_progress("Connecting with OAuth Token")
ret_val, oauth_token = self._get_oauth_token(action_result, force_new)
if phantom.is_fail(ret_val):
return ret_val, None, None
self.save_progress("OAuth Token Retrieved")
headers = {"Authorization": "Bearer {0}".format(oauth_token)}
self._try_oauth = True
else:
ret_val = phantom.APP_SUCCESS
self.save_progress("Connecting with HTTP Basic Auth")
config = self.get_config()
if config.get(SERVICENOW_JSON_USERNAME) and config.get(SERVICENOW_JSON_PASSWORD):
auth = requests.auth.HTTPBasicAuth(config[SERVICENOW_JSON_USERNAME], config[SERVICENOW_JSON_PASSWORD])
else:
action_result.set_status(phantom.APP_ERROR, "Unable to get authorization credentials")
return action_result.get_status(), None, {}
headers = {}
return ret_val, auth, headers
def _check_for_existing_container(self, sdi, label):
uri = "rest/container?page_size=0&_filter_source_data_identifier="
filter = "&_filter_label="
prefix = "&sort=create_time&order=asc"
request_str = '{0}{1}"{2}"{3}"{4}"{5}'.format(self.get_phantom_base_url(), uri, sdi, filter, label, prefix)
try:
r = requests.get(request_str, verify=False) # nosemgrep
except Exception as e:
self.error_print("Error making local rest call: {0}".format(self._get_error_message_from_exception(e)))
return 0, None, None, None
try:
resp_json = r.json()
except Exception as e:
self.error_print("Exception caught parsing JSON: {0}".format(self._get_error_message_from_exception(e)))
return 0, None, None, None
if resp_json.get("failed"):
return 0, None, None, None
count = resp_json.get("count", -1)
self.debug_print("{0} existing container(s) with SDI {1}".format(count, sdi))
if count > 0:
if count > 1:
self.debug_print("More than one container exists with SDI {0}. Going with oldest.".format(sdi))
response_data = resp_json["data"][0]
return response_data["id"], response_data["label"], response_data["name"], response_data["description"]
elif count < 0:
self.debug_print("Something went wrong getting container count")
self.debug_print(resp_json)
return 0, None, None, None
def _test_connectivity(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# Progress
self.save_progress(SERVICENOW_USING_BASE_URL, base_url=self._base_url)
# Connectivity
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, self._host)
ret_val, auth, headers = self._get_authorization_credentials(action_result, force_new=True)
if phantom.is_fail(ret_val):
return action_result.get_status()
request_params = {"sysparm_limit": "1"}
action_result = self.add_action_result(ActionResult(param))
self.save_progress(SERVICENOW_MESSAGE_GET_INCIDENT_TEST)
ret_val, response = self._make_rest_call_helper(
action_result, SERVICENOW_TEST_CONNECTIVITY_ENDPOINT, params=request_params, headers=headers, auth=auth
)
if phantom.is_fail(ret_val):
self.debug_print(action_result.get_message())
message = action_result.get_message()
if message:
message = message.strip().rstrip(".")
self.save_progress(message)
self.save_progress(SERVICENOW_ERROR_CONNECTIVITY_TEST)
return action_result.set_status(phantom.APP_ERROR)
self.save_progress(SERVICENOW_SUCCESS_CONNECTIVITY_TEST)
return action_result.set_status(phantom.APP_SUCCESS, SERVICENOW_SUCCESS_CONNECTIVITY_TEST)
def _get_fields(self, param, action_result):
fields = param.get(SERVICENOW_JSON_FIELDS)
# fields is an optional field
if not fields:
return RetVal(phantom.APP_SUCCESS, None)
try:
fields = ast.literal_eval(fields)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error building fields dictionary: {0}. \
Please ensure that provided input is in valid JSON format".format(
error_message
),
),
None,
)
if not isinstance(fields, dict):
return RetVal(action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_FIELDS_JSON_PARSE), None)
return RetVal(phantom.APP_SUCCESS, fields)
def _create_ticket(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# Progress
self.save_progress(SERVICENOW_USING_BASE_URL, base_url=self._base_url)
# Connectivity
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, self._host)
table = param.get(SERVICENOW_JSON_TABLE, SERVICENOW_DEFAULT_TABLE)
ret_val, auth, headers = self._get_authorization_credentials(action_result)
if phantom.is_fail(ret_val):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_AUTH_ERROR_MESSAGE)
endpoint = SERVICENOW_TABLE_ENDPOINT.format(table)
ret_val, fields = self._get_fields(param, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
data = dict()
if fields:
data.update(fields)
short_desc = param.get(SERVICENOW_JSON_SHORT_DESCRIPTION)
desc = param.get(SERVICENOW_JSON_DESCRIPTION)
if (not fields) and (not short_desc) and (SERVICENOW_JSON_DESCRIPTION not in param):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_ERROR_ONE_PARAM_REQ)
if short_desc:
data.update(
{
"short_description": short_desc.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\'", "'")
.replace('\\"', '"')
.replace("\\a", "\a")
.replace("\\b", "\b")
}
)
if desc:
json_description = param.get(SERVICENOW_JSON_DESCRIPTION, "")
data.update(
{
"description": "{0}\n\n{1}{2}".format(
json_description.replace("\\n", "\n")
.replace("\\r", "\r")
.replace("\\t", "\t")
.replace("\\'", "'")
.replace('\\"', '"')
.replace("\\a", "\a")
.replace("\\b", "\b"),
SERVICENOW_TICKET_FOOTNOTE,
self.get_container_id(),
)
}
)
elif fields and "description" in fields:
field_description = fields.get(SERVICENOW_JSON_DESCRIPTION, "")
data.update({"description": "{0}\n\n{1}{2}".format(field_description, SERVICENOW_TICKET_FOOTNOTE, self.get_container_id())})
else:
data.update({"description": "{0}\n\n{1}{2}".format("", SERVICENOW_TICKET_FOOTNOTE, self.get_container_id())})
ret_val, response = self._make_rest_call_helper(action_result, endpoint, data=data, auth=auth, headers=headers, method="post")
if phantom.is_fail(ret_val):
self.debug_print(action_result.get_message())
action_result.set_status(phantom.APP_ERROR, action_result.get_message())
return phantom.APP_ERROR
if not response.get("result"):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_INVALID_PARAMETER_MESSAGE)
created_ticket_id = response.get("result", {}).get("sys_id")
action_result.update_summary({SERVICENOW_JSON_NEW_TICKET_ID: created_ticket_id})
vault_ids = param.get(SERVICENOW_JSON_VAULT_ID)
if vault_ids:
ret_val = self._handle_multiple_attachements(action_result, table, created_ticket_id, vault_ids)
if phantom.is_fail(ret_val):
return action_result.get_status()
ret_val = self._get_ticket_details(action_result, param.get(SERVICENOW_JSON_TABLE, SERVICENOW_DEFAULT_TABLE), created_ticket_id)
if phantom.is_fail(ret_val):
return action_result.get_status()
return action_result.set_status(phantom.APP_SUCCESS)
def _add_attachment(self, action_result, table, ticket_id, vault_id):
if not vault_id:
return (phantom.APP_SUCCESS, None)
ret_val, auth, headers = self._get_authorization_credentials(action_result)
if phantom.is_fail(ret_val):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_AUTH_ERROR_MESSAGE), None
# Check for file in vault
try:
success, message, file_info = phrules.vault_info(vault_id=vault_id)
file_info = list(file_info)[0]
except IndexError:
return action_result.set_status(phantom.APP_ERROR, "Vault file could not be found with supplied Vault ID"), None
except Exception:
return action_result.set_status(phantom.APP_ERROR, "Vault ID not valid"), None
filename = file_info.get("name", vault_id)
filepath = file_info.get("path")
mime = magic.Magic(mime=True)
magic_str = mime.from_file(filepath)
headers.update({"Content-Type": magic_str})
try:
data = open(filepath, "rb").read()
except Exception as e:
self._dump_error_log(e, "Error reading the file")
return (action_result.set_status(phantom.APP_ERROR, "Failed to read file from Vault"), None)
# Was not detonated before
self.save_progress("Uploading the file")
params = {"table_name": table, "table_sys_id": ticket_id, "file_name": filename}
ret_val, response = self._upload_file_helper(action_result, "/attachment/file", headers=headers, params=params, data=data, auth=auth)
if phantom.is_fail(ret_val):
return (action_result.get_status(), response)
return (phantom.APP_SUCCESS, response)
def _handle_multiple_attachements(self, action_result, table, ticket_id, vault_ids):
attachment_count = 0
vault_error = {}
vault_ids = self.csv_to_list(vault_ids)
for vault_id in vault_ids:
if vault_id:
self.save_progress("Attaching file to the ticket with vault id {}".format(vault_id))
try:
ret_val, response = self._add_attachment(action_result, table, ticket_id, vault_id)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return action_result.set_status(
phantom.APP_ERROR,
"Invalid Vault ID, please enter \
valid Vault ID. {}".format(
error_message
),
)
if phantom.is_success(ret_val):
attachment_count += 1
else:
if vault_error.get(action_result.get_message()):
values = vault_error.get(action_result.get_message())
values.append(vault_id)
vault_error.update({"{}".format(action_result.get_message()): values})
else:
vault_error[action_result.get_message()] = [vault_id]
action_result.update_summary({"successfully_added_attachments_count": attachment_count})
if vault_error:
action_result.update_summary({"vault_failure_details": vault_error})
return phantom.APP_SUCCESS
def _update_ticket(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# Progress
self.save_progress(SERVICENOW_USING_BASE_URL, base_url=self._base_url)
# Connectivity
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, self._host)
try:
table = param.get(SERVICENOW_JSON_TABLE, SERVICENOW_DEFAULT_TABLE)
ticket_id = param[SERVICENOW_JSON_TICKET_ID]
is_sys_id = param.get("is_sys_id", False)
except Exception:
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_INVALID_PARAMETER_MESSAGE)
ret_val, auth, headers = self._get_authorization_credentials(action_result)
if phantom.is_fail(ret_val):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_AUTH_ERROR_MESSAGE)
if not is_sys_id:
params = {"sysparm_query": "number={0}".format(ticket_id)}
endpoint = SERVICENOW_TABLE_ENDPOINT.format(table)
ret_val, response = self._make_rest_call_helper(action_result, endpoint, auth=auth, headers=headers, params=params)
if phantom.is_fail(ret_val):
return action_result.get_status()
if response.get("result"):
sys_id = response.get("result")[0].get("sys_id")
if not sys_id:
return action_result.set_status(
phantom.APP_ERROR, "Unable to fetch the ticket SYS ID for the provided ticket number: {0}".format(ticket_id)
)
ticket_id = sys_id
else:
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_TICKET_ID_MESSAGE)
endpoint = SERVICENOW_TICKET_ENDPOINT.format(table, ticket_id)
ret_val, fields = self._get_fields(param, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
vault_ids = param.get(SERVICENOW_JSON_VAULT_ID)
if not fields and not vault_ids:
return action_result.set_status(phantom.APP_ERROR, "Please specify at-least one of fields or vault_id parameter")
if fields:
self.save_progress("Updating ticket with the provided fields")
ret_val, response = self._make_rest_call_helper(action_result, endpoint, data=fields, auth=auth, headers=headers, method="put")
if phantom.is_fail(ret_val):
return action_result.get_status()
action_result.update_summary({"fields_updated": True})
if vault_ids:
ret_val = self._handle_multiple_attachements(action_result, table, ticket_id, vault_ids)
if phantom.is_fail(ret_val):
return action_result.get_status()
ret_val = self._get_ticket_details(action_result, table, ticket_id)
if phantom.is_fail(ret_val):
return action_result.get_status()
return action_result.set_status(phantom.APP_SUCCESS)
def _get_ticket_details(self, action_result, table, sys_id, is_sys_id=True):
ret_val, auth, headers = self._get_authorization_credentials(action_result)
if phantom.is_fail(ret_val):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_AUTH_ERROR_MESSAGE)
if not is_sys_id:
params = {"sysparm_query": "number={0}".format(sys_id)}
endpoint = SERVICENOW_TABLE_ENDPOINT.format(table)
ret_val, response = self._make_rest_call_helper(action_result, endpoint, auth=auth, headers=headers, params=params)
if phantom.is_fail(ret_val):
return action_result.get_status()
if response.get("result"):
sys_id = response.get("result")[0].get("sys_id")
if not sys_id:
return action_result.set_status(
phantom.APP_ERROR,
"Unable to fetch the ticket SYS ID \
for the provided ticket number: {0}".format(
sys_id
),
)
else:
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_TICKET_ID_MESSAGE)
endpoint = SERVICENOW_TICKET_ENDPOINT.format(table, sys_id)
ret_val, response = self._make_rest_call_helper(action_result, endpoint, auth=auth, headers=headers)
if phantom.is_fail(ret_val):
self.debug_print(action_result.get_message())
action_result.set_status(phantom.APP_ERROR, action_result.get_message())
return phantom.APP_ERROR
if not response.get("result"):
return action_result.set_status(phantom.APP_ERROR, SERVICENOW_INVALID_PARAMETER_MESSAGE)
ticket = response.get("result", {})
ticket_sys_id = ticket.get("sys_id")
params = {"sysparm_query": "table_sys_id={0}".format(ticket_sys_id)}
# get the attachment details
ret_val, attach_resp = self._make_rest_call_helper(action_result, "/attachment", auth=auth, headers=headers, params=params)
# is some versions of servicenow fail the attachment query if not present
# some pass it with no data if not present, so only add data if present and valid
if phantom.is_success(ret_val):
try:
attach_details = attach_resp["result"]
ticket["attachment_details"] = attach_details
except Exception:
pass
params = {}
params["element_id"] = sys_id
params["sysparm_query"] = "element=comments^ORelement=work_notes"
ret_val, response = self._make_rest_call_helper(
action_result, SERVICENOW_SYS_JOURNAL_FIELD_ENDPOINT, auth=auth, headers=headers, params=params
)
if phantom.is_fail(ret_val):
self.debug_print(
"Unable to fetch comments and work_notes for \
the ticket with sys ID: {0}. Details: {1}".format(