;idZddlZddlmZddlZddlZddlmZddl Z ddl Z ddl Z ddl Z ddl mZddlZddlmZddlmZddlmZddlmZdd lmZd Zd Zd Zd ZdZdZGddeZdZdZ dZ!difdZ"eGddZ#Gddej$Z%Gdde%Z&Gddej'Z'dS) 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. This module also provides a definition for an abstract AWS security credentials supplier. This supplier can be implemented to return valid AWS security credentials and an AWS region and used to create AWS credentials. The credentials will then call the supplier instead of using pre-defined methods such as calling the EC2 metadata endpoints. 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) dataclass)Optional)urljoin)_helpers)environment_vars) exceptions)external_accountzAWS4-HMAC-SHA256 aws4_requestzx-amz-security-tokenz x-amz-datezNhttps://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15300c$eZdZdZdZdifdZdS) RequestSignerzImplements 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||_dS)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 CC:\PYTHON\MyICR_Workspace\venv\Lib\site-packages\google/auth/aws.py__init__zRequestSigner.__init__Rs(c v|pi}tj|}tjt|t j|j}|jr |jdkrtj dt|j|jpdt|j ||j|||}|d|jd} d|vr|d| t <|D] } || | | <|j|j| t$<||| d } |r|| d <| S) 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 (AWSSecurityCredentials): 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. httpszInvalid AWS service URL/)host canonical_uricanonical_querystringmethodregionaws_security_credentialsrequest_payloadadditional_headersauthorization_header) Authorizationramz_dateNurlrheadersdata)urllibparseurlparser posixpathnormpathpathhostnameschemerInvalidResource#_generate_authentication_header_map_get_canonical_querystringqueryrget_AWS_DATE_HEADER session_token_AWS_SECURITY_TOKEN_HEADER) rrr%rrr urinormalized_uri header_mapr&keysigned_requests rget_request_optionsz!RequestSigner.get_request_options\sk4052l##C(( .. C+CH55 6 6  | HszW44,-FGG G8(-4" >FV[))Hh --Ii00I rrc |dd}tj} | d} | d} i} |D]} || | | < |j|j| t <|| d<d| vr | | t<d}t| }| |D]} d || | | } d |}tj|pdd }d ||||||}d | ||t"}d t$| |tj|d }t'|j| ||}t+j||d tj}d t$|j|||}d|i}d| vr| |d<|S)aGenerates 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. aws_security_credentials (AWSSecurityCredentials): The AWS security credentials. 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. .rz%Y%m%dT%H%M%SZz%Y%m%dNrdaterz{}{}:{} ;rUz{} {} {} {} {} {}z {}/{}/{}/{}z {} {} {} {}z3{} Credential={}/{}, SignedHeaders={}, Signature={}r!r#)splitrutcnowstrftimelowerr6r7r5rJrKrIrLrMrYrZrX hexdigest_AWS_REQUEST_TYPE_AWS_ALGORITHMrfsecret_access_keyrVrW access_key_id)rrrrrrrr ra current_timer#r` full_headersr;canonical_headers header_keyssigned_headers payload_hashcanonical_requestcredential_scopestring_to_sign signing_key signaturer!authentication_headers rr1r1s>::c??1%L?$$L$$%566H&&x00JL!<<$6s$; SYY[[!!-9 % 2  &  L \!!)1 %&|((**++K  '.. sL$5  XXk**N>?#8b"@"@"I"IJJTTVVL177 %++FL*; &,,(//8899CCEE N# 2J K^**733W^ikk QWW . 45IJ \!!,4j)  rcBeZdZUdZeed<eed<dZeeed<dS)AwsSecurityCredentialsaA class that models AWS security credentials with an optional session token. Attributes: access_key_id (str): The AWS security credentials access key id. secret_access_key (str): The AWS security credentials secret access key. session_token (Optional[str]): The optional AWS security credentials session token. This should be set when using temporary credentials. rsrrNr6)r>r?r@rAstr__annotations__r6rrBrrrr[sJ#'M8C='''''rrcReZdZdZejdZejdZdS)AwsSecurityCredentialsSupplieraCBase class for AWS security credential suppliers. This can be implemented with custom logic to retrieve AWS security credentials to exchange for a Google Cloud access token. The AWS external account credential does not cache the AWS security credentials, so caching logic should be added in the implementation. c td)aReturns the AWS security credentials for the requested context. .. 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 security credential retrieval logic. Returns: AwsSecurityCredentials: The requested AWS security credentials. rNotImplementedErrorrcontextrequests rget_aws_security_credentialsz;AwsSecurityCredentialsSupplier.get_aws_security_credentialsps&""%%%rc td)a&Returns the AWS region for the requested context. 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 region retrieval logic. Returns: str: The AWS region. rrrs rget_aws_regionz-AwsSecurityCredentialsSupplier.get_aws_regions"""%%%rN)r>r?r@rAabcabstractmethodrrrBrrrrjs\  &&&( &&&&&rr) metaclassceZdZdZdZejedZejedZ dZ dZ dZ dS) &_DefaultAwsSecurityCredentialsSupplierzDefault implementation of AWS security credentials supplier. Supports retrieving credentials and region via EC2 metadata endpoints and environment variables. c|d|_|d|_|d|_dS)N region_urlr%imdsv2_session_token_url)r4 _region_url_security_credentials_url_imdsv2_session_token_url)rcredential_sources rrz/_DefaultAwsSecurityCredentialsSupplier.__init__sO,00>>):)>)>u)E)E&):)>)> &* * &&&rc:tjtj}tjtj}tjtj}|r|rt|||S||}| ||}| |||}t|d|d|dS)N AccessKeyIdSecretAccessKeyToken) osenvironr4rAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKENr_get_imdsv2_session_token_get_metadata_role_name"_get_metadata_security_credentials) rrrenv_aws_access_key_idenv_aws_secret_access_keyenv_aws_session_tokenimdsv2_session_token role_name credentialss rrzC_DefaultAwsSecurityCredentialsSupplier.get_aws_security_credentialss  !# /?/Q R R$&JNN  2% % !!# /?/Q R R  %> )%'@BW  $==gFF00:NOO == Y 4  & OOM * * OO- . . OOG $ $   rcDtjtj}||Stjtj}||S|jstjdd}| |}|d|i}||jd|}t|j dr|j dn|j }|j tjkr'tjd||ddS) NzUnable to determine AWS regionX-aws-ec2-metadata-tokenGETr$decoderUz!Unable to retrieve AWS region: {})rrr4r AWS_REGIONAWS_DEFAULT_REGIONrr RefreshErrorrhasattrr'rstatus http_clientOKrL)rrrenv_aws_regionr&rresponse response_bodys rrz5_DefaultAwsSecurityCredentialsSupplier.get_aws_regions( (8(CDD  %! !(8(KLL  %! ! L)*JKK K#==gFF  +13GHG7t/wOOO x}h// HM  ) ) )  ?kn , ,)3::=II  SbS!!rc|k|jddti}||jd|}|jtjkr,t jd|j|jSdS)Nz$X-aws-ec2-metadata-token-ttl-secondsPUTr$z(Unable to retrieve AWS Session Token: {}) r!_IMDSV2_SESSION_TOKEN_TTL_SECONDSrrrrrrLr')rrr&imdsv2_session_token_responses rrz@_DefaultAwsSecurityCredentialsSupplier._get_imdsv2_session_tokens  4#A#M68YG-4G25'--- )-3{~EE ->EE5: 15 54rcvddi}|||d<|d|j|d|}t|jdr|jd n|j}|jt jkr'tj d |tj |}|S) aJRetrieves 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-Typezapplication/jsonNrz{}/{}rr$rrUz/Unable to retrieve AWS security credentials: {}) rLrrr'rrrrrrjsonloads)rrrrr&rrcredentials_responses rrzI_DefaultAwsSecurityCredentialsSupplier._get_metadata_security_credentialss."#56  +2FG. /7t=yII   x}h// HM  ) ) )  ?kn , ,)AHHWW  $z-88##rcV|jtjdd}|d|i}||jd|}t|jdr|jdn|j}|jtjkr'tjd ||S) aRetrieves 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 endpointrrr$rrUz#Unable to retrieve AWS role name {}) rrrrr'rrrrrL)rrrr&rrs rrz>_DefaultAwsSecurityCredentialsSupplier._get_metadata_role_name0s&  ) 1)[   +13GHG7.ug   x}h// HM  ) ) )  ?kn , ,)5<<]KK rN) r>r?r@rArrcopy_docstringrrrrrrrBrrrrs   X;<<  =< :X;<<$"$"=<$"L*/$/$/$b,,,,,rrceZdZdZejddffd ZdZfdZdZ fdZ e fdZ e fd Z xZS) CredentialszAWS external account credentials. This is used to exchange serialized AWS signature v4 signed requests to AWS STS GetCallerIdentity service for Google access tokens. Nctt|j|||||d|||tjd||tjd|r||_t |_n|dpd}t||_|d|_tj d|} | r| \} } nd \} } | d ks|jtj d | t| d kr'tjd | ||_d|_dS)u Instantiates an AWS workload 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:aws:token-type:aws4_request” 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 an AWS security credentials supplier must be provided. Example credential_source for AWS credential:: { "environment_id": "aws1", "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15", "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone", "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials", imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" } aws_security_credentials_supplier (Optional [AwsSecurityCredentialsSupplier]): Optional AWS security credentials supplier. This will be called to supply valid AWS security credentails which will then be exchanged for Google access tokens. Either an AWS security credentials 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. )audiencesubject_token_type token_urlrNzPA valid credential source or AWS security credentials supplier must be provided.z]AWS credential cannot have both a credential source and an AWS security credentials supplier.environment_idrregional_cred_verification_urlz^(aws)([\d]+)$)NNawsz)No valid AWS 'credential_source' providedz7aws version '{}' is not supported in the current build.)superrrr InvalidValue"_aws_security_credentials_supplier1_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL_cred_verification_urlr4rrematchgroupsr0intrL_target_resource_request_signer) rrrrr!aws_security_credentials_supplierargskwargsrmatchesenv_id env_version __class__s rrzCredentials.__init__esd *k4  )  1/         $)J)R)b   )1=)o  - 6WD 3B  ' '/223CDDJN6\!77D 3+<*?*?0++D ' h0.AAG 3&-nn&6&6# &2# $"="E 0?$K(8(8A(=(= -MTT# !)#rc|j>|j|j||_t |j|_|j|j|}|j||j d|jd}| d}|j |d<i}| d|d<| d|d<g|d<| D]&}|d |||d'tjt#j|d d S) aiRetrieves 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{region}POSTr&zx-goog-cloud-target-resourcer%r)r;value),:T) separators sort_keys)rrr_supplier_context_regionr rr=rreplacer4rrKrHr(r)rGrdumps)rrrrequest_optionsrequest_headersaws_signed_reqr;s rretrieve_subject_tokenz"Credentials.retrieve_subject_tokensF   'BQQ&DL$1#>#>D $(#J#g#g  "G$ $  .BB $  ' / / DL I I   "*--i88 ;?:O67 / 3 3E : :u#2#6#6x#@#@x $&y!"''))  C 9 % , ,oc&:;;    |!! J~* M M M   rctt|}d|d<|rd|d<|S)Nrsource programmatic)rr_create_default_metrics_options_has_custom_supplier)rmetrics_optionsrs rrz+Credentials._create_default_metrics_options&sL T22RRTT$)!  $ $ & & 7(6OH %rc|jduS)N)_credential_source)rs rrz Credentials._has_custom_supplier-s&$..rctt|}|r|d|ji|S)Nr)rr_constructor_argsrupdater)rrrs rrzCredentials._constructor_args0s\[$''99;;  $ $ & &  KK79`     rc |d}|d|itt|j|fi|S)aCreates 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)r4rrr from_info)clsinforrrs rrzCredentials.from_info;sd-1HH /- - )  02S T   1u[#&&0@@@@@rc Ftt|j|fi|S)aHCreates 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. )rr from_file)rfilenamerrs rrzCredentials.from_fileRs*1u[#&&0DDVDDDr)r>r?r@rAr _DEFAULT_TOKEN_URLrrrrr classmethodrr __classcell__)rs@rrr_s#5*. h$h$h$h$h$h$TU U U n///     AAAA[A, E E E E[ E E E E Err)(rAr dataclassesrrYrV http.clientclientrrrr+rtypingrr( urllib.parser google.authrrrr rqrpr7r5rrobjectr r2r]rfr1rABCMetarrrrBrrrs4 !!!!!! !!!!!!   ((((((""""""(((((($#3U2%*!SSSSSFSSSl!/!/!/H G G G8o!o!o!o!d  ( ( ( ( ( ( (  (,&,&,&,&,&s{,&,&,&,&^CCCCC-KCCCL~E~E~E~E~E".~E~E~E~E~Er