datalake-scripts 2.7.2__py3-none-any.whl → 2.7.4__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.
@@ -18,7 +18,15 @@ class TokenManager:
18
18
  """
19
19
 
20
20
  def __init__(
21
- self, endpoint_config: dict, *, environment: str, username=None, password=None
21
+ self,
22
+ endpoint_config: dict,
23
+ *,
24
+ environment: str,
25
+ username=None,
26
+ password=None,
27
+ longterm_token=None,
28
+ proxies: dict = None,
29
+ verify: bool = True,
22
30
  ):
23
31
  """environment can be either prod or preprod"""
24
32
  base_url = urljoin(
@@ -33,37 +41,73 @@ class TokenManager:
33
41
 
34
42
  self.username = username
35
43
  self.password = password
44
+ self.longterm_token = longterm_token
45
+ self.proxies = proxies
46
+ self.verify = verify
36
47
  self.access_token = None
37
48
  self.refresh_token = None
38
49
  self.get_token()
39
50
 
40
51
  def get_token(self):
41
52
  """
42
- Generate token from user input, with email and password
53
+ Generate token from user input
54
+ by default, we use the values given as args,
55
+ then in second choice, we try the environment variables,
56
+ and finally we ask for user input
57
+ Priority is given to the long term token if it is provided at the same place (args, environment variable or prompt) than the username/password )
43
58
  """
44
- self.username = (
45
- self.username or os.getenv("OCD_DTL_USERNAME") or input("Email: ")
46
- )
47
- self.password = self.password or os.getenv("OCD_DTL_PASSWORD") or getpass()
48
- print()
49
- data = {"email": self.username, "password": self.password}
59
+ if self.username is None and self.password is None:
60
+ """We do not ignore the values username and password in favor of long term token if the two credentials are given explicitly when instancing Datalake"""
61
+ self.longterm_token = self.longterm_token or os.getenv(
62
+ "OCD_DTL_LONGTERM_TOKEN"
63
+ )
50
64
 
51
- response = requests.post(url=self.url_token, json=data)
52
- json_response = json.loads(response.text)
53
- try:
54
- self.access_token = f'Token {json_response["access_token"]}'
55
- self.refresh_token = f'Token {json_response["refresh_token"]}'
56
- except KeyError:
57
- logger.error(
58
- f"An error occurred while retrieving an access token, for URL: {self.url_token}\n"
59
- f"response of the API: {response.text}"
65
+ self.username = self.username or os.getenv("OCD_DTL_USERNAME")
66
+ self.password = self.password or os.getenv("OCD_DTL_PASSWORD")
67
+
68
+ if self.longterm_token is None and (
69
+ self.username is None or self.password is None
70
+ ):
71
+ """I only ask in prompt if no other choice"""
72
+ self.username = self.username or input("Email: ")
73
+ self.password = self.password or getpass()
74
+ self.longterm_token = self.longterm_token or input(
75
+ "Long term token (Default : None): "
60
76
  )
61
- raise ValueError(f"Could not login: {response.text}")
77
+ print()
78
+
79
+ if self.longterm_token:
80
+ self.longterm_token = f"Token {self.longterm_token}"
81
+ if self.username or self.password:
82
+ logger.warning(
83
+ f"Using provided Long Term Token for Authentication to the Datalake API. Ignoring username and/or password."
84
+ )
85
+ else:
86
+ data = {"email": self.username, "password": self.password}
87
+
88
+ response = requests.post(
89
+ url=self.url_token, json=data, proxies=self.proxies, verify=self.verify
90
+ )
91
+ json_response = json.loads(response.text)
92
+ try:
93
+ self.access_token = f'Token {json_response["access_token"]}'
94
+ self.refresh_token = f'Token {json_response["refresh_token"]}'
95
+ except KeyError:
96
+ logger.error(
97
+ f"An error occurred while retrieving an access token, for URL: {self.url_token}\n"
98
+ f"response of the API: {response.text}"
99
+ )
100
+ raise ValueError(f"Could not login: {response.text}")
62
101
 
63
102
  def fetch_new_token(self):
64
103
  logger.debug("Token will be refreshed")
65
104
  headers = {"Authorization": self.refresh_token}
66
- response = requests.post(url=self.url_refresh, headers=headers)
105
+ response = requests.post(
106
+ url=self.url_refresh,
107
+ headers=headers,
108
+ proxies=self.proxies,
109
+ verify=self.verify,
110
+ )
67
111
 
68
112
  json_response = response.json()
69
113
  if (
@@ -94,6 +138,21 @@ class TokenManager:
94
138
  ):
95
139
  self.get_token()
96
140
  elif error_msg == "Token has expired":
97
- self.fetch_new_token()
141
+ if self.longterm_token:
142
+ raise ValueError(f"Long term token has expired")
143
+ else:
144
+ self.fetch_new_token()
145
+ elif error_msg == "Token has been revoked":
146
+ raise ValueError(f"Long term token has been revoked")
147
+ elif error_msg == "Fresh token required":
148
+ raise ValueError(
149
+ f"You cannot use Long term token with this endpoint, please use only the credentials username and password to init the Datalake instance for this request"
150
+ )
151
+ elif (
152
+ error_msg
153
+ in ("Invalid token", "Not enough segments", "Signature verification failed")
154
+ and self.longterm_token
155
+ ):
156
+ raise ValueError(f"Long term token is invalid")
98
157
  else:
99
158
  raise ValueError(f"Unexpected msg: {error_msg}")
datalake/datalake.py CHANGED
@@ -19,21 +19,34 @@ class Datalake:
19
19
 
20
20
  Usage:
21
21
  >>> dtl = Datalake(username='some username', password='some password')
22
+ or
23
+ >>> dtl = Datalake(longterm_token='some longterm token')
24
+ then
22
25
  >>> dtl.Threats.lookup(atom_value='mayoclinic.org', atom_type=AtomType.DOMAIN, hashkey_only=False)
26
+
23
27
  """
24
28
 
25
29
  def __init__(
26
30
  self,
27
31
  username: str = None,
28
32
  password: str = None,
33
+ longterm_token: str = None,
29
34
  env="prod",
30
35
  log_level=logging.WARNING,
36
+ proxies: dict = None,
37
+ verify: bool = True,
31
38
  ):
32
39
  configure_logging(log_level)
33
40
  endpoint_config = Config().load_config()
34
41
  try:
35
42
  token_manager = TokenManager(
36
- endpoint_config, environment=env, username=username, password=password
43
+ endpoint_config,
44
+ environment=env,
45
+ username=username,
46
+ password=password,
47
+ longterm_token=longterm_token,
48
+ proxies=proxies,
49
+ verify=verify,
37
50
  )
38
51
  except Exception as e:
39
52
  if "Failed to resolve" in str(e) or "Failed to establish" in str(e):
@@ -43,14 +56,24 @@ class Datalake:
43
56
  else:
44
57
  raise
45
58
 
46
- self.Threats = Threats(endpoint_config, env, token_manager)
47
- self.BulkSearch = BulkSearch(endpoint_config, env, token_manager)
48
- self.Tags = Tags(endpoint_config, env, token_manager)
59
+ self.Threats = Threats(
60
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
61
+ )
62
+ self.BulkSearch = BulkSearch(
63
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
64
+ )
65
+ self.Tags = Tags(
66
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
67
+ )
49
68
  self.FilteredTagSubcategory = FilteredTagSubcategory(
50
- endpoint_config, env, token_manager
69
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
70
+ )
71
+ self.AdvancedSearch = AdvancedSearch(
72
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
73
+ )
74
+ self.Sightings = Sightings(
75
+ endpoint_config, env, token_manager, proxies=proxies, verify=verify
51
76
  )
52
- self.AdvancedSearch = AdvancedSearch(endpoint_config, env, token_manager)
53
- self.Sightings = Sightings(endpoint_config, env, token_manager)
54
77
  self.SearchWatch = SearchWatch(self.BulkSearch)
55
78
 
56
79
  def sightings_filtered_from_atom_value(
@@ -28,13 +28,20 @@ class Endpoint:
28
28
  SET_MAX_RETRY = 3
29
29
 
30
30
  def __init__(
31
- self, endpoint_config: dict, environment: str, token_manager: TokenManager
31
+ self,
32
+ endpoint_config: dict,
33
+ environment: str,
34
+ token_manager: TokenManager,
35
+ proxies: dict = None,
36
+ verify: bool = True,
32
37
  ):
33
38
  self.endpoint_config = endpoint_config
34
39
  self.environment = environment
35
40
  self.terminal_size = self._get_terminal_size()
36
41
  self.token_manager = token_manager
37
42
  self.SET_MAX_RETRY = 3
43
+ self.proxies = proxies
44
+ self.verify = verify
38
45
 
39
46
  @staticmethod
40
47
  def _get_terminal_size() -> int:
@@ -65,11 +72,19 @@ class Endpoint:
65
72
  tries_left = self.SET_MAX_RETRY
66
73
 
67
74
  while tries_left > 0:
68
- headers["Authorization"] = self.token_manager.access_token
75
+ headers["Authorization"] = (
76
+ self.token_manager.access_token or self.token_manager.longterm_token
77
+ )
69
78
  logger.debug(self._pretty_debug_request(url, method, post_body, headers))
70
79
 
71
80
  response = self._send_request(
72
- url, method, headers, post_body, stream=stream
81
+ url,
82
+ method,
83
+ headers,
84
+ post_body,
85
+ stream=stream,
86
+ proxies=self.proxies,
87
+ verify=self.verify,
73
88
  )
74
89
 
75
90
  if logger.isEnabledFor(logging.DEBUG):
@@ -77,7 +92,7 @@ class Endpoint:
77
92
  logger.debug("API response:\n%s", response.text)
78
93
  if response.status_code == 401:
79
94
  logger.warning(
80
- "Token expired or Missing authorization header. Updating token"
95
+ "Missing authorization header or Token Error. Updating token"
81
96
  )
82
97
  self.token_manager.process_auth_error(response.json())
83
98
  elif response.status_code == 422:
@@ -109,7 +124,13 @@ class Endpoint:
109
124
 
110
125
  @staticmethod
111
126
  def _send_request(
112
- url: str, method: str, headers: dict, data: dict, stream=False
127
+ url: str,
128
+ method: str,
129
+ headers: dict,
130
+ data: dict,
131
+ stream=False,
132
+ proxies: dict = None,
133
+ verify: bool = True,
113
134
  ) -> Response:
114
135
  """
115
136
  Send the correct http request to url from method [get, post, delete, patch, put].
@@ -119,7 +140,10 @@ class Endpoint:
119
140
  "url": url,
120
141
  "headers": headers,
121
142
  "stream": stream,
143
+ "verify": verify,
122
144
  }
145
+ if proxies:
146
+ common_kwargs["proxies"] = proxies
123
147
 
124
148
  if method == "get":
125
149
  api_response = requests.get(**common_kwargs)
@@ -148,6 +172,7 @@ class Endpoint:
148
172
  + f" - data: \n{data}\n"
149
173
  + f" - token: \n{self.token_manager.access_token}\n"
150
174
  + f" - refresh_token: \n{self.token_manager.refresh_token}\n"
175
+ + f" - longterm_token: \n{self.token_manager.longterm_token}\n"
151
176
  + "-" * self.terminal_size
152
177
  )
153
178
  return debug
@@ -73,7 +73,18 @@ class FilteredTagSubcategory(Endpoint):
73
73
  )
74
74
  if limit_match:
75
75
  print("The 'limit' parameter must be >= 0 and <= 5000.")
76
- if not tag_category_match and not ordering_match and not limit_match:
76
+ token_match = re.search(
77
+ r"token",
78
+ error_message,
79
+ )
80
+ if token_match:
81
+ raise ve
82
+ if (
83
+ not tag_category_match
84
+ and not ordering_match
85
+ and not limit_match
86
+ and not token_match
87
+ ):
77
88
  print(
78
89
  "An error occurred, but no specific pattern was matched in the 422 HTTP error message."
79
90
  )
datalake_scripts/cli.py CHANGED
@@ -20,7 +20,7 @@ from datalake_scripts.scripts import (
20
20
 
21
21
  class Cli:
22
22
  CLI_NAME = "ocd-dtl"
23
- VERSION = "2.7.2"
23
+ VERSION = "2.7.4"
24
24
 
25
25
  def __init__(self):
26
26
  parser = argparse.ArgumentParser(
@@ -33,14 +33,26 @@ class BaseEngine:
33
33
  Json = Union[dict, list] # json like object that can be a dict or root level array
34
34
 
35
35
  def __init__(
36
- self, endpoint_config: dict, environment: str, token_manager: TokenManager
36
+ self,
37
+ endpoint_config: dict,
38
+ environment: str,
39
+ token_manager: TokenManager,
40
+ proxies: dict = None,
41
+ verify: bool = True,
37
42
  ):
38
43
  self.endpoint_config = endpoint_config
39
44
  self.environment = environment
40
- self.requests_ssl_verify = suppress_insecure_request_warns(environment)
45
+ self.requests_ssl_verify = (
46
+ verify
47
+ if suppress_insecure_request_warns(environment)
48
+ else suppress_insecure_request_warns(environment)
49
+ )
41
50
  self.url = self._build_url(endpoint_config, environment)
42
51
  self.token_manager = token_manager
43
- self.endpoint = Endpoint(endpoint_config, environment, token_manager)
52
+ self.proxies = proxies
53
+ self.endpoint = Endpoint(
54
+ endpoint_config, environment, token_manager, proxies, verify
55
+ )
44
56
 
45
57
  def datalake_requests(
46
58
  self, url: str, method: str, headers: dict, post_body: dict = None
@@ -50,7 +62,8 @@ class BaseEngine:
50
62
  """
51
63
  try:
52
64
  response = self.endpoint.datalake_requests(url, method, headers, post_body)
53
- except ValueError:
65
+ except ValueError as ve:
66
+ logger.error(f"Error while attempting to request datalake : {ve}")
54
67
  logger.error("Request failed: Will return nothing for this request")
55
68
  return {}
56
69
  if (
@@ -47,11 +47,15 @@ class HandleBulkTaskMixin(BaseEngine):
47
47
 
48
48
  json_response = None
49
49
  while not json_response:
50
- headers = {"Authorization": self.token_manager.access_token}
50
+ headers = {
51
+ "Authorization": self.token_manager.access_token
52
+ or self.token_manager.longterm_token
53
+ }
51
54
  response = requests.get(
52
55
  url=retrieve_bulk_result_url,
53
56
  headers=headers,
54
57
  verify=self.requests_ssl_verify,
58
+ proxies=self.proxies,
55
59
  )
56
60
  if response.status_code == 200:
57
61
  potential_json_response = response.json()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: datalake-scripts
3
- Version: 2.7.2
3
+ Version: 2.7.4
4
4
  Summary: A collection of scripts to easily use the API of OCD Datalake
5
5
  Home-page: https://github.com/cert-orangecyberdefense/datalake/
6
6
  Author: OCD
@@ -43,7 +43,19 @@ $ pip install datalake-scripts
43
43
  $ pip3 install datalake-scripts
44
44
  ```
45
45
  ### Using as a library
46
- see [the following link](tutorial.md)
46
+ ```python
47
+ from datalake import Datalake, AtomType, Output
48
+
49
+ dtl = Datalake(username='username', password='password')
50
+ dtl.Threats.lookup(
51
+ atom_value='mayoclinic.org',
52
+ atom_type=AtomType.DOMAIN,
53
+ hashkey_only=False,
54
+ output=Output.JSON
55
+ )
56
+ ```
57
+
58
+ see [the following link](https://github.com/cert-orangecyberdefense/datalake/blob/master/tutorial.md)
47
59
 
48
60
  ### Using as a CLI
49
61
 
@@ -60,10 +72,31 @@ You can also use a script directly by using the following command: `<script_name
60
72
  ## Environment variables
61
73
 
62
74
  #### Authentication
63
- In case you don't want to enter credential for each commands and you are on a secured terminal, set those variables:
75
+
76
+ There are two methods of authentication:
77
+ - The first one is the use of the username and password. Every request to the API, will then use fresh tokens periodically created with these credentials.
78
+ - The second one is the use of a long term token. You can create long term token through the GUI, it can have more restricted permissions than your account. You can create several long term tokens for one account.
79
+
80
+ In case you don't want to enter credentials for each commands and you are on a secured terminal, set those variables:
81
+ * `OCD_DTL_LONGTERM_TOKEN` a long term token associated to your Datalake account.
82
+ Please note that if this variable is set, then the long term token will be used for every request to the Datalake API, even if you set the username and passsword environment variables below. This is important because some endpoints / requests do not accept long term tokens but need fresh tokens (ie a Datalake instance with username and password). Check for the need of fresh tokens in each endpoint description [here](https://datalake.cert.orangecyberdefense.com/api/v2/docs/)
83
+
84
+ or
85
+
64
86
  * `OCD_DTL_USERNAME` email address used to login on Datalake API/GUI.
65
87
  * `OCD_DTL_PASSWORD` password used to login on Datalake API/GUI.
66
- > They are independent and one can be used without the other if you wish.
88
+ > These last two are independent and one can be used without the other if you wish.
89
+
90
+ #### Using a Proxy
91
+
92
+ You can set up following environment variables :
93
+
94
+ * `HTTP_PROXY`
95
+ * `HTTPS_PROXY`
96
+
97
+ We use the format accepted by the requests python library.
98
+ See its documenation for other possible kinds of proxy to set up.
99
+
67
100
 
68
101
  #### Throttling
69
102
  For throttling the request, those two environment variable can be used:
@@ -1,5 +1,5 @@
1
1
  datalake/__init__.py,sha256=A2Cmrxun_uvpfjPC_9kwwAFKTpUI5uBcln2-ortksMY,699
2
- datalake/datalake.py,sha256=fQHPRkgw1qp6GzhpHUJqblps9jVoreKx0w7AcD3pn8g,3868
2
+ datalake/datalake.py,sha256=mFUEXYJ89YIw8eYR7nZyfl9l0TeXvvRMqw_7DkqKiQA,4503
3
3
  datalake/api_objects/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  datalake/api_objects/bulk_search_task.py,sha256=2H1EKFNR6ttf5yJWW0F8kpHgWjA-Pawpu2i2Z3xP-kg,4627
5
5
  datalake/common/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
@@ -9,26 +9,26 @@ datalake/common/config.py,sha256=b9PAfwL2qhJzGBZXaUTe1HtH_WZole1xnbawFq9LbyI,476
9
9
  datalake/common/logger.py,sha256=vC03L_VZ6kN5YHGCRJX2_iSNlTNqx010bFH90Cyxf9A,460
10
10
  datalake/common/output.py,sha256=sU6wZLznokKjMvtNNcGq5BRn9nDKtE_3N2RrFM8NDqg,1537
11
11
  datalake/common/throttler.py,sha256=O9h1DsGiloatsnOrwJdZIZEFCGL4pPqF6dafHmMFvYA,1882
12
- datalake/common/token_manager.py,sha256=dHlxyKBai2xKsB7Ii2JPKp7e_FIksgZaubO4seWC8o8,3656
12
+ datalake/common/token_manager.py,sha256=uzcHGUzFrjTvlNosRU-wsycKob_gCRrsmtaEF-CYt_Q,6198
13
13
  datalake/common/utils.py,sha256=b2wUo6t9H-l9ctCpthKpS9CgOMvWiSJGOci3t6-M330,3504
14
14
  datalake/common/warn.py,sha256=8-YFJHlH3q91vp4TDyifmG05a5uvlVjHzcztbOiVP44,271
15
15
  datalake/config/endpoints.json,sha256=D2XUhnOEoZsIUWhlqOnMTFl9QJdpI0OnTksHTi27BzQ,1426
16
16
  datalake/endpoints/__init__.py,sha256=4GqELe9-njbc5BikldIX9RLDvVqQ96RqKRW9ykUsAL0,49
17
17
  datalake/endpoints/advanced_search.py,sha256=zS4iSOkUsZES59NvlrPsmmy9mF2w2pi8It1NBcWkH8g,2538
18
18
  datalake/endpoints/bulk_search.py,sha256=KGHd3zSM-A_2oXCm6HO81xJ4xVS9eZfCJNCrxD445ms,2570
19
- datalake/endpoints/endpoint.py,sha256=KKwUQ_vtly62YykOH5jLzFJhhqUf_0weIP5EGbz44Us,5850
20
- datalake/endpoints/filtered_tag_subcategory.py,sha256=9ZX5tiltt0ojX0djdvTojqR-PahJwyx3mO-HFJ2ajnU,2835
19
+ datalake/endpoints/endpoint.py,sha256=pa6_X9cJ3vt_919WlGW97uiG2JytIqqo_OAgdA0XCXg,6465
20
+ datalake/endpoints/filtered_tag_subcategory.py,sha256=8ERU3PtSrNHM5A72gXGe6S6iAdHWnCKDT2ByU4oAuuI,3096
21
21
  datalake/endpoints/sightings.py,sha256=bXl_hEm8hrvyCG8vg1944jCnCgOfl_lVe7vvaDe1Bw8,7801
22
22
  datalake/endpoints/tags.py,sha256=zYKBjaNTuVOwUmdzDC2Og0IAvZSUirXTMVlJCPNQMoY,1027
23
23
  datalake/endpoints/threats.py,sha256=ZfDJA7SX4pJglpK42oWJdRriRkzVYPoqvN8RRX4pG2g,20320
24
24
  datalake/miscellaneous/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
25
  datalake/miscellaneous/search_watch.py,sha256=078kLpkDPW1fx9u1ANKg_haFSvUxjsFz9T3P-_nqFtI,6897
26
26
  datalake_scripts/__init__.py,sha256=EKgNnE5TNzttTOC4vPKID6gWB4S2Zj-qpKxI8ZA8mCw,147
27
- datalake_scripts/cli.py,sha256=7FAa2u5br7jmDCBqK3GFylSvhKiDor82pgGOroM1ztQ,2702
27
+ datalake_scripts/cli.py,sha256=ZbvP3_OP22oe9XrV8j07fXkRUUKsCB6Xp2Z9fc2WQn8,2702
28
28
  datalake_scripts/common/__init__.py,sha256=CeFL01aRaUnr4v36sE_CKoTQ9rDRAGYZBOMLsoKKsLc,803
29
- datalake_scripts/common/base_engine.py,sha256=3B7AxkIk0N5vTYkICznlCInMb6SVEXMpiFI3axfGya0,4236
29
+ datalake_scripts/common/base_engine.py,sha256=SgN6a5d5gJ5KFiTgjIwdtTBxUXX1Q0qNfcv1v9JzMKM,4583
30
30
  datalake_scripts/common/base_script.py,sha256=M6yRiUWwkuwj6iS9Bcg16D--tGA_UgAQCwUp_yqkUAo,2520
31
- datalake_scripts/common/mixins.py,sha256=sUF6hXNTc9kynH35rntV0cGVJ1fva1M1Bf2_6SdWOM4,3018
31
+ datalake_scripts/common/mixins.py,sha256=3gEDzQs4CAmsf8SO2weXUxSe5u9lZvX_xKHNaQYdPxc,3139
32
32
  datalake_scripts/engines/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
33
33
  datalake_scripts/engines/get_engine.py,sha256=CAkU1phNuFUYKdNob_keI2Qjwh_-fgVFhoLaD2J6vkc,3816
34
34
  datalake_scripts/engines/post_engine.py,sha256=H9FkwbWcW98S0tBlQ9ddojurB5muPKM6oBA9s6DLq_c,6136
@@ -52,13 +52,13 @@ datalake_scripts/scripts/search_watch.py,sha256=8CM79GsL5TBXwPB2pb7QMw8HeoVdivUi
52
52
  tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
53
  tests/conftest.py,sha256=MqEvz9qs2NtMjKnBj6IUJjMx34pJwKbCgRtzaJIpyxw,240
54
54
  tests/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
55
- tests/common/fixture.py,sha256=1oOq71ZEZ7_JLu7NLDqPl2uhENuGtJVkTPg3QckWO_Y,1672
55
+ tests/common/fixture.py,sha256=BfmI6BtPP-q6ki3JAEVuXSalNG6JcBVRXm9SdmpwJ70,1798
56
56
  tests/common/test_output.py,sha256=9_Aud8dxy2iLEUAK8u7IsyBWMjnUXDYzy5AbRHtNT8Y,888
57
57
  tests/common/test_utils.py,sha256=Fyz2r5ufgu6FyH79qCTKHsLc4AjICGvRsXhm4n83YPE,1740
58
58
  tests/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
59
59
  tests/lib/test_advanced_search.py,sha256=dPsPeKf2fEayBgeD07TWX-PpimURbCCd4gjrCQOsaQk,4493
60
60
  tests/lib/test_atom_type.py,sha256=4XgCJAJEDuzyzxYdzqO4vL00Fv26HH-0rc7ZIiVuZXk,4418
61
- tests/lib/test_auth_via_tokens.py,sha256=gQffONnmY0v3oh7jF7nA4boDemXvhcW4sMs_jFIxLj4,5937
61
+ tests/lib/test_auth_via_tokens.py,sha256=3moKCwKbMN3awjJSjO0PJCAukY3tYG54SCmuAcvfVGU,11545
62
62
  tests/lib/test_bulk_search.py,sha256=Rh1P4X9L4K6jL4o1HHB1cQycorsRzxEAFWyz8lLn7OY,14237
63
63
  tests/lib/test_filtered_tag_subcategory.py,sha256=7cry-lf2e6KdR_bY8bIyRG8Gyt_CpcecEjDDnXwo94k,7132
64
64
  tests/lib/test_search_watch.py,sha256=dPmW5Wmruw7NejZlKA-l8YVZYc211BGz_UnB3inyzM0,10402
@@ -71,8 +71,8 @@ tests/scripts/test_base_engine.py,sha256=vk-qqVHXwo9riQUQccoMhebw3GQSMD456rsB_FQ
71
71
  tests/scripts/test_cli.py,sha256=X0zS6z1begL4304IpQ0AK861FuY_RFM9B4RoUZkUGYI,1652
72
72
  tests/scripts/test_csv_builder.py,sha256=QEhbzH4w_epcFXYieZ2rTij7TGGMYRLTR-7LbiwSA60,7997
73
73
  tests/scripts/test_endpoint_config.py,sha256=gqE12mfuh_qGx6e-bTArcWxhhg4MUQEIYNZyrcy3m8g,987
74
- datalake_scripts-2.7.2.dist-info/METADATA,sha256=b2pMXUzcKDy6HOD7SCzLRvEj3O7YM8qV8HQSshRqrqs,3286
75
- datalake_scripts-2.7.2.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
76
- datalake_scripts-2.7.2.dist-info/entry_points.txt,sha256=DlfjQgUDIGnK_Ef_35515ACzOw1Vpdx9cI3sI0pMEL0,471
77
- datalake_scripts-2.7.2.dist-info/top_level.txt,sha256=uU48AOj64UXu2kR5yxRNQrTU133Il-sI6FrwEYBjxkk,32
78
- datalake_scripts-2.7.2.dist-info/RECORD,,
74
+ datalake_scripts-2.7.4.dist-info/METADATA,sha256=dDZepY5Dko5suOAtCJsV1yX3nAlFD7gDMQZens_qeTY,4825
75
+ datalake_scripts-2.7.4.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
76
+ datalake_scripts-2.7.4.dist-info/entry_points.txt,sha256=DlfjQgUDIGnK_Ef_35515ACzOw1Vpdx9cI3sI0pMEL0,471
77
+ datalake_scripts-2.7.4.dist-info/top_level.txt,sha256=uU48AOj64UXu2kR5yxRNQrTU133Il-sI6FrwEYBjxkk,32
78
+ datalake_scripts-2.7.4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.42.0)
2
+ Generator: bdist_wheel (0.45.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
tests/common/fixture.py CHANGED
@@ -49,3 +49,9 @@ def datalake():
49
49
 
50
50
  responses.add(responses.POST, url, json=auth_response, status=200)
51
51
  return Datalake(username="username", password="password")
52
+
53
+
54
+ @pytest.fixture
55
+ @responses.activate
56
+ def datalake_longterm_token():
57
+ return Datalake(longterm_token="longterm_token1234")
@@ -6,18 +6,23 @@ import pytest
6
6
  import responses
7
7
 
8
8
  from datalake import Datalake, AtomType
9
- from tests.common.fixture import datalake # noqa needed fixture import
9
+ from tests.common.fixture import (
10
+ datalake,
11
+ datalake_longterm_token,
12
+ ) # noqa needed fixture import
10
13
 
11
14
 
12
15
  @responses.activate
13
16
  def test_token_auth(datalake):
14
17
  expected_tokens = {
18
+ "longterm_token": None,
15
19
  "access_token": "12345",
16
20
  "refresh_token": "123456",
17
21
  }
18
22
 
19
23
  token_manager = datalake.Threats.token_manager
20
24
 
25
+ assert token_manager.longterm_token == None
21
26
  assert token_manager.access_token == f"Token {expected_tokens['access_token']}"
22
27
  assert token_manager.refresh_token == f"Token {expected_tokens['refresh_token']}"
23
28
 
@@ -93,7 +98,7 @@ def test_access_token_expired(datalake, caplog):
93
98
  == expected_json
94
99
  )
95
100
  assert caplog.messages == [
96
- "Token expired or Missing authorization header. Updating token"
101
+ "Missing authorization header or Token Error. Updating token"
97
102
  ]
98
103
 
99
104
 
@@ -138,7 +143,7 @@ def test_refresh_token_expired(datalake, caplog):
138
143
  == expected_json
139
144
  )
140
145
  assert caplog.messages == [
141
- "Token expired or Missing authorization header. Updating token",
146
+ "Missing authorization header or Token Error. Updating token",
142
147
  "Refreshing the refresh token",
143
148
  ]
144
149
 
@@ -177,5 +182,151 @@ def test_invalid_token(datalake, caplog):
177
182
  == expected_json
178
183
  )
179
184
  assert caplog.messages == [
180
- "Token expired or Missing authorization header. Updating token"
185
+ "Missing authorization header or Token Error. Updating token"
186
+ ]
187
+
188
+
189
+ def test_active_longterm_token(datalake_longterm_token):
190
+ token_manager = datalake_longterm_token.Threats.token_manager
191
+ expected_tokens = {
192
+ "longterm_token": "longterm_token1234",
193
+ "access_token": None,
194
+ "refresh_token": None,
195
+ }
196
+
197
+ assert token_manager.longterm_token == f"Token {expected_tokens['longterm_token']}"
198
+ assert token_manager.access_token == None
199
+ assert token_manager.refresh_token == None
200
+
201
+
202
+ def lookup_callback_longterm_token(
203
+ request,
204
+ expired_longterm_token,
205
+ disabled_longterm_token,
206
+ not_fresh_token,
207
+ response_on_expired_longterm_token={"msg": "Token has expired"},
208
+ response_on_disabled_longterm_token={"msg": "Token has been revoked"},
209
+ response_on_not_fresh_token={"msg": "Fresh token required"},
210
+ response_on_invalid_token={"msg": "Invalid token"},
211
+ ):
212
+ headers = {}
213
+ if request.headers["Authorization"] == f"Token {expired_longterm_token}":
214
+ return 401, headers, json.dumps(response_on_expired_longterm_token)
215
+ elif request.headers["Authorization"] == f"Token {disabled_longterm_token}":
216
+ return 401, headers, json.dumps(response_on_disabled_longterm_token)
217
+ elif request.headers["Authorization"] == f"Token {not_fresh_token}":
218
+ return 401, headers, json.dumps(response_on_not_fresh_token)
219
+ else:
220
+ return 401, headers, json.dumps(response_on_invalid_token)
221
+
222
+
223
+ @responses.activate
224
+ def test_disabled_longterm_token(datalake_longterm_token, caplog):
225
+ caplog.set_level(level=logging.INFO, logger="OCD_DTL")
226
+
227
+ responses.add_callback(
228
+ responses.GET,
229
+ "https://datalake.cert.orangecyberdefense.com/api/v2/mrti/threats/lookup/",
230
+ callback=partial(
231
+ lookup_callback_longterm_token,
232
+ expired_longterm_token="expired_longterm_token_1234",
233
+ disabled_longterm_token="longterm_token1234",
234
+ not_fresh_token="not_fresh_token_1234",
235
+ ),
236
+ content_type="application/json",
237
+ )
238
+
239
+ with caplog.at_level(logging.WARNING):
240
+ with pytest.raises(ValueError) as ve:
241
+ r = datalake_longterm_token.Threats.lookup(
242
+ atom_value="wow.com", atom_type=AtomType.DOMAIN
243
+ )
244
+ assert str(ve.value) == "Long term token has been revoked"
245
+ assert caplog.messages == [
246
+ "Missing authorization header or Token Error. Updating token"
247
+ ]
248
+
249
+
250
+ @responses.activate
251
+ def test_expired_longterm_token(datalake_longterm_token, caplog):
252
+ caplog.set_level(level=logging.INFO, logger="OCD_DTL")
253
+
254
+ responses.add_callback(
255
+ responses.GET,
256
+ "https://datalake.cert.orangecyberdefense.com/api/v2/mrti/threats/lookup/",
257
+ callback=partial(
258
+ lookup_callback_longterm_token,
259
+ expired_longterm_token="longterm_token1234",
260
+ disabled_longterm_token="disabled_token1234",
261
+ not_fresh_token="not_fresh_token_1234",
262
+ ),
263
+ content_type="application/json",
264
+ )
265
+
266
+ with caplog.at_level(logging.WARNING):
267
+ with pytest.raises(ValueError) as ve:
268
+ r = datalake_longterm_token.Threats.lookup(
269
+ atom_value="wow.com", atom_type=AtomType.DOMAIN
270
+ )
271
+ assert str(ve.value) == "Long term token has expired"
272
+ assert caplog.messages == [
273
+ "Missing authorization header or Token Error. Updating token"
274
+ ]
275
+
276
+
277
+ # test long test token on endpoint requiring fresh token
278
+ @responses.activate
279
+ def test_requires_fresh_token(datalake_longterm_token, caplog):
280
+ caplog.set_level(level=logging.INFO, logger="OCD_DTL")
281
+
282
+ responses.add_callback(
283
+ responses.GET,
284
+ "https://datalake.cert.orangecyberdefense.com/api/v2/mrti/threats/lookup/",
285
+ callback=partial(
286
+ lookup_callback_longterm_token,
287
+ expired_longterm_token="expired_longterm_token_1234",
288
+ disabled_longterm_token="disabled_token1234",
289
+ not_fresh_token="longterm_token1234",
290
+ ),
291
+ content_type="application/json",
292
+ )
293
+
294
+ with caplog.at_level(logging.WARNING):
295
+ with pytest.raises(ValueError) as ve:
296
+ r = datalake_longterm_token.Threats.lookup(
297
+ atom_value="wow.com", atom_type=AtomType.DOMAIN
298
+ )
299
+ assert (
300
+ str(ve.value)
301
+ == "You cannot use Long term token with this endpoint, please use only the credentials username and password to init the Datalake instance for this request"
302
+ )
303
+ assert caplog.messages == [
304
+ "Missing authorization header or Token Error. Updating token"
305
+ ]
306
+
307
+
308
+ @responses.activate
309
+ def test_invalid_longterm_token(datalake_longterm_token, caplog):
310
+ caplog.set_level(level=logging.INFO, logger="OCD_DTL")
311
+
312
+ responses.add_callback(
313
+ responses.GET,
314
+ "https://datalake.cert.orangecyberdefense.com/api/v2/mrti/threats/lookup/",
315
+ callback=partial(
316
+ lookup_callback_longterm_token,
317
+ expired_longterm_token="expired_longterm_token_1234",
318
+ disabled_longterm_token="disabled_token1234",
319
+ not_fresh_token="not_fresh_token_1234",
320
+ ),
321
+ content_type="application/json",
322
+ )
323
+
324
+ with caplog.at_level(logging.WARNING):
325
+ with pytest.raises(ValueError) as ve:
326
+ r = datalake_longterm_token.Threats.lookup(
327
+ atom_value="wow.com", atom_type=AtomType.DOMAIN
328
+ )
329
+ assert str(ve.value) == "Long term token is invalid"
330
+ assert caplog.messages == [
331
+ "Missing authorization header or Token Error. Updating token"
181
332
  ]