o
    ~j6hQJ                     @   s   d 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 dd	l	m
Z
 dd
lmZ G dd dejejejZdZdZG dd dejejejZdS )zGoogle Compute Engine credentials.

This module provides authentication for an application running on Google
Compute Engine using the Compute Engine metadata server.

    N)_helpers)credentials)
exceptions)iam)jwt)metrics)	_metadata)_clientc                       s   e Zd ZdZ					d fdd	Zdd Zdd	 Zd
d Zedd Z	edd Z
edd Zeejdd Zeejdd ZeejdddZeejdd Z  ZS )Credentialsa  Compute Engine Credentials.

    These credentials use the Google Compute Engine metadata server to obtain
    OAuth 2.0 access tokens associated with the instance's service account,
    and are also used for Cloud Run, Flex and App Engine (except for the Python
    2.7 runtime, which is supported only on older versions of this library).

    For more information about Compute Engine authentication, including how
    to configure scopes, see the `Compute Engine authentication
    documentation`_.

    .. note:: On Compute Engine the metadata server ignores requested scopes.
        On Cloud Run, Flex and App Engine the server honours requested scopes.

    .. _Compute Engine authentication documentation:
        https://cloud.google.com/compute/docs/authentication#using
    defaultNc                    sD   t t|   || _|| _|| _|| _d| _|r || _d| _dS dS )a_  
        Args:
            service_account_email (str): The service account email to use, or
                'default'. A Compute Engine instance may have multiple service
                accounts.
            quota_project_id (Optional[str]): The project ID used for quota and
                billing.
            scopes (Optional[Sequence[str]]): The list of scopes for the credentials.
            default_scopes (Optional[Sequence[str]]): Default scopes passed by a
                Google client library. Use 'scopes' for user-defined scopes.
            universe_domain (Optional[str]): The universe domain. If not
                provided or None, credential will attempt to fetch the value
                from metadata server. If metadata server doesn't have universe
                domain endpoint, then the default googleapis.com will be used.
        FTN)	superr
   __init___service_account_email_quota_project_id_scopes_default_scopes_universe_domain_cached_universe_domain)selfservice_account_emailquota_project_idscopesdefault_scopesuniverse_domain	__class__ u/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/auth/compute_engine/credentials.pyr   9   s   
zCredentials.__init__c                 C   s6   t j|| jd}|d | _| jdu r|d | _dS dS )zRetrieve information about the service account.

        Updates the scopes and retrieves the full service account email.

        Args:
            request (google.auth.transport.Request): The object used to make
                HTTP requests.
        )service_accountemailNr   )r   get_service_account_infor   r   )r   requestinfor   r   r   _retrieve_infoZ   s   	

zCredentials._retrieve_infoc                 C   s   t jS N)r   CRED_TYPE_SA_MDSr   r   r   r   _metric_header_for_usagem   s   z$Credentials._metric_header_for_usagec              
   C   sl   | j dur| j n| j}z| | tj|| j|d\| _| _W dS  tj	y5 } zt
|}||d}~ww )aj  Refresh the access token and scopes.

        Args:
            request (google.auth.transport.Request): The object used to make
                HTTP requests.

        Raises:
            google.auth.exceptions.RefreshError: If the Compute Engine metadata
                service can't be reached if if the instance has not
                credentials.
        N)r   r   )r   r   r#   r   get_service_account_tokenr   tokenexpiryr   TransportErrorRefreshError)r   r!   r   
caught_excnew_excr   r   r   refreshp   s   

zCredentials.refreshc                 C      | j S )zThe service account email.

        .. note:: This is not guaranteed to be set until :meth:`refresh` has been
            called.
        r   r&   r   r   r   r      s   z!Credentials.service_account_emailc                 C   s   | j  S r$   )r   r&   r   r   r   requires_scopes   s   zCredentials.requires_scopesc                 C   s4   | j r| jS ddlm} t| | _d| _ | jS )Nr   )requestsT)r   r   google.auth.transportr3   r   get_universe_domainRequest)r   google_auth_requestsr   r   r   r      s   zCredentials.universe_domainc                 C   s   dd| j dS )Nzmetadata serverzVM credentials)credential_sourcecredential_type	principal)r   r&   r   r   r   get_cred_info   s   zCredentials.get_cred_infoc                 C   s,   | j | j|| j| jd}| j|_| j|_|S )N)r   r   r   r   )r   r   r   r   r   r   )r   r   credsr   r   r   with_quota_project   s   zCredentials.with_quota_projectc                 C   s*   | j ||| j| jd}| j|_| j|_|S )N)r   r   r   r   )r   r   r   r   r   )r   r   r   r<   r   r   r   with_scopes   s   zCredentials.with_scopesc                 C   s   | j | j| j| j| j|dS )N)r   r   r   r   r   )r   r   r   r   r   )r   r   r   r   r   with_universe_domain   s   z Credentials.with_universe_domain)r   NNNNr$   )__name__
__module____qualname____doc__r   r#   r'   r/   propertyr   r2   r   r   copy_docstringr   r
   r;   CredentialsWithQuotaProjectr=   Scopedr>   CredentialsWithUniverseDomainr?   __classcell__r   r   r   r   r
   "   s2    !








r
   i  z*https://www.googleapis.com/oauth2/v4/tokenc                       s   e Zd ZdZ						d fdd	Zdd Zeej	dd	 Z
eejd
d Zdd Zdd Zdd Zeeejdd Zdd Zedd Zedd Z  ZS )IDTokenCredentialsa>  Open ID Connect ID Token-based service account credentials.

    These credentials relies on the default service account of a GCE instance.

    ID token can be requested from `GCE metadata server identity endpoint`_, IAM
    token endpoint or other token endpoints you specify. If metadata server
    identity endpoint is not used, the GCE instance must have been started with
    a service account that has access to the IAM Cloud API.

    .. _GCE metadata server identity endpoint:
        https://cloud.google.com/compute/docs/instances/verifying-instance-identity
    NFc	           
         s   t t|   || _|| _|| _|r(|s|s|s|rtdd| _d| _	d| _
|du r7t|}	|	d | _n|| _|s`|du rJtj|t | jd}|| _
|pPt| _|dur[|| _	dS i | _	dS dS )a\  
        Args:
            request (google.auth.transport.Request): The object used to make
                HTTP requests.
            target_audience (str): The intended audience for these credentials,
                used when requesting the ID Token. The ID Token's ``aud`` claim
                will be set to this string.
            token_uri (str): The OAuth 2.0 Token URI.
            additional_claims (Mapping[str, str]): Any additional claims for
                the JWT assertion used in the authorization grant.
            service_account_email (str): Optional explicit service account to
                use to sign JWT tokens.
                By default, this is the default GCE service account.
            signer (google.auth.crypt.Signer): The signer used to sign JWTs.
                In case the signer is specified, the request argument will be
                ignored.
            use_metadata_identity_endpoint (bool): Whether to use GCE metadata
                identity endpoint. For backward compatibility the default value
                is False. If set to True, ``token_uri``, ``additional_claims``,
                ``service_account_email``, ``signer`` argument should not be set;
                otherwise ValueError will be raised.
            quota_project_id (Optional[str]): The project ID used for quota and
                billing.

        Raises:
            ValueError:
                If ``use_metadata_identity_endpoint`` is set to True, and one of
                ``token_uri``, ``additional_claims``, ``service_account_email``,
                 ``signer`` arguments is set.
        zIf use_metadata_identity_endpoint is set, token_uri, additional_claims, service_account_email, signer arguments must not be setNr   )r!   r   r   )r   rJ   r   r   _use_metadata_identity_endpoint_target_audiencer   MalformedError
_token_uri_additional_claims_signerr   r    r   r   Signerr
   _DEFAULT_TOKEN_URI)
r   r!   target_audience	token_uriadditional_claimsr   signeruse_metadata_identity_endpointr   sa_infor   r   r   r      s:   )



zIDTokenCredentials.__init__c              
   C   sB   | j r| jd|d| jdS | jd| j| j|| j | jd| jdS )a]  Create a copy of these credentials with the specified target
        audience.
        Args:
            target_audience (str): The intended audience for these credentials,
            used when requesting the ID Token.
        Returns:
            google.auth.service_account.IDTokenCredentials: A new credentials
                instance.
        NTrS   rW   r   Fr   rT   rS   rU   rV   rW   r   )rK   r   r   r   rN   rO   copyrV   )r   rS   r   r   r   with_target_audience3  s"   z'IDTokenCredentials.with_target_audiencec              
   C   sB   | j r| jd | jd|dS | jd | j| j| j| j | jd|dS )NTrY   FrZ   )rK   r   rL   r   rN   rO   r[   rV   )r   r   r   r   r   r=   R  s"   z%IDTokenCredentials.with_quota_projectc              
   C   s8   | j rtd| jd | j|| j| j | jd| j	dS )NzCIf use_metadata_identity_endpoint is set, token_uri must not be setFrZ   )
rK   r   rM   r   r   rL   rO   r[   rV   r   )r   rT   r   r   r   with_token_urij  s   z!IDTokenCredentials.with_token_uric                 C   s\   t  }tjtd}|| }t |t || j| j| jd}|	| j
 t| j|}|S )zCreate the OAuth 2.0 assertion.
        This assertion is used during the OAuth 2.0 grant to acquire an
        ID token.
        Returns:
            bytes: The authorization grant assertion.
        )seconds)iatexpissaudrS   )r   utcnowdatetime	timedelta_DEFAULT_TOKEN_LIFETIME_SECSdatetime_to_secsr   rN   rL   updaterO   r   encoderP   )r   nowlifetimer*   payloadr)   r   r   r   #_make_authorization_grant_assertion  s   z6IDTokenCredentials._make_authorization_grant_assertionc           
   
   C   s   zd}| j dd}tjt i}tj||||d}W n tjy/ } zt|}||d}~ww t	
|\}}	}}|tj|	d fS )a  Request ID token from metadata identity endpoint.

        Args:
            request (google.auth.transport.Request): The object used to make
                HTTP requests.

        Returns:
            Tuple[str, datetime.datetime]: The ID token and the expiry of the ID token.

        Raises:
            google.auth.exceptions.RefreshError: If the Compute Engine metadata
                service can't be reached or if the instance has no credentials.
            ValueError: If extracting expiry from the obtained ID token fails.
        z*instance/service-accounts/default/identityfull)audienceformat)paramsheadersNr`   )rL   r   API_CLIENT_HEADERtoken_request_id_token_mdsr   getr   r+   r,   r   _unverified_decoderd   utcfromtimestamp)
r   r!   pathrq   metrics_headerid_tokenr-   r.   _rl   r   r   r    _call_metadata_identity_endpoint  s   


z3IDTokenCredentials._call_metadata_identity_endpointc                 C   sJ   | j r| |\| _| _dS |  }t|| j|\}}}|| _|| _dS )ag  Refreshes the ID token.

        Args:
            request (google.auth.transport.Request): The object used to make
                HTTP requests.

        Raises:
            google.auth.exceptions.RefreshError: If the credentials could
                not be refreshed.
            ValueError: If extracting expiry from the obtained ID token fails.
        N)rK   r|   r)   r*   rm   r	   id_token_jwt_grantrN   )r   r!   	assertionaccess_tokenr*   r{   r   r   r   r/     s   

zIDTokenCredentials.refreshc                 C   r0   r$   )rP   r&   r   r   r   rV        zIDTokenCredentials.signerc                 C   s   | j rtd| j|S )a&  Signs the given message.

        Args:
            message (bytes): The message to sign.

        Returns:
            bytes: The message's cryptographic signature.

        Raises:
            ValueError:
                Signer is not available if metadata identity endpoint is used.
        z=Signer is not available if metadata identity endpoint is used)rK   r   InvalidOperationrP   sign)r   messager   r   r   
sign_bytes  s
   zIDTokenCredentials.sign_bytesc                 C   r0   )zThe service account email.r1   r&   r   r   r   r     r   z(IDTokenCredentials.service_account_emailc                 C   r0   r$   r1   r&   r   r   r   signer_email  s   zIDTokenCredentials.signer_email)NNNNFN)r@   rA   rB   rC   r   r\   r   rE   r   rF   r=   CredentialsWithTokenUrir]   rm   r|   r/   rD   SigningrV   r   r   r   rI   r   r   r   r   rJ      s2    O





rJ   )rC   rd   google.authr   r   r   r   r   r   google.auth.compute_enginer   google.oauth2r	   rG   rF   rH   r
   rf   rR   r   r   rJ   r   r   r   r   <module>   s.   
 -
