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:
@@ -82,8 +82,7 @@ def serialize_asn1_string_as_der(value):
|
||||
|
||||
if value_type != "UTF8":
|
||||
raise ValueError(
|
||||
'The ASN.1 serialized string is not a known type "{0}", only UTF8 types are '
|
||||
"supported".format(value_type)
|
||||
f'The ASN.1 serialized string is not a known type "{value_type}", only UTF8 types are supported'
|
||||
)
|
||||
|
||||
b_value = to_bytes(asn1_value, encoding="utf-8", errors="surrogate_or_strict")
|
||||
@@ -117,7 +116,7 @@ def pack_asn1(tag_class, constructed, tag_number, b_data):
|
||||
b_asn1_data = bytearray()
|
||||
|
||||
if tag_class < 0 or tag_class > 3:
|
||||
raise ValueError("tag_class must be between 0 and 3 not %s" % tag_class)
|
||||
raise ValueError(f"tag_class must be between 0 and 3 not {tag_class}")
|
||||
|
||||
# Bit 8 and 7 denotes the class.
|
||||
identifier_octets = tag_class << 6
|
||||
|
||||
@@ -15,9 +15,7 @@ for dotted, names in OID_MAP.items():
|
||||
for name in names:
|
||||
if name in NORMALIZE_NAMES and OID_LOOKUP[name] != dotted:
|
||||
raise AssertionError(
|
||||
'Name collision during setup: "{0}" for OIDs {1} and {2}'.format(
|
||||
name, dotted, OID_LOOKUP[name]
|
||||
)
|
||||
f'Name collision during setup: "{name}" for OIDs {dotted} and {OID_LOOKUP[name]}'
|
||||
)
|
||||
NORMALIZE_NAMES[name] = names[0]
|
||||
NORMALIZE_NAMES_SHORT[name] = names[-1]
|
||||
@@ -25,9 +23,7 @@ for dotted, names in OID_MAP.items():
|
||||
for alias, original in [("userID", "userId")]:
|
||||
if alias in NORMALIZE_NAMES:
|
||||
raise AssertionError(
|
||||
'Name collision during adding aliases: "{0}" (alias for "{1}") is already mapped to OID {2}'.format(
|
||||
alias, original, OID_LOOKUP[alias]
|
||||
)
|
||||
f'Name collision during adding aliases: "{alias}" (alias for "{original}") is already mapped to OID {OID_LOOKUP[alias]}'
|
||||
)
|
||||
NORMALIZE_NAMES[alias] = original
|
||||
NORMALIZE_NAMES_SHORT[alias] = NORMALIZE_NAMES_SHORT[original]
|
||||
|
||||
@@ -242,7 +242,7 @@ def cryptography_name_to_oid(name):
|
||||
if dotted is None:
|
||||
if DOTTED_OID.match(name):
|
||||
return x509.oid.ObjectIdentifier(name)
|
||||
raise OpenSSLObjectError('Cannot find OID for "{0}"'.format(name))
|
||||
raise OpenSSLObjectError(f'Cannot find OID for "{name}"')
|
||||
return x509.oid.ObjectIdentifier(dotted)
|
||||
|
||||
|
||||
@@ -297,7 +297,7 @@ else:
|
||||
def _parse_dn_component(name, sep=b",", decode_remainder=True):
|
||||
m = DN_COMPONENT_START_RE.match(name)
|
||||
if not m:
|
||||
raise OpenSSLObjectError('cannot start part in "{0}"'.format(to_text(name)))
|
||||
raise OpenSSLObjectError(f'cannot start part in "{to_text(name)}"')
|
||||
oid = cryptography_name_to_oid(to_text(m.group(1)))
|
||||
idx = len(m.group(0))
|
||||
decoded_name = []
|
||||
@@ -314,7 +314,7 @@ def _parse_dn_component(name, sep=b",", decode_remainder=True):
|
||||
idx2 = DN_HEX_LETTER.find(ch2.lower())
|
||||
if idx1 < 0 or idx2 < 0:
|
||||
raise OpenSSLObjectError(
|
||||
'Invalid hex sequence entry "{0}"'.format(to_text(ch1 + ch2))
|
||||
f'Invalid hex sequence entry "{to_text(ch1 + ch2)}"'
|
||||
)
|
||||
idx += 2
|
||||
decoded_name.append(_int_to_byte(idx1 * 16 + idx2))
|
||||
@@ -333,17 +333,13 @@ def _parse_dn_component(name, sep=b",", decode_remainder=True):
|
||||
if idx1 >= 0:
|
||||
if idx + 2 >= length:
|
||||
raise OpenSSLObjectError(
|
||||
'Hex escape sequence "\\{0}" incomplete at end of string'.format(
|
||||
to_text(ch)
|
||||
)
|
||||
f'Hex escape sequence "\\{to_text(ch)}" incomplete at end of string'
|
||||
)
|
||||
ch2 = name[idx + 2 : idx + 3]
|
||||
idx2 = DN_HEX_LETTER.find(ch2.lower())
|
||||
if idx2 < 0:
|
||||
raise OpenSSLObjectError(
|
||||
'Hex escape sequence "\\{0}" has invalid second letter'.format(
|
||||
to_text(ch + ch2)
|
||||
)
|
||||
f'Hex escape sequence "\\{to_text(ch + ch2)}" has invalid second letter'
|
||||
)
|
||||
ch = _int_to_byte(idx1 * 16 + idx2)
|
||||
idx += 1
|
||||
@@ -375,17 +371,13 @@ def _parse_dn(name):
|
||||
attribute, name = _parse_dn_component(name, sep=sep)
|
||||
except OpenSSLObjectError as e:
|
||||
raise OpenSSLObjectError(
|
||||
'Error while parsing distinguished name "{0}": {1}'.format(
|
||||
to_text(original_name), e
|
||||
)
|
||||
f'Error while parsing distinguished name "{to_text(original_name)}": {e}'
|
||||
)
|
||||
result.append(attribute)
|
||||
if name:
|
||||
if name[0:1] != sep or len(name) < 2:
|
||||
raise OpenSSLObjectError(
|
||||
'Error while parsing distinguished name "{0}": unexpected end of string'.format(
|
||||
to_text(original_name)
|
||||
)
|
||||
f'Error while parsing distinguished name "{to_text(original_name)}": unexpected end of string'
|
||||
)
|
||||
name = name[1:]
|
||||
return result
|
||||
@@ -398,9 +390,7 @@ def cryptography_parse_relative_distinguished_name(rdn):
|
||||
names.append(_parse_dn_component(to_bytes(part), decode_remainder=False)[0])
|
||||
except OpenSSLObjectError as e:
|
||||
raise OpenSSLObjectError(
|
||||
'Error while parsing relative distinguished name "{0}": {1}'.format(
|
||||
part, e
|
||||
)
|
||||
f'Error while parsing relative distinguished name "{part}": {e}'
|
||||
)
|
||||
return cryptography.x509.RelativeDistinguishedName(names)
|
||||
|
||||
@@ -420,16 +410,14 @@ def _adjust_idn(value, idn_rewrite):
|
||||
if idn_rewrite == "idna" and _is_ascii(value):
|
||||
return value
|
||||
if idn_rewrite not in ("idna", "unicode"):
|
||||
raise ValueError('Invalid value for idn_rewrite: "{0}"'.format(idn_rewrite))
|
||||
raise ValueError(f'Invalid value for idn_rewrite: "{idn_rewrite}"')
|
||||
if not HAS_IDNA:
|
||||
what = "IDNA" if idn_rewrite == "unicode" else "Unicode"
|
||||
dest = "Unicode" if idn_rewrite == "unicode" else "IDNA"
|
||||
raise OpenSSLObjectError(
|
||||
missing_required_lib(
|
||||
"idna",
|
||||
reason='to transform {what} DNS name "{name}" to {dest}'.format(
|
||||
name=value,
|
||||
what="IDNA" if idn_rewrite == "unicode" else "Unicode",
|
||||
dest="Unicode" if idn_rewrite == "unicode" else "IDNA",
|
||||
),
|
||||
reason=f'to transform {what} DNS name "{value}" to {dest}',
|
||||
)
|
||||
)
|
||||
# Since IDNA does not like '*' or empty labels (except one empty label at the end),
|
||||
@@ -450,16 +438,11 @@ def _adjust_idn(value, idn_rewrite):
|
||||
elif idn_rewrite == "unicode" and part.startswith("xn--"):
|
||||
parts[index] = part.encode("ascii").decode("idna")
|
||||
except Exception as exc2003:
|
||||
what = "IDNA" if idn_rewrite == "unicode" else "Unicode"
|
||||
dest = "Unicode" if idn_rewrite == "unicode" else "IDNA"
|
||||
raise OpenSSLObjectError(
|
||||
'Error while transforming part "{part}" of {what} DNS name "{name}" to {dest}.'
|
||||
' IDNA2008 transformation resulted in "{exc2008}", IDNA2003 transformation resulted in "{exc2003}".'.format(
|
||||
part=part,
|
||||
name=value,
|
||||
what="IDNA" if idn_rewrite == "unicode" else "Unicode",
|
||||
dest="Unicode" if idn_rewrite == "unicode" else "IDNA",
|
||||
exc2003=exc2003,
|
||||
exc2008=exc2008,
|
||||
)
|
||||
f'Error while transforming part "{part}" of {what} DNS name "{value}" to {dest}.'
|
||||
f' IDNA2008 transformation resulted in "{exc2008}", IDNA2003 transformation resulted in "{exc2003}".'
|
||||
)
|
||||
return ".".join(parts)
|
||||
|
||||
@@ -468,18 +451,18 @@ def _adjust_idn_email(value, idn_rewrite):
|
||||
idx = value.find("@")
|
||||
if idx < 0:
|
||||
return value
|
||||
return "{0}@{1}".format(value[:idx], _adjust_idn(value[idx + 1 :], idn_rewrite))
|
||||
return f"{value[:idx]}@{_adjust_idn(value[idx + 1:], idn_rewrite)}"
|
||||
|
||||
|
||||
def _adjust_idn_url(value, idn_rewrite):
|
||||
url = urlparse(value)
|
||||
host = _adjust_idn(url.hostname, idn_rewrite)
|
||||
if url.username is not None and url.password is not None:
|
||||
host = "{0}:{1}@{2}".format(url.username, url.password, host)
|
||||
host = f"{url.username}:{url.password}@{host}"
|
||||
elif url.username is not None:
|
||||
host = "{0}@{1}".format(url.username, host)
|
||||
host = f"{url.username}@{host}"
|
||||
if url.port is not None:
|
||||
host = "{0}:{1}".format(host, url.port)
|
||||
host = f"{host}:{url.port}"
|
||||
return urlunparse(
|
||||
ParseResult(
|
||||
scheme=url.scheme,
|
||||
@@ -514,9 +497,7 @@ def cryptography_get_name(name, what="Subject Alternative Name"):
|
||||
if name.startswith("RID:"):
|
||||
m = re.match(r"^([0-9]+(?:\.[0-9]+)*)$", to_text(name[4:]))
|
||||
if not m:
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse {what} "{name}"'.format(name=name, what=what)
|
||||
)
|
||||
raise OpenSSLObjectError(f'Cannot parse {what} "{name}"')
|
||||
return x509.RegisteredID(x509.oid.ObjectIdentifier(m.group(1)))
|
||||
if name.startswith("otherName:"):
|
||||
# otherName can either be a raw ASN.1 hex string or in the format that OpenSSL works with.
|
||||
@@ -534,9 +515,9 @@ def cryptography_get_name(name, what="Subject Alternative Name"):
|
||||
name = to_text(name[10:], errors="surrogate_or_strict")
|
||||
if ";" not in name:
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse {what} otherName "{name}", must be in the '
|
||||
f'Cannot parse {what} otherName "{name}", must be in the '
|
||||
'format "otherName:<OID>;<ASN.1 OpenSSL Encoded String>" or '
|
||||
'"otherName:<OID>;<hex string>"'.format(name=name, what=what)
|
||||
'"otherName:<OID>;<hex string>"'
|
||||
)
|
||||
|
||||
oid, value = name.split(";", 1)
|
||||
@@ -547,21 +528,13 @@ def cryptography_get_name(name, what="Subject Alternative Name"):
|
||||
x509.Name(reversed(_parse_dn(to_bytes(name[8:]))))
|
||||
)
|
||||
except Exception as e:
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse {what} "{name}": {error}'.format(
|
||||
name=name, what=what, error=e
|
||||
)
|
||||
)
|
||||
raise OpenSSLObjectError(f'Cannot parse {what} "{name}": {e}')
|
||||
if ":" not in name:
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse {what} "{name}" (forgot "DNS:" prefix?)'.format(
|
||||
name=name, what=what
|
||||
)
|
||||
f'Cannot parse {what} "{name}" (forgot "DNS:" prefix?)'
|
||||
)
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse {what} "{name}" (potentially unsupported by cryptography backend)'.format(
|
||||
name=name, what=what
|
||||
)
|
||||
f'Cannot parse {what} "{name}" (potentially unsupported by cryptography backend)'
|
||||
)
|
||||
|
||||
|
||||
@@ -571,12 +544,12 @@ def _dn_escape_value(value):
|
||||
"""
|
||||
value = value.replace("\\", "\\\\")
|
||||
for ch in [",", "+", "<", ">", ";", '"']:
|
||||
value = value.replace(ch, "\\%s" % ch)
|
||||
value = value.replace(ch, f"\\{ch}")
|
||||
value = value.replace("\0", "\\00")
|
||||
if value.startswith((" ", "#")):
|
||||
value = "\\%s" % value[0] + value[1:]
|
||||
value = f"\\{value[0]}{value[1:]}"
|
||||
if value.endswith(" "):
|
||||
value = value[:-1] + "\\ "
|
||||
value = f"{value[:-1]}\\ "
|
||||
return value
|
||||
|
||||
|
||||
@@ -590,36 +563,29 @@ def cryptography_decode_name(name, idn_rewrite="ignore"):
|
||||
'idn_rewrite must be one of "ignore", "idna", or "unicode"'
|
||||
)
|
||||
if isinstance(name, x509.DNSName):
|
||||
return "DNS:{0}".format(_adjust_idn(name.value, idn_rewrite))
|
||||
return f"DNS:{_adjust_idn(name.value, idn_rewrite)}"
|
||||
if isinstance(name, x509.IPAddress):
|
||||
if isinstance(name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
|
||||
return "IP:{0}/{1}".format(
|
||||
name.value.network_address.compressed, name.value.prefixlen
|
||||
)
|
||||
return "IP:{0}".format(name.value.compressed)
|
||||
return f"IP:{name.value.network_address.compressed}/{name.value.prefixlen}"
|
||||
return f"IP:{name.value.compressed}"
|
||||
if isinstance(name, x509.RFC822Name):
|
||||
return "email:{0}".format(_adjust_idn_email(name.value, idn_rewrite))
|
||||
return f"email:{_adjust_idn_email(name.value, idn_rewrite)}"
|
||||
if isinstance(name, x509.UniformResourceIdentifier):
|
||||
return "URI:{0}".format(_adjust_idn_url(name.value, idn_rewrite))
|
||||
return f"URI:{_adjust_idn_url(name.value, idn_rewrite)}"
|
||||
if isinstance(name, x509.DirectoryName):
|
||||
# According to https://datatracker.ietf.org/doc/html/rfc4514.html#section-2.1 the
|
||||
# list needs to be reversed, and joined by commas
|
||||
return "dirName:" + ",".join(
|
||||
[
|
||||
"{0}={1}".format(
|
||||
to_text(cryptography_oid_to_name(attribute.oid, short=True)),
|
||||
_dn_escape_value(attribute.value),
|
||||
)
|
||||
f"{to_text(cryptography_oid_to_name(attribute.oid, short=True))}={_dn_escape_value(attribute.value)}"
|
||||
for attribute in reversed(list(name.value))
|
||||
]
|
||||
)
|
||||
if isinstance(name, x509.RegisteredID):
|
||||
return "RID:{0}".format(name.value.dotted_string)
|
||||
return f"RID:{name.value.dotted_string}"
|
||||
if isinstance(name, x509.OtherName):
|
||||
return "otherName:{0};{1}".format(
|
||||
name.type_id.dotted_string, _get_hex(name.value)
|
||||
)
|
||||
raise OpenSSLObjectError('Cannot decode name "{0}"'.format(name))
|
||||
return f"otherName:{name.type_id.dotted_string};{_get_hex(name.value)}"
|
||||
raise OpenSSLObjectError(f'Cannot decode name "{name}"')
|
||||
|
||||
|
||||
def _cryptography_get_keyusage(usage):
|
||||
@@ -645,7 +611,7 @@ def _cryptography_get_keyusage(usage):
|
||||
return "encipher_only"
|
||||
if usage in ("Decipher Only", "decipherOnly"):
|
||||
return "decipher_only"
|
||||
raise OpenSSLObjectError('Unknown key usage "{0}"'.format(usage))
|
||||
raise OpenSSLObjectError(f'Unknown key usage "{usage}"')
|
||||
|
||||
|
||||
def cryptography_parse_key_usage_params(usages):
|
||||
@@ -685,9 +651,7 @@ def cryptography_get_basic_constraints(constraints):
|
||||
ca = False
|
||||
else:
|
||||
raise OpenSSLObjectError(
|
||||
'Unknown basic constraint value "{0}" for CA'.format(
|
||||
constraint[3:]
|
||||
)
|
||||
f'Unknown basic constraint value "{constraint[3:]}" for CA'
|
||||
)
|
||||
elif constraint.startswith("pathlen:"):
|
||||
v = constraint[len("pathlen:") :]
|
||||
@@ -695,12 +659,10 @@ def cryptography_get_basic_constraints(constraints):
|
||||
path_length = int(v)
|
||||
except Exception as e:
|
||||
raise OpenSSLObjectError(
|
||||
'Cannot parse path length constraint "{0}" ({1})'.format(v, e)
|
||||
f'Cannot parse path length constraint "{v}" ({e})'
|
||||
)
|
||||
else:
|
||||
raise OpenSSLObjectError(
|
||||
'Unknown basic constraint "{0}"'.format(constraint)
|
||||
)
|
||||
raise OpenSSLObjectError(f'Unknown basic constraint "{constraint}"')
|
||||
return ca, path_length
|
||||
|
||||
|
||||
@@ -958,7 +920,7 @@ def cryptography_verify_signature(signature, data, hash_algorithm, signer_public
|
||||
signer_public_key.verify(signature, data)
|
||||
return True
|
||||
raise OpenSSLObjectError(
|
||||
"Unsupported public key type {0}".format(type(signer_public_key))
|
||||
f"Unsupported public key type {type(signer_public_key)}"
|
||||
)
|
||||
except InvalidSignature:
|
||||
return False
|
||||
|
||||
@@ -162,9 +162,9 @@ else:
|
||||
def _convert_int_to_bytes(count, n):
|
||||
if n == 0 and count == 0:
|
||||
return ""
|
||||
h = "%x" % n
|
||||
h = f"{n:x}"
|
||||
if len(h) > 2 * count:
|
||||
raise Exception("Number {1} needs more than {0} bytes!".format(count, n))
|
||||
raise Exception(f"Number {n} needs more than {count} bytes!")
|
||||
return ("0" * (2 * count - len(h)) + h).decode("hex")
|
||||
|
||||
def _convert_bytes_to_int(data):
|
||||
@@ -174,7 +174,7 @@ else:
|
||||
return v
|
||||
|
||||
def _to_hex(no):
|
||||
return "%x" % no
|
||||
return f"{no:x}"
|
||||
|
||||
|
||||
def convert_int_to_bytes(no, count=None):
|
||||
|
||||
@@ -363,16 +363,14 @@ def select_backend(module, backend, provider):
|
||||
# Fail if no backend has been found
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
@@ -31,17 +31,17 @@ class AcmeCertificateBackend(CertificateBackend):
|
||||
)
|
||||
if self.csr_content is None and not os.path.exists(self.csr_path):
|
||||
raise CertificateError(
|
||||
"The certificate signing request file %s does not exist" % self.csr_path
|
||||
f"The certificate signing request file {self.csr_path} does not exist"
|
||||
)
|
||||
|
||||
if not os.path.exists(self.accountkey_path):
|
||||
raise CertificateError(
|
||||
"The account key %s does not exist" % self.accountkey_path
|
||||
f"The account key {self.accountkey_path} does not exist"
|
||||
)
|
||||
|
||||
if not os.path.exists(self.challenge_path):
|
||||
raise CertificateError(
|
||||
"The challenge path %s does not exist" % self.challenge_path
|
||||
f"The challenge path {self.challenge_path} does not exist"
|
||||
)
|
||||
|
||||
self.acme_tiny_path = self.module.get_bin_path("acme-tiny", required=True)
|
||||
@@ -66,7 +66,7 @@ class AcmeCertificateBackend(CertificateBackend):
|
||||
except Exception:
|
||||
pass
|
||||
self.module.fail_json(
|
||||
msg="failed to create temporary CSR file: %s" % to_native(err),
|
||||
msg=f"failed to create temporary CSR file: {to_native(err)}",
|
||||
exception=traceback.format_exc(),
|
||||
)
|
||||
f.close()
|
||||
|
||||
@@ -56,9 +56,7 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
)
|
||||
if self.csr_content is None and not os.path.exists(self.csr_path):
|
||||
raise CertificateError(
|
||||
"The certificate signing request file {0} does not exist".format(
|
||||
self.csr_path
|
||||
)
|
||||
f"The certificate signing request file {self.csr_path} does not exist"
|
||||
)
|
||||
|
||||
self._ensure_csr_loaded()
|
||||
@@ -77,7 +75,7 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
self.module.fail_json(
|
||||
msg=(
|
||||
"Entrust provider does not currently support multiple validated organizations. Multiple organizations found in "
|
||||
"Subject DN: '{0}'. ".format(self.csr.subject)
|
||||
f"Subject DN: '{self.csr.subject}'. "
|
||||
)
|
||||
)
|
||||
# If no organization in the CSR, explicitly tell ECS that it should be blank in issued cert, not defaulted to
|
||||
@@ -98,11 +96,7 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
],
|
||||
)
|
||||
except SessionConfigurationException as e:
|
||||
module.fail_json(
|
||||
msg="Failed to initialize Entrust Provider: {0}".format(
|
||||
to_native(e.message)
|
||||
)
|
||||
)
|
||||
module.fail_json(msg=f"Failed to initialize Entrust Provider: {e.message}")
|
||||
|
||||
def generate_certificate(self):
|
||||
"""(Re-)Generate certificate."""
|
||||
@@ -138,9 +132,7 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
self.trackingId = result.get("trackingId")
|
||||
except RestOperationException as e:
|
||||
self.module.fail_json(
|
||||
msg="Failed to request new certificate from Entrust Certificate Services (ECS): {0}".format(
|
||||
to_native(e.message)
|
||||
)
|
||||
msg=f"Failed to request new certificate from Entrust Certificate Services (ECS): {e.message}"
|
||||
)
|
||||
|
||||
self.cert_bytes = to_bytes(result.get("endEntityCert"))
|
||||
@@ -159,9 +151,7 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
cert_details = self._get_cert_details()
|
||||
except RestOperationException as e:
|
||||
self.module.fail_json(
|
||||
msg="Failed to get status of existing certificate from Entrust Certificate Services (ECS): {0}.".format(
|
||||
to_native(e.message)
|
||||
)
|
||||
msg=f"Failed to get status of existing certificate from Entrust Certificate Services (ECS): {e.message}."
|
||||
)
|
||||
|
||||
# Always issue a new certificate if the certificate is expired, suspended or revoked
|
||||
@@ -189,8 +179,8 @@ class EntrustCertificateBackend(CertificateBackend):
|
||||
serial_number = None
|
||||
expiry = None
|
||||
if self.backend == "cryptography":
|
||||
serial_number = "{0:X}".format(
|
||||
cryptography_serial_number_of_cert(self.existing_certificate)
|
||||
serial_number = (
|
||||
f"{cryptography_serial_number_of_cert(self.existing_certificate):X}"
|
||||
)
|
||||
expiry = get_not_valid_after(self.existing_certificate)
|
||||
|
||||
|
||||
@@ -332,11 +332,9 @@ class CertificateInfoRetrievalCryptography(CertificateInfoRetrieval):
|
||||
x509.BasicConstraints
|
||||
)
|
||||
result = []
|
||||
result.append(
|
||||
"CA:{0}".format("TRUE" if ext_keyusage_ext.value.ca else "FALSE")
|
||||
)
|
||||
result.append(f"CA:{'TRUE' if ext_keyusage_ext.value.ca else 'FALSE'}")
|
||||
if ext_keyusage_ext.value.path_length is not None:
|
||||
result.append("pathlen:{0}".format(ext_keyusage_ext.value.path_length))
|
||||
result.append(f"pathlen:{ext_keyusage_ext.value.path_length}")
|
||||
return sorted(result), ext_keyusage_ext.critical
|
||||
except cryptography.x509.ExtensionNotFound:
|
||||
return None, False
|
||||
@@ -474,20 +472,17 @@ def select_backend(module, backend, content):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect any of the required Python libraries "
|
||||
"cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect any of the required Python libraries cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return backend, CertificateInfoRetrievalCryptography(module, content)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
@@ -93,21 +93,17 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
|
||||
)
|
||||
if self.csr_content is None and not os.path.exists(self.csr_path):
|
||||
raise CertificateError(
|
||||
"The certificate signing request file {0} does not exist".format(
|
||||
self.csr_path
|
||||
)
|
||||
f"The certificate signing request file {self.csr_path} does not exist"
|
||||
)
|
||||
if self.ca_cert_content is None and not os.path.exists(self.ca_cert_path):
|
||||
raise CertificateError(
|
||||
"The CA certificate file {0} does not exist".format(self.ca_cert_path)
|
||||
f"The CA certificate file {self.ca_cert_path} does not exist"
|
||||
)
|
||||
if self.ca_privatekey_content is None and not os.path.exists(
|
||||
self.ca_privatekey_path
|
||||
):
|
||||
raise CertificateError(
|
||||
"The CA private key file {0} does not exist".format(
|
||||
self.ca_privatekey_path
|
||||
)
|
||||
f"The CA private key file {self.ca_privatekey_path} does not exist"
|
||||
)
|
||||
|
||||
self._ensure_csr_loaded()
|
||||
@@ -134,8 +130,7 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
|
||||
if cryptography_key_needs_digest_for_signing(self.ca_private_key):
|
||||
if self.digest is None:
|
||||
raise CertificateError(
|
||||
"The digest %s is not supported with the cryptography backend"
|
||||
% module.params["ownca_digest"]
|
||||
f"The digest {module.params['ownca_digest']} is not supported with the cryptography backend"
|
||||
)
|
||||
else:
|
||||
self.digest = None
|
||||
|
||||
@@ -67,13 +67,11 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
|
||||
|
||||
if self.csr_path is not None and not os.path.exists(self.csr_path):
|
||||
raise CertificateError(
|
||||
"The certificate signing request file {0} does not exist".format(
|
||||
self.csr_path
|
||||
)
|
||||
f"The certificate signing request file {self.csr_path} does not exist"
|
||||
)
|
||||
if self.privatekey_content is None and not os.path.exists(self.privatekey_path):
|
||||
raise CertificateError(
|
||||
"The private key file {0} does not exist".format(self.privatekey_path)
|
||||
f"The private key file {self.privatekey_path} does not exist"
|
||||
)
|
||||
|
||||
self._module = module
|
||||
@@ -90,9 +88,7 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
|
||||
digest = self.digest
|
||||
if digest is None:
|
||||
self.module.fail_json(
|
||||
msg='Unsupported digest "{0}"'.format(
|
||||
module.params["selfsigned_digest"]
|
||||
)
|
||||
msg=f'Unsupported digest "{module.params["selfsigned_digest"]}"'
|
||||
)
|
||||
try:
|
||||
self.csr = csr.sign(self.privatekey, digest, default_backend())
|
||||
@@ -109,8 +105,7 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
|
||||
if cryptography_key_needs_digest_for_signing(self.privatekey):
|
||||
if self.digest is None:
|
||||
raise CertificateError(
|
||||
"The digest %s is not supported with the cryptography backend"
|
||||
% module.params["selfsigned_digest"]
|
||||
f"The digest {module.params['selfsigned_digest']} is not supported with the cryptography backend"
|
||||
)
|
||||
else:
|
||||
self.digest = None
|
||||
|
||||
@@ -58,7 +58,7 @@ class CRLInfoRetrieval:
|
||||
else:
|
||||
self.crl = x509.load_der_x509_crl(self.content, default_backend())
|
||||
except ValueError as e:
|
||||
self.module.fail_json(msg="Error while decoding CRL: {0}".format(e))
|
||||
self.module.fail_json(msg=f"Error while decoding CRL: {e}")
|
||||
|
||||
result = {
|
||||
"changed": False,
|
||||
@@ -96,9 +96,7 @@ class CRLInfoRetrieval:
|
||||
def get_crl_info(module, content, list_revoked_certificates=True):
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
msg=missing_required_lib(f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ class CertificateSigningRequestBackend:
|
||||
if not self.subjectAltName and module.params["use_common_name_for_san"]:
|
||||
for sub in self.subject:
|
||||
if sub[0] in ("commonName", "CN"):
|
||||
self.subjectAltName = ["DNS:%s" % sub[1]]
|
||||
self.subjectAltName = [f"DNS:{sub[1]}"]
|
||||
self.using_common_name_for_san = True
|
||||
break
|
||||
|
||||
@@ -174,7 +174,7 @@ class CertificateSigningRequestBackend:
|
||||
)
|
||||
except Exception as e:
|
||||
raise CertificateSigningRequestError(
|
||||
"Cannot parse subject_key_identifier: {0}".format(e)
|
||||
f"Cannot parse subject_key_identifier: {e}"
|
||||
)
|
||||
|
||||
if self.authority_key_identifier is not None:
|
||||
@@ -184,7 +184,7 @@ class CertificateSigningRequestBackend:
|
||||
)
|
||||
except Exception as e:
|
||||
raise CertificateSigningRequestError(
|
||||
"Cannot parse authority_key_identifier: {0}".format(e)
|
||||
f"Cannot parse authority_key_identifier: {e}"
|
||||
)
|
||||
|
||||
self.existing_csr = None
|
||||
@@ -337,9 +337,7 @@ def parse_crl_distribution_points(module, crl_distribution_points):
|
||||
result.append(cryptography.x509.DistributionPoint(**params))
|
||||
except (OpenSSLObjectError, ValueError) as e:
|
||||
raise OpenSSLObjectError(
|
||||
"Error while parsing CRL distribution point #{index}: {error}".format(
|
||||
index=index, error=e
|
||||
)
|
||||
f"Error while parsing CRL distribution point #{index}: {e}"
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -446,9 +444,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
|
||||
critical=self.name_constraints_critical,
|
||||
)
|
||||
except TypeError as e:
|
||||
raise OpenSSLObjectError(
|
||||
"Error while parsing name constraint: {0}".format(e)
|
||||
)
|
||||
raise OpenSSLObjectError(f"Error while parsing name constraint: {e}")
|
||||
|
||||
if self.create_subject_key_identifier:
|
||||
csr = csr.add_extension(
|
||||
@@ -494,7 +490,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
|
||||
digest = select_message_digest(self.digest)
|
||||
if digest is None:
|
||||
raise CertificateSigningRequestError(
|
||||
'Unsupported digest "{0}"'.format(self.digest)
|
||||
f'Unsupported digest "{self.digest}"'
|
||||
)
|
||||
try:
|
||||
self.csr = csr.sign(self.privatekey, digest, self.cryptography_backend)
|
||||
@@ -518,7 +514,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
|
||||
# https://github.com/kjd/idna/commit/ebefacd3134d0f5da4745878620a6a1cba86d130
|
||||
# and then
|
||||
# https://github.com/kjd/idna/commit/ea03c7b5db7d2a99af082e0239da2b68aeea702a).
|
||||
msg = "Error while creating CSR: {0}\n".format(e)
|
||||
msg = f"Error while creating CSR: {e}\n"
|
||||
if self.using_common_name_for_san:
|
||||
self.module.fail_json(
|
||||
msg=msg
|
||||
@@ -813,23 +809,20 @@ def select_backend(module, backend):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect any of the required Python libraries "
|
||||
"cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect any of the required Python libraries cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return backend, CertificateSigningRequestCryptographyBackend(module)
|
||||
else:
|
||||
raise Exception("Unsupported value for backend: {0}".format(backend))
|
||||
raise Exception(f"Unsupported value for backend: {backend}")
|
||||
|
||||
|
||||
def get_csr_argument_spec():
|
||||
|
||||
@@ -258,9 +258,9 @@ class CSRInfoRetrievalCryptography(CSRInfoRetrieval):
|
||||
ext_keyusage_ext = self.csr.extensions.get_extension_for_class(
|
||||
x509.BasicConstraints
|
||||
)
|
||||
result = ["CA:{0}".format("TRUE" if ext_keyusage_ext.value.ca else "FALSE")]
|
||||
result = [f"CA:{'TRUE' if ext_keyusage_ext.value.ca else 'FALSE'}"]
|
||||
if ext_keyusage_ext.value.path_length is not None:
|
||||
result.append("pathlen:{0}".format(ext_keyusage_ext.value.path_length))
|
||||
result.append(f"pathlen:{ext_keyusage_ext.value.path_length}")
|
||||
return sorted(result), ext_keyusage_ext.critical
|
||||
except cryptography.x509.ExtensionNotFound:
|
||||
return None, False
|
||||
@@ -380,16 +380,14 @@ def select_backend(module, backend, content, validate_signature=True):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
@@ -397,4 +395,4 @@ def select_backend(module, backend, content, validate_signature=True):
|
||||
module, content, validate_signature=validate_signature
|
||||
)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
@@ -273,7 +273,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
|
||||
ecclass = cryptography.hazmat.primitives.asymmetric.ec.__dict__.get(ectype)
|
||||
if ecclass is None:
|
||||
self.module.fail_json(
|
||||
msg="Your cryptography version does not support {0}".format(ectype)
|
||||
msg=f"Your cryptography version does not support {ectype}"
|
||||
)
|
||||
return ecclass
|
||||
|
||||
@@ -385,9 +385,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
|
||||
if self.type == "ECC" and self.curve in self.curves:
|
||||
if self.curves[self.curve]["deprecated"]:
|
||||
self.module.warn(
|
||||
"Elliptic curves of type {0} should not be used for new keys!".format(
|
||||
self.curve
|
||||
)
|
||||
f"Elliptic curves of type {self.curve} should not be used for new keys!"
|
||||
)
|
||||
self.private_key = (
|
||||
cryptography.hazmat.primitives.asymmetric.ec.generate_private_key(
|
||||
@@ -397,9 +395,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
|
||||
)
|
||||
except cryptography.exceptions.UnsupportedAlgorithm:
|
||||
self.module.fail_json(
|
||||
msg="Cryptography backend does not support the algorithm required for {0}".format(
|
||||
self.type
|
||||
)
|
||||
msg=f"Cryptography backend does not support the algorithm required for {self.type}"
|
||||
)
|
||||
|
||||
def get_private_key_data(self):
|
||||
@@ -426,9 +422,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
|
||||
)
|
||||
except AttributeError:
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend does not support the selected output format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
msg=f'Cryptography backend does not support the selected output format "{self.format}"'
|
||||
)
|
||||
|
||||
# Select key encryption
|
||||
@@ -454,15 +448,11 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
|
||||
)
|
||||
except ValueError:
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
msg=f'Cryptography backend cannot serialize the private key in the required format "{self.format}"'
|
||||
)
|
||||
except Exception:
|
||||
self.module.fail_json(
|
||||
msg='Error while serializing the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
),
|
||||
msg=f'Error while serializing the private key in the required format "{self.format}"',
|
||||
exception=traceback.format_exc(),
|
||||
)
|
||||
|
||||
@@ -611,21 +601,19 @@ def select_backend(module, backend):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return backend, PrivateKeyCryptographyBackend(module)
|
||||
else:
|
||||
raise Exception("Unsupported value for backend: {0}".format(backend))
|
||||
raise Exception(f"Unsupported value for backend: {backend}")
|
||||
|
||||
|
||||
def get_privatekey_argument_spec():
|
||||
|
||||
@@ -161,9 +161,7 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
)
|
||||
except AttributeError:
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend does not support the selected output format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
msg=f'Cryptography backend does not support the selected output format "{self.format}"'
|
||||
)
|
||||
|
||||
# Select key encryption
|
||||
@@ -186,15 +184,11 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
)
|
||||
except ValueError:
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
msg=f'Cryptography backend cannot serialize the private key in the required format "{self.format}"'
|
||||
)
|
||||
except Exception:
|
||||
self.module.fail_json(
|
||||
msg='Error while serializing the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
),
|
||||
msg=f'Error while serializing the private key in the required format "{self.format}"',
|
||||
exception=traceback.format_exc(),
|
||||
)
|
||||
|
||||
@@ -285,9 +279,7 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
def select_backend(module):
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
msg=missing_required_lib(f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return PrivateKeyConvertCryptographyBackend(module)
|
||||
|
||||
@@ -173,7 +173,7 @@ def _is_cryptography_key_consistent(
|
||||
return False
|
||||
# For X25519 and X448, there's no test yet.
|
||||
if warn_func is not None:
|
||||
warn_func("Cannot determine consistency for key of type %s" % type(key))
|
||||
warn_func(f"Cannot determine consistency for key of type {type(key)}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -338,16 +338,14 @@ def select_backend(
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
@@ -359,4 +357,4 @@ def select_backend(
|
||||
check_consistency=check_consistency,
|
||||
)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
@@ -84,7 +84,7 @@ def _get_cryptography_public_key_info(key):
|
||||
key_public_data["y"] = public_numbers.y
|
||||
key_public_data["exponent_size"] = key.curve.key_size
|
||||
else:
|
||||
key_type = "unknown ({0})".format(type(key))
|
||||
key_type = f"unknown ({type(key)})"
|
||||
return key_type, key_public_data
|
||||
|
||||
|
||||
@@ -174,17 +174,14 @@ def select_backend(module, backend, content=None, key=None):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect any of the required Python libraries "
|
||||
"cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect any of the required Python libraries cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
@@ -192,4 +189,4 @@ def select_backend(module, backend, content=None, key=None):
|
||||
module, content=content, key=key
|
||||
)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
@@ -98,36 +98,24 @@ def _extract_type(line, start=PEM_START):
|
||||
def extract_pem(content, strict=False):
|
||||
lines = content.splitlines()
|
||||
if len(lines) < 3:
|
||||
raise ValueError(
|
||||
"PEM must have at least 3 lines, have only {count}".format(count=len(lines))
|
||||
)
|
||||
raise ValueError(f"PEM must have at least 3 lines, have only {len(lines)}")
|
||||
header_type = _extract_type(lines[0])
|
||||
if header_type is None:
|
||||
raise ValueError(
|
||||
"First line is not of format {start}...{end}: {line!r}".format(
|
||||
start=PEM_START, end=PEM_END, line=lines[0]
|
||||
)
|
||||
f"First line is not of format {PEM_START}...{PEM_END}: {lines[0]!r}"
|
||||
)
|
||||
footer_type = _extract_type(lines[-1], start=PEM_END_START)
|
||||
if strict:
|
||||
if header_type != footer_type:
|
||||
raise ValueError(
|
||||
"Header type ({header}) is different from footer type ({footer})".format(
|
||||
header=header_type, footer=footer_type
|
||||
)
|
||||
f"Header type ({header_type}) is different from footer type ({footer_type})"
|
||||
)
|
||||
for idx, line in enumerate(lines[1:-2]):
|
||||
if len(line) != 64:
|
||||
raise ValueError(
|
||||
"Line {idx} has length {len} instead of 64".format(
|
||||
idx=idx, len=len(line)
|
||||
)
|
||||
)
|
||||
raise ValueError(f"Line {idx} has length {len(line)} instead of 64")
|
||||
if not (0 < len(lines[-2]) <= 64):
|
||||
raise ValueError(
|
||||
"Last line has length {len}, should be in (0, 64]".format(
|
||||
len=len(lines[-2])
|
||||
)
|
||||
f"Last line has length {len(lines[-2])}, should be in (0, 64]"
|
||||
)
|
||||
content = lines[1:-1]
|
||||
return header_type, "".join(content)
|
||||
|
||||
@@ -179,7 +179,7 @@ def load_publickey(path=None, content=None, backend=None):
|
||||
content, backend=cryptography_backend()
|
||||
)
|
||||
except Exception as e:
|
||||
raise OpenSSLObjectError("Error while deserializing key: {0}".format(e))
|
||||
raise OpenSSLObjectError(f"Error while deserializing key: {e}")
|
||||
|
||||
|
||||
def load_certificate(
|
||||
@@ -209,9 +209,7 @@ def load_certificate(
|
||||
cert_content, cryptography_backend()
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise OpenSSLObjectError(
|
||||
"Cannot parse DER certificate: {0}".format(exc)
|
||||
)
|
||||
raise OpenSSLObjectError(f"Cannot parse DER certificate: {exc}")
|
||||
|
||||
|
||||
def load_certificate_request(path, content=None, backend="cryptography"):
|
||||
@@ -241,31 +239,30 @@ def parse_name_field(input_dict, name_field_name=None):
|
||||
for entry in value:
|
||||
if not isinstance(entry, six.string_types):
|
||||
raise TypeError(
|
||||
("Values %s must be strings" % error_str).format(
|
||||
f"Values {error_str} must be strings".format(
|
||||
key=key, name=name_field_name
|
||||
)
|
||||
)
|
||||
if not entry:
|
||||
raise ValueError(
|
||||
("Values for %s must not be empty strings" % error_str).format(
|
||||
key=key
|
||||
f"Values for {error_str} must not be empty strings".format(
|
||||
key=key, name=name_field_name
|
||||
)
|
||||
)
|
||||
result.append((key, entry))
|
||||
elif isinstance(value, six.string_types):
|
||||
if not value:
|
||||
raise ValueError(
|
||||
("Value for %s must not be an empty string" % error_str).format(
|
||||
key=key
|
||||
f"Value for {error_str} must not be an empty string".format(
|
||||
key=key, name=name_field_name
|
||||
)
|
||||
)
|
||||
result.append((key, value))
|
||||
else:
|
||||
raise TypeError(
|
||||
(
|
||||
"Value for %s must be either a string or a list of strings"
|
||||
% error_str
|
||||
).format(key=key)
|
||||
f"Value for {error_str} must be either a string or a list of strings"
|
||||
).format(key=key, name=name_field_name)
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -277,17 +274,13 @@ def parse_ordered_name_field(input_list, name_field_name):
|
||||
for index, entry in enumerate(input_list):
|
||||
if len(entry) != 1:
|
||||
raise ValueError(
|
||||
"Entry #{index} in {name} must be a dictionary with exactly one key-value pair".format(
|
||||
name=name_field_name, index=index + 1
|
||||
)
|
||||
f"Entry #{index + 1} in {name_field_name} must be a dictionary with exactly one key-value pair"
|
||||
)
|
||||
try:
|
||||
result.extend(parse_name_field(entry, name_field_name=name_field_name))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(
|
||||
"Error while processing entry #{index} in {name}: {error}".format(
|
||||
name=name_field_name, index=index + 1, error=exc
|
||||
)
|
||||
f"Error while processing entry #{index + 1} in {name_field_name}: {exc}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
Reference in New Issue
Block a user