mirror of
https://github.com/ansible-collections/community.crypto.git
synced 2026-05-06 05:12:54 +00:00
Replace % and str.format() with f-strings (#875)
* Replace % and str.format() with f-strings. * Apply suggestions from review.
This commit is contained in:
@@ -73,7 +73,7 @@ class OpensshModule:
|
||||
self._execute()
|
||||
except Exception as e:
|
||||
self.module.fail_json(
|
||||
msg="unexpected error occurred: %s" % to_native(e),
|
||||
msg=f"unexpected error occurred: {to_native(e)}",
|
||||
exception=traceback.format_exc(),
|
||||
)
|
||||
|
||||
@@ -125,8 +125,7 @@ class OpensshModule:
|
||||
if not os.path.isdir(base_dir):
|
||||
self.module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
def _get_ssh_version(self):
|
||||
@@ -253,8 +252,7 @@ class KeygenCommand:
|
||||
os.chmod(private_key_path, stat.S_IWUSR + stat.S_IRUSR)
|
||||
except (IOError, OSError) as e:
|
||||
raise e(
|
||||
"The private key at %s is not writeable preventing a comment update"
|
||||
% private_key_path
|
||||
f"The private key at {private_key_path} is not writeable preventing a comment update"
|
||||
)
|
||||
|
||||
command = [self._bin_path, "-q"]
|
||||
@@ -332,7 +330,7 @@ class PublicKey:
|
||||
return not self == other
|
||||
|
||||
def __str__(self):
|
||||
return "%s %s" % (self._type_string, self._data)
|
||||
return f"{self._type_string} {self._data}"
|
||||
|
||||
@property
|
||||
def comment(self):
|
||||
|
||||
@@ -90,7 +90,7 @@ class KeypairBackend(OpensshModule):
|
||||
result = 256
|
||||
else:
|
||||
return self.module.fail_json(
|
||||
msg="%s is not a valid value for key type" % self.type
|
||||
msg=f"{self.type} is not a valid value for key type"
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -100,8 +100,7 @@ class KeypairBackend(OpensshModule):
|
||||
|
||||
if os.path.isdir(self.private_key_path):
|
||||
self.module.fail_json(
|
||||
msg="%s is a directory. Please specify a path to a file."
|
||||
% self.private_key_path
|
||||
msg=f"{self.private_key_path} is a directory. Please specify a path to a file."
|
||||
)
|
||||
|
||||
def _execute(self):
|
||||
@@ -562,4 +561,4 @@ def select_backend(module, backend):
|
||||
module.fail_json(msg=missing_required_lib("cryptography >= 2.6"))
|
||||
return backend, KeypairBackendCryptography(module)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
@@ -110,8 +110,7 @@ class OpensshCertificateTimeParameters:
|
||||
|
||||
if self._valid_from > self._valid_to:
|
||||
raise ValueError(
|
||||
"Valid from: %s must not be greater than Valid to: %s"
|
||||
% (valid_from, valid_to)
|
||||
f"Valid from: {valid_from} must not be greater than Valid to: {valid_to}"
|
||||
)
|
||||
|
||||
def __eq__(self, other):
|
||||
@@ -129,10 +128,7 @@ class OpensshCertificateTimeParameters:
|
||||
@property
|
||||
def validity_string(self):
|
||||
if not (self._valid_from == _ALWAYS and self._valid_to == _FOREVER):
|
||||
return "%s:%s" % (
|
||||
self.valid_from(date_format="openssh"),
|
||||
self.valid_to(date_format="openssh"),
|
||||
)
|
||||
return f"{self.valid_from(date_format='openssh')}:{self.valid_to(date_format='openssh')}"
|
||||
return ""
|
||||
|
||||
def valid_from(self, date_format):
|
||||
@@ -166,7 +162,7 @@ class OpensshCertificateTimeParameters:
|
||||
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
|
||||
)
|
||||
else:
|
||||
raise ValueError("%s is not a valid format" % date_format)
|
||||
raise ValueError(f"{date_format} is not a valid format")
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
@@ -182,8 +178,7 @@ class OpensshCertificateTimeParameters:
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
"Value must be of type (str, unicode, int, long) not %s"
|
||||
% type(time_string_or_timestamp)
|
||||
f"Value must be of type (str, unicode, int, long) not {type(time_string_or_timestamp)}"
|
||||
)
|
||||
except ValueError:
|
||||
raise
|
||||
@@ -238,10 +233,10 @@ class OpensshCertificateOption:
|
||||
raise ValueError("type must be either 'critical' or 'extension'")
|
||||
|
||||
if not isinstance(name, six.string_types):
|
||||
raise TypeError("name must be a string not %s" % type(name))
|
||||
raise TypeError(f"name must be a string not {type(name)}")
|
||||
|
||||
if not isinstance(data, six.string_types):
|
||||
raise TypeError("data must be a string not %s" % type(data))
|
||||
raise TypeError(f"data must be a string not {type(data)}")
|
||||
|
||||
self._option_type = option_type
|
||||
self._name = name.lower()
|
||||
@@ -267,7 +262,7 @@ class OpensshCertificateOption:
|
||||
|
||||
def __str__(self):
|
||||
if self._data:
|
||||
return "%s=%s" % (self._name, self._data)
|
||||
return f"{self._name}={self._data}"
|
||||
return self._name
|
||||
|
||||
@property
|
||||
@@ -286,7 +281,7 @@ class OpensshCertificateOption:
|
||||
def from_string(cls, option_string):
|
||||
if not isinstance(option_string, six.string_types):
|
||||
raise ValueError(
|
||||
"option_string must be a string not %s" % type(option_string)
|
||||
f"option_string must be a string not {type(option_string)}"
|
||||
)
|
||||
option_type = None
|
||||
|
||||
@@ -356,7 +351,7 @@ class OpensshCertificateInfo:
|
||||
elif cert_type == "host" or cert_type == _HOST_TYPE:
|
||||
self._cert_type = _HOST_TYPE
|
||||
else:
|
||||
raise ValueError("%s is not a valid certificate type" % cert_type)
|
||||
raise ValueError(f"{cert_type} is not a valid certificate type")
|
||||
|
||||
def signing_key_fingerprint(self):
|
||||
return fingerprint(self.signing_key)
|
||||
@@ -447,8 +442,7 @@ class OpensshECDSACertificateInfo(OpensshCertificateInfo):
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
"Curve must be one of %s"
|
||||
% (b",".join(list(_ECDSA_CURVE_IDENTIFIERS.values()))).decode("UTF-8")
|
||||
"Curve must be one of {(b','.join(_ECDSA_CURVE_IDENTIFIERS.values())).decode('UTF-8')}"
|
||||
)
|
||||
|
||||
# See https://datatracker.ietf.org/doc/html/rfc4253#section-6.6
|
||||
@@ -500,13 +494,13 @@ class OpensshCertificate:
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("%s is not a valid path." % path)
|
||||
raise ValueError(f"{path} is not a valid path.")
|
||||
|
||||
try:
|
||||
with open(path, "rb") as cert_file:
|
||||
data = cert_file.read()
|
||||
except (IOError, OSError) as e:
|
||||
raise ValueError("%s cannot be opened for reading: %s" % (path, e))
|
||||
raise ValueError(f"{path} cannot be opened for reading: {e}")
|
||||
|
||||
try:
|
||||
format_identifier, b64_cert = data.split(b" ")[:2]
|
||||
@@ -520,7 +514,7 @@ class OpensshCertificate:
|
||||
break
|
||||
else:
|
||||
raise ValueError(
|
||||
"Invalid certificate format identifier: %s" % format_identifier
|
||||
f"Invalid certificate format identifier: {format_identifier}"
|
||||
)
|
||||
|
||||
parser = OpensshParser(cert)
|
||||
@@ -532,12 +526,11 @@ class OpensshCertificate:
|
||||
cert_info = cls._parse_cert_info(pub_key_type, parser)
|
||||
signature = parser.string()
|
||||
except (TypeError, ValueError) as e:
|
||||
raise ValueError("Invalid certificate data: %s" % e)
|
||||
raise ValueError(f"Invalid certificate data: {e}")
|
||||
|
||||
if parser.remaining_bytes():
|
||||
raise ValueError(
|
||||
"%s bytes of additional data was not parsed while loading %s"
|
||||
% (parser.remaining_bytes(), path)
|
||||
f"{parser.remaining_bytes()} bytes of additional data was not parsed while loading {path}"
|
||||
)
|
||||
|
||||
return cls(
|
||||
@@ -651,7 +644,7 @@ class OpensshCertificate:
|
||||
|
||||
def apply_directives(directives):
|
||||
if any(d not in _DIRECTIVES for d in directives):
|
||||
raise ValueError("directives must be one of %s" % ", ".join(_DIRECTIVES))
|
||||
raise ValueError(f"directives must be one of {', '.join(_DIRECTIVES)}")
|
||||
|
||||
directive_to_option = {
|
||||
"no-x11-forwarding": OpensshCertificateOption(
|
||||
@@ -696,7 +689,7 @@ def get_cert_info_object(key_type):
|
||||
elif key_type == "ed25519":
|
||||
cert_info = OpensshED25519CertificateInfo()
|
||||
else:
|
||||
raise ValueError("%s is not a valid key type" % key_type)
|
||||
raise ValueError(f"{key_type} is not a valid key type")
|
||||
|
||||
return cert_info
|
||||
|
||||
@@ -708,8 +701,8 @@ def get_option_type(name):
|
||||
result = "extension"
|
||||
else:
|
||||
raise ValueError(
|
||||
"%s is not a valid option. " % name
|
||||
+ "Custom options must start with 'critical:' or 'extension:' to indicate type"
|
||||
f"{name} is not a valid option. "
|
||||
"Custom options must start with 'critical:' or 'extension:' to indicate type"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -137,8 +137,7 @@ class AsymmetricKeypair:
|
||||
|
||||
if keytype not in _ALGORITHM_PARAMETERS.keys():
|
||||
raise InvalidKeyTypeError(
|
||||
"%s is not a valid keytype. Valid keytypes are %s"
|
||||
% (keytype, ", ".join(_ALGORITHM_PARAMETERS.keys()))
|
||||
f"{keytype} is not a valid keytype. Valid keytypes are {', '.join(_ALGORITHM_PARAMETERS)}"
|
||||
)
|
||||
|
||||
if not size:
|
||||
@@ -146,7 +145,7 @@ class AsymmetricKeypair:
|
||||
else:
|
||||
if size not in _ALGORITHM_PARAMETERS[keytype]["valid_sizes"]:
|
||||
raise InvalidKeySizeError(
|
||||
"%s is not a valid key size for %s keys" % (size, keytype)
|
||||
f"{size} is not a valid key size for {keytype} keys"
|
||||
)
|
||||
|
||||
if passphrase:
|
||||
@@ -229,9 +228,7 @@ class AsymmetricKeypair:
|
||||
elif isinstance(privatekey, Ed25519PrivateKey):
|
||||
keytype = "ed25519"
|
||||
else:
|
||||
raise InvalidKeyTypeError(
|
||||
"Key type '%s' is not supported" % type(privatekey)
|
||||
)
|
||||
raise InvalidKeyTypeError(f"Key type '{type(privatekey)}' is not supported")
|
||||
|
||||
return cls(
|
||||
keytype=keytype,
|
||||
@@ -363,7 +360,7 @@ class OpensshKeypair:
|
||||
"""
|
||||
|
||||
if comment is None:
|
||||
comment = "%s@%s" % (getuser(), gethostname())
|
||||
comment = f"{getuser()}@{gethostname()}"
|
||||
|
||||
asym_keypair = AsymmetricKeypair.generate(keytype, size, passphrase)
|
||||
openssh_privatekey = cls.encode_openssh_privatekey(asym_keypair, "SSH")
|
||||
@@ -457,7 +454,7 @@ class OpensshKeypair:
|
||||
validate_comment(comment)
|
||||
|
||||
encoded_publickey += (
|
||||
(" %s" % comment).encode(encoding=_TEXT_ENCODING) if comment else b""
|
||||
f" {comment}".encode(encoding=_TEXT_ENCODING) if comment else b""
|
||||
)
|
||||
|
||||
return encoded_publickey
|
||||
@@ -541,7 +538,7 @@ class OpensshKeypair:
|
||||
|
||||
self.__comment = comment
|
||||
encoded_comment = (
|
||||
(" %s" % self.__comment).encode(encoding=_TEXT_ENCODING)
|
||||
f" {self.__comment}".encode(encoding=_TEXT_ENCODING)
|
||||
if self.__comment
|
||||
else b""
|
||||
)
|
||||
@@ -578,12 +575,11 @@ def load_privatekey(path, passphrase, key_format):
|
||||
privatekey_loader = privatekey_loaders[key_format]
|
||||
except KeyError:
|
||||
raise InvalidKeyFormatError(
|
||||
"%s is not a valid key format (%s)"
|
||||
% (key_format, ",".join(privatekey_loaders.keys()))
|
||||
f"{key_format} is not a valid key format ({','.join(privatekey_loaders)})"
|
||||
)
|
||||
|
||||
if not os.path.exists(path):
|
||||
raise InvalidPrivateKeyFileError("No file was found at %s" % path)
|
||||
raise InvalidPrivateKeyFileError(f"No file was found at {path}")
|
||||
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
@@ -631,12 +627,11 @@ def load_publickey(path, key_format):
|
||||
publickey_loader = publickey_loaders[key_format]
|
||||
except KeyError:
|
||||
raise InvalidKeyFormatError(
|
||||
"%s is not a valid key format (%s)"
|
||||
% (key_format, ",".join(publickey_loaders.keys()))
|
||||
f"{key_format} is not a valid key format ({','.join(publickey_loaders)})"
|
||||
)
|
||||
|
||||
if not os.path.exists(path):
|
||||
raise InvalidPublicKeyFileError("No file was found at %s" % path)
|
||||
raise InvalidPublicKeyFileError(f"No file was found at {path}")
|
||||
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
@@ -689,13 +684,13 @@ def get_encryption_algorithm(passphrase):
|
||||
|
||||
def validate_comment(comment):
|
||||
if not hasattr(comment, "encode"):
|
||||
raise InvalidCommentError("%s cannot be encoded to text" % comment)
|
||||
raise InvalidCommentError(f"{comment} cannot be encoded to text")
|
||||
|
||||
|
||||
def extract_comment(path):
|
||||
|
||||
if not os.path.exists(path):
|
||||
raise InvalidPublicKeyFileError("No file was found at %s" % path)
|
||||
raise InvalidPublicKeyFileError(f"No file was found at {path}")
|
||||
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
@@ -715,6 +710,5 @@ def calculate_fingerprint(openssh_publickey):
|
||||
decoded_pubkey = b64decode(openssh_publickey.split(b" ")[1])
|
||||
digest.update(decoded_pubkey)
|
||||
|
||||
return "SHA256:%s" % b64encode(digest.finalize()).decode(
|
||||
encoding=_TEXT_ENCODING
|
||||
).rstrip("=")
|
||||
value = b64encode(digest.finalize()).decode(encoding=_TEXT_ENCODING).rstrip("=")
|
||||
return f"SHA256:{value}"
|
||||
|
||||
@@ -91,7 +91,7 @@ class OpensshParser:
|
||||
|
||||
def __init__(self, data):
|
||||
if not isinstance(data, (bytes, bytearray)):
|
||||
raise TypeError("Data must be bytes-like not %s" % type(data))
|
||||
raise TypeError(f"Data must be bytes-like not {type(data)}")
|
||||
|
||||
self._data = memoryview(data) if PY3 else data
|
||||
self._pos = 0
|
||||
@@ -174,7 +174,7 @@ class OpensshParser:
|
||||
|
||||
def _check_position(self, offset):
|
||||
if self._pos + offset > len(self._data):
|
||||
raise ValueError("Insufficient data remaining at position: %s" % self._pos)
|
||||
raise ValueError(f"Insufficient data remaining at position: {self._pos}")
|
||||
elif self._pos + offset < 0:
|
||||
raise ValueError("Position cannot be less than zero.")
|
||||
else:
|
||||
@@ -210,7 +210,7 @@ class OpensshParser:
|
||||
signature_data["R"] = cls._big_int(signature_blob[:32], "little")
|
||||
signature_data["S"] = cls._big_int(signature_blob[32:], "little")
|
||||
else:
|
||||
raise ValueError("%s is not a valid signature type" % signature_type)
|
||||
raise ValueError(f"{signature_type} is not a valid signature type")
|
||||
|
||||
signature_data["signature_type"] = signature_type
|
||||
|
||||
@@ -220,7 +220,7 @@ class OpensshParser:
|
||||
def _big_int(cls, raw_string, byte_order, signed=False):
|
||||
if byte_order not in ("big", "little"):
|
||||
raise ValueError(
|
||||
"Byte_order must be one of (big, little) not %s" % byte_order
|
||||
f"Byte_order must be one of (big, little) not {byte_order}"
|
||||
)
|
||||
|
||||
if PY3:
|
||||
@@ -279,7 +279,7 @@ class _OpensshWriter:
|
||||
if buffer is not None:
|
||||
if not isinstance(buffer, (bytes, bytearray)):
|
||||
raise TypeError(
|
||||
"Buffer must be a bytes-like object not %s" % type(buffer)
|
||||
f"Buffer must be a bytes-like object not {type(buffer)}"
|
||||
)
|
||||
else:
|
||||
buffer = bytearray()
|
||||
@@ -288,7 +288,7 @@ class _OpensshWriter:
|
||||
|
||||
def boolean(self, value):
|
||||
if not isinstance(value, bool):
|
||||
raise TypeError("Value must be of type bool not %s" % type(value))
|
||||
raise TypeError(f"Value must be of type bool not {type(value)}")
|
||||
|
||||
self._buff.extend(_BOOLEAN.pack(value))
|
||||
|
||||
@@ -296,10 +296,10 @@ class _OpensshWriter:
|
||||
|
||||
def uint32(self, value):
|
||||
if not isinstance(value, int):
|
||||
raise TypeError("Value must be of type int not %s" % type(value))
|
||||
raise TypeError(f"Value must be of type int not {type(value)}")
|
||||
if value < 0 or value > _UINT32_MAX:
|
||||
raise ValueError(
|
||||
"Value must be a positive integer less than %s" % _UINT32_MAX
|
||||
f"Value must be a positive integer less than {_UINT32_MAX}"
|
||||
)
|
||||
|
||||
self._buff.extend(_UINT32.pack(value))
|
||||
@@ -308,10 +308,10 @@ class _OpensshWriter:
|
||||
|
||||
def uint64(self, value):
|
||||
if not isinstance(value, (long, int)):
|
||||
raise TypeError("Value must be of type (long, int) not %s" % type(value))
|
||||
raise TypeError(f"Value must be of type (long, int) not {type(value)}")
|
||||
if value < 0 or value > _UINT64_MAX:
|
||||
raise ValueError(
|
||||
"Value must be a positive integer less than %s" % _UINT64_MAX
|
||||
f"Value must be a positive integer less than {_UINT64_MAX}"
|
||||
)
|
||||
|
||||
self._buff.extend(_UINT64.pack(value))
|
||||
@@ -320,7 +320,7 @@ class _OpensshWriter:
|
||||
|
||||
def string(self, value):
|
||||
if not isinstance(value, (bytes, bytearray)):
|
||||
raise TypeError("Value must be bytes-like not %s" % type(value))
|
||||
raise TypeError(f"Value must be bytes-like not {type(value)}")
|
||||
self.uint32(len(value))
|
||||
self._buff.extend(value)
|
||||
|
||||
@@ -328,7 +328,7 @@ class _OpensshWriter:
|
||||
|
||||
def mpint(self, value):
|
||||
if not isinstance(value, (int, long)):
|
||||
raise TypeError("Value must be of type (long, int) not %s" % type(value))
|
||||
raise TypeError(f"Value must be of type (long, int) not {type(value)}")
|
||||
|
||||
self.string(self._int_to_mpint(value))
|
||||
|
||||
@@ -336,18 +336,18 @@ class _OpensshWriter:
|
||||
|
||||
def name_list(self, value):
|
||||
if not isinstance(value, list):
|
||||
raise TypeError("Value must be a list of byte strings not %s" % type(value))
|
||||
raise TypeError(f"Value must be a list of byte strings not {type(value)}")
|
||||
|
||||
try:
|
||||
self.string(",".join(value).encode("ASCII"))
|
||||
except UnicodeEncodeError as e:
|
||||
raise ValueError("Name-list's must consist of US-ASCII characters: %s" % e)
|
||||
raise ValueError(f"Name-list's must consist of US-ASCII characters: {e}")
|
||||
|
||||
return self
|
||||
|
||||
def string_list(self, value):
|
||||
if not isinstance(value, list):
|
||||
raise TypeError("Value must be a list of byte string not %s" % type(value))
|
||||
raise TypeError(f"Value must be a list of byte string not {type(value)}")
|
||||
|
||||
writer = _OpensshWriter()
|
||||
for s in value:
|
||||
|
||||
Reference in New Issue
Block a user