| 1 |
# Copyright (c) 2016 Michael Gruener <[email protected]> |
| 2 |
# Copyright (c) 2021 Felix Fontein <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 7 |
# Do not use this from other collections or standalone plugins/modules! |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import time |
| 12 |
import typing as t |
| 13 |
from collections.abc import Callable |
| 14 |
|
| 15 |
from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( |
| 16 |
Authorization, |
| 17 |
normalize_combined_identifier, |
| 18 |
) |
| 19 |
from ansible_collections.community.crypto.plugins.module_utils._acme.errors import ( |
| 20 |
ACMEProtocolException, |
| 21 |
ModuleFailException, |
| 22 |
) |
| 23 |
from ansible_collections.community.crypto.plugins.module_utils._acme.utils import ( |
| 24 |
nopad_b64, |
| 25 |
) |
| 26 |
|
| 27 |
if t.TYPE_CHECKING: |
| 28 |
from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover |
| 29 |
ACMEClient, |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
_Order = t.TypeVar("_Order", bound="Order") |
| 34 |
|
| 35 |
|
| 36 |
class Order: |
| 37 |
def __init__(self, *, url: str) -> None: |
| 38 |
self.url = url |
| 39 |
|
| 40 |
self.data: dict[str, t.Any] | None = None |
| 41 |
|
| 42 |
self.status: str | None = None |
| 43 |
self.identifiers: list[tuple[str, str]] = [] |
| 44 |
self.replaces_cert_id: str | None = None |
| 45 |
self.finalize_uri: str | None = None |
| 46 |
self.certificate_uri: str | None = None |
| 47 |
self.authorization_uris: list[str] = [] |
| 48 |
self.authorizations: dict[str, Authorization] = {} |
| 49 |
|
| 50 |
def _setup(self, *, client: ACMEClient, data: dict[str, t.Any]) -> None: |
| 51 |
self.data = data |
| 52 |
|
| 53 |
self.status = data["status"] |
| 54 |
self.identifiers = [] |
| 55 |
for identifier in data["identifiers"]: |
| 56 |
self.identifiers.append((identifier["type"], identifier["value"])) |
| 57 |
self.replaces_cert_id = data.get("replaces") |
| 58 |
self.finalize_uri = data.get("finalize") |
| 59 |
self.certificate_uri = data.get("certificate") |
| 60 |
self.authorization_uris = data["authorizations"] |
| 61 |
self.authorizations = {} |
| 62 |
|
| 63 |
@classmethod |
| 64 |
def from_json( |
| 65 |
cls: type[_Order], *, client: ACMEClient, data: dict[str, t.Any], url: str |
| 66 |
) -> _Order: |
| 67 |
result = cls(url=url) |
| 68 |
result._setup(client=client, data=data) |
| 69 |
return result |
| 70 |
|
| 71 |
@classmethod |
| 72 |
def from_url(cls: type[_Order], *, client: ACMEClient, url: str) -> _Order: |
| 73 |
result = cls(url=url) |
| 74 |
result.refresh(client=client) |
| 75 |
return result |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def create( |
| 79 |
cls: type[_Order], |
| 80 |
*, |
| 81 |
client: ACMEClient, |
| 82 |
identifiers: list[tuple[str, str]], |
| 83 |
replaces_cert_id: str | None = None, |
| 84 |
profile: str | None = None, |
| 85 |
) -> _Order: |
| 86 |
""" |
| 87 |
Start a new certificate order (ACME v2 protocol). |
| 88 |
https://tools.ietf.org/html/rfc8555#section-7.4 |
| 89 |
""" |
| 90 |
acme_identifiers = [] |
| 91 |
for identifier_type, identifier in identifiers: |
| 92 |
acme_identifiers.append( |
| 93 |
{ |
| 94 |
"type": identifier_type, |
| 95 |
"value": identifier, |
| 96 |
} |
| 97 |
) |
| 98 |
new_order: dict[str, t.Any] = {"identifiers": acme_identifiers} |
| 99 |
if replaces_cert_id is not None: |
| 100 |
new_order["replaces"] = replaces_cert_id |
| 101 |
if profile is not None: |
| 102 |
new_order["profile"] = profile |
| 103 |
result, info = client.send_signed_request( |
| 104 |
client.directory["newOrder"], |
| 105 |
new_order, |
| 106 |
error_msg="Failed to start new order", |
| 107 |
expected_status_codes=[201], |
| 108 |
) |
| 109 |
if not isinstance(result, dict): |
| 110 |
raise ACMEProtocolException( |
| 111 |
module=client.module, |
| 112 |
msg="Unexpected new order response", |
| 113 |
content_json=result, |
| 114 |
) |
| 115 |
return cls.from_json(client=client, data=result, url=info["location"]) |
| 116 |
|
| 117 |
@classmethod |
| 118 |
def create_with_error_handling( |
| 119 |
cls: type[_Order], |
| 120 |
*, |
| 121 |
client: ACMEClient, |
| 122 |
identifiers: list[tuple[str, str]], |
| 123 |
error_strategy: t.Literal[ |
| 124 |
"auto", "fail", "always", "retry_without_replaces_cert_id" |
| 125 |
] = "auto", |
| 126 |
error_max_retries: int = 3, |
| 127 |
replaces_cert_id: str | None = None, |
| 128 |
profile: str | None = None, |
| 129 |
message_callback: Callable[[str], None] | None = None, |
| 130 |
) -> _Order: |
| 131 |
""" |
| 132 |
error_strategy can be one of the following strings: |
| 133 |
|
| 134 |
* ``fail``: simply fail. (Same behavior as ``Order.create()``.) |
| 135 |
* ``retry_without_replaces_cert_id``: if ``replaces_cert_id`` is not ``None``, set it to ``None`` and retry. |
| 136 |
The only exception is an error of type ``urn:ietf:params:acme:error:alreadyReplaced``, that indicates that |
| 137 |
the certificate was already replaced. |
| 138 |
* ``auto``: try to be clever. Right now this is identical to ``retry_without_replaces_cert_id``, but that can |
| 139 |
change at any time in the future. |
| 140 |
* ``always``: always retry until ``error_max_retries`` has been reached. |
| 141 |
""" |
| 142 |
tries = 0 |
| 143 |
while True: |
| 144 |
tries += 1 |
| 145 |
try: |
| 146 |
return cls.create( |
| 147 |
client=client, |
| 148 |
identifiers=identifiers, |
| 149 |
replaces_cert_id=replaces_cert_id, |
| 150 |
profile=profile, |
| 151 |
) |
| 152 |
except ACMEProtocolException as exc: |
| 153 |
if tries <= error_max_retries + 1 and error_strategy != "fail": |
| 154 |
if error_strategy == "always": |
| 155 |
continue |
| 156 |
|
| 157 |
if ( |
| 158 |
error_strategy in ("auto", "retry_without_replaces_cert_id") |
| 159 |
and replaces_cert_id is not None |
| 160 |
and not ( |
| 161 |
exc.error_code == 409 |
| 162 |
and exc.error_type |
| 163 |
== "urn:ietf:params:acme:error:alreadyReplaced" |
| 164 |
) |
| 165 |
): |
| 166 |
if message_callback: |
| 167 |
message_callback( |
| 168 |
f"Stop passing `replaces={replaces_cert_id}` due to error {exc.error_code} {exc.error_type} when creating ACME order" |
| 169 |
) |
| 170 |
replaces_cert_id = None |
| 171 |
continue |
| 172 |
|
| 173 |
raise |
| 174 |
|
| 175 |
def refresh(self, *, client: ACMEClient) -> bool: |
| 176 |
result, info = client.get_request(self.url) |
| 177 |
if not isinstance(result, dict): |
| 178 |
raise ACMEProtocolException( |
| 179 |
module=client.module, |
| 180 |
msg="Unexpected authorization data", |
| 181 |
info=info, |
| 182 |
content_json=result, |
| 183 |
) |
| 184 |
changed = self.data != result |
| 185 |
self._setup(client=client, data=result) |
| 186 |
return changed |
| 187 |
|
| 188 |
def load_authorizations(self, *, client: ACMEClient) -> None: |
| 189 |
for auth_uri in self.authorization_uris: |
| 190 |
authz = Authorization.from_url(client=client, url=auth_uri) |
| 191 |
self.authorizations[ |
| 192 |
normalize_combined_identifier(authz.combined_identifier) |
| 193 |
] = authz |
| 194 |
|
| 195 |
def wait_for_finalization(self, *, client: ACMEClient) -> None: |
| 196 |
while True: |
| 197 |
self.refresh(client=client) |
| 198 |
if self.status in ["valid", "invalid", "pending", "ready"]: |
| 199 |
break |
| 200 |
time.sleep(2) |
| 201 |
|
| 202 |
if self.status != "valid": |
| 203 |
raise ACMEProtocolException( |
| 204 |
module=client.module, |
| 205 |
msg=f'Failed to wait for order to complete; got status "{self.status}"', |
| 206 |
content_json=self.data, |
| 207 |
) |
| 208 |
|
| 209 |
def finalize( |
| 210 |
self, *, client: ACMEClient, csr_der: bytes, wait: bool = True |
| 211 |
) -> None: |
| 212 |
""" |
| 213 |
Create a new certificate based on the csr. |
| 214 |
Return the certificate object as dict |
| 215 |
https://tools.ietf.org/html/rfc8555#section-7.4 |
| 216 |
""" |
| 217 |
if self.finalize_uri is None: |
| 218 |
raise ModuleFailException("finalize_uri must be set") |
| 219 |
new_cert = { |
| 220 |
"csr": nopad_b64(csr_der), |
| 221 |
} |
| 222 |
result, info = client.send_signed_request( |
| 223 |
self.finalize_uri, |
| 224 |
new_cert, |
| 225 |
error_msg="Failed to finalizing order", |
| 226 |
expected_status_codes=[200], |
| 227 |
) |
| 228 |
# It is not clear from the RFC whether the finalize call returns the order object or not. |
| 229 |
# Instead of using the result, we call self.refresh(client) below. |
| 230 |
|
| 231 |
if wait: |
| 232 |
self.wait_for_finalization(client=client) |
| 233 |
else: |
| 234 |
self.refresh(client=client) |
| 235 |
if self.status not in ["procesing", "valid", "invalid"]: |
| 236 |
raise ACMEProtocolException( |
| 237 |
module=client.module, |
| 238 |
msg=f'Failed to finalize order; got status "{self.status}"', |
| 239 |
info=info, |
| 240 |
content_json=result, |
| 241 |
) |
| 242 |
|
| 243 |
|
| 244 |
__all__ = ("Order",) |