mirror of
https://github.com/ansible-collections/community.crypto.git
synced 2026-05-07 13:53:06 +00:00
Reformat everything with black.
I had to undo the u string prefix removals to not drop Python 2 compatibility. That's why black isn't enabled in antsibull-nox.toml yet.
This commit is contained in:
@@ -41,13 +41,14 @@ from ansible_collections.community.crypto.plugins.module_utils.version import (
|
||||
)
|
||||
|
||||
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION = '1.6'
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION = "1.6"
|
||||
|
||||
CRYPTOGRAPHY_IMP_ERR = None
|
||||
CRYPTOGRAPHY_VERSION = None
|
||||
try:
|
||||
import cryptography
|
||||
from cryptography import x509
|
||||
|
||||
CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
|
||||
except ImportError:
|
||||
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
|
||||
@@ -66,21 +67,21 @@ class CertificateBackend(object):
|
||||
self.module = module
|
||||
self.backend = backend
|
||||
|
||||
self.force = module.params['force']
|
||||
self.ignore_timestamps = module.params['ignore_timestamps']
|
||||
self.privatekey_path = module.params['privatekey_path']
|
||||
self.privatekey_content = module.params['privatekey_content']
|
||||
self.force = module.params["force"]
|
||||
self.ignore_timestamps = module.params["ignore_timestamps"]
|
||||
self.privatekey_path = module.params["privatekey_path"]
|
||||
self.privatekey_content = module.params["privatekey_content"]
|
||||
if self.privatekey_content is not None:
|
||||
self.privatekey_content = self.privatekey_content.encode('utf-8')
|
||||
self.privatekey_passphrase = module.params['privatekey_passphrase']
|
||||
self.csr_path = module.params['csr_path']
|
||||
self.csr_content = module.params['csr_content']
|
||||
self.privatekey_content = self.privatekey_content.encode("utf-8")
|
||||
self.privatekey_passphrase = module.params["privatekey_passphrase"]
|
||||
self.csr_path = module.params["csr_path"]
|
||||
self.csr_content = module.params["csr_content"]
|
||||
if self.csr_content is not None:
|
||||
self.csr_content = self.csr_content.encode('utf-8')
|
||||
self.csr_content = self.csr_content.encode("utf-8")
|
||||
|
||||
# The following are default values which make sure check() works as
|
||||
# before if providers do not explicitly change these properties.
|
||||
self.create_subject_key_identifier = 'never_create'
|
||||
self.create_subject_key_identifier = "never_create"
|
||||
self.create_authority_key_identifier = False
|
||||
|
||||
self.privatekey = None
|
||||
@@ -99,8 +100,10 @@ class CertificateBackend(object):
|
||||
if data is None:
|
||||
return dict()
|
||||
try:
|
||||
result = get_certificate_info(self.module, self.backend, data, prefer_one_fingerprint=True)
|
||||
result['can_parse_certificate'] = True
|
||||
result = get_certificate_info(
|
||||
self.module, self.backend, data, prefer_one_fingerprint=True
|
||||
)
|
||||
result["can_parse_certificate"] = True
|
||||
return result
|
||||
except Exception:
|
||||
return dict(can_parse_certificate=False)
|
||||
@@ -118,7 +121,9 @@ class CertificateBackend(object):
|
||||
def set_existing(self, certificate_bytes):
|
||||
"""Set existing certificate bytes. None indicates that the key does not exist."""
|
||||
self.existing_certificate_bytes = certificate_bytes
|
||||
self.diff_after = self.diff_before = self._get_info(self.existing_certificate_bytes)
|
||||
self.diff_after = self.diff_before = self._get_info(
|
||||
self.existing_certificate_bytes
|
||||
)
|
||||
|
||||
def has_existing(self):
|
||||
"""Query whether an existing certificate is/has been there."""
|
||||
@@ -166,33 +171,60 @@ class CertificateBackend(object):
|
||||
|
||||
def _check_privatekey(self):
|
||||
"""Check whether provided parameters match, assuming self.existing_certificate and self.privatekey have been populated."""
|
||||
if self.backend == 'cryptography':
|
||||
return cryptography_compare_public_keys(self.existing_certificate.public_key(), self.privatekey.public_key())
|
||||
if self.backend == "cryptography":
|
||||
return cryptography_compare_public_keys(
|
||||
self.existing_certificate.public_key(), self.privatekey.public_key()
|
||||
)
|
||||
|
||||
def _check_csr(self):
|
||||
"""Check whether provided parameters match, assuming self.existing_certificate and self.csr have been populated."""
|
||||
if self.backend == 'cryptography':
|
||||
if self.backend == "cryptography":
|
||||
# Verify that CSR is signed by certificate's private key
|
||||
if not self.csr.is_signature_valid:
|
||||
return False
|
||||
if not cryptography_compare_public_keys(self.csr.public_key(), self.existing_certificate.public_key()):
|
||||
if not cryptography_compare_public_keys(
|
||||
self.csr.public_key(), self.existing_certificate.public_key()
|
||||
):
|
||||
return False
|
||||
# Check subject
|
||||
if self.check_csr_subject and self.csr.subject != self.existing_certificate.subject:
|
||||
if (
|
||||
self.check_csr_subject
|
||||
and self.csr.subject != self.existing_certificate.subject
|
||||
):
|
||||
return False
|
||||
# Check extensions
|
||||
if not self.check_csr_extensions:
|
||||
return True
|
||||
cert_exts = list(self.existing_certificate.extensions)
|
||||
csr_exts = list(self.csr.extensions)
|
||||
if self.create_subject_key_identifier != 'never_create':
|
||||
if self.create_subject_key_identifier != "never_create":
|
||||
# Filter out SubjectKeyIdentifier extension before comparison
|
||||
cert_exts = list(filter(lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier), cert_exts))
|
||||
csr_exts = list(filter(lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier), csr_exts))
|
||||
cert_exts = list(
|
||||
filter(
|
||||
lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier),
|
||||
cert_exts,
|
||||
)
|
||||
)
|
||||
csr_exts = list(
|
||||
filter(
|
||||
lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier),
|
||||
csr_exts,
|
||||
)
|
||||
)
|
||||
if self.create_authority_key_identifier:
|
||||
# Filter out AuthorityKeyIdentifier extension before comparison
|
||||
cert_exts = list(filter(lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier), cert_exts))
|
||||
csr_exts = list(filter(lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier), csr_exts))
|
||||
cert_exts = list(
|
||||
filter(
|
||||
lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier),
|
||||
cert_exts,
|
||||
)
|
||||
)
|
||||
csr_exts = list(
|
||||
filter(
|
||||
lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier),
|
||||
csr_exts,
|
||||
)
|
||||
)
|
||||
if len(cert_exts) != len(csr_exts):
|
||||
return False
|
||||
for cert_ext in cert_exts:
|
||||
@@ -208,19 +240,28 @@ class CertificateBackend(object):
|
||||
"""Check whether Subject Key Identifier matches, assuming self.existing_certificate has been populated."""
|
||||
# Get hold of certificate's SKI
|
||||
try:
|
||||
ext = self.existing_certificate.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
|
||||
ext = self.existing_certificate.extensions.get_extension_for_class(
|
||||
x509.SubjectKeyIdentifier
|
||||
)
|
||||
except cryptography.x509.ExtensionNotFound:
|
||||
return False
|
||||
# Get hold of CSR's SKI for 'create_if_not_provided'
|
||||
csr_ext = None
|
||||
if self.create_subject_key_identifier == 'create_if_not_provided':
|
||||
if self.create_subject_key_identifier == "create_if_not_provided":
|
||||
try:
|
||||
csr_ext = self.csr.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
|
||||
csr_ext = self.csr.extensions.get_extension_for_class(
|
||||
x509.SubjectKeyIdentifier
|
||||
)
|
||||
except cryptography.x509.ExtensionNotFound:
|
||||
pass
|
||||
if csr_ext is None:
|
||||
# If CSR had no SKI, or we chose to ignore it ('always_create'), compare with created SKI
|
||||
if ext.value.digest != x509.SubjectKeyIdentifier.from_public_key(self.existing_certificate.public_key()).digest:
|
||||
if (
|
||||
ext.value.digest
|
||||
!= x509.SubjectKeyIdentifier.from_public_key(
|
||||
self.existing_certificate.public_key()
|
||||
).digest
|
||||
):
|
||||
return False
|
||||
else:
|
||||
# If CSR had SKI and we did not ignore it ('create_if_not_provided'), compare SKIs
|
||||
@@ -249,7 +290,10 @@ class CertificateBackend(object):
|
||||
return True
|
||||
|
||||
# Check SubjectKeyIdentifier
|
||||
if self.create_subject_key_identifier != 'never_create' and not self._check_subject_key_identifier():
|
||||
if (
|
||||
self.create_subject_key_identifier != "never_create"
|
||||
and not self._check_subject_key_identifier()
|
||||
):
|
||||
return True
|
||||
|
||||
# Check not before
|
||||
@@ -265,10 +309,7 @@ class CertificateBackend(object):
|
||||
|
||||
def dump(self, include_certificate):
|
||||
"""Serialize the object into a dictionary."""
|
||||
result = {
|
||||
'privatekey': self.privatekey_path,
|
||||
'csr': self.csr_path
|
||||
}
|
||||
result = {"privatekey": self.privatekey_path, "csr": self.csr_path}
|
||||
# Get hold of certificate bytes
|
||||
certificate_bytes = self.existing_certificate_bytes
|
||||
if self.cert is not None:
|
||||
@@ -276,9 +317,11 @@ class CertificateBackend(object):
|
||||
self.diff_after = self._get_info(certificate_bytes)
|
||||
if include_certificate:
|
||||
# Store result
|
||||
result['certificate'] = certificate_bytes.decode('utf-8') if certificate_bytes else None
|
||||
result["certificate"] = (
|
||||
certificate_bytes.decode("utf-8") if certificate_bytes else None
|
||||
)
|
||||
|
||||
result['diff'] = dict(
|
||||
result["diff"] = dict(
|
||||
before=self.diff_before,
|
||||
after=self.diff_after,
|
||||
)
|
||||
@@ -311,26 +354,38 @@ def select_backend(module, backend, provider):
|
||||
"""
|
||||
provider.validate_module_args(module)
|
||||
|
||||
backend = module.params['select_crypto_backend']
|
||||
if backend == 'auto':
|
||||
backend = module.params["select_crypto_backend"]
|
||||
if backend == "auto":
|
||||
# Detect what backend we can use
|
||||
can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
can_use_cryptography = (
|
||||
CRYPTOGRAPHY_FOUND
|
||||
and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
)
|
||||
|
||||
# If cryptography is available we'll use it
|
||||
if can_use_cryptography:
|
||||
backend = 'cryptography'
|
||||
backend = "cryptography"
|
||||
|
||||
# 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))
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
)
|
||||
|
||||
if backend == 'cryptography':
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(msg=missing_required_lib('cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION)),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR)
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
if provider.needs_version_two_certs(module):
|
||||
module.fail_json(msg='The cryptography backend does not support v2 certificates')
|
||||
module.fail_json(
|
||||
msg="The cryptography backend does not support v2 certificates"
|
||||
)
|
||||
|
||||
return provider.create_backend(module, backend)
|
||||
|
||||
@@ -338,20 +393,26 @@ def select_backend(module, backend, provider):
|
||||
def get_certificate_argument_spec():
|
||||
return ArgumentSpec(
|
||||
argument_spec=dict(
|
||||
provider=dict(type='str', choices=[]), # choices will be filled by add_XXX_provider_to_argument_spec() in certificate_xxx.py
|
||||
force=dict(type='bool', default=False,),
|
||||
csr_path=dict(type='path'),
|
||||
csr_content=dict(type='str'),
|
||||
ignore_timestamps=dict(type='bool', default=True),
|
||||
select_crypto_backend=dict(type='str', default='auto', choices=['auto', 'cryptography']),
|
||||
|
||||
provider=dict(
|
||||
type="str", choices=[]
|
||||
), # choices will be filled by add_XXX_provider_to_argument_spec() in certificate_xxx.py
|
||||
force=dict(
|
||||
type="bool",
|
||||
default=False,
|
||||
),
|
||||
csr_path=dict(type="path"),
|
||||
csr_content=dict(type="str"),
|
||||
ignore_timestamps=dict(type="bool", default=True),
|
||||
select_crypto_backend=dict(
|
||||
type="str", default="auto", choices=["auto", "cryptography"]
|
||||
),
|
||||
# General properties of a certificate
|
||||
privatekey_path=dict(type='path'),
|
||||
privatekey_content=dict(type='str', no_log=True),
|
||||
privatekey_passphrase=dict(type='str', no_log=True),
|
||||
privatekey_path=dict(type="path"),
|
||||
privatekey_content=dict(type="str", no_log=True),
|
||||
privatekey_passphrase=dict(type="str", no_log=True),
|
||||
),
|
||||
mutually_exclusive=[
|
||||
['csr_path', 'csr_content'],
|
||||
['privatekey_path', 'privatekey_content'],
|
||||
["csr_path", "csr_content"],
|
||||
["privatekey_path", "privatekey_content"],
|
||||
],
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user