
    )!                        d Z ddlZddlZddlZddlmZ ddlmZ ej                  Zej                  ZdZ	dZ
dZ ej                  e      Z G d de      Zd	 Z	 dd
lmZ ej&                  Zej(                  Zej*                  Z	 ddlmZ ej0                  Zej2                  ZereZeZnereZeZneZeZddZd Zd Zd ZddZ y# e$ r	 dZdZeZY Pw xY w# e$ r dZdZY @w xY w)z-Crypto-related routines for oauth2client_4_0.    N)_helpers)_pure_python_crypti,  iQ c                       e Zd ZdZy)AppIdentityErrorz!Error to indicate crypto failure.N)__name__
__module____qualname____doc__     1platform/bq/third_party/oauth2client_4_0/crypt.pyr   r   %   s    +r   r   c                      t        d      )Nz#pkcs12_key_as_pem requires OpenSSL.)NotImplementedError)argskwargss     r   _bad_pkcs12_key_as_pemr   )   s    
C
DDr   )_openssl_crypt)_pycrypto_cryptc                    ddd}|||d<   t        j                  t        j                  |            t        j                  t        j                  |            g}dj                  |      }| j	                  |      }|j                  t        j                  |             t        j                  t        |             dj                  |      S )aR  Make a signed JWT.

    See http://self-issued.info/docs/draft-jones-json-web-token.html.

    Args:
        signer: crypt.Signer, Cryptographic signer.
        payload: dict, Dictionary of data to convert to JSON and then sign.
        key_id: string, (Optional) Key ID header.

    Returns:
        string, The JWT for the payload.
    JWTRS256)typalgkid   .)	r   _urlsafe_b64encode_json_encodejoinsignappendloggerdebugstr)signerpayloadkey_idheadersegmentssigning_input	signatures          r   make_signed_jwtr+   K   s     7+Fu 	##H$9$9&$AB##H$9$9'$BCH IIh'MM*IOOH//	:;
LLX99Xr   c                 |    |D ]-  }t         j                  |d      }|j                  | |      s- y t        d      )a  Verifies signed content using a list of certificates.

    Args:
        message: string or bytes, The message to verify.
        signature: string or bytes, The signature on the message.
        certs: iterable, certificates in PEM format.

    Raises:
        AppIdentityError: If none of the certificates can verify the message
                          against the signature.
    T)is_x509_certNzInvalid token signature)Verifierfrom_stringverifyr   )messager*   certspemverifiers        r   _verify_signaturer5   j   sB     ''$'???7I.  4
55r   c                     |y| j                  d      }|t        dj                  |             ||k7  rt        dj                  |||             y)aA  Checks audience field from a JWT payload.

    Does nothing if the passed in ``audience`` is null.

    Args:
        payload_dict: dict, A dictionary containing a JWT payload.
        audience: string or NoneType, an audience to check for in
                  the JWT payload.

    Raises:
        AppIdentityError: If there is no ``'aud'`` field in the payload
                          dictionary but there is an ``audience`` to check.
        AppIdentityError: If the ``'aud'`` field in the payload dictionary
                          does not match the ``audience``.
    NaudzNo aud field in token: {0}z Wrong recipient, {0} != {1}: {2})getr   format)payload_dictaudienceaudience_in_payloads      r   _check_audiencer=      sn      &**51"(//=? 	?h&AHH< 9 : 	: 'r   c                    t        t        j                               }| j                  d      }|t        dj	                  |             | j                  d      }|t        dj	                  |             ||t
        z   k\  rt        dj	                  |             |t        z
  }||k  rt        dj	                  |||             |t        z   }||kD  rt        dj	                  |||             y)	a  Verifies the issued at and expiration from a JWT payload.

    Makes sure the current time (in UTC) falls between the issued at and
    expiration for the JWT (with some skew allowed for via
    ``CLOCK_SKEW_SECS``).

    Args:
        payload_dict: dict, A dictionary containing a JWT payload.

    Raises:
        AppIdentityError: If there is no ``'iat'`` field in the payload
                          dictionary.
        AppIdentityError: If there is no ``'exp'`` field in the payload
                          dictionary.
        AppIdentityError: If the JWT expiration is too far in the future (i.e.
                          if the expiration would imply a token lifetime
                          longer than what is allowed.)
        AppIdentityError: If the token appears to have been issued in the
                          future (up to clock skew).
        AppIdentityError: If the token appears to have expired in the past
                          (up to clock skew).
    iatNzNo iat field in token: {0}expzNo exp field in token: {0}z exp field too far in future: {0}z$Token used too early, {0} < {1}: {2}z#Token used too late, {0} > {1}: {2})inttimer8   r   r9   MAX_TOKEN_LIFETIME_SECSCLOCK_SKEW_SECS)r:   now	issued_at
expirationearliestlatests         r   _verify_time_rangerJ      s   0 diik
C   'I(//=? 	?!!%(J(//=? 	? S222.55lCE 	E ?*H
X~ELL< ) * 	* /)F
V|DKK ' ( 	( r   c                    t        j                  |       } | j                  d      dk7  rt        dj	                  |             | j                  d      \  }}}|dz   |z   }t        j                  |      }t        j                  |      }	 t        j                  t        j                  |            }t        |||j                                t        |       t        ||       |S #  t        dj	                  |            xY w)a  Verify a JWT against public certs.

    See http://self-issued.info/docs/draft-jones-json-web-token.html.

    Args:
        jwt: string, A JWT.
        certs: dict, Dictionary where values of public keys in PEM format.
        audience: string, The audience, 'aud', that this JWT should contain. If
                  None then the JWT's 'aud' parameter is not verified.

    Returns:
        dict, The deserialized JSON payload in the JWT.

    Raises:
        AppIdentityError: if any checks are failed.
    r      z&Wrong number of segments in token: {0}zCan't parse token: {0})r   	_to_bytescountr   r9   split_urlsafe_b64decodejsonloads_from_bytesr5   valuesrJ   r=   )	jwtr2   r;   r'   r%   r*   message_to_signpayload_bytesr:   s	            r   verify_signed_jwt_with_certsrX      s    " 

S
!C
yy!4;;C@B 	B "%4FGYtmg-O++I6I //8MPzz("6"6}"EF
 oy%,,.A |$ L(+P8??NOOs   (C( (D)N)!r
   rQ   loggingrB   oauth2client_4_0r   r   	RsaSignerRsaVerifierrD   AUTH_TOKEN_LIFETIME_SECSrC   	getLoggerr   r!   	Exceptionr   r   r   OpenSSLSignerOpenSSLVerifierpkcs12_key_as_pemImportErrorr   PyCryptoSignerPyCryptoVerifierSignerr.   r+   r5   r=   rJ   rX   r   r   r   <module>rg      s,  " 4    % / ((	 ,,  			8	$,y ,E//"00M$44O&880$33N&77 FHFHFH>6*:82(j+}  /OM./  Ns$   *C C CC	C$#C$