Skip to content

Commit 7328144

Browse files
committed
Add typing to worker module
1 parent 1ffc3cf commit 7328144

3 files changed

Lines changed: 47 additions & 23 deletions

File tree

cortexutils/py.typed

Whitespace-only changes.

cortexutils/worker.py

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,25 @@
55
import json
66
import os
77
import sys
8+
from typing import Sequence, Any, NoReturn
89

9-
DEFAULT_SECRET_PHRASES = ("key", "password", "secret")
10+
DEFAULT_SECRET_PHRASES: Sequence[str] = ("key", "password", "secret")
1011

1112

1213
class Worker:
1314
READ_TIMEOUT = 3 # seconds
1415

15-
def __init__(self, job_directory, secret_phrases):
16+
def __init__(
17+
self,
18+
job_directory: str | None,
19+
secret_phrases: Sequence[str] | None = None,
20+
) -> None:
1621
if job_directory is None:
1722
if len(sys.argv) > 1:
1823
job_directory = sys.argv[1]
1924
else:
2025
job_directory = "/job"
21-
self.job_directory = job_directory
26+
self.job_directory: str | None = job_directory
2227
if secret_phrases is None:
2328
self.secret_phrases = DEFAULT_SECRET_PHRASES
2429
else:
@@ -57,20 +62,20 @@ def __init__(self, job_directory, secret_phrases):
5762
self.__set_proxies()
5863

5964
# Finally run check tlp
60-
if not (self.__check_tlp()):
65+
if not self.__check_tlp():
6166
self.error("TLP is higher than allowed.")
6267

63-
if not (self.__check_pap()):
68+
if not self.__check_pap():
6469
self.error("PAP is higher than allowed.")
6570

66-
def __set_proxies(self):
71+
def __set_proxies(self) -> None:
6772
if self.http_proxy is not None:
6873
os.environ["http_proxy"] = self.http_proxy
6974
if self.https_proxy is not None:
7075
os.environ["https_proxy"] = self.https_proxy
7176

7277
@staticmethod
73-
def __set_encoding():
78+
def __set_encoding() -> None:
7479
try:
7580
if sys.stdout.encoding != "UTF-8":
7681
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict")
@@ -79,7 +84,13 @@ def __set_encoding():
7984
except Exception:
8085
pass # nosec B110
8186

82-
def __get_param(self, source, name, default=None, message=None):
87+
def __get_param(
88+
self,
89+
source: dict,
90+
name: str | list[str],
91+
default: Any = None,
92+
message: str | None = None,
93+
) -> Any:
8394
"""Extract a specific parameter from given source.
8495
:param source: Python dict to search through
8596
:param name: Name of the parameter to get. JSON-like syntax,
@@ -104,17 +115,17 @@ def __get_param(self, source, name, default=None, message=None):
104115
self.error(message)
105116
return default
106117

107-
def __check_tlp(self):
118+
def __check_tlp(self) -> bool:
108119
"""Check if tlp is okay or not; returns False if too high."""
109120

110121
return not (self.enable_check_tlp and self.tlp > self.max_tlp)
111122

112-
def __check_pap(self):
123+
def __check_pap(self) -> bool:
113124
"""Check if pap is okay or not; returns False if too high."""
114125

115126
return not (self.enable_check_pap and self.pap > self.max_pap)
116127

117-
def __write_output(self, data, ensure_ascii=False):
128+
def __write_output(self, data: dict, ensure_ascii: bool = False) -> None:
118129
if self.job_directory is None:
119130
json.dump(data, sys.stdout, ensure_ascii=ensure_ascii)
120131
else:
@@ -124,31 +135,35 @@ def __write_output(self, data, ensure_ascii=False):
124135
with open(output_path, mode="w") as f_output:
125136
json.dump(data, f_output, ensure_ascii=ensure_ascii)
126137

127-
def get_data(self):
138+
def get_data(self) -> Any:
128139
"""Wrapper for getting data from input dict.
129140
130141
:return: Data (observable value) given through Cortex"""
131142
return self.get_param("data", None, "Missing data field")
132143

133144
@staticmethod
134-
def build_operation(op_type, **parameters):
145+
def build_operation(op_type: str, **parameters: dict) -> dict:
135146
"""
136147
:param op_type: an operation type as a string
137148
:param parameters: a dict including the operation's params
138149
:return: dict
139150
"""
140-
operation = {"type": op_type}
151+
operation: dict = {"type": op_type}
141152
operation.update(parameters)
142-
143153
return operation
144154

145-
def operations(self, raw):
155+
def operations(self, raw: dict) -> list[dict]:
146156
"""Returns the list of operations to be executed after the job completes
147157
148158
:returns: by default return an empty array"""
149159
return []
150160

151-
def get_param(self, name, default=None, message=None):
161+
def get_param(
162+
self,
163+
name: str,
164+
default: Any = None,
165+
message: str | None = None,
166+
) -> Any:
152167
"""Just a wrapper for Analyzer.__get_param.
153168
:param name: Name of the parameter to get.
154169
JSON-like syntax, e.g. `config.username`
@@ -159,7 +174,12 @@ def get_param(self, name, default=None, message=None):
159174

160175
return self.__get_param(self._input, name, default, message)
161176

162-
def get_env(self, key, default=None, message=None):
177+
def get_env(
178+
self,
179+
key: str,
180+
default: Any = None,
181+
message: str | None = None,
182+
) -> Any:
163183
"""Wrapper for getting configuration values from the environment.
164184
:param key: Key of the environment variable to get.
165185
:param default: Default value, if not found. Default: None
@@ -174,7 +194,8 @@ def get_env(self, key, default=None, message=None):
174194
self.error(message)
175195
return default
176196

177-
def error(self, message, ensure_ascii=False):
197+
# def error(self, message: str, ensure_ascii: bool = False):
198+
def error(self, message: str, ensure_ascii: bool = False) -> NoReturn:
178199
"""Stop analyzer with an error message.
179200
180201
Changing ensure_ascii can be helpful when stuck with ascii <-> utf-8 issues.
@@ -203,25 +224,25 @@ def error(self, message, ensure_ascii=False):
203224
# Force exit after error
204225
sys.exit(1)
205226

206-
def summary(self, raw):
227+
def summary(self, raw: dict) -> dict:
207228
"""Returns a summary, needed for 'short.html' template.
208229
209230
Overwrite it for your needs!
210231
211232
:returns: by default return an empty dict"""
212233
return {}
213234

214-
def artifacts(self, raw):
235+
def artifacts(self, raw: dict) -> list[dict]:
215236
return []
216237

217-
def report(self, output, ensure_ascii=False):
238+
def report(self, output: dict, ensure_ascii: bool = False) -> None:
218239
"""Returns a json dict via stdout.
219240
220241
:param output: worker output.
221242
:param ensure_ascii: Force ascii output. Default: False"""
222243

223244
self.__write_output(output, ensure_ascii=ensure_ascii)
224245

225-
def run(self):
246+
def run(self) -> None:
226247
"""Overwritten by analyzers"""
227248
pass

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ dev = ["cortexutils[audit, lint, test, build]", "nox"]
4242
[tool.setuptools.packages.find]
4343
include = ["cortexutils*"]
4444

45+
[tool.setuptools.package-data]
46+
cortexutils = ["py.typed"]
47+
4548
[tool.coverage.run]
4649
omit = ["tests/*"]
4750

0 commit comments

Comments
 (0)