o
    Mf>                  
   @   s:  d Z ddlmZ ddlZddlZddlZzddlZW n ey%   dZY nw z
ddlZddl	ZW n eyA Z
 zede
dZ
[
ww 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 eejed
krpejjZnejjZeeZG dd dejZG dd dejZdd Zdd ZG dd deZ dS )zTransport adapter for urllib3.    )absolute_importNzjThe urllib3 library is not installed from please install the urllib3 package to use the urllib3 transport.)version)environment_vars)
exceptions)	transport)service_accountz2.0.0c                   @   s<   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )	_Responsezurllib3 transport response adapter.

    Args:
        response (urllib3.response.HTTPResponse): The raw urllib3 response.
    c                 C   
   || _ d S N)	_response)selfresponse r   _/var/www/html/analyze/labelStudio/lib/python3.10/site-packages/google/auth/transport/urllib3.py__init__A      
z_Response.__init__c                 C      | j jS r
   )r   statusr   r   r   r   r   D      z_Response.statusc                 C   r   r
   )r   headersr   r   r   r   r   H   r   z_Response.headersc                 C   r   r
   )r   datar   r   r   r   r   L   r   z_Response.dataN)	__name__
__module____qualname____doc__r   propertyr   r   r   r   r   r   r   r   :   s    

r   c                   @   s$   e Zd ZdZdd Z	dddZdS )	Requesta#  urllib3 request adapter.

    This class is used internally for making requests using various transports
    in a consistent way. If you use :class:`AuthorizedHttp` 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.urllib3
        import urllib3

        http = urllib3.PoolManager()
        request = google.auth.transport.urllib3.Request(http)

        credentials.refresh(request)

    Args:
        http (urllib3.request.RequestMethods): An instance of any urllib3
            class that implements :class:`~urllib3.request.RequestMethods`,
            usually :class:`urllib3.PoolManager`.

    .. automethod:: __call__
    c                 C   r	   r
   )http)r   r   r   r   r   r   k   r   zRequest.__init__GETNc           
   
   K   sr   |dur||d< zt d|| | jj||f||d|}t|W S  tjjy8 } zt|}	|	|d}~ww )a=  Make an HTTP request using urllib3.

        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 / 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
                urllib3 default timeout will be used.
            kwargs: Additional arguments passed throught to the underlying
                urllib3 :meth:`urlopen` method.

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

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        NtimeoutzMaking request: %s %sbodyr   )	_LOGGERdebugr   requestr   urllib3r   	HTTPErrorTransportError)
r   urlmethodr"   r   r    kwargsr   
caught_excnew_excr   r   r   __call__n   s"   

zRequest.__call__)r   NNN)r   r   r   r   r   r.   r   r   r   r   r   Q   s
    r   c                   C   s"   t d urtjdt  dS t S )NCERT_REQUIRED)	cert_reqsca_certs)certifir&   PoolManagerwherer   r   r   r   _make_default_http   s   r5   c           	      C   s   ddl }ddlm} ddl}|jj  |jj	 }|j
| d ||j|}||j| }|j| |j| |j|d}|S )a  Create a mutual TLS HTTP connection with the given client cert and key.
    See https://github.com/urllib3/urllib3/issues/474#issuecomment-253168415

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

    Returns:
        urllib3.PoolManager: Mutual TLS HTTP connection.

    Raises:
        ImportError: If certifi or pyOpenSSL is not installed.
        OpenSSL.crypto.Error: If the cert or key is invalid.
    r   N)crypto)cafile)ssl_context)r2   OpenSSLr6   urllib3.contrib.pyopensslcontrib	pyopensslinject_into_urllib3utilssl_create_urllib3_contextload_verify_locationsr4   load_privatekeyFILETYPE_PEMload_certificate_ctxuse_certificateuse_privatekeyr3   )	certkeyr2   r6   r&   ctxpkeyx509r   r   r   r   _make_mutual_tls_http   s   rM   c                       st   e Zd ZdZdejejdf fdd	ZdddZdddZ	d	d
 Z
dd Zdd Zedd Zejdd Z  ZS )AuthorizedHttpa  A urllib3 HTTP class with credentials.

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

        from google.auth.transport.urllib3 import AuthorizedHttp

        authed_http = AuthorizedHttp(credentials)

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

    This class implements :class:`urllib3.request.RequestMethods` and can be
    used just like any other :class:`urllib3.PoolManager`.

    The underlying :meth:`urlopen` 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:`AuthorizedHttp`
    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_http = AuthorizedHttp(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:
            is_mtls = authed_http.configure_mtls_channel(my_cert_callback)
        except:
            # handle exceptions.

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

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

        try:
            is_mtls = authed_http.configure_mtls_channel()
        except:
            # handle exceptions.

    Args:
        credentials (google.auth.credentials.Credentials): The credentials to
            add to the request.
        http (urllib3.PoolManager): The underlying HTTP object to
            use to make requests. If not specified, a
            :class:`urllib3.PoolManager` instance will be constructed with
            sane defaults.
        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.
        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   |d u rt  | _d| _n|| _d| _|| _|| _|| _|| _t| j| _t	| jt
jr:| j| jr7d| jnd  tt|   d S )NFTzhttps://{}/)r5   r   _has_user_provided_httpcredentials_refresh_status_codes_max_refresh_attempts_default_hostr   _request
isinstancer   Credentials_create_self_signed_jwtformatsuperrN   r   )r   rP   r   refresh_status_codesmax_refresh_attemptsdefault_host	__class__r   r   r     s   zAuthorizedHttp.__init__c           	   
   C   s   t tjd}|dkrdS zddl}W n ty' } zt|}||d}~ww ztj	
|\}}}|r;t||| _nt | _W n tjt|jjfyZ } zt|}||d}~ww | jrgd| _tdt |S )aS  Configures mutual TLS channel using the given client_cert_callback or
        application default SSL credentials. The behavior is controlled by
        `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable.
        (1) If the environment variable value is `true`, the function returns True
        if the channel is mutual TLS and False otherwise. The `http` provided
        in the constructor will be overwritten.
        (2) If the environment variable is not set or `false`, the function does
        nothing and it always return False.

        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.

        Returns:
            True if the channel is mutual TLS and False otherwise.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
                creation failed for any reason.
        falsetrueFr   Nz1`http` provided in the constructor is overwritten)osgetenvr   !GOOGLE_API_USE_CLIENT_CERTIFICATEr9   ImportErrorr   MutualTLSChannelErrorr   _mtls_helperget_client_cert_and_keyrM   r   r5   ClientCertErrorr6   ErrorrO   warningswarnUserWarning)	r   client_cert_callbackuse_client_certr9   r,   r-   found_cert_keyrH   rI   r   r   r   configure_mtls_channel0  sF   


z%AuthorizedHttp.configure_mtls_channelc           	      K   s   | dd}|du r| j}| }| j| j||| | jj||f||d|}|j| j	v rW|| j
k rWtd|j|d | j
 | j| j | j||f|||d d|S |S )z$Implementation of urllib3's urlopen._credential_refresh_attemptr   Nr!   z;Refreshing credentials due to a %s response. Attempt %s/%s.   )r"   r   rq   )popr   copyrP   before_requestrT   r   urlopenr   rQ   rR   r#   inforefresh)	r   r*   r)   r"   r   r+   rq   request_headersr   r   r   r   rv   m  s@   	
	zAuthorizedHttp.urlopenc                 C   s
   | j  S Proxy to ``self.http``.)r   	__enter__r   r   r   r   r|     s   
zAuthorizedHttp.__enter__c                 C   s   | j |||S rz   )r   __exit__)r   exc_typeexc_valexc_tbr   r   r   r}     s   zAuthorizedHttp.__exit__c                 C   s*   t | dr| jd ur| j  d S d S d S )Nr   )hasattrr   clearr   r   r   r   __del__  s   zAuthorizedHttp.__del__c                 C   r   rz   r   r   r   r   r   r   r     s   zAuthorizedHttp.headersc                 C   s   || j _dS )r{   Nr   )r   valuer   r   r   r     s   r
   )NN)r   r   r   r   r   DEFAULT_REFRESH_STATUS_CODESDEFAULT_MAX_REFRESH_ATTEMPTSr   rp   rv   r|   r}   r   r   r   setter__classcell__r   r   r]   r   rN      s     U
 
=;
rN   )!r   
__future__r   loggingra   rj   r2   rd   r&   urllib3.exceptionsr,   	packagingr   google.authr   r   r   google.oauth2r   parse__version___request_methodsRequestMethodsr%   	getLoggerr   r#   Responser   r   r5   rM   rN   r   r   r   r   <module>   sF   

D!