
    Vh`                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZ d dlmZmZmZ d dlmZmZmZ d d	lmZmZmZmZmZ d d
lmZ d dlmZ d dlmZ d dl m!Z!m"Z" dZ# G d de$      Z%d Z&e'dk(  r e&        yy)    )absolute_importdivisionprint_functiona@  
module: acme_certificate
author: "Michael Gruener (@mgruener)"
short_description: Create SSL/TLS certificates with the ACME protocol
description:
  - Create and renew SSL/TLS certificates with a CA supporting the L(ACME protocol,https://tools.ietf.org/html/rfc8555), such
    as L(Let's Encrypt,https://letsencrypt.org/) or L(Buypass,https://www.buypass.com/). The current implementation supports
    the V(http-01), V(dns-01) and V(tls-alpn-01) challenges.
  - To use this module, it has to be executed twice. Either as two different tasks in the same run or during two runs. Note
    that the output of the first run needs to be recorded and passed to the second run as the module argument O(data).
  - Between these two tasks you have to fulfill the required steps for the chosen challenge by whatever means necessary. For
    V(http-01) that means creating the necessary challenge file on the destination webserver. For V(dns-01) the necessary
    DNS record has to be created. For V(tls-alpn-01) the necessary certificate has to be created and served. It is I(not)
    the responsibility of this module to perform these steps.
  - For details on how to fulfill these challenges, you might have to read through L(the main ACME specification,https://tools.ietf.org/html/rfc8555#section-8)
    and the L(TLS-ALPN-01 specification,https://www.rfc-editor.org/rfc/rfc8737.html#section-3). Also, consider the examples
    provided for this module.
  - The module includes experimental support for IP identifiers according to the L(RFC 8738,https://www.rfc-editor.org/rfc/rfc8738.html).
notes:
  - At least one of O(dest) and O(fullchain_dest) must be specified.
  - This module includes basic account management functionality. If you want to have more control over your ACME account,
    use the M(community.crypto.acme_account) module and disable account management for this module using the O(modify_account)
    option.
  - This module was called C(letsencrypt) before Ansible 2.6. The usage did not change.
seealso:
  - name: The Let's Encrypt documentation
    description: Documentation for the Let's Encrypt Certification Authority. Provides useful information for example on rate
      limits.
    link: https://letsencrypt.org/docs/
  - name: Buypass Go SSL
    description: Documentation for the Buypass Certification Authority. Provides useful information for example on rate limits.
    link: https://www.buypass.com/ssl/products/acme
  - name: Automatic Certificate Management Environment (ACME)
    description: The specification of the ACME protocol (RFC 8555).
    link: https://tools.ietf.org/html/rfc8555
  - name: ACME TLS ALPN Challenge Extension
    description: The specification of the V(tls-alpn-01) challenge (RFC 8737).
    link: https://www.rfc-editor.org/rfc/rfc8737.html
  - module: community.crypto.acme_challenge_cert_helper
    description: Helps preparing V(tls-alpn-01) challenges.
  - module: community.crypto.openssl_privatekey
    description: Can be used to create private keys (both for certificates and accounts).
  - module: community.crypto.openssl_privatekey_pipe
    description: Can be used to create private keys without writing it to disk (both for certificates and accounts).
  - module: community.crypto.openssl_csr
    description: Can be used to create a Certificate Signing Request (CSR).
  - module: community.crypto.openssl_csr_pipe
    description: Can be used to create a Certificate Signing Request (CSR) without writing it to disk.
  - module: community.crypto.certificate_complete_chain
    description: Allows to find the root certificate for the returned fullchain.
  - module: community.crypto.acme_certificate_revoke
    description: Allows to revoke certificates.
  - module: community.crypto.acme_account
    description: Allows to create, modify or delete an ACME account.
  - module: community.crypto.acme_inspect
    description: Allows to debug problems.
  - module: community.crypto.acme_certificate_deactivate_authz
    description: Allows to deactivate (invalidate) ACME v2 orders.
extends_documentation_fragment:
  - community.crypto.acme.basic
  - community.crypto.acme.account
  - community.crypto.acme.certificate
  - community.crypto.attributes
  - community.crypto.attributes.files
  - community.crypto.attributes.actiongroup_acme
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
  safe_file_operations:
    support: full
  idempotent:
    support: partial
    details:
      - If O(force=true), the module is not idempotent.
        If O(force=false), it depends on the certificate's validity period and the value of O(remaining_days).
      - The second phase invocation of the module is always idempotent, assuming no error occurs.
options:
  account_email:
    description:
      - The email address associated with this account.
      - It will be used for certificate expiration warnings.
      - Note that when O(modify_account) is not set to V(false) and you also used the M(community.crypto.acme_account) module
        to specify more than one contact for your account, this module will update your account and restrict it to the (at
        most one) contact email address specified here.
    type: str
  agreement:
    description:
      - URI to a terms of service document you agree to when using the ACME v1 service at O(acme_directory).
      - Default is latest gathered from O(acme_directory) URL.
      - This option will only be used when O(acme_version) is 1.
    type: str
  terms_agreed:
    description:
      - Boolean indicating whether you agree to the terms of service document.
      - ACME servers can require this to be true.
      - This option will only be used when O(acme_version) is not 1.
    type: bool
    default: false
  modify_account:
    description:
      - Boolean indicating whether the module should create the account if necessary, and update its contact data.
      - Set to V(false) if you want to use the M(community.crypto.acme_account) module to manage your account instead, and
        to avoid accidental creation of a new account using an old key if you changed the account key with M(community.crypto.acme_account).
      - If set to V(false), O(terms_agreed) and O(account_email) are ignored.
    type: bool
    default: true
  challenge:
    description:
      - The challenge to be performed.
      - If set to V(no challenge), no challenge will be used. This is necessary for some private CAs which use External Account
        Binding and other means of validating certificate assurance. For example, an account could be allowed to issue certificates
        for C(foo.example.com) without any further validation for a certain period of time.
    type: str
    default: 'http-01'
    choices:
      - 'http-01'
      - 'dns-01'
      - 'tls-alpn-01'
      - 'no challenge'
  csr:
    aliases: ['src']
  csr_content:
    version_added: 1.2.0
  data:
    description:
      - The data to validate ongoing challenges. This must be specified for the second run of the module only.
      - The value that must be used here will be provided by a previous use of this module. See the examples for more details.
      - Note that for ACME v2, only the C(order_uri) entry of O(data) will be used. For ACME v1, O(data) must be non-empty
        to indicate the second stage is active; all needed data will be taken from the CSR.
      - 'I(Note): the O(data) option was marked as C(no_log) up to Ansible 2.5. From Ansible 2.6 on, it is no longer marked
        this way as it causes error messages to be come unusable, and O(data) does not contain any information which can be
        used without having access to the account key or which are not public anyway.'
    type: dict
  dest:
    description:
      - The destination file for the certificate.
      - Required if O(fullchain_dest) is not specified.
    type: path
    aliases: ['cert']
  fullchain_dest:
    description:
      - The destination file for the full chain (that is, a certificate followed by chain of intermediate certificates).
      - Required if O(dest) is not specified.
    type: path
    aliases: ['fullchain']
  chain_dest:
    description:
      - If specified, the intermediate certificate will be written to this file.
    type: path
    aliases: ['chain']
  remaining_days:
    description:
      - The number of days the certificate must have left being valid. If RV(cert_days) < O(remaining_days), then it will
        be renewed. If the certificate is not renewed, module return values will not include RV(challenge_data).
      - To make sure that the certificate is renewed in any case, you can use the O(force) option.
    type: int
    default: 10
  deactivate_authzs:
    description:
      - Deactivate authentication objects (authz) after issuing a certificate, or when issuing the certificate failed.
      - Authentication objects are bound to an account key and remain valid for a certain amount of time, and can be used
        to issue certificates without having to re-authenticate the domain. This can be a security concern.
    type: bool
    default: false
  force:
    description:
      - Enforces the execution of the challenge and validation, even if an existing certificate is still valid for more than
        O(remaining_days).
      - This is especially helpful when having an updated CSR, for example with additional domains for which a new certificate
        is desired.
    type: bool
    default: false
  retrieve_all_alternates:
    description:
      - When set to V(true), will retrieve all alternate trust chains offered by the ACME CA. These will not be written to
        disk, but will be returned together with the main chain as RV(all_chains). See the documentation for the RV(all_chains)
        return value for details.
    type: bool
    default: false
  select_chain:
    description:
      - Allows to specify criteria by which an (alternate) trust chain can be selected.
      - The list of criteria will be processed one by one until a chain is found matching a criterium. If such a chain is
        found, it will be used by the module instead of the default chain.
      - If a criterium matches multiple chains, the first one matching will be returned. The order is determined by the ordering
        of the C(Link) headers returned by the ACME server and might not be deterministic.
      - Every criterium can consist of multiple different conditions, like O(select_chain[].issuer) and O(select_chain[].subject).
        For the criterium to match a chain, all conditions must apply to the same certificate in the chain.
      - This option can only be used with the C(cryptography) backend.
    type: list
    elements: dict
    version_added: '1.0.0'
    suboptions:
      test_certificates:
        description:
          - Determines which certificates in the chain will be tested.
          - V(all) tests all certificates in the chain (excluding the leaf, which is identical in all chains).
          - V(first) only tests the first certificate in the chain, that is the one which signed the leaf.
          - V(last) only tests the last certificate in the chain, that is the one furthest away from the leaf. Its issuer
            is the root certificate of this chain.
        type: str
        default: all
        choices: [first, last, all]
      issuer:
        description:
          - Allows to specify parts of the issuer of a certificate in the chain must have to be selected.
          - If O(select_chain[].issuer) is empty, any certificate will match.
          - 'An example value would be V({"commonName": "My Preferred CA Root"}).'
        type: dict
      subject:
        description:
          - Allows to specify parts of the subject of a certificate in the chain must have to be selected.
          - If O(select_chain[].subject) is empty, any certificate will match.
          - 'An example value would be V({"CN": "My Preferred CA Intermediate"}).'
        type: dict
      subject_key_identifier:
        description:
          - Checks for the SubjectKeyIdentifier extension. This is an identifier based on the private key of the intermediate
            certificate.
          - The identifier must be of the form V(A8:4A:6A:63:04:7D:DD:BA:E6:D1:39:B7:A6:45:65:EF:F3:A8:EC:A1).
        type: str
      authority_key_identifier:
        description:
          - Checks for the AuthorityKeyIdentifier extension. This is an identifier based on the private key of the issuer
            of the intermediate certificate.
          - The identifier must be of the form V(C4:A7:B1:A4:7B:2C:71:FA:DB:E1:4B:90:75:FF:C4:15:60:85:89:10).
        type: str
  include_renewal_cert_id:
    description:
      - Determines whether to request renewal of an existing certificate according to L(the ACME ARI draft 3,
        https://www.ietf.org/archive/id/draft-ietf-acme-ari-03.html#section-5).
      - This is only used when the certificate specified in O(dest) or O(fullchain_dest) already exists.
      - Generally you should use V(when_ari_supported) if you know that the ACME service supports a compatible draft (or final
        version, once it is out) of the ARI extension. V(always) should never be necessary. If you are not sure, or if you
        receive strange errors on invalid C(replaces) values in order objects, use V(never), which also happens to be the
        default.
      - ACME servers might refuse to create new orders with C(replaces) for certificates that already have an existing order.
        This can happen if this module is used to create an order, and then the playbook/role fails in case the challenges
        cannot be set up. If the playbook/role does not record the order data to continue with the existing order, but tries
        to create a new one on the next run, creating the new order might fail. If O(order_creation_error_strategy=fail)
        this will make the module fail. O(order_creation_error_strategy=auto) and
        O(order_creation_error_strategy=retry_without_replaces_cert_id) will avoid this by leaving away C(replaces)
        on retries.
      - If O(order_creation_error_strategy=fail), for the above reason, this option should only be set to a value different
        from V(never) if the role/playbook using it keeps track of order data accross restarts, or if it takes care to
        deactivate orders whose processing is aborted. Orders can be deactivated with the
        M(community.crypto.acme_certificate_deactivate_authz) module.
    type: str
    choices:
      never: Never send the certificate ID of the certificate to renew.
      when_ari_supported: Only send the certificate ID if the ARI endpoint is found in the ACME directory.
      always: Will always send the certificate ID of the certificate to renew.
    default: never
    version_added: 2.20.0
  profile:
    description:
      - Chose a specific profile for certificate selection. The available profiles depend on the CA.
      - See L(a blog post by Let's Encrypt, https://letsencrypt.org/2025/01/09/acme-profiles/) and
        L(draft-aaron-acme-profiles-00, https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/)
        for more information.
    type: str
    version_added: 2.24.0
  order_creation_error_strategy:
    description:
      - Selects the error handling strategy for ACME protocol errors if creating a new ACME order fails.
    type: str
    choices:
      auto:
        - An unspecified algorithm that tries to be clever.
        - Right now identical to V(retry_without_replaces_cert_id).
      always:
        - Always retry, until the limit in O(order_creation_max_retries) has been reached.
      fail:
        - Simply fail in case of errors. Do not attempt to retry.
        - This has been the default before community.crypto 2.24.0.
      retry_without_replaces_cert_id:
        - If O(include_renewal_cert_id) is present, creating the order will be tried again without C(replaces).
        - The only exception is an error of type C(urn:ietf:params:acme:error:alreadyReplaced), that indicates that
          the certificate was already replaced. This usually means something went wrong and the user should investigate.
    default: auto
    version_added: 2.24.0
  order_creation_max_retries:
    description:
      - Depending on the strategy selected in O(order_creation_error_strategy), will retry creating new orders
        for at most the specified amount of times.
    type: int
    default: 3
    version_added: 2.24.0
aR  
---
### Example with HTTP challenge ###

- name: Create a challenge for sample.com using a account key from a variable.
  community.crypto.acme_certificate:
    account_key_content: "{{ account_private_key }}"
    csr: /etc/pki/cert/csr/sample.com.csr
    dest: /etc/httpd/ssl/sample.com.crt
  register: sample_com_challenge

# Alternative first step:
- name: Create a challenge for sample.com using a account key from Hashi Vault.
  community.crypto.acme_certificate:
    account_key_content: >-
      {{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/account_private_key:value') }}
    csr: /etc/pki/cert/csr/sample.com.csr
    fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
  register: sample_com_challenge

# Alternative first step:
- name: Create a challenge for sample.com using a account key file.
  community.crypto.acme_certificate:
    account_key_src: /etc/pki/cert/private/account.key
    csr_content: "{{ lookup('file', '/etc/pki/cert/csr/sample.com.csr') }}"
    dest: /etc/httpd/ssl/sample.com.crt
    fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
  register: sample_com_challenge

# perform the necessary steps to fulfill the challenge
# for example:
#
# - name: Copy http-01 challenge for sample.com
#   ansible.builtin.copy:
#     dest: /var/www/html/{{ sample_com_challenge['challenge_data']['sample.com']['http-01']['resource'] }}
#     content: "{{ sample_com_challenge['challenge_data']['sample.com']['http-01']['resource_value'] }}"
#   when: sample_com_challenge is changed and 'sample.com' in sample_com_challenge['challenge_data']
#
# Alternative way:
#
# - name: Copy http-01 challenges
#   ansible.builtin.copy:
#     dest: /var/www/{{ item.key }}/{{ item.value['http-01']['resource'] }}
#     content: "{{ item.value['http-01']['resource_value'] }}"
#   loop: "{{ sample_com_challenge.challenge_data | dict2items }}"
#   when: sample_com_challenge is changed

- name: Let the challenge be validated and retrieve the cert and intermediate certificate
  community.crypto.acme_certificate:
    account_key_src: /etc/pki/cert/private/account.key
    csr: /etc/pki/cert/csr/sample.com.csr
    dest: /etc/httpd/ssl/sample.com.crt
    fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
    chain_dest: /etc/httpd/ssl/sample.com-intermediate.crt
    data: "{{ sample_com_challenge }}"

---
### Example with DNS challenge against production ACME server ###

- name: Create a challenge for sample.com using a account key file.
  community.crypto.acme_certificate:
    account_key_src: /etc/pki/cert/private/account.key
    account_email: myself@sample.com
    src: /etc/pki/cert/csr/sample.com.csr
    cert: /etc/httpd/ssl/sample.com.crt
    challenge: dns-01
    acme_directory: https://acme-v01.api.letsencrypt.org/directory
    # Renew if the certificate is at least 30 days old
    remaining_days: 60
  register: sample_com_challenge

# perform the necessary steps to fulfill the challenge
# for example:
#
# - name: Create DNS record for sample.com dns-01 challenge
#   community.aws.route53:
#     zone: sample.com
#     record: "{{ sample_com_challenge.challenge_data['sample.com']['dns-01'].record }}"
#     type: TXT
#     ttl: 60
#     state: present
#     wait: true
#     # Note: route53 requires TXT entries to be enclosed in quotes
#     value: "{{ sample_com_challenge.challenge_data['sample.com']['dns-01'].resource_value | community.dns.quote_txt(always_quote=true) }}"
#   when: sample_com_challenge is changed and 'sample.com' in sample_com_challenge.challenge_data
#
# Alternative way:
#
# - name: Create DNS records for dns-01 challenges
#   community.aws.route53:
#     zone: sample.com
#     record: "{{ item.key }}"
#     type: TXT
#     ttl: 60
#     state: present
#     wait: true
#     # Note: item.value is a list of TXT entries, and route53
#     # requires every entry to be enclosed in quotes
#     value: "{{ item.value | map('community.dns.quote_txt', always_quote=true) | list }}"
#   loop: "{{ sample_com_challenge.challenge_data_dns | dict2items }}"
#   when: sample_com_challenge is changed

- name: Let the challenge be validated and retrieve the cert and intermediate certificate
  community.crypto.acme_certificate:
    account_key_src: /etc/pki/cert/private/account.key
    account_email: myself@sample.com
    src: /etc/pki/cert/csr/sample.com.csr
    cert: /etc/httpd/ssl/sample.com.crt
    fullchain: /etc/httpd/ssl/sample.com-fullchain.crt
    chain: /etc/httpd/ssl/sample.com-intermediate.crt
    challenge: dns-01
    acme_directory: https://acme-v01.api.letsencrypt.org/directory
    remaining_days: 60
    data: "{{ sample_com_challenge }}"
  when: sample_com_challenge is changed

# Alternative second step:
- name: Let the challenge be validated and retrieve the cert and intermediate certificate
  community.crypto.acme_certificate:
    account_key_src: /etc/pki/cert/private/account.key
    account_email: myself@sample.com
    src: /etc/pki/cert/csr/sample.com.csr
    cert: /etc/httpd/ssl/sample.com.crt
    fullchain: /etc/httpd/ssl/sample.com-fullchain.crt
    chain: /etc/httpd/ssl/sample.com-intermediate.crt
    challenge: tls-alpn-01
    remaining_days: 60
    data: "{{ sample_com_challenge }}"
    # We use Let's Encrypt's ACME v2 endpoint
    acme_directory: https://acme-v02.api.letsencrypt.org/directory
    acme_version: 2
    # The following makes sure that if a chain with /CN=DST Root CA X3 in its issuer is provided
    # as an alternative, it will be selected. These are the roots cross-signed by IdenTrust.
    # As long as Let's Encrypt provides alternate chains with the cross-signed root(s) when
    # switching to their own ISRG Root X1 root, this will use the chain ending with a cross-signed
    # root. This chain is more compatible with older TLS clients.
    select_chain:
      - test_certificates: last
        issuer:
          CN: DST Root CA X3
          O: Digital Signature Trust Co.
  when: sample_com_challenge is changed
aq  
cert_days:
  description: The number of days the certificate remains valid.
  returned: success
  type: int
challenge_data:
  description:
    - Per identifier / challenge type challenge data.
    - Since Ansible 2.8.5, only challenges which are not yet valid are returned.
  returned: changed
  type: dict
  contains:
    identifier:
      description:
        - For every identifier, provides a dictionary of challenge types mapping to challenge data.
        - The keys in this dictionary are the identifiers. C(identifier) is a placeholder used in the documentation.
        - Note that the keys are not valid Jinja2 identifiers.
      returned: changed
      type: dict
      contains:
        challenge-type:
          description:
            - Data for every challenge type.
            - The keys in this dictionary are the challenge types. C(challenge-type) is a placeholder used in the documentation.
              Possible keys are V(http-01), V(dns-01), and V(tls-alpn-01).
            - Note that the keys are not valid Jinja2 identifiers.
          returned: changed
          type: dict
          contains:
            resource:
              description: The challenge resource that must be created for validation.
              returned: changed
              type: str
              sample: .well-known/acme-challenge/evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA
            resource_original:
              description:
                - The original challenge resource including type identifier for V(tls-alpn-01) challenges.
              returned: changed and O(challenge) is V(tls-alpn-01)
              type: str
              sample: DNS:example.com
            resource_value:
              description:
                - The value the resource has to produce for the validation.
                - For V(http-01) and V(dns-01) challenges, the value can be used as-is.
                - For V(tls-alpn-01) challenges, note that this return value contains a Base64 encoded version of the correct
                  binary blob which has to be put into the acmeValidation x509 extension; see U(https://www.rfc-editor.org/rfc/rfc8737.html#section-3)
                  for details. To do this, you might need the P(ansible.builtin.b64decode#filter) Jinja filter to extract
                  the binary blob from this return value.
              returned: changed
              type: str
              sample: IlirfxKKXA...17Dt3juxGJ-PCt92wr-oA
            record:
              description: The full DNS record's name for the challenge.
              returned: changed and challenge is V(dns-01)
              type: str
              sample: _acme-challenge.example.com
challenge_data_dns:
  description:
    - List of TXT values per DNS record, in case challenge is V(dns-01).
    - Since Ansible 2.8.5, only challenges which are not yet valid are returned.
  returned: changed
  type: dict
authorizations:
  description:
    - ACME authorization data.
    - Maps an identifier to ACME authorization objects. See U(https://tools.ietf.org/html/rfc8555#section-7.1.4).
  returned: changed
  type: dict
  sample:
    example.com:
      identifier:
        type: dns
        value: example.com
      status: valid
      expires: '2022-08-04T01:02:03.45Z'
      challenges:
        - url: https://example.org/acme/challenge/12345
          type: http-01
          status: valid
          token: A5b1C3d2E9f8G7h6
          validated: '2022-08-01T01:01:02.34Z'
      wildcard: false
order_uri:
  description: ACME order URI.
  returned: changed
  type: str
finalization_uri:
  description: ACME finalization URI.
  returned: changed
  type: str
account_uri:
  description: ACME account URI.
  returned: changed
  type: str
all_chains:
  description:
    - When O(retrieve_all_alternates) is set to V(true), the module will query the ACME server for alternate chains. This
      return value will contain a list of all chains returned, the first entry being the main chain returned by the server.
    - See L(Section 7.4.2 of RFC8555,https://tools.ietf.org/html/rfc8555#section-7.4.2) for details.
  returned: when certificate was retrieved and O(retrieve_all_alternates) is set to V(true)
  type: list
  elements: dict
  contains:
    cert:
      description:
        - The leaf certificate itself, in PEM format.
      type: str
      returned: always
    chain:
      description:
        - The certificate chain, excluding the root, as concatenated PEM certificates.
      type: str
      returned: always
    full_chain:
      description:
        - The certificate chain, excluding the root, but including the leaf certificate, as concatenated PEM certificates.
      type: str
      returned: always
N)ACMEAccount)
ACMEClientcreate_backendcreate_default_argspec)CertificateChain	Criteriumretrieve_acme_v1_certificate)Authorizationcombine_identifiernormalize_combined_identifiersplit_identifierwait_for_validation)ModuleFailException)
write_file)Order)compute_cert_id
pem_to_derzno challengec                   L    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zy)ACMECertificateClientz
    ACME client class. Uses an ACME account object and a CSR to
    start and validate ACME challenges and download the respective
    certificates.
    c           	      "	   || _         |j                  d   | _        |j                  d   | _        | j                  t        k(  rd | _        |j                  d   | _        |j                  d   | _        |j                  j                  d      | _        |j                  j                  d      | _	        |j                  j                  d      | _
        t        ||      | _        t        | j                        | _        | j                  j                  | _        |j                  d   | _        d | _        d	| _        d | _        | j                   r| j                   j                  d
      nd | _        d | _        g | _        |j                  d   | _        |j                  d   | _        |j                  d   | _        |j                  d   | _        | j                   j                  d   rtt7        | j                   j                  d         D ]O  \  }}	 | j,                  j9                  | j                  j:                  j=                  t?        ||                   Q | j0                  s| j                  j                  d      xs i j                  d      xs i }|stG        d      | j0                  |vr%tG        djE                  | j0                              |j                  d   }|s| j                  dkD  rg }|j                  d   r!|j9                  d|j                  d   z          | j                  jI                  ||j                  j                  d      |j                  j                  d      |      \  }	}
|
tG        d      d }|	s#|
r!|r| j                  jK                  |
|      \  }}
|	xs || _&        n	 | j
                  AtN        jP                  jS                  | j
                        stG        d!| j
                  z        | j                  j:                  jU                  | j
                  | j                  "      | _+        y # t@        $ r6}| j                   jC                  djE                  |             Y d }~d }~ww xY w)#Nacme_version	challengecsrcsr_contentdestfullchain_dest
chain_destdata	order_uriinclude_renewal_cert_idprofileorder_creation_error_strategyorder_creation_max_retriesselect_chain)indexz;Error while parsing criterium: {error}. Ignoring criterium.)errormetaprofilesz&The ACME CA does not support profiles.)msgz4The ACME CA does not support selected profile {0!r}.modify_account   account_emailzmailto:	agreementterms_agreed)r1   r2   allow_creationz)Account does not exist or is deactivated.FzCSR %s not found)csr_filenamer   ),moduleparamsversionr   NO_CHALLENGEr   r   getr   r   r    r   clientr   account	directoryr!   authorizations	cert_daysorderr#   
all_chainsselect_chain_matcherr$   r%   r&   r'   	enumerateappendbackendcreate_chain_matcherr   
ValueErrorwarnformatr   setup_accountupdate_accountchangedospathexistsget_ordered_csr_identifiersidentifiers)selfr5   rD   criterium_idx	criteriumexcmeta_profilesr.   contactcreatedaccount_dataupdateds               u/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/crypto/plugins/modules/acme_certificate.py__init__zACMECertificateClient.__init__e  s   }}^4{3>>\)!DN=='!==7MM%%f-	$mm//0@A --++L9 1"4;;/..MM&)	"
7;yy{3d$&!'-}}5N'O$}}Y/-3]]+.
* +1--8T*U';;n-,5"">2- (y--44++@@%i}E	  <<#!^^//7=2BB:NTRTM ).VWW||=0)NUU   '78T\\A-G}}_-y6==+IIJ$(LL$>$> --++K8#]]..~>-	 %? %!G\ #)C  G|(,(C(C ')% #-gDL 88txx(@%&8DHH&EFF  ;;..JJt/?/? K 
i " KK$$U\\"% ]  s   A	Q	R+R		Rc                 p    | j                   y| j                  dk(  r| j                    S | j                  du S )z
        Return True if this is the first execution of this module, i.e. if a
        sufficient data object from a first run has not been provided.
        NTr/   )r!   r7   r#   )rQ   s    rZ   is_first_stepz#ACMECertificateClient.is_first_step  s:    
 99<<1yy=  >>T))    c                 >   | j                   j                  j                  d      r| j                   j                  d   }n| j                   j                  d   }t        j                  j                  |      sy | j                  j                  j                  |      S )Nr   r   )cert_filename)	r5   r6   r9   rL   rM   rN   r:   rD   get_cert_information)rQ   filenames     rZ   _get_cert_info_or_nonez,ACMECertificateClient._get_cert_info_or_none  st    ;;!!&){{))&1H{{))*:;Hww~~h'{{""77h7OOr^   c           	         i | _         | j                  dk(  r| j                  D ]  \  }}|dk7  st        d       | j                  D ]H  \  }}t	        j
                  | j                  ||      }|| j                   t        |j                        <   J d| _        yd}| j                  dk(  s3| j                  dk(  rX| j                  j                  j                         r4| j                         }|"t        | j                  j                  |d      }t        j                   | j                  | j                  | j"                  | j$                  || j&                  | j(                  j*                  	      | _        | j,                  j.                  | _        | j,                  j3                  | j                         | j                   j5                  | j,                  j                          d| _        y)
z
        Create new authorizations for all identifiers of the CSR,
        respectively start a new order for ACME v2.
        r/   dnsz&ACME v1 only supports DNS identifiers!Nalwayswhen_ari_supportedT)	cert_info'none_if_required_information_is_missing)error_strategyerror_max_retriesreplaces_cert_idr%   message_callback)r=   r7   rP   r   r   creater:   r   combined_identifierr$   r<   has_renewal_info_endpointrc   r   rD   r   create_with_error_handlingr&   r'   r%   r5   rG   r?   urlr#   load_authorizationsupdaterK   )rQ   identifier_type
identifierauthzrl   rh   s         rZ   start_challengesz&ACMECertificateClient.start_challenges  s   
 !<<1/3/?/? X+"e+-.VWWX 04/?/? +%,,T[[/:V  ##1%2K2KL< 1  $++x7,,0DDKK))CCE 779	('6++"+@D($
 99  #AA"&"A"A!1!%!1!1DJ "ZZ^^DNJJ**4;;7&&tzz'@'@Ar^   c                    i }| j                   j                         D ]  \  }}t        |      \  }}|j                  dk(  r$|j	                  | j
                        ||j                  <   |sO| j                  \| j                  ||j                     vsxt        dj                  | j                  |             i }| j                  dk(  r|j                         D ]o  \  }}| j                  |v s|j                  || j                     d         }	|	g }	|	||| j                     d   <   |	j                  || j                     d          q ||fS )z
        Get challenge details for the chosen challenge type.
        Return a tuple of generic challenge details, and specialized DNS challenge details.
        validz4Found no challenge of type '{0}' for identifier {1}!dns-01recordresource_value)r=   itemsr   statusget_challenge_datar:   rv   r   r   rH   r9   rC   )
rQ   
first_stepr!   type_identifierrw   ru   rv   data_dns
challengesvaluess
             rZ   get_challenges_dataz)ACMECertificateClient.get_challenges_data  sS    &*&9&9&?&?&A 	"OU*:?*K'OZ ||w&%*%=%=dkk%JD!!"NN.NN$u/?/?*@@)JQQ 	& >>X%*.**, P&
J>>Z/%\\*T^^*DX*NOF~!#IODNN!;H!EFMM*T^^"<=M"NOP X~r^   c                 n   i | _         | j                  dk(  rO| j                  D ]?  \  }}t        j                  | j
                  ||      }|| j                   t        ||      <   A nt        j                  | j
                  | j                        | _
        | j                  j                  | j
                         | j                   j                  | j                  j                          g }| j                   j                         D ]  \  }}|j                  dk(  s| j                  :|j!                  | j
                  | j                  d       |j#                  |       n6|j                  dk7  r'|j%                  d| j
                  j&                         d	| _         t+        || j
                         y)
zC
        Verify challenges for all identifiers of the CSR.
        r/   pendingNF)waitrz   zCStatus is not "valid", even though no challenge should be necessaryr5   T)r=   r7   rP   r   rn   r:   r   r   from_urlr#   r?   rs   rt   r~   r   r   call_validaterC   raise_errorr5   rK   r   )rQ   ru   rv   rw   authzs_to_wait_forr   s         rZ   finish_challengesz'ACMECertificateClient.finish_challenges+  sn    ! <<1 04/?/? +%,,T[[/:V ##$6
$ST T^^DDJJJ**4;;7&&tzz'@'@A  &*&9&9&?&?&A 	$"OU||y(>>-''T^^%'P&--e4\\W,%%]#{{11 &   $	$ 	.<r^   c                    g }|j                   D ]4  }	 t        j                  | j                  |      }|j                  |       6 |S # t        $ r5}| j
                  j                  dj                  ||             Y d }~rd }~ww xY w)Nz8Error while downloading alternative certificate {0}: {1})	
alternatesr
   downloadr:   r   r5   rG   rH   rC   )rQ   certalternate_chains	alternatealt_certes         rZ   download_alternate_chainsz/ACMECertificateClient.download_alternate_chainsS  s     
	.I+44T[[)L ##H-
	.   '   NUU!1
 s    A	B+BBc                     t        | j                        D ]M  \  }}|D ]C  }|j                  |      s| j                  j	                  dj                  |             |c c S  O y )Nz&Found matching chain for criterium {0})rB   rA   matchr5   debugrH   )rQ   chainsrR   matcherchains        rZ   find_matching_chainz)ACMECertificateClient.find_matching_chainb  sh    &/0I0I&J 	!"M7 !=='KK%%@GGV !L!	! r^   c           	      ~   | j                   D ]  \  }}| j                  j                  t        t	        ||                  }|%t        dj                  t	        ||                  |j                  dk7  sk|j                  dj                  |j                        | j                          | j                  dk(  r6t        | j                  t        | j                  | j                              }nN| j                   j#                  | j                  t        | j                  | j                               t%        j&                  | j                  | j                   j(                        }| j                  j*                  d	   s| j,                  r| j/                  |      }| j                  j*                  d	   rF|j1                         g| _        |D ]+  }| j2                  j5                  |j1                                - | j,                  r5| j7                  |g|z         }|r|}n| j                  j9                  d
       |j:                  m|j:                  }|j<                  }	| j>                  rktA        | j                  | j>                  |jC                  d            r;| j                  jD                  jG                  | j>                        | _$        d| _%        | jL                  r}tA        | j                  | jL                  |djO                  |	      z   jC                  d            r;| j                  jD                  jG                  | jL                        | _$        d| _%        | jP                  rHtA        | j                  | jP                  djO                  |	      jC                  d            rd| _%        yyyy)z
        Request a new certificate and write it to the destination file.
        First verifies whether all authorizations are valid; if not, aborts
        with an error.
        Nz6Found no authorization information for "{identifier}"!)rv   rz   z$Status is "{status}" and not "valid")r   r   r/   retrieve_all_alternatesz#Found no matching alternative chainutf8T
))rP   r=   r9   r   r   r   rH   r   r   r5   r7   r   r:   r   r   r   r?   finalizer
   r   certificate_urir6   rA   r   to_jsonr@   rC   r   r   r   r   r   r   encoderD   get_cert_daysr>   rK   r   joinr    )
rQ   ru   rv   rw   r   r   	alt_chainmatching_chainpem_certr   s
             rZ   get_certificatez%ACMECertificateClient.get_certificatel  s    ,0+;+; 	'OZ''++-&
CE
 })LSS#5oz#R T  
 ||w&!!:AAAV;; " 	$ <<1/Z$2B2BCD JJZ$BRBR-ST#,,T[[$**:T:TUD""#<=,, $(#A#A$#G  ;;%%&?@'+||~&6DO%5 D	..y/@/@/BCD ,,%)%=%=tfGW>W%XN%-))*OP99 yyHJJEyyZTYY(? "&!4!4!B!B499!M#""z##DIIe,,44V<(
 "&!4!4!B!B4CVCV!W#:T__tyy/?.G.G.O$  $$% !r^   c                 "   | j                   j                         D ]c  }	 |j                  | j                         |j
                  dk7  s/| j                  j                  dj                  |j                               e y# t        $ r Y Sw xY w)z
        Deactivates all valid authz's. Does not raise exceptions.
        https://community.letsencrypt.org/t/authorization-deactivation/19860/2
        https://tools.ietf.org/html/rfc8555#section-7.5.2
        deactivatedz&Could not deactivate authz object {0}.)warningN)
r=   r   
deactivater:   	Exceptionr   r5   rG   rH   rr   )rQ   rw   s     rZ   deactivate_authzsz'ACMECertificateClient.deactivate_authzs  s     ((//1 		E  - ||},  DKKEIIV ! 		  s   B	BBN)__name__
__module____qualname____doc__r[   r]   rc   rx   r   r   r   r   r   r    r^   rZ   r   r   ^  sA    ]
~*P(T#J&=P I$Vr^   r   c                     t        d      } dg| j                  d   d<   | j                  t        dd      t        d	      t        d	      t        dd
      t        dddddt        g      t        d	      t        ddg      t        ddg      t        ddg      t        dd      t        dd
      t        dd
      t        dd
      t        ddt        t        ddg d      t        d	      t        d	      t        d	      t        d	                  t        dg dd      t        d	      t        ddg d       t        dd!      "       | j                  d#d$gg%       | j                  d&      }t        |d
      }	 |j                  j                  d#      r|j                  |j                  d#         }n|j                  |j                  d$         }|j                  d'   s||j                  d(   k  r|j                  r|j                  di i |)       y t        ||      }||_        t               }|j                         }|r|j!                          n\	 |j#                          |j%                          |j&                  |j&                  |d*<   |j                  d+   r|j)                          	 |j+                  |,      \  }}t               }	|j,                  j/                         D ]"  \  }
}|j1                         |	|j2                  <   $  |j                  d/|j4                  |	|j6                  r|j6                  j8                  nd |j:                  |j<                  j>                  |||j                  d-| y |j                  d
|.       y # |j                  d+   r|j)                          w w xY w# t@        $ r}|jC                  |       Y d }~y d }~ww xY w)0NT)with_certificatesrcr   aliasesbool)typedefaultstr)r   Fzhttp-01r{   ztls-alpn-01)r   r   choicesdictrM   r   )r   r   	fullchainr   int
   listall)firstlastr   )test_certificatesissuersubjectsubject_key_identifierauthority_key_identifier)r   elementsoptions)neverrg   rf   r   )r   r   r   auto)r   rf   failretry_without_replaces_cert_id   )r.   r0   r1   r2   r   r!   r   r   r    remaining_daysr   forcer   r(   r$   r%   r&   r'   r   r   )required_one_of)supports_check_moder   r   )rK   r=   challenge_datar>   r@   r   )r   )rK   r=   finalize_urir#   account_urir   challenge_data_dnsr>   )rK   r>   r   )"r	   argument_specupdate_argspecr   r8   rt   create_ansible_moduler   r6   r9   r   
check_mode	exit_jsonr   r>   r]   rx   r   r   r@   r   r   r=   r~   r   rv   rK   r?   r   r#   r:   r   r   do_fail)r   r5   rD   r>   r:   otherr]   r!   r   authskvr   s                rZ   mainr     s   *DAM5:GM&y1  6&E"vu5-F

 vvx0+?VgY73FE:. $&% @"&7O# (&)'+'7)-5)9
 !%=!

 % &*P'

 $(UA#>U ! +X %&
  
 00T0JFVU+G7==V$--fmmF.CDI--fmm<L.MNI==!Y?O1P%P
      #%#%'	 !  /vw?#,  & 4 4 6 ++-7002..0!,,8282C2CE,/!==)<="446!'!;!;}!;!Uh"11779 6DAq*+))+E!,,'6 !   
"NN#(>Dll!:!:PT$.. & 9 9#''/$..
 
 Ui@' "==)<="446 >(  			&s?   BO ,A O -;N* (C-O O *"OO 	O3O..O3__main__)(
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrL   Fansible_collections.community.crypto.plugins.module_utils.acme.accountr   Cansible_collections.community.crypto.plugins.module_utils.acme.acmer   r   r	   Kansible_collections.community.crypto.plugins.module_utils.acme.certificatesr
   r   r   Iansible_collections.community.crypto.plugins.module_utils.acme.challengesr   r   r   r   r   Eansible_collections.community.crypto.plugins.module_utils.acme.errorsr   Aansible_collections.community.crypto.plugins.module_utils.acme.ior   Eansible_collections.community.crypto.plugins.module_utils.acme.ordersr   Dansible_collections.community.crypto.plugins.module_utils.acme.utilsr   r   r8   objectr   r   r   r   r^   rZ   <module>r      s    A @ bH	N`v
p 
 
 
  Y W hF hVnb zF r^   