o
    ~j6hp                     @   s2  d 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	Z
eeZdZdZdZdZd	Zd
ZeeeeeefZdZdZdZdd Z	d0ddZ	d0ddZdd Zd1ddZd1ddZdd Zd2ddZ	d3ddZ 	d3d d!Z!d1d"d#Z"d2d$d%Z#d&d' Z$d(d) Z%d*d+ Z&d,d- Z'd0d.d/Z(dS )4zgApplication default credentials.

Implements application default credentials and project ID detection.
    N)environment_vars)
exceptionsauthorized_userservice_accountexternal_account external_account_authorized_userimpersonated_service_accountgdch_service_accountzYour default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information.a'  Your application has authenticated using end user credentials from Google Cloud SDK without a quota project. You might receive a "quota exceeded" or "API not enabled" error. See the following page for troubleshooting: https://cloud.google.com/docs/authentication/adc-troubleshooting/user-creds. z+urn:ietf:params:aws:token-type:aws4_requestc                 C   s*   ddl m} | j|jkrtt dS dS )zDetermines if the credentials are problematic.

    Credentials from the Cloud SDK that are associated with Cloud SDK's project
    are problematic because they may not have APIs enabled and have limited
    quota. If this is the case, warn about it.
    r   
_cloud_sdkN)google.authr   	client_idCLOUD_SDK_CLIENT_IDwarningswarn_CLOUD_SDK_CREDENTIALS_WARNING)credentialsr    r   c/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/auth/_default.py#_warn_about_problematic_credentialsB   s   r   c           	      C   s   t j| std| t| d(}zt	|}W n t
y4 } ztd| |}||d}~ww W d   n1 s?w   Y  t| |||||S )a  Loads Google credentials from a file.

    The credentials file must be a service account key, stored authorized
    user credentials, external account credentials, or impersonated service
    account credentials.

    .. warning::
        Important: If you accept a credential configuration (credential JSON/File/Stream)
        from an external source for authentication to Google Cloud Platform, you must
        validate it before providing it to any Google API or client library. Providing an
        unvalidated credential configuration to Google APIs or libraries can compromise
        the security of your systems and data. For more information, refer to
        `Validate credential configurations from external sources`_.

        .. _Validate credential configurations from external sources:
            https://cloud.google.com/docs/authentication/external/externally-sourced-credentials

    Args:
        filename (str): The full path to the credentials file.
        scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
            specified, the credentials will automatically be scoped if
            necessary
        default_scopes (Optional[Sequence[str]]): Default scopes passed by a
            Google client library. Use 'scopes' for user-defined scopes.
        quota_project_id (Optional[str]):  The project ID used for
            quota and billing.
        request (Optional[google.auth.transport.Request]): An object used to make
            HTTP requests. This is used to determine the associated project ID
            for a workload identity pool resource (external account credentials).
            If not specified, then it will use a
            google.auth.transport.requests.Request client to make requests.

    Returns:
        Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
            credentials and the project ID. Authorized user credentials do not
            have the project ID information. External account credentials project
            IDs may not always be determined.

    Raises:
        google.auth.exceptions.DefaultCredentialsError: if the file is in the
            wrong format or is missing.
    zFile {} was not found.rz!File {} is not a valid json file.N)ospathexistsr   DefaultCredentialsErrorformatioopenjsonload
ValueError_load_credentials_from_info)	filenamescopesdefault_scopesquota_project_idrequestfile_objinfo
caught_excnew_excr   r   r   load_credentials_from_fileO   s&   -
r+   c                 C   s0   t | tstdt| td| ||||S )a  Loads Google credentials from a dict.

    The credentials file must be a service account key, stored authorized
    user credentials, external account credentials, or impersonated service
    account credentials.

    .. warning::
        Important: If you accept a credential configuration (credential JSON/File/Stream)
        from an external source for authentication to Google Cloud Platform, you must
        validate it before providing it to any Google API or client library. Providing an
        unvalidated credential configuration to Google APIs or libraries can compromise
        the security of your systems and data. For more information, refer to
        `Validate credential configurations from external sources`_.

    .. _Validate credential configurations from external sources:
        https://cloud.google.com/docs/authentication/external/externally-sourced-credentials

    Args:
        info (Dict[str, Any]): A dict object containing the credentials
        scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
            specified, the credentials will automatically be scoped if
            necessary
        default_scopes (Optional[Sequence[str]]): Default scopes passed by a
            Google client library. Use 'scopes' for user-defined scopes.
        quota_project_id (Optional[str]):  The project ID used for
            quota and billing.
        request (Optional[google.auth.transport.Request]): An object used to make
            HTTP requests. This is used to determine the associated project ID
            for a workload identity pool resource (external account credentials).
            If not specified, then it will use a
            google.auth.transport.requests.Request client to make requests.

    Returns:
        Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
            credentials and the project ID. Authorized user credentials do not
            have the project ID information. External account credentials project
            IDs may not always be determined.

    Raises:
        google.auth.exceptions.DefaultCredentialsError: if the file is in the
            wrong format or is missing.
    z6info object was of type {} but dict type was expected.zdict object)
isinstancedictr   r   r   typer!   )r(   r#   r$   r%   r&   r   r   r   load_credentials_from_dict   s   
-r/   c           
      C   s   ddl m} |d}|tkrt| ||\}}	nO|tkr&t| |||\}}	nA|tkr6t|| |||d\}}	n1|t	krCt
| ||\}}	n$|tkrPt| ||\}}	n|tkr\t| |\}}	ntdj| |tdt||rqt||}||	fS )Nr   CredentialsWithQuotaProjectr.   )r#   r$   r&   zZThe file {file} does not have a valid type. Type is {type}, expected one of {valid_types}.)filer.   valid_types)google.auth.credentialsr1   get_AUTHORIZED_USER_TYPE _get_authorized_user_credentials_SERVICE_ACCOUNT_TYPE _get_service_account_credentials_EXTERNAL_ACCOUNT_TYPE!_get_external_account_credentials&_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE1_get_external_account_authorized_user_credentials"_IMPERSONATED_SERVICE_ACCOUNT_TYPE-_get_impersonated_service_account_credentials_GDCH_SERVICE_ACCOUNT_TYPE%_get_gdch_service_account_credentialsr   r   r   _VALID_TYPESr,   _apply_quota_project_id)
r"   r(   r#   r$   r%   r&   r1   credential_typer   
project_idr   r   r   r!      sJ   






r!   c                 C   sb   ddl m} td | }tj|std dS t|| d\}}||_	|s-|
 }||fS )z7Gets the credentials and project ID from the Cloud SDK.r   r
   z9Checking Cloud SDK credentials as part of auth process...z7Cloud SDK credentials not found on disk; not using themNNr%   )r   r   _LOGGERdebug(get_application_default_credentials_pathr   r   isfiler+   _cred_file_pathget_project_id)r%   r   credentials_filenamer   rE   r   r   r   _get_gcloud_sdk_credentials   s   


rO   c                 C   s   ddl m} | }tjtj}t	d| |dur*||kr*t	d| t
| dS |durDttjtj | d\}}| d|_||fS dS )	zRGets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
    variable.r   r
   z?Checking %s for explicit credentials as part of auth process...NzrExplicit credentials path %s is the same as Cloud SDK credentials path, fall back to Cloud SDK credentials flow...rG   zA file via the GOOGLE_APPLICATION_CREDENTIALS environment variablerF   )r   r   rJ   r   environr5   r   CREDENTIALSrH   rI   rO   r+   rL   )r%   r   cloud_sdk_adc_pathexplicit_filer   rE   r   r   r   !_get_explicit_environ_credentials  s&   

rT   c                  C   s   t jtjdkrdS ztd ddlm  m	}  W n t
y*   td Y dS w z|  }|  }||fW S  tyG   td Y dS w )z?Gets Google App Engine App Identity credentials and project ID.python27rF   z:Checking for App Engine runtime as part of auth process...r   Nz)Import of App Engine auth library failed.z]No App Engine library was found so cannot authentication via App Engine Identity Credentials.)r   rP   r5   r   LEGACY_APPENGINE_RUNTIMErH   rI   google.auth.app_engineauth
app_engineImportErrorwarningCredentialsrM   EnvironmentError)rY   r   rE   r   r   r   _get_gae_credentials0  s&   


r^   c                 C   s   zddl m} ddlm} W n ty   td Y dS w | du r)tjj	j
 } |j| drQz|j| d}W n tjyC   d}Y nw | }t||}||fS td dS )	z>Gets credentials and project ID from the GCE Metadata Service.r   )compute_engine)	_metadataz-Import of Compute Engine auth library failed.rF   Nr&   z]Authentication failed using Compute Engine authentication due to unavailable metadata server.)r   r_   google.auth.compute_enginer`   rZ   rH   r[   googlerX   	transport_http_clientRequest	is_on_gcerM   r   TransportErrorr\   rC   )r&   r%   r_   r`   rE   credr   r   r   _get_gce_credentialsK  s,   	

rj   c           
      C   s   |  dtkrddlm} |jj| ||d}nB|  ddur8|  d ddur8ddlm} |jj| ||d}n!zdd	lm} |jj| ||d}W n tyX   t	
d
|w |du rhddl}	|	jjj }||j|dfS )a{  Loads external account Credentials from the parsed external account info.

    The credentials information must correspond to a supported external account
    credentials.

    Args:
        info (Mapping[str, str]): The external account info in Google format.
        filename (str): The full path to the credentials file.
        scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
            specified, the credentials will automatically be scoped if
            necessary.
        default_scopes (Optional[Sequence[str]]): Default scopes passed by a
            Google client library. Use 'scopes' for user-defined scopes.
        request (Optional[google.auth.transport.Request]): An object used to make
            HTTP requests. This is used to determine the associated project ID
            for a workload identity pool resource (external account credentials).
            If not specified, then it will use a
            google.auth.transport.requests.Request client to make requests.

    Returns:
        Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
            credentials and the project ID. External account credentials project
            IDs may not always be determined.

    Raises:
        google.auth.exceptions.DefaultCredentialsError: if the info dictionary
            is in the wrong format or is missing required information.
    subject_token_typer   )awsr#   r$   credential_sourceN
executable)	pluggable)identity_poolz3Failed to load external account credentials from {}ra   )r5   _AWS_SUBJECT_TOKEN_TYPEr   rl   r\   	from_inforp   rq   r    r   r   r   google.auth.transport.requestsrX   rd   requestsrf   rM   )
r(   r"   r#   r$   r&   rl   r   rp   rq   rc   r   r   r   r;   p  s2    
r;   c                 C   sB   zddl m} |j|}W |d fS  ty    td| w )Nr   )r   zCFailed to load external account authorized user credentials from {})r   r   r\   rs   r    r   r   r   )r"   r(   r#   r$   r&   r   r   r   r   r   r=     s   r=   c              
   C   s\   ddl m} z|jj||d}W |d fS  ty- } zd| }t||}||d }~ww )Nr   r   r#   z2Failed to load authorized user credentials from {})google.oauth2r   r\   from_authorized_user_infor    r   r   r   )r"   r(   r#   r   r)   msgr*   r   r   r   r7     s   
r7   c           	   
   C   sf   ddl m} z|jj|||d}W n ty+ } zd| }t||}||d }~ww ||dfS )Nr   )r   rm   z2Failed to load service account credentials from {}rE   )	rx   r   r\   from_service_account_infor    r   r   r   r5   )	r"   r(   r#   r$   r   r   r)   rz   r*   r   r   r   r9     s   

r9   c              
   C   s\   ddl m} z|jj||d}W |d fS  ty- } zd| }t||}||d }~ww )Nr   )impersonated_credentialsrw   z?Failed to load impersonated service account credentials from {})r   r|   r\   &from_impersonated_service_account_infor    r   r   r   )r"   r(   r#   r|   r   r)   rz   r*   r   r   r   r?     s   	r?   c              
   C   s`   ddl m} z|j|}W n ty( } zd| }t||}||d }~ww ||dfS )Nr   )gdch_credentialsz7Failed to load GDCH service account credentials from {}project)	rx   r~   ServiceAccountCredentialsr{   r    r   r   r   r5   )r"   r(   r~   r   r)   rz   r*   r   r   r   rA     s   
rA   c                 C   s   ddl m} || S )z*Return credentials with the given API key.r   )api_key)r   r   r\   )keyr   r   r   r   get_api_key_credentials  s   
r   c                 C   sB   |r|  |} n|  } ddlm} t| |jr| jst|  | S )Nr   rv   )with_quota_project#with_quota_project_from_environmentrx   r   r,   r\   r%   r   )r   r%   authorized_user_credentialsr   r   r   rC     s   rC   c                    s  ddl m} ddl m} tjtjtjtj} fdd fddt	 fddf}|D ]P}| \}	}
|	dur~||	| |d	}	|pC|
}|sct
t|	d
drcdu r]ddl}|jjj |	jd} rot|	|ro|	 }	|sxtdtj |	|f  S q.tt)a  Gets the default credentials for the current environment.

    `Application Default Credentials`_ provides an easy way to obtain
    credentials to call Google APIs for server-to-server or local applications.
    This function acquires credentials from the environment in the following
    order:

    1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
       to the path of a valid service account JSON private key file, then it is
       loaded and returned. The project ID returned is the project ID defined
       in the service account file if available (some older files do not
       contain project ID information).

       If the environment variable is set to the path of a valid external
       account JSON configuration file (workload identity federation), then the
       configuration file is used to determine and retrieve the external
       credentials from the current environment (AWS, Azure, etc).
       These will then be exchanged for Google access tokens via the Google STS
       endpoint.
       The project ID returned in this case is the one corresponding to the
       underlying workload identity pool resource if determinable.

       If the environment variable is set to the path of a valid GDCH service
       account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH
       credential will be returned. The project ID returned is the project
       specified in the JSON file.
    2. If the `Google Cloud SDK`_ is installed and has application default
       credentials set they are loaded and returned.

       To enable application default credentials with the Cloud SDK run::

            gcloud auth application-default login

       If the Cloud SDK has an active project, the project ID is returned. The
       active project can be set using::

            gcloud config set project

    3. If the application is running in the `App Engine standard environment`_
       (first generation) then the credentials and project ID from the
       `App Identity Service`_ are used.
    4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or
       the `App Engine flexible environment`_ or the `App Engine standard
       environment`_ (second generation) then the credentials and project ID
       are obtained from the `Metadata Service`_.
    5. If no credentials are found,
       :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.

    .. _Application Default Credentials: https://developers.google.com            /identity/protocols/application-default-credentials
    .. _Google Cloud SDK: https://cloud.google.com/sdk
    .. _App Engine standard environment: https://cloud.google.com/appengine
    .. _App Identity Service: https://cloud.google.com/appengine/docs/python            /appidentity/
    .. _Compute Engine: https://cloud.google.com/compute
    .. _App Engine flexible environment: https://cloud.google.com            /appengine/flexible
    .. _Metadata Service: https://cloud.google.com/compute/docs            /storing-retrieving-metadata
    .. _Cloud Run: https://cloud.google.com/run
    .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics            /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted

    Example::

        import google.auth

        credentials, project_id = google.auth.default()

    Args:
        scopes (Sequence[str]): The list of scopes for the credentials. If
            specified, the credentials will automatically be scoped if
            necessary.
        request (Optional[google.auth.transport.Request]): An object used to make
            HTTP requests. This is used to either detect whether the application
            is running on Compute Engine or to determine the associated project
            ID for a workload identity pool resource (external account
            credentials). If not specified, then it will either use the standard
            library http client to make requests for Compute Engine credentials
            or a google.auth.transport.requests.Request client for external
            account credentials.
        quota_project_id (Optional[str]): The project ID used for
            quota and billing.
        default_scopes (Optional[Sequence[str]]): Default scopes passed by a
            Google client library. Use 'scopes' for user-defined scopes.
    Returns:
        Tuple[~google.auth.credentials.Credentials, Optional[str]]:
            the current environment's credentials and project ID. Project ID
            may be None, which indicates that the Project ID could not be
            ascertained from the environment.

    Raises:
        ~google.auth.exceptions.DefaultCredentialsError:
            If no credentials were found, or if the credentials found were
            invalid.
    r   )with_scopes_if_requiredr0   c                      
   t  dS NrG   )rT   r   rG   r   r   <lambda>     
 zdefault.<locals>.<lambda>c                      r   r   )rO   r   rG   r   r   r     r   c                      s   t  dS r   )rj   r   r%   r&   r   r   r     s    N)r$   rM   ra   zvNo project ID could be determined. Consider running `gcloud config set project` or setting the %s environment variable)r4   r   r1   r   rP   r5   r   PROJECTLEGACY_PROJECTr^   callablegetattrrt   rX   rd   ru   rf   rM   r,   r   rH   r[   r   r   _CLOUD_SDK_MISSING_CREDENTIALS)r#   r&   r%   r$   r   r1   explicit_project_idcheckerscheckerr   rE   effective_project_idrc   r   r   r   default  sH   a
	




!r   )NNNN)NrF   )NNN))__doc__r   r   loggingr   r   r   r   r   "google.auth.transport._http_clientrc   	getLogger__name__rH   r6   r8   r:   r<   r>   r@   rB   r   r   rr   r   r+   r/   r!   rO   rT   r^   rj   r;   r=   r7   r9   r?   rA   r   rC   r   r   r   r   r   <module>   s^   


@
7
1
"
&
G


