
    }f>                         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  G d d	ej                  
      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_accountc                   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      X/var/www/feuerwehr-webapp/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	   5   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   R   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__`   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_tokene   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__u   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)r@   methodrA   decoder.      z.Unable to retrieve Identity Pool subject token)r>   r?   hasattrdatarE   statusr   r2   r   r6   r&   r'   )r   r   r   responseresponse_bodyr8   s         r   r   z_UrlSupplier.get_subject_token{   s    tyyN
 x}}h/ MM  ) 	 ??c!))@-  &mTYY? 4,,d.L.L
 	
r   Nr9   r   r   r   r<   r<   r   s/     B  X12
 3
r   r<   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   r2   r3   r   )r8   r)   r*   tokenresponse_datas        r   r6   r6      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
 fdZd Z f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| _        yt        |t              sd| _
        t        j                  d      |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  d	i       }|j                  d
      xs d| _        d|v rt        j                  d      | j                  dvr.t        j                  dj                  | j                              | j                  dk(  r7|j                  d      | _        | j                   t        j                  d      d| _        | j                  r!| j                  rt        j                  d      | j                  s!| j                  st        j                  d      | j                  r1t#        | j                  | j                  | j                         | _        yt%        | j                  | j                  | j                   | j                        | _        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.filer@   rA   r3   typerM   environment_idz>Invalid Identity Pool credential_source field 'environment_id')rM   rN   z%Invalid credential_source format '{}'rN   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.)superrU   r+   r   InvalidValue_subject_token_supplier_credential_source_file_credential_source_url
isinstancer   _credential_source_executableMalformedErrorget_credential_source_headers_credential_source_format_typer3   _credential_source_field_namer"   r<   )
r   rW   rX   rY   rZ   subject_token_supplierargskwargscredential_source_format	__class__s
            r   r+   zCredentials.__init__   s   x 	k4)
 	 1/		
 	
 $)?)G))Y  (-C-O))m  "-+AD(+/D(*.D'/9592 //U  ,=+@+@+HD(*;*?*?*FD'.?.C.CI.ND+'8'<'<Xr'J$ ),,V4> /
  #44 //T  22:JJ //;BB;;  22f<5M5Q5Q.62 55=$33\  6:2++0K0K //[  //8S8S //T  ++/<0077660, 0<//776633	0,r   c                 N    | j                   j                  | j                  |      S r$   )r`   r   _supplier_context)r   r   s     r   retrieve_subject_tokenz"Credentials.retrieve_subject_token8  s&    ++==""G
 	
r   c                     t         t        |          }t        | j                  t
              r)| j                  j                  d      rd|d<   |S d|d<   |S d|d<   |S )Nr[   sourcer@   programmatic)r^   rU   _create_default_metrics_optionsrc   _credential_sourcer   rf   )r   metrics_optionsrn   s     r   ru   z+Credentials._create_default_metrics_options>  sp    TRT d--w7&&**62,2)
  -2)  )7OH%r   c                     | j                   d u S r$   )rv   )r   s    r   _has_custom_supplierz Credentials._has_custom_supplierL  s    &&$..r   c                     t         t        |          }| j                         r|j	                  d| j
                  i       |S )Nrj   )r^   rU   _constructor_argsry   updater`   )r   rk   rn   s     r   r{   zCredentials._constructor_argsO  s;    [$9;$$&KK143O3OPQ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.
        rj   )rf   r|   r^   rU   	from_info)clsinforl   rj   rn   s       r   r~   zCredentials.from_infoV  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.
        )r^   rU   	from_file)r   filenamerl   rn   s      r   r   zCredentials.from_filej  s     [#0DVDDr   )r   r   r   r   r   _DEFAULT_TOKEN_URLr+   r   r:   rU   rq   ru   ry   r{   classmethodr~   r   __classcell__)rn   s   @r   rU   rU      s    C #55#M^ X-99:
 ;

/ A A& E Er   rU   )rM   N)r   collections.abcr   ImportErrorcollectionsr   rN   r0   typingr   google.authr   r   r   ABCMetar	   r   r"   r<   r6   rU   r   r   r   <module>r      s   .$'   	    " (&S[[ &:J 
( 
*
' 
<,PE".. PE{  $#$s   A? ?BB