Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/account.py

raw
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 typing as t
12 from collections.abc import Mapping
13
14 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
15 ACMEProtocolException,
16 ModuleFailException,
17 )
18
19 if t.TYPE_CHECKING:
20 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
21 ACMEClient,
22 )
23
24 _JsonMapping = Mapping[str, t.Any]
25 else:
26 # Since we need to pass this to t.cast(), we need a version that doesn't break with Python 3.7 and 3.8
27 _JsonMapping = Mapping
28
29
30 class ACMEAccount:
31 """
32 ACME account object. Allows to create new accounts, check for existence of accounts,
33 retrieve account data.
34 """
35
36 def __init__(self, *, client: ACMEClient) -> None:
37 # Set to true to enable logging of all signed requests
38 self._debug: bool = False
39
40 self.client = client
41
42 def _new_reg(
43 self,
44 *,
45 contact: list[str] | None = None,
46 terms_agreed: bool = False,
47 allow_creation: bool = True,
48 external_account_binding: dict[str, t.Any] | None = None,
49 ) -> tuple[bool, Mapping[str, t.Any] | None]:
50 """
51 Registers a new ACME account. Returns a pair ``(created, data)``.
52 Here, ``created`` is ``True`` if the account was created and
53 ``False`` if it already existed (e.g. it was not newly created),
54 or does not exist. In case the account was created or exists,
55 ``data`` contains the account data; otherwise, it is ``None``.
56
57 If specified, ``external_account_binding`` should be a dictionary
58 with keys ``kid``, ``alg`` and ``key``
59 (https://tools.ietf.org/html/rfc8555#section-7.3.4).
60
61 https://tools.ietf.org/html/rfc8555#section-7.3
62 """
63 contact = contact or []
64
65 if (
66 external_account_binding is not None
67 or self.client.directory["meta"].get("externalAccountRequired")
68 ) and allow_creation:
69 # Some ACME servers such as ZeroSSL do not like it when you try to register an existing account
70 # and provide external_account_binding credentials. Thus we first send a request with allow_creation=False
71 # to see whether the account already exists.
72
73 # Unfortunately, for other ACME servers it's the other way around: (at least some) HARICA endpoints
74 # do not allow *any* access without external account data. That's why we catch errors and check
75 # for 'externalAccountRequired'.
76 try:
77 # Note that we pass contact here: ZeroSSL does not accept registration calls without contacts, even
78 # if onlyReturnExisting is set to true.
79 created, data = self._new_reg(contact=contact, allow_creation=False)
80 if data:
81 # An account already exists! Return data
82 return created, data
83 # An account does not yet exist. Try to create one next.
84 except ACMEProtocolException as exc:
85 if (
86 exc.error_type
87 != "urn:ietf:params:acme:error:externalAccountRequired"
88 or external_account_binding is None
89 ):
90 # Either another error happened, or we got 'externalAccountRequired' and external account data was not supplied
91 # => re-raise exception!
92 raise
93 # In this case, the server really wants external account data.
94 # The below code tries to create the account with external account data present.
95
96 new_reg: dict[str, t.Any] = {"contact": contact}
97 if not allow_creation:
98 # https://tools.ietf.org/html/rfc8555#section-7.3.1
99 new_reg["onlyReturnExisting"] = True
100 if terms_agreed:
101 new_reg["termsOfServiceAgreed"] = True
102 url = self.client.directory["newAccount"]
103 if external_account_binding is not None:
104 new_reg["externalAccountBinding"] = self.client.sign_request(
105 protected={
106 "alg": external_account_binding["alg"],
107 "kid": external_account_binding["kid"],
108 "url": url,
109 },
110 payload=self.client.account_jwk,
111 key_data=self.client.backend.create_mac_key(
112 alg=external_account_binding["alg"],
113 key=external_account_binding["key"],
114 ),
115 )
116 elif (
117 self.client.directory["meta"].get("externalAccountRequired")
118 and allow_creation
119 ):
120 raise ModuleFailException(
121 "To create an account, an external account binding must be specified. Use the acme_account module with the external_account_binding option."
122 )
123
124 result, info = self.client.send_signed_request(
125 url, new_reg, fail_on_error=False
126 )
127 if not isinstance(result, Mapping):
128 raise ACMEProtocolException(
129 module=self.client.module,
130 msg="Invalid account creation reply from ACME server",
131 info=info,
132 content_json=result,
133 )
134
135 if info["status"] == 201:
136 # Account did not exist
137 if "location" in info:
138 self.client.set_account_uri(info["location"])
139 return True, t.cast(_JsonMapping, result)
140 if info["status"] == 200:
141 # Account did exist
142 if result.get("status") == "deactivated":
143 # A bug in Pebble (https://github.com/letsencrypt/pebble/issues/179) and
144 # Boulder (https://github.com/letsencrypt/boulder/issues/3971): this should
145 # not return a valid account object according to
146 # https://tools.ietf.org/html/rfc8555#section-7.3.6:
147 # "Once an account is deactivated, the server MUST NOT accept further
148 # requests authorized by that account's key."
149 if not allow_creation:
150 return False, None
151 raise ModuleFailException("Account is deactivated")
152 if "location" in info:
153 self.client.set_account_uri(info["location"])
154 return False, t.cast(_JsonMapping, result)
155 if (
156 info["status"] in (400, 404)
157 and result["type"] == "urn:ietf:params:acme:error:accountDoesNotExist"
158 and not allow_creation
159 ):
160 # Account does not exist (and we did not try to create it)
161 # (According to RFC 8555, Section 7.3.1, the HTTP status code MUST be 400.
162 # Unfortunately Digicert does not care and sends 404 instead.)
163 return False, None
164 if (
165 info["status"] == 403
166 and result["type"] == "urn:ietf:params:acme:error:unauthorized"
167 and "deactivated" in (result.get("detail") or "")
168 ):
169 # Account has been deactivated; currently works for Pebble; has not been
170 # implemented for Boulder (https://github.com/letsencrypt/boulder/issues/3971),
171 # might need adjustment in error detection.
172 if not allow_creation:
173 return False, None
174 raise ModuleFailException("Account is deactivated")
175 raise ACMEProtocolException(
176 module=self.client.module,
177 msg="Registering ACME account failed",
178 info=info,
179 content_json=result,
180 )
181
182 def get_account_data(self) -> dict[str, t.Any] | None:
183 """
184 Retrieve account information. Can only be called when the account
185 URI is already known (such as after calling setup_account).
186 Return None if the account was deactivated, or a dict otherwise.
187 """
188 if self.client.account_uri is None:
189 raise ModuleFailException("Account URI unknown")
190 # try POST-as-GET first (draft-15 or newer)
191 data: dict[str, t.Any] | None = None
192 result, info = self.client.send_signed_request(
193 self.client.account_uri, data, fail_on_error=False
194 )
195 # check whether that failed with a malformed request error
196 if (
197 info["status"] >= 400
198 and isinstance(result, Mapping)
199 and result.get("type") == "urn:ietf:params:acme:error:malformed"
200 ):
201 # retry as a regular POST (with no changed data) for pre-draft-15 ACME servers
202 data = {}
203 result, info = self.client.send_signed_request(
204 self.client.account_uri, data, fail_on_error=False
205 )
206 if not isinstance(result, dict):
207 raise ACMEProtocolException(
208 module=self.client.module,
209 msg="Invalid account data retrieved from ACME server",
210 info=info,
211 content_json=result,
212 )
213 if (
214 info["status"] in (400, 403)
215 and result.get("type") == "urn:ietf:params:acme:error:unauthorized"
216 ):
217 # Returned when account is deactivated
218 return None
219 if (
220 info["status"] in (400, 404)
221 and result.get("type") == "urn:ietf:params:acme:error:accountDoesNotExist"
222 ):
223 # Returned when account does not exist
224 return None
225 if info["status"] < 200 or info["status"] >= 300:
226 raise ACMEProtocolException(
227 module=self.client.module,
228 msg="Error retrieving account data",
229 info=info,
230 content_json=result,
231 )
232 return result
233
234 @t.overload
235 def setup_account(
236 self,
237 *,
238 contact: list[str] | None = None,
239 terms_agreed: bool = False,
240 allow_creation: t.Literal[True] = True,
241 remove_account_uri_if_not_exists: bool = False,
242 external_account_binding: dict[str, t.Any] | None = None,
243 ) -> tuple[bool, Mapping[str, t.Any]]: ...
244
245 @t.overload
246 def setup_account(
247 self,
248 *,
249 contact: list[str] | None = None,
250 terms_agreed: bool = False,
251 allow_creation: bool = True,
252 remove_account_uri_if_not_exists: bool = False,
253 external_account_binding: dict[str, t.Any] | None = None,
254 ) -> tuple[bool, Mapping[str, t.Any] | None]: ...
255
256 def setup_account(
257 self,
258 *,
259 contact: list[str] | None = None,
260 terms_agreed: bool = False,
261 allow_creation: bool = True,
262 remove_account_uri_if_not_exists: bool = False,
263 external_account_binding: dict[str, t.Any] | None = None,
264 ) -> tuple[bool, Mapping[str, t.Any] | None]:
265 """
266 Detect or create an account on the ACME server. For ACME v1,
267 as the only way (without knowing an account URI) to test if an
268 account exists is to try and create one with the provided account
269 key, this method will always result in an account being present
270 (except on error situations). For ACME v2, a new account will
271 only be created if ``allow_creation`` is set to True.
272
273 For ACME v2, ``check_mode`` is fully respected. For ACME v1, the
274 account might be created if it does not yet exist.
275
276 Return a pair ``(created, account_data)``. Here, ``created`` will
277 be ``True`` in case the account was created or would be created
278 (check mode). ``account_data`` will be the current account data,
279 or ``None`` if the account does not exist.
280
281 The account URI will be stored in ``client.account_uri``; if it is ``None``,
282 the account does not exist.
283
284 If specified, ``external_account_binding`` should be a dictionary
285 with keys ``kid``, ``alg`` and ``key``
286 (https://tools.ietf.org/html/rfc8555#section-7.3.4).
287
288 https://tools.ietf.org/html/rfc8555#section-7.3
289 """
290
291 if self.client.account_uri is not None:
292 created = False
293 # Verify that the account key belongs to the URI.
294 # (If update_contact is True, this will be done below.)
295 account_data: Mapping[str, t.Any] | None = self.get_account_data()
296 if account_data is None:
297 if remove_account_uri_if_not_exists and not allow_creation:
298 self.client.account_uri = None
299 else:
300 raise ModuleFailException(
301 "Account is deactivated or does not exist!"
302 )
303 else:
304 created, account_data = self._new_reg(
305 contact=contact,
306 terms_agreed=terms_agreed,
307 allow_creation=allow_creation and not self.client.module.check_mode,
308 external_account_binding=external_account_binding,
309 )
310 if (
311 self.client.module.check_mode
312 and self.client.account_uri is None
313 and allow_creation
314 ):
315 created = True
316 account_data = {"contact": contact or []}
317 return created, account_data
318
319 def update_account(
320 self, *, account_data: dict[str, t.Any], contact: list[str] | None = None
321 ) -> tuple[bool, Mapping[str, t.Any]]:
322 """
323 Update an account on the ACME server. Check mode is fully respected.
324
325 The current account data must be provided as ``account_data``.
326
327 Return a pair ``(updated, account_data)``, where ``updated`` is
328 ``True`` in case something changed (contact info updated) or
329 would be changed (check mode), and ``account_data`` the updated
330 account data.
331
332 https://tools.ietf.org/html/rfc8555#section-7.3.2
333 """
334 if self.client.account_uri is None:
335 raise ModuleFailException("Cannot update account without account URI")
336
337 # Create request
338 update_request: dict[str, t.Any] = {}
339 if contact is not None and account_data.get("contact", []) != contact:
340 update_request["contact"] = list(contact)
341
342 # No change?
343 if not update_request:
344 return False, dict(account_data)
345
346 # Apply change
347 account_data_res: Mapping[str, t.Any]
348 if self.client.module.check_mode:
349 account_data_dict = dict(account_data)
350 account_data_dict.update(update_request)
351 account_data_res = account_data_dict
352 else:
353 raw_account_data, info = self.client.send_signed_request(
354 self.client.account_uri, update_request
355 )
356 if not isinstance(raw_account_data, Mapping):
357 raise ACMEProtocolException(
358 module=self.client.module,
359 msg="Invalid account updating reply from ACME server",
360 info=info,
361 content_json=account_data,
362 )
363 account_data_res = raw_account_data
364
365 return True, account_data_res
366
367
368 __all__ = ("ACMEAccount",)