-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathArcherV2.py
1875 lines (1623 loc) · 67.3 KB
/
ArcherV2.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 datetime import UTC, datetime
import random
import dateparser
import urllib3
""" IMPORTS """
# Disable insecure warnings
urllib3.disable_warnings()
FETCH_PARAM_ID_KEY = "field_time_id"
LAST_FETCH_TIME_KEY = "last_fetch"
OCCURRED_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
REQUEST_HEADERS = {
"Accept": "application/json,text/html,application/xhtml +xml,application/xml;q=0.9,*/*;q=0.8",
"Content-Type": "application/json",
}
FIELD_TYPE_DICT = {
1: "Text",
2: "Numeric",
3: "Date",
4: "Values List",
6: "TrackingID",
7: "External Links",
8: "Users/Groups List",
9: "Cross-Reference",
11: "Attachment",
12: "Image",
14: "Cross-Application Status Tracking (CAST)",
16: "Matrix",
19: "IP Address",
20: "Record Status",
21: "First Published",
22: "Last Updated Field",
23: "Related Records",
24: "Sub-Form",
25: "History Log",
26: "Discussion",
27: "Multiple Reference Display Control",
28: "Questionnaire Reference",
29: "Access History",
30: "V oting",
31: "Scheduler",
1001: "Cross-Application Status Tracking Field Value",
}
ACCOUNT_STATUS_DICT = {1: "Active", 2: "Inactive", 3: "Locked"}
API_ENDPOINT = demisto.params().get("api_endpoint", "api")
def parser(
date_str,
date_formats=None,
languages=None,
locales=None,
region=None,
settings=None,
) -> datetime:
"""Wrapper of dateparser.parse to support return type value"""
date_obj = dateparser.parse(
date_str,
date_formats=date_formats,
languages=languages,
locales=locales,
region=region,
settings=settings,
)
assert isinstance(
date_obj, datetime
), f"Could not parse date {date_str}" # MYPY Fix
return date_obj.replace(tzinfo=UTC)
def get_token_soap_request(user, password, instance, domain=None):
if domain:
# Create the root element
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.orecord_to_incidentrg/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the CreateUserSessionFromInstance element
create_user_session = ET.SubElement(
body,
"CreateDomainUserSessionFromInstance",
{"xmlns": "http://archer-tech.com/webservices/"},
)
# Add the userName, instanceName, and password elements
ET.SubElement(create_user_session, "userName").text = user
ET.SubElement(create_user_session, "instanceName").text = instance
ET.SubElement(create_user_session, "password").text = password
ET.SubElement(create_user_session, "usersDomain").text = domain
else:
# Create the root element
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the CreateUserSessionFromInstance element
create_user_session = ET.SubElement(
body,
"CreateUserSessionFromInstance",
{"xmlns": "http://archer-tech.com/webservices/"},
)
# Add the userName, instanceName, and password elements
ET.SubElement(create_user_session, "userName").text = user
ET.SubElement(create_user_session, "instanceName").text = instance
ET.SubElement(create_user_session, "password").text = password
return ET.tostring(root)
def get_reports_soap_request(token):
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the GetReports element
get_reports = ET.SubElement(
body, "GetReports", {"xmlns": "http://archer-tech.com/webservices/"}
)
# Add the sessionToken element
ET.SubElement(get_reports, "sessionToken").text = token
return ET.tostring(root)
def get_statistic_search_report_soap_request(token, report_guid, max_results):
# Create the root element
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the ExecuteStatisticSearchByReport element
execute_statistic_search = ET.SubElement(
body,
"ExecuteStatisticSearchByReport",
{"xmlns": "http://archer-tech.com/webservices/"},
)
# Add the sessionToken, reportIdOrGuid and pageNumber elements
ET.SubElement(execute_statistic_search, "sessionToken").text = token
ET.SubElement(execute_statistic_search, "reportIdOrGuid").text = report_guid
ET.SubElement(execute_statistic_search, "pageNumber").text = str(max_results)
return ET.tostring(root)
def get_search_options_soap_request(token, report_guid):
# Create the root element
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the GetSearchOptionsByGuid element
get_search_options_by_grid = ET.SubElement(
body, "GetSearchOptionsByGuid", {"xmlns": "http://archer-tech.com/webservices/"}
)
# Add the sessionToken and searchReportGuid elements
ET.SubElement(get_search_options_by_grid, "sessionToken").text = token
ET.SubElement(get_search_options_by_grid, "searchReportGuid").text = report_guid
return ET.tostring(root)
def search_records_by_report_soap_request(token, report_guid):
# Create the root element
root = ET.Element(
"soap:Envelope",
{
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
},
)
# Create the soap:Body element
body = ET.SubElement(root, "soap:Body")
# Create the SearchRecordsByReport element
search_records_by_report = ET.SubElement(
body, "SearchRecordsByReport", {"xmlns": "http://archer-tech.com/webservices/"}
)
# Add the sessionToken, reportIdOrGuid and pageNumber elements
ET.SubElement(search_records_by_report, "sessionToken").text = token
ET.SubElement(search_records_by_report, "reportIdOrGuid").text = report_guid
ET.SubElement(search_records_by_report, "pageNumber").text = "1"
return ET.tostring(root)
def search_records_soap_request(
token,
app_id,
display_fields,
field_id,
field_name,
search_value,
date_operator="",
field_to_search_by_id="",
numeric_operator="",
max_results=10,
level_id="",
sort_type: str = "Ascending",
):
# CDATA is not supported in Element Tree, therefore keeping original structure.
request_body = (
'<?xml version="1.0" encoding="UTF-8"?>'
+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" '
'xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
+ " <soap:Body>"
+ ' <ExecuteSearch xmlns="http://archer-tech.com/webservices/">'
+ f" <sessionToken>{token}</sessionToken>"
+ " <searchOptions>"
+ " <![CDATA[<SearchReport>"
+ f" <PageSize>{max_results}</PageSize>"
+ " <PageNumber>1</PageNumber>"
+ f" <MaxRecordCount>{max_results}</MaxRecordCount>"
+ " <ShowStatSummaries>false</ShowStatSummaries>"
+ f" <DisplayFields>{display_fields}</DisplayFields>"
+ f' <Criteria><ModuleCriteria><Module name="appname">{app_id}</Module></ModuleCriteria>'
)
if search_value:
request_body += "<Filter><Conditions>"
if date_operator:
request_body += (
"<DateComparisonFilterCondition>"
+ f" <Operator>{date_operator}</Operator>"
+ f' <Field name="{field_name}">{field_id}</Field>'
+ f" <Value>{search_value}</Value>"
+ " <TimeZoneId>UTC Standard Time</TimeZoneId>"
+ " <IsTimeIncluded>TRUE</IsTimeIncluded>"
+ "</DateComparisonFilterCondition >"
)
elif numeric_operator:
request_body += (
"<NumericFilterCondition>"
+ f" <Operator>{numeric_operator}</Operator>"
+ f' <Field name="{field_name}">{field_id}</Field>'
+ f" <Value>{search_value}</Value>"
+ "</NumericFilterCondition >"
)
else:
if (
field_to_search_by_id
and field_to_search_by_id.lower() == field_name.lower()
):
request_body += (
"<ContentFilterCondition>"
+ f" <Level>{level_id}</Level>"
+ " <Operator>Equals</Operator>"
+ f" <Values><Value>{search_value}</Value></Values>"
+ "</ContentFilterCondition>"
)
else:
request_body += (
"<TextFilterCondition>"
+ " <Operator>Contains</Operator>"
+ f' <Field name="{field_name}">{field_id}</Field>'
+ f" <Value>{search_value}</Value>"
+ "</TextFilterCondition >"
)
request_body += "</Conditions></Filter>"
if date_operator: # Fetch incidents must present date_operator
request_body += (
"<Filter>"
+ "<Conditions>"
+ " <DateComparisonFilterCondition>"
+ f" <Operator>{date_operator}</Operator>"
+ f' <Field name="{field_name}">{field_id}</Field>'
+ f" <Value>{search_value}</Value>"
+ " <TimeZoneId>UTC Standard Time</TimeZoneId>"
+ " <IsTimeIncluded>TRUE</IsTimeIncluded>"
+ " </DateComparisonFilterCondition >"
+ "</Conditions>"
+ "</Filter>"
)
if field_id:
request_body += (
"<SortFields>"
+ " <SortField>"
+ f" <Field>{field_id}</Field>"
+ f" <SortType>{sort_type}</SortType>"
+ " </SortField >"
+ "</SortFields>"
)
request_body += (
" </Criteria></SearchReport>]]>"
+ "</searchOptions>"
+ "<pageNumber>1</pageNumber>"
+ "</ExecuteSearch>"
+ "</soap:Body>"
+ "</soap:Envelope>"
)
return request_body
SOAP_COMMANDS = {
"archer-get-reports": {
"soapAction": "http://archer-tech.com/webservices/GetReports",
"urlSuffix": "ws/search.asmx",
"soapBody": get_reports_soap_request,
"outputPath": "Envelope.Body.GetReportsResponse.GetReportsResult",
},
"archer-execute-statistic-search-by-report": {
"soapAction": "http://archer-tech.com/webservices/ExecuteStatisticSearchByReport",
"urlSuffix": "ws/search.asmx",
"soapBody": get_statistic_search_report_soap_request,
"outputPath": "Envelope.Body.ExecuteStatisticSearchByReportResponse.ExecuteStatistic"
"SearchByReportResult",
},
"archer-get-search-options-by-guid": {
"soapAction": "http://archer-tech.com/webservices/GetSearchOptionsByGuid",
"urlSuffix": "ws/search.asmx",
"soapBody": get_search_options_soap_request,
"outputPath": "Envelope.Body.GetSearchOptionsByGuidResponse.GetSearchOptionsByGuidResult",
},
"archer-search-records": {
"soapAction": "http://archer-tech.com/webservices/ExecuteSearch",
"urlSuffix": "ws/search.asmx",
"soapBody": search_records_soap_request,
"outputPath": "Envelope.Body.ExecuteSearchResponse.ExecuteSearchResult",
},
"archer-search-records-by-report": {
"soapAction": "http://archer-tech.com/webservices/SearchRecordsByReport",
"urlSuffix": "ws/search.asmx",
"soapBody": search_records_by_report_soap_request,
"outputPath": "Envelope.Body.SearchRecordsByReportResponse.SearchRecordsByReportResult",
},
}
def merge_integration_context(new_dict):
old_context = get_integration_context()
old_context.update(new_dict)
set_integration_context(old_context)
def get_occurred_time(fields: List[dict] | dict, field_id: str) -> str:
"""
Occurred time is part of the raw 'Field' key in the response.
It should be under @xmlConvertedValue, but field can be both a list or a dict.
Arguments:
fields: Field to find the occurred utc time on
field_id: The @id in the response the time should be on
Returns:
Time of occurrence according to the field ID.
"""
try:
field_id = str(field_id) # In case it passed as a integer
if isinstance(fields, dict):
return fields["@xmlConvertedValue"]
else:
for field in fields:
if str(field["@id"]) == field_id: # In a rare case @id is an integer
return str(field["@xmlConvertedValue"])
raise KeyError(
"Could not find @xmlConvertedValue in record."
) # No xmlConvertedValue
except KeyError as exc:
raise DemistoException(
f"Could not find the property @xmlConvertedValue in field id {field_id}. Is that a date field?"
) from exc
class Client(BaseClient):
def __init__(
self, base_url, username, password, instance_name, domain, timeout, **kwargs
):
self.username = username
self.password = password
self.instance_name = instance_name
self.domain = domain
super().__init__(base_url=base_url, timeout=timeout, **kwargs)
def get_headers(self, create_new_session: bool = False):
"""
This function returns the relevant headers dict which also contains session id. In case the session doesn't exist in
context or the create_new_session flag is given, the session will ge re-generated using create_session().
In order to support some level of concurrency when running tasks simultaneously, the function has a small
sleeping mechanism to allow tasks to first try and use existing session before moving forward to create a new
one.
Args:
create_new_session (bool): whether to force creation of a new session
Returns:
dict: the dictionary containing the headers together with the session id.
"""
time.sleep(random.uniform(0, 5))
headers = REQUEST_HEADERS
context_session_id = get_integration_context().get("session_id")
session_id = (
self.create_session()
if create_new_session or not context_session_id
else context_session_id
)
headers["Authorization"] = f"Archer session-id={session_id}"
return headers
def try_rest_request(
self,
method,
url_suffix,
data=None,
params=None,
create_new_session=False,
attempts=1,
):
"""
This function perform several attempts to extract the necessary headers and call the Base client http request
function. If the create_new_session flag is given it will enforce the creation of a new session, otherwise it
will try to use the existing one.
Args:
method: (str) the HTTP method to use
url_suffix: (str) the url_suffix to use
data: (str) the to send in the json body
params: (str) the url parameters to send
create_new_session: (bool) whether to enforce creation of new session (will be true in case previous calls
returned 401)
attempts: (int) number of attempts to try with the given session extraction/method.
Returns:
requets.Response: the response object
"""
for _ in range(attempts):
headers = self.get_headers(create_new_session=create_new_session)
res = self._http_request(
method,
url_suffix,
headers=headers,
json_data=data,
params=params,
resp_type="response",
ok_codes=(200, 401),
)
demisto.debug(f"rest status code: {res.status_code}")
if 200 <= res.status_code <= 300:
break
return res
def do_rest_request(self, method, url_suffix, data=None, params=None):
"""
This function manages the REST API calls by calling the *try_rest_request* function twice:
- First without the *create_new_session* flag (this will cause *try_rest_request* to try and use exiting
session id if exists).
- In case of bad session (401), another call will be made with the *create_new_session* flag set to true
which performs force update of the session id.
Args:
method: (str) the HTTP method to use
url_suffix: (str) the url_suffix to use
data: (dict) the data to send in the json body
params: (dict) the url parameters to send
Returns:
dict: the response json object
"""
res = self.try_rest_request(
method=method, url_suffix=url_suffix, data=data, params=params, attempts=2
)
if res.status_code == 401:
demisto.debug("trying rest with new session")
res = self.try_rest_request(
method=method,
url_suffix=url_suffix,
data=data,
params=params,
create_new_session=True,
attempts=4,
)
return res.json()
def create_session(self):
body = {
"InstanceName": self.instance_name,
"Username": self.username,
"UserDomain": self.domain,
"Password": self.password,
}
try:
res = self._http_request(
"POST", f"{API_ENDPOINT}/core/security/login", json_data=body
)
except DemistoException as e:
if "<html>" in str(e):
raise DemistoException(
f"Check the given URL, it can be a redirect issue. Failed with error: {str(e)}"
)
raise e
is_successful_response = res.get("IsSuccessful")
if not is_successful_response:
return_error(res.get("ValidationMessages"))
session = res.get("RequestedObject", {}).get("SessionToken")
merge_integration_context({"session_id": session})
return session
def generate_token(self):
endpoint = (
"CreateDomainUserSessionFromInstance"
if self.domain
else "CreateUserSessionFromInstance"
)
body = get_token_soap_request(
self.username, self.password, self.instance_name, self.domain
)
headers = {
"SOAPAction": f"http://archer-tech.com/webservices/{endpoint}",
"Content-Type": "text/xml; charset=utf-8",
}
res = self._http_request(
"POST", "ws/general.asmx", headers=headers, data=body, resp_type="content"
)
token = extract_from_xml(
res, f"Envelope.Body.{endpoint}Response.{endpoint}Result"
)
merge_integration_context({"token": token})
return token
def update_body_with_token(
self, request_body_builder_function, create_new_token: bool = False, **kwargs
):
"""
This function returns the updated body dict which also contains api token. In case the token doesn't exist in
context or the create_new_token flag is given, the token will be re-generated using generate_token().
In order to support some level of concurrency when running tasks simultaneously, the function has a small
sleeping mechanism to allow tasks to first try and use existing session before moving forward to create a new
one.
Args:
request_body_builder_function (function): function to build the relevant request body
create_new_token (bool): whether to force creation of a new session
kwargs: (dict) dict of additional parameters relevant to the soap request.
Returns:
dict: the dictionary containing the necessary body together with the api token.
"""
time.sleep(random.uniform(0, 5))
context_token = get_integration_context().get("token")
token = (
self.generate_token()
if create_new_token or not context_token
else context_token
)
body = request_body_builder_function(token, **kwargs)
return body
def try_soap_request(
self, req_data, method, create_new_token=False, attempts=1, **kwargs
):
"""
This function perform several attempts to read/generate api token and call the Base client http request
function. If the create_new_token flag is given it will enforce the creation of a new token, otherwise it
will try to use the existing one.
Args:
method: (str) the HTTP method to use
req_data: (dict) dictionary containing API info relevant to the specific API request
create_new_token: (bool) whether to enforce creation of new session (will be true in case previous calls
returned 500)
attempts: (int) number of attempts to try with the given session extraction/method.
kwargs: (dict) dict of additional parameters relevant to the soap request.
Returns:
requets.Response: the response object
"""
headers = {
"SOAPAction": req_data["soapAction"],
"Content-Type": "text/xml; charset=utf-8",
}
request_body_builder_function = req_data["soapBody"]
url_suffix = req_data["urlSuffix"]
for _ in range(attempts):
body = self.update_body_with_token(
request_body_builder_function=request_body_builder_function,
create_new_token=create_new_token,
**kwargs,
)
res = self._http_request(
method=method,
url_suffix=url_suffix,
headers=headers,
data=body,
resp_type="response",
ok_codes=(200, 500),
)
demisto.debug(f"soap status code: {res.status_code}")
if 200 <= res.status_code <= 300:
return res
return res
def do_soap_request(self, command, **kwargs):
"""
This function manages the SOAP API calls by calling the *try_soap_request* function twice:
- First without the *create_new_token* flag (this will cause *try_soap_request* to try and use exiting
token if exists).
- In case of bad session (500), another call will be made with the *create_new_token* flag set to true
which performs force update of the token.
Args:
command: (str) the name of the command to use
kwargs: (dict) dict of additional parameters relevant to the soap request.
Returns:
dict: the relevant dict containing the data in the relevant path of the xml response
bytes: res.content
"""
req_data = SOAP_COMMANDS[command]
res = self.try_soap_request(
req_data=req_data, method="POST", attempts=2, **kwargs
)
if res.status_code == 500:
demisto.debug("trying soap with new session")
res = self.try_soap_request(
req_data=req_data,
method="POST",
create_new_token=True,
attempts=2,
**kwargs,
)
return extract_from_xml(res.content, req_data["outputPath"]), res.content
def get_level_by_app_id(self, app_id, specify_level_id=None):
levels = []
cache = get_integration_context()
if cache.get(app_id):
levels = cache[app_id]
else:
all_levels_res = self.do_rest_request(
"GET", f"{API_ENDPOINT}/core/system/level/module/{app_id}"
)
for level in all_levels_res:
if level.get("RequestedObject") and level.get("IsSuccessful"):
level_id = level.get("RequestedObject").get("Id")
fields = {}
level_res = self.do_rest_request(
"GET",
f"{API_ENDPOINT}/core/system/fielddefinition/level/{level_id}",
)
for field in level_res:
if field.get("RequestedObject") and field.get("IsSuccessful"):
field_item = field.get("RequestedObject")
field_id = str(field_item.get("Id"))
fields[field_id] = {
"Type": field_item.get("Type"),
"Name": field_item.get("Name"),
"FieldId": field_id,
"IsRequired": field_item.get("IsRequired", False),
"RelatedValuesListId": field_item.get(
"RelatedValuesListId"
),
}
levels.append({"level": level_id, "mapping": fields})
if levels:
cache[int(app_id)] = levels
merge_integration_context(cache)
level_data = None
if specify_level_id:
level_data = next(
(
level
for level in levels
if level.get("level") == int(specify_level_id)
),
None,
)
elif levels:
level_data = levels[0]
if not level_data:
raise DemistoException(
"Got no level by app id. You might be using the wrong application id or level id."
)
return level_data
def get_record(self, app_id, record_id, depth):
res = self.do_rest_request("GET", f"{API_ENDPOINT}/core/content/{record_id}")
if not isinstance(res, dict):
res = res.json()
errors = get_errors_from_res(res)
record = {}
if res.get("RequestedObject") and res.get("IsSuccessful"):
content_obj = res.get("RequestedObject")
level_id = content_obj.get("LevelId")
level = self.get_level_by_app_id(app_id, level_id)
if level:
level_fields = level["mapping"]
else:
return {}, res, errors
for i, (_id, field) in enumerate(content_obj.get("FieldContents").items()):
field_data = level_fields.get(str(_id), {}) # type: ignore
field_type = field_data.get("Type")
# when field type is IP Address
if field_type == 19:
field_value = field.get("IpAddressBytes")
# when field type is Values List
elif (
field_type == 4
and field.get("Value")
and field["Value"].get("ValuesListIds")
):
list_data = self.get_field_value_list(_id, depth)
list_ids = field["Value"]["ValuesListIds"]
list_ids = list(
filter(lambda x: x["Id"] in list_ids, list_data["ValuesList"])
)
field_value = [x["Name"] for x in list_ids]
else:
field_value = field.get("Value")
if field_value:
if not field_data.get("Name"):
demisto.debug(
f"{field_data.get('Name')=}\n{field_data.get('Value')=}"
)
record[
field_data.get("Name")
or self.get_field_value_name(_id)
or f"None-{i}"
] = field_value
record["Id"] = content_obj.get("Id")
return record, res, errors
@staticmethod
def record_to_incident(
record_item, app_id, fetch_param_id
) -> tuple[dict, datetime]:
"""Transform a record to incident
Args:
record_item: The record item dict
app_id: ID of the app
fetch_param_id: ID of the fetch param.
Returns:
incident, incident created time (UTC Time)
"""
labels = []
raw_record = record_item["raw"]
record_item = record_item["record"]
try:
occurred_time = get_occurred_time(raw_record["Field"], fetch_param_id)
except KeyError as exc:
raise DemistoException(
f'Could not find occurred time in record {record_item.get("Id")=}'
) from exc
# Will convert value to strs
for k, v in record_item.items():
if isinstance(v, str):
labels.append({"type": k, "value": v})
else:
labels.append({"type": k, "value": json.dumps(v)})
labels.append({"type": "ModuleId", "value": app_id})
labels.append({"type": "ContentId", "value": record_item.get("Id")})
labels.append({"type": "rawJSON", "value": json.dumps(raw_record)})
incident = {
"name": f'RSA Archer Incident: {record_item.get("Id")}',
"details": json.dumps(record_item),
"occurred": occurred_time,
"labels": labels,
"rawJSON": json.dumps(raw_record),
}
return incident, parser(occurred_time)
def search_records(
self,
app_id,
fields_to_display=None,
field_to_search="",
search_value="",
field_to_search_by_id="",
numeric_operator="",
date_operator="",
max_results=10,
sort_type: str = "Ascending",
):
demisto.debug(f"searching for records {field_to_search}:{search_value}")
if fields_to_display is None:
fields_to_display = []
level_data = self.get_level_by_app_id(app_id)
# Building request fields
fields_xml = ""
search_field_name = ""
search_field_id = ""
fields_mapping = level_data["mapping"]
level_id = level_data["level"]
for field in fields_mapping:
field_name = fields_mapping[field]["Name"]
if field_name in fields_to_display:
fields_xml += (
f'<DisplayField name="{field_name}">{field}</DisplayField>'
)
if (field_to_search and field_name.lower() == field_to_search.lower()) or (
field_to_search_by_id
and field_name.lower() == field_to_search_by_id.lower()
):
search_field_name = field_name
search_field_id = field
res, raw_res = self.do_soap_request(
"archer-search-records",
app_id=app_id,
display_fields=fields_xml,
field_id=search_field_id,
field_name=search_field_name,
field_to_search_by_id=field_to_search_by_id,
numeric_operator=numeric_operator,
date_operator=date_operator,
search_value=search_value,
max_results=max_results,
sort_type=sort_type,
level_id=level_id,
)
if not res:
return [], raw_res
records = self.xml_to_records(res, fields_mapping)
return records, raw_res
def xml_to_records(self, xml_response, fields_mapping):
res = json.loads(xml2json(xml_response))
records = []
if res.get("Records") and res["Records"].get("Record"):
records_data = res["Records"]["Record"]
if isinstance(records_data, dict):
records_data = [records_data]
for item in records_data:
record = {"Id": item.get("@contentId")}
record_fields = item.get("Field")
if isinstance(record_fields, dict):
record_fields = [record_fields]
for field in record_fields:
field_name = fields_mapping[field.get("@id")]["Name"]
field_type = field.get("@type")
field_value = ""
if field_type == "3":
field_value = field.get("@xmlConvertedValue")
elif field_type == "4":
if field.get("ListValues"):
field_value = field["ListValues"]["ListValue"][
"@displayName"
]
elif field_type == "8":
field_value = json.dumps(field)
else:
field_value = field.get("#text")
record[field_name] = field_value
records.append({"record": record, "raw": item})
return records
def get_field_value_list_helper(self, child, values_list, depth, parent="root"):
values_list.append(
{
"Id": child["Data"]["Id"],
"Name": child["Data"]["Name"],
"IsSelectable": child["Data"]["IsSelectable"],
"Parent": parent,
"Depth": child.get("Depth"),
}
)
depth -= 1
if depth > -1:
for grandchild in child.get("Children", []):
self.get_field_value_list_helper(
grandchild, values_list, depth, child["Data"]["Name"]
)
def get_field_value_list(self, field_id, depth=0):
cache = get_integration_context()
if cache["fieldValueList"].get(field_id):
return cache.get("fieldValueList").get(field_id)
res = self.do_rest_request(
"GET", f"{API_ENDPOINT}/core/system/fielddefinition/{field_id}"
)
errors = get_errors_from_res(res)
if errors:
return_error(errors)
if res.get("RequestedObject") and res.get("IsSuccessful"):
if res.get("RequestedObject").get("Type") != 4:
raise Exception(
'The command returns values only for fields of type "Values List".\n'
)
list_id = res["RequestedObject"]["RelatedValuesListId"]
values_list_res = self.do_rest_request(
"GET",
f"{API_ENDPOINT}/core/system/valueslistvalue/valueslist/{list_id}",
)
if values_list_res.get("RequestedObject") and values_list_res.get(
"IsSuccessful"
):
values_list: List[dict[str, Any]] = []
for value in values_list_res["RequestedObject"].get("Children", ()):
self.get_field_value_list_helper(value, values_list, depth)
field_data = {"FieldId": field_id, "ValuesList": values_list}
cache["fieldValueList"][field_id] = field_data
merge_integration_context(cache)
return field_data
return {}
def get_field_value_name(self, field_id):
cache = get_integration_context()
if cache["fieldValueNames"].get(field_id):
return cache.get("fieldValueNames").get(field_id)
res = self.do_rest_request(
"GET", f"{API_ENDPOINT}/core/system/fielddefinition/{field_id}"
)
errors = get_errors_from_res(res)
if errors:
return_error(errors)
if res.get("RequestedObject") and res.get("IsSuccessful"):
field_obj = res["RequestedObject"]
cache["fieldValueNames"][field_obj.get("Id")] = field_obj.get("Name")
merge_integration_context(cache)
return field_obj.get("Name")
return field_id
def get_field_id(self, app_id: str, field_name: str) -> str:
"""Get field ID by field name
Args:
app_id: app id to search on
field_name: field name to search on
Raises:
DemistoException: If could not find field ID
Returns:
The ID of the field
"""
fields, _ = self.get_application_fields(app_id)
for field in fields:
if field_name == field.get("FieldName"):