Ensure that *everything* is typed in community.crypto (#917)

* Ensure that *everything* is typed in community.crypto.

* Fix comment.

* Ignore type definitions/imports and AssertionErrors for code coverage.
This commit is contained in:
Felix Fontein
2025-06-09 10:10:19 +02:00
committed by GitHub
parent ec063d8515
commit d83a923325
73 changed files with 494 additions and 317 deletions

View File

@@ -21,13 +21,13 @@ from ansible_collections.community.crypto.plugins.plugin_utils._action_module im
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._argspec import (
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( # pragma: no cover
ArgumentSpec,
)
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import (
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import ( # pragma: no cover
PrivateKeyBackend,
)
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)

View File

@@ -58,10 +58,14 @@ from ansible_collections.community.crypto.plugins.plugin_utils._gnupg import (
class LookupModule(LookupBase):
def run(self, terms: list[t.Any], variables=None, **kwargs) -> list[str]:
def run(
self, terms: list[t.Any], variables: None = None, **kwargs: t.Any
) -> list[str]:
self.set_options(direct=kwargs)
if self._loader is None:
raise AssertionError("Contract violation: self._loader is None")
raise AssertionError(
"Contract violation: self._loader is None"
) # pragma: no cover
try:
gpg = PluginGPGRunner(cwd=self._loader.get_basedir())

View File

@@ -18,7 +18,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.errors impo
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
ACMEClient,
)

View File

@@ -49,13 +49,15 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
import os
import http.client # pragma: no cover
import os # pragma: no cover
import urllib.error # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.account import ( # pragma: no cover
ACMEAccount,
)
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
CertificateInformation,
CryptoBackend,
)
@@ -68,7 +70,11 @@ RETRY_COUNT = 10
def _decode_retry(
*, module: AnsibleModule, response: t.Any, info: dict[str, t.Any], retry_count: int
*,
module: AnsibleModule,
response: urllib.error.HTTPError | http.client.HTTPResponse | None,
info: dict[str, t.Any],
retry_count: int,
) -> bool:
if info["status"] not in RETRY_STATUS_CODES:
return False
@@ -102,7 +108,7 @@ def _decode_retry(
def _assert_fetch_url_success(
*,
module: AnsibleModule,
response: t.Any,
response: urllib.error.HTTPError | http.client.HTTPResponse | None,
info: dict[str, t.Any],
allow_redirect: bool = False,
allow_client_error: bool = True,
@@ -288,7 +294,9 @@ class ACMEClient:
In case of an error, raises KeyParsingError.
"""
if key_file is None and key_content is None:
raise AssertionError("One of key_file and key_content must be specified!")
raise AssertionError(
"One of key_file and key_content must be specified!"
) # pragma: no cover
return self.backend.parse_key(
key_file=key_file, key_content=key_content, passphrase=passphrase
)

View File

@@ -80,10 +80,10 @@ else:
)
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
CertificateChain,
Criterium,
)

View File

@@ -39,8 +39,8 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
Criterium,
)

View File

@@ -31,10 +31,10 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
import os
import os # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
ChainMatcher,
Criterium,
)
@@ -132,12 +132,24 @@ class CryptoBackend(metaclass=abc.ABCMeta):
start + percentage * (end - start), with_timezone=self._with_timezone
)
def get_utc_datetime(self, *args, **kwargs) -> datetime.datetime:
kwargs_ext: dict[str, t.Any] = dict(kwargs)
if self._with_timezone and ("tzinfo" not in kwargs_ext and len(args) < 8):
kwargs_ext["tzinfo"] = UTC
result = datetime.datetime(*args, **kwargs_ext)
if self._with_timezone and ("tzinfo" in kwargs or len(args) >= 8):
def get_utc_datetime(
self,
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tzinfo: datetime.timezone | None = None,
) -> datetime.datetime:
has_tzinfo = tzinfo is not None
if self._with_timezone and not has_tzinfo:
tzinfo = UTC
result = datetime.datetime(
year, month, day, hour, minute, second, microsecond, tzinfo
)
if self._with_timezone and has_tzinfo:
result = ensure_utc_timezone(result)
return result

View File

@@ -37,14 +37,14 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.utils impor
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
CryptoBackend,
)
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
ChainMatcher,
)
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import (
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( # pragma: no cover
Challenge,
)

View File

@@ -24,7 +24,7 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.pem impor
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
ACMEClient,
)

View File

@@ -28,8 +28,8 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.utils impor
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
ACMEClient,
)

View File

@@ -15,7 +15,10 @@ from ansible.module_utils.common.text.converters import to_text
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
import http.client # pragma: no cover
import urllib.error # pragma: no cover
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
def format_http_status(status_code: int) -> str:
@@ -59,7 +62,7 @@ class ModuleFailException(Exception):
self.msg = msg
self.module_fail_args = args
def do_fail(self, *, module: AnsibleModule, **arguments) -> t.NoReturn:
def do_fail(self, *, module: AnsibleModule, **arguments: t.Any) -> t.NoReturn:
module.fail_json(msg=self.msg, other=self.module_fail_args, **arguments)
@@ -70,11 +73,11 @@ class ACMEProtocolException(ModuleFailException):
module: AnsibleModule,
msg: str | None = None,
info: dict[str, t.Any] | None = None,
response=None,
response: urllib.error.HTTPError | http.client.HTTPResponse | None = None,
content: bytes | None = None,
content_json: object | bytes | None = None,
extras: dict[str, t.Any] | None = None,
):
) -> None:
# Try to get hold of content, if response is given and content is not provided
if content is None and content_json is None and response is not None:
try:

View File

@@ -21,7 +21,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.errors impo
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
def read_file(fn: str | os.PathLike) -> bytes:

View File

@@ -25,7 +25,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.utils impor
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
ACMEClient,
)

View File

@@ -29,7 +29,7 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
CertificateInformation,
CryptoBackend,
)

View File

@@ -45,7 +45,7 @@ class ArgumentSpec:
self.required_if = _ensure_list(required_if)
self.required_by = required_by or {}
def update_argspec(self, **kwargs) -> t.Self:
def update_argspec(self, **kwargs: t.Any) -> t.Self:
self.argument_spec.update(kwargs)
return self
@@ -63,7 +63,7 @@ class ArgumentSpec:
| None
) = None,
required_by: dict[str, tuple[str, ...] | list[str]] | None = None,
):
) -> t.Self:
if mutually_exclusive:
self.mutually_exclusive.extend(mutually_exclusive)
if required_together:

View File

@@ -31,13 +31,15 @@
from __future__ import annotations
import typing as t
# WARNING: this function no longer works with cryptography 35.0.0 and newer!
# It must **ONLY** be used in compatibility code for older
# cryptography versions!
def obj2txt(openssl_lib, openssl_ffi, obj) -> str:
def obj2txt(openssl_lib: t.Any, openssl_ffi: t.Any, obj: t.Any) -> str:
# Set to 80 on the recommendation of
# https://www.openssl.org/docs/crypto/OBJ_nid2ln.html#return_values
#

View File

@@ -19,7 +19,7 @@ NORMALIZE_NAMES_SHORT: dict[str, str] = {}
for dotted, names in OID_MAP.items():
for name in names:
if name in NORMALIZE_NAMES and OID_LOOKUP[name] != dotted:
raise AssertionError(
raise AssertionError( # pragma: no cover
f'Name collision during setup: "{name}" for OIDs {dotted} and {OID_LOOKUP[name]}'
)
NORMALIZE_NAMES[name] = names[0]
@@ -27,7 +27,7 @@ for dotted, names in OID_MAP.items():
OID_LOOKUP[name] = dotted
for alias, original in [("userID", "userId")]:
if alias in NORMALIZE_NAMES:
raise AssertionError(
raise AssertionError( # pragma: no cover
f'Name collision during adding aliases: "{alias}" (alias for "{original}") is already mapped to OID {OID_LOOKUP[alias]}'
)
NORMALIZE_NAMES[alias] = original

View File

@@ -34,7 +34,7 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptogra
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
# TODO: once cryptography has a _utc variant of InvalidityDate.invalidity_date, set this

View File

@@ -86,30 +86,33 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.basic imp
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.dh import DHPrivateKey, DHPublicKey
from cryptography.hazmat.primitives.asymmetric.dsa import (
from cryptography.hazmat.primitives import hashes # pragma: no cover
from cryptography.hazmat.primitives.asymmetric.dh import ( # pragma: no cover
DHPrivateKey,
DHPublicKey,
)
from cryptography.hazmat.primitives.asymmetric.dsa import ( # pragma: no cover
DSAPrivateKey,
DSAPublicKey,
)
from cryptography.hazmat.primitives.asymmetric.ec import (
from cryptography.hazmat.primitives.asymmetric.ec import ( # pragma: no cover
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from cryptography.hazmat.primitives.asymmetric.rsa import (
from cryptography.hazmat.primitives.asymmetric.rsa import ( # pragma: no cover
RSAPrivateKey,
RSAPublicKey,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
CertificateIssuerPublicKeyTypes,
CertificatePublicKeyTypes,
PrivateKeyTypes,
PublicKeyTypes,
)
from cryptography.hazmat.primitives.serialization.pkcs12 import (
from cryptography.hazmat.primitives.serialization.pkcs12 import ( # pragma: no cover
PKCS12KeyAndCertificates,
)
@@ -117,13 +120,13 @@ if t.TYPE_CHECKING:
CertificateIssuerPrivateKeyTypes,
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey,
]
] # pragma: no cover
PublicKeyTypesWOEdwards = t.Union[ # pylint: disable=invalid-name
DHPublicKey, DSAPublicKey, EllipticCurvePublicKey, RSAPublicKey
]
] # pragma: no cover
PrivateKeyTypesWOEdwards = t.Union[ # pylint: disable=invalid-name
DHPrivateKey, DSAPrivateKey, EllipticCurvePrivateKey, RSAPrivateKey
]
] # pragma: no cover
else:
PublicKeyTypesWOEdwards = None # pylint: disable=invalid-name
PrivateKeyTypesWOEdwards = None # pylint: disable=invalid-name
@@ -602,7 +605,7 @@ def cryptography_decode_name(
Raises an OpenSSLObjectError if the name is not supported.
"""
if idn_rewrite not in ("ignore", "idna", "unicode"):
raise AssertionError(
raise AssertionError( # pragma: no cover
'idn_rewrite must be one of "ignore", "idna", or "unicode"'
)
if isinstance(name, x509.DNSName):

View File

@@ -38,13 +38,13 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
CertificatePrivateKeyTypes,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
)
@@ -170,11 +170,11 @@ class CertificateBackend(metaclass=abc.ABCMeta):
def _check_privatekey(self) -> bool:
"""Check whether provided parameters match, assuming self.existing_certificate and self.privatekey have been populated."""
if self.existing_certificate is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"Contract violation: existing_certificate has not been populated"
)
if self.privatekey is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"Contract violation: privatekey has not been populated"
)
return cryptography_compare_public_keys(
@@ -184,11 +184,13 @@ class CertificateBackend(metaclass=abc.ABCMeta):
def _check_csr(self) -> bool:
"""Check whether provided parameters match, assuming self.existing_certificate and self.csr have been populated."""
if self.existing_certificate is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"Contract violation: existing_certificate has not been populated"
)
if self.csr is None:
raise AssertionError("Contract violation: csr has not been populated")
raise AssertionError(
"Contract violation: csr has not been populated"
) # pragma: no cover
# Verify that CSR is signed by certificate's private key
if not self.csr.is_signature_valid:
return False
@@ -249,11 +251,13 @@ class CertificateBackend(metaclass=abc.ABCMeta):
def _check_subject_key_identifier(self) -> bool:
"""Check whether Subject Key Identifier matches, assuming self.existing_certificate and self.csr have been populated."""
if self.existing_certificate is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"Contract violation: existing_certificate has not been populated"
)
if self.csr is None:
raise AssertionError("Contract violation: csr has not been populated")
raise AssertionError(
"Contract violation: csr has not been populated"
) # pragma: no cover
# Get hold of certificate's SKI
try:
ext = self.existing_certificate.extensions.get_extension_for_class(

View File

@@ -22,8 +22,8 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.module_ba
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._argspec import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( # pragma: no cover
ArgumentSpec,
)
@@ -100,7 +100,9 @@ class AcmeCertificateBackend(CertificateBackend):
def get_certificate_data(self) -> bytes:
"""Return bytes for self.cert."""
if self.cert_bytes is None:
raise AssertionError("Contract violation: cert_bytes is None")
raise AssertionError(
"Contract violation: cert_bytes is None"
) # pragma: no cover
return self.cert_bytes
def dump(self, *, include_certificate: bool) -> dict[str, t.Any]:

View File

@@ -38,21 +38,25 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._argspec import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( # pragma: no cover
ArgumentSpec,
)
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes
from cryptography.hazmat.primitives.asymmetric.types import (
PublicKeyTypes, # pragma: no cover
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION

View File

@@ -42,13 +42,13 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._argspec import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( # pragma: no cover
ArgumentSpec,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
)
@@ -157,7 +157,9 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
def generate_certificate(self) -> None:
"""(Re-)Generate certificate."""
if self.csr is None:
raise AssertionError("Contract violation: csr has not been populated")
raise AssertionError(
"Contract violation: csr has not been populated"
) # pragma: no cover
cert_builder = x509.CertificateBuilder()
cert_builder = cert_builder.subject_name(self.csr.subject)
cert_builder = cert_builder.issuer_name(self.ca_cert.subject)
@@ -214,7 +216,9 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
def get_certificate_data(self) -> bytes:
"""Return bytes for self.cert."""
if self.cert is None:
raise AssertionError("Contract violation: cert has not been populated")
raise AssertionError(
"Contract violation: cert has not been populated"
) # pragma: no cover
return self.cert.public_bytes(Encoding.PEM)
def needs_regeneration(

View File

@@ -36,13 +36,13 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._argspec import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( # pragma: no cover
ArgumentSpec,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
)
@@ -114,9 +114,11 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
def generate_certificate(self) -> None:
"""(Re-)Generate certificate."""
if self.csr is None:
raise AssertionError("Contract violation: csr has not been populated")
if self.privatekey is None:
raise AssertionError(
"Contract violation: csr has not been populated"
) # pragma: no cover
if self.privatekey is None:
raise AssertionError( # pragma: no cover
"Contract violation: privatekey has not been populated"
)
try:
@@ -156,7 +158,9 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
def get_certificate_data(self) -> bytes:
"""Return bytes for self.cert."""
if self.cert is None:
raise AssertionError("Contract violation: cert has not been populated")
raise AssertionError(
"Contract violation: cert has not been populated"
) # pragma: no cover
return self.cert.public_bytes(Encoding.PEM)
def needs_regeneration(

View File

@@ -28,18 +28,20 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PrivateKeyTypes,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
# crypto_utils

View File

@@ -48,16 +48,16 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
CertificatePrivateKeyTypes,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
PrivateKeyTypes,
)
_ET = t.TypeVar("_ET", bound="cryptography.x509.ExtensionType")
_ET = t.TypeVar("_ET", bound="cryptography.x509.ExtensionType") # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
@@ -453,7 +453,9 @@ class CertificateSigningRequestBackend:
def get_csr_data(self) -> bytes:
"""Return bytes for self.csr."""
if self.csr is None:
raise AssertionError("Violated contract: csr is not populated")
raise AssertionError(
"Violated contract: csr is not populated"
) # pragma: no cover
return self.csr.public_bytes(
cryptography.hazmat.primitives.serialization.Encoding.PEM
)
@@ -485,9 +487,13 @@ class CertificateSigningRequestBackend:
def _check_csr(self) -> bool:
"""Check whether provided parameters, assuming self.existing_csr and self.privatekey have been populated."""
if self.existing_csr is None:
raise AssertionError("Violated contract: existing_csr is not populated")
raise AssertionError(
"Violated contract: existing_csr is not populated"
) # pragma: no cover
if self.privatekey is None:
raise AssertionError("Violated contract: privatekey is not populated")
raise AssertionError(
"Violated contract: privatekey is not populated"
) # pragma: no cover
def _check_subject(csr: cryptography.x509.CertificateSigningRequest) -> bool:
subject = [

View File

@@ -31,19 +31,21 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificatePublicKeyTypes,
PrivateKeyTypes,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION

View File

@@ -37,15 +37,17 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PrivateKeyTypes,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule
] # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
@@ -267,7 +269,7 @@ class PrivateKeyBackend:
def get_private_key_data(self) -> bytes:
"""Return bytes for self.private_key"""
if self.private_key is None:
raise AssertionError("private_key not set")
raise AssertionError("private_key not set") # pragma: no cover
# Select export format and encoding
try:
export_format_txt = self._get_wanted_format()
@@ -341,7 +343,9 @@ class PrivateKeyBackend:
def _load_privatekey(self) -> PrivateKeyTypes:
data = self.existing_private_key_bytes
if data is None:
raise AssertionError("existing_private_key_bytes not set")
raise AssertionError(
"existing_private_key_bytes not set"
) # pragma: no cover
try:
# Interpret bytes depending on format.
key_format = identify_private_key_format(data)
@@ -388,7 +392,9 @@ class PrivateKeyBackend:
def _check_passphrase(self) -> bool:
"""Check whether provided passphrase matches, assuming self.existing_private_key_bytes has been populated."""
if self.existing_private_key_bytes is None:
raise AssertionError("existing_private_key_bytes not set")
raise AssertionError(
"existing_private_key_bytes not set"
) # pragma: no cover
try:
key_format = identify_private_key_format(self.existing_private_key_bytes)
if key_format == "raw":
@@ -460,7 +466,9 @@ class PrivateKeyBackend:
def _check_format(self) -> bool:
"""Check whether the key file format, assuming self.existing_private_key and self.existing_private_key_bytes has been populated."""
if self.existing_private_key_bytes is None:
raise AssertionError("existing_private_key_bytes not set")
raise AssertionError(
"existing_private_key_bytes not set"
) # pragma: no cover
if self.format == "auto_ignore":
return True
try:

View File

@@ -31,8 +31,8 @@ from ansible_collections.community.crypto.plugins.module_utils._io import load_f
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from cryptography.hazmat.primitives.asymmetric.types import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PrivateKeyTypes,
)
@@ -81,7 +81,7 @@ class PrivateKeyConvertBackend:
self.src_private_key_bytes = load_file(path=self.src_path, module=module)
else:
if self.src_content is None:
raise AssertionError("src_content is None")
raise AssertionError("src_content is None") # pragma: no cover
self.src_private_key_bytes = self.src_content.encode("utf-8")
self.dest_private_key: PrivateKeyTypes | None = None
@@ -90,7 +90,7 @@ class PrivateKeyConvertBackend:
def get_private_key_data(self) -> bytes:
"""Return bytes for self.src_private_key in output format"""
if self.src_private_key is None:
raise AssertionError("src_private_key not set")
raise AssertionError("src_private_key not set") # pragma: no cover
# Select export format and encoding
try:
export_encoding = cryptography.hazmat.primitives.serialization.Encoding.PEM

View File

@@ -33,18 +33,20 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PrivateKeyTypes,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION

View File

@@ -23,18 +23,20 @@ from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PublicKeyTypes,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
@@ -119,7 +121,7 @@ class PublicKeyInfoRetrieval:
def _get_public_key(self, binary: bool) -> bytes:
if self.key is None:
raise AssertionError("key must be set")
raise AssertionError("key must be set") # pragma: no cover
return self.key.public_bytes(
serialization.Encoding.DER if binary else serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo,
@@ -127,7 +129,7 @@ class PublicKeyInfoRetrieval:
def _get_key_info(self) -> tuple[str, dict[str, t.Any]]:
if self.key is None:
raise AssertionError("key must be set")
raise AssertionError("key must be set") # pragma: no cover
return _get_cryptography_public_key_info(self.key)
def get_info(self, *, prefer_one_fingerprint: bool = False) -> dict[str, t.Any]:

View File

@@ -38,11 +38,11 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.basic imp
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
CertificatePrivateKeyTypes,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
PrivateKeyTypes,
PublicKeyTypes,

View File

@@ -23,15 +23,17 @@ from ansible_collections.community.crypto.plugins.module_utils._version import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
AnsibleActionModule,
)
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import (
from ansible_collections.community.crypto.plugins.plugin_utils._filter_module import ( # pragma: no cover
FilterModuleMock,
)
GeneralAnsibleModule = t.Union[AnsibleModule, AnsibleActionModule, FilterModuleMock]
GeneralAnsibleModule = t.Union[
AnsibleModule, AnsibleActionModule, FilterModuleMock
] # pragma: no cover
_CRYPTOGRAPHY_IMP_ERR: str | None = None

View File

@@ -14,7 +14,7 @@ import typing as t
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
def load_file(*, path: str | os.PathLike, module: AnsibleModule | None = None) -> bytes:

View File

@@ -19,23 +19,26 @@ from ansible_collections.community.crypto.plugins.module_utils._openssh.utils im
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._openssh.certificate import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._openssh.certificate import ( # pragma: no cover
OpensshCertificateTimeParameters,
)
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
PrivateKeyTypes,
)
Param = t.ParamSpec("Param")
Param = t.ParamSpec("Param") # pragma: no cover
def restore_on_failure(
f: t.Callable[t.Concatenate[AnsibleModule, str | os.PathLike, Param], None],
) -> t.Callable[t.Concatenate[AnsibleModule, str | os.PathLike, Param], None]:
def backup_and_restore(
module: AnsibleModule, path: str | os.PathLike, *args, **kwargs
module: AnsibleModule,
path: str | os.PathLike,
*args: Param.args,
**kwargs: Param.kwargs,
) -> None:
backup_file = module.backup_local(path) if os.path.exists(path) else None
@@ -74,8 +77,8 @@ def _restore_all_on_failure(
def backup_and_restore(
self: OpensshModule,
sources_and_destinations: list[tuple[str | os.PathLike, str | os.PathLike]],
*args,
**kwargs,
*args: Param.args,
**kwargs: Param.kwargs,
) -> None:
backups = [
(d, self.module.backup_local(d))
@@ -97,6 +100,9 @@ def _restore_all_on_failure(
return backup_and_restore
_OpensshModule = t.TypeVar("_OpensshModule", bound="OpensshModule")
class OpensshModule(metaclass=abc.ABCMeta):
def __init__(self, *, module: AnsibleModule) -> None:
self.module = module
@@ -141,16 +147,24 @@ class OpensshModule(metaclass=abc.ABCMeta):
pass
@staticmethod
def skip_if_check_mode(f: t.Callable[Param, None]) -> t.Callable[Param, None]:
def wrapper(self, *args, **kwargs) -> None:
def skip_if_check_mode(
f: t.Callable[t.Concatenate[_OpensshModule, Param], None],
) -> t.Callable[t.Concatenate[_OpensshModule, Param], None]:
def wrapper(
self: _OpensshModule, *args: Param.args, **kwargs: Param.kwargs
) -> None:
if not self.check_mode:
f(self, *args, **kwargs)
return wrapper # type: ignore
@staticmethod
def trigger_change(f: t.Callable[Param, None]) -> t.Callable[Param, None]:
def wrapper(self, *args, **kwargs) -> None:
def trigger_change(
f: t.Callable[t.Concatenate[_OpensshModule, Param], None],
) -> t.Callable[t.Concatenate[_OpensshModule, Param], None]:
def wrapper(
self: _OpensshModule, *args: Param.args, **kwargs: Param.kwargs
) -> None:
f(self, *args, **kwargs)
self.changed = True
@@ -202,6 +216,13 @@ class OpensshModule(metaclass=abc.ABCMeta):
self.changed = True
if t.TYPE_CHECKING:
class _RunCommandKwarg(t.TypedDict):
check_rc: t.NotRequired[bool]
environ_update: t.NotRequired[dict[str, str] | None]
class KeygenCommand:
def __init__(self, module: AnsibleModule) -> None:
self._bin_path = module.get_bin_path("ssh-keygen", True)
@@ -221,7 +242,7 @@ class KeygenCommand:
cert_type: t.Literal["host", "user"] | None,
time_parameters: OpensshCertificateTimeParameters,
use_agent: bool,
**kwargs,
**kwargs: t.Unpack[_RunCommandKwarg],
) -> tuple[int, str, str]:
args = [self._bin_path, "-s", signing_key_path, "-P", "", "-I", identifier]
@@ -253,7 +274,7 @@ class KeygenCommand:
size: int,
key_type: str,
comment: str | None,
**kwargs,
**kwargs: t.Unpack[_RunCommandKwarg],
) -> tuple[int, str, str]:
args = [
self._bin_path,
@@ -276,21 +297,21 @@ class KeygenCommand:
return self._run_command(args, data=data, **kwargs)
def get_certificate_info(
self, *, certificate_path: str, **kwargs
self, *, certificate_path: str, **kwargs: t.Unpack[_RunCommandKwarg]
) -> tuple[int, str, str]:
return self._run_command(
[self._bin_path, "-L", "-f", certificate_path], **kwargs
)
def get_matching_public_key(
self, *, private_key_path: str, **kwargs
self, *, private_key_path: str, **kwargs: t.Unpack[_RunCommandKwarg]
) -> tuple[int, str, str]:
return self._run_command(
[self._bin_path, "-P", "", "-y", "-f", private_key_path], **kwargs
)
def get_private_key(
self, *, private_key_path: str, **kwargs
self, *, private_key_path: str, **kwargs: t.Unpack[_RunCommandKwarg]
) -> tuple[int, str, str]:
return self._run_command(
[self._bin_path, "-l", "-f", private_key_path], **kwargs
@@ -302,7 +323,7 @@ class KeygenCommand:
private_key_path: str,
comment: str,
force_new_format: bool = True,
**kwargs,
**kwargs: t.Unpack[_RunCommandKwarg],
) -> tuple[int, str, str]:
if os.path.exists(private_key_path) and not os.access(
private_key_path, os.W_OK

View File

@@ -44,8 +44,8 @@ from ansible_collections.community.crypto.plugins.module_utils._version import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from cryptography.hazmat.primitives.asymmetric.types import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
PrivateKeyTypes,
)

View File

@@ -31,13 +31,13 @@ from ansible_collections.community.crypto.plugins.module_utils._time import (
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._openssh.cryptography import (
from ansible_collections.community.crypto.plugins.module_utils._openssh.cryptography import ( # pragma: no cover
KeyType,
)
DateFormat = t.Literal["human_readable", "openssh", "timestamp"]
DateFormatStr = t.Literal["human_readable", "openssh"]
DateFormatInt = t.Literal["timestamp"]
DateFormat = t.Literal["human_readable", "openssh", "timestamp"] # pragma: no cover
DateFormatStr = t.Literal["human_readable", "openssh"] # pragma: no cover
DateFormatInt = t.Literal["timestamp"] # pragma: no cover
else:
KeyType = None # pylint: disable=invalid-name
@@ -338,6 +338,22 @@ class OpensshCertificateOption:
)
if t.TYPE_CHECKING:
class _OpensshCertificateInfoKwarg(t.TypedDict):
nonce: t.NotRequired[bytes | None]
serial: t.NotRequired[int | None]
cert_type: t.NotRequired[int | None]
key_id: t.NotRequired[bytes | None]
principals: t.NotRequired[list[bytes] | None]
valid_after: t.NotRequired[int | None]
valid_before: t.NotRequired[int | None]
critical_options: t.NotRequired[list[tuple[bytes, bytes]] | None]
extensions: t.NotRequired[list[tuple[bytes, bytes]] | None]
reserved: t.NotRequired[bytes | None]
signing_key: t.NotRequired[bytes | None]
class OpensshCertificateInfo(metaclass=abc.ABCMeta):
"""Encapsulates all certificate information which is signed by a CA key"""
@@ -402,7 +418,13 @@ class OpensshCertificateInfo(metaclass=abc.ABCMeta):
class OpensshRSACertificateInfo(OpensshCertificateInfo):
def __init__(self, *, e: int | None = None, n: int | None = None, **kwargs) -> None:
def __init__(
self,
*,
e: int | None = None,
n: int | None = None,
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg],
) -> None:
super().__init__(**kwargs)
self.type_string = _SSH_TYPE_STRINGS["rsa"] + _CERT_SUFFIX_V01
self.e = e
@@ -433,7 +455,7 @@ class OpensshDSACertificateInfo(OpensshCertificateInfo):
q: int | None = None,
g: int | None = None,
y: int | None = None,
**kwargs,
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg],
) -> None:
super().__init__(**kwargs)
self.type_string = _SSH_TYPE_STRINGS["dsa"] + _CERT_SUFFIX_V01
@@ -465,7 +487,11 @@ class OpensshDSACertificateInfo(OpensshCertificateInfo):
class OpensshECDSACertificateInfo(OpensshCertificateInfo):
def __init__(
self, *, curve: bytes | None = None, public_key: bytes | None = None, **kwargs
self,
*,
curve: bytes | None = None,
public_key: bytes | None = None,
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg],
):
super().__init__(**kwargs)
self._curve: bytes | None = None
@@ -509,7 +535,12 @@ class OpensshECDSACertificateInfo(OpensshCertificateInfo):
class OpensshED25519CertificateInfo(OpensshCertificateInfo):
def __init__(self, *, pk: bytes | None = None, **kwargs) -> None:
def __init__(
self,
*,
pk: bytes | None = None,
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg],
) -> None:
super().__init__(**kwargs)
self.type_string = _SSH_TYPE_STRINGS["ed25519"] + _CERT_SUFFIX_V01
self.pk = pk

View File

@@ -75,22 +75,22 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptogra
if t.TYPE_CHECKING:
KeyFormat = t.Literal["SSH", "PKCS8", "PKCS1"]
KeySerializationFormat = t.Literal["PEM", "DER", "SSH"]
KeyType = t.Literal["rsa", "dsa", "ed25519", "ecdsa"]
KeyFormat = t.Literal["SSH", "PKCS8", "PKCS1"] # pragma: no cover
KeySerializationFormat = t.Literal["PEM", "DER", "SSH"] # pragma: no cover
KeyType = t.Literal["rsa", "dsa", "ed25519", "ecdsa"] # pragma: no cover
PrivateKeyTypes = t.Union[
rsa.RSAPrivateKey,
dsa.DSAPrivateKey,
ec.EllipticCurvePrivateKey,
Ed25519PrivateKey,
]
] # pragma: no cover
PublicKeyTypes = t.Union[
rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey, Ed25519PublicKey
]
] # pragma: no cover
from cryptography.hazmat.primitives.asymmetric.types import (
PublicKeyTypes as AllPublicKeyTypes,
PublicKeyTypes as AllPublicKeyTypes, # pragma: no cover
)

View File

@@ -252,7 +252,7 @@ def main() -> t.NoReturn:
if client.account_key_data:
diff_before["public_account_key"] = client.account_key_data["jwk"]
if created:
raise AssertionError("Unwanted account creation")
raise AssertionError("Unwanted account creation") # pragma: no cover
if account_data is not None:
# Account is not yet deactivated
if not module.check_mode:
@@ -310,7 +310,7 @@ def main() -> t.NoReturn:
# Verify that the account exists and has not been deactivated
created, account_data = account.setup_account(allow_creation=False)
if created:
raise AssertionError("Unwanted account creation")
raise AssertionError("Unwanted account creation") # pragma: no cover
if account_data is None:
raise ModuleFailException(
msg="Account does not exist or is deactivated."

View File

@@ -224,7 +224,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.utils impor
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
def get_orders_list(
@@ -310,7 +310,7 @@ def main() -> t.NoReturn:
remove_account_uri_if_not_exists=True,
)
if created:
raise AssertionError("Unwanted account creation")
raise AssertionError("Unwanted account creation") # pragma: no cover
result: dict[str, t.Any] = {
"changed": False,
"exists": False,

View File

@@ -594,12 +594,12 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.utils impor
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
CertificateInformation,
CryptoBackend,
)
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import (
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( # pragma: no cover
Authorization,
)

View File

@@ -332,7 +332,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.errors impo
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
CertificateChain,
)

View File

@@ -244,7 +244,7 @@ from ansible_collections.community.crypto.plugins.module_utils._acme.errors impo
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import (
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( # pragma: no cover
Authorization,
)

View File

@@ -206,7 +206,7 @@ def main() -> t.NoReturn:
"supports_ari": False,
}
def complete(should_renew: bool, **kwargs) -> t.NoReturn:
def complete(should_renew: bool, **kwargs: t.Any) -> t.NoReturn:
result["should_renew"] = should_renew
result.update(kwargs)
module.exit_json(**result)

View File

@@ -205,7 +205,7 @@ def main() -> t.NoReturn:
# Step 1: get hold of account URI
created, account_data = account.setup_account(allow_creation=False)
if created:
raise AssertionError("Unwanted account creation")
raise AssertionError("Unwanted account creation") # pragma: no cover
if account_data is None:
raise ModuleFailException(
msg="Account does not exist or is deactivated."

View File

@@ -179,7 +179,7 @@ def is_parent(
public_key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
):
if cert.cert.signature_hash_algorithm is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"signature_hash_algorithm should be present for RSA certificates"
)
public_key.verify(
@@ -193,7 +193,7 @@ def is_parent(
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey,
):
if cert.cert.signature_hash_algorithm is None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"signature_hash_algorithm should be present for EC certificates"
)
public_key.verify(

View File

@@ -421,11 +421,17 @@ class Certificate(OpensshModule):
def _is_fully_valid(self) -> bool:
if self.original_data is None:
raise AssertionError("Contract violation original_data not provided")
raise AssertionError(
"Contract violation original_data not provided"
) # pragma: no cover
if self.public_key is None:
raise AssertionError("Contract violation public_key not provided")
raise AssertionError(
"Contract violation public_key not provided"
) # pragma: no cover
if self.signing_key is None:
raise AssertionError("Contract violation signing_key not provided")
raise AssertionError(
"Contract violation signing_key not provided"
) # pragma: no cover
return self._is_partially_valid() and all(
[
self._compare_options() if self.original_data.type == "user" else True,
@@ -439,7 +445,9 @@ class Certificate(OpensshModule):
def _is_partially_valid(self) -> bool:
if self.original_data is None:
raise AssertionError("Contract violation original_data not provided")
raise AssertionError(
"Contract violation original_data not provided"
) # pragma: no cover
return all(
[
set(self.original_data.principals) == set(self.principals),
@@ -460,7 +468,9 @@ class Certificate(OpensshModule):
def _compare_time_parameters(self) -> bool:
if self.original_data is None:
raise AssertionError("Contract violation original_data not provided")
raise AssertionError(
"Contract violation original_data not provided"
) # pragma: no cover
try:
original_time_parameters = OpensshCertificateTimeParameters(
valid_from=self.original_data.valid_after,
@@ -481,7 +491,9 @@ class Certificate(OpensshModule):
def _compare_options(self) -> bool:
if self.original_data is None:
raise AssertionError("Contract violation original_data not provided")
raise AssertionError(
"Contract violation original_data not provided"
) # pragma: no cover
try:
critical_options, extensions = parse_option_list(self.options)
except ValueError as e:
@@ -518,11 +530,17 @@ class Certificate(OpensshModule):
def _generate_temp_certificate(self) -> str:
if self.public_key is None:
raise AssertionError("Contract violation public_key not provided")
raise AssertionError(
"Contract violation public_key not provided"
) # pragma: no cover
if self.signing_key is None:
raise AssertionError("Contract violation signing_key not provided")
raise AssertionError(
"Contract violation signing_key not provided"
) # pragma: no cover
if self.time_parameters is None:
raise AssertionError("Contract violation time_parameters not provided")
raise AssertionError(
"Contract violation time_parameters not provided"
) # pragma: no cover
key_copy = os.path.join(self.module.tmpdir, os.path.basename(self.public_key))

View File

@@ -258,8 +258,8 @@ from ansible_collections.community.crypto.plugins.module_utils._io import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import ( # pragma: no cover
CertificateSigningRequestBackend,
)

View File

@@ -139,8 +139,8 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.module_ba
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import ( # pragma: no cover
CertificateSigningRequestBackend,
)

View File

@@ -416,7 +416,7 @@ def main() -> t.NoReturn:
)
dhparam = DHParameterCryptography(module)
else:
raise AssertionError("Internal error: unknown backend")
raise AssertionError("Internal error: unknown backend") # pragma: no cover
if module.check_mode:
result = dhparam.dump()

View File

@@ -334,7 +334,7 @@ else:
CRYPTOGRAPHY_HAS_COMPATIBILITY2022 = True
if t.TYPE_CHECKING:
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
CertificateIssuerPrivateKeyTypes,
)
@@ -343,7 +343,7 @@ if t.TYPE_CHECKING:
t.Union[cryptography.x509.Certificate, None],
list[cryptography.x509.Certificate],
t.Union[bytes, None],
]
] # pragma: no cover
def load_certificate_set(
@@ -688,7 +688,7 @@ class Pkcs(OpenSSLObject):
]:
"""Read PKCS#12 file."""
if self.src is None:
raise AssertionError("Contract violation: src is None")
raise AssertionError("Contract violation: src is None") # pragma: no cover
try:
with open(self.src, "rb") as pkcs12_fh:

View File

@@ -174,8 +174,8 @@ from ansible_collections.community.crypto.plugins.module_utils._io import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import ( # pragma: no cover
PrivateKeyBackend,
)

View File

@@ -79,8 +79,8 @@ from ansible_collections.community.crypto.plugins.module_utils._io import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey_convert import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey_convert import ( # pragma: no cover
PrivateKeyConvertBackend,
)
@@ -115,7 +115,9 @@ class PrivateKeyConvertModule(OpenSSLObject):
# Convert
privatekey_data = self.module_backend.get_private_key_data()
if privatekey_data is None:
raise AssertionError("Contract violation: privatekey_data is None")
raise AssertionError(
"Contract violation: privatekey_data is None"
) # pragma: no cover
if not self.check_mode:
if self.backup:
self.backup_file = module.backup_local(self.path)

View File

@@ -220,7 +220,7 @@ except ImportError:
pass
if t.TYPE_CHECKING:
from cryptography.hazmat.primitives.asymmetric.types import (
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
PrivateKeyTypes,
PublicKeyTypes,
)

View File

@@ -238,8 +238,8 @@ from ansible_collections.community.crypto.plugins.module_utils._io import (
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import ( # pragma: no cover
CertificateBackend,
)

View File

@@ -136,8 +136,8 @@ from ansible_collections.community.crypto.plugins.module_utils._crypto.module_ba
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import (
from ansible.module_utils.basic import AnsibleModule # pragma: no cover
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import ( # pragma: no cover
CertificateBackend,
)

View File

@@ -497,7 +497,7 @@ except ImportError:
pass
if t.TYPE_CHECKING:
import datetime
import datetime # pragma: no cover
class CRLError(OpenSSLObjectError):

View File

@@ -141,7 +141,7 @@ class AnsibleActionModule:
collection_name: str | None = None,
) -> None:
if version is not None and date is not None:
raise AssertionError(
raise AssertionError( # pragma: no cover
"implementation error -- version and date must not both be set"
)
@@ -203,13 +203,13 @@ class AnsibleActionModule:
kwargs = remove_values(kwargs, self.no_log_values)
raise _ModuleExitException(kwargs)
def exit_json(self, **kwargs) -> t.NoReturn:
def exit_json(self, **kwargs: t.Any) -> t.NoReturn:
result = dict(kwargs)
if "failed" not in result:
result["failed"] = False
self._return_formatted(result)
def fail_json(self, msg: str, **kwargs) -> t.NoReturn:
def fail_json(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
result = dict(kwargs)
result["failed"] = True
result["msg"] = msg
@@ -226,7 +226,9 @@ class ActionModuleBase(ActionBase, metaclass=abc.ABCMeta):
"""Run module code"""
module.fail_json(msg="Not implemented.")
def run(self, tmp=None, task_vars=None) -> dict[str, t.Any]:
def run(
self, tmp: None = None, task_vars: dict[str, t.Any] | None = None
) -> dict[str, t.Any]:
if task_vars is None:
task_vars = {}

View File

@@ -24,7 +24,7 @@ class FilterModuleMock:
self.params = params
self._diff = False
def fail_json(self, msg: str, **kwargs) -> t.NoReturn:
def fail_json(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
raise AnsibleFilterError(msg)
def warn(self, warning: str) -> None: