
    @wjL8                         d Z ddlm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 ej                  e      Z G d	 d
ej"                        Z	 	 ddZ G d d      Zy# e$ rZ ed      edZ[ww xY w)zAuthorization support for gRPC.    )absolute_importN)
exceptions)_mtls_helper)mtls)service_accountzWgRPC is not installed from please install the grpcio package to use the gRPC transport.c                   8     e Zd ZdZ	 ddd fdZd Zd Z xZS )AuthMetadataPlugina  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.
        suppress_metrics_header (bool): When enabled, ``x-goog-api-client``
            will be stripped from authorization headers.
    F)suppress_metrics_headerc                b    t         t        |           || _        || _        || _        || _        y N)superr	   __init___credentials_request_default_host_suppress_metrics_header)selfcredentialsrequestdefault_hostr
   	__class__s        X/root/dashboard-youtube/.venv/lib/python3.12/site-packages/google/auth/transport/grpc.pyr   zAuthMetadataPlugin.__init__7   s2     	 $02')(?%    c                    i }t        | j                  t        j                        rB| j                  j	                  | j
                  rdj                  | j
                        nd       | j                  j                  | j                  |j                  |j                  |       | j                  rd|v r|d= t        |j                               S )zGets 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://{}/Nzx-goog-api-client)
isinstancer   r   Credentials_create_self_signed_jwtr   formatbefore_requestr   method_nameservice_urlr   listitems)r   contextheaderss      r   _get_authorization_headersz-AuthMetadataPlugin._get_authorization_headersC   s      d'')D)DE55<@<N<N$$T%7%78TX 	((MM7..0C0CW	
 ((-@G-K+,GMMO$$r   c                 4     || j                  |      d       y)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$   callbacks      r   __call__zAuthMetadataPlugin.__call__^   s     	0094@r   r   )__name__
__module____qualname____doc__r   r&   r)   __classcell__)r   s   @r   r	   r	   $   s'    & 26
@RW
@%6Ar   r	   c                    t        | |      }t        j                  |      }|r|rt        j                  d      |sgt        j                         }|r$|r" |       \  }	}
t        j                  |	|
      }n-|rt               }|j                  }nt        j                         }t        j                  ||      }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, request, regular_endpoint,
            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, request, mtls_endpoint,
                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, request, endpoint_to_use,
            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, request, regular_endpoint)

    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, request, mtls_endpoint)

    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.certificate_chainprivate_key)r	   grpcmetadata_call_credentialsr   MalformedErrorr   check_use_client_certssl_channel_credentialsSslCredentialsssl_credentialscomposite_channel_credentialssecure_channel)r   r   targetr9   client_cert_callbackkwargsmetadata_plugingoogle_auth_credentialsuse_client_certcertkeyadc_ssl_credentilscomposite_credentialss                r   secure_authorized_channelrF   i   s    h )g>O #<<_M/'',
 	
 &<<>3,.ID#"::"&CO !/!10@@O"::<O !>>0 v'<GGGr   c                   6    e Zd ZdZd Zed        Zed        Zy)r8   a*  Class for application default SSL credentials.

    Mutual TLS (mTLS) is enabled if either:

    1. The `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is explicitly
       set to `"true"`.
    2. The `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset or empty,
       but a valid workload certificate configuration is found (e.g., via the
       `GOOGLE_API_CERTIFICATE_CONFIG` environment variable or the default gcloud config path).

    See https://google.aip.dev/auth/4114 for client certificate discovery details.

    If client certificate usage is enabled, 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                 r    t        j                         }|sd| _        y t        j                         | _        y )NF)r   r6   _is_mtlsr   has_default_client_cert_source)r   rA   s     r   r   zSslCredentials.__init__3  s*    &<<>!DM ??ADMr   c                    | j                   re	 t        j                         \  }}}}|rt        j                  ||      | _        n t        j                         | _        d| _         | j
                  S t        j                         | _        | j
                  S # t        j                  t        f$ r}t        j                  |      }||d}~ww xY w)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.
        r0   FN)
rI   r   get_client_ssl_credentialsr3   r7   _ssl_credentialsr   ClientCertErrorOSErrorMutualTLSChannelError)r   has_certrB   rC   _
caught_excnew_excs          r   r9   zSslCredentials.ssl_credentials:  s      ==.)5)P)P)R&$Q,0,H,H*.C-D) -1,H,H,JD)$)DM $$$ %)$@$@$BD!$$$ ..8 .$:::F:-.s   AB C0CCc                     | j                   S )z?Indicates if the created SSL channel credentials is mutual TLS.)rI   )r   s    r   is_mtlszSslCredentials.is_mtls\  s     }}r   N)r*   r+   r,   r-   r   propertyr9   rV    r   r   r8   r8      s6    $B % %B  r   r8   )NN)r-   
__future__r   logginggoogle.authr   google.auth.transportr   r   google.oauth2r   r3   ImportErrorrS   	getLoggerr*   _LOGGERr	   rF   r8   rX   r   r   <module>ra      s    & &  " . & ) '

H
%BA00 BAR tHn? ?I  
as   A" "A5'	A00A5