-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathDetectionTestingInfrastructure.py
More file actions
1573 lines (1403 loc) · 59.3 KB
/
Copy pathDetectionTestingInfrastructure.py
File metadata and controls
1573 lines (1403 loc) · 59.3 KB
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 abc
import configparser
import datetime
import json
import os.path
import pathlib
import time
import urllib.parse
import uuid
from ssl import SSLEOFError, SSLZeroReturnError
from sys import stdout
from tempfile import TemporaryDirectory, mktemp
from typing import Callable, Optional, Union
import requests # type: ignore
import splunklib.client as client # type: ignore
import tqdm # type: ignore
from pydantic import (
BaseModel,
ConfigDict,
Field,
PrivateAttr,
computed_field,
dataclasses,
)
from semantic_version import Version
from splunklib.binding import HTTPError # type: ignore
from splunklib.results import JSONResultsReader, Message # type: ignore
from urllib3 import disable_warnings
from contentctl.actions.detection_testing.progress_bar import (
FinalTestingStates,
TestingStates,
TestReportingType,
format_pbar_string,
)
from contentctl.helper.utils import Utils
from contentctl.objects.base_test import BaseTest
from contentctl.objects.base_test_result import TestResultStatus
from contentctl.objects.config import Infrastructure, test_common
from contentctl.objects.content_versioning_service import ContentVersioningService
from contentctl.objects.correlation_search import CorrelationSearch, PbarData
from contentctl.objects.detection import Detection
from contentctl.objects.enums import AnalyticsType, PostTestBehavior
from contentctl.objects.integration_test import IntegrationTest
from contentctl.objects.integration_test_result import IntegrationTestResult
from contentctl.objects.test_attack_data import TestAttackData
from contentctl.objects.test_group import TestGroup
from contentctl.objects.unit_test import UnitTest
from contentctl.objects.unit_test_result import UnitTestResult
# The app name of ES; needed to check ES version
ES_APP_NAME = "SplunkEnterpriseSecuritySuite"
class SetupTestGroupResults(BaseModel):
exception: Union[Exception, None] = None
success: bool = True
duration: float = 0
start_time: float
model_config = ConfigDict(arbitrary_types_allowed=True)
class CleanupTestGroupResults(BaseModel):
duration: float
start_time: float
class ContainerStoppedException(Exception):
pass
class CannotRunBaselineException(Exception):
# Support for testing detections with baselines
# does not currently exist in contentctl.
# As such, whenever we encounter a detection
# with baselines we should generate a descriptive
# exception
pass
class ReplayIndexDoesNotExistOnServer(Exception):
"""
In order to replay data files into the Splunk Server
for testing, they must be replayed into an index that
exists. If that index does not exist, this error will
be generated and raised before we try to do anything else
with that Data File.
"""
pass
@dataclasses.dataclass(frozen=False)
class DetectionTestingManagerOutputDto:
inputQueue: list[Detection] = Field(default_factory=list)
outputQueue: list[Detection] = Field(default_factory=list)
currentTestingQueue: dict[str, Union[Detection, None]] = Field(default_factory=dict)
start_time: Union[datetime.datetime, None] = None
replay_index: str = "contentctl_testing_index"
replay_host: str = "CONTENTCTL_HOST"
timeout_seconds: int = 120
terminate: bool = False
class DetectionTestingInfrastructure(BaseModel, abc.ABC):
# thread: threading.Thread = threading.Thread()
global_config: test_common
infrastructure: Infrastructure
sync_obj: DetectionTestingManagerOutputDto
hec_token: str = ""
hec_channel: str = ""
all_indexes_on_server: list[str] = []
_conn: client.Service = PrivateAttr()
pbar: tqdm.tqdm = None
start_time: Optional[float] = None
model_config = ConfigDict(arbitrary_types_allowed=True)
def __init__(self, **data):
super().__init__(**data)
# TODO: why not use @abstractmethod
def start(self):
raise (
NotImplementedError(
"start() is not implemented for Abstract Type DetectionTestingInfrastructure"
)
)
# TODO: why not use @abstractmethod
def get_name(self) -> str:
raise (
NotImplementedError(
"get_name() is not implemented for Abstract Type DetectionTestingInfrastructure"
)
)
def setup(self):
self.pbar = tqdm.tqdm(
total=100,
initial=0,
bar_format=f"{self.get_name()} starting",
miniters=0,
mininterval=0,
file=stdout,
)
self.start_time = time.time()
# Init the list of setup functions we always need
primary_setup_functions: list[
tuple[Callable[[], None | client.Service], str]
] = [
(self.start, "Starting"),
(self.get_conn, "Waiting for App Installation"),
(self.configure_conf_file_datamodels, "Configuring Datamodels"),
(self.create_replay_index, f"Create index '{self.sync_obj.replay_index}'"),
(self.get_all_indexes, "Getting all indexes from server"),
(self.check_for_es_install, "Checking for ES Install"),
(self.configure_imported_roles, "Configuring Roles"),
(self.configure_delete_indexes, "Configuring Indexes"),
(self.configure_hec, "Configuring HEC"),
(self.wait_for_ui_ready, "Finishing Primary Setup"),
]
# Execute and report on each setup function
try:
# Run the primary setup functions
for func, msg in primary_setup_functions:
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
msg,
update_sync_status=True,
)
func()
self.check_for_teardown()
# Run any setup functions only applicable to content versioning validation
if self.should_test_content_versioning:
self.pbar.write(
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
"Beginning Content Versioning Validation...",
set_pbar=False,
)
)
for func, msg in self.content_versioning_service.setup_functions:
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
msg,
update_sync_status=True,
)
func()
self.check_for_teardown()
except Exception as e:
msg = f"[{self.get_name()}]: {e!s}"
self.finish()
if isinstance(e, ExceptionGroup):
raise ExceptionGroup(msg, e.exceptions) from e # type: ignore
raise Exception(msg) from e
self.pbar.write(
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
"Finished Setup!",
set_pbar=False,
)
)
def wait_for_ui_ready(self):
self.get_conn()
@computed_field
@property
def content_versioning_service(self) -> ContentVersioningService:
"""
A computed field returning a handle to the content versioning service, used by ES to
version detections. We use this model to validate that all detections have been installed
compatibly with ES versioning.
:return: a handle to the content versioning service on the instance
:rtype: :class:`contentctl.objects.content_versioning_service.ContentVersioningService`
"""
return ContentVersioningService(
global_config=self.global_config,
infrastructure=self.infrastructure,
service=self.get_conn(),
detections=self.sync_obj.inputQueue,
)
@property
def should_test_content_versioning(self) -> bool:
"""
Indicates whether we should test content versioning. Content versioning
should be tested when integration testing is enabled, the mode is all, and ES is at least
version 8.0.0.
:return: a bool indicating whether we should test content versioning
:rtype: bool
"""
# es_version = self.es_version
# return (
# self.global_config.enable_integration_testing
# and isinstance(self.global_config.mode, All)
# and es_version is not None
# and es_version >= Version("8.0.0")
# )
return False
@property
def es_version(self) -> Version | None:
"""
Returns the version of Enterprise Security installed on the instance; None if not installed.
:return: the version of ES, as a semver aware object
:rtype: :class:`semantic_version.Version`
"""
if not self.es_installed:
return None
return Version(self.get_conn().apps[ES_APP_NAME]["version"]) # type: ignore
@property
def es_installed(self) -> bool:
"""
Indicates whether ES is installed on the instance.
:return: a bool indicating whether ES is installed or not
:rtype: bool
"""
return ES_APP_NAME in self.get_conn().apps
def check_for_es_install(self) -> None:
"""
Validating function which raises an error if Enterprise Security is not installed and
integration testing is enabled.
"""
if not self.es_installed and self.global_config.enable_integration_testing:
raise Exception(
"Enterprise Security does not appear to be installed on this instance and "
"integration testing is enabled."
)
def configure_hec(self):
self.hec_channel = str(uuid.uuid4())
try:
res = self.get_conn().input(
path="/servicesNS/nobody/splunk_httpinput/data/inputs/http/http:%2F%2FDETECTION_TESTING_HEC"
)
self.hec_token = str(res.token)
return
except Exception:
# HEC input does not exist. That's okay, we will create it
pass
try:
res = self.get_conn().inputs.create(
name="DETECTION_TESTING_HEC",
kind="http",
index=self.sync_obj.replay_index,
indexes=",".join(
self.all_indexes_on_server
), # This allows the HEC to write to all indexes
useACK=True,
)
self.hec_token = str(res.token)
return
except Exception as e:
raise (Exception(f"Failure creating HEC Endpoint: {e!s}"))
def get_all_indexes(self) -> None:
"""
Retrieve a list of all indexes in the Splunk instance
"""
try:
# We do not include the replay index because by
# the time we get to this function, it has already
# been created on the server.
indexes = []
res = self.get_conn().indexes
for index in res.list():
indexes.append(index.name)
# Retrieve all available indexes on the splunk instance
self.all_indexes_on_server = indexes
except Exception as e:
raise (Exception(f"Failure getting indexes: {e!s}"))
def get_conn(self) -> client.Service:
try:
if not self._conn:
self.connect_to_api()
elif self._conn.restart_required:
# continue trying to re-establish a connection until after
# the server has restarted
self.connect_to_api()
except Exception:
# there was some issue getting the connection. Try again just once
self.connect_to_api()
return self._conn
def check_for_teardown(self):
# Make sure we can easily quit during setup if we need to.
# Some of these stages can take a long time
if self.sync_obj.terminate:
# Exiting in a thread just quits the thread, not the entire process
raise (ContainerStoppedException(f"Testing stopped for {self.get_name()}"))
def connect_to_api(self, sleep_seconds: int = 5):
while True:
self.check_for_teardown()
try:
conn = client.connect(
host=self.infrastructure.instance_address,
port=self.infrastructure.api_port,
username=self.infrastructure.splunk_app_username,
password=self.infrastructure.splunk_app_password,
)
if conn.restart_required:
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
"Waiting for reboot",
update_sync_status=True,
)
else:
# Finished setup
self._conn = conn
return
except ConnectionRefusedError as e:
raise (e)
except SSLEOFError:
pass
except SSLZeroReturnError:
pass
except ConnectionResetError:
pass
except Exception as e:
self.pbar.write(
f"Error getting API connection (not quitting) '{type(e).__name__}': {e!s}"
)
for _ in range(sleep_seconds):
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
"Getting API Connection",
update_sync_status=True,
)
time.sleep(1)
def create_replay_index(self):
try:
self.get_conn().indexes.create(name=self.sync_obj.replay_index)
except HTTPError as e:
if b"already exists" in e.body:
pass
else:
raise Exception(
f"Error creating index {self.sync_obj.replay_index} - {e!s}"
)
def configure_imported_roles(
self,
imported_roles: list[str] = ["user", "power", "can_delete"],
enterprise_security_roles: list[str] = ["ess_admin", "ess_analyst", "ess_user"],
):
# Set which roles should be configured. For Enterprise Security/Integration Testing,
# we must add some extra foles.
if self.global_config.enable_integration_testing:
roles = imported_roles + enterprise_security_roles
else:
roles = imported_roles
try:
self.get_conn().roles.post(
self.infrastructure.splunk_app_username,
imported_roles=roles,
srchIndexesAllowed=";".join(self.all_indexes_on_server),
srchIndexesDefault=self.sync_obj.replay_index,
)
return
except Exception as e:
msg = f"Error configuring roles: {e!s}"
self.pbar.write(msg)
raise Exception(msg) from e
def configure_delete_indexes(self):
endpoint = "/services/properties/authorize/default/deleteIndexesAllowed"
try:
self.get_conn().post(endpoint, value=";".join(self.all_indexes_on_server))
except Exception as e:
self.pbar.write(
f"Error configuring deleteIndexesAllowed with '{self.all_indexes_on_server}': [{e!s}]"
)
def wait_for_conf_file(self, app_name: str, conf_file_name: str):
while True:
self.check_for_teardown()
time.sleep(1)
try:
_ = self.get_conn().get(f"configs/conf-{conf_file_name}", app=app_name)
return
except Exception:
pass
self.format_pbar_string(
TestReportingType.SETUP,
self.get_name(),
"Configuring Datamodels",
)
def configure_conf_file_datamodels(self, APP_NAME: str = "Splunk_SA_CIM"):
self.wait_for_conf_file(APP_NAME, "datamodels")
parser = configparser.ConfigParser()
cim_acceleration_datamodels = pathlib.Path(
os.path.join(
os.path.dirname(__file__), "../../../templates/datamodels_cim.conf"
)
)
custom_acceleration_datamodels = pathlib.Path(
os.path.join(
os.path.dirname(__file__), "../../../templates/datamodels_custom.conf"
)
)
if custom_acceleration_datamodels.is_file():
parser.read(custom_acceleration_datamodels)
if len(parser.keys()) > 1:
self.pbar.write(
f"Read {len(parser) - 1} custom datamodels from {custom_acceleration_datamodels!s}!"
)
if not cim_acceleration_datamodels.is_file():
self.pbar.write(
f"******************************\nDATAMODEL ACCELERATION FILE {cim_acceleration_datamodels!s} NOT "
"FOUND. CIM DATAMODELS NOT ACCELERATED\n******************************\n"
)
else:
parser.read(cim_acceleration_datamodels)
for datamodel_name in parser:
if datamodel_name == "DEFAULT":
# Skip the DEFAULT section for configparser
continue
for name, value in parser[datamodel_name].items():
try:
_ = self.get_conn().post(
f"properties/datamodels/{datamodel_name}/{name}",
app=APP_NAME,
value=value,
)
except Exception as e:
self.pbar.write(
f"Error creating the conf Datamodel {datamodel_name} key/value {name}/{value}: {e!s}"
)
def execute(self):
while True:
try:
self.check_for_teardown()
except ContainerStoppedException:
self.finish()
return
try:
detection = self.sync_obj.inputQueue.pop()
self.sync_obj.currentTestingQueue[self.get_name()] = detection
except IndexError:
# self.pbar.write(
# f"No more detections to test, shutting down {self.get_name()}"
# )
self.finish()
return
try:
self.test_detection(detection)
except ContainerStoppedException:
self.pbar.write(
f"Warning - container was stopped when trying to execute detection [{self.get_name()}]"
)
self.finish()
return
except Exception as e:
self.pbar.write(f"Error testing detection: {type(e).__name__}: {e!s}")
raise e
finally:
self.sync_obj.outputQueue.append(detection)
self.sync_obj.currentTestingQueue[self.get_name()] = None
def test_detection(self, detection: Detection) -> None:
"""
Tests a single detection; iterates over the TestGroups for the detection (one TestGroup per
unit test, where a TestGroup is a unit test and integration test relying on the same attack
data)
:param detection: the Detection to test
"""
# iterate TestGroups
for test_group in detection.test_groups:
# If all tests in the group have been skipped, report and continue.
# Note that the logic for skipping tests for detections tagged manual_test exists in
# the detection builder.
if test_group.all_tests_skipped():
self.pbar.write(
self.format_pbar_string(
TestReportingType.GROUP,
test_group.name,
FinalTestingStates.SKIP,
start_time=time.time(),
set_pbar=False,
)
)
continue
# replay attack_data
setup_results = self.setup_test_group(test_group)
# run unit test
self.execute_unit_test(detection, test_group.unit_test, setup_results)
# run integration test
self.execute_integration_test(
detection,
test_group.integration_test,
setup_results,
test_group.unit_test.result,
)
# cleanup
cleanup_results = self.cleanup_test_group(
test_group, setup_results.start_time
)
# update the results duration w/ the setup/cleanup time (for those not skipped)
if (test_group.unit_test.result is not None) and (
not test_group.unit_test_skipped()
):
test_group.unit_test.result.duration = round(
test_group.unit_test.result.duration
+ setup_results.duration
+ cleanup_results.duration,
2,
)
if (test_group.integration_test.result is not None) and (
not test_group.integration_test_skipped()
):
test_group.integration_test.result.duration = round(
test_group.integration_test.result.duration
+ setup_results.duration
+ cleanup_results.duration,
2,
)
# Write test group status
self.pbar.write(
self.format_pbar_string(
TestReportingType.GROUP,
test_group.name,
TestingStates.DONE_GROUP,
start_time=setup_results.start_time,
set_pbar=False,
)
)
def setup_test_group(self, test_group: TestGroup) -> SetupTestGroupResults:
"""
Executes attack_data replay, captures test group start time, does some reporting to the CLI
and returns an object encapsulating the results of data replay
:param test_group: the TestGroup to replay for
:returns: SetupTestGroupResults
"""
# Capture the setup start time
setup_start_time = time.time()
# Log the start of the test group
self.pbar.reset()
self.format_pbar_string(
TestReportingType.GROUP,
test_group.name,
TestingStates.BEGINNING_GROUP,
start_time=setup_start_time,
)
# https://github.com/WoLpH/python-progressbar/issues/164
# Use NullBar if there is more than 1 container or we are running
# in a non-interactive context
# Initialize the setup results
results = SetupTestGroupResults(start_time=setup_start_time)
# Replay attack data
try:
self.replay_attack_data_files(test_group, setup_start_time)
except Exception as e:
print("\n\nexception replaying attack data files\n\n")
results.exception = e
results.success = False
# Set setup duration
results.duration = time.time() - setup_start_time
return results
def cleanup_test_group(
self,
test_group: TestGroup,
test_group_start_time: float,
) -> CleanupTestGroupResults:
"""
Deletes attack data for the test group and returns metadata about the cleanup duration
:param test_group: the TestGroup being cleaned up
:param test_group_start_time: the start time of the TestGroup (for logging)
"""
# Get the start time for cleanup
cleanup_start_time = time.time()
# Log the cleanup action
self.format_pbar_string(
TestReportingType.GROUP,
test_group.name,
TestingStates.DELETING,
start_time=test_group_start_time,
)
# TODO: do we want to clean up even if replay failed? Could have been partial failure?
# Delete attack data
self.delete_attack_data(test_group.attack_data)
# Return the cleanup metadata, adding start time and duration
return CleanupTestGroupResults(
duration=time.time() - cleanup_start_time, start_time=cleanup_start_time
)
def format_pbar_string(
self,
test_reporting_type: TestReportingType,
test_name: str,
state: str,
start_time: Optional[float] = None,
set_pbar: bool = True,
update_sync_status: bool = False,
) -> str:
"""
Instance specific function to log testing information via pbar; returns a formatted string
that can be written and optionally updates the existing progress bar
:param test_reporting_type: the type of reporting to be done (e.g. unit, integration, group)
:param test_name: the name of the test to be logged
:param state: the state/message of the test to be logged
:param start_time: the start_time of this progres bar
:param set_pbar: bool indicating whether pbar.update should be called
:param update_sync_status: bool indicating whether a sync status update should be queued
:returns: a formatted string for use w/ pbar
"""
# set start time if not provided
if start_time is None:
# if self.start_time is still None, something went wrong
if self.start_time is None:
raise ValueError(
"self.start_time is still None; a function may have been called before self.setup()"
)
start_time = self.start_time
# invoke the helper method
new_string = format_pbar_string(
self.pbar, test_reporting_type, test_name, state, start_time, set_pbar
)
# update sync status if needed
if update_sync_status:
self.sync_obj.currentTestingQueue[self.get_name()] = { # type: ignore
"name": state,
"search": "N/A",
}
# return the formatted string
return new_string
def execute_unit_test(
self,
detection: Detection,
test: UnitTest,
setup_results: SetupTestGroupResults,
FORCE_ALL_TIME: bool = True,
):
"""
Execute a unit test and set its results appropriately
:param detection: the detection being tested
:param test: the specific test case (UnitTest)
:param setup_results: the results of test group setup
:param FORCE_ALL_TIME: boolean flag; if True, searches check data for all time; if False,
any earliest_time or latest_time configured in the test is respected
"""
# Capture unit test start time
test_start_time = time.time()
# First, check to see if this test has been skipped; log and return if so
if test.result is not None and test.result.status == TestResultStatus.SKIP:
# report the skip to the CLI
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.SKIP,
start_time=test_start_time,
set_pbar=False,
)
)
return
# Reset the pbar and print that we are beginning a unit test
self.pbar.reset()
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
TestingStates.BEGINNING_TEST,
start_time=test_start_time,
)
# if the replay failed, record the test failure and return
if not setup_results.success:
test.result = UnitTestResult()
test.result.set_job_content(
None,
self.infrastructure,
TestResultStatus.ERROR,
exception=setup_results.exception,
duration=time.time() - test_start_time,
)
# report the failure to the CLI
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.ERROR,
start_time=test_start_time,
set_pbar=False,
)
)
return
# Set the mode and timeframe, if required
kwargs = {"exec_mode": "blocking"}
# Set earliest_time and latest_time appropriately if FORCE_ALL_TIME is False
if not FORCE_ALL_TIME:
if test.earliest_time is not None:
kwargs.update({"earliest_time": test.earliest_time})
if test.latest_time is not None:
kwargs.update({"latest_time": test.latest_time})
# Run the detection's search query
try:
# Iterate over baselines (if any)
for baseline in detection.baselines:
raise CannotRunBaselineException(
"Detection requires Execution of a Baseline, "
"however Baseline execution is not "
"currently supported in contentctl. Mark "
"this as manual_test."
)
self.retry_search_until_timeout(detection, test, kwargs, test_start_time)
except CannotRunBaselineException as e:
# Init the test result and record a failure if there was an issue during the search
test.result = UnitTestResult()
test.result.set_job_content(
None,
self.infrastructure,
TestResultStatus.ERROR,
exception=e,
duration=time.time() - test_start_time,
)
except ContainerStoppedException as e:
raise e
except Exception as e:
# Init the test result and record a failure if there was an issue during the search
print("\n\nexception trying search until timeout\n\n")
test.result = UnitTestResult()
test.result.set_job_content(
None,
self.infrastructure,
TestResultStatus.ERROR,
exception=e,
duration=time.time() - test_start_time,
)
# Pause here if the terminate flag has NOT been set AND either of the below are true:
# 1. the behavior is always_pause
# 2. the behavior is pause_on_failure and the test failed
if self.pause_for_user(test):
# Determine the state to report to the user
if test.result is None:
res = "ERROR"
link = detection.search
else:
res = test.result.status.upper() # type: ignore
link = test.result.get_summary_dict()["sid_link"]
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
f"{res} - {link} (CTRL+D to continue)",
start_time=test_start_time,
)
# Wait for user input
try:
_ = input()
except Exception:
pass
# Treat the case where no result is created as an error
if test.result is None:
message = "TEST ERROR: No result generated during testing"
test.result = UnitTestResult(
message=message,
exception=ValueError(message),
status=TestResultStatus.ERROR,
)
# Report a pass
if test.result.status == TestResultStatus.PASS:
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.PASS,
start_time=test_start_time,
set_pbar=False,
)
)
elif test.result.status == TestResultStatus.SKIP:
# Report a skip
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.SKIP,
start_time=test_start_time,
set_pbar=False,
)
)
elif test.result.status == TestResultStatus.FAIL:
# Report a FAIL
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.FAIL,
start_time=test_start_time,
set_pbar=False,
)
)
elif test.result.status == TestResultStatus.ERROR:
# Report an ERROR
self.pbar.write(
self.format_pbar_string(
TestReportingType.UNIT,
f"{detection.name}:{test.name}",
FinalTestingStates.ERROR,
start_time=test_start_time,
set_pbar=False,
)
)
else:
# Status was None or some other unexpected value
raise ValueError(
f"Status for (unit) '{detection.name}:{test.name}' was an unexpected"
f"value: {test.result.status}"
)
# Flush stdout and set duration
stdout.flush()
test.result.duration = round(time.time() - test_start_time, 2)
# TODO (#227): break up the execute routines for integration/unit tests some more to remove
# code w/ similar structure
def execute_integration_test(
self,
detection: Detection,
test: IntegrationTest,
setup_results: SetupTestGroupResults,
unit_test_result: Optional[UnitTestResult],
):
"""
Executes an integration test on the detection
:param detection: the detection on which to run the test
"""
# Capture unit test start time
test_start_time = time.time()
# First, check to see if the test should be skipped (Hunting or Correlation)
if detection.type in [AnalyticsType.Hunting, AnalyticsType.Correlation]:
test.skip(
f"TEST SKIPPED: detection is type {detection.type} and cannot be integration "
"tested at this time"
)
# Next, check to see if the unit test failed; preemptively fail integration testing if so
if unit_test_result is not None:
# check status is set (complete) and if failed (FAIL/ERROR)
if unit_test_result.complete and unit_test_result.failed:
test.result = IntegrationTestResult(
message="TEST FAILED (PREEMPTIVE): associated unit test failed or encountered an error",
exception=unit_test_result.exception,
status=unit_test_result.status,
)
# Next, check to see if this test has already had its status set (just now or elsewhere);
# log and return if so
if (test.result is not None) and test.result.complete:
# Determine the reporting state (we should only encounter SKIP/FAIL/ERROR)
state: str
if test.result.status == TestResultStatus.SKIP:
state = FinalTestingStates.SKIP
elif test.result.status == TestResultStatus.FAIL:
state = FinalTestingStates.FAIL
elif test.result.status == TestResultStatus.ERROR:
state = FinalTestingStates.ERROR
else:
raise ValueError(
f"Status for (integration) '{detection.name}:{test.name}' was preemptively set"
f"to an unexpected value: {test.result.status}"
)
# report the status to the CLI
self.pbar.write(
self.format_pbar_string(
TestReportingType.INTEGRATION,
f"{detection.name}:{test.name}",
state,
start_time=test_start_time,
set_pbar=False,
)
)
return
# Reset the pbar and print that we are beginning an integration test
self.pbar.reset()
self.format_pbar_string(
TestReportingType.INTEGRATION,
f"{detection.name}:{test.name}",
TestingStates.BEGINNING_TEST,
start_time=test_start_time,
)
# if the replay failed, record the test failure and return
if not setup_results.success:
test.result = IntegrationTestResult(
message=(
"TEST FAILED (ERROR): something went wrong during during TestGroup setup (e.g. "
"attack data replay)"
),