
    @wj0J                     4   d Z ddlm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
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  ej.                  e
j0                         ej.                  d      k\  re
j2                  j4                  Zne
j6                  j4                  Z ej8                  e      Z G d dej>                        Z  G d dejB                        Z!d Z"d Z# G d de      Z$y# e	$ r dZY w xY w# e	$ rZ e	de d      edZ[ww xY w)zTransport adapter for urllib3.    )absolute_importN)versionzError: aS  . The 'google-auth' library requires the extras installed for urllib3 network transport.
Please install the necessary dependencies using pip:
  pip install google-auth[urllib3]

(Note: Using '[urllib3]' ensures the specific dependencies needed for this feature are installed. We recommend running this command in your virtual environment.))_helpers)
exceptions)	transport)_mtls_helper)service_accountz2.0.0c                   F    e Zd ZdZd Zed        Zed        Zed        Zy)	_Responsezurllib3 transport response adapter.

    Args:
        response (urllib3.response.HTTPResponse): The raw urllib3 response.
    c                     || _         y N)	_response)selfresponses     [/root/dashboard-youtube/.venv/lib/python3.12/site-packages/google/auth/transport/urllib3.py__init__z_Response.__init__J   s	    !    c                 .    | j                   j                  S r   )r   statusr   s    r   r   z_Response.statusM   s    ~~$$$r   c                 .    | j                   j                  S r   )r   headersr   s    r   r   z_Response.headersQ   s    ~~%%%r   c                 .    | j                   j                  S r   )r   datar   s    r   r   z_Response.dataU   s    ~~"""r   N)	__name__
__module____qualname____doc__r   propertyr   r   r    r   r   r   r   C   sH    " % % & & # #r   r   c                        e Zd ZdZd Z	 ddZy)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.PoolManager): An instance of a urllib3 class that implements
            the request interface (e.g. :class:`urllib3.PoolManager`).

    .. automethod:: __call__
    c                     || _         y r   )http)r   r$   s     r   r   zRequest.__init__s   s	    	r   Nc                 R   |||d<   	 t        j                  t        ||||        | j                  j                  ||f||d|}t        j
                  t        |       t        |      S # t        j                  j                  $ r}t        j                  |      }	|	|d}~ww xY 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timeoutbodyr   )r   request_log_LOGGERr$   requestresponse_logr   urllib3r   	HTTPErrorTransportError)
r   urlmethodr(   r   r&   kwargsr   
caught_excnew_excs
             r   __call__zRequest.__call__v   s    2  'F9		*  &#tWE(tyy(("&;AH !!'84X&&!!++ 	* //
;Gz)	*s   A"A, ,B&	B!!B&)GETNNN)r   r   r   r   r   r5   r    r   r   r"   r"   Z   s    0 CG%*r   r"   c                      t         )t        j                  dt        j                               S t        j                         S )NCERT_REQUIRED)	cert_reqsca_certs)certifir-   PoolManagerwherer    r   r   _make_default_httpr>      s0    ""_w}}WW""$$r   c                    ddl }ddl}t        j                  j                  j                         }|j                   |j                                	 t        j                  | |      5 \  }}}|}|j                  |||       ddd       t        j&                  |      }
|
S # 1 sw Y   !xY w# |j                  t        t        t        t        t         f$ r}	t#        j$                  d      |	d}	~	ww xY w)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:
        google.auth.exceptions.MutualTLSChannelError: If the cert or key is invalid.
    r   N)cafile)certfilekeyfilepasswordz8Failed to configure client certificate and key for mTLS.)ssl_context)r;   sslr-   utilssl_create_urllib3_contextload_verify_locationsr=   r   secure_cert_key_pathsload_cert_chainSSLErrorOSErrorIOError
ValueErrorRuntimeError	TypeErrorr   MutualTLSChannelErrorr<   )certkeyr;   rE   ctx	cert_pathkey_path
passphraserC   excr$   s              r   _make_mutual_tls_httprZ      s     
,,


2
2
4C]W]]_5//c: 
	 ?
!H" !   
	  3/DK#
	 
	 LL'7JiP ..F
	s0   B0 )B$B0 $B-)B0 0)C4C//C4c                        e Zd ZdZdej
                  ej                  df fd	ZddZddZ	d Z
d Zd Zed	        Zej                  d
        Z x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 the urllib3 request interface 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                    |t               | _        d| _        n|| _        d| _        || _        || _        || _        || _        t        | j                        | _        d| _	        t        | j                  t        j                        rB| j                  j                  | j                  rdj                  | j                        nd        t        t         | G          y )NFTzhttps://{}/)r>   r$   _has_user_provided_httpcredentials_refresh_status_codes_max_refresh_attempts_default_hostr"   _request_is_mtls
isinstancer	   Credentials_create_self_signed_jwtformatsuperr\   r   )r   r_   r$   refresh_status_codesmax_refresh_attemptsdefault_host	__class__s         r   r   zAuthorizedHttp.__init__!  s     <*,DI+0D(DI+/D(&%9"%9")  		* d&&(C(CD44<@<N<N$$T%7%78TX 	nd,.r   c           
      x   t         j                  j                         }|sy	 t         j                  j                  |      \  }}}|rt	        ||      }d}nt               }d}| j                  }
|| _        || _        || j                  _        |
"|
|ur t        |
dt        |
dd                     |r|| _        nt#        | d      r| `| j$                  r!d| _        t'        j(                  dt*               |S # t        j                  t        t        t        f$ r}t        j                  |      }	|	|d}~ww xY w)	a  Configures mutual TLS channel using the given client_cert_callback or
        application default SSL credentials.

        The channel is configured if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true",
        or if it is unset and workload certificates are detected in the environment.
        If client_cert_callback is None, default SSL credentials (workload or SecureConnect)
        are loaded.

        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.

        .. warning::
            Calling this method mutates the underlying `urllib3.PoolManager`.
            It is not thread-safe to call this explicitly while other
            threads are making requests.

        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. The existing channel state (the
                HTTP client) remains unmodified if this error is raised.
        FTNclearclosec                       y r   r    r    r   r   <lambda>z7AuthorizedHttp.configure_mtls_channel.<locals>.<lambda>~      r   _cached_certz1`http` provided in the constructor is overwritten)r   r   check_use_client_certget_client_cert_and_keyrZ   r>   r   ClientCertErrorImportErrorrM   rO   rR   r$   rd   rc   getattrrt   hasattrr^   warningswarnUserWarning)r   client_cert_callbackuse_client_certfound_cert_keyrS   rT   new_httpnew_is_mtlsr3   r4   old_https              r   configure_mtls_channelz%AuthorizedHttp.configure_mtls_channelB  s7   : $00FFH	*(1(>(>(V(V$)%ND# 0s;"-/# 99	#%HH$<PGHgwx,'OPR $Dt^,%''+0D(MMC[ ; &&	
 	* !66zBGz)	*s   A C9 9#D9D44D9c                    |j                  dd      }|| j                  }d}| j                  rddg}t        |D 	cg c]  }	|	|v  c}	      }|j	                         }
| j
                  j                  | j                  |||
        | j                  j                  ||f||
d|}|j                  | j                  v r|| j                  k  r|j                  t        j                  k(  rm|rkt        j                   | j"                        \  }}||k7  r-	 t$        j'                  d       | j)                  fd	
       nt$        j'                  d       t$        j'                  d|j                  |dz   | j                         | j
                  j3                  | j                          | j                  ||f|||dz   d|S |S c c}	w # t*        $ r1}t$        j-                  d|       t/        j0                  d      |d}~ww xY w)z$Implementation of urllib3's urlopen._credential_refresh_attemptr   NFzmtls.googleapis.comzmtls.sandbox.googleapis.comr'   z;Client certificate has changed, reconfiguring mTLS channel.c                       fS r   r    )call_cert_bytescall_key_bytess   r   rr   z(AuthorizedHttp.urlopen.<locals>.<lambda>  s    $3$2>" r   )r~   z&Failed to reconfigure mTLS channel: %sz"Failed to reconfigure mTLS channelzXSkipping reconfiguration of mTLS channel because the client certificate has not changed.z;Refreshing credentials due to a %s response. Attempt %s/%s.   )r(   r   r   )popr   rd   anycopyr_   before_requestrc   r$   urlopenr   r`   ra   http_clientUNAUTHORIZEDr   *check_parameters_for_unauthorized_responsert   r*   infor   	Exceptionerrorr   rR   refresh)r   r1   r0   r(   r   r2   r   use_mtlsMTLS_URL_PREFIXESprefixrequest_headersr   cached_fingerprintcurrent_cert_fingerprinter   r   s                  @@r   r   zAuthorizedHttp.urlopen  s'    '-jj1NPQ&R#?llG==!68U V8IJfFcMJKH ",,.''vsOT$499$$C
"O
?E
 OOt999+d.H.HH+":":: %OO))'&*0 *-EE%#LL!+ !776" 8   B
 LLM+a/**	 $$T]]3  4<< ,G!,K   Y KZ  ) %#MM*RTUV","B"B D##$%%s   G+G 	H,HHc                 6    | j                   j                         S Proxy to ``self.http``.)r$   	__enter__r   s    r   r   zAuthorizedHttp.__enter__  s    yy""$$r   c                 <    | j                   j                  |||      S r   )r$   __exit__)r   exc_typeexc_valexc_tbs       r   r   zAuthorizedHttp.__exit__  s    yy!!(GV<<r   c           
          t        | d      r@| j                  3 t        | j                  dt        | j                  dd                     y y y )Nr$   ro   rp   c                       y r   r    r    r   r   rr   z(AuthorizedHttp.__del__.<locals>.<lambda>  rs   r   )rz   r$   ry   r   s    r   __del__zAuthorizedHttp.__del__  s?    4 TYY%:RGDIIw		7L(QRT &; r   c                 .    | j                   j                  S r   r$   r   r   s    r   r   zAuthorizedHttp.headers  s     yy   r   c                 &    || j                   _        y)r   Nr   )r   values     r   r   zAuthorizedHttp.headers   s     "		r   r   )NN)r   r   r   r   r   DEFAULT_REFRESH_STATUS_CODESDEFAULT_MAX_REFRESH_ATTEMPTSr   r   r   r   r   r   r   r   setter__classcell__)rm   s   @r   r\   r\      st    Pj &CC&CC/BJX]B%=U ! ! ^^" "r   r\   )%r   
__future__r   http.clientclientr   loggingr{   r;   rx   r-   urllib3.exceptions	packagingr   r3   google.authr   r   r   google.auth.transportr   google.oauth2r	   parse__version___request_methodsRequestMethodsr+   	getLoggerr   r*   Responser   r"   r>   rZ   r\   r    r   r   <module>r      s#   % & !  !  ! " ! . )7==$$%w)??--<<N__33N
'

H
%#	"" #.A*i A*H%&Ru"^ u"_  G  
	 J		J s(   C3 D  3C=<C= DDD