o
    MfX                  
   @   s<  d Z ddlmZ ddlZddlZddlZddlZddlZzddlZW n e	y3 Z
 ze	de
dZ
[
ww 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Zdd	lmZ eeZd
ZG dd dejZG dd deZG dd dejZG dd dej j!Z"G dd dej j!Z#G dd dej$Z%dS )zTransport adapter for Requests.    )absolute_importNzmThe requests library is not installed from please install the requests package to use the requests transport.)create_urllib3_context)environment_vars)
exceptions)	transport)service_accountx   c                   @   s<   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )	_ResponsezuRequests transport response adapter.

    Args:
        response (requests.Response): The raw Requests response.
    c                 C   s
   || _ d S N)	_response)selfresponse r   `/var/www/html/analyze/labelStudio/lib/python3.10/site-packages/google/auth/transport/requests.py__init__7   s   
z_Response.__init__c                 C      | j jS r
   )r   status_coder   r   r   r   status:      z_Response.statusc                 C   r   r
   )r   headersr   r   r   r   r   >   r   z_Response.headersc                 C   r   r
   )r   contentr   r   r   r   dataB   r   z_Response.dataN)	__name__
__module____qualname____doc__r   propertyr   r   r   r   r   r   r   r	   0   s    

r	   c                   @   s0   e Zd ZdZejjfddZdd Zdd Z	dS )	TimeoutGuardaU  A context manager raising an error if the suite execution took too long.

    Args:
        timeout (Union[None, Union[float, Tuple[float, float]]]):
            The maximum number of seconds a suite can run without the context
            manager raising a timeout exception on exit. If passed as a tuple,
            the smaller of the values is taken as a timeout. If ``None``, a
            timeout error is never raised.
        timeout_error_type (Optional[Exception]):
            The type of the error to raise on timeout. Defaults to
            :class:`requests.exceptions.Timeout`.
    c                 C   s   || _ || _|| _d S r
   )_timeoutremaining_timeout_timeout_error_type)r   timeouttimeout_error_typer   r   r   r   U   s   
zTimeoutGuard.__init__c                 C   s   t   | _| S r
   )time_startr   r   r   r   	__enter__Z   s   
zTimeoutGuard.__enter__c                    s   |rd S | j d u rd S t | j  d}t| j tjr'| j   | _| jdk}nt fdd| j D | _t| jdk}|rA| 	 d S )NFr   c                 3   s    | ]}|  V  qd S r
   r   ).0xelapsedr   r   	<genexpr>l   s    z(TimeoutGuard.__exit__.<locals>.<genexpr>)
r   r$   r%   
isinstancenumbersNumberr    tupleminr!   )r   exc_type	exc_value	tracebackdeadline_hitr   r)   r   __exit__^   s   
zTimeoutGuard.__exit__N)
r   r   r   r   requestsr   Timeoutr   r&   r5   r   r   r   r   r   G   s
    r   c                   @   s4   e Zd ZdZd
ddZdd Zdddefdd	ZdS )Requesta  Requests request adapter.

    This class is used internally for making requests using various transports
    in a consistent way. If you use :class:`AuthorizedSession` you do not need
    to construct or use this class directly.

    This class can be useful if you want to manually refresh a
    :class:`~google.auth.credentials.Credentials` instance::

        import google.auth.transport.requests
        import requests

        request = google.auth.transport.requests.Request()

        credentials.refresh(request)

    Args:
        session (requests.Session): An instance :class:`requests.Session` used
            to make HTTP requests. If not specified, a session will be created.

    .. automethod:: __call__
    Nc                 C   s   |st  }|| _d S r
   )r6   Sessionsession)r   r:   r   r   r   r      s   
zRequest.__init__c                 C   sF   zt | dr| jd ur| j  W d S W d S W d S  ty"   Y d S w )Nr:   )hasattrr:   close	TypeErrorr   r   r   r   __del__   s   zRequest.__del__GETc           
   
   K   sd   zt d|| | jj||f|||d|}t|W S  tjjy1 } zt|}	|	|d}~ww )aR  Make an HTTP request using requests.

        Args:
            url (str): The URI to be requested.
            method (str): The HTTP method to use for the request. Defaults
                to 'GET'.
            body (bytes): The payload or body in HTTP request.
            headers (Mapping[str, str]): Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`~requests.Session.request` method.

        Returns:
            google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        zMaking request: %s %sr   r   r"   N)	_LOGGERdebugr:   requestr	   r6   r   RequestExceptionTransportError)
r   urlmethodbodyr   r"   kwargsr   
caught_excnew_excr   r   r   __call__   s   

zRequest.__call__r
   )r   r   r   r   r   r>   _DEFAULT_TIMEOUTrL   r   r   r   r   r8   s   s    
r8   c                       8   e Zd ZdZ fddZ fddZ fddZ  ZS )_MutualTlsAdaptera7  
    A TransportAdapter that enables mutual TLS.

    Args:
        cert (bytes): client certificate in PEM format
        key (bytes): client private key in PEM format

    Raises:
        ImportError: if certifi or pyOpenSSL is not installed
        OpenSSL.crypto.Error: if client cert or key is invalid
    c           
         s   dd l }ddlm} dd l}|jj  ||j|}|	|j|}t
 }|j| d |j| |j| || _t
 }	|	j| d |	j| |	j| |	| _tt|   d S )Nr   )cryptocafile)certifiOpenSSLrP   urllib3.contrib.pyopensslcontrib	pyopensslinject_into_urllib3load_privatekeyFILETYPE_PEMload_certificater   load_verify_locationswhere_ctxuse_certificateuse_privatekey_ctx_poolmanager_ctx_proxymanagersuperrO   r   )
r   certkeyrS   rP   urllib3pkeyx509ctx_poolmanagerctx_proxymanager	__class__r   r   r      s"   z_MutualTlsAdapter.__init__c                    $   | j |d< tt| j|i | d S Nssl_context)ra   rc   rO   init_poolmanagerr   argsrI   rk   r   r   rp         
z"_MutualTlsAdapter.init_poolmanagerc                        | j |d< tt| j|i |S rn   )rb   rc   rO   proxy_manager_forrq   rk   r   r   ru         
z#_MutualTlsAdapter.proxy_manager_forr   r   r   r   r   rp   ru   __classcell__r   r   rk   r   rO      s
    rO   c                       rN   )_MutualTlsOffloadAdaptera  
    A TransportAdapter that enables mutual TLS and offloads the client side
    signing operation to the signing library.

    Args:
        enterprise_cert_file_path (str): the path to a enterprise cert JSON
            file. The file should contain the following field:

                {
                    "libs": {
                        "signer_library": "...",
                        "offload_library": "..."
                    }
                }

    Raises:
        ImportError: if certifi or pyOpenSSL is not installed
        google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
            creation failed for any reason.
    c                    s   dd l }dd l}ddlm} |jj  ||| _| j	  t
 }|j| d | j| || _t
 }|j| d | j| || _tt|   d S )Nr   )_custom_tls_signerrQ   )rS   rU   google.auth.transportrz   rV   rW   rX   CustomTlsSignersignerload_librariesr   r\   r]   attach_to_ssl_contextra   rb   rc   ry   r   )r   enterprise_cert_file_pathrS   rf   rz   poolmanagerproxymanagerrk   r   r   r     s   
z!_MutualTlsOffloadAdapter.__init__c                    rm   rn   )ra   rc   ry   rp   rq   rk   r   r   rp   "  rs   z)_MutualTlsOffloadAdapter.init_poolmanagerc                    rt   rn   )rb   rc   ry   ru   rq   rk   r   r   ru   &  rv   z*_MutualTlsOffloadAdapter.proxy_manager_forrw   r   r   rk   r   ry      s
    ry   c                       sh   e Zd ZdZejejdddf fdd	ZdddZddde	f fdd	Z
ed	d
 Z fddZ  ZS )AuthorizedSessiona"  A Requests Session class with credentials.

    This class is used to perform requests to API endpoints that require
    authorization::

        from google.auth.transport.requests import AuthorizedSession

        authed_session = AuthorizedSession(credentials)

        response = authed_session.request(
            'GET', 'https://www.googleapis.com/storage/v1/b')


    The underlying :meth:`request` implementation handles adding the
    credentials' headers to the request and refreshing credentials as needed.

    This class also supports mutual TLS via :meth:`configure_mtls_channel`
    method. In order to use this method, the `GOOGLE_API_USE_CLIENT_CERTIFICATE`
    environment variable must be explicitly set to ``true``, otherwise it does
    nothing. Assume the environment is set to ``true``, the method behaves in the
    following manner:

    If client_cert_callback is provided, client certificate and private
    key are loaded using the callback; if client_cert_callback is None,
    application default SSL credentials will be used. Exceptions are raised if
    there are problems with the certificate, private key, or the loading process,
    so it should be called within a try/except block.

    First we set the environment variable to ``true``, then create an :class:`AuthorizedSession`
    instance and specify the endpoints::

        regular_endpoint = 'https://pubsub.googleapis.com/v1/projects/{my_project_id}/topics'
        mtls_endpoint = 'https://pubsub.mtls.googleapis.com/v1/projects/{my_project_id}/topics'

        authed_session = AuthorizedSession(credentials)

    Now we can pass a callback to :meth:`configure_mtls_channel`::

        def my_cert_callback():
            # some code to load client cert bytes and private key bytes, both in
            # PEM format.
            some_code_to_load_client_cert_and_key()
            if loaded:
                return cert, key
            raise MyClientCertFailureException()

        # Always call configure_mtls_channel within a try/except block.
        try:
            authed_session.configure_mtls_channel(my_cert_callback)
        except:
            # handle exceptions.

        if authed_session.is_mtls:
            response = authed_session.request('GET', mtls_endpoint)
        else:
            response = authed_session.request('GET', regular_endpoint)


    You can alternatively use application default SSL credentials like this::

        try:
            authed_session.configure_mtls_channel()
        except:
            # handle exceptions.

    Args:
        credentials (google.auth.credentials.Credentials): The credentials to
            add to the request.
        refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
            that credentials should be refreshed and the request should be
            retried.
        max_refresh_attempts (int): The maximum number of times to attempt to
            refresh the credentials and retry the request.
        refresh_timeout (Optional[int]): The timeout value in seconds for
            credential refresh HTTP requests.
        auth_request (google.auth.transport.requests.Request):
            (Optional) An instance of
            :class:`~google.auth.transport.requests.Request` used when
            refreshing credentials. If not passed,
            an instance of :class:`~google.auth.transport.requests.Request`
            is created.
        default_host (Optional[str]): A host like "pubsub.googleapis.com".
            This is used when a self-signed JWT is created from service
            account credentials.
    Nc                    s   t t|   || _|| _|| _|| _d| _|| _|d u r6t	
 | _t	jjdd}| jd| t| j}nd | _|| _t| jtjrT| j| jrOd| jnd  d S d S )NF   )max_retrieshttps://zhttps://{}/)rc   r   r   credentials_refresh_status_codes_max_refresh_attempts_refresh_timeout_is_mtls_default_hostr6   r9   _auth_request_sessionadaptersHTTPAdaptermountr8   _auth_requestr,   r   Credentials_create_self_signed_jwtformat)r   r   refresh_status_codesmax_refresh_attemptsrefresh_timeoutauth_requestdefault_hostretry_adapterrk   r   r   r     s&   	
zAuthorizedSession.__init__c           	   
   C   s   t tjd}|dkrd| _dS zddl}W n ty* } zt|}||d}~ww z t	j
jj|\| _}}| jrIt||}| d| W dS W dS  tjt|jjfye } zt|}||d}~ww )a  Configure the client certificate and key for SSL connection.

        The function does nothing unless `GOOGLE_API_USE_CLIENT_CERTIFICATE` is
        explicitly set to `true`. In this case if client certificate and key are
        successfully obtained (from the given client_cert_callback or from application
        default SSL credentials), a :class:`_MutualTlsAdapter` instance will be mounted
        to "https://" prefix.

        Args:
            client_cert_callback (Optional[Callable[[], (bytes, bytes)]]):
                The optional callback returns the client certificate and private
                key bytes both in PEM format.
                If the callback is None, application default SSL credentials
                will be used.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
                creation failed for any reason.
        falsetrueFNr   r   )osgetenvr   !GOOGLE_API_USE_CLIENT_CERTIFICATEr   rT   ImportErrorr   MutualTLSChannelErrorgoogleauthr   _mtls_helperget_client_cert_and_keyrO   r   ClientCertErrorrP   Error)	r   client_cert_callbackuse_client_certrT   rJ   rK   rd   re   mtls_adapterr   r   r   configure_mtls_channel  sD   



z(AuthorizedSession.configure_mtls_channelc                    s  | dd}|dur| ni }	|du r| jntj| j|d}
|}t|}| j|
|||	 W d   n1 s9w   Y  |j}t|}t	t
| j||f||	|d|}W d   n1 saw   Y  |j}|j| jv r|| jk rtd|j|d | j |du r| jntj| j|d}
t|}| j|
 W d   n1 sw   Y  |j}| j||f|||||d d|S |S )	a  Implementation of Requests' request.

        Args:
            timeout (Optional[Union[float, Tuple[float, float]]]):
                The amount of time in seconds to wait for the server response
                with each individual request. Can also be passed as a tuple
                ``(connect_timeout, read_timeout)``. See :meth:`requests.Session.request`
                documentation for details.
            max_allowed_time (Optional[float]):
                If the method runs longer than this, a ``Timeout`` exception is
                automatically raised. Unlike the ``timeout`` parameter, this
                value applies to the total method execution time, even if
                multiple requests are made under the hood.

                Mind that it is not guaranteed that the timeout error is raised
                at ``max_allowed_time``. It might take longer, for example, if
                an underlying request takes a lot of time, but the request
                itself does not timeout, e.g. if a large file is being
                transmitted. The timout error will be raised after such
                request completes.
        _credential_refresh_attemptr   N)r"   r@   z;Refreshing credentials due to a %s response. Attempt %s/%s.   )r   r   max_allowed_timer"   r   )popcopyr   	functoolspartialr   r   before_requestr    rc   r   rC   r   r   r   rA   inforefresh)r   rG   rF   r   r   r   r"   rI   r   request_headersr   remaining_timeguardr   rk   r   r   rC     sj   &


	

zAuthorizedSession.requestc                 C   s   | j S )z3Indicates if the created SSL channel is mutual TLS.)r   r   r   r   r   is_mtlsS  s   zAuthorizedSession.is_mtlsc                    s&   | j d ur
| j   tt|   d S r
   )r   r<   rc   r   r   rk   r   r   r<   X  s   

zAuthorizedSession.closer
   )r   r   r   r   r   DEFAULT_REFRESH_STATUS_CODESDEFAULT_MAX_REFRESH_ATTEMPTSr   r   rM   rC   r   r   r<   rx   r   r   rk   r   r   +  s"    Y
+9q
r   )&r   
__future__r   r   loggingr-   r   r$   r6   r   rJ   requests.adaptersrequests.exceptions#requests.packages.urllib3.util.ssl_r   google.authr   r   r   "google.auth.transport._mtls_helperr   google.oauth2r   	getLoggerr   rA   rM   Responser	   objectr   r8   r   r   rO   ry   r9   r   r   r   r   r   <module>   sB   
,P.: