-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
CoreIRApiModule_test.py
3699 lines (3167 loc) · 127 KB
/
CoreIRApiModule_test.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 copy
from freezegun import freeze_time
import json
import os
import zipfile
from typing import Any
from pytest_mock import MockerFixture
import pytest
import demistomock as demisto
from CommonServerPython import Common, tableToMarkdown, pascalToSpace, DemistoException
from CoreIRApiModule import CoreClient
from CoreIRApiModule import add_tag_to_endpoints_command, remove_tag_from_endpoints_command, quarantine_files_command, \
isolate_endpoint_command, list_user_groups_command, parse_user_groups, list_users_command, list_roles_command, \
change_user_role_command, list_risky_users_or_host_command, enrich_error_message_id_group_role
test_client = CoreClient(
base_url='https://test_api.com/public_api/v1', headers={}
)
Core_URL = 'https://api.xdrurl.com'
''' HELPER FUNCTIONS '''
def load_test_data(json_path):
with open(json_path) as f:
return json.load(f)
def get_incident_extra_data_by_status(incident_id, alerts_limit):
"""
The function simulate the client.get_incident_extra_data method for the test_fetch_incidents_filtered_by_status.
The function got the incident_id, and return the json file by the incident id.
"""
if incident_id == '1':
incident_extra_data = load_test_data('./test_data/get_incident_extra_data.json')
else:
incident_extra_data = load_test_data('./test_data/get_incident_extra_data_new_status.json')
return incident_extra_data['reply']
''' TESTS FUNCTIONS '''
# Note this test will fail when run locally (in pycharm/vscode)
# as it assumes the machine (docker image) has UTC timezone set
@pytest.mark.parametrize(argnames='time_to_convert, expected_value',
argvalues=[('1322683200000', 1322683200000),
('2018-11-06T08:56:41', 1541494601000)])
def test_convert_time_to_epoch(time_to_convert, expected_value):
from CoreIRApiModule import convert_time_to_epoch
assert convert_time_to_epoch(time_to_convert) == expected_value
def return_extra_data_result(*args):
if args[1].get('incident_id') == '2':
raise Exception("Rate limit exceeded")
else:
incident_from_extra_data_command = load_test_data('./test_data/incident_example_from_extra_data_command.json')
return {}, {}, {"incident": incident_from_extra_data_command}
def test_get_endpoints(requests_mock):
from CoreIRApiModule import get_endpoints_command, CoreClient
get_endpoints_response = load_test_data('./test_data/get_endpoints.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json=get_endpoints_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'hostname': 'foo',
'page': 1,
'limit': 3
}
res = get_endpoints_command(client, args)
assert get_endpoints_response.get('reply').get('endpoints') == \
res.outputs['CoreApiModule.Endpoint(val.endpoint_id == obj.endpoint_id)']
def test_get_all_endpoints_using_limit(requests_mock):
"""
Given:
The default arguments for the get endpoints command: limit = 1, page = 0, sort_order = 'asc'.
When:
Calling the get_endpoints_command function
Then:
a. Make sure the 'get_endpoints' API is not called (not to be confused with get_endpoint - see last comment
here: https://jira-hq.paloaltonetworks.local/browse/XSUP-15995)
b. Make sure the returned result as in the expected format.
"""
from CoreIRApiModule import get_endpoints_command, CoreClient
get_endpoints_response = load_test_data('./test_data/get_all_endpoints.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json=get_endpoints_response)
get_endpoints_mock = requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoints/')
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'limit': 1,
'page': 0,
'sort_order': 'asc'
}
res = get_endpoints_command(client, args)
expected_endpoint = get_endpoints_response.get('reply').get('endpoints')
assert not get_endpoints_mock.called
assert res.outputs['CoreApiModule.Endpoint(val.endpoint_id == obj.endpoint_id)'] == expected_endpoint
def test_endpoint_command(requests_mock):
from CoreIRApiModule import endpoint_command, CoreClient
get_endpoints_response = load_test_data('./test_data/get_endpoints.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json=get_endpoints_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {'id': 'identifier'}
outputs = endpoint_command(client, args)
get_endpoints_response = {
Common.Endpoint.CONTEXT_PATH: [{'ID': '1111',
'Hostname': 'ip-3.3.3.3',
'IPAddress': '3.3.3.3',
'OS': 'Linux',
'Vendor': 'CoreApiModule',
'Status': 'Online',
'IsIsolated': 'No'}]}
results = outputs[0].to_context()
for key, value in results.get("EntryContext", {}).items():
assert get_endpoints_response[key] == value
assert results.get("EntryContext") == get_endpoints_response
def test_isolate_endpoint(requests_mock):
from CoreIRApiModule import isolate_endpoint_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json={
'reply': {
'endpoints': [
{
'endpoint_id': '1111',
"endpoint_status": "CONNECTED"
}
]
}
})
isolate_endpoint_response = load_test_data('./test_data/isolate_endpoint.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/isolate', json=isolate_endpoint_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"endpoint_id": "1111"
}
res = isolate_endpoint_command(client, args)
assert res.readable_output == 'The isolation request has been submitted successfully on Endpoint 1111.\n'
def test_isolate_endpoint_unconnected_machine(requests_mock, mocker):
from CoreIRApiModule import isolate_endpoint_command, CoreClient
# return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json={
'reply': {
'endpoints': [
{
'endpoint_id': '1111',
"endpoint_status": "DISCONNECTED"
}
]
}
})
isolate_endpoint_response = load_test_data('./test_data/isolate_endpoint.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/isolate', json=isolate_endpoint_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"endpoint_id": "1111",
"suppress_disconnected_endpoint_error": False
}
with pytest.raises(ValueError, match='Error: Endpoint 1111 is disconnected and therefore can not be isolated.'):
isolate_endpoint_command(client, args)
def test_unisolate_endpoint(requests_mock):
from CoreIRApiModule import unisolate_endpoint_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json={
'reply': {
'endpoints': [
{
'endpoint_id': '1111',
"endpoint_status": "CONNECTED"
}
]
}
})
unisolate_endpoint_response = load_test_data('./test_data/unisolate_endpoint.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/unisolate', json=unisolate_endpoint_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"endpoint_id": "1111"
}
res = unisolate_endpoint_command(client, args)
assert res.readable_output == 'The un-isolation request has been submitted successfully on Endpoint 1111.\n'
def test_unisolate_endpoint_unconnected_machine(requests_mock):
from CoreIRApiModule import unisolate_endpoint_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json={
'reply': {
'endpoints': [
{
'endpoint_id': '1111',
"endpoint_status": "DISCONNECTED"
}
]
}
})
unisolate_endpoint_response = load_test_data('./test_data/unisolate_endpoint.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/unisolate', json=unisolate_endpoint_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"endpoint_id": "1111",
"suppress_disconnected_endpoint_error": True
}
res = unisolate_endpoint_command(client, args)
assert res.readable_output == 'Warning: un-isolation action is pending for the following disconnected endpoint: 1111.'
def test_unisolate_endpoint_pending_isolation(requests_mock):
from CoreIRApiModule import unisolate_endpoint_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_endpoint/', json={
'reply': {
'endpoints': [
{
'endpoint_id': '1111',
"is_isolated": "AGENT_PENDING_ISOLATION"
}
]
}
})
unisolate_endpoint_response = load_test_data('./test_data/unisolate_endpoint.json')
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/unisolate', json=unisolate_endpoint_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"endpoint_id": "1111"
}
with pytest.raises(ValueError, match='Error: Endpoint 1111 is pending isolation and therefore can not be'
' un-isolated.'):
unisolate_endpoint_command(client, args)
def test_get_distribution_url(requests_mock):
from CoreIRApiModule import get_distribution_url_command, CoreClient
get_distribution_url_response = load_test_data('./test_data/get_distribution_url.json')
requests_mock.post(f'{Core_URL}/public_api/v1/distributions/get_dist_url/', json=get_distribution_url_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'distribution_id': '1111',
'package_type': 'x86'
}
readable_output, outputs, _ = get_distribution_url_command(client, args)
expected_url = get_distribution_url_response.get('reply').get('distribution_url')
assert outputs == {
'CoreApiModule.Distribution(val.id == obj.id)': {
'id': '1111',
'url': expected_url
}
}
assert readable_output == f'[Distribution URL]({expected_url})'
def test_get_audit_management_logs(requests_mock):
from CoreIRApiModule import get_audit_management_logs_command, CoreClient
get_audit_management_logs_response = load_test_data('./test_data/get_audit_management_logs.json')
requests_mock.post(f'{Core_URL}/public_api/v1/audits/management_logs/', json=get_audit_management_logs_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'email': 'woo@demisto.com',
'limit': '3',
'timestamp_gte': '3 month'
}
readable_output, outputs, _ = get_audit_management_logs_command(client, args)
expected_outputs = get_audit_management_logs_response.get('reply').get('data')
assert outputs['CoreApiModule.AuditManagementLogs(val.AUDIT_ID == obj.AUDIT_ID)'] == expected_outputs
def test_get_audit_agent_reports(requests_mock):
from CoreIRApiModule import get_audit_agent_reports_command, CoreClient
get_audit_agent_reports_response = load_test_data('./test_data/get_audit_agent_report.json')
requests_mock.post(f'{Core_URL}/public_api/v1/audits/agents_reports/', json=get_audit_agent_reports_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'endpoint_names': 'woo.demisto',
'limit': '3',
'timestamp_gte': '3 month'
}
readable_output, outputs, _ = get_audit_agent_reports_command(client, args)
expected_outputs = get_audit_agent_reports_response.get('reply').get('data')
assert outputs['CoreApiModule.AuditAgentReports'] == expected_outputs
assert outputs['Endpoint(val.ID && val.ID == obj.ID && val.Vendor == obj.Vendor)'] == [
{'ID': '1111', 'Hostname': '1111.eu-central-1'},
{'ID': '1111', 'Hostname': '1111.eu-central-1'},
{'ID': '1111', 'Hostname': '1111.eu-central-1'}]
def test_get_distribution_status(requests_mock):
from CoreIRApiModule import get_distribution_status_command, CoreClient
get_distribution_status_response = load_test_data('./test_data/get_distribution_status.json')
requests_mock.post(f'{Core_URL}/public_api/v1/distributions/get_status/', json=get_distribution_status_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"distribution_ids": "588a56de313549b49d70d14d4c1fd0e3"
}
readable_output, outputs, _ = get_distribution_status_command(client, args)
assert outputs == {
'CoreApiModule.Distribution(val.id == obj.id)': [
{
'id': '588a56de313549b49d70d14d4c1fd0e3',
'status': 'Completed'
}
]
}
def test_get_distribution_versions(requests_mock):
from CoreIRApiModule import get_distribution_versions_command, CoreClient
get_distribution_versions_response = load_test_data('./test_data/get_distribution_versions.json')
requests_mock.post(f'{Core_URL}/public_api/v1/distributions/get_versions/', json=get_distribution_versions_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
readable_output, outputs, _ = get_distribution_versions_command(client, args={})
assert outputs == {
'CoreApiModule.DistributionVersions': {
"windows": [
"7.0.0.27797"
],
"linux": [
"7.0.0.1915"
],
"macos": [
"7.0.0.1914"
]
}
}
def test_create_distribution(requests_mock):
from CoreIRApiModule import create_distribution_command, CoreClient
create_distribution_response = load_test_data('./test_data/create_distribution.json')
requests_mock.post(f'{Core_URL}/public_api/v1/distributions/create/', json=create_distribution_response)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
"name": "dfslcxe",
"platform": "windows",
"package_type": "standalone",
"agent_version": "7.0.0.28644"
}
readable_output, outputs, _ = create_distribution_command(client, args)
expected_distribution_id = create_distribution_response.get('reply').get('distribution_id')
assert outputs == {
'CoreApiModule.Distribution(val.id == obj.id)': {
'id': expected_distribution_id,
"name": "dfslcxe",
"platform": "windows",
"package_type": "standalone",
"agent_version": "7.0.0.28644",
'description': None
}
}
assert readable_output == f'Distribution {expected_distribution_id} created successfully'
def test_blocklist_files_command_with_more_than_one_file(requests_mock):
"""
Given:
- List of files' hashes to put in blocklist
When
- A user desires to mark more than one file
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import blocklist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.blocklist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['multi_command_args']['hash_list']
}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/blocklist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = blocklist_files_command(client, test_data['multi_command_args'])
assert expected_command_result == res.outputs
def test_blocklist_files_command_with_single_file(requests_mock):
"""
Given:
- List of a file hashes to put in blocklist.
When
- A user desires to blocklist one file.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import blocklist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.blocklist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['single_command_args']['hash_list']}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/blocklist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = blocklist_files_command(client, test_data['single_command_args'])
assert expected_command_result == res.outputs
def test_blocklist_files_command_with_no_comment_file(requests_mock):
"""
Given:
- List of files' hashes to put in blocklist without passing the comment argument.
When
- A user desires to blocklist files without adding a comment.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import blocklist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.blocklist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['no_comment_command_args']['hash_list']}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/blocklist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = blocklist_files_command(client, test_data['no_comment_command_args'])
assert expected_command_result == res.outputs
def test_allowlist_files_command_with_more_than_one_file(requests_mock):
"""
Given:
- List of files' hashes to put in allowlist
When
- A user desires to mark more than one file
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import allowlist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.allowlist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['multi_command_args']['hash_list']
}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/allowlist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = allowlist_files_command(client, test_data['multi_command_args'])
assert expected_command_result == res.outputs
def test_allowlist_files_command_with_single_file(requests_mock):
"""
Given:
- List of a file hashes to put in allowlist.
When
- A user desires to allowlist one file.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import allowlist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.allowlist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['single_command_args']['hash_list']}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/allowlist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = allowlist_files_command(client, test_data['single_command_args'])
assert expected_command_result == res.outputs
def test_allowlist_files_command_with_no_comment_file(requests_mock):
"""
Given:
- List of files' hashes to put in allowlist without passing the comment argument.
When
- A user desires to allowlist files without adding a comment.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import allowlist_files_command, CoreClient
test_data = load_test_data('test_data/blocklist_allowlist_files_success.json')
expected_command_result = {
'CoreApiModule.allowlist.added_hashes.fileHash(val.fileHash == obj.fileHash)':
test_data['no_comment_command_args'][
'hash_list']}
requests_mock.post(f'{Core_URL}/public_api/v1/hash_exceptions/allowlist/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = allowlist_files_command(client, test_data['no_comment_command_args'])
assert expected_command_result == res.outputs
def test_quarantine_files_command(requests_mock):
"""
Given:
- List of files' hashes to put in quarantine
When
- A user desires to quarantine files.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import quarantine_files_command, CoreClient
test_data = load_test_data('test_data/quarantine_files.json')
quarantine_files_expected_tesult = {
'CoreApiModule.quarantineFiles.actionIds(val.actionId === obj.actionId)': test_data['context_data']}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/quarantine/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = quarantine_files_command(client, test_data['command_args'])
assert quarantine_files_expected_tesult == res.outputs
def test_get_quarantine_status_command(requests_mock):
"""
Given:
- Endpoint_id, file_path, file_hash
When
- A user desires to check a file's quarantine status.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import get_quarantine_status_command, CoreClient
test_data = load_test_data('test_data/get_quarantine_status.json')
quarantine_files_expected_tesult = {
'CoreApiModule.quarantineFiles.status(val.fileHash === obj.fileHash &&val.endpointId'
' === obj.endpointId && val.filePath === obj.filePath)':
test_data['context_data']}
requests_mock.post(f'{Core_URL}/public_api/v1/quarantine/status/', json=test_data['api_response'])
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = get_quarantine_status_command(client, test_data['command_args'])
assert quarantine_files_expected_tesult == res.outputs
def test_restore_file_command(requests_mock):
"""
Given:
- file_hash
When
- A user desires to restore a file.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import restore_file_command, CoreClient
restore_expected_tesult = {'CoreApiModule.restoredFiles.actionId(val.actionId == obj.actionId)': 123}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/restore/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = restore_file_command(client, {"file_hash": "123"})
assert restore_expected_tesult == res.outputs
def test_endpoint_scan_command(requests_mock):
"""
Given:
- endpoint_id_list, dist_name, gte_first_seen, gte_last_seen, lte_first_seen, lte_last_seen, ip_list,
group_name, platform, alias, isolate, hostname
When
- A user desires to scan endpoint.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import endpoint_scan_command, CoreClient
test_data = load_test_data('test_data/scan_endpoints.json')
scan_expected_tesult = {'CoreApiModule.endpointScan(val.actionId == obj.actionId)': {'actionId': 123,
'aborted': False}}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = endpoint_scan_command(client, test_data['command_args'])
assert scan_expected_tesult == res.outputs
def test_endpoint_scan_command_scan_all_endpoints(requests_mock):
"""
Given:
- the filter all as true.
When
- A user desires to scan all endpoints.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import endpoint_scan_command, CoreClient
test_data = load_test_data('test_data/scan_all_endpoints.json')
scan_expected_tesult = {'CoreApiModule.endpointScan(val.actionId == obj.actionId)': {'actionId': 123,
'aborted': False}}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = endpoint_scan_command(client, test_data['command_args'])
assert scan_expected_tesult == res.outputs
def test_endpoint_scan_command_scan_all_endpoints_no_filters_error(requests_mock):
"""
Given:
- No filters.
When
- A user desires to scan all endpoints but without the correct argumetns.
Then
- raise a descriptive error.
"""
from CoreIRApiModule import endpoint_scan_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
err_msg = 'To scan/abort scan all the endpoints run this command with the \'all\' argument as True ' \
'and without any other filters. This may cause performance issues.\n' \
'To scan/abort scan some of the endpoints, please use the filter arguments.'
with pytest.raises(Exception, match=err_msg):
endpoint_scan_command(client, {})
def test_endpoint_scan_abort_command_scan_all_endpoints_no_filters_error(requests_mock):
"""
Given:
- No filters.
When
- A user desires to abort scan on all endpoints but without the correct arguments.
Then
- raise a descriptive error.
"""
from CoreIRApiModule import endpoint_scan_abort_command, CoreClient
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/abort_scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
err_msg = 'To scan/abort scan all the endpoints run this command with the \'all\' argument as True ' \
'and without any other filters. This may cause performance issues.\n' \
'To scan/abort scan some of the endpoints, please use the filter arguments.'
with pytest.raises(Exception, match=err_msg):
endpoint_scan_abort_command(client, {})
def test_endpoint_scan_abort_command(requests_mock):
"""
Given:
- endpoint_id_list, dist_name, gte_first_seen, gte_last_seen, lte_first_seen, lte_last_seen, ip_list,
group_name, platform, alias, isolate, hostname
When
- A user desires to abort scan endpoint.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import endpoint_scan_abort_command, CoreClient
test_data = load_test_data('test_data/scan_endpoints.json')
scan_expected_tesult = {'CoreApiModule.endpointScan(val.actionId == obj.actionId)': {'actionId': 123,
'aborted': True}}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/abort_scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = endpoint_scan_abort_command(client, test_data['command_args'])
assert scan_expected_tesult == res.outputs
def test_endpoint_scan_abort_command_all_endpoints(requests_mock):
"""
Given:
- the filter all as true.
When
- A user desires to abort scan for all endpoints.
Then
- returns markdown, context data and raw response.
"""
from CoreIRApiModule import endpoint_scan_abort_command, CoreClient
test_data = load_test_data('test_data/scan_all_endpoints.json')
scan_expected_tesult = {'CoreApiModule.endpointScan(val.actionId == obj.actionId)': {'actionId': 123,
'aborted': True}}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/abort_scan/', json={"reply": {"action_id": 123}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
client._headers = {}
res = endpoint_scan_abort_command(client, test_data['command_args'])
assert scan_expected_tesult == res.outputs
def test_get_update_args_unassgning_user(mocker):
"""
Given:
- a dict indicating changed fields (delta) with assigned_user_mail set to "None"
- the incident status - set to 1 == Active
When
- running get_update_args
Then
- update_args have assigned_user_mail and assigned_user_pretty_name set to None and unassign_user set to 'true'
"""
from CoreIRApiModule import get_update_args
from CommonServerPython import UpdateRemoteSystemArgs
mocker.patch('CoreIRApiModule.handle_outgoing_issue_closure')
remote_args = UpdateRemoteSystemArgs({'delta': {'assigned_user_mail': 'None'}})
update_args = get_update_args(remote_args)
assert update_args.get('assigned_user_mail') is None
assert update_args.get('assigned_user_pretty_name') is None
assert update_args.get('unassign_user') == 'true'
def test_get_update_args_close_incident():
"""
Given:
- a dict indicating changed fields (delta) with closeReason set to Other and a closeNotes
- the incident status - set to 2 == Closed
- the current status of the remote incident are 'new'
When
- running get_update_args
Then
- update_args status has the correct status (resolved_other)
- the resolve_comment is the same as the closeNotes
"""
from CoreIRApiModule import get_update_args
from CommonServerPython import UpdateRemoteSystemArgs
remote_args = UpdateRemoteSystemArgs({
'delta': {'closeReason': 'Other', "closeNotes": "Not Relevant", 'closingUserId': 'admin'},
'data': {'status': 'new'},
'status': 2}
)
update_args = get_update_args(remote_args)
assert update_args.get('status') == 'resolved_other'
assert update_args.get('resolve_comment') == 'Not Relevant'
def test_get_update_args_owner_sync(mocker):
"""
Given:
- a dict indicating changed fields (delta) with a change in owner
- the incident status - set to 2 == Close
When
- running get_update_args
Then
- update_args assigned_user_mail has the correct associated mail
"""
from CoreIRApiModule import get_update_args
from CommonServerPython import UpdateRemoteSystemArgs
remote_args = UpdateRemoteSystemArgs({
'delta': {'owner': 'username'},
'data': {'status': 'new'}}
)
mocker.patch.object(demisto, 'params', return_value={"sync_owners": True, "mirror_direction": "Incoming"})
mocker.patch.object(demisto, 'findUser', return_value={"email": "moo@demisto.com", 'username': 'username'})
update_args = get_update_args(remote_args)
assert update_args.get('assigned_user_mail') == 'moo@demisto.com'
def test_get_policy(requests_mock):
"""
Given:
-endpoint_id
When:
-Retrieving the policy name of the requested actions according to the specific endpoint.
Then:
- Assert the returned markdown, context data and raw response are as expected.
"""
from CoreIRApiModule import get_policy_command, CoreClient
expected_context = {
'endpoint_id': 'aeec6a2cc92e46fab3b6f621722e9916',
'policy_name': 'test'
}
run_script_expected_result = {'CoreApiModule.Policy(val.endpoint_id == obj.endpoint_id)': expected_context}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/get_policy/', json={'reply': {
'policy_name': 'test'}})
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'endpoint_id': 'aeec6a2cc92e46fab3b6f621722e9916'
}
hr, context, raw_response = get_policy_command(client, args)
assert hr == 'The policy name of endpoint: aeec6a2cc92e46fab3b6f621722e9916 is: test.'
assert run_script_expected_result == context
assert raw_response == {'policy_name': 'test'}
def test_get_endpoint_device_control_violations_command(requests_mock):
"""
Given:
- violation_id_list='100'
When:
- Request for list of device control violations filtered by selected fields.
You can retrieve up to 100 violations.
Then:
- Assert the returned markdown, context data and raw response are as expected.
"""
from CoreIRApiModule import get_endpoint_device_control_violations_command, CoreClient
from CommonServerPython import timestamp_to_datestring, tableToMarkdown, string_to_table_header
get_endpoint_violations_reply = load_test_data('./test_data/get_endpoint_violations.json')
violations = get_endpoint_violations_reply.get('reply').get('violations')
for violation in violations:
timestamp = violation.get('timestamp')
violation['date'] = timestamp_to_datestring(timestamp, '%Y-%m-%dT%H:%M:%S')
get_endpoint_violations_expected_result = {
'CoreApiModule.EndpointViolations(val.violation_id==obj.violation_id)':
violations
}
headers = ['date', 'hostname', 'platform', 'username', 'ip', 'type', 'violation_id', 'vendor', 'product',
'serial']
requests_mock.post(f'{Core_URL}/public_api/v1/device_control/get_violations/', json=get_endpoint_violations_reply)
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
args = {
'violation_id_list': '100'
}
hr, context, raw_response = get_endpoint_device_control_violations_command(client, args)
assert hr == tableToMarkdown(name='Endpoint Device Control Violation', t=violations, headers=headers,
headerTransform=string_to_table_header, removeNull=True)
assert context == get_endpoint_violations_expected_result
assert raw_response == get_endpoint_violations_reply.get('reply')
def test_retrieve_files_command(requests_mock):
"""
Given:
- endpoint_ids
- windows_file_paths
When
- A user desires to retrieve a file.
Then
- Assert the returned markdown, context data and raw response are as expected.
"""
from CoreIRApiModule import retrieve_files_command, CoreClient
from CommonServerPython import tableToMarkdown, string_to_table_header
retrieve_expected_result = {'action_id': 1773}
requests_mock.post(f'{Core_URL}/public_api/v1/endpoints/file_retrieval/', json={'reply': {'action_id': 1773}})
result = {'action_id': 1773}
client = CoreClient(
base_url=f'{Core_URL}/public_api/v1', headers={}
)
res = retrieve_files_command(client, {'endpoint_ids': 'aeec6a2cc92e46fab3b6f621722e9916',
'windows_file_paths': 'C:\\Users\\demisto\\Desktop\\demisto.txt'})
assert res.readable_output == tableToMarkdown(
name='Retrieve files', t=result, headerTransform=string_to_table_header)
assert res.outputs == retrieve_expected_result
assert res.raw_response == {'action_id': 1773}