
    gye                     @   d Z ddlZddlZddlm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
mZ ddl
mZ ddl
mZ dd	lmZ dd
lmZ dZdZdZdZdZe G d d             Z G d dej2                  ej4                  ej6                  ej8                        Zy)a  External Account Credentials.

This module provides credentials that exchange workload identity pool external
credentials for Google access tokens. This facilitates accessing Google Cloud
Platform resources from on-prem and non-Google Cloud platforms (e.g. AWS,
Microsoft Azure, OIDC identity providers), using native credentials retrieved
from the current environment without the need to copy, save and manage
long-lived service account credentials.

Specifically, this is intended to use access tokens acquired using the GCP STS
token exchange endpoint following the `OAuth 2.0 Token Exchange`_ spec.

.. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693
    N)	dataclass)_helpers)credentials)
exceptions)impersonated_credentials)metrics)sts)utilsexternal_accountz/urn:ietf:params:oauth:grant-type:token-exchangez-urn:ietf:params:oauth:token-type:access_tokenz8https://cloudresourcemanager.googleapis.com/v1/projects/z&https://sts.{universe_domain}/v1/tokenc                   &    e Zd ZU dZeed<   eed<   y)SupplierContextu  A context class that contains information about the requested third party credential that is passed
        to AWS security credential and subject token suppliers.

        Attributes:
            subject_token_type (str): The requested 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”
                    “urn:ietf:params:aws:token-type:aws4_request”

            audience (str): The requested audience for the subject token.
    subject_token_typeaudienceN)__name__
__module____qualname____doc__str__annotations__     y/var/www/html/FastMealFinder_FlaskServer-InitialRelease/venv/lib/python3.12/site-packages/google/auth/external_account.pyr   r   ;   s     Mr   r   c                       e Zd ZdZdddddddddej
                  df fd	Zed        Zd Z	ed        Z
ed        Zed        Zed	        Zed
        Zed        Z ej"                  ej$                        d        Z ej"                  ej(                        dd       Zej.                  d        Zd Z ej"                  ej$                        d        Zd Z ej"                  ej8                        d        Z ej"                  ej<                        d        Z ej"                  ej@                        d        Z!d Z"d Z#d Z$d Z%d Z&e'd        Z(e'd        Z) xZ*S )CredentialsaL  Base class for all external account credentials.

    This is used to instantiate Credentials for exchanging external account
    credentials for Google access token and authorizing requests to Google APIs.
    The base class implements the common logic for exchanging external account
    credentials for Google access tokens.
    Nc                    t         t        |           || _        || _        || _        || _        | j                  t        k(  r+| j                  j                  d| j
                        | _        |	| _	        || _
        || _        |xs i | _        || _        || _        |
| _        || _        || _        || _        g dd| _        | j                  rIt)        j*                  t(        j,                  j.                  | j                  | j                        | _        nd| _        t3        j4                  | j                  | j0                        | _        | j9                         | _        d| _        d| _        tA        | j                  | j                        | _!        d| _"        | jF                  s"| j$                  rtI        jJ                  d      yy)u6  Instantiates an external account credentials object.

        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”
                    “urn:ietf:params:aws:token-type:aws4_request”

            token_url (str): The STS endpoint URL.
            credential_source (Mapping): The credential source dictionary.
            service_account_impersonation_url (Optional[str]): The optional service account
                impersonation generateAccessToken URL.
            client_id (Optional[str]): The optional client ID.
            client_secret (Optional[str]): The optional client secret.
            token_info_url (str): The optional STS endpoint URL for token introspection.
            quota_project_id (Optional[str]): The optional quota project ID.
            scopes (Optional[Sequence[str]]): Optional scopes to request during the
                authorization grant.
            default_scopes (Optional[Sequence[str]]): Default scopes passed by a
                Google client library. Use 'scopes' for user-defined scopes.
            workforce_pool_user_project (Optona[str]): The optional workforce pool user
                project number when the credential corresponds to a workforce pool and not
                a workload identity pool. The underlying principal must still have
                serviceusage.services.use IAM permission to use the project for
                billing/quota.
            universe_domain (str): The universe domain. The default universe
                domain is googleapis.com.
            trust_boundary (str): String representation of trust boundary meta.
        Raises:
            google.auth.exceptions.RefreshError: If the generateAccessToken
                endpoint returned an error.
        z{universe_domain}0x0)	locationsencoded_locationsNzPworkforce_pool_user_project should not be set for non-workforce pool credentials)&superr   __init__	_audience_subject_token_type_universe_domain
_token_url_DEFAULT_TOKEN_URLreplace_token_info_url_credential_source"_service_account_impersonation_url&_service_account_impersonation_options
_client_id_client_secret_quota_project_id_scopes_default_scopes_workforce_pool_user_project_trust_boundaryr
   ClientAuthenticationClientAuthTypebasic_client_authr	   Client_sts_client_create_default_metrics_options_metrics_options_impersonated_credentials_project_idr   _supplier_context_cred_file_pathis_workforce_poolr   InvalidValue)selfr   r   	token_urlcredential_source!service_account_impersonation_url%service_account_impersonation_options	client_idclient_secrettoken_info_urlquota_project_idscopesdefault_scopesworkforce_pool_user_projectuniverse_domaintrust_boundary	__class__s                   r   r    zCredentials.__init__^   s   l 	k4)+!#5  /#??00"oo55#T%:%:DO  ."32S/17R 	3 $+!1-,G)!& 

 ?? % : :$$**DOOT=P=P!D !%D::doot7H7HI $ D D F)-&!0$$dnn"
  $%%$*K*K))  +L%r   c                    | j                         }|j                  t        |j                  dd             |j                  dd       |j                  dd       |j	                         D ci c]  \  }}|	|| c}}S c c}}w )at  Generates the dictionary representation of the current credentials.

        Returns:
            Mapping: The dictionary representation of the credentials. This is the
                reverse of "from_info" defined on the subclasses of this class. It is
                useful for serializing the current credentials so it can deserialized
                later.
        rD   N)typeservice_account_impersonationrI   rJ   )_constructor_argsupdate_EXTERNAL_ACCOUNT_JSON_TYPEpopitems)r@   config_infokeyvalues       r   infozCredentials.info   s     ,,.,*5//7+ 	 	
 	$'($/-8->->-@VzsEEDUU
VVVs   /
B:Bc                    | j                   | j                  | j                  | j                  | j                  t        j                  | j                        xs d t        j                  | j                        | j                  | j                  | j                  | j                  | j                  | j                  | j                  d}| j                   s|j#                  d       |S )N)r   r   rA   rG   rC   rD   rB   rH   rE   rF   rK   rI   rJ   rL   rK   )r!   r"   r$   r'   r)   copydeepcopyr*   r(   r-   r+   r,   r0   r.   r/   r#   r>   rU   )r@   argss     r   rR   zCredentials._constructor_args   s    "&":":"22151X1X59]];;6 6 !%t/F/F!G $ 6 6!00+/+L+Lll"22#44#
& %%HH23r   c                     | j                   rG| j                   }|j                  d      }|j                  d      }|dk7  r|dk7  r||k  r
|dz   }||| S y)zReturns the service account email if service account impersonation is used.

        Returns:
            Optional[str]: The service account email if impersonation is used. Otherwise
                None is returned.
        /z:generateAccessToken   N)r)   rfindfind)r@   urlstart_index	end_indexs       r   service_account_emailz!Credentials.service_account_email   sd     22 99C))C.K!78Ib Y"_y9P)Ao;y11r   c                 4    | j                   ry| j                  S )a%  Returns whether the credentials represent a user (True) or workload (False).
        Workloads behave similarly to service accounts. Currently workloads will use
        service account impersonation but will eventually not require impersonation.
        As a result, this property is more reliable than the service account email
        property in determining if the credentials represent a user or workload.

        Returns:
            bool: True if the credentials represent a user. False if they represent a
                workload.
        F)r)   r>   r@   s    r   is_userzCredentials.is_user  s     22%%%r   c                 n    t        j                  d      }|j                  | j                  xs d      duS )ag  Returns whether the credentials represent a workforce pool (True) or
        workload (False) based on the credentials' audience.

        This will also return True for impersonated workforce pool credentials.

        Returns:
            bool: True if the credentials represent a workforce pool. False if they
                represent a workload.
        z6//iam\.googleapis\.com/locations/[^/]+/workforcePools/ N)recompilematchr!   )r@   ps     r   r>   zCredentials.is_workforce_pool  s0     JJPQwwt~~+,D88r   c                 :    | j                    xr | j                   S )zChecks if the credentials requires scopes.

        Returns:
            bool: True if there are no scopes set otherwise False.
        )r.   r/   rj   s    r   requires_scopeszCredentials.requires_scopes(  s     <<<(<(<$<<r   c                     | j                   j                  d      }	 |j                  d      }|dz   t        |      k  r||dz      xs dS y# t        $ r Y yw xY w)zNOptional[str]: The project number corresponding to the workload identity pool.r`   projectsrb   N)r!   splitindexlen
ValueError)r@   
componentsproject_indexs      r   project_numberzCredentials.project_number1  sj     ^^))#.
	&,,Z8Mq 3z?2!-!"34<< 3 		s   -A 	AAc                     | j                   S )z4Optional[str]: The STS token introspection endpoint.)r'   rj   s    r   rG   zCredentials.token_info_url?  s     ###r   c                 t    | j                   r,| j                   dd}| j                  r| j                  |d<   |S y )Nzexternal account credentials)rB   credential_type	principal)r=   rh   )r@   cred_info_jsons     r   get_cred_infozCredentials.get_cred_infoE  sB    %)%9%9#AN )).2.H.H{+!!r   c                     | j                         }|j                  ||        | j                  di |}| j                  |_        | j                  |_        |S )N)rI   rJ   r   )rR   rS   rN   r=   r9   )r@   rI   rJ   kwargsscopeds        r   with_scopeszCredentials.with_scopesQ  sT    '')VNC)&)!%!5!5"&"7"7r   c                     t        d      )a  Retrieves the subject token using the credential_source object.

        Args:
            request (google.auth.transport.Request): A callable used to make
                HTTP requests.
        Returns:
            str: The retrieved subject token.
        z*retrieve_subject_token must be implementedNotImplementedError)r@   requests     r   retrieve_subject_tokenz"Credentials.retrieve_subject_tokenZ  s     ""NOOr   c                    | j                   r| j                   S | j                  | j                  n| j                  }| j                  xs | j                  }|r|ri }t
        |z   }| j                  |d||        ||d|      }t        |j                  d      r|j                  j                  d      n|j                  }t        j                  |      }|j                  dk(  r"|j                  d      | _         | j                   S y)a  Retrieves the project ID corresponding to the workload identity or workforce pool.
        For workforce pool credentials, it returns the project ID corresponding to
        the workforce_pool_user_project.

        When not determinable, None is returned.

        This is introduced to support the current pattern of using the Auth library:

            credentials, project_id = google.auth.default()

        The resource may not have permission (resourcemanager.projects.get) to
        call this API or the required scopes may not be selected:
        https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes

        Args:
            request (google.auth.transport.Request): A callable used to make
                HTTP requests.
        Returns:
            Optional[str]: The project ID corresponding to the workload identity pool
                or workforce pool if determinable.
        NGET)re   methodheadersdecodeutf-8   	projectId)r;   r.   r/   r|   r0   _CLOUD_RESOURCE_MANAGERbefore_requesthasattrdatar   jsonloadsstatusget)	r@   r   rI   r|   r   re   responseresponse_bodyresponse_datas	            r   get_project_idzCredentials.get_project_idh  s    , ###!%!9t?S?S,,Q0Q0QfG)N:CW=3ugFH 8==(3 $$W-]] 
 !JJ}5M#%#0#4#4[#A '''r   c                    | j                   | j                   n| j                  }| j                         r%t        j                  || j                               }| j                         r| j                         | _        | j                  rR| j                  j                  |       | j                  j                  | _
        | j                  j                  | _        y t        j                         }d }| j                  r| j                  sd| j                  i}t         j"                  t!        j$                  | j&                        i}| j(                  j+                  |t,        | j/                  |      | j0                  | j2                  |t4        ||	      }|j7                  d      | _
        |j7                  d      }t9        |t:              rt=        |      }t?        j@                  |      }||z   | _        y )N)certuserProject)	r   
grant_typesubject_tokenr   r   rI   requested_token_typeadditional_optionsadditional_headersaccess_token
expires_in)seconds)!r.   r/   _mtls_required	functoolspartial_get_mtls_cert_and_key_paths+_should_initialize_impersonated_credentials$_initialize_impersonated_credentialsr:   refreshtokenexpiryr   utcnowr0   r+   r   API_CLIENT_HEADERbyoid_metrics_headerr9   r7   exchange_token_STS_GRANT_TYPEr   r"   r!   _STS_REQUESTED_TOKEN_TYPEr   
isinstancer   intdatetime	timedelta)	r@   r   rI   nowr   r   r   r   lifetimes	            r   r   zCredentials.refresh  s   !%!9t?S?S  ''d??AG ;;=-1-V-V-XD*))**227;77==DJ88??DK//#C!% 00&3T5V5V%W"))7+G+G)),"
 !,,;;*"99'B#'#;#;%>#5#5 < 
M '**>:DJ&**<8J *c* _
))*=H.DKr   c                     | j                         } | j                  di |}| j                  |_        | j                  |_        |S )Nr   )rR   rN   r=   r9   )r@   r   new_creds      r   
_make_copyzCredentials._make_copy  sD    '')!4>>+F+#'#7#7 $($9$9!r   c                 4    | j                         }||_        |S N)r   r-   )r@   rH   creds      r   with_quota_projectzCredentials.with_quota_project  s      !1r   c                 4    | j                         }||_        |S r   )r   r$   )r@   	token_urir   s      r   with_token_urizCredentials.with_token_uri  s     #r   c                 4    | j                         }||_        |S r   )r   r#   )r@   rL   r   s      r   with_universe_domainz Credentials.with_universe_domain  s      /r   c                 >    | j                   d uxr | j                  d u S r   )r)   r:   rj   s    r   r   z7Credentials._should_initialize_impersonated_credentials  s(    334? 7..$6	
r   c           
         | j                         }|j                  di         | j                  di |}| j                  |_        | j                  }|st        j                  d      | j                  | j                  n| j                  }t        j                  |||| j                  | j                  | j                  j                  d            S )a(  Generates an impersonated credentials.

        For more details, see `projects.serviceAccounts.generateAccessToken`_.

        .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken

        Returns:
            impersonated_credentials.Credential: The impersonated credentials
                object.

        Raises:
            google.auth.exceptions.RefreshError: If the generateAccessToken
                endpoint returned an error.
        N)rC   rD   zLUnable to determine target principal from service account impersonation URL.token_lifetime_seconds)source_credentialstarget_principaltarget_scopesrH   iam_endpoint_overrider   r   )rR   rS   rN   r9   rh   r   RefreshErrorr.   r/   r   r   r-   r)   r*   r   )r@   r   r   r   rI   s        r   r   z0Credentials._initialize_impersonated_credentials  s      '').224 	 	
 ,T^^5f5.2.C.C+  55))^  "&!9t?S?S'331- !33"&"I"I@@DD(	
 		
r   c                     i }| j                   rd|d<   nd|d<   | j                  j                  d      rd|d<   |S d|d<   |S )Ntruezsa-impersonationfalser   zconfig-lifetime)r)   r*   r   )r@   metrics_optionss     r   r8   z+Credentials._create_default_metrics_options  sa    2228O./29O./66::;ST17O-.  29O-.r   c                      y)a>  Returns a boolean representing whether the current credential is configured
        for mTLS and should add a certificate to the outgoing calls to the sts and service
        account impersonation endpoint.

        Returns:
            bool: True if the credential is configured for mTLS, False if it is not.
        Fr   rj   s    r   r   zCredentials._mtls_required$  s     r   c                     t        d      )a  Gets the file locations for a certificate and private key file
        to be used for configuring mTLS for the sts and service account
        impersonation calls. Currently only expected to return a value when using
        X509 workload identity federation.

        Returns:
            Tuple[str, str]: The cert and key file locations as strings in a tuple.

        Raises:
            NotImplementedError: When the current credential is not configured for
                mTLS.
        z4_get_mtls_cert_and_key_location must be implemented.r   rj   s    r   r   z(Credentials._get_mtls_cert_and_key_paths.  s     "B
 	
r   c                     | d|j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      xs i |j                  d      |j                  d      |j                  d	      |j                  d
      |j                  d      |j                  dt        j                        d|S )a  Creates a Credentials instance from parsed external account info.

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

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

        Raises:
            InvalidValue: For invalid parameters.
        r   r   rA   rG   rC   rQ   rE   rF   rB   rH   rK   rL   )r   r   rA   rG   rC   rD   rE   rF   rB   rH   rK   rL   r   )r   r   DEFAULT_UNIVERSE_DOMAIN)clsrZ   r   s      r   	from_infozCredentials.from_info?  s       
XXj)#xx(<=hh{+88$45.2hh3/ 37((/3 3 hh{+((?3"hh':;!XX&89(,1N(O HH!;#F#F#
( )
 	
r   c                     t        j                  |dd      5 }t        j                  |      } | j                  |fi |cddd       S # 1 sw Y   yxY w)aY  Creates a Credentials instance from an external account json file.

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

        Returns:
            google.auth.identity_pool.Credentials: The constructed
                credentials.
        rr   )encodingN)ioopenr   loadr   )r   filenamer   	json_filer   s        r   	from_filezCredentials.from_filef  sL     WWXsW5 	199Y'D 3==00	1 	1 	1s   (AAr   )+r   r   r   r   r   r   r    propertyrZ   rR   rh   rk   r>   rs   r|   rG   r   copy_docstringr   r   Scopedr   abcabstractmethodr   r   r   r   CredentialsWithQuotaProjectr   CredentialsWithTokenUrir   CredentialsWithUniverseDomainr   r   r   r8   r   r   classmethodr   r   __classcell__)rN   s   @r   r   r   P   s#    +/.2$(#;;!fP W W(0  $ & &" 9 9 = =   $ $
 X[445	 6	 X[//0 1 	P P.` X[4450) 60)d X[DDE F X[@@A B
 X[FFG H

*
X
" $
 $
L 1 1r   r   )	metaclass)r   r   r\   dataclassesr   r   r   r   r   rn   google.authr   r   r   r   r   google.oauth2r	   r
   rT   r   r   r   r%   r   r   r   r   ABCMetar   r   r   r   <module>r      s      !   	  	   # " 0    1 CK T =    (d1++''kk	d1r   