o
    ÔèFh‹>  ã                   @   sà   d Z zddlmZ W n ey   ddlmZ Y nw 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 G dd	„ d	ejd
�ZG dd„ de	ƒZG dd„ deƒZG dd„ deƒZddd„ZG dd„ dejƒZdS )a=  Identity Pool Credentials.

This module provides credentials to access Google Cloud resources from on-prem
or non-Google Cloud platforms which support external credentials (e.g. OIDC ID
tokens) retrieved from local file locations or local servers. This includes
Microsoft Azure and OIDC identity providers (e.g. K8s workloads registered with
Hub with Hub workload identity enabled).

These credentials are recommended over the use of service account credentials
in on-prem/non-Google Cloud platforms as they do not involve the management of
long-live service account private keys.

Identity Pool Credentials are initialized using external_account
arguments which are typically loaded from an external credentials file or
an external credentials URL.

This module also provides a definition for an abstract subject token supplier.
This supplier can be implemented to return a valid OIDC or SAML2.0 subject token
and used to create Identity Pool credentials. The credentials will then call the
supplier instead of using pre-defined methods such as reading a local file or
calling a URL.
é    )ÚMappingN)Ú
NamedTuple)Ú_helpers)Ú
exceptions)Úexternal_accountc                   @   s   e Zd ZdZejdd„ ƒZdS )ÚSubjectTokenSupplieraW  Base class for subject token suppliers. This can be implemented with custom logic to retrieve
    a subject token to exchange for a Google Cloud access token when using Workload or
    Workforce Identity Federation. The identity pool credential does not cache the subject token,
    so caching logic should be added in the implementation.
    c                 C   s   t dƒ‚)a×  Returns the requested subject token. The subject token must be valid.

        .. warning: This is not cached by the calling Google credential, so caching logic should be implemented in the supplier.

        Args:
            context (google.auth.externalaccount.SupplierContext): The context object
                containing information about the requested audience and subject token type.
            request (google.auth.transport.Request): The object used to make
                HTTP requests.

        Raises:
            google.auth.exceptions.RefreshError: If an error is encountered during
                subject token retrieval logic.

        Returns:
            str: The requested subject token string.
        Ú )ÚNotImplementedError)ÚselfÚcontextÚrequest© r   úR/var/www/html/loop/nvenv/lib/python3.10/site-packages/google/auth/identity_pool.pyÚget_subject_token<   s   z&SubjectTokenSupplier.get_subject_tokenN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚabcÚabstractmethodr   r   r   r   r   r   5   s    r   )Ú	metaclassc                   @   s"   e Zd ZU dZeed< eed< dS )Ú_TokenContenta"  Models the token content response from file and url internal suppliers.
        Attributes:
            content (str): The string content of the file or URL response.
            location (str): The location the content was retrieved from. This will either be a file location or a URL.
    ÚcontentÚlocationN)r   r   r   r   ÚstrÚ__annotations__r   r   r   r   r   R   s   
 r   c                   @   ó*   e Zd ZdZdd„ Ze e¡dd„ ƒZdS )Ú_FileSupplierzf Internal implementation of subject token supplier which supports reading a subject token from a file.c                 C   s   || _ || _|| _d S ©N)Ú_pathÚ_format_typeÚ_subject_token_field_name)r
   ÚpathÚformat_typeÚsubject_token_field_namer   r   r   Ú__init__`   s   
z_FileSupplier.__init__c                 C   sp   t j | j¡st d | j¡¡‚t| jddd��}t| 	¡ | jƒ}W d   ƒ n1 s+w   Y  t
|| j| jƒS )NzFile '{}' was not found.Úrúutf-8)Úencoding)Úosr"   Úexistsr   r   ÚRefreshErrorÚformatÚopenr   ÚreadÚ_parse_token_datar    r!   )r
   r   r   Úfile_objÚtoken_contentr   r   r   r   e   s   ÿ
ÿz_FileSupplier.get_subject_tokenN©	r   r   r   r   r%   r   Úcopy_docstringr   r   r   r   r   r   r   ]   s
    r   c                   @   r   )Ú_UrlSupplierzw Internal implementation of subject token supplier which supports retrieving a subject token by calling a URL endpoint.c                 C   s   || _ || _|| _|| _d S r   )Ú_urlr    r!   Ú_headers)r
   Úurlr#   r$   Úheadersr   r   r   r%   u   s   
z_UrlSupplier.__init__c                 C   sb   || j d| jd�}t|jdƒr|j d¡n|j}|jdkr#t d|¡‚t|| j ƒ}t	|| j
| jƒS )NÚGET)r7   Úmethodr8   Údecoder'   éÈ   z.Unable to retrieve Identity Pool subject token)r5   r6   ÚhasattrÚdatar;   Ústatusr   r+   r   r/   r    r!   )r
   r   r   ÚresponseÚresponse_bodyr1   r   r   r   r   {   s   
ÿý
ÿ
ÿz_UrlSupplier.get_subject_tokenNr2   r   r   r   r   r4   r   s
    r4   Útextc              	   C   sb   |dkr| j }n zt | j ¡}|| }W n ttfy'   t d | j|¡¡‚w |s/t d¡‚|S )NrB   z@Unable to parse subject_token from JSON file '{}' using key '{}'z3Missing subject_token in the credential_source file)	r   ÚjsonÚloadsÚKeyErrorÚ
ValueErrorr   r+   r,   r   )r1   r#   r$   ÚtokenÚresponse_datar   r   r   r/   �   s"   ÿÿÿÿr/   c                       s~   e Zd ZdZejddf‡ fdd„	Ze ej	¡dd„ ƒZ
‡ fdd„Zd	d
„ Z‡ fdd„Ze‡ fdd„ƒZe‡ fdd„ƒZ‡  ZS )ÚCredentialsz9External account credentials sourced from files and URLs.Nc           	         s’  t t| ƒj|||||dœ|¤Ž |du r|du rt d¡‚|dur*|dur*t d¡‚|dur9|| _d| _d| _dS t|t	ƒsFd| _
t d¡‚| d¡| _| d¡| _| d¡| _| d	i ¡}| d
¡pdd| _d|v rot d¡‚| jdvr}t d | j¡¡‚| jdkr“| d¡| _| jdu r’t d¡‚nd| _| jr¡| jr¡t d¡‚| js¬| js¬t d¡‚| jr»t| j| j| jƒ| _dS t| j| j| j| jƒ| _dS )uÁ	  Instantiates an external account credentials object from a file/URL.

        Args:
            audience (str): The STS audience field.
            subject_token_type (str): The subject token type based on the Oauth2.0 token exchange spec.
                Expected values include::

                    â€œurn:ietf:params:oauth:token-type:jwtâ€�
                    â€œurn:ietf:params:oauth:token-type:id-tokenâ€�
                    â€œurn:ietf:params:oauth:token-type:saml2â€�

            token_url (Optional [str]): The STS endpoint URL. If not provided, will default to "https://sts.googleapis.com/v1/token".
            credential_source (Optional [Mapping]): The credential source dictionary used to
                provide instructions on how to retrieve external credential to be
                exchanged for Google access tokens. Either a credential source or
                a subject token supplier must be provided.

                Example credential_source for url-sourced credential::

                    {
                        "url": "http://www.example.com",
                        "format": {
                            "type": "json",
                            "subject_token_field_name": "access_token",
                        },
                        "headers": {"foo": "bar"},
                    }

                Example credential_source for file-sourced credential::

                    {
                        "file": "/path/to/token/file.txt"
                    }
            subject_token_supplier (Optional [SubjectTokenSupplier]): Optional subject token supplier.
                This will be called to supply a valid subject token which will then
                be exchanged for Google access tokens. Either a subject token  supplier
                or a credential source must be provided.
            args (List): Optional positional arguments passed into the underlying :meth:`~external_account.Credentials.__init__` method.
            kwargs (Mapping): Optional keyword arguments passed into the underlying :meth:`~external_account.Credentials.__init__` method.

        Raises:
            google.auth.exceptions.RefreshError: If an error is encountered during
                access token retrieval logic.
            ValueError: For invalid parameters.

        .. note:: Typically one of the helper constructors
            :meth:`from_file` or
            :meth:`from_info` are used instead of calling the constructor directly.
        )ÚaudienceÚsubject_token_typeÚ	token_urlÚcredential_sourceNzGA valid credential source or a subject token supplier must be provided.z[Identity pool credential cannot have both a credential source and a subject token supplier.z?Invalid credential_source. The credential_source is not a dict.Úfiler7   r8   r,   ÚtyperB   Úenvironment_idz>Invalid Identity Pool credential_source field 'environment_id')rB   rC   z%Invalid credential_source format '{}'rC   r$   zBMissing subject_token_field_name for JSON credential_source formatzEAmbiguous credential_source. 'file' is mutually exclusive with 'url'.z>Missing credential_source. A 'file' or 'url' must be provided.)ÚsuperrI   r%   r   ÚInvalidValueÚ_subject_token_supplierÚ_credential_source_fileÚ_credential_source_urlÚ
isinstancer   Ú_credential_source_executableÚMalformedErrorÚgetÚ_credential_source_headersÚ_credential_source_format_typer,   Ú_credential_source_field_namer   r4   )	r
   rJ   rK   rL   rM   Úsubject_token_supplierÚargsÚkwargsÚcredential_source_format©Ú	__class__r   r   r%   ©   s�   
<üüúÿÿ

ÿÿÿ
ÿÿ
ÿ
ÿÿÿÿ
ý
üzCredentials.__init__c                 C   s   | j  | j|¡S r   )rS   r   Ú_supplier_context)r
   r   r   r   r   Úretrieve_subject_token8  s   ÿz"Credentials.retrieve_subject_tokenc                    sJ   t t| ƒ ¡ }t| jtƒr| j d¡rd|d< |S d|d< |S d|d< |S )NrN   Úsourcer7   Úprogrammatic)rQ   rI   Ú_create_default_metrics_optionsrV   Ú_credential_sourcer   rY   )r
   Úmetrics_optionsra   r   r   rg   >  s   ýÿz+Credentials._create_default_metrics_optionsc                 C   s
   | j d u S r   )rh   )r
   r   r   r   Ú_has_custom_supplierL  s   
z Credentials._has_custom_supplierc                    s*   t t| ƒ ¡ }|  ¡ r| d| ji¡ |S )Nr]   )rQ   rI   Ú_constructor_argsrj   ÚupdaterS   )r
   r^   ra   r   r   rk   O  s   zCredentials._constructor_argsc                    s0   |  d¡}| d|i¡ tt| ƒj|fi |¤ŽS )aÐ  Creates an Identity Pool Credentials instance from parsed external account info.

        Args:
            info (Mapping[str, str]): The Identity Pool external account info in Google
                format.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.identity_pool.Credentials: The constructed
                credentials.

        Raises:
            ValueError: For invalid parameters.
        r]   )rY   rl   rQ   rI   Ú	from_info)ÚclsÚinfor_   r]   ra   r   r   rm   V  s   
zCredentials.from_infoc                    s   t t| ƒj|fi |¤ŽS )at  Creates an IdentityPool Credentials instance from an external account json file.

        Args:
            filename (str): The path to the IdentityPool external account json file.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.identity_pool.Credentials: The constructed
                credentials.
        )rQ   rI   Ú	from_file)rn   Úfilenamer_   ra   r   r   rp   j  s   zCredentials.from_file)r   r   r   r   r   Ú_DEFAULT_TOKEN_URLr%   r   r3   rI   rd   rg   rj   rk   Úclassmethodrm   rp   Ú__classcell__r   r   ra   r   rI   ¦   s     ú 

rI   )rB   N)r   Úcollections.abcr   ÚImportErrorÚcollectionsr   rC   r)   Útypingr   Úgoogle.authr   r   r   ÚABCMetar   r   r   r4   r/   rI   r   r   r   r   Ú<module>   s&   ÿ
