o
    ~j6hC                     @   s  d Z ddlZddlm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 ddlmZ dd	lmZ d
ZdZdZdZdd Zdd Zdd Z				d$ddZ				d$ddZd%ddZe
jfddZd%ddZd d! Z			d&d"d#ZdS )'a  OAuth 2.0 client.

This is a client for interacting with an OAuth 2.0 authorization server's
token endpoint.

For more information about the token endpoint, see
`Section 3.1 of rfc6749`_

.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
    N)_exponential_backoff)_helpers)credentials)
exceptions)jwt)metrics)	transportz!application/x-www-form-urlencodedzapplication/jsonz+urn:ietf:params:oauth:grant-type:jwt-bearerrefresh_tokenc              	   C   sp   |r|nd}t | trtj| |dzd| d | d}W n ttfy/   t	| }Y nw tj|| |d)aX  Translates an error response into an exception.

    Args:
        response_data (Mapping | str): The decoded response data.
        retryable_error Optional[bool]: A boolean indicating if an error is retryable.
            Defaults to False.

    Raises:
        google.auth.exceptions.RefreshError: The errors contained in response_data.
    F	retryablez{}: {}errorerror_description)

isinstancestrr   RefreshErrorformatgetKeyError
ValueErrorjsondumps)response_dataretryable_errorerror_details r   d/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/oauth2/_client.py_handle_error_response-   s   
r   c                    s   | t jv rdS z2|dpd}|dpd}t|tr t|ts#W dS h d t fdd||fD r7W dS W dS  tyC   Y dS w )	a;  Checks if a request can be retried by inspecting the status code
    and response body of the request.

    Args:
        status_code (int): The response status code.
        response_data (Mapping | str): The decoded response data.

    Returns:
      bool: True if the response is retryable. False otherwise.
    Tr    r   F>   server_errorinternal_failuretemporarily_unavailablec                 3   s    | ]}| v V  qd S )Nr   ).0eretryable_error_descriptionsr   r   	<genexpr>h   s    z_can_retry.<locals>.<genexpr>)r   DEFAULT_RETRYABLE_STATUS_CODESr   r   r   anyAttributeError)status_coder   
error_desc
error_coder   r#   r   
_can_retryJ   s    
r,   c                 C   s>   |  dd}|durt|trt|}t tj|d S dS )zParses the expiry field from a response into a datetime.

    Args:
        response_data (Mapping): The JSON-parsed response data.

    Returns:
        Optional[datetime]: The expiration or ``None`` if no expiration was
            specified.
    
expires_inN)seconds)r   r   r   intr   utcnowdatetime	timedelta)r   r-   r   r   r   _parse_expiryq   s   

r3   FTc              	   K   s  |rdt i}t|d}ndti}tj|d}|r%d||d< |r,|	| i }	d}
t
 }|D ]O}| dd|||d|}t|jdrP|jdn|j}zt|}	W n tye   |}	Y nw |jtjkrsd	|	d
f  S t|j|	d}
|r~|
sd|	|
f  S q6d|	|
fS )a  Makes a request to the OAuth 2.0 authorization server's token endpoint.
    This function doesn't throw on response errors.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        body (Mapping[str, str]): The parameters to send in the request body.
        access_token (Optional(str)): The access token needed to make the request.
        use_json (Optional(bool)): Use urlencoded format or json format for the
            content type. The default value is False.
        can_retry (bool): Enable or disable request retry behavior.
        headers (Optional[Mapping[str, str]]): The headers for the request.
        kwargs: Additional arguments passed on to the request method. The
            kwargs will be passed to `requests.request` method, see:
            https://docs.python-requests.org/en/latest/api/#requests.request.
            For example, you can use `cert=("cert_pem_path", "key_pem_path")`
            to set up client side SSL certificate, and use
            `verify="ca_bundle_path"` to set up the CA certificates for sever
            side SSL certificate verification.

    Returns:
        Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating
          if the request is successful, a mapping for the JSON-decoded response
          data and in the case of an error a boolean indicating if the error
          is retryable.
    zContent-Typezutf-8z	Bearer {}AuthorizationFPOST)methodurlheadersbodydecodeTN)r)   r   r   )_JSON_CONTENT_TYPEr   r   encode_URLENCODED_CONTENT_TYPEurllibparse	urlencoder   updater   ExponentialBackoffhasattrdatar:   loadsr   statushttp_clientOKr,   )request	token_urir9   access_tokenuse_json	can_retryr8   kwargsheaders_to_user   r   retries_responseresponse_bodyr   r   r    _token_endpoint_request_no_throw   sH   &


rT   c                 K   s6   t | ||f||||d|\}}	}
|st|	|
 |	S )al  Makes a request to the OAuth 2.0 authorization server's token endpoint.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        body (Mapping[str, str]): The parameters to send in the request body.
        access_token (Optional(str)): The access token needed to make the request.
        use_json (Optional(bool)): Use urlencoded format or json format for the
            content type. The default value is False.
        can_retry (bool): Enable or disable request retry behavior.
        headers (Optional[Mapping[str, str]]): The headers for the request.
        kwargs: Additional arguments passed on to the request method. The
            kwargs will be passed to `requests.request` method, see:
            https://docs.python-requests.org/en/latest/api/#requests.request.
            For example, you can use `cert=("cert_pem_path", "key_pem_path")`
            to set up client side SSL certificate, and use
            `verify="ca_bundle_path"` to set up the CA certificates for sever
            side SSL certificate verification.

    Returns:
        Mapping[str, str]: The JSON-decoded response data.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    )rK   rL   rM   r8   )rT   r   )rI   rJ   r9   rK   rL   rM   r8   rN   response_status_okr   r   r   r   r   _token_endpoint_request   s   '

rV   c           
   
   C   st   |t d}t| |||tjt id}z|d }W n ty0 } ztjd|dd}||d}~ww t|}	||	|fS )a  Implements the JWT Profile for OAuth 2.0 Authorization Grants.

    For more details, see `rfc7523 section 4`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        assertion (str): The OAuth 2.0 assertion.
        can_retry (bool): Enable or disable request retry behavior.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
            expiration, and additional data returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
    	assertion
grant_typerM   r8   rK   No access token in response.Fr
   N)	_JWT_GRANT_TYPErV   r   API_CLIENT_HEADER'token_request_access_token_sa_assertionr   r   r   r3   )
rI   rJ   rX   rM   r9   r   rK   
caught_excnew_excexpiryr   r   r   	jwt_grant  s(   



rb   c              
   C   s   |ddd}t | |tj||||dd}z|d }W n ty4 }	 ztjd|dd}
|
|	d	}	~	ww tj	|dd
}t
j
|d }||fS )a!  Call iam.generateIdToken endpoint to get ID token.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        iam_id_token_endpoint (str): The IAM ID token endpoint to use.
        signer_email (str): The signer email used to form the IAM
            generateIdToken endpoint.
        audience (str): The audience for the ID token.
        access_token (str): The access token used to call the IAM endpoint.

    Returns:
        Tuple[str, datetime]: The ID token and expiration.
    true)audienceincludeEmailuseEmailAzpT)rK   rL   tokenNo ID token in response.Fr
   Nverifyexp)rV   replacer   DEFAULT_UNIVERSE_DOMAINr   r   r   r   r   r:   r1   utcfromtimestamp)rI   iam_id_token_endpointsigner_emailrd   rK   universe_domainr9   r   id_tokenr_   r`   payloadra   r   r   r   #call_iam_generate_id_token_endpointB  s.   
rt   c              
   C   s   |t d}t| |||tjt id}z|d }W n ty0 } ztjd|dd}||d}~ww tj	|dd}	t
j
|	d	 }
||
|fS )
a:  Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
    requests an OpenID Connect ID Token instead of an access token.

    This is a variant on the standard JWT Profile that is currently unique
    to Google. This was added for the benefit of authenticating to services
    that require ID Tokens instead of access tokens or JWT bearer tokens.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorization server's token endpoint
            URI.
        assertion (str): JWT token signed by a service account. The token's
            payload must include a ``target_audience`` claim.
        can_retry (bool): Enable or disable request retry behavior.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]:
            The (encoded) Open ID Connect ID Token, expiration, and additional
            data returned by the endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    rW   rZ   rr   rh   Fr
   Nri   rk   )r\   rV   r   r]   #token_request_id_token_sa_assertionr   r   r   r   r:   r1   rn   )rI   rJ   rX   rM   r9   r   rr   r_   r`   rs   ra   r   r   r   id_token_jwt_grantr  s*   



rv   c              
   C   s\   z| d }W n t y } ztjd| dd}||d}~ww | d|}t| }|||| fS )aW  Extract tokens from refresh grant response.

    Args:
        response_data (Mapping[str, str]): Refresh grant response data.
        refresh_token (str): Current refresh token.

    Returns:
        Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token,
            refresh token, expiration, and additional data returned by the token
            endpoint. If response_data doesn't have refresh token, then the current
            refresh token will be returned.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    rK   r[   Fr
   Nr	   )r   r   r   r   r3   )r   r	   rK   r_   r`   ra   r   r   r   _handle_refresh_grant_response  s   rw   c           
      C   sF   t |||d}|rd||d< |r||d< t| |||d}	t|	|S )a&  Implements the OAuth 2.0 refresh token grant.

    For more details, see `rfc678 section 6`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        refresh_token (str): The refresh token to use to get a new access
            token.
        client_id (str): The OAuth 2.0 application's client ID.
        client_secret (str): The Oauth 2.0 appliaction's client secret.
        scopes (Optional(Sequence[str])): Scopes to request. If present, all
            scopes must be authorized for the refresh token. Useful if refresh
            token has a wild card scope (e.g.
            'https://www.googleapis.com/auth/any-api').
        rapt_token (Optional(str)): The reauth Proof Token.
        can_retry (bool): Enable or disable request retry behavior.

    Returns:
        Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access
            token, new or current refresh token, expiration, and additional data
            returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
    )rY   	client_idclient_secretr	    scoperapt)rM   )_REFRESH_GRANT_TYPEjoinrV   rw   )
rI   rJ   r	   rx   ry   scopes
rapt_tokenrM   r9   r   r   r   r   refresh_grant  s   *
r   )NFTN)T)NNT)__doc__r1   http.clientclientrG   r   r>   google.authr   r   r   r   r   r   r   r=   r;   r\   r}   r   r,   r3   rT   rV   rb   rm   rt   rv   rw   r   r   r   r   r   <module>   sL   '
X

66

04%