forked from demisto/content
/
SplunkPy_test.py
1906 lines (1633 loc) · 81.5 KB
/
SplunkPy_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 demistomock as demisto
from CommonServerPython import *
import pytest
from copy import deepcopy
from collections import namedtuple
from datetime import timedelta, datetime
from splunklib.binding import AuthenticationError
from splunklib import client
from splunklib import results
import SplunkPy as splunk
RETURN_ERROR_TARGET = 'SplunkPy.return_error'
DICT_RAW_RESPONSE = '"1528755951, url="https://test.url.com", search_name="NG_SIEM_UC25- High number of hits against ' \
'unknown website from same subnet", action="allowed", dest="bb.bbb.bb.bbb , cc.ccc.ccc.cc , ' \
'xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa", distinct_hosts="5", ' \
'first_3_octets="1.1.1", first_time="06/11/18 17:34:07 , 06/11/18 17:37:55 , 06/11/18 17:41:28 , ' \
'06/11/18 17:42:05 , 06/11/18 17:42:38", info_max_time="+Infinity", info_min_time="0.000", ' \
'src="xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa", u_category="unknown", ' \
'user="xyz\\a1234 , xyz\\b5678 , xyz\\c91011 , xyz\\d121314 , unknown", website="2.2.2.2""'
DICT_RAW_RESPONSE_WITH_MESSAGE_ID = '"1528755951, message-id="1", url="https://test.url.com", ' \
'search_name="NG_SIEM_UC25- High number of hits against ' \
'unknown website from same subnet", action="allowed", dest="bb.bbb.bb.bbb , ' \
'cc.ccc.ccc.cc , xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa", ' \
'distinct_hosts="5", ' \
'first_3_octets="1.1.1", first_time="06/11/18 17:34:07 , ' \
'06/11/18 17:37:55 , 06/11/18 17:41:28 , ' \
'06/11/18 17:42:05 , 06/11/18 17:42:38", info_max_time="+Infinity", info_min_time="0.000", ' \
'src="xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa", u_category="unknown", ' \
'user="xyz\\a1234 , xyz\\b5678 , xyz\\c91011 , xyz\\d121314 , unknown", website="2.2.2.2""'
LIST_RAW = 'Feb 13 09:02:55 1,2020/02/13 09:02:55,001606001116,THREAT,url,' \
'1,2020/02/13 09:02:55,10.1.1.1,1.2.3.4,0.0.0.0,0.0.0.0,rule1,jordy,,web-browsing,vsys1,trust,untrust,' \
'ethernet1/2,ethernet1/1,forwardAll,2020/02/13 09:02:55,59460,1,62889,80,0,0,0x208000,tcp,alert,' \
'"ushship.com/xed/config.bin",(9999),not-resolved,informational,client-to-server,' \
'0,0x0,1.1.22.22-5.6.7.8,United States,0,text/html'
RAW_WITH_MESSAGE = '{"@timestamp":"2019-10-15T13:30:08.578-04:00","message":"{"TimeStamp":"2019-10-15 13:30:08",' \
'"CATEGORY_1":"CONTACT","ASSOCIATEOID":"G2N2TJETBRAAX68V","HOST":' \
'"step-up-authentication-api.gslb.es.oneadp.com","SCOPE[4]":"PiSvcsProvider\/payroll","SCOPE[19]":' \
'"\/api\/events\/core\/v1\/user-status","CONTEXT":"\/smsstepup","FLOW":"API","X-REAL-IP":' \
'"2.2.2.2","PRODUCT_CODE":"WFNPortal","X-FORWARDED-PROTO":"http","ERROR_ID":"4008",' \
'"SCOPE[23]":"\/security\/notification-communication-response-value.accept","REQ_URL":' \
'"http:\/\/step-up-authentication-api.gslb.es.blabla.com\/smsstepup\/events\/core\/v1\/step-up-' \
'user-authorization-request.evaluate","SCOPE[35]":"autopay\/payroll\/v1\/cafeteria-plan-' \
'configurations\/{configurationItemID}","SCOPE_MATCHED":"Y","SCOPE[43]":"communication\/n' \
'otification-message-template.add","SCOPE[11]":"\/ISIJWSUserSecurity","SCOPE[27]":"autopay\/events' \
'\/payroll\/v1\/earning-configuration.add","ORGOID":"G2SY6MR3ATKA232T","SCOPE[8]":"\/' \
'ISIJWSAssociatesService","SCOPE[39]":"autopay\/payroll\/v1\/earning-configurations",' \
'"SETUP_SELF":"N","SCOPE[47]":"communication\/notification.publish","SCOPE[15]":"' \
'\/OrganizationSoftPurge","X-FORWARDED-HOST":"step-up-authentication-api.gslb.es.blabla.com",' \
'"ADP-MESSAGEID":"a1d57ed2-1fe6-4800-be7a-26cd89bhello","CNAME":"JRJG INC","CONTENT-LENGTH":' \
'"584","SCOPE[31]":"autopay\/events\/payroll\/v1\/earning-configuration.remove","CID":"BSTAR00044"' \
',"ACTOR_UID":"ABinters@BSTAR00044","SECURE_API_MODE":"HTTPS_SECURE","X-REQUEST-ID":' \
'"2473a981bef27bc8444e510adc12234a","SCOPE[1]":"AVSSCP\/Docstash\/Download","SCOPE[18]":' \
'"\/api\/events\/core\/v1\/product-role.assign","BLOCK_SESSION":"Y","CONSUMER_ID":' \
'"ab2e715e-41c4-43d6-bff7-fc2d713hello","SCOPE[34]":"autopay\/payroll\/v1\/cafeteria-plan-' \
'configurations","SCOPE[46]":"communication\/notification-message-template.remove","MODULE":' \
'"STEPUP_API","SCOPE[9]":"\/ISIJWSClientService","SCOPE[10]":"\/ISIJWSJobsService","SCOPE[22]":' \
'"\/api\/person-account-registration","SCOPE[38]":"autopay\/payroll\/v1\/deposit-configurations",' \
'"SUBJECT_ORGOID":"G2SY6MR3ATKA232T","SCOPE[5]":"\/Associate","SCOPE[14]":"\/Organization",' \
'"SCOPE[26]":"WFNSvcsProvider\/payrollPi","EVENT_ID":"9ea87118-5679-5b0e-a67f-1abd8ccabcde",' \
'"SCOPE[30]":"autopay\/events\/payroll\/v1\/earning-configuration.payroll-accumulators.modify",' \
'"X-FORWARDED-PORT":"80","SCOPE[42]":"autopay\/payroll\/v1\/worker-employment-records","JTI":' \
'"867b6d06-47cf-40ab-8dd7-bd0d57babcde","X-DOMAIN":"secure.api.es.abc.com","SOR_CODE":' \
'"WFNPortal","SCOPE[29]":"autopay\/events\/payroll\/v1\/earning-configuration.configuration' \
'-tags.modify","SCOPE[2]":"AVSSCP\/Docstash\/Get","OUTPUT_TYPE":"FAIL","ERR_MSG":"BLOCK_SESSION",' \
'"TRANS_ID":"3AF-D30-7CTTCQ","SCOPE[45]":"communication\/notification-message-template.read",' \
'"USE_HISTORY":"Y","SCHEME":"http","SCOPE[13]":"\/ISIJWSUsersService","SCOPE[21]":"\/api\/person",' \
'"SCOPE[33]":"autopay\/events\/payroll\/v1\/worker-insurable-payments.modify","X-FORWARDED-FOR":' \
'"8.8.8.8, 10.10.10.10, 1.2.3.4, 5.6.7.8","SCOPE[17]":"\/api\/core\/v1\/organization",' \
'"SCOPE[25]":"\/step-up-user-authorization.initiate","SCOPE[6]":"\/Associate\/PIC","SCOPE[37]":' \
'"autopay\/payroll\/v1\/cafeteria-plan-configurations\/{configurationItemID}\/' \
'payroll-item-configurations\/{payrollItemID}","FLOW_TYPE":"REST","SCOPE[41]":' \
'"autopay\/payroll\/v1\/payroll-output","CONSUMERAPPOID":"WFNPortal","RESOURCE":' \
'"\/events\/core\/v1\/step-up-user-authorization-request.evaluate","USER-AGENT":' \
'"Apache-HttpClient\/4.5.5 (Java\/10.0.1)","SCOPE[3]":"AVSSCP\/Docstash\/List",' \
'"SUB_CATEGORY_1":"worker.businessCommunication.email.change","TIME":"9","X-SCHEME":' \
'"http","ADP-CONVERSATIONID":"stY46PpweABoT5JX04CZGCeBbX8=","SCOPE[12]":' \
'"\/ISIJWSUserSecurityService","SCOPE[24]":"\/step-up-user-authorization-request.evaluate",' \
'"SCOPE[32]":"autopay\/events\/payroll\/v1\/retro-pay-request.add","SCOPE[44]":' \
'"communication\/notification-message-template.change","ACTION":"POST","SCOPE[7]":' \
'"\/AssociateSoftPurge","SCOPE[16]":"\/api\/authentication","X-ORIGINAL-URI":' \
'"\/smsstepup\/events\/core\/v1\/step-up-user-authorization-request.evaluate","SCOPE[28]":' \
'"autopay\/events\/payroll\/v1\/earning-configuration.change","SCOPE[36]":' \
'"autopay\/payroll\/v1\/cafeteria-plan-configurations\/{configurationItemID}\/payroll-item' \
'-configurations","SESSION_ID":"f50be909-9e4f-408d-bf77-68499012bc35","SCOPE[20]":' \
'"\/api\/events\/core\/v1\/user.provision","SUBJECT_AOID":"G370XX6XYCABCDE",' \
'"X-ORIGINAL-FORWARDED-FOR":"1.1.1.1, 3.3.3.3, 4.4.4.4","SCOPE[40]":' \
'"autopay\/payroll\/v1\/employer-details"}","TXID":"3AF-D30-ABCDEF","ADP-MessageID":' \
'"a1d57ed2-1fe6-4800-be7a-26cd89bf686d","SESSIONID":"stY46PpweFToT5JX04CZGMeCvP8=","ORGOID":' \
'"G2SY6MR3ATKA232T","AOID":"G2N2TJETBRAAXAAA","MSGID":"a1d57ed2-1fe6-0000-be7a-26cd89bf686d"}'
SAMPLE_RESPONSE = [
results.Message("INFO-TEST", "test message"),
{
'_bkt': 'notable~668~66D21DF4-F4FD-4886-A986-82E72ADCBFE9',
'_cd': '668:17198',
'_indextime': '1596545116',
'_raw': '1596545116, search_name="Endpoint - Recurring Malware Infection - Rule", count="17", '
'day_count="8", dest="ACME-workstation-012", info_max_time="1596545100.000000000", '
'info_min_time="1595939700.000000000", info_search_time="1596545113.965466000", '
'signature="Trojan.Gen.2"',
'_serial': '50',
'_si': ['ip-172-31-44-193', 'notable'],
'_sourcetype': 'stash',
'_time': '2020-08-04T05:45:16.000-07:00',
'dest': 'ACME-workstation-012',
'dest_asset_id': '028877d3c80cb9d87900eb4f9c9601ea993d9b63',
'dest_asset_tag': ['cardholder', 'pci', 'americas'],
'dest_bunit': 'americas',
'dest_category': ['cardholder', 'pci'],
'dest_city': 'Pleasanton',
'dest_country': 'USA',
'dest_ip': '192.168.3.12',
'dest_is_expected': 'TRUE',
'dest_lat': '37.694452',
'dest_long': '-121.894461',
'dest_nt_host': 'ACME-workstation-012',
'dest_pci_domain': ['trust', 'cardholder'],
'dest_priority': 'medium',
'dest_requires_av': 'TRUE',
'dest_risk_object_type': 'system',
'dest_risk_score': '15680',
'dest_should_timesync': 'TRUE',
'dest_should_update': 'TRUE',
'host': 'ip-172-31-44-193',
'host_risk_object_type': 'system',
'host_risk_score': '0',
'index': 'notable',
'linecount': '1',
'priorities': 'medium',
'priority': 'medium',
'risk_score': '15680',
'rule_description': 'Endpoint - Recurring Malware Infection - Rule',
'rule_name': 'Endpoint - Recurring Malware Infection - Rule',
'rule_title': 'Endpoint - Recurring Malware Infection - Rule',
'security_domain': 'Endpoint - Recurring Malware Infection - Rule',
'severity': 'unknown',
'signature': 'Trojan.Gen.2',
'source': 'Endpoint - Recurring Malware Infection - Rule',
'sourcetype': 'stash',
'splunk_server': 'ip-172-31-44-193',
'urgency': 'low',
'owner': 'unassigned',
'event_id': '66D21DF4-F4FD-4886-A986-82E72ADCBFE9@@notable@@5aa44496ec8e5cf45c78ab230189a4ca',
}]
EXPECTED = {
"action": "allowed",
"dest": "bb.bbb.bb.bbb , cc.ccc.ccc.cc , xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa",
"distinct_hosts": '5',
"first_3_octets": "1.1.1",
"first_time": "06/11/18 17:34:07 , 06/11/18 17:37:55 , 06/11/18 17:41:28 , 06/11/18 17:42:05 , 06/11/18 17:42:38",
"info_max_time": "+Infinity",
"info_min_time": '0.000',
"search_name": "NG_SIEM_UC25- High number of hits against unknown website from same subnet",
"src": "xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa",
"u_category": "unknown",
"user": "xyz\\a1234 , xyz\\b5678 , xyz\\c91011 , xyz\\d121314 , unknown",
"website": "2.2.2.2",
"url": "https://test.url.com"
}
EXPECTED_WITH_MESSAGE_ID = {
"message-id": "1",
"action": "allowed",
"dest": "bb.bbb.bb.bbb , cc.ccc.ccc.cc , xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa",
"distinct_hosts": '5',
"first_3_octets": "1.1.1",
"first_time": "06/11/18 17:34:07 , 06/11/18 17:37:55 , 06/11/18 17:41:28 , 06/11/18 17:42:05 , 06/11/18 17:42:38",
"info_max_time": "+Infinity",
"info_min_time": '0.000',
"search_name": "NG_SIEM_UC25- High number of hits against unknown website from same subnet",
"src": "xx.xx.xxx.xx , yyy.yy.yyy.yy , zz.zzz.zz.zzz , aa.aa.aaa.aaa",
"u_category": "unknown",
"user": "xyz\\a1234 , xyz\\b5678 , xyz\\c91011 , xyz\\d121314 , unknown",
"website": "2.2.2.2",
"url": "https://test.url.com"
}
URL_TESTING_IN = '"url="https://test.com?key=val"'
URL_TESTING_OUT = {'url': 'https://test.com?key=val'}
# checking a case where the last character for each value was cut
RESPONSE = 'NAS-IP-Address=2.2.2.2, NAS-Port=50222, NAS-Identifier=de-wilm-251littl-idf3b-s2, NAS-Port-Type=' \
'Ethernet, NAS-Port-Id=GigabitEthernet2/0/05'
POSITIVE = {
"NAS-IP-Address": "2.2.2.2",
"NAS-Identifier": "de-wilm-251littl-idf3b-s2",
"NAS-Port": "50222",
"NAS-Port-Id": "GigabitEthernet2/0/05",
"NAS-Port-Type": "Ethernet"
}
# testing the ValueError and json sections
RAW_JSON = '{"Test": "success"}'
RAW_STANDARD = '"Test="success"'
RAW_JSON_AND_STANDARD_OUTPUT = {"Test": "success"}
class Jobs:
def __init__(self, status, service):
self.oneshot = lambda x, **kwargs: x
state = namedtuple('state', 'content')
self.state = state(content={'dispatchState': str(status)})
self.service = service
def __getitem__(self, arg):
return 0
def create(self, query, **kwargs):
job = client.Job(sid='123456', service=self.service, **kwargs)
job.resultCount = 0
return job
class Service:
def __init__(self, status):
self.jobs = Jobs(status, self)
self.status = status
self.disable_v2_api = False
self.namespace = {'app': 'test', 'owner': 'test', 'sharing': 'global'}
self._abspath = lambda x, **kwargs: x
def get(self, path_segment, owner=None, app=None, headers=None, sharing=None, **query):
return {'status': '200', 'body': 'test', 'headers': {'content-type': 'application/json'}, 'reason': 'OK'}
def job(self, sid):
return self.jobs
def test_raw_to_dict():
actual_raw = DICT_RAW_RESPONSE
response = splunk.rawToDict(actual_raw)
response_with_message = splunk.rawToDict(DICT_RAW_RESPONSE_WITH_MESSAGE_ID)
list_response = splunk.rawToDict(LIST_RAW)
raw_message = splunk.rawToDict(RAW_WITH_MESSAGE)
empty = splunk.rawToDict('')
url_test = splunk.rawToDict(URL_TESTING_IN)
character_check = splunk.rawToDict(RESPONSE)
assert response == EXPECTED
assert response_with_message == EXPECTED_WITH_MESSAGE_ID
assert {} == list_response
assert raw_message.get('SCOPE[29]') == 'autopay\/events\/payroll\/v1\/earning-configuration.configuration-tags' \
'.modify'
assert isinstance(raw_message, dict)
assert empty == {}
assert url_test == URL_TESTING_OUT
assert character_check == POSITIVE
assert splunk.rawToDict(RAW_JSON) == RAW_JSON_AND_STANDARD_OUTPUT
assert splunk.rawToDict(RAW_STANDARD) == RAW_JSON_AND_STANDARD_OUTPUT
assert splunk.rawToDict('drilldown_search="key IN ("test1","test2")') == {
'drilldown_search': 'key IN (test1,test2)'}
@pytest.mark.parametrize('text, output', [
('', ['']),
('"",', ['"",']),
# a value shouldn't do anything special
('woopwoop', ['woopwoop']),
# a normal key value without quotes
('abc=123', ['abc="123"']),
# add a comma at the end
('abc=123,', ['abc="123"']),
# a normal key value with quotes
('cbd="123"', ['cbd="123"']),
# check all wrapped with quotes removed
('"abc="123""', ['abc="123"']),
# we need to remove 111 at the start.
('111, cbd="123"', ['cbd="123"']),
# Testing with/without quotes and/or spaces:
('abc=123,cbd=123', ['abc="123"', 'cbd="123"']),
('abc=123,cbd="123"', ['abc="123"', 'cbd="123"']),
('abc="123",cbd=123', ['abc="123"', 'cbd="123"']),
('abc="123",cbd="123"', ['abc="123"', 'cbd="123"']),
('abc=123, cbd=123', ['abc="123"', 'cbd="123"']),
('abc=123, cbd="123"', ['abc="123"', 'cbd="123"']),
('cbd="123", abc=123', ['abc="123"', 'cbd="123"']),
('cbd="123",abc=123', ['abc="123"', 'cbd="123"']),
# Continue testing quotes with more values:
('xyz=321,cbd=123,abc=123', ['xyz="321"', 'abc="123"', 'cbd="123"']),
('xyz=321,cbd="123",abc=123', ['xyz="321"', 'abc="123"', 'cbd="123"']),
('xyz="321",cbd="123",abc=123', ['xyz="321"', 'abc="123"', 'cbd="123"']),
('xyz="321",cbd="123",abc="123"', ['xyz="321"', 'abc="123"', 'cbd="123"']),
# Testing nested quotes (the main reason for quote_group):
# Try to remove the start 111.
('111, cbd="a="123""', ['cbd="a="123""']),
('cbd="a="123""', ['cbd="a="123""']),
('cbd="a="123", b=321"', ['cbd="a="123", b="321""']),
('cbd="a=123, b=321"', ['cbd="a="123", b="321""']),
('cbd="a=123, b="321""', ['cbd="a="123", b="321""']),
('cbd="a="123", b="321""', ['cbd="a="123", b="321""']),
('cbd="a=123, b=321"', ['cbd="a="123", b="321""']),
('xyz=123, cbd="a="123", b=321"', ['xyz="123"', 'cbd="a="123", b="321""']),
('xyz="123", cbd="a="123", b="321""', ['xyz="123"', 'cbd="a="123", b="321""']),
('xyz="123", cbd="a="123", b="321"", qqq=2', ['xyz="123"', 'cbd="a="123", b="321""', 'qqq="2"']),
('xyz="123", cbd="a="123", b="321"", qqq="2"', ['xyz="123"', 'cbd="a="123", b="321""', 'qqq="2"']),
])
def test_quote_group(text, output):
assert sorted(splunk.quote_group(text)) == sorted(output)
data_test_replace_keys = [
({}, {}),
({'test': 'test'}, {'test': 'test'}),
({'test.': 'test.'}, {'test_': 'test.'}),
({'te.st': 'te.st'}, {'te_st': 'te.st'}),
({'te[st': 'te[st'}, {'te_st': 'te[st'}),
({'te]st': 'te]st'}, {'te_st': 'te]st'}),
({'te)st': 'te)st'}, {'te_st': 'te)st'}),
({'te(st': 'te(st'}, {'te_st': 'te(st'}),
('', ''),
(None, None)
]
@pytest.mark.parametrize('dict_in, dict_out', data_test_replace_keys)
def test_replace_keys(dict_in, dict_out):
out = splunk.replace_keys(deepcopy(dict_in))
assert out == dict_out, f'replace_keys({dict_in}) got: {out} instead: {dict_out}'
def test_parse_time_to_minutes_no_error():
splunk.FETCH_TIME = '3 hours'
res = splunk.parse_time_to_minutes()
assert res == 180
def test_parse_time_to_minutes_invalid_time_integer(mocker):
return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
splunk.FETCH_TIME = 'abc hours'
splunk.parse_time_to_minutes()
err_msg = return_error_mock.call_args[0][0]
assert err_msg == "Error: Invalid fetch time, need to be a positive integer with the time unit afterwards " \
"e.g '2 months, 4 days'."
def test_parse_time_to_minutes_invalid_time_unit(mocker):
return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
splunk.FETCH_TIME = '3 hoursss'
splunk.parse_time_to_minutes()
err_msg = return_error_mock.call_args[0][0]
assert err_msg == 'Error: Invalid time unit.'
SEARCH_RESULT = [
{
"But": {
"This": "is"
},
"Very": "Unique"
},
{
"Something": "regular",
"But": {
"This": "is"
},
"Very": "Unique"
},
{
"Something": "natural",
"But": {
"This": "is a very very"
},
"Very": "Unique and awesome"
}
]
REGULAR_ALL_CHOSEN_FIELDS = [
"Something",
"But",
"Very"
]
REGULAR_CHOSEN_FIELDS_SUBSET = [
"Something",
"Very"
]
REGEX_CHOSEN_FIELDS_SUBSET = [
"Some*",
"Very"
]
NON_EXISTING_FIELDS = [
"SDFAFSD",
"ASBLFKDJK"
]
@pytest.mark.parametrize('search_result, chosen_fields, expected_result', [
(SEARCH_RESULT, REGULAR_ALL_CHOSEN_FIELDS, REGULAR_ALL_CHOSEN_FIELDS),
(SEARCH_RESULT, REGULAR_CHOSEN_FIELDS_SUBSET, REGULAR_CHOSEN_FIELDS_SUBSET),
(SEARCH_RESULT, REGEX_CHOSEN_FIELDS_SUBSET, REGULAR_CHOSEN_FIELDS_SUBSET),
(SEARCH_RESULT, NON_EXISTING_FIELDS, []),
])
def test_commands(search_result, chosen_fields, expected_result):
from SplunkPy import update_headers_from_field_names
headers = update_headers_from_field_names(search_result, chosen_fields)
assert expected_result == headers
APPS = ['app']
STORES = ['store']
EMPTY_CASE = {}
STORE_WITHOUT_APP = {"kv_store_collection_name": "test"}
JUST_APP_NAME = {'app_name': 'app'} # happens in splunk-kv-store-collections-list command
CREATE_COMMAND = {'app_name': 'app', 'kv_store_name': 'not_store'}
CORRECT = {'app_name': 'app', 'kv_store_collection_name': 'store'}
INCORRECT_STORE_NAME = {'app_name': 'app', 'kv_store_collection_name': 'not_store'}
data_test_check_error = [
(EMPTY_CASE, 'app not found'),
(STORE_WITHOUT_APP, 'app not found'),
(JUST_APP_NAME, 'empty'),
(CREATE_COMMAND, 'empty'),
(CORRECT, 'empty'),
(INCORRECT_STORE_NAME, 'KV Store not found'),
]
@pytest.mark.parametrize('args, out_error', data_test_check_error)
def test_check_error(args, out_error):
class Service:
def __init__(self):
self.apps = APPS
self.kvstore = STORES
try:
splunk.check_error(Service(), args)
raise splunk.DemistoException('empty')
except splunk.DemistoException as error:
output = str(error)
assert (
output == out_error
), f'check_error(service, {args})\n\treturns: {output}\n\tinstead: {out_error}'
EMPTY_CASE = {}
JUST_KEY = {"key": "key"}
WITH_ALL_PARAMS = {"key": "demisto", "value": "is awesome", "limit": 1, "query": "test"}
STANDARD_KEY_VAL = {"key": "demisto", "value": "is awesome"}
KEY_AND_LIMIT = {"key": "key", "limit": 1}
KEY_AND_QUERY = {"key": "key", "query": 'test_query'}
QUERY = {"query": 'test_query'}
QUERY_AND_VALUE = {"query": 'test_query', "value": "awesome"}
data_test_build_kv_store_query = [
(EMPTY_CASE, str(EMPTY_CASE)),
(JUST_KEY, str(EMPTY_CASE)),
(STANDARD_KEY_VAL, '{"demisto": "is awesome"}'),
(WITH_ALL_PARAMS, '{"demisto": "is awesome"}'),
(KEY_AND_LIMIT, {"limit": 1}),
(KEY_AND_QUERY, 'test_query'),
(QUERY, 'test_query'),
(QUERY_AND_VALUE, 'test_query'),
]
@pytest.mark.parametrize('args, expected_query', data_test_build_kv_store_query)
def test_build_kv_store_query(args, expected_query, mocker):
mocker.patch('SplunkPy.get_key_type', return_value=None)
output = splunk.build_kv_store_query(None, args)
assert (
output == expected_query
), f'build_kv_store_query({args})\n\treturns: {output}\n\tinstead: {expected_query}'
data_test_build_kv_store_query_with_key_val = [
({"key": "demisto", "value": "is awesome"}, str, '{"demisto": "is awesome"}'),
({"key": "demisto", "value": "1"}, int, '{"demisto": 1}'),
({"key": "demisto", "value": "True"}, bool, '{"demisto": true}'),
]
@pytest.mark.parametrize('args, _type, expected_query', data_test_build_kv_store_query_with_key_val)
def test_build_kv_store_query_with_key_val(args, _type, expected_query, mocker):
mocker.patch('SplunkPy.get_key_type', return_value=_type)
output = splunk.build_kv_store_query(None, args)
assert output == expected_query, 'build_kv_store_query({})\n\treturns: {}\n\tinstead: {}'.format(args, output,
expected_query)
test_test_get_key_type = [
({'field.key': 'number'}, float),
({'field.key': 'string'}, str),
({'field.key': 'cidr'}, str),
({'field.key': 'boolean'}, bool),
({'field.key': 'empty'}, None),
({'field.key': 'time'}, str),
]
@pytest.mark.parametrize('keys_and_types, expected_type', test_test_get_key_type)
def test_get_key_type(keys_and_types, expected_type, mocker):
mocker.patch('SplunkPy.get_keys_and_types', return_value=keys_and_types)
output = splunk.get_key_type(None, 'key')
assert output == expected_type, 'get_key_type(kv_store, key)\n\treturns: {}\n\tinstead: {}'.format(output,
expected_type)
EMPTY_CASE = {}
WITHOUT_FIELD = {'empty': 'number'}
STRING_FIELD = {'field.test': 'string'}
NUMBER_FIELD = {'field.test': 'number'}
INDEX = {'index.test': 'string'}
MIXED = {'field.test': 'string', 'empty': 'field'}
data_test_get_keys_and_types = [
(EMPTY_CASE, EMPTY_CASE),
(WITHOUT_FIELD, EMPTY_CASE),
(STRING_FIELD, {'field.test': 'string'}),
(NUMBER_FIELD, {'field.test': 'number'}),
(INDEX, {'index.test': 'string'}),
(MIXED, {'field.test': 'string'}),
]
@pytest.mark.parametrize('raw_keys, expected_keys', data_test_get_keys_and_types)
def test_get_keys_and_types(raw_keys, expected_keys):
class KVMock:
def __init__(self):
pass
def content(self):
return raw_keys
output = splunk.get_keys_and_types(KVMock())
assert (
output == expected_keys
), f'get_keys_and_types(kv_store)\n\treturns: {output}\n\tinstead: {expected_keys}'
START_OUTPUT = (
'#### configuration for name store\n| field name | type |\n| --- | --- |'
)
EMPTY_OUTPUT = ''
STANDARD_CASE = {'field.test': 'number'}
STANDARD_OUTPUT = '\n| field.test | number |'
data_test_get_kv_store_config = [
({}, EMPTY_OUTPUT),
(STANDARD_CASE, STANDARD_OUTPUT)
]
@pytest.mark.parametrize('fields, expected_output', data_test_get_kv_store_config)
def test_get_kv_store_config(fields, expected_output, mocker):
class Name:
def __init__(self):
self.name = 'name'
mocker.patch('SplunkPy.get_keys_and_types', return_value=fields)
output = splunk.get_kv_store_config(Name())
expected_output = f'{START_OUTPUT}{expected_output}'
assert output == expected_output
def test_fetch_incidents(mocker):
"""
Given
- mocked incidents api response
- a mapper which should not map the user owner into the incident response
When
- executing the fetch incidents flow
Then
- make sure the incident response is valid.
- make sure that the owner is not part of the incident response
"""
from SplunkPy import UserMappingObject
mocker.patch.object(demisto, 'incidents')
mocker.patch.object(demisto, 'setLastRun')
mock_last_run = {'time': '2018-10-24T14:13:20'}
mock_params = {'fetchQuery': "something"}
mocker.patch('demistomock.getLastRun', return_value=mock_last_run)
mocker.patch('demistomock.params', return_value=mock_params)
service = mocker.patch('splunklib.client.connect', return_value=None)
mocker.patch('splunklib.results.JSONResultsReader', return_value=SAMPLE_RESPONSE)
mapper = UserMappingObject(service, False)
splunk.fetch_incidents(service, mapper, 'from_xsoar', 'from_splunk')
incidents = demisto.incidents.call_args[0][0]
assert demisto.incidents.call_count == 1
assert len(incidents) == 1
assert incidents[0]["name"] == "Endpoint - Recurring Malware Infection - Rule : Endpoint - " \
"Recurring Malware Infection - Rule"
assert not incidents[0].get('owner')
SPLUNK_RESULTS = [
{
"rawJSON":
'{"source": "This is the alert type", "field_name1": "field_val1", "field_name2": "field_val2"}',
"details": "Endpoint - High Or Critical Priority Host With Malware - Rule",
"labels": [
{
"type": "security_domain",
"value": "Endpoint - High Or Critical Priority Host With Malware - Rule"
}
],
}
]
EXPECTED_OUTPUT = {
'This is the alert type': {
"source": "This is the alert type",
"field_name1": "field_val1",
"field_name2": "field_val2"
}
}
def test_create_mapping_dict():
mapping_dict = splunk.create_mapping_dict(SPLUNK_RESULTS, type_field='source')
assert mapping_dict == EXPECTED_OUTPUT
def test_fetch_notables(mocker):
"""
Given
- mocked incidents api response
- a mapper which should not map the user owner into the incident response
When
- executing the fetch notables flow
Then
- make sure the incident response is valid.
- make sure that the owner is not part of the incident response
"""
mocker.patch.object(splunk.client.Job, 'is_done', return_value=True)
mocker.patch.object(splunk.client.Job, 'results', return_value=None)
mocker.patch.object(splunk, 'ENABLED_ENRICHMENTS', [splunk.ASSET_ENRICHMENT,
splunk.DRILLDOWN_ENRICHMENT, splunk.IDENTITY_ENRICHMENT])
mocker.patch.object(demisto, 'incidents')
mocker.patch.object(demisto, 'setLastRun')
mock_last_run = {'time': '2018-10-24T14:13:20'}
mock_params = {'fetchQuery': "something"}
mocker.patch('demistomock.getLastRun', return_value=mock_last_run)
mocker.patch('demistomock.params', return_value=mock_params)
service = Service('DONE')
mocker.patch('splunklib.results.JSONResultsReader', return_value=SAMPLE_RESPONSE)
mapper = splunk.UserMappingObject(service, False)
splunk.fetch_incidents(service, mapper=mapper, comment_tag_to_splunk='comment_tag_to_splunk',
comment_tag_from_splunk='comment_tag_from_splunk')
cache_object = splunk.Cache.load_from_integration_context(get_integration_context())
assert cache_object.submitted_notables
notable = cache_object.submitted_notables[0]
incident_from_cache = notable.to_incident(mapper, 'comment_tag_to_splunk', 'comment_tag_from_splunk')
incidents = demisto.incidents.call_args[0][0]
assert demisto.incidents.call_count == 1
assert len(incidents) == 0
assert incident_from_cache["name"] == "Endpoint - Recurring Malware Infection - Rule : Endpoint - " \
"Recurring Malware Infection - Rule"
assert not incident_from_cache.get('owner')
# now call second time to make sure that the incident fetched
splunk.fetch_incidents(service, mapper=mapper, comment_tag_to_splunk='comment_tag_to_splunk',
comment_tag_from_splunk='comment_tag_from_splunk')
incidents = demisto.incidents.call_args[0][0]
assert len(incidents) == 1
assert incidents[0]["name"] == "Endpoint - Recurring Malware Infection - Rule : Endpoint - " \
"Recurring Malware Infection - Rule"
assert not incidents[0].get('owner')
""" ========== Enriching Fetch Mechanism Tests ========== """
@pytest.mark.parametrize('integration_context, output', [
({splunk.INCIDENTS: ['incident']}, ['incident']),
({splunk.INCIDENTS: []}, []),
({}, [])
])
def test_fetch_incidents_for_mapping(integration_context, output, mocker):
"""
Scenario: When a user configures a mapper using Fetch from Instance when the enrichment mechanism is working,
we save the ready incidents in the integration context.
Given:
- List of ready incidents
- An empty list of incidents
- An empty integration context object
When:
- fetch_incidents_for_mapping is called
Then:
- Return the expected result
"""
mocker.patch.object(demisto, 'info')
mocker.patch.object(demisto, 'incidents')
splunk.fetch_incidents_for_mapping(integration_context)
assert demisto.incidents.call_count == 1
assert demisto.incidents.call_args[0][0] == output
def test_reset_enriching_fetch_mechanism(mocker):
"""
Scenario: When a user is willing to reset the enriching fetch mechanism and start over.
Given:
- An integration context object with not empty Cache and incidents
When:
- reset_enriching_fetch_mechanism is called
Then:
- Check that the integration context does not contain this fields
"""
integration_context = {
splunk.CACHE: "cache_string",
splunk.INCIDENTS: ['i1', 'i2'],
'wow': 'wow'
}
mocker.patch('SplunkPy.get_integration_context', return_value=integration_context)
mocker.patch('SplunkPy.set_integration_context')
splunk.reset_enriching_fetch_mechanism()
assert integration_context == {'wow': 'wow'}
@pytest.mark.parametrize(
"drilldown_creation_time, asset_creation_time, enrichment_timeout, output",
[
(datetime.utcnow().isoformat(), datetime.utcnow().isoformat(), 5, False),
(
(datetime.utcnow() - timedelta(minutes=6)).isoformat(),
datetime.utcnow().isoformat(),
5,
True,
),
],
)
def test_is_enrichment_exceeding_timeout(mocker, drilldown_creation_time, asset_creation_time, enrichment_timeout,
output):
"""
Scenario: When one of the notable's enrichments is exceeding the timeout, we want to create an incident we all
the data gathered so far.
Given:
- Two enrichments that none of them exceeds the timeout.
- An enrichment exceeding the timeout and one that does not exceeds the timeout.
When:
- is_enrichment_process_exceeding_timeout is called
Then:
- Return the expected result
"""
mocker.patch.object(splunk, 'ENABLED_ENRICHMENTS',
return_value=[splunk.DRILLDOWN_ENRICHMENT, splunk.ASSET_ENRICHMENT])
notable = splunk.Notable({splunk.EVENT_ID: 'id'})
notable.enrichments.append(splunk.Enrichment(splunk.DRILLDOWN_ENRICHMENT, creation_time=drilldown_creation_time))
notable.enrichments.append(splunk.Enrichment(splunk.ASSET_ENRICHMENT, creation_time=asset_creation_time))
assert notable.is_enrichment_process_exceeding_timeout(enrichment_timeout) is output
INCIDENT_1 = {'name': 'incident1', 'rawJSON': json.dumps({})}
INCIDENT_2 = {'name': 'incident2', 'rawJSON': json.dumps({})}
@pytest.mark.parametrize('integration_context, incidents, output', [
({}, [], []),
({}, [INCIDENT_1, INCIDENT_2], [INCIDENT_1, INCIDENT_2])
])
def test_store_incidents_for_mapping(integration_context, incidents, output):
"""
Scenario: Store ready incidents in integration context, to be retrieved by a user configuring a mapper
and selecting "Fetch from instance" when the enrichment mechanism is working.
Given:
- An empty list of incidents
- A list of two incidents
When:
- store_incidents_for_mapping is called
Then:
- Return the expected result
"""
splunk.store_incidents_for_mapping(incidents, integration_context)
assert integration_context.get(splunk.INCIDENTS, []) == output
@pytest.mark.parametrize('notable_data, raw, status, earliest, latest', [
({}, {}, False, "", ""),
({"drilldown_earliest": f"${splunk.INFO_MIN_TIME}$",
"drilldown_latest": f"${splunk.INFO_MAX_TIME}$"},
{splunk.INFO_MIN_TIME: '1', splunk.INFO_MAX_TIME: '2'}, True, '1', '2'),
({"drilldown_earliest": '1', "drilldown_latest": '2', }, {}, True, '1', '2')
])
def test_get_drilldown_timeframe(notable_data, raw, status, earliest, latest, mocker):
"""
Scenario: Trying to get the drilldown's timeframe from the notable's data
Given:
- An empty notable's data
- An notable's data that the info of the timeframe is in the raw field
- An notable's data that the info is in the data dict
When:
- get_drilldown_timeframe is called
Then:
- Return the expected result
"""
mocker.patch.object(demisto, 'info')
task_status, earliest_offset, latest_offset = splunk.get_drilldown_timeframe(notable_data, raw)
assert task_status == status
assert earliest_offset == earliest
assert latest_offset == latest
@pytest.mark.parametrize('raw_field, notable_data, expected_field, expected_value', [
('field|s', {'field': '1'}, 'field', '1'),
('field', {'field': '1'}, 'field', '1'),
('field|s', {'_raw': 'field=1, value=2'}, 'field', '1'),
('x', {'y': '2'}, '', '')
])
def test_get_notable_field_and_value(raw_field, notable_data, expected_field, expected_value, mocker):
"""
Scenario: When building the drilldown search query, we search for the field in the raw search query
and search for its real name in the notable's data or in the notable's raw data.
We also ignore Splunk advanced syntax such as "|s, |h, ..."
Given:
- A raw field that has the same name in the notable's data
- A raw field that has "|s" as a suffix in the raw search query and its value is in the notable's data
- A raw field that has "|s" as a suffix in the raw search query and its value is in the notable's raw data
- A raw field that is not is the notable's data or in the notable's raw data
When:
- get_notable_field_and_value is called
Then:
- Return the expected result
"""
mocker.patch.object(demisto, 'error')
field, value = splunk.get_notable_field_and_value(raw_field, notable_data)
assert field == expected_field
assert value == expected_value
@pytest.mark.parametrize('notable_data, search, raw, expected_search', [
({'a': '1', '_raw': 'c=3'}, 'search a=$a|s$ c=$c$ suffix', {'c': '3'}, 'search a="1" c="3" suffix'),
({'a': ['1', '2'], 'b': '3'}, 'search a=$a|s$ b=$b|s$ suffix', {}, 'search (a="1" OR a="2") b="3" suffix'),
({'a': '1', '_raw': 'b=3', 'event_id': '123'}, 'search a=$a|s$ c=$c$ suffix', {'b': '3'}, ''),
])
def test_build_drilldown_search(notable_data, search, raw, expected_search, mocker):
"""
Scenario: When building the drilldown search query, we replace every field in between "$" sign with its
corresponding query part (key & value).
Given:
- A raw search query with fields both in the notable's data and in the notable's raw data
- A raw search query with fields in the notable's data that has more than one value
- A raw search query with fields that does not exist in the notable's data or in the notable's raw data
When:
- build_drilldown_search is called
Then:
- Return the expected result
"""
mocker.patch.object(demisto, 'error')
assert splunk.build_drilldown_search(notable_data, search, raw) == expected_search
@pytest.mark.parametrize('notable_data, prefix, fields, query_part', [
({'user': ['u1', 'u2']}, 'identity', ['user'], '(identity="u1" OR identity="u2")'),
({'_raw': '1233, user=u1'}, 'user', ['user'], 'user="u1"'),
({'user': ['u1', 'u2'], '_raw': '1321, src_user=u3'}, 'user', ['user', 'src_user'],
'(user="u1" OR user="u2" OR user="u3")'),
({}, 'prefix', ['field'], '')
])
def test_get_fields_query_part(notable_data, prefix, fields, query_part):
"""
Scenario: When building an enrichment search query, we search for values in the notable's data / notable's raw data
and fill them in the raw search query to create a searchable query.
Given:
- One field with multiple values, values in the data
- One field, value is in the raw data
- Two fields with multiple values, values in both the data and the raw data
- An empty notable data, field does not exists
When:
- get_fields_query_part is called
Then:
- Return the expected result
"""
assert splunk.get_fields_query_part(notable_data, prefix, fields) == query_part
""" ========== Mirroring Mechanism Tests ========== """
@pytest.mark.parametrize('last_update, demisto_params, splunk_time_timestamp', [
('2021-02-22T18:39:47.753+00:00', {'timezone': '0'}, 1614019187.753),
('2021-02-22T18:39:47.753+02:00', {'timezone': '+120'}, 1614019187.753),
('2021-02-22T20:39:47.753+02:00', {'timezone': '0'}, 1614019187.753),
('2021-02-09T16:41:30.589575+02:00', {}, '')
])
def test_get_last_update_in_splunk_time(last_update, demisto_params, splunk_time_timestamp, mocker):
""" Tests the conversion of the Demisto server time into timestamp in Splunk Server time
Given:
- The last update time in the Demisto server
- The timezone in the Splunk Server
When:
Converting the time in the Demisto server into timestamp in Splunk Server time
Then:
- Conversion is correct
- An Exception is raised in case that Splunk Server timezone is not specified in Demisto params
"""
mocker.patch.object(demisto, 'params', return_value=demisto_params)
if demisto_params:
assert splunk.get_last_update_in_splunk_time(last_update) == splunk_time_timestamp
else:
error_msg = 'Cannot mirror incidents when timezone is not configured. Please enter the '
'timezone of the Splunk server being used in the integration configuration.'
with pytest.raises(Exception, match=error_msg):
splunk.get_last_update_in_splunk_time(last_update)
@pytest.mark.parametrize(
"notable_data, func_call_kwargs, expected_closure_data",
[
# A Notable with a "Closed" status label
(
[
results.Message("INFO-TEST", "test message"),
{"status_label": "Closed", "event_id": "id", "status_end": "true"},
],
{
"close_incident": True,
"close_end_statuses": False,
"close_extra_labels": [],
},
{
"Type": EntryType.NOTE,
"Contents": {
"dbotIncidentClose": True,
"closeReason": 'Notable event was closed on Splunk with status "Closed".',
},
"ContentsFormat": EntryFormat.JSON,
},
),
# A Notable with a "New" status label (shouldn't close)
(
[
results.Message("INFO-TEST", "test message"),
{"status_label": "New", "event_id": "id", "status_end": "false"},
],
{
"close_incident": True,
"close_end_statuses": False,
"close_extra_labels": [],
},
None,
),
# A Notable with a custom status label that is on close_extra_labels (should close)
(
[
results.Message("INFO-TEST", "test message"),
{"status_label": "Custom", "event_id": "id", "status_end": "false"},
],
{
"close_incident": True,
"close_end_statuses": False,
"close_extra_labels": ["Custom"],
},
{
"Type": EntryType.NOTE,
"Contents": {
"dbotIncidentClose": True,
"closeReason": 'Notable event was closed on Splunk with status "Custom".',
},
"ContentsFormat": EntryFormat.JSON,
},
),
# A Notable with close_extra_labels that don't include status_label (shouldn't close)
(
[
results.Message("INFO-TEST", "test message"),
{"status_label": "Custom", "event_id": "id", "status_end": "false"},
],
{
"close_incident": True,
"close_end_statuses": False,
"close_extra_labels": ["A", "B"],
},