diff --git a/securesystemslib/ecdsa_keys.py b/securesystemslib/ecdsa_keys.py index 65098f39..a05df5b3 100755 --- a/securesystemslib/ecdsa_keys.py +++ b/securesystemslib/ecdsa_keys.py @@ -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. diff --git a/securesystemslib/exceptions.py b/securesystemslib/exceptions.py index 5f25fbe0..e41ea7c0 100755 --- a/securesystemslib/exceptions.py +++ b/securesystemslib/exceptions.py @@ -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.""" @@ -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.""" @@ -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.""" @@ -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 diff --git a/securesystemslib/gpg/common.py b/securesystemslib/gpg/common.py index 9d8c4d8f..fcbc5ae0 100644 --- a/securesystemslib/gpg/common.py +++ b/securesystemslib/gpg/common.py @@ -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"] ): @@ -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"] ): @@ -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, diff --git a/securesystemslib/keys.py b/securesystemslib/keys.py index 22a863e2..76c37ab8 100755 --- a/securesystemslib/keys.py +++ b/securesystemslib/keys.py @@ -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( @@ -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' @@ -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)] diff --git a/securesystemslib/rsa_keys.py b/securesystemslib/rsa_keys.py index a567ef8c..0e083983 100755 --- a/securesystemslib/rsa_keys.py +++ b/securesystemslib/rsa_keys.py @@ -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. diff --git a/securesystemslib/schema.py b/securesystemslib/schema.py index d1d1e612..aa8c2588 100755 --- a/securesystemslib/schema.py +++ b/securesystemslib/schema.py @@ -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 @@ -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) @@ -886,9 +884,7 @@ 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) @@ -896,12 +892,12 @@ def check_match(self, object): # pylint: disable=redefined-builtin + 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 ) diff --git a/securesystemslib/unittest_toolbox.py b/securesystemslib/unittest_toolbox.py index 0b6223e8..7ad4e9e4 100755 --- a/securesystemslib/unittest_toolbox.py +++ b/securesystemslib/unittest_toolbox.py @@ -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 @@ -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 diff --git a/securesystemslib/util.py b/securesystemslib/util.py index 755f13aa..8490b923 100644 --- a/securesystemslib/util.py +++ b/securesystemslib/util.py @@ -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 diff --git a/tests/check_public_interfaces.py b/tests/check_public_interfaces.py index 2103370c..69608947 100644 --- a/tests/check_public_interfaces.py +++ b/tests/check_public_interfaces.py @@ -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 diff --git a/tests/test_ecdsa_keys.py b/tests/test_ecdsa_keys.py index fc9b90ce..732d496e 100755 --- a/tests/test_ecdsa_keys.py +++ b/tests/test_ecdsa_keys.py @@ -17,7 +17,6 @@ Test cases for test_ecdsa_keys.py. """ -import os # pylint: disable=unused-import import unittest import securesystemslib.ecdsa_keys @@ -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( diff --git a/tests/test_formats.py b/tests/test_formats.py index af21b088..213c3f58 100755 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -220,10 +220,7 @@ def test_schemas(self): # Iterate 'valid_schemas', ensuring each 'valid_schema' correctly matches # its respective 'schema_type'. - for schema_name, ( # pylint: disable=unused-variable - schema_type, - valid_schema, - ) in valid_schemas.items(): + for (schema_type, valid_schema) in valid_schemas.values(): if not schema_type.matches( # pylint: disable=no-member valid_schema ): @@ -237,7 +234,7 @@ def test_schemas(self): # Test conditions for invalid schemas. # Set the 'valid_schema' of 'valid_schemas' to an invalid # value and test that it does not match 'schema_type'. - for schema_name, (schema_type, valid_schema) in valid_schemas.items(): + for (schema_type, valid_schema) in valid_schemas.values(): invalid_schema = 0xBAD if isinstance(schema_type, securesystemslib.schema.Integer): @@ -251,9 +248,6 @@ def test_schemas(self): def test_unix_timestamp_to_datetime(self): # Test conditions for valid arguments. - UNIX_TIMESTAMP_SCHEMA = ( # pylint: disable=invalid-name,unused-variable - securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA - ) self.assertTrue( datetime.datetime, securesystemslib.formats.unix_timestamp_to_datetime(499137720), @@ -377,7 +371,6 @@ def test_encode_canonical(self): encode = securesystemslib.formats.encode_canonical result = [] output = result.append - bad_output = 123 # pylint: disable=unused-variable self.assertEqual('""', encode("")) self.assertEqual("[1,2,3]", encode([1, 2, 3])) diff --git a/tests/test_gpg.py b/tests/test_gpg.py index 5431de73..f4ddbfd0 100644 --- a/tests/test_gpg.py +++ b/tests/test_gpg.py @@ -21,24 +21,17 @@ import os import shutil -import sys import tempfile import unittest -if sys.version_info >= (3, 3): - from unittest.mock import ( # pylint: disable=no-name-in-module,import-error - patch, - ) -else: - from mock import patch # pylint: disable=import-error - # pylint: disable=wrong-import-position from collections import OrderedDict from copy import deepcopy +from unittest.mock import patch -import cryptography.hazmat.backends as backends # pylint: disable=consider-using-from-import import cryptography.hazmat.primitives.hashes as hashing -import cryptography.hazmat.primitives.serialization as serialization # pylint: disable=consider-using-from-import +from cryptography.hazmat import backends +from cryptography.hazmat.primitives import serialization from securesystemslib import exceptions, process from securesystemslib.formats import ANY_PUBKEY_DICT_SCHEMA, GPG_PUBKEY_SCHEMA @@ -62,12 +55,7 @@ have_gpg, ) from securesystemslib.gpg.dsa import create_pubkey as dsa_create_pubkey - -# pylint: disable=unused-import from securesystemslib.gpg.eddsa import ED25519_SIG_LENGTH -from securesystemslib.gpg.eddsa import create_pubkey as eddsa_create_pubkey - -# pylint: enable=unused-import from securesystemslib.gpg.exceptions import ( CommandError, KeyExpirationError, diff --git a/tests/test_hash.py b/tests/test_hash.py index f13ce3bb..647c7e04 100755 --- a/tests/test_hash.py +++ b/tests/test_hash.py @@ -21,7 +21,6 @@ import io import logging import os -import sys # pylint: disable=unused-import import tempfile import unittest diff --git a/tests/test_interface.py b/tests/test_interface.py index 260bdeec..f48b1073 100755 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -17,26 +17,16 @@ Unit test for 'interface.py'. """ -import datetime # pylint: disable=unused-import -import json # pylint: disable=unused-import import os import shutil import stat -import sys import tempfile -import time # pylint: disable=unused-import import unittest +from unittest import mock from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import load_pem_private_key -# Use external backport 'mock' on versions under 3.3 -if sys.version_info >= (3, 3): - import unittest.mock as mock # pylint: disable=consider-using-from-import - -else: - import mock - from securesystemslib import ( # pylint: disable=wrong-import-position KEY_TYPE_ECDSA, KEY_TYPE_ED25519, diff --git a/tests/test_keys.py b/tests/test_keys.py index 0a60f14b..7302b86d 100755 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -175,30 +175,23 @@ def test_format_metadata_to_key(self): del test_rsakey_dict["keyid"] # Call format_metadata_to_key by using the default value for keyid_hash_algorithms - ( - rsakey_dict_from_meta_default, - junk, # pylint: disable=unused-variable - ) = KEYS.format_metadata_to_key(test_rsakey_dict) + rsakey_formatted, _ = KEYS.format_metadata_to_key(test_rsakey_dict) # Check if the format of the object returned by calling this function with # default hash algorithms e.g. securesystemslib.settings.HASH_ALGORITHMS corresponds # to RSAKEY_SCHEMA format. self.assertTrue( - securesystemslib.formats.RSAKEY_SCHEMA.matches( - rsakey_dict_from_meta_default - ), + securesystemslib.formats.RSAKEY_SCHEMA.matches(rsakey_formatted), FORMAT_ERROR_MSG, ) self.assertTrue( - securesystemslib.formats.KEY_SCHEMA.matches( - rsakey_dict_from_meta_default - ), + securesystemslib.formats.KEY_SCHEMA.matches(rsakey_formatted), FORMAT_ERROR_MSG, ) # Call format_metadata_to_key by using custom value for keyid_hash_algorithms - rsakey_dict_from_meta_custom, junk = KEYS.format_metadata_to_key( + rsakey_dict_from_meta_custom, _ = KEYS.format_metadata_to_key( test_rsakey_dict, keyid_hash_algorithms=["sha384"] ) @@ -552,10 +545,7 @@ def test_create_rsa_encrypted_pem(self): def test_import_rsakey_from_private_pem(self): # Try to import an rsakey from a valid PEM. private_pem = self.rsakey_dict["keyval"]["private"] - - private_rsakey = KEYS.import_rsakey_from_private_pem( # pylint: disable=unused-variable - private_pem - ) + _ = KEYS.import_rsakey_from_private_pem(private_pem) # Test for invalid arguments. self.assertRaises( @@ -681,16 +671,14 @@ def test_import_rsakey_from_pem(self): def test_import_ecdsakey_from_private_pem(self): # Try to import an ecdsakey from a valid PEM. private_pem = self.ecdsakey_dict["keyval"]["private"] - ecdsakey = KEYS.import_ecdsakey_from_private_pem( # pylint: disable=unused-variable - private_pem - ) + _ = KEYS.import_ecdsakey_from_private_pem(private_pem) # Test for an encrypted PEM. scheme = "ecdsa-sha2-nistp256" encrypted_pem = securesystemslib.ecdsa_keys.create_ecdsa_encrypted_pem( private_pem, "password" ) - private_ecdsakey = KEYS.import_ecdsakey_from_private_pem( # pylint: disable=unused-variable + _ = KEYS.import_ecdsakey_from_private_pem( encrypted_pem.decode("utf-8"), scheme, "password" ) diff --git a/tests/test_rsa_keys.py b/tests/test_rsa_keys.py index 1ff26619..9659d767 100755 --- a/tests/test_rsa_keys.py +++ b/tests/test_rsa_keys.py @@ -393,9 +393,7 @@ def test_decrypt_key(self): rsa_key, passphrase ) - decrypted_rsa_key = securesystemslib.rsa_keys.decrypt_key( # pylint: disable=unused-variable - encrypted_rsa_key, passphrase - ) + _ = securesystemslib.rsa_keys.decrypt_key(encrypted_rsa_key, passphrase) # Test for invalid arguments. self.assertRaises( diff --git a/tests/test_util.py b/tests/test_util.py index 55747e8b..f6c4472c 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -19,18 +19,15 @@ import logging import os -import shutil # pylint: disable=unused-import import stat -import sys # pylint: disable=unused-import import tempfile import timeit import unittest -import securesystemslib.exceptions as exceptions # pylint: disable=consider-using-from-import import securesystemslib.hash import securesystemslib.settings -import securesystemslib.unittest_toolbox as unittest_toolbox # pylint: disable=consider-using-from-import import securesystemslib.util +from securesystemslib import exceptions, unittest_toolbox logger = logging.getLogger(__name__) @@ -135,9 +132,6 @@ def test_B3_get_file_length(self): filepath = self.make_temp_data_file() # Computing the length of the tempfile. - digest_object = securesystemslib.hash.digest_filename( # pylint: disable=unused-variable - filepath, algorithm="sha256" - ) file_length = os.path.getsize(filepath) # Test: Expected input.