tcex 5.0.0.dev2__py3-none-any.whl → 5.0.0.dev4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tcex/__metadata__.py +1 -1
- tcex/api/tc/ti_transform/__init__.py +1 -5
- tcex/api/tc/ti_transform/ti_predefined_functions.py +12 -5
- tcex/api/tc/ti_transform/ti_transform.py +8 -8
- tcex/api/tc/ti_transform/transform_abc.py +8 -6
- tcex/api/tc/ti_transform/transform_builder/__init__.py +30 -0
- tcex/api/tc/ti_transform/transform_builder/v2/__init__.py +3 -0
- tcex/api/tc/ti_transform/transform_builder/v2/errors.py +36 -0
- tcex/api/tc/ti_transform/transform_builder/v2/load_transform.py +319 -0
- tcex/api/tc/util/threat_intel_util.py +2 -2
- tcex/api/tc/v2/batch/batch_cleaner.py +2 -2
- tcex/api/tc/v3/_gen/_gen_abc.py +2 -2
- tcex/api/tc/v3/_gen/_gen_model_abc.py +9 -11
- tcex/api/tc/v3/_gen/_gen_object_abc.py +15 -14
- tcex/api/tc/v3/_gen/_options_data_filter.py +0 -3
- tcex/api/tc/v3/_gen/_options_data_object.py +0 -3
- tcex/api/tc/v3/_gen/model/_filter_model.py +1 -1
- tcex/api/tc/v3/artifact_types/artifact_type.py +1 -1
- tcex/api/tc/v3/artifact_types/artifact_type_model.py +1 -1
- tcex/api/tc/v3/artifacts/artifact.py +1 -1
- tcex/api/tc/v3/artifacts/artifact_model.py +7 -7
- tcex/api/tc/v3/attribute_types/attribute_type.py +1 -1
- tcex/api/tc/v3/attribute_types/attribute_type_model.py +1 -1
- tcex/api/tc/v3/case_attributes/case_attribute.py +1 -1
- tcex/api/tc/v3/case_attributes/case_attribute_model.py +3 -3
- tcex/api/tc/v3/cases/case.py +2 -2
- tcex/api/tc/v3/cases/case_filter.py +1 -1
- tcex/api/tc/v3/cases/case_model.py +14 -14
- tcex/api/tc/v3/file_occurrences/file_occurrence_model.py +1 -1
- tcex/api/tc/v3/group_attributes/group_attribute.py +1 -1
- tcex/api/tc/v3/group_attributes/group_attribute_model.py +4 -4
- tcex/api/tc/v3/groups/group.py +2 -2
- tcex/api/tc/v3/groups/group_filter.py +36 -0
- tcex/api/tc/v3/groups/group_model.py +25 -20
- tcex/api/tc/v3/indicator_attributes/indicator_attribute.py +1 -1
- tcex/api/tc/v3/indicator_attributes/indicator_attribute_model.py +4 -4
- tcex/api/tc/v3/indicators/indicator.py +2 -2
- tcex/api/tc/v3/indicators/indicator_filter.py +16 -0
- tcex/api/tc/v3/indicators/indicator_model.py +10 -10
- tcex/api/tc/v3/intel_requirements/categories/category.py +1 -1
- tcex/api/tc/v3/intel_requirements/categories/category_model.py +1 -1
- tcex/api/tc/v3/intel_requirements/intel_req_type_model.py +1 -1
- tcex/api/tc/v3/intel_requirements/intel_requirement.py +3 -3
- tcex/api/tc/v3/intel_requirements/intel_requirement_model.py +10 -10
- tcex/api/tc/v3/intel_requirements/results/result.py +1 -1
- tcex/api/tc/v3/intel_requirements/results/result_model.py +1 -1
- tcex/api/tc/v3/intel_requirements/subtypes/subtype.py +1 -1
- tcex/api/tc/v3/intel_requirements/subtypes/subtype_model.py +1 -1
- tcex/api/tc/v3/notes/note.py +1 -1
- tcex/api/tc/v3/notes/note_model.py +5 -5
- tcex/api/tc/v3/object_abc.py +4 -3
- tcex/api/tc/v3/object_collection_abc.py +1 -1
- tcex/api/tc/v3/security/assignee_model.py +1 -1
- tcex/api/tc/v3/security/assignee_user_group_model.py +1 -1
- tcex/api/tc/v3/security/assignee_user_model.py +1 -1
- tcex/api/tc/v3/security/exclusion_lists/exclusion_list.py +1 -1
- tcex/api/tc/v3/security/exclusion_lists/exclusion_list_model.py +1 -1
- tcex/api/tc/v3/security/owner_roles/owner_role.py +1 -1
- tcex/api/tc/v3/security/owner_roles/owner_role_model.py +1 -1
- tcex/api/tc/v3/security/owners/owner.py +1 -1
- tcex/api/tc/v3/security/owners/owner_model.py +1 -1
- tcex/api/tc/v3/security/system_roles/system_role.py +1 -1
- tcex/api/tc/v3/security/system_roles/system_role_model.py +1 -1
- tcex/api/tc/v3/security/task_assignee_model.py +1 -1
- tcex/api/tc/v3/security/user_groups/user_group.py +1 -1
- tcex/api/tc/v3/security/user_groups/user_group_model.py +2 -2
- tcex/api/tc/v3/security/users/user.py +1 -1
- tcex/api/tc/v3/security/users/user_model.py +1 -1
- tcex/api/tc/v3/security_labels/security_label.py +1 -1
- tcex/api/tc/v3/security_labels/security_label_model.py +1 -1
- tcex/api/tc/v3/tags/tag.py +1 -1
- tcex/api/tc/v3/tags/tag_model.py +5 -5
- tcex/api/tc/v3/tasks/task.py +1 -1
- tcex/api/tc/v3/tasks/task_model.py +5 -5
- tcex/api/tc/v3/v3_model_abc.py +16 -16
- tcex/api/tc/v3/victim_assets/victim_asset.py +1 -1
- tcex/api/tc/v3/victim_assets/victim_asset_model.py +2 -2
- tcex/api/tc/v3/victim_attributes/victim_attribute.py +1 -1
- tcex/api/tc/v3/victim_attributes/victim_attribute_model.py +3 -3
- tcex/api/tc/v3/victims/victim.py +1 -1
- tcex/api/tc/v3/victims/victim_model.py +6 -6
- tcex/api/tc/v3/workflow_events/workflow_event.py +1 -1
- tcex/api/tc/v3/workflow_events/workflow_event_model.py +4 -4
- tcex/api/tc/v3/workflow_templates/workflow_template.py +1 -1
- tcex/api/tc/v3/workflow_templates/workflow_template_model.py +3 -3
- tcex/app/config/app_spec_yml.py +22 -1
- tcex/app/config/install_json.py +34 -0
- tcex/app/config/layout_json.py +17 -1
- tcex/app/config/model/app_spec_yml_model.py +2 -2
- tcex/app/config/model/install_json_model.py +4 -4
- tcex/app/config/model/job_json_model.py +8 -4
- tcex/app/config/model/layout_json_model.py +1 -1
- tcex/app/config/permutation.py +8 -8
- tcex/app/config/tcex_json.py +16 -0
- tcex/app/decorator/benchmark.py +6 -3
- tcex/app/decorator/debug.py +1 -1
- tcex/app/decorator/fail_on_output.py +1 -1
- tcex/app/decorator/on_exception.py +1 -1
- tcex/app/decorator/on_success.py +1 -1
- tcex/app/decorator/output.py +1 -1
- tcex/app/key_value_store/key_value_redis.py +3 -3
- tcex/app/playbook/advanced_request.py +1 -1
- tcex/app/playbook/playbook_create.py +24 -16
- tcex/app/playbook/playbook_read.py +2 -2
- tcex/app/service/common_service_trigger.py +2 -2
- tcex/app/service/mqtt_message_broker.py +6 -2
- tcex/app/service/webhook_trigger_service.py +1 -1
- tcex/app/token/token.py +1 -1
- tcex/input/field_type/edit_choice.py +4 -1
- tcex/input/field_type/key_value.py +3 -15
- tcex/input/field_type/validator.py +9 -8
- tcex/pleb/cached_property.py +3 -2
- tcex/pleb/cached_property_filesystem.py +3 -3
- tcex/pleb/jmespath_custom.py +18 -305
- tcex/pleb/jmespath_functions_array_mixin.py +665 -0
- tcex/pleb/jmespath_functions_base.py +43 -0
- tcex/pleb/jmespath_functions_control_mixin.py +91 -0
- tcex/pleb/jmespath_functions_crypto_mixin.py +65 -0
- tcex/pleb/jmespath_functions_datetime_mixin.py +130 -0
- tcex/pleb/jmespath_functions_math_mixin.py +236 -0
- tcex/pleb/jmespath_functions_object_mixin.py +253 -0
- tcex/pleb/jmespath_functions_string_mixin.py +602 -0
- tcex/pleb/proxies.py +2 -2
- tcex/registry.py +5 -2
- tcex/requests_external/external_session.py +6 -5
- tcex/requests_tc/auth/hmac_auth.py +6 -1
- tcex/requests_tc/auth/tc_auth.py +2 -2
- tcex/requests_tc/auth/token_auth.py +6 -1
- tcex/requests_tc/requests_tc.py +5 -3
- tcex/requests_tc/tc_session.py +13 -13
- tcex/util/code_operation.py +2 -1
- tcex/util/datetime_operation.py +2 -1
- tcex/util/requests_to_curl.py +6 -4
- {tcex-5.0.0.dev2.dist-info → tcex-5.0.0.dev4.dist-info}/METADATA +16 -16
- {tcex-5.0.0.dev2.dist-info → tcex-5.0.0.dev4.dist-info}/RECORD +138 -126
- {tcex-5.0.0.dev2.dist-info → tcex-5.0.0.dev4.dist-info}/WHEEL +0 -0
- {tcex-5.0.0.dev2.dist-info → tcex-5.0.0.dev4.dist-info}/licenses/LICENSE +0 -0
- {tcex-5.0.0.dev2.dist-info → tcex-5.0.0.dev4.dist-info}/top_level.txt +0 -0
tcex/__metadata__.py
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
"""TcEx Framework Module"""
|
|
2
2
|
|
|
3
|
-
from tcex.api.tc.ti_transform.ti_predefined_functions import
|
|
4
|
-
ProcessingFunctions,
|
|
5
|
-
transform_builder_to_model,
|
|
6
|
-
)
|
|
3
|
+
from tcex.api.tc.ti_transform.ti_predefined_functions import ProcessingFunctions
|
|
7
4
|
from tcex.api.tc.ti_transform.ti_transform import TiTransform, TiTransforms
|
|
8
5
|
from tcex.api.tc.ti_transform.transform_abc import TransformException
|
|
9
6
|
|
|
@@ -12,5 +9,4 @@ __all__ = [
|
|
|
12
9
|
'TiTransform',
|
|
13
10
|
'TiTransforms',
|
|
14
11
|
'TransformException',
|
|
15
|
-
'transform_builder_to_model',
|
|
16
12
|
]
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""TcEx Framework Module"""
|
|
2
|
+
# ruff: noqa: TRY301
|
|
2
3
|
|
|
3
4
|
import hashlib
|
|
4
5
|
import json
|
|
@@ -23,11 +24,17 @@ class TransformBuilderExport(TypedDict):
|
|
|
23
24
|
transform: dict
|
|
24
25
|
|
|
25
26
|
|
|
26
|
-
def
|
|
27
|
+
def _transform_builder_to_model(
|
|
27
28
|
transform: TransformBuilderExport,
|
|
28
29
|
processing_functions: 'ProcessingFunctions',
|
|
29
30
|
) -> IndicatorTransformModel | GroupTransformModel:
|
|
30
|
-
"""Convert a transform from Transform Builder to one of the tcex transform models.
|
|
31
|
+
"""Convert a transform from Transform Builder to one of the tcex transform models.
|
|
32
|
+
|
|
33
|
+
This is for transforms exported from Transform Builder v1, and should not be called directly.
|
|
34
|
+
|
|
35
|
+
Instead, use tcex.api.tc.ti_transform.transform_builder.load, which will detect the version of
|
|
36
|
+
the transform and call the appropriate function to convert it to a tcex transform model.
|
|
37
|
+
"""
|
|
31
38
|
|
|
32
39
|
def find_entries(data, key, context='') -> Iterable[tuple[str, dict]]:
|
|
33
40
|
"""Find entries in a dict with a given name, regardless of depth."""
|
|
@@ -260,7 +267,7 @@ class ProcessingFunctions:
|
|
|
260
267
|
|
|
261
268
|
if not type_:
|
|
262
269
|
ex_msg = 'No method or for_each key found in definition.'
|
|
263
|
-
raise ValueError(ex_msg)
|
|
270
|
+
raise ValueError(ex_msg)
|
|
264
271
|
|
|
265
272
|
fn_name = api_def[type_]
|
|
266
273
|
|
|
@@ -271,7 +278,7 @@ class ProcessingFunctions:
|
|
|
271
278
|
|
|
272
279
|
if not fn:
|
|
273
280
|
ex_msg = f'Unknown function: {fn_name}'
|
|
274
|
-
raise ValueError(ex_msg)
|
|
281
|
+
raise ValueError(ex_msg)
|
|
275
282
|
|
|
276
283
|
translated[type_] = fn
|
|
277
284
|
|
|
@@ -281,7 +288,7 @@ class ProcessingFunctions:
|
|
|
281
288
|
for kwarg in api_def['kwargs']:
|
|
282
289
|
if kwarg not in sig.parameters:
|
|
283
290
|
ex_msg = f'Unknown argument {kwarg} for function {fn_name}'
|
|
284
|
-
raise ValueError(ex_msg)
|
|
291
|
+
raise ValueError(ex_msg)
|
|
285
292
|
|
|
286
293
|
annotation = sig.parameters[kwarg].annotation
|
|
287
294
|
additional_context = f', Argument: {kwarg}'
|
|
@@ -154,7 +154,7 @@ class TiTransform(TransformABC):
|
|
|
154
154
|
{'summary': summary, 'indicatorType': indicator_type}
|
|
155
155
|
)
|
|
156
156
|
|
|
157
|
-
def add_associated_group(self,
|
|
157
|
+
def add_associated_group(self, group_xid: str):
|
|
158
158
|
"""Add an associated group.
|
|
159
159
|
|
|
160
160
|
{
|
|
@@ -165,33 +165,33 @@ class TiTransform(TransformABC):
|
|
|
165
165
|
if not self.separate_batch_associations:
|
|
166
166
|
# process type specific data
|
|
167
167
|
if isinstance(self.transform, GroupTransformModel):
|
|
168
|
-
self.transformed_item.setdefault('associatedGroupXid', []).append(
|
|
168
|
+
self.transformed_item.setdefault('associatedGroupXid', []).append(group_xid)
|
|
169
169
|
elif isinstance(self.transform, IndicatorTransformModel):
|
|
170
|
-
associated_group = {'groupXid':
|
|
170
|
+
associated_group = {'groupXid': group_xid}
|
|
171
171
|
self.transformed_item.setdefault('associatedGroups', []).append(associated_group)
|
|
172
172
|
elif isinstance(self.transform, GroupTransformModel):
|
|
173
173
|
self.transformed_item.setdefault('association', []).append(
|
|
174
174
|
{
|
|
175
|
-
'ref_1':
|
|
175
|
+
'ref_1': group_xid,
|
|
176
176
|
'ref_2': self.transformed_item['xid'],
|
|
177
177
|
}
|
|
178
178
|
)
|
|
179
179
|
self.log.trace(
|
|
180
180
|
'Added associated group with xid: %s to %s',
|
|
181
|
-
|
|
181
|
+
group_xid,
|
|
182
182
|
self.transformed_item['xid'],
|
|
183
183
|
)
|
|
184
184
|
elif isinstance(self.transform, IndicatorTransformModel):
|
|
185
185
|
self.transformed_item.setdefault('association', []).append(
|
|
186
186
|
{
|
|
187
|
-
'ref_1':
|
|
187
|
+
'ref_1': group_xid,
|
|
188
188
|
'ref_2': self.transformed_item['summary'],
|
|
189
189
|
'type_2': self.transformed_item['type'],
|
|
190
190
|
}
|
|
191
191
|
)
|
|
192
192
|
self.log.trace(
|
|
193
193
|
'Added associated group with xid: %s to %s',
|
|
194
|
-
|
|
194
|
+
group_xid,
|
|
195
195
|
self.transformed_item['summary'],
|
|
196
196
|
)
|
|
197
197
|
|
|
@@ -264,7 +264,7 @@ class TiTransform(TransformABC):
|
|
|
264
264
|
"""
|
|
265
265
|
self.adhoc_indicators.append(indicator_data)
|
|
266
266
|
|
|
267
|
-
def add_metadata(self, key: str, value: str):
|
|
267
|
+
def add_metadata(self, key: str, value: str | int):
|
|
268
268
|
"""Add name to the transformed item."""
|
|
269
269
|
if all([key, value]):
|
|
270
270
|
self.transformed_item[key] = value
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""TcEx Framework Module"""
|
|
2
2
|
|
|
3
|
+
# ruff: noqa: TRY301
|
|
3
4
|
import collections
|
|
4
5
|
import logging
|
|
5
6
|
from abc import ABC, abstractmethod
|
|
@@ -319,7 +320,7 @@ class TransformABC(ABC):
|
|
|
319
320
|
bool,
|
|
320
321
|
[v for v in self._process_metadata_transform_model(association.value) if v],
|
|
321
322
|
):
|
|
322
|
-
self.add_associated_group(value)
|
|
323
|
+
self.add_associated_group(value)
|
|
323
324
|
except Exception as ex:
|
|
324
325
|
ex_msg = f'Associated Group [{i}]'
|
|
325
326
|
raise TransformException(ex_msg, ex, context=association.model_dump()) from ex
|
|
@@ -601,7 +602,7 @@ class TransformABC(ABC):
|
|
|
601
602
|
for i, tag in enumerate(tags or [], 1):
|
|
602
603
|
try:
|
|
603
604
|
for value in filter(bool, self._process_metadata_transform_model(tag.value)):
|
|
604
|
-
self.add_tag(name=value)
|
|
605
|
+
self.add_tag(name=value)
|
|
605
606
|
except Exception as ex:
|
|
606
607
|
ex_msg = f'Tags [{i}]'
|
|
607
608
|
raise TransformException(ex_msg, ex, context=tag.model_dump()) from ex
|
|
@@ -629,7 +630,7 @@ class TransformABC(ABC):
|
|
|
629
630
|
f'path={transform.type.path}, value={_type}'
|
|
630
631
|
)
|
|
631
632
|
ex_msg = 'Invalid type'
|
|
632
|
-
raise RuntimeError(ex_msg)
|
|
633
|
+
raise RuntimeError(ex_msg)
|
|
633
634
|
except Exception as ex:
|
|
634
635
|
ex_msg = 'Type'
|
|
635
636
|
raise TransformException(ex_msg, ex, context=transform.type.model_dump()) from ex
|
|
@@ -765,7 +766,7 @@ class TransformABC(ABC):
|
|
|
765
766
|
if v_ is not None:
|
|
766
767
|
_values.append(v_)
|
|
767
768
|
value = _values
|
|
768
|
-
#
|
|
769
|
+
# type-checker miss - None check for value already performed above
|
|
769
770
|
elif callable(t.method) and value is not None:
|
|
770
771
|
value = self._transform_value_callable(value, t.method, t.kwargs)
|
|
771
772
|
elif callable(t.for_each):
|
|
@@ -774,8 +775,9 @@ class TransformABC(ABC):
|
|
|
774
775
|
for v in self._always_array(value)
|
|
775
776
|
]
|
|
776
777
|
|
|
777
|
-
# the output should be an array of strings or empty array
|
|
778
|
-
|
|
778
|
+
# the output should be an array of strings or empty array; the accumulator may transiently
|
|
779
|
+
# hold non-string members (e.g. a numeric metadata.default) before stringification.
|
|
780
|
+
_value: list[Any] = []
|
|
779
781
|
for v in self._always_array(value):
|
|
780
782
|
if v in [None, '']:
|
|
781
783
|
if metadata.default is not None:
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Module for various utilities for working with transforms created with Transform Builder."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from tcex.api.tc.ti_transform.model.transform_model import (
|
|
7
|
+
GroupTransformModel,
|
|
8
|
+
IndicatorTransformModel,
|
|
9
|
+
)
|
|
10
|
+
from tcex.api.tc.ti_transform.ti_predefined_functions import (
|
|
11
|
+
ProcessingFunctions,
|
|
12
|
+
_transform_builder_to_model,
|
|
13
|
+
)
|
|
14
|
+
from tcex.api.tc.ti_transform.transform_builder.v2.load_transform import LoadTransform
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def load(
|
|
18
|
+
transform: dict,
|
|
19
|
+
processing_functions: 'ProcessingFunctions',
|
|
20
|
+
) -> IndicatorTransformModel | GroupTransformModel:
|
|
21
|
+
"""Convert a transform from Transform Builder to one of the tcex transform models."""
|
|
22
|
+
|
|
23
|
+
match transform:
|
|
24
|
+
case {'transform': dict(), 'type': str()}: # TB v1
|
|
25
|
+
return _transform_builder_to_model(transform, processing_functions) # type: ignore
|
|
26
|
+
case {'metadata': {'threatIntelType': str()}}: # TB v2
|
|
27
|
+
return LoadTransform(processing_functions).load_transform(transform)
|
|
28
|
+
case _:
|
|
29
|
+
ex_msg = 'Unrecognized transform format.'
|
|
30
|
+
raise ValueError(ex_msg)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Errors for the Transform Builder."""
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict
|
|
6
|
+
from pydantic.alias_generators import to_camel
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ModelBase(BaseModel):
|
|
10
|
+
"""Model Definition"""
|
|
11
|
+
|
|
12
|
+
model_config = ConfigDict(
|
|
13
|
+
alias_generator=to_camel,
|
|
14
|
+
extra='forbid',
|
|
15
|
+
validate_assignment=True,
|
|
16
|
+
validate_by_name=True,
|
|
17
|
+
validate_default=True,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TransformErrorCause(ModelBase):
|
|
22
|
+
"""Cause for an error, which should be enough information to locate the issue."""
|
|
23
|
+
|
|
24
|
+
section: Literal[
|
|
25
|
+
'Metadata', 'Associations', 'Attributes', 'File Occurrences', 'Security Labels', 'Tags'
|
|
26
|
+
]
|
|
27
|
+
name: str
|
|
28
|
+
index: int | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TransformError(ModelBase):
|
|
32
|
+
"""Structured presentation of a validation error with a transform."""
|
|
33
|
+
|
|
34
|
+
message: str
|
|
35
|
+
cause: TransformErrorCause
|
|
36
|
+
definition: dict
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Utility to load transform files."""
|
|
2
|
+
|
|
3
|
+
# ruff: noqa: TRY301
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from inspect import signature
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from tcex.api.tc.ti_transform.model.transform_model import (
|
|
10
|
+
GroupTransformModel,
|
|
11
|
+
IndicatorTransformModel,
|
|
12
|
+
)
|
|
13
|
+
from tcex.api.tc.ti_transform.ti_predefined_functions import ProcessingFunctions
|
|
14
|
+
from tcex.api.tc.ti_transform.transform_builder.v2.errors import TransformError, TransformErrorCause
|
|
15
|
+
from tcex.logger.trace_logger import TraceLogger
|
|
16
|
+
from tcex.util import Util
|
|
17
|
+
|
|
18
|
+
_logger: TraceLogger = logging.getLogger(__name__.split('.', maxsplit=1)[0]) # type: ignore
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LoadTransform:
|
|
22
|
+
"""Load and process transform mapping JSON."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
processing_functions: ProcessingFunctions,
|
|
27
|
+
log: logging.Logger = _logger,
|
|
28
|
+
):
|
|
29
|
+
"""Initialize class properties."""
|
|
30
|
+
self.util = Util()
|
|
31
|
+
self.log = log
|
|
32
|
+
self.fns = processing_functions
|
|
33
|
+
|
|
34
|
+
def load_transform(
|
|
35
|
+
self,
|
|
36
|
+
mapping_json: dict,
|
|
37
|
+
) -> GroupTransformModel | IndicatorTransformModel:
|
|
38
|
+
"""Load and process the transform mapping JSON."""
|
|
39
|
+
metadata = mapping_json.pop('metadata', {})
|
|
40
|
+
ti_type = metadata['threatIntelType']
|
|
41
|
+
# transformSchemaVersion = metadata.get('transformSchemaVersion', '1')
|
|
42
|
+
match ti_type:
|
|
43
|
+
case 'group':
|
|
44
|
+
return GroupTransformModel(**self._transform_data(self._normalize(mapping_json)))
|
|
45
|
+
case 'indicator':
|
|
46
|
+
return IndicatorTransformModel(
|
|
47
|
+
**self._transform_data(self._normalize(mapping_json))
|
|
48
|
+
)
|
|
49
|
+
case _:
|
|
50
|
+
msg = f'Unknown transform type: {ti_type}'
|
|
51
|
+
raise TypeError(msg)
|
|
52
|
+
|
|
53
|
+
def _normalize(self, data: dict) -> dict:
|
|
54
|
+
"""Normalize the transform data."""
|
|
55
|
+
normalized = {}
|
|
56
|
+
for key, value in data.items():
|
|
57
|
+
normalized_key = self.util.camel_to_snake(key)
|
|
58
|
+
if isinstance(value, dict):
|
|
59
|
+
normalized[normalized_key] = self._normalize(value)
|
|
60
|
+
elif isinstance(value, list):
|
|
61
|
+
normalized[normalized_key] = [
|
|
62
|
+
self._normalize(item) if isinstance(item, dict) else item for item in value
|
|
63
|
+
]
|
|
64
|
+
else:
|
|
65
|
+
normalized[normalized_key] = value
|
|
66
|
+
|
|
67
|
+
return normalized
|
|
68
|
+
|
|
69
|
+
def _transform_data(self, body: dict) -> dict:
|
|
70
|
+
"""Transform the data."""
|
|
71
|
+
fields_copy = {**body}
|
|
72
|
+
fields_copy.pop('associated_indicators', None)
|
|
73
|
+
|
|
74
|
+
transform_data = {}
|
|
75
|
+
|
|
76
|
+
for j, (field_key, field_value) in enumerate(fields_copy.items()):
|
|
77
|
+
match field_key:
|
|
78
|
+
case 'associated_groups' | 'security_labels' | 'tags':
|
|
79
|
+
for i, item in enumerate(field_value):
|
|
80
|
+
value = item.get('value', {})
|
|
81
|
+
try:
|
|
82
|
+
metadata = item.pop('metadata', {})
|
|
83
|
+
transform_data.setdefault(field_key, []).append(item)
|
|
84
|
+
|
|
85
|
+
if isinstance(value, dict):
|
|
86
|
+
self._translate_processing_function(value)
|
|
87
|
+
except Exception:
|
|
88
|
+
# best effort to continue processing other items
|
|
89
|
+
self.log.exception(
|
|
90
|
+
TransformError(
|
|
91
|
+
message=f'Error processing {field_key} field',
|
|
92
|
+
cause=TransformErrorCause(
|
|
93
|
+
section=self._field_type_to_error_type(field_key),
|
|
94
|
+
index=i,
|
|
95
|
+
name=self._field_type_to_error_type(field_key),
|
|
96
|
+
),
|
|
97
|
+
definition=value,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
case 'associated_indicators' | 'attributes' | 'file_occurrences':
|
|
103
|
+
# Remove metadata from attribute objects
|
|
104
|
+
for i, field in enumerate(field_value):
|
|
105
|
+
try:
|
|
106
|
+
metadata = field.pop('metadata', {})
|
|
107
|
+
if metadata.get('disabled', False):
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
for af, ad in list(field.items()):
|
|
111
|
+
if isinstance(ad, dict):
|
|
112
|
+
metadata = ad.pop('metadata', {})
|
|
113
|
+
if (
|
|
114
|
+
af
|
|
115
|
+
in (
|
|
116
|
+
'type',
|
|
117
|
+
'value',
|
|
118
|
+
'summary',
|
|
119
|
+
'association_type',
|
|
120
|
+
)
|
|
121
|
+
and not ad.get('path')
|
|
122
|
+
and not ad.get('default')
|
|
123
|
+
):
|
|
124
|
+
field.pop(af, None)
|
|
125
|
+
self.log.error(
|
|
126
|
+
TransformError(
|
|
127
|
+
message='{af} required',
|
|
128
|
+
cause=TransformErrorCause(
|
|
129
|
+
section=self._field_type_to_error_type(
|
|
130
|
+
field_key
|
|
131
|
+
),
|
|
132
|
+
index=i,
|
|
133
|
+
name=self._field_type_to_error_type(field_key),
|
|
134
|
+
),
|
|
135
|
+
definition=field,
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
msg = '{af} required'
|
|
139
|
+
raise RuntimeError(msg)
|
|
140
|
+
|
|
141
|
+
self._translate_processing_function(field[af])
|
|
142
|
+
|
|
143
|
+
transform_data.setdefault(field_key, []).append(field)
|
|
144
|
+
except Exception:
|
|
145
|
+
# best effort to continue processing other items
|
|
146
|
+
self.log.exception(
|
|
147
|
+
TransformError(
|
|
148
|
+
message=f'Error processing {field_key} field',
|
|
149
|
+
cause=TransformErrorCause(
|
|
150
|
+
section=self._field_type_to_error_type(field_key),
|
|
151
|
+
index=i,
|
|
152
|
+
name=self._field_type_to_error_type(field_key),
|
|
153
|
+
),
|
|
154
|
+
definition=field,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
raise
|
|
158
|
+
|
|
159
|
+
case _:
|
|
160
|
+
try:
|
|
161
|
+
# skip null configured fields
|
|
162
|
+
if not field_value:
|
|
163
|
+
self.log.error(
|
|
164
|
+
TransformError(
|
|
165
|
+
message='missing value',
|
|
166
|
+
cause=TransformErrorCause(
|
|
167
|
+
section=self._field_type_to_error_type(field_key),
|
|
168
|
+
name=field_key,
|
|
169
|
+
),
|
|
170
|
+
definition=field_value,
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
msg = 'missing value'
|
|
174
|
+
raise RuntimeError(msg)
|
|
175
|
+
|
|
176
|
+
# Remove metadata from standard fields
|
|
177
|
+
metadata = field_value.pop('metadata', {})
|
|
178
|
+
|
|
179
|
+
# do not transform disabled fields or fields without path/default
|
|
180
|
+
if metadata.get('disabled', False) or not (
|
|
181
|
+
field_value.get('path') or field_value.get('default')
|
|
182
|
+
):
|
|
183
|
+
self.log.error(
|
|
184
|
+
TransformError(
|
|
185
|
+
message='missing value',
|
|
186
|
+
cause=TransformErrorCause(
|
|
187
|
+
section=self._field_type_to_error_type(field_key),
|
|
188
|
+
index=j,
|
|
189
|
+
name=field_key,
|
|
190
|
+
),
|
|
191
|
+
definition=field_value,
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
msg = 'missing value'
|
|
195
|
+
raise RuntimeError(msg)
|
|
196
|
+
transform_data[field_key] = field_value
|
|
197
|
+
|
|
198
|
+
self._translate_processing_function(field_value)
|
|
199
|
+
|
|
200
|
+
except Exception:
|
|
201
|
+
# best effort to continue processing other items
|
|
202
|
+
self.log.exception(
|
|
203
|
+
TransformError(
|
|
204
|
+
message=f'Error processing {field_key} field',
|
|
205
|
+
cause=TransformErrorCause(
|
|
206
|
+
section=self._field_type_to_error_type(field_key),
|
|
207
|
+
index=j,
|
|
208
|
+
name=field_key,
|
|
209
|
+
),
|
|
210
|
+
definition=field_value,
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
raise
|
|
214
|
+
|
|
215
|
+
# Clean the transform data by removing empty lists, dicts, and None values
|
|
216
|
+
return self._clean_empty_values(transform_data)
|
|
217
|
+
|
|
218
|
+
def _clean_empty_values(self, data: dict) -> dict:
|
|
219
|
+
"""Remove keys with empty lists, dicts, or None values recursively."""
|
|
220
|
+
clean_data = {}
|
|
221
|
+
for key, value in data.items():
|
|
222
|
+
if value is None:
|
|
223
|
+
continue
|
|
224
|
+
|
|
225
|
+
if isinstance(value, dict):
|
|
226
|
+
# Recursively clean nested dictionaries
|
|
227
|
+
cleaned_dict = self._clean_empty_values(value)
|
|
228
|
+
if cleaned_dict: # Only add if the cleaned dict is not empty
|
|
229
|
+
clean_data[key] = cleaned_dict
|
|
230
|
+
elif isinstance(value, list):
|
|
231
|
+
# Recursively clean items in lists
|
|
232
|
+
cleaned_list = []
|
|
233
|
+
for item in value:
|
|
234
|
+
if isinstance(item, dict):
|
|
235
|
+
cleaned_item = self._clean_empty_values(item)
|
|
236
|
+
if cleaned_item: # Only add if the cleaned dict is not empty
|
|
237
|
+
cleaned_list.append(cleaned_item)
|
|
238
|
+
elif item is not None: # Keep non-None list items
|
|
239
|
+
cleaned_list.append(item)
|
|
240
|
+
if cleaned_list: # Only add if the cleaned list is not empty
|
|
241
|
+
clean_data[key] = cleaned_list
|
|
242
|
+
else:
|
|
243
|
+
# Keep all other non-None values
|
|
244
|
+
clean_data[key] = value
|
|
245
|
+
return clean_data
|
|
246
|
+
|
|
247
|
+
def _translate_processing_function(self, mapping: dict):
|
|
248
|
+
"""Translate a function definition in transform builder/API format to an actual function."""
|
|
249
|
+
# convert transform function names to callables
|
|
250
|
+
transforms_with_callable = []
|
|
251
|
+
for function in mapping.get('transform', []):
|
|
252
|
+
transforms_with_callable.append(self._function_name_to_callable(function))
|
|
253
|
+
if transforms_with_callable:
|
|
254
|
+
mapping['transform'] = transforms_with_callable
|
|
255
|
+
else:
|
|
256
|
+
mapping.pop('transform', None)
|
|
257
|
+
|
|
258
|
+
def _function_name_to_callable(self, function_data: dict):
|
|
259
|
+
"""Translate a function definition in transform builder/API format to an actual function."""
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
translated = function_data.copy()
|
|
263
|
+
type_ = 'method' if 'method' in function_data else 'for_each'
|
|
264
|
+
|
|
265
|
+
fn_name = function_data[type_]
|
|
266
|
+
|
|
267
|
+
# REMOVE: if name is already a callable, return it
|
|
268
|
+
if callable(fn_name):
|
|
269
|
+
return function_data
|
|
270
|
+
|
|
271
|
+
fn = getattr(self.fns, fn_name)
|
|
272
|
+
|
|
273
|
+
if not fn:
|
|
274
|
+
msg = f'Function {fn_name} not found.'
|
|
275
|
+
raise RuntimeError(msg)
|
|
276
|
+
|
|
277
|
+
translated[type_] = fn
|
|
278
|
+
|
|
279
|
+
if 'kwargs' in function_data:
|
|
280
|
+
sig = signature(fn)
|
|
281
|
+
|
|
282
|
+
for kwarg in function_data['kwargs']:
|
|
283
|
+
if kwarg not in sig.parameters:
|
|
284
|
+
msg = f'Unknown argument ("{kwarg}") for function {fn_name}.'
|
|
285
|
+
raise RuntimeError(msg)
|
|
286
|
+
|
|
287
|
+
annotation = sig.parameters[kwarg].annotation
|
|
288
|
+
match annotation():
|
|
289
|
+
case dict():
|
|
290
|
+
translated['kwargs'][kwarg] = json.loads(function_data['kwargs'][kwarg])
|
|
291
|
+
case _:
|
|
292
|
+
translated['kwargs'][kwarg] = sig.parameters[kwarg].annotation(
|
|
293
|
+
function_data['kwargs'][kwarg]
|
|
294
|
+
)
|
|
295
|
+
except Exception as ex:
|
|
296
|
+
self.log.exception('Error translating function definition')
|
|
297
|
+
msg = 'Error loading function'
|
|
298
|
+
raise RuntimeError(msg) from ex
|
|
299
|
+
return translated
|
|
300
|
+
|
|
301
|
+
def _field_type_to_error_type(
|
|
302
|
+
self,
|
|
303
|
+
field_key: str,
|
|
304
|
+
) -> Literal[
|
|
305
|
+
'Metadata', 'Associations', 'Attributes', 'File Occurrences', 'Security Labels', 'Tags'
|
|
306
|
+
]:
|
|
307
|
+
match field_key:
|
|
308
|
+
case 'associated_groups' | 'associated_indicators':
|
|
309
|
+
return 'Associations'
|
|
310
|
+
case 'security_labels':
|
|
311
|
+
return 'Security Labels'
|
|
312
|
+
case 'tags':
|
|
313
|
+
return 'Tags'
|
|
314
|
+
case 'attributes':
|
|
315
|
+
return 'Attributes'
|
|
316
|
+
case 'file_occurrences':
|
|
317
|
+
return 'File Occurrences'
|
|
318
|
+
case _:
|
|
319
|
+
return 'Metadata'
|
|
@@ -194,14 +194,14 @@ class ThreatIntelUtil:
|
|
|
194
194
|
"""
|
|
195
195
|
return list(self.indicator_types_data.keys())
|
|
196
196
|
|
|
197
|
-
def resolve_variables(self, inputs: list[str]) -> list[str]:
|
|
197
|
+
def resolve_variables(self, inputs: list[str]) -> list[str | None]:
|
|
198
198
|
"""Resolve all of the provided inputs if appropriate.
|
|
199
199
|
|
|
200
200
|
Args:
|
|
201
201
|
inputs: A list of strings to resolve if string matches a entry in the
|
|
202
202
|
"resolved_variables" dict.
|
|
203
203
|
"""
|
|
204
|
-
resolved_inputs = []
|
|
204
|
+
resolved_inputs: list[str | None] = []
|
|
205
205
|
for input_ in inputs:
|
|
206
206
|
# handle null inputs
|
|
207
207
|
if not input_:
|
|
@@ -246,7 +246,7 @@ class BatchCleaner:
|
|
|
246
246
|
if not config:
|
|
247
247
|
return attribute_value
|
|
248
248
|
|
|
249
|
-
max_length = config.get('
|
|
249
|
+
max_length = config.get('max_size')
|
|
250
250
|
if not max_length:
|
|
251
251
|
return attribute_value
|
|
252
252
|
|
|
@@ -275,7 +275,7 @@ class BatchCleaner:
|
|
|
275
275
|
item: A single group or indicator dictionary.
|
|
276
276
|
attribute_types: Attribute type config dict keyed by name.
|
|
277
277
|
deduplicate: Whether to remove duplicate attributes.
|
|
278
|
-
truncate: Whether to truncate attributes based on
|
|
278
|
+
truncate: Whether to truncate attributes based on max_size.
|
|
279
279
|
truncated_types: A shared set tracking attribute types that have already
|
|
280
280
|
been logged as truncated, to avoid duplicate log warnings. If None,
|
|
281
281
|
warnings are logged for every truncation.
|
tcex/api/tc/v3/_gen/_gen_abc.py
CHANGED
|
@@ -128,7 +128,7 @@ class GenerateABC(ABC): # noqa: B024
|
|
|
128
128
|
_imports = [] # temp store for imports so they can be sorted
|
|
129
129
|
for lib in libs:
|
|
130
130
|
if isinstance(lib, dict):
|
|
131
|
-
imports = ', '.join(sorted(lib.get('imports')))
|
|
131
|
+
imports = ', '.join(sorted(lib.get('imports')))
|
|
132
132
|
_imports.append(f'{indent}from {lib.get("module")} import {imports}{comment}')
|
|
133
133
|
elif isinstance(lib, str):
|
|
134
134
|
_imports.append(f'{indent}{lib}{comment}')
|
|
@@ -138,7 +138,7 @@ class GenerateABC(ABC): # noqa: B024
|
|
|
138
138
|
_libs.append('') # add newline
|
|
139
139
|
|
|
140
140
|
# This is the last part of the requirements generated.
|
|
141
|
-
return '\n'.join(_libs)
|
|
141
|
+
return '\n'.join(_libs)
|
|
142
142
|
|
|
143
143
|
def tap(self, type_: str):
|
|
144
144
|
"""Return the TcEx Api Path."""
|