|
| 1 | +from pathlib import Path |
| 2 | +from typing import Any, Union, Type |
| 3 | +from contentctl.input.yml_reader import YmlReader |
| 4 | +from contentctl.objects.config import test_common, test, test_servers |
| 5 | +from contentctl.objects.security_content_object import SecurityContentObject |
| 6 | +from contentctl.input.director import DirectorOutputDto |
| 7 | + |
| 8 | +def config_from_file(path:Path=Path("contentctl.yml"), config: dict[str,Any]={}, |
| 9 | + configType:Type[Union[test,test_servers]]=test)->test_common: |
| 10 | + |
| 11 | + """ |
| 12 | + Fetch a configuration object that can be used for a number of different contentctl |
| 13 | + operations including validate, build, inspect, test, and test_servers. A file will |
| 14 | + be used as the basis for constructing the configuration. |
| 15 | +
|
| 16 | + Args: |
| 17 | + path (Path, optional): Relative or absolute path to a contentctl config file. |
| 18 | + Defaults to Path("contentctl.yml"), which is the default name and location (in the current directory) |
| 19 | + of the configuration files which are automatically generated for contentctl. |
| 20 | + config (dict[], optional): Dictionary of values to override values read from the YML |
| 21 | + path passed as the first argument. Defaults to {}, an empty dict meaning that nothing |
| 22 | + will be overwritten |
| 23 | + configType (Type[Union[test,test_servers]], optional): The Config Class to instantiate. |
| 24 | + This may be a test or test_servers object. Note that this is NOT an instance of the class. Defaults to test. |
| 25 | + Returns: |
| 26 | + test_common: Returns a complete contentctl test_common configuration. Note that this configuration |
| 27 | + will have all applicable field for validate and build as well, but can also be used for easily |
| 28 | + construction a test or test_servers object. |
| 29 | + """ |
| 30 | + |
| 31 | + try: |
| 32 | + yml_dict = YmlReader.load_file(path, add_fields=False) |
| 33 | + |
| 34 | + |
| 35 | + except Exception as e: |
| 36 | + raise Exception(f"Failed to load contentctl configuration from file '{path}': {str(e)}") |
| 37 | + |
| 38 | + # Apply settings that have been overridden from the ones in the file |
| 39 | + try: |
| 40 | + yml_dict.update(config) |
| 41 | + except Exception as e: |
| 42 | + raise Exception(f"Failed updating dictionary of values read from file '{path}'" |
| 43 | + f" with the dictionary of arguments passed: {str(e)}") |
| 44 | + |
| 45 | + # The function below will throw its own descriptive exception if it fails |
| 46 | + configObject = config_from_dict(yml_dict, configType=configType) |
| 47 | + |
| 48 | + return configObject |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +def config_from_dict(config: dict[str,Any]={}, |
| 54 | + configType:Type[Union[test,test_servers]]=test)->test_common: |
| 55 | + """ |
| 56 | + Fetch a configuration object that can be used for a number of different contentctl |
| 57 | + operations including validate, build, inspect, test, and test_servers. A dict will |
| 58 | + be used as the basis for constructing the configuration. |
| 59 | +
|
| 60 | + Args: |
| 61 | + config (dict[str,Any],Optional): If a dictionary is not explicitly passed, then |
| 62 | + an empty dict will be used to create a configuration, if possible, from default |
| 63 | + values. Note that based on default values in the contentctl/objects/config.py |
| 64 | + file, this may raise an exception. If so, please set appropriate default values |
| 65 | + in the file above or supply those values via this argument. |
| 66 | + configType (Type[Union[test,test_servers]], optional): The Config Class to instantiate. |
| 67 | + This may be a test or test_servers object. Note that this is NOT an instance of the class. Defaults to test. |
| 68 | + Returns: |
| 69 | + test_common: Returns a complete contentctl test_common configuration. Note that this configuration |
| 70 | + will have all applicable field for validate and build as well, but can also be used for easily |
| 71 | + construction a test or test_servers object. |
| 72 | + """ |
| 73 | + try: |
| 74 | + test_object = configType.model_validate(config) |
| 75 | + except Exception as e: |
| 76 | + raise Exception(f"Failed to load contentctl configuration from dict:\n{str(e)}") |
| 77 | + |
| 78 | + return test_object |
| 79 | + |
| 80 | + |
| 81 | +def update_config(config:Union[test,test_servers], **key_value_updates:dict[str,Any])->test_common: |
| 82 | + |
| 83 | + """Update any relevant keys in a config file with the specified values. |
| 84 | + Full validation will be performed after this update and descriptive errors |
| 85 | + will be produced |
| 86 | +
|
| 87 | + Args: |
| 88 | + config (test_common): A previously-constructed test_common object. This can be |
| 89 | + build using the configFromDict or configFromFile functions. |
| 90 | + key_value_updates (kwargs, optional): Additional keyword/argument pairs to update |
| 91 | + arbitrary fields in the configuration. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + test_common: A validated object which has had the relevant fields updated. |
| 95 | + Note that descriptive Exceptions will be generated if updated values are either |
| 96 | + invalid (have the wrong type, or disallowed values) or you attempt to update |
| 97 | + fields that do not exist |
| 98 | + """ |
| 99 | + # Create a copy so we don't change the underlying model |
| 100 | + config_copy = config.model_copy(deep=True) |
| 101 | + |
| 102 | + # Force validation of assignment since doing so via arbitrary dict can be error prone |
| 103 | + # Also, ensure that we do not try to add fields that are not part of the model |
| 104 | + config_copy.model_config.update({'validate_assignment': True, 'extra': 'forbid'}) |
| 105 | + |
| 106 | + |
| 107 | + |
| 108 | + # Collect any errors that may occur |
| 109 | + errors:list[Exception] = [] |
| 110 | + |
| 111 | + # We need to do this one by one because the extra:forbid argument does not appear to |
| 112 | + # be respected at this time. |
| 113 | + for key, value in key_value_updates.items(): |
| 114 | + try: |
| 115 | + setattr(config_copy,key,value) |
| 116 | + except Exception as e: |
| 117 | + errors.append(e) |
| 118 | + if len(errors) > 0: |
| 119 | + errors_string = '\n'.join([str(e) for e in errors]) |
| 120 | + raise Exception(f"Error(s) updaitng configuration:\n{errors_string}") |
| 121 | + |
| 122 | + return config_copy |
| 123 | + |
| 124 | + |
| 125 | + |
| 126 | +def content_to_dict(director:DirectorOutputDto)->dict[str,list[dict[str,Any]]]: |
| 127 | + output_dict:dict[str,list[dict[str,Any]]] = {} |
| 128 | + for contentType in ['detections','stories','baselines','investigations', |
| 129 | + 'playbooks','macros','lookups','deployments','ssa_detections']: |
| 130 | + |
| 131 | + output_dict[contentType] = [] |
| 132 | + t:list[SecurityContentObject] = getattr(director,contentType) |
| 133 | + |
| 134 | + for item in t: |
| 135 | + output_dict[contentType].append(item.model_dump()) |
| 136 | + return output_dict |
| 137 | + |
0 commit comments