Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/acme_account_info.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2018 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 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: acme_account_info
10 author: "Felix Fontein (@felixfontein)"
11 short_description: Retrieves information on ACME accounts
12 description:
13 - Allows to retrieve information on accounts a CA supporting the L(ACME protocol,https://tools.ietf.org/html/rfc8555), such
14 as L(Let's Encrypt,https://letsencrypt.org/).
15 - This module only works with the ACME v2 protocol.
16 notes:
17 - The M(community.crypto.acme_account) module allows to modify, create and delete ACME accounts.
18 - This module was called C(acme_account_facts) before Ansible 2.8. The usage did not change.
19 extends_documentation_fragment:
20 - community.crypto._acme.basic
21 - community.crypto._acme.account
22 - community.crypto._attributes
23 - community.crypto._attributes.actiongroup_acme
24 - community.crypto._attributes.info_module
25 - community.crypto._attributes.idempotent_not_modify_state
26 options:
27 retrieve_orders:
28 description:
29 - Whether to retrieve the list of order URLs or order objects, if provided by the ACME server.
30 - A value of V(ignore) will not fetch the list of orders.
31 - If the value is not V(ignore) and the ACME server supports orders, the RV(order_uris) return value is always populated.
32 The RV(orders) return value is only returned if this option is set to V(object_list).
33 - Currently, Let's Encrypt does not return orders, so the RV(orders) result will always be empty.
34 type: str
35 choices:
36 - ignore
37 - url_list
38 - object_list
39 default: ignore
40 seealso:
41 - module: community.crypto.acme_account
42 description: Allows to create, modify or delete an ACME account.
43 """
44
45 EXAMPLES = r"""
46 ---
47 - name: Check whether an account with the given account key exists
48 community.crypto.acme_account_info:
49 account_key_src: /etc/pki/cert/private/account.key
50 register: account_data
51 - name: Verify that account exists
52 ansible.builtin.assert:
53 that:
54 - account_data.exists
55 - name: Print account URI
56 ansible.builtin.debug:
57 var: account_data.account_uri
58 - name: Print account contacts
59 ansible.builtin.debug:
60 var: account_data.account.contact
61
62 - name: Check whether the account exists and is accessible with the given account key
63 acme_account_info:
64 account_key_content: "{{ acme_account_key }}"
65 account_uri: "{{ acme_account_uri }}"
66 register: account_data
67 - name: Verify that account exists
68 ansible.builtin.assert:
69 that:
70 - account_data.exists
71 - name: Print account contacts
72 ansible.builtin.debug:
73 var: account_data.account.contact
74 """
75
76 RETURN = r"""
77 exists:
78 description: Whether the account exists.
79 returned: always
80 type: bool
81
82 account_uri:
83 description: ACME account URI, or None if account does not exist.
84 returned: always
85 type: str
86
87 account:
88 description: The account information, as retrieved from the ACME server.
89 returned: if account exists
90 type: dict
91 contains:
92 contact:
93 description: The challenge resource that must be created for validation.
94 returned: always
95 type: list
96 elements: str
97 sample: ['mailto:[email protected]', 'tel:00123456789']
98 status:
99 description: The account's status.
100 returned: always
101 type: str
102 choices: ['valid', 'deactivated', 'revoked']
103 sample: valid
104 orders:
105 description:
106 - A URL where a list of orders can be retrieved for this account.
107 - Use the O(retrieve_orders) option to query this URL and retrieve the complete list of orders.
108 returned: always
109 type: str
110 sample: https://example.ca/account/1/orders
111 public_account_key:
112 description: The public account key as a L(JSON Web Key,https://tools.ietf.org/html/rfc7517).
113 returned: always
114 type: str
115 sample: '{"kty":"EC","crv":"P-256","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}'
116
117 orders:
118 description:
119 - The list of orders.
120 type: list
121 elements: dict
122 returned: if account exists, O(retrieve_orders) is V(object_list), and server supports order listing
123 contains:
124 status:
125 description: The order's status.
126 type: str
127 choices:
128 - pending
129 - ready
130 - processing
131 - valid
132 - invalid
133 expires:
134 description:
135 - When the order expires.
136 - Timestamp should be formatted as described in RFC3339.
137 - Only required to be included in result when RV(orders[].status) is V(pending) or V(valid).
138 type: str
139 returned: when server gives expiry date
140 identifiers:
141 description:
142 - List of identifiers this order is for.
143 type: list
144 elements: dict
145 contains:
146 type:
147 description: Type of identifier.
148 type: str
149 choices:
150 - dns
151 - ip
152 value:
153 description: Name of identifier. Hostname or IP address.
154 type: str
155 wildcard:
156 description: "Whether RV(orders[].identifiers[].value) is actually a wildcard. The wildcard prefix C(*.) is not
157 included in RV(orders[].identifiers[].value) if this is V(true)."
158 type: bool
159 returned: required to be included if the identifier is wildcarded
160 notBefore:
161 description:
162 - The requested value of the C(notBefore) field in the certificate.
163 - Date should be formatted as described in RFC3339.
164 - Server is not required to return this.
165 type: str
166 returned: when server returns this
167 notAfter:
168 description:
169 - The requested value of the C(notAfter) field in the certificate.
170 - Date should be formatted as described in RFC3339.
171 - Server is not required to return this.
172 type: str
173 returned: when server returns this
174 error:
175 description:
176 - In case an error occurred during processing, this contains information about the error.
177 - The field is structured as a problem document (RFC7807).
178 type: dict
179 returned: when an error occurred
180 authorizations:
181 description:
182 - A list of URLs for authorizations for this order.
183 type: list
184 elements: str
185 finalize:
186 description:
187 - A URL used for finalizing an ACME order.
188 type: str
189 certificate:
190 description:
191 - The URL for retrieving the certificate.
192 type: str
193 returned: when certificate was issued
194
195 order_uris:
196 description:
197 - The list of orders.
198 - If O(retrieve_orders) is V(url_list), this will be a list of URLs.
199 - If O(retrieve_orders) is V(object_list), this will be a list of objects.
200 type: list
201 elements: str
202 returned: if account exists, O(retrieve_orders) is not V(ignore), and server supports order listing
203 version_added: 1.5.0
204 """
205
206 import typing as t
207
208 from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
209 ACMEAccount,
210 )
211 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
212 ACMEClient,
213 create_backend,
214 create_default_argspec,
215 )
216 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
217 ACMEProtocolException,
218 ModuleFailException,
219 )
220 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
221 process_links,
222 )
223
224 if t.TYPE_CHECKING:
225 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
226
227
228 def _collect_next(info: dict[str, t.Any]) -> list[str]:
229 result: list[str] = []
230
231 def f(link: str, relation: str) -> None:
232 if relation == "next":
233 result.append(link)
234
235 process_links(info=info, callback=f)
236 return result
237
238
239 def get_orders_list(
240 module: AnsibleModule, client: ACMEClient, orders_url: str
241 ) -> list[str]:
242 """
243 Retrieves order URL list (handles pagination).
244 """
245 orders: list[str] = []
246 next_orders_url: str | None = orders_url
247 while next_orders_url:
248 # Get part of orders list
249 res, info = client.get_request(
250 next_orders_url, parse_json_result=True, fail_on_error=True
251 )
252 if not isinstance(res, dict):
253 raise ACMEProtocolException(
254 module=module,
255 msg="Unexpected account information",
256 info=info,
257 content_json=res,
258 )
259 if not res.get("orders"):
260 if orders:
261 module.warn(
262 f"When retrieving orders list part {next_orders_url}, got empty result list"
263 )
264 break
265 # Add order URLs to result list
266 orders.extend(res["orders"])
267 # Extract URL of next part of results list
268 new_orders_url: list[str | None] = []
269 new_orders_url.extend(_collect_next(info))
270 new_orders_url.append(None)
271 previous_orders_url, next_orders_url = next_orders_url, new_orders_url.pop(0)
272 if next_orders_url == previous_orders_url:
273 # Prevent infinite loop
274 next_orders_url = None
275 return orders
276
277
278 def get_order(client: ACMEClient, order_url: str) -> dict[str, t.Any]:
279 """
280 Retrieve order data.
281 """
282 result, info = client.get_request(
283 order_url, parse_json_result=True, fail_on_error=True
284 )
285 if not isinstance(result, dict):
286 raise ACMEProtocolException(
287 module=client.module,
288 msg="Unexpected order data",
289 info=info,
290 content_json=result,
291 )
292 return result
293
294
295 def main() -> t.NoReturn:
296 argument_spec = create_default_argspec()
297 argument_spec.update_argspec(
298 retrieve_orders={
299 "type": "str",
300 "default": "ignore",
301 "choices": ["ignore", "url_list", "object_list"],
302 },
303 )
304 module = argument_spec.create_ansible_module(supports_check_mode=True)
305 backend = create_backend(module, needs_acme_v2=True)
306
307 try:
308 client = ACMEClient(module=module, backend=backend)
309 account = ACMEAccount(client=client)
310 # Check whether account exists
311 created, account_data = account.setup_account(
312 contact=[],
313 allow_creation=False,
314 remove_account_uri_if_not_exists=True,
315 )
316 if created:
317 raise AssertionError("Unwanted account creation") # pragma: no cover
318 result: dict[str, t.Any] = {
319 "changed": False,
320 "exists": False,
321 "account_uri": None,
322 }
323 if client.account_uri is not None and account_data:
324 result["account_uri"] = client.account_uri
325 result["exists"] = True
326 # Make sure promised data is there
327 account_data_dict = dict(account_data)
328 if "contact" not in account_data:
329 account_data_dict["contact"] = []
330 if client.account_key_data:
331 account_data_dict["public_account_key"] = client.account_key_data["jwk"]
332 result["account"] = account_data_dict
333 # Retrieve orders list
334 if (
335 account_data.get("orders")
336 and module.params["retrieve_orders"] != "ignore"
337 ):
338 orders = get_orders_list(module, client, account_data["orders"])
339 result["order_uris"] = orders
340 if module.params["retrieve_orders"] == "object_list":
341 result["orders"] = [get_order(client, order) for order in orders]
342 module.exit_json(**result)
343 except ModuleFailException as e:
344 e.do_fail(module=module)
345
346
347 if __name__ == "__main__":
348 main()