
    g.I                     B   d Z 	 ddlm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
mZ ddl
mZ ddlmZ  G d	 d
ej                         Z G d de	      Z G d de      Z G d de      Z G d de      ZddZ G d dej.                        Zy# e$ r	 ddlmZ Y w xY w)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_account)_mtls_helperc                   4    e Zd ZdZej
                  d        Zy)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                     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requests      v/var/www/html/FastMealFinder_FlaskServer-InitialRelease/venv/lib/python3.12/site-packages/google/auth/identity_pool.pyget_subject_tokenz&SubjectTokenSupplier.get_subject_token=   s    & ""%%    N)__name__
__module____qualname____doc__abcabstractmethodr    r   r   r
   r
   6   s!     	& &r   r
   )	metaclassc                   &    e Zd ZU dZeed<   eed<   y)_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   S   s     LMr   r   c                   F    e Zd ZdZd Z ej                  e      d        Zy)_FileSupplierzf Internal implementation of subject token supplier which supports reading a subject token from a file.c                 .    || _         || _        || _        y N)_path_format_type_subject_token_field_name)r   pathformat_typesubject_token_field_names       r   __init__z_FileSupplier.__init__a   s    
')A&r   c                    t         j                  j                  | j                        s.t	        j
                  dj                  | j                              t        | j                  dd      5 }t        |j                         | j                        }d d d        t        | j                  | j                        S # 1 sw Y   *xY w)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_contents        r   r   z_FileSupplier.get_subject_tokenf   s    ww~~djj)))*D*K*KDJJ*WXX$**cG4 	G)(--/4::FM	G !4,,d.L.L
 	
	G 	Gs   0%B>>CN	r   r   r   r   r-   r   copy_docstringr
   r   r   r   r   r$   r$   ^   s-    pB
 X12	
 3	
r   r$   c                   F    e Zd ZdZd Z ej                  e      d        Zy)_UrlSupplierzw Internal implementation of subject token supplier which supports retrieving a subject token by calling a URL endpoint.c                 <    || _         || _        || _        || _        y r&   )_urlr(   r)   _headers)r   urlr+   r,   headerss        r   r-   z_UrlSupplier.__init__v   s     	')A&r   c                 r    || j                   d| j                        }t        |j                  d      r|j                  j	                  d      n|j                  }|j
                  dk7  rt        j                  d|      t        || j                         }t        || j                  | j                        S )NGET)rB   methodrC   decoder0      z.Unable to retrieve Identity Pool subject token)r@   rA   hasattrdatarG   statusr   r4   r   r8   r(   r)   )r   r   r   responseresponse_bodyr:   s         r   r   z_UrlSupplier.get_subject_token|   s    tyyN
 x}}h/ MM  ) 	 ??c!))@-  &mTYY? 4,,d.L.L
 	
r   Nr;   r   r   r   r>   r>   s   s/     B  X12
 3
r   r>   c                   @    e Zd ZdZ ej
                  e      d        Zy)_X509SupplierzInternal supplier for X509 workload credentials. This class is used internally and always returns an empty string as the subject token.c                      y)Nr   r   r   s      r   r   z_X509Supplier.get_subject_token   s    r   N)r   r   r   r   r   r<   r
   r   r   r   r   rO   rO      s(     RX12 3r   rO   c                 &   |dk(  r| j                   }n%	 t        j                  | j                         }||   }|st        j                  d      |S # t        t        f$ r0 t        j                  dj                  | j                  |            w xY w)Ntextz@Unable to parse subject_token from JSON file '{}' using key '{}'z3Missing subject_token in the credential_source file)	r   jsonloadsKeyError
ValueErrorr   r4   r5   r    )r:   r+   r,   tokenresponse_datas        r   r8   r8      s    f%%
	 JJ}'<'<=M!":;E %%A
 	
 L *% 	))RYY!**,D 	s   $A ?Bc                        e Zd ZdZej
                  ddf fd	Z ej                  ej                        d        Z
d Zd Z fdZd Z fd	Zd
 Zd Zd Ze fd       Ze fd       Z xZS )Credentialsz9External account credentials sourced from files and URLs.Nc                    t        t        | 
  |||||d| ||t        j                  d      ||t        j                  d      ||| _        d| _        d| _        d| _        yt        |t              sd| _        t        j                  d      |j                  d      | _        |j                  d      | _        |j                  d      | _        d	|v rt        j                  d
      | j                          | j                  r| j                          n| j!                  |       | j                  r1t#        | j                  | j$                  | j&                        | _        y| j                  r<t)        | j                  | j$                  | j&                  | j*                        | _        yt-               | _        y)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.filerB   certificateenvironment_idz>Invalid Identity Pool credential_source field 'environment_id')superrZ   r-   r   InvalidValue_subject_token_supplier_credential_source_file_credential_source_url_credential_source_certificate
isinstancer   _credential_source_executableMalformedErrorget_validate_single_source_validate_certificate_config_validate_file_or_url_configr$   _credential_source_format_type_credential_source_field_namer>   _credential_source_headersrO   )	r   r\   r]   r^   r_   subject_token_supplierargskwargs	__class__s	           r   r-   zCredentials.__init__   s   x 	k4)
 	 1/		
 	
 $)?)G))Y  (-C-O))m  "-+AD(+/D(*.D'26D//9592 //U  ,=+@+@+HD(*;*?*?*FD'2C2G2G2VD/  #44 //T 
 ((*22113112CD++/<0077660,
 ,,/;//776633	0, 0=,r   c                 N    | j                   j                  | j                  |      S r&   )re   r   _supplier_context)r   r   s     r   retrieve_subject_tokenz"Credentials.retrieve_subject_token-  s&    ++==""G
 	
r   c                     | j                   t        j                  d      t        j                  | j
                        S )NzThe credential is not configured to use mtls requests. The credential should include a "certificate" section in the credential source.)rh   r   r4   r    _get_workload_cert_and_key_paths_certificate_config_locationr   s    r   _get_mtls_cert_and_key_pathsz(Credentials._get_mtls_cert_and_key_paths3  sE    ..6)) Y   @@11 r   c                     | j                   d uS r&   )rh   r}   s    r   _mtls_requiredzCredentials._mtls_required=  s    22$>>r   c                     t         t        |          }t        | j                  t
              rK| j                  j                  d      rd|d<   |S | j                  j                  d      rd|d<   |S d|d<   |S d|d<   |S )Nr`   sourcerB   x509programmatic)rc   rZ   _create_default_metrics_optionsri   _credential_sourcer   rl   )r   metrics_optionsrv   s     r   r   z+Credentials._create_default_metrics_options@  s    TRT d--w7&&**62,2)  ((,,U3,1)
  -3)  )7OH%r   c                     | j                   d u S r&   )r   r}   s    r   _has_custom_supplierz Credentials._has_custom_supplierP  s    &&$..r   c                     t         t        |          }| j                         r|j	                  d| j
                  i       |S )Nrs   )rc   rZ   _constructor_argsr   updatere   )r   rt   rv   s     r   r   zCredentials._constructor_argsS  s;    [$9;$$&KK143O3OPQr   c                    | j                   j                  d      | _        | j                   j                  d      }| j                  r|rt        j                  d      | j                  s|st        j                  d      y y )Ncertificate_config_locationuse_default_certificate_configz~Invalid certificate configuration, certificate_config_location cannot be specified when use_default_certificate_config = true.zInvalid certificate configuration, use_default_certificate_config should be true if no certificate_config_location is provided.)rh   rl   r|   r   rk   )r   use_defaults     r   rn   z(Credentials._validate_certificate_configZ  s    ,0,O,O,S,S)-
) 99==,
 ,,++ Q  00++ R  :E0r   c                    |j                  d      | _        |j                  di       }|j                  d      xs d| _        | j                  dvr.t        j                  dj                  | j                              | j                  dk(  r8|j                  d      | _        | j                  t        j                  d	      y d | _        y )
NrC   r5   typerR   )rR   rS   z%Invalid credential_source format '{}'rS   r,   zBMissing subject_token_field_name for JSON credential_source format)rl   rr   rp   r   rk   r5   rq   )r   r_   credential_source_formats      r   ro   z(Credentials._validate_file_or_url_configj  s    *;*?*?	*J'#4#8#82#F  %((0:F 	+ ..6FF++7>>77  ..&81I1M1M*2D. 119 //X  :
 26D.r   c                    | j                   | j                  | j                  g}t        t	        d |            }t        |      dkD  rt        j                  d      t        |      dk7  rt        j                  d      y )Nc                 
    | d uS r&   r   )r   s    r   <lambda>z5Credentials._validate_single_source.<locals>.<lambda>  s    &"4 r      zVAmbiguous credential_source. 'file', 'url', and 'certificate' are mutually exclusive..zNMissing credential_source. A 'file', 'url', or 'certificate' must be provided.)rf   rg   rh   listfilterlenr   rk   )r   credential_sourcesvalid_credential_sourcess      r   rm   z#Credentials._validate_single_source  s    ((''//

 $(46HI$
  '(1,++h  '(A-++`  .r   c                 t    |j                  d      }|j                  d|i       t        t        |   |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.
        rs   )rl   r   rc   rZ   	from_info)clsinforu   rs   rv   s       r   r   zCredentials.from_info  s?      "&*B!C/1GHI[#0@@@r   c                 ,    t        t        | 
  |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.
        )rc   rZ   	from_file)r   filenameru   rv   s      r   r   zCredentials.from_file  s     [#0DVDDr   )r   r   r   r   r   _DEFAULT_TOKEN_URLr-   r   r<   rZ   ry   r~   r   r   r   r   rn   ro   rm   classmethodr   r   __classcell__)rv   s   @r   rZ   rZ      s    C #55#y?v X-99:
 ;

? / 64& A A& E Er   rZ   )rR   N)r   collections.abcr   ImportErrorcollectionsr   rS   r2   typingr   google.authr   r   r   google.auth.transportr   ABCMetar
   r   r$   r>   rO   r8   rZ   r   r   r   <module>r      s   .$'   	    " ( .&S[[ &:J 
( 
*
' 
<( ,HE".. HEM  $#$s   B BB