Skip to content

Commit 78d3a29

Browse files
committed
Add nosec pragma for bandit false positives. Also re-format some of the
code to comply with style rules.
1 parent e650840 commit 78d3a29

16 files changed

Lines changed: 729 additions & 30 deletions

File tree

libcloud/common/gandi.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@ class GandiException(Exception):
3636

3737
def __str__(self):
3838
# pylint: disable=unsubscriptable-object
39+
3940
return "({}) {}".format(self.args[0], self.args[1])
4041

4142
def __repr__(self):
4243
# pylint: disable=unsubscriptable-object
44+
4345
return '<GandiException code {} "{}">'.format(self.args[0], self.args[1])
4446

4547

@@ -83,6 +85,7 @@ def __init__(
8385

8486
def request(self, method, *args):
8587
args = (self.key,) + args
88+
8689
return super().request(method, *args)
8790

8891

@@ -106,6 +109,7 @@ def _wait_operation(self, id, timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_IN
106109

107110
if op["step"] == "DONE":
108111
return True
112+
109113
if op["step"] in ["ERROR", "CANCEL"]:
110114
return False
111115
except (KeyError, IndexError):
@@ -114,6 +118,7 @@ def _wait_operation(self, id, timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_IN
114118
raise GandiException(1002, e)
115119

116120
time.sleep(check_interval)
121+
117122
return False
118123

119124

@@ -147,7 +152,8 @@ def get_uuid(self):
147152
same UUID!
148153
"""
149154
hashstring = "{}:{}:{}".format(self.uuid_prefix, self.id, self.driver.type)
150-
return hashlib.sha1(b(hashstring)).hexdigest()
155+
156+
return hashlib.sha1(b(hashstring)).hexdigest() # nosec
151157

152158

153159
class IPAddress(BaseObject):

libcloud/common/nfsn.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,13 @@ def parse_error(self):
4545
# If we only have one of "error" or "debug", use the one that we have.
4646
# If we have both, use both, with a space character in between them.
4747
value = "No message specified"
48+
4849
if error is not None:
4950
value = error
51+
5052
if debug is not None:
5153
value = debug
54+
5255
if error is not None and value is not None:
5356
value = error + " " + value
5457
value = value + " (HTTP Code: %d)" % self.status
@@ -70,22 +73,25 @@ def _header(self, action, data):
7073
salt = self._salt()
7174
api_key = self.key
7275
data = urlencode(data)
73-
data_hash = hashlib.sha1(data.encode("utf-8")).hexdigest()
76+
data_hash = hashlib.sha1(data.encode("utf-8")).hexdigest() # nosec
7477

7578
string = ";".join((login, timestamp, salt, api_key, action, data_hash))
76-
string_hash = hashlib.sha1(string.encode("utf-8")).hexdigest()
79+
string_hash = hashlib.sha1(string.encode("utf-8")).hexdigest() # nosec
7780

7881
return ";".join((login, timestamp, salt, string_hash))
7982

8083
def request(self, action, params=None, data="", headers=None, method="GET"):
8184
"""Add the X-NFSN-Authentication header to an HTTP request."""
85+
8286
if not headers:
8387
headers = {}
88+
8489
if not params:
8590
params = {}
8691
header = self._header(action, data)
8792

8893
headers["X-NFSN-Authentication"] = header
94+
8995
if method == "POST":
9096
headers["Content-Type"] = "application/x-www-form-urlencoded"
9197

@@ -94,16 +100,20 @@ def request(self, action, params=None, data="", headers=None, method="GET"):
94100
def encode_data(self, data):
95101
"""NFSN expects the body to be regular key-value pairs that are not
96102
JSON-encoded."""
103+
97104
if data:
98105
data = urlencode(data)
106+
99107
return data
100108

101109
def _salt(self):
102110
"""Return a 16-character alphanumeric string."""
103111
r = random.SystemRandom()
112+
104113
return "".join(r.choice(SALT_CHARACTERS) for _ in range(16))
105114

106115
def _timestamp(self):
107116
"""Return the current number of seconds since the Unix epoch,
108117
as a string."""
118+
109119
return str(int(time.time()))

libcloud/common/ovh.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,13 @@ class OvhConnection(ConnectionUserAndKey):
109109

110110
def __init__(self, user_id, *args, **kwargs):
111111
region = kwargs.pop("region", "")
112+
112113
if region:
113114
self.host = ("{}.{}".format(region, API_HOST)).lstrip(".")
114115
else:
115116
self.host = API_HOST
116117
self.consumer_key = kwargs.pop("ex_consumer_key", None)
118+
117119
if self.consumer_key is None:
118120
consumer_key_json = self.request_consumer_key(user_id)
119121
msg = (
@@ -145,27 +147,32 @@ def request_consumer_key(self, user_id):
145147

146148
json_response = response.parse_body()
147149
httpcon.close()
150+
148151
return json_response
149152

150153
def get_timestamp(self):
151154
if not self._timedelta:
152155
url = "https://{}{}/auth/time".format(self.host, API_ROOT)
153156
response = get_response_object(url=url, method="GET", headers={})
157+
154158
if not response or not response.body:
155159
raise Exception("Failed to get current time from Ovh API")
156160

157161
timestamp = int(response.body)
158162
self._timedelta = timestamp - int(time.time())
163+
159164
return int(time.time()) + self._timedelta
160165

161166
def make_signature(self, method, action, params, data, timestamp):
162167
full_url = "https://{}{}".format(self.host, action)
168+
163169
if params:
164170
full_url += "?"
171+
165172
for key, value in params.items():
166173
full_url += "{}={}&".format(key, value)
167174
full_url = full_url[:-1]
168-
sha1 = hashlib.sha1()
175+
sha1 = hashlib.sha1() # nosec
169176
base_signature = "+".join(
170177
[
171178
self.key,
@@ -178,6 +185,7 @@ def make_signature(self, method, action, params, data, timestamp):
178185
)
179186
sha1.update(base_signature.encode())
180187
signature = "$1$" + sha1.hexdigest()
188+
181189
return signature
182190

183191
def add_default_params(self, params):
@@ -191,6 +199,7 @@ def add_default_headers(self, headers):
191199
"Content-type": "application/json",
192200
}
193201
)
202+
194203
return headers
195204

196205
def request(self, action, params=None, data=None, headers=None, method="GET", raw=False):

libcloud/compute/base.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,14 +144,18 @@ def get_uuid(self):
144144
145145
:rtype: ``str``
146146
"""
147+
147148
if not self._uuid:
148-
self._uuid = hashlib.sha1(b("{}:{}".format(self.id, self.driver.type))).hexdigest()
149+
self._uuid = hashlib.sha1(
150+
b("{}:{}".format(self.id, self.driver.type))
151+
).hexdigest() # nosec
149152

150153
return self._uuid
151154

152155
@property
153156
def uuid(self):
154157
# type: () -> str
158+
155159
return self.get_uuid()
156160

157161

@@ -280,6 +284,7 @@ def reboot(self):
280284
>>> node.state == NodeState.REBOOTING
281285
True
282286
"""
287+
283288
return self.driver.reboot_node(self)
284289

285290
def start(self):
@@ -289,6 +294,7 @@ def start(self):
289294
290295
:return: ``bool``
291296
"""
297+
292298
return self.driver.start_node(self)
293299

294300
def stop_node(self):
@@ -298,6 +304,7 @@ def stop_node(self):
298304
299305
:return: ``bool``
300306
"""
307+
301308
return self.driver.stop_node(self)
302309

303310
def destroy(self):
@@ -321,6 +328,7 @@ def destroy(self):
321328
False
322329
323330
"""
331+
324332
return self.driver.destroy_node(self)
325333

326334
def __repr__(self):
@@ -688,6 +696,7 @@ def list_snapshots(self):
688696
"""
689697
:rtype: ``list`` of ``VolumeSnapshot``
690698
"""
699+
691700
return self.driver.list_volume_snapshots(volume=self)
692701

693702
def attach(self, node, device=None):
@@ -705,6 +714,7 @@ def attach(self, node, device=None):
705714
:return: ``True`` if attach was successful, ``False`` otherwise.
706715
:rtype: ``bool``
707716
"""
717+
708718
return self.driver.attach_volume(node=node, volume=self, device=device)
709719

710720
def detach(self):
@@ -715,6 +725,7 @@ def detach(self):
715725
:return: ``True`` if detach was successful, ``False`` otherwise.
716726
:rtype: ``bool``
717727
"""
728+
718729
return self.driver.detach_volume(volume=self)
719730

720731
def snapshot(self, name):
@@ -725,6 +736,7 @@ def snapshot(self, name):
725736
:return: Created snapshot.
726737
:rtype: ``VolumeSnapshot``
727738
"""
739+
728740
return self.driver.create_volume_snapshot(volume=self, name=name)
729741

730742
def destroy(self):
@@ -804,6 +816,7 @@ def destroy(self):
804816
805817
:rtype: ``bool``
806818
"""
819+
807820
return self.driver.destroy_volume_snapshot(snapshot=self)
808821

809822
def __repr__(self):
@@ -1148,6 +1161,7 @@ def deploy_node(
11481161
:type wait_period: ``int``
11491162
11501163
"""
1164+
11511165
if not libcloud.compute.ssh.have_paramiko:
11521166
raise RuntimeError(
11531167
"paramiko is not installed. You can install " + "it using pip: pip install paramiko"
@@ -1163,6 +1177,7 @@ def deploy_node(
11631177
pass
11641178
elif "create_node" in self.features:
11651179
f = self.features["create_node"]
1180+
11661181
if "generates_password" not in f and "password" not in f:
11671182
raise NotImplementedError("deploy_node not implemented for this driver")
11681183
else:
@@ -1181,13 +1196,15 @@ def deploy_node(
11811196
try:
11821197
# NOTE: We only pass auth to the method if auth argument is
11831198
# provided
1199+
11841200
if auth:
11851201
node = self.create_node(auth=auth, **create_node_kwargs)
11861202
else:
11871203
node = self.create_node(**create_node_kwargs)
11881204
except TypeError as e:
11891205
msg_1_re = r"create_node\(\) missing \d+ required " "positional arguments.*"
11901206
msg_2_re = r"create_node\(\) takes at least \d+ arguments.*"
1207+
11911208
if re.match(msg_1_re, str(e)) or re.match(msg_2_re, str(e)):
11921209
# pylint: disable=unexpected-keyword-arg
11931210
node = self.create_node( # type: ignore
@@ -1211,6 +1228,7 @@ def deploy_node(
12111228
atexit.register(at_exit_func, driver=self, node=node)
12121229

12131230
password = None
1231+
12141232
if auth:
12151233
if isinstance(auth, NodeAuthPassword):
12161234
password = auth.password
@@ -1261,6 +1279,7 @@ def deploy_node(
12611279
else:
12621280
# Script successfully executed, don't try alternate username
12631281
deploy_error = None
1282+
12641283
break
12651284

12661285
if deploy_error is not None:
@@ -1674,15 +1693,18 @@ def is_supported(address):
16741693
"""
16751694
Return True for supported address.
16761695
"""
1696+
16771697
if force_ipv4 and not is_valid_ip_address(address=address, family=socket.AF_INET):
16781698
return False
1699+
16791700
return True
16801701

16811702
def filter_addresses(addresses):
16821703
# type: (List[str]) -> List[str]
16831704
"""
16841705
Return list of supported addresses.
16851706
"""
1707+
16861708
return [address for address in addresses if is_supported(address)]
16871709

16881710
if ssh_interface not in ["public_ips", "private_ips"]:
@@ -1708,15 +1730,18 @@ def filter_addresses(addresses):
17081730

17091731
running_nodes = [node for node in matching_nodes if node.state == NodeState.RUNNING]
17101732
addresses = []
1733+
17111734
for node in running_nodes:
17121735
node_addresses = filter_addresses(getattr(node, ssh_interface))
1736+
17131737
if len(node_addresses) >= 1:
17141738
addresses.append(node_addresses)
17151739

17161740
if len(running_nodes) == len(uuids) == len(addresses):
17171741
return list(zip(running_nodes, addresses))
17181742
else:
17191743
time.sleep(wait_period)
1744+
17201745
continue
17211746

17221747
raise LibcloudError(value="Timed out after %s seconds" % (timeout), driver=self)
@@ -1757,6 +1782,7 @@ def _get_and_check_auth(self, auth):
17571782
# Some providers require password to also include uppercase
17581783
# characters so convert some characters to uppercase
17591784
password = ""
1785+
17601786
for char in value:
17611787
if not char.isdigit() and char.islower():
17621788
if random.randint(0, 1) == 1:
@@ -1784,6 +1810,7 @@ def _wait_until_running(
17841810
# type: (Node, float, int, str, bool) -> List[Tuple[Node, List[str]]]
17851811
# This is here for backward compatibility and will be removed in the
17861812
# next major release
1813+
17871814
return self.wait_until_running(
17881815
nodes=[node],
17891816
wait_period=wait_period,
@@ -1836,6 +1863,7 @@ def _ssh_client_connect(self, ssh_client, wait_period=1.5, timeout=300):
18361863
pass
18371864

18381865
time.sleep(wait_period)
1866+
18391867
continue
18401868
else:
18411869
return ssh_client
@@ -1881,6 +1909,7 @@ def _connect_and_run_deployment_script(
18811909
node = self._run_deployment_script(
18821910
task=task, node=node, ssh_client=ssh_client, max_tries=max_tries
18831911
)
1912+
18841913
return node
18851914

18861915
def _run_deployment_script(self, task, node, ssh_client, max_tries=3):
@@ -1940,6 +1969,7 @@ def _run_deployment_script(self, task, node, ssh_client, max_tries=3):
19401969
else:
19411970
# Deployment succeeded
19421971
ssh_client.close()
1972+
19431973
return node
19441974

19451975
return node
@@ -1949,6 +1979,7 @@ def _get_size_price(self, size_id):
19491979
"""
19501980
Return pricing information for the provided size id.
19511981
"""
1982+
19521983
return get_size_price(driver_type="compute", driver_name=self.api_name, size_id=size_id)
19531984

19541985

0 commit comments

Comments
 (0)