Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CreateHash, DeduplicateValuesbyKey, JsonUnescape [Common Scripts Utility Consolidations] #23672

Merged
merged 31 commits into from Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ec0906d
Moved CreateHash script to CommonScripts
samuelFain Jan 9, 2023
4e561d2
Standardized CreateHash code
samuelFain Jan 9, 2023
e0a13f4
Added createHash UT
samuelFain Jan 9, 2023
ec2138f
Moved DeduplicateValuesbyKey to CommonScripts
samuelFain Jan 10, 2023
e58a564
Added DeduplicateValuesbyKey UT
samuelFain Jan 10, 2023
a61e1e0
Updated release notes, Moved JsonUnescape
samuelFain Jan 10, 2023
86c7e91
Added JsonUnescape UT
samuelFain Jan 10, 2023
057696a
Merge branch 'master' into sf_CreateHash
samuelFain Jan 10, 2023
b7217f1
fixed DeduplicateValuesbyKey UT
samuelFain Jan 10, 2023
6bb438e
Merge branch 'master' into sf_CreateHash
samuelFain Jan 10, 2023
c4d9d6b
Updated CommonScripts RN
samuelFain Jan 10, 2023
a62c72a
Merge branch 'master' into sf_CreateHash
samuelFain Jan 10, 2023
8e6ded4
Removed nosec from hashlib functions
samuelFain Jan 10, 2023
6a46a7c
Added to known_words.txt
samuelFain Jan 10, 2023
f5f3888
Fixed linting issue, Updated RN
samuelFain Jan 11, 2023
a347154
Merge branch 'master' into sf_CreateHash
samuelFain Jan 11, 2023
6fc6b9a
added noseq to ignore hash Bandit error
samuelFain Jan 11, 2023
a04ef42
Updated RN
samuelFain Jan 11, 2023
3037ad7
Merge branch 'master' into sf_CreateHash
samuelFain Jan 11, 2023
1e57bbc
Updated RN
samuelFain Jan 12, 2023
ce333a2
Updated RN
samuelFain Jan 12, 2023
d6cde16
Updated RN
samuelFain Jan 12, 2023
91409e5
Merge branch 'master' into sf_CreateHash
samuelFain Jan 12, 2023
c23c351
Updated RN
samuelFain Jan 12, 2023
3daf991
Updated RN
samuelFain Jan 12, 2023
7a4fa57
Merge branch 'master' into sf_CreateHash
samuelFain Jan 12, 2023
8b9937f
Updated RN
samuelFain Jan 12, 2023
c16cfe7
Merge branch 'master' into sf_CreateHash
samuelFain Jan 12, 2023
6fd242d
Merge branch 'master' into sf_CreateHash
samuelFain Jan 12, 2023
5b481a7
Updated docker images & RN
samuelFain Jan 12, 2023
06c9392
Merge branch 'master' into sf_CreateHash
samuelFain Jan 12, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions Packs/CommonScripts/ReleaseNotes/1_10_49.md
@@ -0,0 +1,9 @@

#### Scripts
##### New: JsonUnescape
- Recursively un-escapes JSON data if escaped JSON is found (Available from Cortex XSOAR 6.0.0).
##### New: DeduplicateValuesbyKey
- Given a list of objects and a key found in each of those objects, return a unique list of values associated with that key. Returns error if the objects provided do not contain the key of interest. (Available from Cortex XSOAR 6.0.0).
##### New: CreateHash
- Creating a hash of a given input, support sha1, sha256, sha512, md5 and blake. Wrapper for https://docs.python.org/3/library/hashlib.html.
(Available from Cortex XSOAR 6.0.0).
52 changes: 52 additions & 0 deletions Packs/CommonScripts/Scripts/CreateHash/CreateHash.py
@@ -0,0 +1,52 @@

import hashlib
from hashlib import blake2b

import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401


def create_hash(text, hashtype):
"""Create a hash from a given input and return it as a context outputs

Args:
text (str): input to hash
hashtype (str): hash type

Returns:
Dict[str,str]: Dictionary representing the command results context
"""
if hashtype == "sha512":
h = hashlib.sha512()
h.update(text.encode('utf-8'))
elif hashtype == "sha256":
h = hashlib.sha256()
h.update(text.encode('utf-8'))
elif hashtype == 'sha1':
h = hashlib.sha1() # nosec
h.update(text.encode('utf-8'))
elif hashtype == 'md5':
h = hashlib.md5() # nosec
h.update(text.encode('utf-8'))
else:
h = blake2b()
h.update(text.encode('utf-8'))

context = {
"CreateHash": str(h.hexdigest())
}

return context


def main(): # pragma: no cover
args = demisto.args()
text = args.get('text')
hashtype = args.get('type')

context = create_hash(text, hashtype)
return_results(CommandResults(outputs=context))


if __name__ in ('__builtin__', 'builtins', '__main__'):
main()
18 changes: 18 additions & 0 deletions Packs/CommonScripts/Scripts/CreateHash/CreateHash_test.py
@@ -0,0 +1,18 @@
import pytest


@pytest.mark.parametrize("hash_method", ['sha512', 'sha256', 'sha1', 'md5', ''])
def test_create_hash(hash_method):
"""
Given:
- A string
When:
- Running the script
Then:
- Ensure the expected hash is returned
"""
from CreateHash import create_hash
context = create_hash('test', hash_method)

assert isinstance(context, dict)
assert isinstance(context.get('CreateHash'), str)
@@ -1,23 +1,24 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401

"""Given a list of objects (dictionaries) and a key, generate a list
of unique values of that key in the list of objects."""

def generate_unique_values_from_objects(object_list, key, keep_none):
"""Given a list of objects (dictionaries) and a key,
generate a list of unique values of that key in the list of objects
and return the unique values list.

def main():

object_list = demisto.args().get("object_list")
key = demisto.args().get("key_of_interest")
keep_none = argToBoolean(demisto.args().get("keep_none"))

Args:
object_list (List[Dict]): list of objects (dictionaries)
key (Object): key of interest
keep_none (bool): whether to keep None values
"""
values = set()

for obj in object_list:
# Initially attempt to retrieve value using built-in object get method.
#
# This accounts for keys that may contain dots that are NOT intended
# to be retrieved from subkeys.
# to be retrieved from sub-keys.
if key in obj:
values.add(obj[key])
# Otherwise, use demisto.get to access values.
Expand All @@ -31,10 +32,21 @@ def main():
if not values:
return_error("The objects provided did not contain the key of interest.")

return list(values)


def main(): # pragma: no cover
args = demisto.args()
object_list = args.get("object_list")
key = args.get("key_of_interest")
keep_none = argToBoolean(args.get("keep_none"))

values = generate_unique_values_from_objects(object_list, key, keep_none)

return_results(CommandResults(
outputs_prefix="unique_values",
outputs_key_field="unique_values",
outputs={"unique_values": list(values)}))
outputs={"unique_values": values}))


if __name__ in ("__main__", "__builtin__", "builtins"):
Expand Down
@@ -0,0 +1,71 @@

import pytest


def test_generate_unique_values_from_objects():
from DeduplicateValuesbyKey import generate_unique_values_from_objects
objects = [
{
"key": "value1",
"value": "value1"
},
{
"key": "value1",
"value": "value2"
},
{
"key": "value2",
"value": "value3"
},
{
"key": "value2",
"value": "value4"
},
{
"key": "value3",
"value": "value5"
},
{
"key": "value3",
"value": "value6"
}]
values = generate_unique_values_from_objects(objects, "key", False)
assert set(values) == set(["value1", "value2", "value3"])


def test_generate_unique_values_from_objects_with_none():
from DeduplicateValuesbyKey import generate_unique_values_from_objects
objects = [
{
"key": "value1",
"value": "value1"
},
{
"key": "value1",
"value": "value2"
},
{
"key": "value2",
"value": "value3"
},
{
"key": "value2",
"value": "value4"
},
{
"key": "value3",
"value": "value5"
},
{
"key": "None_value",
"value": None
}]
values = generate_unique_values_from_objects(objects, "key", True)
assert set(values) == set(["None_value", "value1", "value2", "value3"])


def test_generate_unique_values_from_objects_fail():
from DeduplicateValuesbyKey import generate_unique_values_from_objects

with pytest.raises(SystemExit):
generate_unique_values_from_objects([], "key", True)
Expand Up @@ -7,6 +7,7 @@


def hook(obj: Dict) -> Dict:
""" Hook to convert string to json if possible """
new_obj = {}
for k, v in obj.items():
try:
Expand All @@ -17,13 +18,15 @@ def hook(obj: Dict) -> Dict:


def unescape(args: Dict) -> Union[Dict, List]:
""" Unescape json string """
json_str = json.dumps(args.get("value"))
return json.loads(json_str, object_hook=hook)


def main():
def main(): # noqa: F841
args = demisto.args()
try:
return_results(unescape(demisto.args()))
return_results(unescape(args))
except Exception as ex:
demisto.error(traceback.format_exc())
return_error(f"Error: {str(ex)}")
Expand Down
26 changes: 26 additions & 0 deletions Packs/CommonScripts/Scripts/JsonUnescape/JsonUnescape_test.py
@@ -0,0 +1,26 @@
def test_hook():
"""
Given
- A string value representing a json
When
- Running the hook function
Then
- Ensure the string value is converted to json
"""
from JsonUnescape import hook
assert hook({"key": "value"}) == {"key": "value"}
assert hook({"key": "{'key': 'value'}"}) == {'key': "{'key': 'value'}"}


def test_unescape():
"""
Given
- A dictionary with a string value
When
- Running the unescape function
Then
- Ensure the string value is converted to json
"""
from JsonUnescape import unescape
assert unescape({"value": "value"}) == 'value'
assert unescape({"value": "{'key': 'value'}"}) == "{'key': 'value'}"
1 change: 1 addition & 0 deletions Packs/CreateHash/ReleaseNotes/1_0_3.json
@@ -0,0 +1 @@
{"breakingChanges":true,"breakingChangesNotes":"The script: CreateHash moved to *CommonScripts* pack. Make sure to update the *CommonScripts* pack to the latest version in order to use this script."}
2 changes: 2 additions & 0 deletions Packs/CreateHash/ReleaseNotes/1_0_3.md
@@ -0,0 +1,2 @@
##### CreateHash
- Deprecated. **CreateHash** script moved to *Common Scripts* pack.
32 changes: 0 additions & 32 deletions Packs/CreateHash/Scripts/CreateHash/CreateHash.py

This file was deleted.

5 changes: 3 additions & 2 deletions Packs/CreateHash/pack_metadata.json
Expand Up @@ -2,10 +2,11 @@
"name": "CreateHash",
"description": "Simple wrapper of the https://docs.python.org/3/library/hashlib.html to produce sha512, sha256, sha1, md5 and Blake (simple hash) of a given text input",
"support": "community",
"currentVersion": "1.0.2",
"currentVersion": "1.0.3",
"author": "Joerg Stephan",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is the deprecating notes in the files? + hidden: true

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in later commit. all deprecating notes now exist for CreateHash.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samuelFain I still don't see it in here. Where is the deprecated in the name and description in this file?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed now :)

"url": "",
"email": "",
"hidden": true,
"created": "2021-12-06T11:19:01Z",
"categories": [
"Utilities"
Expand All @@ -20,4 +21,4 @@
"xsoar",
"marketplacev2"
]
}
}
1 change: 1 addition & 0 deletions Packs/DeduplicateValuesbyKey/ReleaseNotes/1_0_1.json
@@ -0,0 +1 @@
{"breakingChanges":true,"breakingChangesNotes":"The script: DeduplicateValuesbyKey moved to *CommonScripts* pack. Make sure to update the *CommonScripts* pack to the latest version in order to use this script."}
2 changes: 2 additions & 0 deletions Packs/DeduplicateValuesbyKey/ReleaseNotes/1_0_1.md
@@ -0,0 +1,2 @@
##### DeduplicateValuesbyKey
- Deprecated. **DeduplicateValuesbyKey** script moved to *Common Scripts* pack.
7 changes: 4 additions & 3 deletions Packs/DeduplicateValuesbyKey/pack_metadata.json
@@ -1,11 +1,12 @@
{
"name": "DeduplicateValuesbyKey",
"description": "Given a list of objects (dictionaries) and a key (string), return a list of unique values that appear for that key in the list of objects. \n\nThe current implementation only works on the first-level of keys. That is, given a dictionary like {key1: {key2: value}}, you can return a list of unique values for key1, but not key2. ",
"name": "DeduplicateValuesbyKey (Deprecated)",
"description": "Deprecated. DeduplicateValuesbyKey script moved to CommonScripts pack.",
"support": "community",
"currentVersion": "1.0.0",
"currentVersion": "1.0.1",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add hidden: true

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

"author": "Laura Farvour",
"url": "",
"email": "",
"hidden": true,
"created": "2021-12-07T17:00:09Z",
"categories": [
"Utilities"
Expand Down
1 change: 1 addition & 0 deletions Packs/JsonUnescape/ReleaseNotes/1_0_1.json
@@ -0,0 +1 @@
{"breakingChanges":true,"breakingChangesNotes":"The script: JsonUnescape moved to *CommonScripts* pack. Make sure to update the *CommonScripts* pack to the latest version in order to use this script."}
2 changes: 2 additions & 0 deletions Packs/JsonUnescape/ReleaseNotes/1_0_1.md
@@ -0,0 +1,2 @@
##### JsonUnescape
- Deprecated. **JsonUnescape** script moved to *Common Scripts* pack.
23 changes: 0 additions & 23 deletions Packs/JsonUnescape/Scripts/JsonUnescape/Pipfile

This file was deleted.