U
    [^R                     @   s,  d Z ddlZddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 zddlmZ W n  ek
r   ddlmZ Y nX d	Zd
Zdddddddddddddddddddddd d!d"d#d$d%Zed&d' e D Zeed(d' e D  d)d* ZejG d+d, d,ejejZG d-d. d.ejeZG d/d0 d0eZed1Zed2Zed3Zed4Z ed5Z!ed6Z"ed7Z#ed8Z$G d9d: d:eZ%e%d;Z&G d<d= d=ejZ'G d>d? d?ejZ(G d@dA dAejZ)G dBdC dCe)Z*G dDdE dEejZ+G dFdG dGe,Z-G dHdI dIe+Z.e(j/G dJdK dKe.Z0G dLdM dMe.Z1G dNdO dOe*Z2G dPdQ dQe+Z3G dRdS dSe)Z4G dTdU dUe+Z5e(j/G dVdW dWe5Z6G dXdY dYe5Z7G dZd[ d[e*Z8e(j/G d\d] d]ejZ9G d^d_ d_e*Z:e(j/G d`da daejZ;G dbdc dce+Z<G ddde dee*Z=e(j/G dfdg dge<Z>dS )hzACME protocol messages.    N
challenges)errors)fields)jws)util)Hashablezurn:acme:error:zurn:ietf:params:acme:error:z4The request specified an account that does not existzOThe request specified a certificate to be revoked that has already been revokedz2The CSR is unacceptable (e.g., due to a short key)z1The client sent an unacceptable anti-replay noncez>The JWS was signed by a public key the server does not supportz;The revocation reason provided is not allowed by the serverz@The JWS was signed with an algorithm the server does not supportz\Certification Authority Authorization (CAA) records forbid the CA from issuing a certificatezBSpecific error conditions are indicated in the "subproblems" arrayz?The server could not connect to the client to verify the domainzAThere was a problem with a DNS query during identifier validationz4The server could not validate a DNSSEC signed domainz;Response recieved didn't match the challenge's requirementsz1The provided email for a registration was invalidz$The provided contact URI was invalidz!The request message was malformedz9The server will not issue certificates for the identifierzLThe request attempted to finalize an order that is not ready to be finalizedz,There were too many requests of a given typez(The server experienced an internal errorz=The server experienced a TLS error during domain verificationz)The client lacks sufficient authorizationz@A contact URL for an account used an unsupported protocol schemez*The server could not resolve a domain namez'An identifier is of an unsupported typez,The server requires external account binding)ZaccountDoesNotExistZalreadyRevokedZbadCSRZbadNonceZbadPublicKeyZbadRevocationReasonZbadSignatureAlgorithmZcaaZcompoundZ
connectiondnsZdnssecZincorrectResponseZinvalidEmailZinvalidContactZ	malformedZrejectedIdentifierZorderNotReadyZrateLimitedZserverInternalZtlsZunauthorizedZunsupportedContactZunknownHostZunsupportedIdentifierexternalAccountRequiredc                 c   s   | ]\}}t | |fV  qd S N)ERROR_PREFIX.0nameZdesc r   //usr/lib/python3/dist-packages/acme/messages.py	<genexpr>8   s    r   c                 c   s   | ]\}}t | |fV  qd S r   )OLD_ERROR_PREFIXr   r   r   r   r   ;   s    c                 C   s,   t | tr(| jdk	r(t| jkp&t| jkS dS )z#Check if argument is an ACME error.NF)
isinstanceErrortypr   r   )errr   r   r   is_acme_error?   s    r   c                   @   sh   e Zd ZdZejddddZejdddZejdddZe	d	d
 Z
edd Zedd Zdd ZdS )r   zACME error.

    https://tools.ietf.org/html/draft-ietf-appsawg-http-problem-00

    :ivar unicode typ:
    :ivar unicode title:
    :ivar unicode detail:

    typeTzabout:blank	omitemptydefaulttitler   detailc                 K   s.   |t krtd| t| }| f d|i|S )zCreate an Error instance with an ACME Error code.

        :unicode code: An ACME error code, like 'dnssec'.
        :kwargs: kwargs to pass to Error.

        z4The supplied code: %s is not a known ACME error coder   )ERROR_CODES
ValueErrorr   )clscodekwargsr   r   r   r   	with_codeU   s    zError.with_codec                 C   s   t | jS )zHardcoded error description based on its type.

        :returns: Description if standard ACME error or ``None``.
        :rtype: unicode

        )ERROR_TYPE_DESCRIPTIONSgetr   selfr   r   r   descriptionc   s    zError.descriptionc                 C   s$   t | jdd }|tkr |S dS )zACME error code.

        Basically self.typ without the ERROR_PREFIX.

        :returns: error code if standard ACME code or ``None``.
        :rtype: unicode

        :N)strr   splitr    )r)   r#   r   r   r   r#   m   s    
z
Error.codec                 C   s(   d dd | j| j| j| jfD  S )Ns    :: c                 s   s"   | ]}|d k	r| ddV  qd S )Nasciibackslashreplace)encode)r   partr   r   r   r   }   s   z Error.__str__.<locals>.<genexpr>)joinr   r*   r   r   decoder(   r   r   r   __str__|   s    
zError.__str__N)__name__
__module____qualname____doc__joseFieldr   r   r   classmethodr%   propertyr*   r#   r5   r   r   r   r   r   F   s   	

	
r   c                       s\   e Zd ZdZdZeZ fddZdd Ze	dd Z
d	d
 Zdd Zdd Zdd Z  ZS )	_ConstantzACME constant.r   c                    s"   t t|   | | j|< || _d S r   )superr>   __init__POSSIBLE_NAMESr   r)   r   	__class__r   r   rA      s    
z_Constant.__init__c                 C   s   | j S r   r?   r(   r   r   r   to_partial_json   s    z_Constant.to_partial_jsonc                 C   s&   || j krtd| j| j | S )Nz{0} not recognized)rB   r:   ZDeserializationErrorformatr6   r"   jobjr   r   r   	from_json   s
    

z_Constant.from_jsonc                 C   s   d | jj| jS )Nz{0}({1}))rG   rE   r6   r   r(   r   r   r   __repr__   s    z_Constant.__repr__c                 C   s   t |t| o|j| jkS r   )r   r   r   r)   otherr   r   r   __eq__   s    z_Constant.__eq__c                 C   s   t | j| jfS r   )hashrE   r   r(   r   r   r   __hash__   s    z_Constant.__hash__c                 C   s
   | |k S r   r   rL   r   r   r   __ne__   s    z_Constant.__ne__)r6   r7   r8   r9   	__slots__NotImplementedrB   rA   rF   r<   rJ   rK   rN   rP   rQ   __classcell__r   r   rD   r   r>      s   
r>   c                   @   s   e Zd ZdZi ZdS )StatuszACME "status" field.Nr6   r7   r8   r9   rB   r   r   r   r   rU      s   rU   unknownpendingZ
processingZvalidZinvalidZrevokedZreadyZdeactivatedc                   @   s   e Zd ZdZi ZdS )IdentifierTypezACME identifier type.NrV   r   r   r   r   rY      s   rY   r	   c                   @   s*   e Zd ZdZejdejdZedZ	dS )
IdentifierzNACME identifier.

    :ivar IdentifierType typ:
    :ivar unicode value:

    r   decodervalueN)
r6   r7   r8   r9   r:   r;   rY   rJ   r   r]   r   r   r   r   rZ      s   rZ   c                   @   sj   e Zd ZdZi ZG dd dejZedd Z	edd Z
dd	 Zd
d Zdd Zdd Zedd ZdS )	Directoryz
Directory.c                       s   e Zd ZdZejdddZejdddZejdddZejdddZ	ejdddZ
 fd	d
Zedd Z fddZdd Z  ZS )zDirectory.MetazDirectory Meta.zterms-of-serviceTr   ZtermsOfServicewebsiteZcaaIdentitiesr
   c                    s2   t  fdd| D }ttj jf | d S )Nc                 3   s    | ]\}}  ||fV  qd S r   _internal_namer   kvr(   r   r   r      s     z*Directory.Meta.__init__.<locals>.<genexpr>)dictitemsr@   r^   MetarA   r)   r$   rD   r(   r   rA      s    zDirectory.Meta.__init__c                 C   s   | j p
| jS )zURL for the CA TOS)_terms_of_service_terms_of_service_v2r(   r   r   r   terms_of_service   s    zDirectory.Meta.terms_of_servicec                 #   s4   t tj|  D ]}|dkr(|dd  n|V  qd S )Nri      )r@   r^   rg   __iter__rC   rD   r   r   rm      s    zDirectory.Meta.__iter__c                 C   s   |dkrd| S |S )Nrk   _r   rC   r   r   r   ra      s    zDirectory.Meta._internal_name)r6   r7   r8   r9   r:   r;   ri   rj   r_   Zcaa_identitiesZexternal_account_requiredrA   r=   rk   rm   ra   rT   r   r   rD   r   rg      s   
rg   c                 C   s   t |d|S )Nresource_type)getattr)r"   keyr   r   r   
_canon_key   s    zDirectory._canon_keyc                 C   s"   |j }|| jkst|| j|< |S )zRegister resource.)ro   _REGISTERED_TYPESAssertionError)r"   Zresource_body_clsro   r   r   r   register   s    
zDirectory.registerc                 C   s   t || j}|| _d S r   )r   Zmap_keysrr   _jobj)r)   rI   Z
canon_jobjr   r   r   rA      s    zDirectory.__init__c              
   C   sN   z| | dd W S  tk
rH } ztt|d | W 5 d }~X Y nX d S )Nrn   -z: )replaceKeyErrorAttributeErrorr-   )r)   r   errorr   r   r   __getattr__   s    zDirectory.__getattr__c                 C   s4   z| j | | W S  tk
r.   tdY nX d S )NzDirectory field not found)rv   rr   ry   rC   r   r   r   __getitem__   s    zDirectory.__getitem__c                 C   s   | j S r   )rv   r(   r   r   r   rF      s    zDirectory.to_partial_jsonc                 C   s    | j |di |d< | |S )Nmeta)rg   rJ   poprH   r   r   r   rJ     s    zDirectory.from_jsonN)r6   r7   r8   r9   rs   r:   JSONObjectWithFieldsrg   r<   rr   ru   rA   r|   r}   rF   rJ   r   r   r   r   r^      s   

r^   c                   @   s   e Zd ZdZedZdS )ResourcezOACME Resource.

    :ivar acme.messages.ResourceBody body: Resource body.

    bodyN)r6   r7   r8   r9   r:   r;   r   r   r   r   r   r   	  s   r   c                   @   s   e Zd ZdZedZdS )ResourceWithURIzOACME Resource with URI.

    :ivar unicode uri: Location of the resource.

    uriN)r6   r7   r8   r9   r:   r;   r   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZdS )ResourceBodyzACME Resource Body.N)r6   r7   r8   r9   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZedd ZdS )ExternalAccountBindingzACME External Account Bindingc           	      C   sR   t |  }tj|}|d }tj	|tj
j|dtjjd||}| S )zLCreate External Account Binding Resource from contact details, kid and hmac.Z
newAccount)rq   N)jsondumpsrF   r1   r:   Zb64Z	b64decoder   ZJWSZsignZjwkZJWKOctZjwaZHS256)	r"   Zaccount_public_keyZkidZhmac_keyZ	directoryZkey_jsonZdecoded_hmac_keyurlZeabr   r   r   	from_data"  s      z ExternalAccountBinding.from_dataN)r6   r7   r8   r9   r<   r   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZejddejjdZejddddZ	ejddd	Z
ejd
dd	Zejddd	Zejddd	Zejddd	ZdZdZedddZdd Zedd Zedd ZdS )RegistrationzRegistration Resource Body.

    :ivar josepy.jwk.JWK key: Public key.
    :ivar tuple contact: Contact information following ACME spec,
        `tuple` of `unicode`.
    :ivar unicode agreement:

    rq   Tr   r\   contactr   r   	agreementr   statusZtermsOfServiceAgreedZonlyReturnExistingZexternalAccountBindingztel:zmailto:Nc                    sp   t |dd}|dk	r(| j|  |dk	rN| fdd|dD  t||d< |rf||d<  f |S )z2Create registration resource from contact details.r   r   Nc                    s   g | ]} j | qS r   )email_prefix)r   Zmailr"   r   r   
<listcomp>N  s     z*Registration.from_data.<locals>.<listcomp>,external_account_binding)listr   appendphone_prefixextendr.   tuple)r"   ZphoneZemailr   r$   Zdetailsr   r   r   r   G  s    zRegistration.from_datac                    s   t  fdd| jD S )Nc                 3   s(   | ] }|  r|t d  V  qd S r   )
startswithlen)r   r   prefixr   r   r   W  s   
z/Registration._filter_contact.<locals>.<genexpr>)r   r   )r)   r   r   r   r   _filter_contactV  s    zRegistration._filter_contactc                 C   s   |  | jS )z*All phones found in the ``contact`` field.)r   r   r(   r   r   r   phones[  s    zRegistration.phonesc                 C   s   |  | jS )z*All emails found in the ``contact`` field.)r   r   r(   r   r   r   emails`  s    zRegistration.emails)NNN)r6   r7   r8   r9   r:   r;   ZJWKrJ   rq   r   r   r   Zterms_of_service_agreedZonly_return_existingr   r   r   r<   r   r   r=   r   r   r   r   r   r   r   1  s"   

r   c                   @   s   e Zd ZdZdZeeZdS )NewRegistrationzNew registration.znew-regNr6   r7   r8   r9   ro   r   r   resourcer   r   r   r   r   f  s   r   c                   @   s   e Zd ZdZdZeeZdS )UpdateRegistrationzUpdate registration.ZregNr   r   r   r   r   r   m  s   r   c                   @   s<   e Zd ZdZejdejdZejdddZ	ejdddZ
dS )	RegistrationResourcezRegistration Resource.

    :ivar acme.messages.Registration body:
    :ivar unicode new_authzr_uri: Deprecated. Do not use.
    :ivar unicode terms_of_service: URL for the CA TOS.

    r   r[   new_authzr_uriTr   rk   N)r6   r7   r8   r9   r:   r;   r   rJ   r   r   rk   r   r   r   r   r   s  s   r   c                       s   e Zd ZdZdZejddddZejddddZejde	j
ded	Zejd
ddZejdej
ddd	Z fddZ fddZ fddZe fddZedd Zdd Z fddZdd Z  ZS )ChallengeBodya>  Challenge Resource Body.

    .. todo::
       Confusingly, this has a similar name to `.challenges.Challenge`,
       as well as `.achallenges.AnnotatedChallenge`. Please use names
       such as ``challb`` to distinguish instances of this class from
       ``achall``.

    :ivar acme.challenges.Challenge: Wrapped challenge.
        Conveniently, all challenge fields are proxied, i.e. you can
        call ``challb.x`` to get ``challb.chall.x`` contents.
    :ivar acme.messages.Status status:
    :ivar datetime.datetime validated:
    :ivar messages.Error error:

    )challr   TNr   r   r   )r\   r   r   	validatedr   r{   c                    s0   t  fdd| D }tt jf | d S )Nc                 3   s    | ]\}}  ||fV  qd S r   r`   rb   r(   r   r   r     s     z)ChallengeBody.__init__.<locals>.<genexpr>)re   rf   r@   r   rA   rh   rD   r(   r   rA     s    zChallengeBody.__init__c                    s   t t| | |S r   )r@   r   r1   ra   rC   rD   r   r   r1     s    zChallengeBody.encodec                    s"   t t|  }|| j  |S r   )r@   r   rF   updater   )r)   rI   rD   r   r   rF     s    zChallengeBody.to_partial_jsonc                    s$   t t| |}tj||d< |S )Nr   )r@   r   fields_from_jsonr   Z	ChallengerJ   )r"   rI   Zjobj_fieldsrD   r   r   r     s    zChallengeBody.fields_from_jsonc                 C   s   | j p
| jS )zThe URL of this challenge.)_url_urir(   r   r   r   r     s    zChallengeBody.uric                 C   s   t | j|S r   )rp   r   rC   r   r   r   r|     s    zChallengeBody.__getattr__c                 #   s2   t t|  D ]}|dkr&|dd  n|V  qd S )Nr   rl   )r@   r   rm   rC   rD   r   r   rm     s    zChallengeBody.__iter__c                 C   s   |dkrd| S |S )Nr   rn   r   rC   r   r   r   ra     s    zChallengeBody._internal_name)r6   r7   r8   r9   rR   r:   r;   r   r   rU   rJ   STATUS_PENDINGr   r   RFC3339Fieldr   r   r{   rA   r1   rF   r<   r   r=   r   r|   rm   ra   rT   r   r   rD   r   r     s.   
 
 
r   c                   @   s6   e Zd ZdZejdejdZedZ	e
dd ZdS )ChallengeResourcezChallenge Resource.

    :ivar acme.messages.ChallengeBody body:
    :ivar unicode authzr_uri: URI found in the 'up' ``Link`` header.

    r   r[   
authzr_uric                 C   s   | j jS )zThe URL of the challenge body.)r   r   r(   r   r   r   r     s    zChallengeResource.uriN)r6   r7   r8   r9   r:   r;   r   rJ   r   r   r=   r   r   r   r   r   r     s
   
r   c                   @   s   e Zd ZdZejdejddZejdddZ	ejdddZ
ejddejd	Zejd
ddZejdddZe	jdd Z	edd ZdS )Authorizationa^  Authorization Resource Body.

    :ivar acme.messages.Identifier identifier:
    :ivar list challenges: `list` of `.ChallengeBody`
    :ivar tuple combinations: Challenge combinations (`tuple` of `tuple`
        of `int`, as opposed to `list` of `list` from the spec).
    :ivar acme.messages.Status status:
    :ivar datetime.datetime expires:

    
identifierTr\   r   r   r   combinationsr   r   expireswildcardc                 C   s   t dd | D S )Nc                 s   s   | ]}t |V  qd S r   )r   rJ   )r   r   r   r   r   r     s     z+Authorization.challenges.<locals>.<genexpr>r   r]   r   r   r   r     s    zAuthorization.challengesc                    s   t  fdd jD S )z0Combinations with challenges instead of indices.c                 3   s$   | ]}t  fd d|D V  qdS )c                 3   s   | ]} j | V  qd S r   r   )r   idxr(   r   r   r     s     z@Authorization.resolved_combinations.<locals>.<genexpr>.<genexpr>Nr   )r   Zcombor(   r   r   r     s   z6Authorization.resolved_combinations.<locals>.<genexpr>)r   r   r(   r   r(   r   resolved_combinations  s    z#Authorization.resolved_combinationsN)r6   r7   r8   r9   r:   r;   rZ   rJ   r   r   r   rU   r   r   r   r   r   r\   r=   r   r   r   r   r   r     s   

r   c                   @   s   e Zd ZdZdZeeZdS )NewAuthorizationzNew authorization.z	new-authzNr   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZdZeeZdS )UpdateAuthorizationzUpdate authorization.ZauthzNr   r   r   r   r   r     s   r   c                   @   s.   e Zd ZdZejdejdZejdddZ	dS )AuthorizationResourcezAuthorization Resource.

    :ivar acme.messages.Authorization body:
    :ivar unicode new_cert_uri: Deprecated. Do not use.

    r   r[   new_cert_uriTr   N)
r6   r7   r8   r9   r:   r;   r   rJ   r   r   r   r   r   r   r     s   r   c                   @   s2   e Zd ZdZdZeeZej	dej
ejdZdS )CertificateRequestzACME new-cert request.

    :ivar josepy.util.ComparableX509 csr:
        `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`

    znew-certcsrr\   encoderN)r6   r7   r8   r9   ro   r   r   r   r:   r;   Z
decode_csrZ
encode_csrr   r   r   r   r   r     s   
r   c                   @   s$   e Zd ZdZedZedZdS )CertificateResourcea  Certificate Resource.

    :ivar josepy.util.ComparableX509 body:
        `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
    :ivar unicode cert_chain_uri: URI found in the 'up' ``Link`` header
    :ivar tuple authzrs: `tuple` of `AuthorizationResource`.

    cert_chain_uriauthzrsN)r6   r7   r8   r9   r:   r;   r   r   r   r   r   r   r     s   
r   c                   @   s<   e Zd ZdZdZeeZej	dej
ejdZe	dZdS )
Revocationz|Revocation message.

    :ivar .ComparableX509 certificate: `OpenSSL.crypto.X509` wrapped in
        `.ComparableX509`

    zrevoke-certcertificater   reasonN)r6   r7   r8   r9   ro   r   r   r   r:   r;   Zdecode_certZencode_certr   r   r   r   r   r   r   '  s   
  r   c                   @   s   e Zd ZdZejdddZejdejddZ	ejdddZ
ejdddZejd	ddZejd
ddZejddejdZejdd ZdS )Ordera  Order Resource Body.

    :ivar list of .Identifier: List of identifiers for the certificate.
    :ivar acme.messages.Status status:
    :ivar list of str authorizations: URLs of authorizations.
    :ivar str certificate: URL to download certificate as a fullchain PEM.
    :ivar str finalize: URL to POST to to request issuance once all
        authorizations have "valid" status.
    :ivar datetime.datetime expires: When the order expires.
    :ivar .Error error: Any error that occurred during finalization, if applicable.
    identifiersTr   r   r   authorizationsr   finalizer   r{   r   c                 C   s   t dd | D S )Nc                 s   s   | ]}t |V  qd S r   )rZ   rJ   )r   r   r   r   r   r   M  s     z$Order.identifiers.<locals>.<genexpr>r   r   r   r   r   r   K  s    zOrder.identifiersN)r6   r7   r8   r9   r:   r;   r   rU   rJ   r   r   r   r   r   r   r   r   r{   r\   r   r   r   r   r   6  s   
r   c                   @   sF   e Zd ZdZejdejdZejdddZ	edZ
ejdddZd	S )
OrderResourcea  Order Resource.

    :ivar acme.messages.Order body:
    :ivar str csr_pem: The CSR this Order will be finalized with.
    :ivar list of acme.messages.AuthorizationResource authorizations:
        Fully-fetched AuthorizationResource objects.
    :ivar str fullchain_pem: The fetched contents of the certificate URL
        produced once the order was finalized, if it's present.
    r   r[   csr_pemTr   r   fullchain_pemN)r6   r7   r8   r9   r:   r;   r   rJ   r   r   r   r   r   r   r   r   r   O  s
   	
r   c                   @   s   e Zd ZdZdZdS )NewOrderz
New order.z	new-orderN)r6   r7   r8   r9   ro   r   r   r   r   r   ^  s   r   )?r9   r   Zjosepyr:   ZsixZacmer   r   r   r   r   Zcollections.abcr   ImportErrorcollectionsr   r   r    re   rf   r&   r   r   Zpython_2_unicode_compatibler   r   ZJSONDeSerializabler>   rU   ZSTATUS_UNKNOWNr   ZSTATUS_PROCESSINGZSTATUS_VALIDZSTATUS_INVALIDZSTATUS_REVOKEDZSTATUS_READYZSTATUS_DEACTIVATEDrY   ZIDENTIFIER_FQDNrZ   r^   r   r   r   objectr   r   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s   !
<!G		5B"