o
    ýÞhk6  ã                
   @   s¼   d 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 zddlZW n ey? Z zedƒe‚dZ[ww e e¡ZG d	d
„ d
ejƒZ		ddd„ZG dd„ dƒZdS )zAuthorization support for gRPC.é    )Úabsolute_importN)Úenvironment_vars)Ú
exceptions)Ú_mtls_helper)Úservice_accountzWgRPC is not installed from please install the grpcio package to use the gRPC transport.c                       s2   e Zd ZdZd	‡ fdd„	Zdd„ Zdd„ Z‡  ZS )
ÚAuthMetadataPluginan  A `gRPC AuthMetadataPlugin`_ that inserts the credentials into each
    request.

    .. _gRPC AuthMetadataPlugin:
        http://www.grpc.io/grpc/python/grpc.html#grpc.AuthMetadataPlugin

    Args:
        credentials (google.auth.credentials.Credentials): The credentials to
            add to requests.
        request (google.auth.transport.Request): A HTTP transport request
            object used to refresh credentials as needed.
        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 S ©N)Úsuperr   Ú__init__Ú_credentialsÚ_requestÚ_default_host)ÚselfÚcredentialsÚrequestÚdefault_host©Ú	__class__© úZ/var/www/html/premium_crap/venv/lib/python3.10/site-packages/google/auth/transport/grpc.pyr
   6   s   
zAuthMetadataPlugin.__init__c                 C   sT   i }t | jtjƒr| j | jrd | j¡nd¡ | j | j|j	|j
|¡ t| ¡ ƒS )z½Gets the authorization headers for a request.

        Returns:
            Sequence[Tuple[str, str]]: A list of request headers (key, value)
                to add to the request.
        zhttps://{}/N)Ú
isinstancer   r   ÚCredentialsÚ_create_self_signed_jwtr   ÚformatÚbefore_requestr   Úmethod_nameÚservice_urlÚlistÚitems)r   ÚcontextÚheadersr   r   r   Ú_get_authorization_headers?   s   ÿÿz-AuthMetadataPlugin._get_authorization_headersc                 C   s   ||   |¡dƒ dS )a   Passes authorization metadata into the given callback.

        Args:
            context (grpc.AuthMetadataContext): The RPC context.
            callback (grpc.AuthMetadataPluginCallback): The callback that will
                be invoked to pass in the authorization metadata.
        N)r!   )r   r   Úcallbackr   r   r   Ú__call__W   s   zAuthMetadataPlugin.__call__r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r!   r#   Ú__classcell__r   r   r   r   r   %   s
    	r   c                 K   sœ   t | |ƒ}t |¡}|r|rt d¡‚|s>t tjd¡}|dkr/|r/|ƒ \}	}
tj	|	|
d�}n|dkr:t
ƒ }|j}nt 	¡ }t ||¡}tj||fi |¤ŽS )au  Creates a secure authorized gRPC channel.

    This creates a channel with SSL and :class:`AuthMetadataPlugin`. This
    channel can be used to create a stub that can make authorized requests.
    Users can configure client certificate or rely on device certificates to
    establish a mutual TLS channel, if the `GOOGLE_API_USE_CLIENT_CERTIFICATE`
    variable is explicitly set to `true`.

    Example::

        import google.auth
        import google.auth.transport.grpc
        import google.auth.transport.requests
        from google.cloud.speech.v1 import cloud_speech_pb2

        # Get credentials.
        credentials, _ = google.auth.default()

        # Get an HTTP request function to refresh credentials.
        request = google.auth.transport.requests.Request()

        # Create a channel.
        channel = google.auth.transport.grpc.secure_authorized_channel(
            credentials, regular_endpoint, request,
            ssl_credentials=grpc.ssl_channel_credentials())

        # Use the channel to create a stub.
        cloud_speech.create_Speech_stub(channel)

    Usage:

    There are actually a couple of options to create a channel, depending on if
    you want to create a regular or mutual TLS channel.

    First let's list the endpoints (regular vs mutual TLS) to choose from::

        regular_endpoint = 'speech.googleapis.com:443'
        mtls_endpoint = 'speech.mtls.googleapis.com:443'

    Option 1: create a regular (non-mutual) TLS channel by explicitly setting
    the ssl_credentials::

        regular_ssl_credentials = grpc.ssl_channel_credentials()

        channel = google.auth.transport.grpc.secure_authorized_channel(
            credentials, regular_endpoint, request,
            ssl_credentials=regular_ssl_credentials)

    Option 2: create a mutual TLS channel by calling a callback which returns
    the client side certificate and the key (Note that
    `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be explicitly
    set to `true`)::

        def my_client_cert_callback():
            code_to_load_client_cert_and_key()
            if loaded:
                return (pem_cert_bytes, pem_key_bytes)
            raise MyClientCertFailureException()

        try:
            channel = google.auth.transport.grpc.secure_authorized_channel(
                credentials, mtls_endpoint, request,
                client_cert_callback=my_client_cert_callback)
        except MyClientCertFailureException:
            # handle the exception

    Option 3: use application default SSL credentials. It searches and uses
    the command in a context aware metadata file, which is available on devices
    with endpoint verification support (Note that
    `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be explicitly
    set to `true`).
    See https://cloud.google.com/endpoint-verification/docs/overview::

        try:
            default_ssl_credentials = SslCredentials()
        except:
            # Exception can be raised if the context aware metadata is malformed.
            # See :class:`SslCredentials` for the possible exceptions.

        # Choose the endpoint based on the SSL credentials type.
        if default_ssl_credentials.is_mtls:
            endpoint_to_use = mtls_endpoint
        else:
            endpoint_to_use = regular_endpoint
        channel = google.auth.transport.grpc.secure_authorized_channel(
            credentials, endpoint_to_use, request,
            ssl_credentials=default_ssl_credentials)

    Option 4: not setting ssl_credentials and client_cert_callback. For devices
    without endpoint verification support or `GOOGLE_API_USE_CLIENT_CERTIFICATE`
    environment variable is not `true`, a regular TLS channel is created;
    otherwise, a mutual TLS channel is created, however, the call should be
    wrapped in a try/except block in case of malformed context aware metadata.

    The following code uses regular_endpoint, it works the same no matter the
    created channle is regular or mutual TLS. Regular endpoint ignores client
    certificate and key::

        channel = google.auth.transport.grpc.secure_authorized_channel(
            credentials, regular_endpoint, request)

    The following code uses mtls_endpoint, if the created channle is regular,
    and API mtls_endpoint is confgured to require client SSL credentials, API
    calls using this channel will be rejected::

        channel = google.auth.transport.grpc.secure_authorized_channel(
            credentials, mtls_endpoint, request)

    Args:
        credentials (google.auth.credentials.Credentials): The credentials to
            add to requests.
        request (google.auth.transport.Request): A HTTP transport request
            object used to refresh credentials as needed. Even though gRPC
            is a separate transport, there's no way to refresh the credentials
            without using a standard http transport.
        target (str): The host and port of the service.
        ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
            credentials. This can be used to specify different certificates.
            This argument is mutually exclusive with client_cert_callback;
            providing both will raise an exception.
            If ssl_credentials and client_cert_callback are None, application
            default SSL credentials are used if `GOOGLE_API_USE_CLIENT_CERTIFICATE`
            environment variable is explicitly set to `true`, otherwise one way TLS
            SSL credentials are used.
        client_cert_callback (Callable[[], (bytes, bytes)]): Optional
            callback function to obtain client certicate and key for mutual TLS
            connection. This argument is mutually exclusive with
            ssl_credentials; providing both will raise an exception.
            This argument does nothing unless `GOOGLE_API_USE_CLIENT_CERTIFICATE`
            environment variable is explicitly set to `true`.
        kwargs: Additional arguments to pass to :func:`grpc.secure_channel`.

    Returns:
        grpc.Channel: The created gRPC channel.

    Raises:
        google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
            creation failed for any reason.
    zUReceived both ssl_credentials and client_cert_callback; these are mutually exclusive.ÚfalseÚtrue©Úcertificate_chainÚprivate_key)r   ÚgrpcÚmetadata_call_credentialsr   ÚMalformedErrorÚosÚgetenvr   Ú!GOOGLE_API_USE_CLIENT_CERTIFICATEÚssl_channel_credentialsÚSslCredentialsÚssl_credentialsÚcomposite_channel_credentialsÚsecure_channel)r   r   Útargetr6   Úclient_cert_callbackÚkwargsÚmetadata_pluginÚgoogle_auth_credentialsÚuse_client_certÚcertÚkeyÚadc_ssl_credentilsÚcomposite_credentialsr   r   r   Úsecure_authorized_channelb   s0    

ÿÿ
ÿÿrC   c                   @   s0   e Zd ZdZdd„ Zedd„ ƒZedd„ ƒZdS )	r5   aF  Class for application default SSL credentials.

    The behavior is controlled by `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment
    variable whose default value is `false`. Client certificate will not be used
    unless the environment variable is explicitly set to `true`. See
    https://google.aip.dev/auth/4114

    If the environment variable is `true`, then for devices with endpoint verification
    support, a device certificate will be automatically loaded and mutual TLS will
    be established.
    See https://cloud.google.com/endpoint-verification/docs/overview.
    c                 C   s:   t  tjd¡}|dkrd| _d S t tj¡}|d u| _d S )Nr)   r*   F)r1   r2   r   r3   Ú_is_mtlsr   Ú_check_config_pathÚCONTEXT_AWARE_METADATA_PATH)r   r>   Úmetadata_pathr   r   r   r
   )  s   ÿ
ÿzSslCredentials.__init__c              
   C   sj   | j r-zt ¡ \}}}}tj||d�| _W | jS  tjy, } zt |¡}||‚d}~ww t ¡ | _| jS )a  Get the created SSL channel credentials.

        For devices with endpoint verification support, if the device certificate
        loading has any problems, corresponding exceptions will be raised. For
        a device without endpoint verification support, no exceptions will be
        raised.

        Returns:
            grpc.ChannelCredentials: The created grpc channel credentials.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
                creation failed for any reason.
        r+   N)	rD   r   Úget_client_ssl_credentialsr.   r4   Ú_ssl_credentialsr   ÚClientCertErrorÚMutualTLSChannelError)r   Ú_r?   r@   Ú
caught_excÚnew_excr   r   r   r6   6  s   
ÿ	ú
€þ
zSslCredentials.ssl_credentialsc                 C   s   | j S )z?Indicates if the created SSL channel credentials is mutual TLS.)rD   )r   r   r   r   Úis_mtlsT  s   zSslCredentials.is_mtlsN)r$   r%   r&   r'   r
   Úpropertyr6   rO   r   r   r   r   r5     s    
r5   )NN)r'   Ú
__future__r   Úloggingr1   Úgoogle.authr   r   Úgoogle.auth.transportr   Úgoogle.oauth2r   r.   ÚImportErrorrM   Ú	getLoggerr$   Ú_LOGGERr   rC   r5   r   r   r   r   Ú<module>   s2   ÿþ€ÿ
A
û :