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

Fix lint issues #490

Merged
merged 4 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions securesystemslib/ecdsa_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,15 +327,11 @@ def verify_signature(public_key, scheme, signature, data):
f"Failed to load PEM key {public_key}"
) from e

if not isinstance( # pylint: disable=no-else-raise
ecdsa_key, ec.EllipticCurvePublicKey
):
if not isinstance(ecdsa_key, ec.EllipticCurvePublicKey):
raise exceptions.FormatError(
"Invalid ECDSA public" " key: " + repr(public_key)
)

else:
logger.debug("Loaded a valid ECDSA public key.")
logger.debug("Loaded a valid ECDSA public key.")

# verify() raises an 'InvalidSignature' exception if 'signature'
# is invalid.
Expand Down
26 changes: 0 additions & 26 deletions securesystemslib/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,14 @@
class Error(Exception):
"""Indicate a generic error."""

pass # pylint: disable=unnecessary-pass


class Warning(Warning): # pylint: disable=redefined-builtin
"""Generic warning. It is used by the 'warnings' module."""

pass # pylint: disable=unnecessary-pass


class FormatError(Error):
"""Indicate an error while validating an object's format."""

pass # pylint: disable=unnecessary-pass


class InvalidMetadataJSONError(FormatError):
"""Indicate that a metadata file is not valid JSON."""
Expand All @@ -51,8 +45,6 @@ def __str__(self):
class UnsupportedAlgorithmError(Error):
"""Indicate an error while trying to identify a user-specified algorithm."""

pass # pylint: disable=unnecessary-pass


class BadHashError(Error):
"""Indicate an error while checking the value a hash object."""
Expand All @@ -76,14 +68,10 @@ def __str__(self):
class BadPasswordError(Error):
"""Indicate an error after encountering an invalid password."""

pass # pylint: disable=unnecessary-pass


class CryptoError(Error):
"""Indicate any cryptography-related errors."""

pass # pylint: disable=unnecessary-pass


class BadSignatureError(CryptoError):
"""Indicate that some metadata has a bad signature."""
Expand All @@ -100,45 +88,31 @@ def __str__(self):
class UnknownMethodError(CryptoError):
"""Indicate that a user-specified cryptograpthic method is unknown."""

pass # pylint: disable=unnecessary-pass


class UnsupportedLibraryError(Error):
"""Indicate that a supported library could not be located or imported."""

pass # pylint: disable=unnecessary-pass


class InvalidNameError(Error):
"""Indicate an error while trying to validate any type of named object."""

pass # pylint: disable=unnecessary-pass


class NotFoundError(Error):
"""If a required configuration or resource is not found."""

pass # pylint: disable=unnecessary-pass


class URLMatchesNoPatternError(Error):
"""If a URL does not match a user-specified regular expression."""

pass # pylint: disable=unnecessary-pass


class InvalidConfigurationError(Error):
"""If a configuration object does not match the expected format."""

pass # pylint: disable=unnecessary-pass


class StorageError(Error):
"""Indicate an error occured during interaction with an abstracted storage
backend."""

pass # pylint: disable=unnecessary-pass


class UnverifiedSignatureError(Error):
"""Signature could not be verified: either signature was incorrect or
Expand Down
6 changes: 3 additions & 3 deletions securesystemslib/gpg/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def parse_pubkey_bundle(data):
# - there must be least one User ID packet, or
# - order and type of signatures, or
# - disallow duplicate packets
if ( # pylint: disable=no-else-raise
if (
packet_type != PACKET_TYPE_PRIMARY_KEY
and not key_bundle[PACKET_TYPE_PRIMARY_KEY]["key"]
):
Expand All @@ -219,7 +219,7 @@ def parse_pubkey_bundle(data):
"got '{}'.".format(PACKET_TYPE_PRIMARY_KEY, packet_type)
)

elif (
if (
packet_type == PACKET_TYPE_PRIMARY_KEY
and key_bundle[PACKET_TYPE_PRIMARY_KEY]["key"]
):
Expand All @@ -228,7 +228,7 @@ def parse_pubkey_bundle(data):
# Fully parse master key to fail early, e.g. if key is malformed
# or not supported, but also retain original packet for subkey binding
# signature verification
elif packet_type == PACKET_TYPE_PRIMARY_KEY:
if packet_type == PACKET_TYPE_PRIMARY_KEY:
key_bundle[PACKET_TYPE_PRIMARY_KEY] = {
"key": parse_pubkey_payload(bytearray(payload)),
"packet": packet,
Expand Down
70 changes: 32 additions & 38 deletions securesystemslib/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,24 +454,21 @@ def format_keyval_to_metadata(keytype, scheme, key_value, private=False):
# key in the returned dictionary, ensure the private key is actually
# present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA'
# dicts).
if "private" not in key_value: # pylint: disable=no-else-raise
if "private" not in key_value:
raise exceptions.FormatError(
"The required private key"
" is missing from: " + repr(key_value)
"The required private key is missing from: " + repr(key_value)
)

else:
return {"keytype": keytype, "scheme": scheme, "keyval": key_value}
return {"keytype": keytype, "scheme": scheme, "keyval": key_value}

else:
public_key_value = {"public": key_value["public"]}
public_key_value = {"public": key_value["public"]}

return {
"keytype": keytype,
"scheme": scheme,
"keyid_hash_algorithms": settings.HASH_ALGORITHMS,
"keyval": public_key_value,
}
return {
"keytype": keytype,
"scheme": scheme,
"keyid_hash_algorithms": settings.HASH_ALGORITHMS,
"keyval": public_key_value,
}


def format_metadata_to_key(
Expand Down Expand Up @@ -830,15 +827,14 @@ def verify_signature(

# Verify that the KEYID in 'key_dict' matches the KEYID listed in the
# 'signature'.
if key_dict["keyid"] != signature["keyid"]: # pylint: disable=no-else-raise
if key_dict["keyid"] != signature["keyid"]:
raise exceptions.CryptoError(
"The KEYID ("
" " + repr(key_dict["keyid"]) + " ) in the given key does not match"
" the KEYID ( " + repr(signature["keyid"]) + " ) in the signature."
)

else:
logger.debug("The KEYIDs of key_dict and the signature match.")
logger.debug("The KEYIDs of key_dict and the signature match.")

# Using the public key belonging to 'key_dict'
# (i.e., rsakey_dict['keyval']['public']), verify whether 'signature'
Expand Down Expand Up @@ -1235,42 +1231,40 @@ def extract_pem(pem, private_pem=False):

except ValueError:
# Be careful not to print private key material in exception message.
if not private_pem: # pylint: disable=no-else-raise
raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM"
" header " + repr(pem_header) + "\n not found in PEM"
" string: " + repr(pem)
)

else:
if not private_pem:
raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM"
" header "
"Required PEM header "
+ repr(pem_header)
+ "\n not found in private PEM string."
+ "\n not found in PEM string: "
+ repr(pem)
)

raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM header "
+ repr(pem_header)
+ "\n not found in private PEM string."
)

try:
# Search for 'pem_footer' after the PEM header.
footer_start = pem.index(pem_footer, header_start + len(pem_header))

except ValueError:
# Be careful not to print private key material in exception message.
if not private_pem: # pylint: disable=no-else-raise
if not private_pem:
raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM"
" footer " + repr(pem_footer) + "\n not found in PEM"
" string " + repr(pem)
)

else:
raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM"
" footer "
"Required PEM footer "
+ repr(pem_footer)
+ "\n not found in private PEM string."
+ "\n not found in PEM string "
+ repr(pem)
)

raise exceptions.FormatError( # pylint: disable=raise-missing-from
"Required PEM footer "
+ repr(pem_footer)
+ "\n not found in private PEM string."
)

# Extract only the public portion of 'pem'. Leading or trailing whitespace
# is excluded.
pem = pem[header_start : footer_start + len(pem_footer)]
Expand Down
6 changes: 1 addition & 5 deletions securesystemslib/rsa_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1069,11 +1069,7 @@ def _decrypt(file_contents, password):
# specified so that the expected derived key is regenerated correctly.
# Discard the old "salt" and "iterations" values, as we only need the old
# derived key.
(
junk_old_salt, # pylint: disable=unused-variable
junk_old_iterations, # pylint: disable=unused-variable
symmetric_key,
) = _generate_derived_key(password, salt, iterations)
_, _, symmetric_key = _generate_derived_key(password, salt, iterations)

# Verify the hmac to ensure the ciphertext is valid and has not been altered.
# See the encryption routine for why we use the encrypt-then-MAC approach.
Expand Down
16 changes: 6 additions & 10 deletions securesystemslib/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,16 +597,14 @@ def __init__(self, lo=-2147483648, hi=2147483647):
self._hi = hi

def check_match(self, object): # pylint: disable=redefined-builtin
if isinstance( # pylint: disable=no-else-raise
object, bool
) or not isinstance(object, int):
if isinstance(object, bool) or not isinstance(object, int):
# We need to check for bool as a special case, since bool
# is for historical reasons a subtype of int.
raise exceptions.FormatError(
"Got " + repr(object) + " instead of an integer."
)

elif not (self._lo <= object <= self._hi):
if not (self._lo <= object <= self._hi):
int_range = "[" + repr(self._lo) + ", " + repr(self._hi) + "]."
raise exceptions.FormatError(
repr(object) + " not in range " + int_range
Expand Down Expand Up @@ -748,7 +746,7 @@ def __init__(self, object_name="object", **required):
"""

# Ensure valid arguments.
for key, schema in required.items(): # pylint: disable=unused-variable
for schema in required.values():
if not isinstance(schema, Schema):
raise exceptions.FormatError(
"Expected Schema but" " got " + repr(schema)
Expand Down Expand Up @@ -886,22 +884,20 @@ def __init__(
self._struct_name = struct_name

def check_match(self, object): # pylint: disable=redefined-builtin
if not isinstance( # pylint: disable=no-else-raise
object, (list, tuple)
):
if not isinstance(object, (list, tuple)):
raise exceptions.FormatError(
"Expected "
+ repr(self._struct_name)
+ "; but got "
+ repr(object)
)

elif len(object) < self._min:
if len(object) < self._min:
raise exceptions.FormatError(
"Too few fields in " + self._struct_name
)

elif len(object) > len(self._sub_schemas) and not self._allow_more:
if len(object) > len(self._sub_schemas) and not self._allow_more:
raise exceptions.FormatError(
"Too many fields in " + self._struct_name
)
Expand Down
4 changes: 2 additions & 2 deletions securesystemslib/unittest_toolbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def random_path(self, length=7):
"""Generate a 'random' path consisting of random n-length strings."""

rand_path = "/" + self.random_string(length)
for i in range(2): # pylint: disable=unused-variable
for _ in range(2):
rand_path = os.path.join(rand_path, self.random_string(length))

return rand_path
Expand All @@ -130,7 +130,7 @@ def random_string(length=15):
"""Generate a random string of specified length."""

rand_str = ""
for letter in range(length): # pylint: disable=unused-variable
for _ in range(length):
rand_str += random.choice("abcdefABCDEF" + string.digits) # nosec

return rand_str
6 changes: 2 additions & 4 deletions securesystemslib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,10 +450,8 @@ def digests_are_equal(digest1: str, digest2: str) -> bool:

are_equal = True

for element in range( # pylint: disable=consider-using-enumerate
len(digest1)
):
if digest1[element] != digest2[element]:
for val1, val2 in zip(digest1, digest2):
if val1 != val2:
are_equal = False

return are_equal
9 changes: 1 addition & 8 deletions tests/check_public_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,11 @@
when explicitly invoked.
"""

import inspect # pylint: disable=unused-import
import json # pylint: disable=unused-import
import os
import shutil
import sys
import tempfile
import unittest

if sys.version_info >= (3, 3):
import unittest.mock as mock # pylint: disable=consider-using-from-import
else:
import mock
from unittest import mock

import securesystemslib.exceptions # pylint: disable=wrong-import-position
import securesystemslib.gpg.constants # pylint: disable=wrong-import-position
Expand Down
6 changes: 1 addition & 5 deletions tests/test_ecdsa_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
Test cases for test_ecdsa_keys.py.
"""

import os # pylint: disable=unused-import
import unittest

import securesystemslib.ecdsa_keys
Expand Down Expand Up @@ -153,10 +152,7 @@ def test_verify_signature(self):

# Generate an RSA key so that we can verify that non-ECDSA keys are
# rejected.
(
rsa_pem,
junk, # pylint: disable=unused-variable
) = securesystemslib.rsa_keys.generate_rsa_public_and_private()
rsa_pem, _ = securesystemslib.rsa_keys.generate_rsa_public_and_private()

# Verify that a non-ECDSA key (via the PEM argument) is rejected.
self.assertRaises(
Expand Down
Loading