Code refactoring (#889)

* Add __all__ to all module and plugin utils.

* Convert quite a few positional args to keyword args.

* Avoid Python 3.8+ syntax.
This commit is contained in:
Felix Fontein
2025-05-16 06:55:57 +02:00
committed by GitHub
parent a5a4e022ba
commit 44bcc8cebc
101 changed files with 1510 additions and 748 deletions

View File

@@ -218,7 +218,7 @@ def main() -> t.NoReturn:
],
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, True)
backend = create_backend(module, needs_acme_v2=True)
if module.params["external_account_binding"]:
# Make sure padding is there
@@ -235,8 +235,8 @@ def main() -> t.NoReturn:
module.params["external_account_binding"]["key"] = key
try:
client = ACMEClient(module, backend)
account = ACMEAccount(client)
client = ACMEClient(module=module, backend=backend)
account = ACMEAccount(client=client)
changed = False
state: t.Literal["present", "absent", "changed_key"] = module.params["state"]
diff_before: dict[str, t.Any] = {}
@@ -267,7 +267,7 @@ def main() -> t.NoReturn:
terms_agreed = module.params.get("terms_agreed")
external_account_binding = module.params.get("external_account_binding")
created, account_data = account.setup_account(
contact,
contact=contact,
terms_agreed=terms_agreed,
allow_creation=allow_creation,
external_account_binding=external_account_binding,
@@ -284,7 +284,9 @@ def main() -> t.NoReturn:
diff_before["public_account_key"] = client.account_key_data["jwk"]
updated = False
if not created:
updated, account_data = account.update_account(account_data, contact)
updated, account_data = account.update_account(
account_data=account_data, contact=contact
)
changed = created or updated
diff_after = dict(account_data)
if client.account_key_data:
@@ -293,8 +295,8 @@ def main() -> t.NoReturn:
# Parse new account key
try:
new_key_data = client.parse_key(
module.params.get("new_account_key_src"),
module.params.get("new_account_key_content"),
key_file=module.params.get("new_account_key_src"),
key_content=module.params.get("new_account_key_content"),
passphrase=module.params.get("new_account_key_passphrase"),
)
except KeyParsingError as e:
@@ -327,7 +329,11 @@ def main() -> t.NoReturn:
"newKey": new_key_data["jwk"], # specified in draft 12 and older
"oldKey": client.account_jwk, # specified in draft 13 and newer
}
data = client.sign_request(protected, change_key_payload, new_key_data)
data = client.sign_request(
protected=protected,
payload=change_key_payload,
key_data=new_key_data,
)
# Send request and verify result
result, info = client.send_signed_request(
url,
@@ -356,7 +362,7 @@ def main() -> t.NoReturn:
}
module.exit_json(**result)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -254,7 +254,7 @@ def get_orders_list(
if relation == "next":
new_orders_url.append(link)
process_links(info, f)
process_links(info=info, callback=f)
new_orders_url.append(None)
previous_orders_url, next_orders_url = next_orders_url, new_orders_url.pop(0)
if next_orders_url == previous_orders_url:
@@ -278,14 +278,14 @@ def main() -> t.NoReturn:
),
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, True)
backend = create_backend(module, needs_acme_v2=True)
try:
client = ACMEClient(module, backend)
account = ACMEAccount(client)
client = ACMEClient(module=module, backend=backend)
account = ACMEAccount(client=client)
# Check whether account exists
created, account_data = account.setup_account(
[],
contact=[],
allow_creation=False,
remove_account_uri_if_not_exists=True,
)
@@ -316,7 +316,7 @@ def main() -> t.NoReturn:
result["orders"] = [get_order(client, order) for order in orders]
module.exit_json(**result)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -117,10 +117,10 @@ def main() -> t.NoReturn:
mutually_exclusive=[("certificate_path", "certificate_content")],
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, True)
backend = create_backend(module, needs_acme_v2=True)
try:
client = ACMEClient(module, backend)
client = ACMEClient(module=module, backend=backend)
if not client.directory.has_renewal_info_endpoint():
module.fail_json(
msg="The ACME endpoint does not support ACME Renewal Information retrieval"
@@ -132,7 +132,7 @@ def main() -> t.NoReturn:
)
module.exit_json(renewal_info=renewal_info)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -628,8 +628,8 @@ class ACMECertificateClient:
self.dest = module.params.get("dest")
self.fullchain_dest = module.params.get("fullchain_dest")
self.chain_dest = module.params.get("chain_dest")
self.client = ACMEClient(module, backend)
self.account = ACMEAccount(self.client)
self.client = ACMEClient(module=module, backend=backend)
self.account = ACMEAccount(client=self.client)
self.directory = self.client.directory
self.data = module.params["data"]
self.authorizations: dict[str, Authorization] | None = None
@@ -652,7 +652,9 @@ class ACMECertificateClient:
try:
self.select_chain_matcher.append(
self.client.backend.create_chain_matcher(
Criterium(criterium, index=criterium_idx)
criterium=Criterium(
criterium=criterium, index=criterium_idx
)
)
)
except ValueError as exc:
@@ -675,7 +677,7 @@ class ACMECertificateClient:
if module.params["account_email"]:
contact.append("mailto:" + module.params["account_email"])
created, account_data = self.account.setup_account(
contact,
contact=contact,
terms_agreed=module.params.get("terms_agreed"),
allow_creation=modify_account,
)
@@ -683,7 +685,9 @@ class ACMECertificateClient:
raise ModuleFailException(msg="Account does not exist or is deactivated.")
updated = False
if not created and account_data and modify_account:
updated, account_data = self.account.update_account(account_data, contact)
updated, account_data = self.account.update_account(
account_data=account_data, contact=contact
)
self.changed = created or updated
if self.csr is not None and not os.path.exists(self.csr):
@@ -728,13 +732,13 @@ class ACMECertificateClient:
cert_info = self._get_cert_info_or_none()
if cert_info is not None:
replaces_cert_id = compute_cert_id(
self.client.backend,
backend=self.client.backend,
cert_info=cert_info,
none_if_required_information_is_missing=True,
)
self.order = Order.create_with_error_handling(
self.client,
self.identifiers,
client=self.client,
identifiers=self.identifiers,
error_strategy=self.order_creation_error_strategy,
error_max_retries=self.order_creation_max_retries,
replaces_cert_id=replaces_cert_id,
@@ -742,7 +746,7 @@ class ACMECertificateClient:
message_callback=self.module.warn,
)
self.order_uri = self.order.url
self.order.load_authorizations(self.client)
self.order.load_authorizations(client=self.client)
self.authorizations.update(self.order.authorizations)
self.changed = True
@@ -763,7 +767,7 @@ class ACMECertificateClient:
if authz.status == "valid":
continue
# We drop the type from the key to preserve backwards compatibility
challenges = authz.get_challenge_data(self.client)
challenges = authz.get_challenge_data(client=self.client)
assert authz.identifier is not None
data[authz.identifier] = challenges
if (
@@ -793,8 +797,8 @@ class ACMECertificateClient:
# For ACME v2, we obtain the order object by fetching the
# order URI, and extract the information from there.
assert self.order_uri is not None
self.order = Order.from_url(self.client, self.order_uri)
self.order.load_authorizations(self.client)
self.order = Order.from_url(client=self.client, url=self.order_uri)
self.order.load_authorizations(client=self.client)
self.authorizations.update(self.order.authorizations)
# Step 2: validate pending challenges
@@ -802,18 +806,20 @@ class ACMECertificateClient:
for type_identifier, authz in self.authorizations.items():
if authz.status == "pending":
if self.challenge is not None:
authz.call_validate(self.client, self.challenge, wait=False)
authz.call_validate(
client=self.client, challenge_type=self.challenge, wait=False
)
authzs_to_wait_for.append(authz)
# If there is no challenge, we must check whether the authz is valid
elif authz.status != "valid":
authz.raise_error(
'Status is not "valid", even though no challenge should be necessary',
error_msg='Status is not "valid", even though no challenge should be necessary',
module=self.client.module,
)
self.changed = True
# Step 3: wait for authzs to validate
wait_for_validation(authzs_to_wait_for, self.client)
wait_for_validation(authzs=authzs_to_wait_for, client=self.client)
def download_alternate_chains(
self, cert: CertificateChain
@@ -821,7 +827,7 @@ class ACMECertificateClient:
alternate_chains = []
for alternate in cert.alternates:
try:
alt_cert = CertificateChain.download(self.client, alternate)
alt_cert = CertificateChain.download(client=self.client, url=alternate)
except ModuleFailException as e:
self.module.warn(
f"Error while downloading alternative certificate {alternate}: {e}"
@@ -835,7 +841,7 @@ class ACMECertificateClient:
) -> CertificateChain | None:
for criterium_idx, matcher in enumerate(self.select_chain_matcher):
for chain in chains:
if matcher.match(chain):
if matcher.match(certificate=chain):
self.module.debug(
f"Found matching chain for criterium {criterium_idx}"
)
@@ -852,23 +858,30 @@ class ACMECertificateClient:
for identifier_type, identifier in self.identifiers:
authz = self.authorizations.get(
normalize_combined_identifier(
combine_identifier(identifier_type, identifier)
combine_identifier(
identifier_type=identifier_type, identifier=identifier
)
)
)
if authz is None:
raise ModuleFailException(
f'Found no authorization information for "{combine_identifier(identifier_type, identifier)}"!'
f'Found no authorization information for "{combine_identifier(identifier_type=identifier_type, identifier=identifier)}"!'
)
if authz.status != "valid":
authz.raise_error(
f'Status is "{authz.status}" and not "valid"',
error_msg=f'Status is "{authz.status}" and not "valid"',
module=self.module,
)
assert self.order is not None
self.order.finalize(self.client, pem_to_der(self.csr, self.csr_content))
self.order.finalize(
client=self.client,
csr_der=pem_to_der(pem_filename=self.csr, pem_content=self.csr_content),
)
assert self.order.certificate_uri is not None
cert = CertificateChain.download(self.client, self.order.certificate_uri)
cert = CertificateChain.download(
client=self.client, url=self.order.certificate_uri
)
if self.module.params["retrieve_all_alternates"] or self.select_chain_matcher:
# Retrieve alternate chains
alternate_chains = self.download_alternate_chains(cert)
@@ -892,21 +905,27 @@ class ACMECertificateClient:
chain = cert.chain
if self.dest and write_file(
self.module, self.dest, pem_cert.encode("utf8")
module=self.module, dest=self.dest, content=pem_cert.encode("utf8")
):
self.cert_days = self.client.backend.get_cert_days(self.dest)
self.cert_days = self.client.backend.get_cert_days(
cert_filename=self.dest
)
self.changed = True
if self.fullchain_dest and write_file(
self.module,
self.fullchain_dest,
(pem_cert + "\n".join(chain)).encode("utf8"),
module=self.module,
dest=self.fullchain_dest,
content=(pem_cert + "\n".join(chain)).encode("utf8"),
):
self.cert_days = self.client.backend.get_cert_days(self.fullchain_dest)
self.cert_days = self.client.backend.get_cert_days(
cert_filename=self.fullchain_dest
)
self.changed = True
if self.chain_dest and write_file(
self.module, self.chain_dest, ("\n".join(chain)).encode("utf8")
module=self.module,
dest=self.chain_dest,
content=("\n".join(chain)).encode("utf8"),
):
self.changed = True
@@ -919,7 +938,7 @@ class ACMECertificateClient:
assert self.authorizations is not None
for authz in self.authorizations.values():
try:
authz.deactivate(self.client)
authz.deactivate(client=self.client)
except Exception:
# ignore errors
pass
@@ -982,13 +1001,15 @@ def main() -> t.NoReturn:
],
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
if module.params.get("dest"):
cert_days = backend.get_cert_days(module.params["dest"])
cert_days = backend.get_cert_days(cert_filename=module.params["dest"])
else:
cert_days = backend.get_cert_days(module.params["fullchain_dest"])
cert_days = backend.get_cert_days(
cert_filename=module.params["fullchain_dest"]
)
if module.params["force"] or cert_days < module.params["remaining_days"]:
# If checkmode is active, base the changed state solely on the status
@@ -1003,7 +1024,7 @@ def main() -> t.NoReturn:
cert_days=cert_days,
)
else:
client = ACMECertificateClient(module, backend)
client = ACMECertificateClient(module=module, backend=backend)
client.cert_days = cert_days
other: dict[str, t.Any] = {}
is_first_step = client.is_first_step()
@@ -1040,7 +1061,7 @@ def main() -> t.NoReturn:
else:
module.exit_json(changed=False, cert_days=cert_days)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -74,18 +74,18 @@ def main() -> t.NoReturn:
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMEClient(module, backend)
account = ACMEAccount(client)
client = ACMEClient(module=module, backend=backend)
account = ACMEAccount(client=client)
dummy, account_data = account.setup_account(allow_creation=False)
if account_data is None:
raise ModuleFailException(msg="Account does not exist or is deactivated.")
order = Order.from_url(client, module.params["order_uri"])
order.load_authorizations(client)
order = Order.from_url(client=client, url=module.params["order_uri"])
order.load_authorizations(client=client)
changed = False
for authz in order.authorizations.values():
@@ -95,7 +95,7 @@ def main() -> t.NoReturn:
if module.check_mode:
continue
try:
authz.deactivate(client)
authz.deactivate(client=client)
except Exception:
# ignore errors
pass
@@ -104,7 +104,7 @@ def main() -> t.NoReturn:
module.exit_json(changed=changed)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -400,10 +400,10 @@ def main() -> t.NoReturn:
)
module = argument_spec.create_ansible_module()
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMECertificateClient(module, backend)
client = ACMECertificateClient(module=module, backend=backend)
profile = module.params["profile"]
if profile is not None:
@@ -439,7 +439,7 @@ def main() -> t.NoReturn:
challenge_data_dns=data_dns,
)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -366,10 +366,10 @@ def main() -> t.NoReturn:
)
module = argument_spec.create_ansible_module()
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMECertificateClient(module, backend)
client = ACMECertificateClient(module=module, backend=backend)
select_chain_matcher = client.parse_select_chain(module.params["select_chain"])
other = dict()
done = False
@@ -416,7 +416,8 @@ def main() -> t.NoReturn:
# Try to select alternate chain depending on criteria
if select_chain_matcher:
matching_chain = client.find_matching_chain(
[cert] + alternate_chains, select_chain_matcher
chains=[cert] + alternate_chains,
select_chain_matcher=select_chain_matcher,
)
if matching_chain:
cert = matching_chain
@@ -424,7 +425,7 @@ def main() -> t.NoReturn:
module.debug("Found no matching alternative chain")
if client.write_cert_chain(
cert,
cert=cert,
cert_dest=module.params["cert_dest"],
fullchain_dest=module.params["fullchain_dest"],
chain_dest=module.params["chain_dest"],
@@ -447,7 +448,7 @@ def main() -> t.NoReturn:
**other,
)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -378,10 +378,10 @@ def main() -> t.NoReturn:
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMECertificateClient(module, backend)
client = ACMECertificateClient(module=module, backend=backend)
order = client.load_order()
authorizations_by_identifier: dict[str, dict[str, t.Any]] = {}
authorizations_by_status: dict[str, list[str]] = {
@@ -405,7 +405,7 @@ def main() -> t.NoReturn:
authorizations_by_status=authorizations_by_status,
)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -258,10 +258,10 @@ def main() -> t.NoReturn:
)
module = argument_spec.create_ansible_module()
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMECertificateClient(module, backend)
client = ACMECertificateClient(module=module, backend=backend)
done = False
order = None
try:
@@ -290,7 +290,10 @@ def main() -> t.NoReturn:
bad_challenge_authzs = [
authz.combined_identifier
for authz in pending_authzs
if authz.find_challenge(challenges[authz.combined_identifier]) is None
if authz.find_challenge(
challenge_type=challenges[authz.combined_identifier]
)
is None
]
if bad_challenge_authzs:
authz_challenges_pairs = ", ".join(
@@ -305,7 +308,7 @@ def main() -> t.NoReturn:
def is_pending(authz: Authorization) -> bool:
challenge_name = challenges[authz.combined_identifier]
challenge_obj = authz.find_challenge(challenge_name)
challenge_obj = authz.find_challenge(challenge_type=challenge_name)
return challenge_obj is not None and challenge_obj.status == "pending"
really_pending_authzs = [
@@ -338,7 +341,7 @@ def main() -> t.NoReturn:
],
)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -194,7 +194,7 @@ def main() -> t.NoReturn:
mutually_exclusive=[("certificate_path", "certificate_content")],
)
module = argument_spec.create_ansible_module(supports_check_mode=True)
backend = create_backend(module, True)
backend = create_backend(module, needs_acme_v2=True)
result = dict(
changed=False,
@@ -222,7 +222,7 @@ def main() -> t.NoReturn:
try:
read_file(module.params["certificate_path"])
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
result["exists"] = True
try:
@@ -233,25 +233,27 @@ def main() -> t.NoReturn:
except ModuleFailException as e:
if module.params["treat_parsing_error_as_non_existing"]:
complete(True, msg=f"Certificate cannot be parsed: {e.msg}")
e.do_fail(module)
e.do_fail(module=module)
result["parsable"] = True
try:
cert_id = compute_cert_id(
backend, cert_info=cert_info, none_if_required_information_is_missing=True
backend=backend,
cert_info=cert_info,
none_if_required_information_is_missing=True,
)
if cert_id is not None:
result["cert_id"] = cert_id
if module.params["now"]:
now = backend.parse_module_parameter(module.params["now"], "now")
now = backend.parse_module_parameter(value=module.params["now"], name="now")
else:
now = backend.get_now()
if now >= cert_info.not_valid_after:
complete(True, msg="The certificate has already expired")
client = ACMEClient(module, backend)
client = ACMEClient(module=module, backend=backend)
if (
cert_id is not None
and module.params["use_ari"]
@@ -281,7 +283,7 @@ def main() -> t.NoReturn:
)
else:
random_time = backend.interpolate_timestamp(
window_start, window_end, random.random()
window_start, window_end, percentage=random.random()
)
if now > random_time:
complete(
@@ -301,7 +303,7 @@ def main() -> t.NoReturn:
timestamp = backend.interpolate_timestamp(
cert_info.not_valid_before,
cert_info.not_valid_after,
1 - module.params["remaining_percentage"],
percentage=1 - module.params["remaining_percentage"],
)
if timestamp < now:
complete(
@@ -312,7 +314,7 @@ def main() -> t.NoReturn:
complete(False)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -159,13 +159,13 @@ def main() -> t.NoReturn:
],
)
module = argument_spec.create_ansible_module()
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
try:
client = ACMEClient(module, backend)
account = ACMEAccount(client)
client = ACMEClient(module=module, backend=backend)
account = ACMEAccount(client=client)
# Load certificate
certificate = pem_to_der(module.params.get("certificate"))
certificate = pem_to_der(pem_filename=module.params.get("certificate"))
certificate_b64 = nopad_b64(certificate)
# Construct payload
payload = {"certificate": certificate_b64}
@@ -181,7 +181,9 @@ def main() -> t.NoReturn:
# Step 1: load and parse private key
try:
private_key_data = client.parse_key(
private_key, private_key_content, passphrase=passphrase
key_file=private_key,
key_content=private_key_content,
passphrase=passphrase,
)
except KeyParsingError as e:
raise ModuleFailException(f"Error while parsing private key: {e.msg}")
@@ -228,11 +230,14 @@ def main() -> t.NoReturn:
if already_revoked:
module.exit_json(changed=False)
raise ACMEProtocolException(
module, "Failed to revoke certificate", info=info, content_json=result
module=module,
msg="Failed to revoke certificate",
info=info,
content_json=result,
)
module.exit_json(changed=True)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -331,7 +331,7 @@ def main() -> t.NoReturn:
),
)
except ModuleFailException as e:
e.do_fail(module)
e.do_fail(module=module)
if __name__ == "__main__":

View File

@@ -256,13 +256,13 @@ def main() -> t.NoReturn:
],
)
module = argument_spec.create_ansible_module()
backend = create_backend(module, False)
backend = create_backend(module, needs_acme_v2=False)
result: dict[str, t.Any] = {}
changed = False
try:
# Get hold of ACMEClient and ACMEAccount objects (includes directory)
client = ACMEClient(module, backend)
client = ACMEClient(module=module, backend=backend)
method = module.params["method"]
result["directory"] = client.directory.directory
# Do we have to do more requests?
@@ -297,11 +297,11 @@ def main() -> t.NoReturn:
pass
# Fail if error was returned
if fail_on_acme_error and info["status"] >= 400:
raise ACMEProtocolException(module, info=info, content=data)
raise ACMEProtocolException(module=module, info=info, content=data)
# Done!
module.exit_json(changed=changed, **result)
except ModuleFailException as e:
e.do_fail(module, **result)
e.do_fail(module=module, **result)
if __name__ == "__main__":

View File

@@ -849,7 +849,10 @@ class EcsCertificate:
if self.request_type != "validate_only":
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, to_bytes(self.cert_details.get("endEntityCert")))
write_file(
module=module,
content=to_bytes(self.cert_details.get("endEntityCert")),
)
if self.full_chain_path and self.cert_details.get("chainCerts"):
if self.backup:
self.backup_full_chain_file = module.backup_local(
@@ -859,17 +862,24 @@ class EcsCertificate:
"\n".join(self.cert_details.get("chainCerts")) + "\n"
)
write_file(
module, to_bytes(chain_string), path=self.full_chain_path
module=module,
content=to_bytes(chain_string),
path=self.full_chain_path,
)
self.changed = True
# If there is no certificate present in path but a tracking ID was specified, save it to disk
elif not os.path.exists(self.path) and self.tracking_id:
if not module.check_mode:
write_file(module, to_bytes(self.cert_details.get("endEntityCert")))
write_file(
module=module,
content=to_bytes(self.cert_details.get("endEntityCert")),
)
if self.full_chain_path and self.cert_details.get("chainCerts"):
chain_string = "\n".join(self.cert_details.get("chainCerts")) + "\n"
write_file(
module, to_bytes(chain_string), path=self.full_chain_path
module=module,
content=to_bytes(chain_string),
path=self.full_chain_path,
)
self.changed = True

View File

@@ -304,7 +304,7 @@ from ansible_collections.community.crypto.plugins.module_utils._version import (
class Certificate(OpensshModule):
def __init__(self, module: AnsibleModule) -> None:
super(Certificate, self).__init__(module)
super(Certificate, self).__init__(module=module)
self.ssh_keygen = KeygenCommand(self.module)
self.identifier: str = self.module.params["identifier"] or ""
@@ -496,7 +496,9 @@ class Certificate(OpensshModule):
)
def _get_key_fingerprint(self, path: str) -> str:
private_key_content = self.ssh_keygen.get_private_key(path, check_rc=True)[1]
private_key_content = self.ssh_keygen.get_private_key(
private_key_path=path, check_rc=True
)[1]
return PrivateKey.from_string(private_key_content).fingerprint
@OpensshModule.trigger_change
@@ -532,17 +534,17 @@ class Certificate(OpensshModule):
self.module.add_cleanup_file(key_copy)
self.ssh_keygen.generate_certificate(
key_copy,
self.identifier,
self.options,
self.pkcs11_provider,
self.principals,
self.serial_number,
self.signature_algorithm,
self.signing_key,
self.type,
self.time_parameters,
self.use_agent,
certificate_path=key_copy,
identifier=self.identifier,
options=self.options,
pkcs11_provider=self.pkcs11_provider,
principals=self.principals,
serial_number=self.serial_number,
signature_algorithm=self.signature_algorithm,
signing_key_path=self.signing_key,
type=self.type,
time_parameters=self.time_parameters,
use_agent=self.use_agent,
environ_update=dict(TZ="UTC"),
check_rc=True,
)
@@ -566,7 +568,7 @@ class Certificate(OpensshModule):
return {}
certificate_info = self.ssh_keygen.get_certificate_info(
self.path,
certificate_path=self.path,
check_rc=self.state == "present" and not self.module.check_mode,
)[1]

View File

@@ -248,7 +248,7 @@ def main() -> t.NoReturn:
add_file_common_args=True,
)
keypair = select_backend(module, module.params["backend"])
keypair = select_backend(module=module, backend=module.params["backend"])
keypair.execute()

View File

@@ -270,10 +270,10 @@ class CertificateSigningRequestModule(OpenSSLObject):
self, module: AnsibleModule, module_backend: CertificateSigningRequestBackend
) -> None:
super(CertificateSigningRequestModule, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.module_backend = module_backend
self.return_content = module.params["return_content"]
@@ -281,7 +281,9 @@ class CertificateSigningRequestModule(OpenSSLObject):
self.backup = module.params["backup"]
self.backup_file: str | None = None
self.module_backend.set_existing(load_file_if_exists(self.path, module))
self.module_backend.set_existing(
csr_bytes=load_file_if_exists(path=self.path, module=module)
)
def generate(self, module: AnsibleModule) -> None:
"""Generate the certificate signing request."""
@@ -291,7 +293,7 @@ class CertificateSigningRequestModule(OpenSSLObject):
result = self.module_backend.get_csr_data()
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, result)
write_file(module=module, content=result)
self.changed = True
file_args = module.load_file_common_arguments(module.params)
@@ -303,7 +305,7 @@ class CertificateSigningRequestModule(OpenSSLObject):
)
def remove(self, module: AnsibleModule) -> None:
self.module_backend.set_existing(None)
self.module_backend.set_existing(csr_bytes=None)
if self.backup and not self.check_mode:
self.backup_file = module.backup_local(self.path)
super(CertificateSigningRequestModule, self).remove(module)

View File

@@ -349,7 +349,9 @@ def main() -> t.NoReturn:
except (IOError, OSError) as e:
module.fail_json(msg=f"Error while reading CSR file from disk: {e}")
module_backend = select_backend(module, data, validate_signature=True)
module_backend = select_backend(
module=module, content=data, validate_signature=True
)
try:
result = module_backend.get_info()

View File

@@ -154,7 +154,9 @@ class CertificateSigningRequestModule:
self.module_backend = module_backend
self.changed = False
if module.params["content"] is not None:
self.module_backend.set_existing(module.params["content"].encode("utf-8"))
self.module_backend.set_existing(
csr_bytes=module.params["content"].encode("utf-8")
)
def generate(self, module: AnsibleModule) -> None:
"""Generate the certificate signing request."""

View File

@@ -244,7 +244,7 @@ class DHParameterBase:
if self.backup_file:
result["backup_file"] = self.backup_file
if self.return_content:
content = load_file_if_exists(self.path, ignore_errors=True)
content = load_file_if_exists(path=self.path, ignore_errors=True)
result["dhparams"] = content.decode("utf-8") if content else None
return result
@@ -338,7 +338,7 @@ class DHParameterCryptography(DHParameterBase):
# Write result
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, result)
write_file(module=module, content=result)
def _check_params_valid(self, module: AnsibleModule) -> bool:
"""Check if the params are in the correct state"""

View File

@@ -357,8 +357,7 @@ def load_certificate_set(
with open(filename, "rb") as f:
data = f.read().decode("utf-8")
return [
load_certificate(None, content=cert.encode("utf-8"))
for cert in split_pem_list(data)
load_certificate(content=cert.encode("utf-8")) for cert in split_pem_list(data)
]
@@ -371,10 +370,10 @@ class Pkcs(OpenSSLObject):
def __init__(self, module: AnsibleModule, iter_size_default: int = 2048) -> None:
super(Pkcs, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.action: t.Literal["export", "parse"] = module.params["action"]
self.other_certificates: list[cryptography.x509.Certificate] = []
@@ -439,7 +438,7 @@ class Pkcs(OpenSSLObject):
)
else:
self.other_certificates = [
load_certificate(other_cert)
load_certificate(path=other_cert)
for other_cert in self.other_certificates_str
]
elif self.other_certificates_content:
@@ -451,8 +450,7 @@ class Pkcs(OpenSSLObject):
)
)
self.other_certificates = [
load_certificate(None, content=to_bytes(other_cert))
for other_cert in certs
load_certificate(content=to_bytes(other_cert)) for other_cert in certs
]
@abc.abstractmethod
@@ -486,7 +484,9 @@ class Pkcs(OpenSSLObject):
def check(self, module: AnsibleModule, perms_required: bool = True) -> bool:
"""Ensure the resource is in its desired state."""
state_and_perms = super(Pkcs, self).check(module, perms_required)
state_and_perms = super(Pkcs, self).check(
module=module, perms_required=perms_required
)
def _check_pkey_passphrase() -> bool:
if self.privatekey_passphrase:
@@ -569,7 +569,7 @@ class Pkcs(OpenSSLObject):
]
)
)
dumped_content = load_file_if_exists(self.path, ignore_errors=True)
dumped_content = load_file_if_exists(path=self.path, ignore_errors=True)
if expected_content != dumped_content:
return False
else:
@@ -589,7 +589,9 @@ class Pkcs(OpenSSLObject):
result["backup_file"] = self.backup_file
if self.return_content:
if self.pkcs12_bytes is None:
self.pkcs12_bytes = load_file_if_exists(self.path, ignore_errors=True)
self.pkcs12_bytes = load_file_if_exists(
path=self.path, ignore_errors=True
)
result["pkcs12"] = (
base64.b64encode(self.pkcs12_bytes) if self.pkcs12_bytes else None
)
@@ -628,7 +630,7 @@ class Pkcs(OpenSSLObject):
"""Write the PKCS#12 file."""
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, content, mode)
write_file(module=module, content=content, default_mode=mode)
if self.return_content:
self.pkcs12_bytes = content
@@ -660,7 +662,7 @@ class PkcsCryptography(Pkcs):
cert = None
if self.certificate_content:
cert = load_certificate(None, content=self.certificate_content)
cert = load_certificate(content=self.certificate_content)
friendly_name = (
to_bytes(self.friendly_name) if self.friendly_name is not None else None
@@ -701,7 +703,7 @@ class PkcsCryptography(Pkcs):
]:
try:
private_key, certificate, additional_certificates, friendly_name = (
parse_pkcs12(pkcs12_content, self.passphrase)
parse_pkcs12(pkcs12_content, passphrase=self.passphrase)
)
pkey = None

View File

@@ -186,10 +186,10 @@ class PrivateKeyModule(OpenSSLObject):
self, module: AnsibleModule, module_backend: PrivateKeyBackend
) -> None:
super(PrivateKeyModule, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.module_backend = module_backend
self.return_content: bool = module.params["return_content"]
@@ -202,7 +202,9 @@ class PrivateKeyModule(OpenSSLObject):
if module.params["mode"] is None:
module.params["mode"] = "0600"
module_backend.set_existing(load_file_if_exists(self.path, module))
module_backend.set_existing(
privatekey_bytes=load_file_if_exists(path=self.path, module=module)
)
def generate(self, module: AnsibleModule) -> None:
"""Generate a keypair."""
@@ -216,7 +218,7 @@ class PrivateKeyModule(OpenSSLObject):
privatekey_data = self.module_backend.get_private_key_data()
if self.return_content:
self.privatekey_bytes = privatekey_data
write_file(module, privatekey_data, 0o600)
write_file(module=module, content=privatekey_data, default_mode=0o600)
self.changed = True
elif self.module_backend.needs_conversion():
# Convert
@@ -227,7 +229,7 @@ class PrivateKeyModule(OpenSSLObject):
privatekey_data = self.module_backend.get_private_key_data()
if self.return_content:
self.privatekey_bytes = privatekey_data
write_file(module, privatekey_data, 0o600)
write_file(module=module, content=privatekey_data, default_mode=0o600)
self.changed = True
file_args = module.load_file_common_arguments(module.params)
@@ -239,7 +241,7 @@ class PrivateKeyModule(OpenSSLObject):
)
def remove(self, module: AnsibleModule) -> None:
self.module_backend.set_existing(None)
self.module_backend.set_existing(privatekey_bytes=None)
if self.backup and not self.check_mode:
self.backup_file = module.backup_local(self.path)
super(PrivateKeyModule, self).remove(module)

View File

@@ -90,10 +90,10 @@ class PrivateKeyConvertModule(OpenSSLObject):
self, module: AnsibleModule, module_backend: PrivateKeyConvertBackend
) -> None:
super(PrivateKeyConvertModule, self).__init__(
module.params["dest_path"],
"present",
False,
module.check_mode,
path=module.params["dest_path"],
state="present",
force=False,
check_mode=module.check_mode,
)
self.module_backend = module_backend
@@ -104,7 +104,9 @@ class PrivateKeyConvertModule(OpenSSLObject):
if module.params["mode"] is None:
module.params["mode"] = "0600"
module_backend.set_existing_destination(load_file_if_exists(self.path, module))
module_backend.set_existing_destination(
privatekey_bytes=load_file_if_exists(path=self.path, module=module)
)
def generate(self, module: AnsibleModule) -> None:
"""Do conversion."""
@@ -117,7 +119,7 @@ class PrivateKeyConvertModule(OpenSSLObject):
if not self.check_mode:
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, privatekey_data, 0o600)
write_file(module=module, content=privatekey_data, default_mode=0o600)
self.changed = True
file_args = module.load_file_common_arguments(module.params)

View File

@@ -250,8 +250,8 @@ def main() -> t.NoReturn:
result["can_load_key"] = True
module_backend = select_backend(
module,
data,
module=module,
content=data,
passphrase=module.params["passphrase"],
return_private_key_data=module.params["return_private_key_data"],
check_consistency=module.params["check_consistency"],

View File

@@ -234,10 +234,10 @@ class PublicKey(OpenSSLObject):
def __init__(self, module: AnsibleModule) -> None:
super(PublicKey, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.module = module
self.format: t.Literal["OpenSSH", "PEM"] = module.params["format"]
@@ -266,7 +266,7 @@ class PublicKey(OpenSSLObject):
try:
result.update(
get_publickey_info(
self.module, content=data, prefer_one_fingerprint=True
module=self.module, content=data, prefer_one_fingerprint=True
)
)
result["can_parse_key"] = True
@@ -312,7 +312,7 @@ class PublicKey(OpenSSLObject):
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, publickey_content)
write_file(module=module, content=publickey_content)
self.changed = True
except OpenSSLBadPassphraseError as exc:
@@ -334,7 +334,9 @@ class PublicKey(OpenSSLObject):
def check(self, module: AnsibleModule, perms_required: bool = True) -> bool:
"""Ensure the resource is in its desired state."""
state_and_perms = super(PublicKey, self).check(module, perms_required)
state_and_perms = super(PublicKey, self).check(
module=module, perms_required=perms_required
)
def _check_privatekey() -> bool:
if self.privatekey_path is not None and not os.path.exists(
@@ -401,7 +403,7 @@ class PublicKey(OpenSSLObject):
if self.return_content:
if self.publickey_bytes is None:
self.publickey_bytes = load_file_if_exists(
self.path, ignore_errors=True
path=self.path, ignore_errors=True
)
result["publickey"] = (
self.publickey_bytes.decode("utf-8") if self.publickey_bytes else None

View File

@@ -195,7 +195,7 @@ def main() -> t.NoReturn:
msg=f"Error while reading public key file from disk: {e}", **result # type: ignore
)
module_backend = select_backend(module, data)
module_backend = select_backend(module=module, content=data)
try:
result.update(module_backend.get_info())

View File

@@ -268,10 +268,10 @@ if t.TYPE_CHECKING:
class CertificateAbsent(OpenSSLObject):
def __init__(self, module: AnsibleModule) -> None:
super(CertificateAbsent, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.module = module
self.return_content: bool = module.params["return_content"]
@@ -306,10 +306,10 @@ class GenericCertificate(OpenSSLObject):
def __init__(self, module: AnsibleModule, module_backend: CertificateBackend):
super(GenericCertificate, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.module = module
self.return_content = module.params["return_content"]
@@ -317,7 +317,9 @@ class GenericCertificate(OpenSSLObject):
self.backup_file = None
self.module_backend = module_backend
self.module_backend.set_existing(load_file_if_exists(self.path, module))
self.module_backend.set_existing(
certificate_bytes=load_file_if_exists(path=self.path, module=module)
)
def generate(self, module: AnsibleModule) -> None:
if self.module_backend.needs_regeneration():
@@ -326,7 +328,7 @@ class GenericCertificate(OpenSSLObject):
result = self.module_backend.get_certificate_data()
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, result)
write_file(module=module, content=result)
self.changed = True
file_args = module.load_file_common_arguments(module.params)
@@ -340,7 +342,9 @@ class GenericCertificate(OpenSSLObject):
def check(self, module: AnsibleModule, perms_required: bool = True) -> bool:
"""Ensure the resource is in its desired state."""
return (
super(GenericCertificate, self).check(module, perms_required)
super(GenericCertificate, self).check(
module=module, perms_required=perms_required
)
and not self.module_backend.needs_regeneration()
)
@@ -411,7 +415,9 @@ def main() -> t.NoReturn:
"selfsigned": SelfSignedCertificateProvider,
}
module_backend = select_backend(module, provider_map[provider]())
module_backend = select_backend(
module=module, provider=provider_map[provider]()
)
certificate = GenericCertificate(module, module_backend)
certificate.generate(module)

View File

@@ -168,10 +168,10 @@ def parse_certificate(
class X509CertificateConvertModule(OpenSSLObject):
def __init__(self, module: AnsibleModule) -> None:
super(X509CertificateConvertModule, self).__init__(
module.params["dest_path"],
"present",
False,
module.check_mode,
path=module.params["dest_path"],
state="present",
force=False,
check_mode=module.check_mode,
)
self.src_path: str | None = module.params["src_path"]
@@ -214,7 +214,7 @@ class X509CertificateConvertModule(OpenSSLObject):
module.params["path"] = self.path
self.dest_content = load_file_if_exists(self.path, module)
self.dest_content = load_file_if_exists(path=self.path, module=module)
self.dest_content_format = None
self.dest_content_pem_type = None
if self.dest_content is not None:
@@ -264,7 +264,7 @@ class X509CertificateConvertModule(OpenSSLObject):
if not self.check_mode:
if self.backup:
self.backup_file = module.backup_local(self.path)
write_file(module, cert_data)
write_file(module=module, content=cert_data)
self.changed = True
file_args = module.load_file_common_arguments(module.params)

View File

@@ -439,7 +439,7 @@ def main() -> t.NoReturn:
except (IOError, OSError) as e:
module.fail_json(msg=f"Error while reading certificate file from disk: {e}")
module_backend = select_backend(module, data)
module_backend = select_backend(module=module, content=data)
valid_at: dict[str, t.Any] = module.params["valid_at"]
if valid_at:
@@ -449,7 +449,9 @@ def main() -> t.NoReturn:
msg=f"The value for valid_at.{k} must be of type string (got {type(v)})"
)
valid_at[k] = get_relative_time_option(
to_text(v), f"valid_at.{k}", with_timezone=CRYPTOGRAPHY_TIMEZONE
to_text(v),
input_name=f"valid_at.{k}",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
try:

View File

@@ -203,7 +203,9 @@ def main() -> t.NoReturn:
"selfsigned": SelfSignedCertificateProvider,
}
module_backend = select_backend(module, provider_map[provider]())
module_backend = select_backend(
module=module, provider=provider_map[provider]()
)
certificate = GenericCertificate(module, module_backend)
certificate.generate(module)
result = certificate.dump()

View File

@@ -508,10 +508,10 @@ class CRL(OpenSSLObject):
def __init__(self, module: AnsibleModule) -> None:
super(CRL, self).__init__(
module.params["path"],
module.params["state"],
module.params["force"],
module.check_mode,
path=module.params["path"],
state=module.params["state"],
force=module.params["force"],
check_mode=module.check_mode,
)
self.format: t.Literal["pem", "der"] = module.params["format"]
@@ -544,23 +544,27 @@ class CRL(OpenSSLObject):
]
if issuer_ordered:
self.issuer_ordered = True
self.issuer = parse_ordered_name_field(issuer_ordered, "issuer_ordered")
self.issuer = parse_ordered_name_field(
issuer_ordered, name_field_name="issuer_ordered"
)
else:
self.issuer_ordered = False
self.issuer = (
parse_name_field(issuer, "issuer") if issuer is not None else []
parse_name_field(issuer, name_field_name="issuer")
if issuer is not None
else []
)
except (TypeError, ValueError) as exc:
module.fail_json(msg=str(exc))
self.last_update: datetime.datetime = get_relative_time_option(
module.params["last_update"],
"last_update",
input_name="last_update",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
self.next_update: datetime.datetime | None = get_relative_time_option(
module.params["next_update"],
"next_update",
input_name="next_update",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
@@ -596,7 +600,7 @@ class CRL(OpenSSLObject):
if content_str is not None:
content = content_str.encode("utf-8")
rc["content"] = content
cert = load_certificate(path, content=content)
cert = load_certificate(path=path, content=content)
result["serial_number"] = cert.serial_number
except OpenSSLObjectError as e:
if content_str is not None:
@@ -615,12 +619,13 @@ class CRL(OpenSSLObject):
# All other options
if rc["issuer"]:
result["issuer"] = [
cryptography_get_name(issuer, "issuer") for issuer in rc["issuer"]
cryptography_get_name(issuer, what="issuer")
for issuer in rc["issuer"]
]
result["issuer_critical"] = rc["issuer_critical"]
result["revocation_date"] = get_relative_time_option(
rc["revocation_date"],
path_prefix + "revocation_date",
input_name=path_prefix + "revocation_date",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
if rc["reason"]:
@@ -629,7 +634,7 @@ class CRL(OpenSSLObject):
if rc["invalidity_date"]:
result["invalidity_date"] = get_relative_time_option(
rc["invalidity_date"],
path_prefix + "invalidity_date",
input_name=path_prefix + "invalidity_date",
with_timezone=CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE,
)
result["invalidity_date_critical"] = rc["invalidity_date_critical"]
@@ -690,7 +695,7 @@ class CRL(OpenSSLObject):
if data is None:
return {}
try:
result = get_crl_info(self.module, data)
result = get_crl_info(module=self.module, content=data)
result["can_parse_crl"] = True
return result
except Exception:
@@ -765,7 +770,9 @@ class CRL(OpenSSLObject):
) -> bool:
"""Ensure the resource is in its desired state."""
state_and_perms = super(CRL, self).check(self.module, perms_required)
state_and_perms = super(CRL, self).check(
module=self.module, perms_required=perms_required
)
if not state_and_perms:
return False
@@ -838,9 +845,9 @@ class CRL(OpenSSLObject):
except ValueError as e:
raise CRLError(e)
crl = set_last_update(crl, self.last_update)
crl = set_last_update(crl, value=self.last_update)
if self.next_update is not None:
crl = set_next_update(crl, self.next_update)
crl = set_next_update(crl, value=self.next_update)
if self.update and self.crl:
new_entries = set(
@@ -856,7 +863,7 @@ class CRL(OpenSSLObject):
revoked_cert = RevokedCertificateBuilder()
revoked_cert = revoked_cert.serial_number(revoked_entry["serial_number"])
revoked_cert = set_revocation_date(
revoked_cert, revoked_entry["revocation_date"]
revoked_cert, value=revoked_entry["revocation_date"]
)
if revoked_entry["issuer"] is not None:
revoked_cert = revoked_cert.add_extension(
@@ -909,7 +916,7 @@ class CRL(OpenSSLObject):
self.crl_content = base64.b64encode(result)
if self.backup:
self.backup_file = self.module.backup_local(self.path)
write_file(self.module, result)
write_file(module=self.module, content=result)
self.changed = True
file_args = self.module.load_file_common_arguments(self.module.params)

View File

@@ -224,8 +224,8 @@ def main() -> t.NoReturn:
list_revoked_certificates: bool = module.params["list_revoked_certificates"]
try:
result = get_crl_info(
module,
data,
module=module,
content=data,
list_revoked_certificates=list_revoked_certificates,
)
module.exit_json(**result)