
    Xiw                         S r SSKrSSKrSSKJr  SSKrSSKrSSKrSSK	r	SSK
r
SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SrS	rS
rSr " S S\5      rS rS rS rS0 4S jr " S S\R8                  5      rg)a  AWS Credentials and AWS Signature V4 Request Signer.

This module provides credentials to access Google Cloud resources from Amazon
Web Services (AWS) workloads. These credentials are recommended over the
use of service account credentials in AWS as they do not involve the management
of long-live service account private keys.

AWS Credentials are initialized using external_account arguments which are
typically loaded from the external credentials JSON file.
Unlike other Credentials that can be initialized with a list of explicit
arguments, secrets or credentials, external account clients use the
environment and hints/guidelines provided by the external_account JSON
file to retrieve credentials and exchange them for Google access tokens.

This module also provides a basic implementation of the
`AWS Signature Version 4`_ request signing algorithm.

AWS Credentials use serialized signed requests to the
`AWS STS GetCallerIdentity`_ API that can be exchanged for Google access tokens
via the GCP STS endpoint.

.. _AWS Signature Version 4: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
.. _AWS STS GetCallerIdentity: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html
    N)urljoin)_helpers)environment_vars)
exceptions)external_accountzAWS4-HMAC-SHA256aws4_requestzx-amz-security-tokenz
x-amz-datec                   ,    \ rS rSrSrS rS0 4S jrSrg)RequestSignerB   zImplements an AWS request signer based on the AWS Signature Version 4 signing
process.
https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
c                     Xl         g)zInstantiates an AWS request signer used to compute authenticated signed
requests to AWS APIs based on the AWS Signature Version 4 signing process.

Args:
    region_name (str): The AWS region to use.
N_region_name)selfregion_names     :/app/.venv/lib/python3.13/site-packages/google/auth/aws.py__init__RequestSigner.__init__H   s
     (     c                     UR                  S5      nUR                  S5      nUR                  S5      nU=(       d    0 n[        R                  R                  U5      n	[        R                  R                  [	        U[
        R                  " U	R                  5      5      5      n
U	R                  (       a  U	R                  S:w  a  [        R                  " S5      e[        U	R                  U
R                  =(       d    S[        U	R                  5      UU R                  UUUUUS9
nUR                  S5      U	R                  S	.nS
U;   a  UR                  S
5      U[         '   U H	  nX]   X'   M     Ub  X["        '   X#US.nU(       a  XNS'   U$ )a  Generates the signed request for the provided HTTP request for calling
an AWS API. This follows the steps described at:
https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html

Args:
    aws_security_credentials (Mapping[str, str]): A dictionary containing
        the AWS security credentials.
    url (str): The AWS service URL containing the canonical URI and
        query string.
    method (str): The HTTP method used to call this API.
    request_payload (Optional[str]): The optional request payload if
        available.
    additional_headers (Optional[Mapping[str, str]]): The optional
        additional headers needed for the requested AWS API.

Returns:
    Mapping[str, str]: The AWS signed request dictionary object.
access_key_idsecret_access_keysecurity_tokenhttpszInvalid AWS service URL/)
hostcanonical_uricanonical_querystringmethodregion
access_key
secret_keyr   request_payloadadditional_headersauthorization_header)Authorizationr   amz_dateurlr   headersdata)geturllibparseurlparser   	posixpathnormpathpathhostnameschemer   InvalidResource#_generate_authentication_header_map_get_canonical_querystringqueryr   _AWS_DATE_HEADER_AWS_SECURITY_TOKEN_HEADER)r   aws_security_credentialsr)   r   r#   r$   r!   r"   r   urinormalized_uri
header_mapr*   keysigned_requests                  r   get_request_options!RequestSigner.get_request_optionsR   sk   6 .11/B
-112EF
1556FG/52ll##C(  ..C++CHH56
 ||szzW4,,-FGG8(--4"<SYY"G$$!!)+1

 (^^,BCLL

 #(2z(BG$%%C-2GL & %2@./!$7K%46"r   r   N)__name__
__module____qualname____firstlineno____doc__r   rA   __static_attributes__ r   r   r
   r
   B   s    
( Jr   r
   c           	         [         R                  R                  U 5      n0 nU Hq  n[         R                  R                  USS9n/ X$'   X    H2  nX$   R	                  [         R                  R                  USS95        M4     X$   R                  5         Ms     [        UR                  5       5      nUR                  5         / nU H.  nX#    H#  nUR	                  SR                  X55      5        M%     M0     SR                  U5      $ )a   Generates the canonical query string given a raw query string.
Logic is based on
https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

Args:
    query (str): The raw query string.

Returns:
    str: The canonical query string.
z-_.~)safez{}={}&)
r-   r.   parse_qsquoteappendsortlistkeysformatjoin)r8   querystringquerystring_encoded_mapr?   	quote_keyitemsorted_keysquerystring_encoded_pairss           r   r7   r7      s     ,,''.K LL&&s&8	-/*$D#.55""4f"5 % 	 *//1  .3356K "+0D%,,W^^C-FG 1  88-..r   c                     [         R                  " XR                  S5      [        R                  5      R                  5       $ )zCreates the HMAC-SHA256 hash of the provided message using the provided
key.

Args:
    key (str): The HMAC-SHA256 key to use.
    msg (str): The message to hash.

Returns:
    str: The computed hash bytes.
utf-8)hmacnewencodehashlibsha256digest)r?   msgs     r   _signrd      s+     88CG,gnn=DDFFr   c                     [        SU -   R                  S5      U5      n[        XB5      n[        XS5      n[        US5      nU$ )a  Calculates the signing key used to calculate the signature for
AWS Signature Version 4 based on:
https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html

Args:
    key (str): The AWS secret access key.
    date_stamp (str): The '%Y%m%d' date format.
    region_name (str): The AWS region.
    service_name (str): The AWS service name, eg. sts.

Returns:
    str: The signing key bytes.
AWS4r\   r   )rd   r_   )r?   
date_stampr   service_namek_datek_region	k_service	k_signings           r   _get_signing_keyrm      sE     FSL((1:>FV)Hh-Ii0Ir   r   c
           
         U R                  S5      S   n
[        R                  " 5       nUR                  S5      nUR                  S5      n0 nU	 H  nX   XR	                  5       '   M     Ub  X~[
        '   XS'   SU;  a  X[        '   Sn[        UR                  5       5      nUR                  5         U H  nSR                  UXU   5      nM     S	R                  U5      n[        R                  " U=(       d    SR                  S
5      5      R                  5       nSR                  UUUUUU5      nSR                  XU
[         5      nSR                  ["        UU[        R                  " UR                  S
5      5      R                  5       5      n[%        XmXJ5      n[&        R(                  " UUR                  S
5      [        R                  5      R                  5       nSR                  ["        UUUU5      nSU0nSU;  a  UUS'   U$ )a  Generates the authentication header map needed for generating the AWS
Signature Version 4 signed request.

Args:
    host (str): The AWS service URL hostname.
    canonical_uri (str): The AWS service URL path name.
    canonical_querystring (str): The AWS service URL query string.
    method (str): The HTTP method used to call this API.
    region (str): The AWS region.
    access_key (str): The AWS access key ID.
    secret_key (str): The AWS secret access key.
    security_token (Optional[str]): The AWS security session token. This is
        available for temporary sessions.
    request_payload (Optional[str]): The optional request payload if
        available.
    additional_headers (Optional[Mapping[str, str]]): The optional
        additional headers needed for the requested AWS API.

Returns:
    Mapping[str, str]: The AWS authentication header dictionary object.
        This contains the x-amz-date and authorization header information.
.r   z%Y%m%dT%H%M%SZz%Y%m%dr   dater   z{}{}:{}
;r\   z{}
{}
{}
{}
{}
{}z{}/{}/{}/{}z{}
{}
{}
{}z3{} Credential={}/{}, SignedHeaders={}, Signature={}r%   r'   )splitr   utcnowstrftimelowerr:   r9   rQ   rR   rP   rS   rT   r`   ra   r_   	hexdigest_AWS_REQUEST_TYPE_AWS_ALGORITHMrm   r]   r^   )r   r   r   r   r    r!   r"   r   r#   r$   rh   current_timer'   rg   full_headersr?   canonical_headersheader_keyssigned_headerspayload_hashcanonical_requestcredential_scopestring_to_signsigning_key	signaturer%   authentication_headers                              r   r6   r6      s   H ::c?1%L??$L$$%56H&&x0J L!$6$;YY[! " !3A/0  
 \!)1%& |((*+K'..s$5
  XXk*N>>?#8b"@"@"IJTTVL 177 %++L*;
 &,,(//89CCE	N #:6PK^**73W^^ik 
 QWW
$4ni 45IJ\!,4j)  r   c                      ^  \ rS rSrSr SU 4S jjrS rS rS rS r	S r
S	 rU 4S
 jr\U 4S j5       r\U 4S j5       rSrU =r$ )CredentialsiU  zAWS external account credentials.
This is used to exchange serialized AWS signature v4 signed requests to
AWS STS GetCallerIdentity service for Google access tokens.
c                   > [         [        U ]
  " UUUUUS.UD6  U=(       d    0 nUR                  S5      =(       d    SU l        UR                  S5      U l        UR                  S5      U l        UR                  S5      U l        UR                  S5      U l        SU l	        SU l
        Xl        [        R                  " S	U R                  5      nU(       a  UR                  5       u  pOS
u  pUS:w  d  U R                  c  [        R                   " S5      e[#        U	=(       d    S5      S:w  a%  [        R$                  " SR'                  U	5      5      eg)a  Instantiates an AWS workload external account credentials object.

Args:
    audience (str): The STS audience field.
    subject_token_type (str): The subject token type.
    token_url (str): The STS endpoint URL.
    credential_source (Mapping): The credential source dictionary used
        to provide instructions on how to retrieve external credential
        to be exchanged for Google access tokens.
    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_sourceenvironment_idr   
region_urlr)   regional_cred_verification_urlimdsv2_session_token_urlNz^(aws)([\d]+)$)NNawsz)No valid AWS 'credential_source' provided   z7aws version '{}' is not supported in the current build.)superr   r   r,   _environment_id_region_url_security_credentials_url_cred_verification_url_imdsv2_session_token_url_region_request_signer_target_resourcerematchgroupsr   r5   intInvalidValuerS   )r   r   r   r   r   argskwargsmatchesenv_idenv_version	__class__s             r   r   Credentials.__init__[  s\   < 	k4)
 	 1/		
 	
 .30445EFL",00>):)>)>u)E&&7&;&;,'
# *;)>)>&*
& # ( ((,d.B.BC").."2FK".FU?d99A,,;  "#q())IPP  )r   c                    Ubv  U R                   bi  U R                  5       (       aT  SS0nU" U R                   SUS9nUR                  S:w  a!  [        R                  " SUR
                  5      eUR
                  nOSnU R                  c;  U R                  XR                  U5      U l	        [        U R                  5      U l        U R                  X5      nU R                  R                  UU R                  R                  SU R                  5      S	5      nUR                  S
5      nU R                   US'   0 nUR                  S5      US'   UR                  S5      US'   / US
'   [#        UR%                  5       5       H  n	US
   R'                  XU	   S.5        M     [(        R*                  R-                  [.        R0                  " USSS95      $ )a  Retrieves the subject token using the credential_source object.
The subject token is a serialized `AWS GetCallerIdentity signed request`_.

The logic is summarized as:

Retrieve the AWS region from the AWS_REGION or AWS_DEFAULT_REGION
environment variable or from the AWS metadata server availability-zone
if not found in the environment variable.

Check AWS credentials in environment variables. If not found, retrieve
from the AWS metadata server security-credentials endpoint.

When retrieving AWS credentials from the metadata server
security-credentials endpoint, the AWS role needs to be determined by
calling the security-credentials endpoint without any argument. Then the
credentials can be retrieved via: security-credentials/role_name

Generate the signed request to AWS STS GetCallerIdentity action.

Inject x-goog-cloud-target-resource into header and serialize the
signed request. This will be the subject-token to pass to GCP STS.

.. _AWS GetCallerIdentity signed request:
    https://cloud.google.com/iam/docs/access-resources-aws#exchange-token

Args:
    request (google.auth.transport.Request): A callable used to make
        HTTP requests.
Returns:
    str: The retrieved subject token.
Nz$X-aws-ec2-metadata-token-ttl-seconds300PUTr(      z$Unable to retrieve AWS Session Tokenz{region}POSTr*   zx-goog-cloud-target-resourcer)   r   )r?   value),:T)
separators	sort_keys)r   _should_use_metadata_serverstatusr   RefreshErrorr+   r   _get_regionr   r   r
   _get_security_credentialsrA   r   replacer,   r   sortedrR   rO   r-   r.   rN   jsondumps)
r   requestr*   imdsv2_session_token_responseimdsv2_session_tokenr;   request_optionsrequest_headersaws_signed_reqr?   s
             r   retrieve_subject_token"Credentials.retrieve_subject_token  s   D ..:0022=uEG,3225'-) -33s: --:166 
 $A#E#E #'  '++))+?DL $1#>D  $(#A#A$
 
 ..BB$''//
DLLI
" *--i8
 ;?:O:O67  / 3 3E :u#2#6#6x#@x $&y!/..01C9%,,c&:; 2
 ||!!JJ~*M
 	
r   c                 *   [         R                  R                  [        R                  5      nUb  U$ [         R                  R                  [        R
                  5      nUb  U$ U R                  (       d  [        R                  " S5      eSnUb  SU0nU" U R                  SUS9n[        UR                  S5      (       a  UR                  R                  S5      OUR                  nUR                  S:w  a  [        R                  " S	U5      eUSS
 $ )a>  Retrieves the current AWS region from either the AWS_REGION or
AWS_DEFAULT_REGION environment variable or from the AWS metadata server.

Args:
    request (google.auth.transport.Request): A callable used to make
        HTTP requests.
    url (str): The AWS metadata server region URL.
    imdsv2_session_token (str): The AWS IMDSv2 session token to be added as a
        header in the requests to AWS metadata endpoint.

Returns:
    str: The current AWS region.

Raises:
    google.auth.exceptions.RefreshError: If an error occurs while
        retrieving the AWS region.
NzUnable to determine AWS regionX-aws-ec2-metadata-tokenGETr(   decoder\   r   zUnable to retrieve AWS region)osenvironr,   r   
AWS_REGIONAWS_DEFAULT_REGIONr   r   r   hasattrr+   r   r   )r   r   r)   r   env_aws_regionr*   responseresponse_bodys           r   r   Credentials._get_region  s    * (8(C(CD%!!(8(K(KL%!!))*JKK+13GHGt//wO
 x}}h// MM  ) 	 ??c!))/  Sb!!r   c                    [         R                  R                  [        R                  5      n[         R                  R                  [        R
                  5      n[         R                  R                  [        R                  5      nU(       a  U(       a  UUUS.$ U R                  X5      nU R                  XU5      nUR                  S5      UR                  S5      UR                  S5      S.$ )a`  Retrieves the AWS security credentials required for signing AWS
requests from either the AWS security credentials environment variables
or from the AWS metadata server.

Args:
    request (google.auth.transport.Request): A callable used to make
        HTTP requests.
    imdsv2_session_token (str): The AWS IMDSv2 session token to be added as a
        header in the requests to AWS metadata endpoint.

Returns:
    Mapping[str, str]: The AWS security credentials dictionary object.

Raises:
    google.auth.exceptions.RefreshError: If an error occurs while
        retrieving the AWS security credentials.
)r   r   r   AccessKeyIdSecretAccessKeyToken)	r   r   r,   r   AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN_get_metadata_role_name"_get_metadata_security_credentials)r   r   r   env_aws_access_key_idenv_aws_secret_access_keyenv_aws_session_token	role_namecredentialss           r   r   %Credentials._get_security_credentialsF  s    * !#

/?/Q/Q R$&JJNN22%
! !#

/?/Q/Q R %>!6%>"7  00O	 == 4

 )__];!,1B!C)oog6
 	
r   c                 z   SS0nUb  X4S'   U" SR                  U R                  U5      SUS9n[        UR                  S5      (       a  UR                  R	                  S5      OUR                  nUR
                  [        R                  :w  a  [        R                  " S	U5      e[        R                  " U5      nU$ )
a  Retrieves the AWS security credentials required for signing AWS
requests from the AWS metadata server.

Args:
    request (google.auth.transport.Request): A callable used to make
        HTTP requests.
    role_name (str): The AWS role name required by the AWS metadata
        server security_credentials endpoint in order to return the
        credentials.
    imdsv2_session_token (str): The AWS IMDSv2 session token to be added as a
        header in the requests to AWS metadata endpoint.

Returns:
    Mapping[str, str]: The AWS metadata server security credentials
        response.

Raises:
    google.auth.exceptions.RefreshError: If an error occurs while
        retrieving the AWS security credentials.
zContent-Typezapplication/jsonr   z{}/{}r   r(   r   r\   z+Unable to retrieve AWS security credentials)rS   r   r   r+   r   r   http_clientOKr   r   r   loads)r   r   r   r   r*   r   r   credentials_responses           r   r   .Credentials._get_metadata_security_credentialsv  s    . "#56+2F./t==yI
 x}}h// MM  ) 	 ??knn,))=}   $zz-8##r   c                 p   U R                   c  [        R                  " S5      eSnUb  SU0nU" U R                   SUS9n[        UR                  S5      (       a  UR                  R                  S5      OUR                  nUR                  [        R                  :w  a  [        R                  " SU5      eU$ )	a  Retrieves the AWS role currently attached to the current AWS
workload by querying the AWS metadata server. This is needed for the
AWS metadata server security credentials endpoint in order to retrieve
the AWS security credentials needed to sign requests to AWS APIs.

Args:
    request (google.auth.transport.Request): A callable used to make
        HTTP requests.
    imdsv2_session_token (str): The AWS IMDSv2 session token to be added as a
        header in the requests to AWS metadata endpoint.

Returns:
    str: The AWS role name.

Raises:
    google.auth.exceptions.RefreshError: If an error occurs while
        retrieving the AWS role name.
NzIUnable to determine the AWS metadata server security credentials endpointr   r   r(   r   r\   z Unable to retrieve AWS role name)	r   r   r   r   r+   r   r   r   r   )r   r   r   r*   r   r   s         r   r   #Credentials._get_metadata_role_name  s    & ))1))[  +13GHG..ug
 x}}h// MM  ) 	 ??knn,))2M  r   c                    [         R                  R                  [        R                  5      (       d3  [         R                  R                  [        R
                  5      (       d  g[         R                  R                  [        R                  5      (       a2  [         R                  R                  [        R                  5      (       d  gg)NTF)r   r   r,   r   r   r   r   r   )r   s    r   r   'Credentials._should_use_metadata_server  s     zz~~.99::2::>>//D
 D
 
 zz~~.@@AA22J
 J
 r   c                 6   > [         [        U ]  5       nSUS'   U$ )Nr   source)r   r   _create_default_metrics_options)r   metrics_optionsr   s     r   r   +Credentials._create_default_metrics_options  s"    TRT$)!r   c                 .   > [         [        U ]
  " U40 UD6$ )aZ  Creates an AWS Credentials instance from parsed external account info.

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

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

Raises:
    ValueError: For invalid parameters.
)r   r   	from_info)clsinfor   r   s      r   r   Credentials.from_info  s     [#0@@@r   c                 .   > [         [        U ]
  " U40 UD6$ )a  Creates an AWS Credentials instance from an external account json file.

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

Returns:
    google.auth.aws.Credentials: The constructed credentials.
)r   r   	from_file)r   filenamer   r   s      r   r   Credentials.from_file  s     [#0DVDDr   )r   r   r   r   r   r   r   r   )N)rC   rD   rE   rF   rG   r   r   r   r   r   r   r   r   classmethodr   r   rH   __classcell__)r   s   @r   r   r   U  si     DLm
^4"l.
`/$b,\&
 A A  
E 
Er   r   )rG   r`   r]   http.clientclientr   r   r   r0   r   r-   urllib.parser   google.authr   r   r   r   rx   rw   r:   r9   objectr
   r7   rd   rm   r6   r   rI   r   r   <module>r      s   2   !  	  	      ( " ( $ # 3  ZF Zz!/HG< l!^tE".. tEr   