a 97a?@sLddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZmZddlZddlZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddl%m&Z&m'Z'ddl%m(Z(ddl%m)Z)ddl%m*Z*ddl%m+Z+e,e-Z.e dgdZ/d\ddZ0Gddde1Z2dd Z3d!d"Z4d#d$Z5d]d&d'Z6d(d)Z7d*d+Z8d,d-Z9Gd.d/d/e1Z:Gd0d1d1e1Z;Gd2d3d3e;ZGd8d9d9e>Z?Gd:d;d;e?Z@Gdd?d?e1ZBGd@dAdAeBZCGdBdCdCeBZDGdDdEdEeBZEGdFdGdGeBZFGdHdIdIeBZGGdJdKdKeBZHGdLdMdMeBZIGdNdOdOeBZJGdPdQdQeBZKGdRdSdSe1ZLGdTdUdUeBZMGdVdWdWe1ZNGdXdYdYe>ZOGdZd[d[eBZPdS)^N) namedtuple)deepcopy)sha1parse)tzlocaltzutc)UNSIGNED) total_seconds)compat_shell_split)Config)UnknownCredentialError)PartialCredentialsError)ConfigNotFound)InvalidConfigError)InfiniteLoopConfigError)RefreshWithMFAUnsupportedError)MetadataRetrievalError)CredentialRetrievalError)UnauthorizedSSOTokenError)InstanceMetadataFetcherparse_key_val_file)ContainerMetadataFetcher)FileWebIdentityTokenLoader)SSOTokenLoader)resolve_imds_endpoint_modeReadOnlyCredentials access_key secret_keytokenc s dp d}d}d}ddu}dtd}|durTi}t}t} tt|||dd } t ||d } t fd d t |||t || | g| d } || g} | j ||d}tt| | g}| ||}|r||tdt|d}|S)zCreate a default credential resolver. This creates a pre-configured credential resolver that includes the default lookup chain for credentials. profiledefaultZmetadata_service_timeoutZmetadata_service_num_attemptsNec2_metadata_service_endpoint)r#Z"ec2_metadata_service_endpoint_mode)timeout num_attempts user_agentconfig)iam_role_fetcher)cache region_namecsjSN) full_configsessionr-o/private/var/folders/s6/9n5zrl012gv99k63s4q6ccsd4s6mqz/T/pip-target-f5cq3f2q/lib/python/botocore/credentials.py\z,create_credential_resolver..) load_configclient_creatorr) profile_namecredential_sourcerprofile_provider_builderr5disable_env_varszWSkipping environment variable credential check because profile name was explicitly set. providers)get_config_variableZinstance_variablesgetr EnvProviderContainerProviderInstanceMetadataProviderrr&ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr;OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r/r)r*r5Zmetadata_timeoutr%r9Z imds_configZ env_providerZcontainer_providerZinstance_metadata_providerr7assume_role_providerZ pre_profileprofile_providersZ post_profiler;resolverr-r.r0create_credential_resolver8sl        rNc@sLeZdZdZdddZdddZdd Zd d Zd d ZddZ ddZ dS)rAaThis class handles the creation of profile based providers. NOTE: This class is only intended for internal use. This class handles the creation and ordering of the various credential providers that primarly source their configuration from the shared config. This is needed to enable sharing between the default credential chain and the source profile chain created by the assume role provider. NcCs||_||_||_||_dSr+)_session_cache _region_name_sso_token_cache)selfr/r)r*Zsso_token_cacher-r-r0__init__szProfileProviderBuilder.__init__FcCs.|||||||||||gSr+)_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_providerrSr5r9r-r-r0r;sz ProfileProviderBuilder.providerscst|fdddS)NcsjjSr+rOr,r-rSr-r0r1r2zAProfileProviderBuilder._create_process_provider..)r5r3)ProcessProviderrSr5r-r\r0rXs z/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r5creds_filename)rOr<SharedCredentialProvider)rSr5Zcredential_filer-r-r0rWs  z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r5config_filename)rOr<ConfigProvider)rSr5rar-r-r0rYs  z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjSr+r[r-r\r-r0r1r2zFProfileProviderBuilder._create_web_identity_provider..)r3r4r)r5r9)!AssumeRoleWithWebIdentityProviderrCrOrQrPrZr-r\r0rUs z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)NcsjjSr+r[r-r\r-r0r1r2z=ProfileProviderBuilder._create_sso_provider..)r3r4r5r) token_cache) SSOProviderrO create_clientrPrRr^r-r\r0rVs z+ProfileProviderBuilder._create_sso_provider)NNN)F) __name__ __module__ __qualname____doc__rTr;rXrWrYrUrVr-r-r-r0rAs    rAcCst|}|Sr+)rNload_credentials)r/rMr-r-r0get_credentialssrmcCstjtSr+)datetimenowrr-r-r-r0 _local_nowsrpcCst|tjr|St|Sr+) isinstancernr)valuer-r-r0_parse_if_neededs rsFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rqrn isoformatstrftime)rrisor-r-r0_serialize_if_neededs   rwcsfdd}|S)Ncs*di}|jfi|j|fi|S)Nr*)updaterg)Z service_namekwargsZcreate_client_kwargsr*r/r-r0r4sz+_get_client_creator..client_creatorr-)r/r*r4r-rzr0rCsrCcsfdd}|S)Ncs:jfi}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expirationrrr expiry_time) assume_rolerw)response credentialsclientparamsr-r0refreshs z-create_assume_role_refresher..refreshr-)rrrr-rr0create_assume_role_refreshers rcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rSrr-r-r0rTsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|SNT)rrrr\r-r-r0__call__ sz8create_mfa_serial_refresher.._Refresher.__call__N)rhrirjrTrr-r-r-r0 _Refreshersr)object)Zactual_refreshrr-r-r0create_mfa_serial_refreshersrc@s`eZdZdZejejddddZedfddZ d d Z d d Z d dZ ddZ ddZdS) JSONFileCachezJSON file cache. This provides a dict like interface that stores JSON serializable objects. The objects are serialized to JSON and stored in a file. These values can be retrieved at a later time. ~.awsZbotor)NcCs||_|dur|j}||_dSr+) _working_dir_default_dumps_dumps)rSZ working_dirZ dumps_funcr-r-r0rT szJSONFileCache.__init__cCstj|tdS)N)r")jsondumpsrw)rSobjr-r-r0r&szJSONFileCache._default_dumpscCs||}tj|Sr+)_convert_cache_keyospathisfile)rS cache_key actual_keyr-r-r0 __contains__)s zJSONFileCache.__contains__c Csh||}z8t|}t|WdWS1s60YWn tttfybt|Yn0dS)z Retrieve value from a cache key.N)ropenrloadOSError ValueErrorIOErrorKeyError)rSrrfr-r-r0 __getitem__-s   .zJSONFileCache.__getitem__c Cs||}z||}Wn"ttfy:td|Yn0tj|jsVt|jt t |tj tj Bdd"}| ||Wdn1s0YdS)Nz5Value cannot be cached, must be JSON serializable: %siw)rr TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rSrrrZfull_keyZ file_contentrr-r-r0 __setitem__6s"     zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rSr full_pathr-r-r0rDsz JSONFileCache._convert_cache_key)rhrirjrkrr expanduserrZ CACHE_DIRrTrrrrrr-r-r-r0rs rc@s*eZdZdZd ddZddZddZdS) r{a\ Holds the credentials needed to authenticate requests. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. NcCs0||_||_||_|durd}||_|dS)Nexplicit)rrr method _normalize)rSrrr rr-r-r0rTTszCredentials.__init__cCs$tj|j|_tj|j|_dSr+)botocorecompatensure_unicoderrr\r-r-r0r`szCredentials._normalizecCst|j|j|jSr+)rrrr r\r-r-r0get_frozen_credentialsjsz"Credentials.get_frozen_credentials)NN)rhrirjrkrTrrr-r-r-r0r{Is    r{c@seZdZdZdZdZefddZddZe dd Z e d d Z e j d d Z e d dZej ddZe ddZej ddZddZd$ddZddZddZddZeddZd d!Zd"d#ZdS)%RefreshableCredentialsa Holds the credentials needed to authenticate requests. In addition, it knows how to refresh itself. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. iXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dSr+) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rSrrr r refresh_usingr time_fetcherr-r-r0rTs zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dSr+)rrrrrr\r-r-r0rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrr r)rrr rrr)_expiry_datetime)clsmetadatarrinstancer-r-r0create_from_metadatas z+RefreshableCredentials.create_from_metadatacCs||jSzWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )rrr\r-r-r0rsz!RefreshableCredentials.access_keycCs ||_dSr+)rrSrrr-r-r0rscCs||jSr)rrr\r-r-r0rsz!RefreshableCredentials.secret_keycCs ||_dSr+)rrr-r-r0rscCs||jSr)rrr\r-r-r0r szRefreshableCredentials.tokencCs ||_dSr+)rrr-r-r0r scCs|j|}t|Sr+)rrr )rSdeltar-r-r0_seconds_remainingsz)RefreshableCredentials._seconds_remainingNcCs:|jdurdS|dur|j}||kr,dStddS)aCheck if a refresh is needed. A refresh is needed if the expiry time associated with the temporary credentials is less than the provided ``refresh_in``. If ``time_delta`` is not provided, ``self.advisory_refresh_needed`` will be used. For example, if your temporary credentials expire in 10 minutes and the provided ``refresh_in`` is ``15 * 60``, then this function will return ``True``. :type refresh_in: int :param refresh_in: The number of seconds before the credentials expire in which refresh attempts should be made. :return: True if refresh needed, False otherwise. NFz!Credentials need to be refreshed.T)r_advisory_refresh_timeoutrrHrIrS refresh_inr-r-r0refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)rr\r-r-r0 _is_expiredsz"RefreshableCredentials._is_expiredcCs||jsdS|jdrpzD||js:W|jdS||j}|j|dW|jdS|j0nZ||jr|j8||jsWddS|jddWdn1s0YdS)NF) is_mandatoryT)rrracquirerelease_mandatory_refresh_timeout_protected_refresh)rSZis_mandatory_refreshr-r-r0rs*        zRefreshableCredentials._refreshc Csz |}WnHtyT}z0|r$dnd}tjd|dd|r>WYd}~dSd}~00||t|j|j|j|_ | rd}t|t |dS)N mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.Texc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r ExceptionrHwarning_set_from_datarrrrrr RuntimeError)rSrreZ period_namemsgr-r-r0rs$     z)RefreshableCredentials._protected_refreshcCst|Sr+r)Ztime_strr-r-r0r0sz'RefreshableCredentials._expiry_datetimecsgd}s|}nfdd|D}|rDd}t|j|d|dd|_d|_d |_td |_t d |j| dS) Nrcsg|]}|vr|qSr-r-).0kdatar-r0 9r2z9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %s, provider error_msgrrr rz(Retrieved credentials will expire at: %s) rrrrrr rrrHrIr)rSrZ expected_keysZ missing_keysmessager-rr0r4s$    z%RefreshableCredentials._set_from_datacCs||jS)aReturn immutable credentials. The ``access_key``, ``secret_key``, and ``token`` properties on this class will always check and refresh credentials if needed before returning the particular credentials. This has an edge case where you can get inconsistent credentials. Imagine this: # Current creds are "t1" tmp.access_key ---> expired? no, so return t1.access_key # ---- time is now expired, creds need refreshing to "t2" ---- tmp.secret_key ---> expired? yes, refresh and return t2.secret_key This means we're using the access key from t1 with the secret key from t2. To fix this issue, you can request a frozen credential object which is guaranteed not to change. The frozen credentials returned from this method should be used immediately and then discarded. The typical usage pattern would be:: creds = RefreshableCredentials(...) some_code = SomeSignerObject() # I'm about to sign the request. # The frozen credentials are only used for the # duration of generate_presigned_url and will be # immediately thrown away. request = some_code.sign_some_request( with_credentials=creds.get_frozen_credentials()) print("Signed request:", request) )rrr\r-r-r0rJs"z-RefreshableCredentials.get_frozen_credentials)N)rhrirjrkrrrprTr classmethodrpropertyrsetterrr rrrrr staticmethodrrrr-r-r-r0rps:          "! rcs.eZdZdZefddZdfdd ZZS)DeferredRefreshableCredentialszyRefreshable credentials that don't require initial credentials. refresh_using will be called upon first access. cCs>||_d|_d|_d|_d|_||_t|_||_ d|_ dSr+) rrrrrrrrrrr)rSrrrr-r-r0rTus z'DeferredRefreshableCredentials.__init__Ncs|jdurdStt||Sr)rsuperrrr __class__r-r0rs   z-DeferredRefreshableCredentials.refresh_needed)N)rhrirjrkrprTr __classcell__r-r-rr0rps rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcherrNcCs4|dur i}||_||_|dur*|j}||_dSr+)rP_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rSr)expiry_window_secondsr-r-r0rTs z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key()NotImplementedErrorr\r-r-r0rsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rSfilenamer-r-r0_make_file_safesz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials()rr\r-r-r0_get_credentialssz(CachedCredentialFetcher._get_credentialscCs|Sr+)_get_cached_credentialsr\r-r-r0fetch_credentialssz)CachedCredentialFetcher.fetch_credentialscCs`|}|dur$|}||n td|d}t|ddd}|d|d|d |d S) zGet up-to-date credentials. This will check the cache for up-to-date credentials, calling assume role if none are available. Nz*Credentials for role retrieved from cache.r{rT)rvr|r}r~r)_load_from_cacher _write_to_cacherHrIrw)rSrcreds expirationr-r-r0r s  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jvr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrPrrrHrI)rSrr-r-r0r s  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dSr+)rrPr)rSrr-r-r0r sz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.r{r)rsr rpr)rSrZend_timesecondsr-r-r0rsz#CachedCredentialFetcher._is_expired)NN) rhrirjrrTrrr r r r r rr-r-r-r0rs  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|duri|_n t||_|j|jd<|jd|_d|_|jsT|tt | ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr=_role_session_name_using_default_session_name_generate_assume_role_namerrrT)rSr4role_arn extra_argsr)rrr-r0rTs   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srT)inttimerrrr\r-r-r0rs z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namecCsZt|j}|jr|d=d|vr0t|d|d<tj|dd}t|d}| |S)Create a predictable cache key for the current configuration. The cache key is intended to be compatible with file names. rPolicyT) sort_keysutf-8) rrrrloadsrrencode hexdigestrrSargsZ argument_hashr-r-r0rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)rhrirjrTrrrr-r-rr0rs rcs6eZdZd fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs<||_||_|jdurtj|_tt|j|||||ddS)a :type client_creator: callable :param client_creator: A callable that creates a client taking arguments like ``Session.create_client``. :type source_credentials: Credentials :param source_credentials: The credentials to use to create the client for the call to AssumeRole. :type role_arn: str :param role_arn: The ARN of the role to be assumed. :type extra_args: dict :param extra_args: Any additional arguments to add to the assume role request using the format of the botocore operation. Possible keys include, but may not be limited to, DurationSeconds, Policy, SerialNumber, ExternalId and RoleSessionName. :type mfa_prompter: callable :param mfa_prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in aws-cli. :type expiry_window_seconds: int :param expiry_window_seconds: The amount of time, in seconds, Nrr)r)_source_credentials _mfa_promptergetpassrr%rT)rSr4source_credentialsrr mfa_prompterr)rrr-r0rTs"  z$AssumeRoleCredentialFetcher.__init__cCs |}|}|jfi|S)'Get credentials by calling assume role.)_assume_role_kwargs_create_clientr)rSryrr-r-r0r +sz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dur6d|}||}||d<|d}|durP||d<|S)AGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rrr=r()rSassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr-r-r0r-1s    z/AssumeRoleCredentialFetcher._assume_role_kwargscCs"|j}|jd|j|j|jdS)z2Create an STS client using the source credentials.sts)aws_access_key_idaws_secret_access_keyaws_session_token)r'rrrrr )rSZfrozen_credentialsr-r-r0r.Cs z*AssumeRoleCredentialFetcher._create_client)NNNN)rhrirjrTr r-r.rr-r-rr0r%s ,r%cs.eZdZdfdd ZddZddZZS) *AssumeRoleWithWebIdentityCredentialFetcherNcs$||_tt|j|||||ddS)aG :type client_creator: callable :param client_creator: A callable that creates a client taking arguments like ``Session.create_client``. :type web_identity_token_loader: callable :param web_identity_token_loader: A callable that takes no arguments and returns a web identity token str. :type role_arn: str :param role_arn: The ARN of the role to be assumed. :type extra_args: dict :param extra_args: Any additional arguments to add to the assume role request using the format of the botocore operation. Possible keys include, but may not be limited to, DurationSeconds, Policy, SerialNumber, ExternalId and RoleSessionName. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in aws-cli. :type expiry_window_seconds: int :param expiry_window_seconds: The amount of time, in seconds, r&N)_web_identity_token_loaderrr:rT)rSr4web_identity_token_loaderrrr)rrr-r0rTQs  z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs0|}ttd}|jd|d}|jfi|S)r,)signature_versionr6r')r-r r rZassume_role_with_web_identity)rSryr'rr-r-r0r us z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)r/ZWebIdentityToken)rrr;)rSr2Zidentity_tokenr-r-r0r-~s z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)rhrirjrTr r-rr-r-rr0r:Ns$ r:c@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dSr+r.)rSr/r-r-r0rTszCredentialProvider.__init__cCsdS)a~ Loads the credentials from their source & sets them on the object. Subclasses should implement this method (by reading from disk, the environment, the network or wherever), returning ``True`` if they were found & loaded. If not found, this method should return ``False``, indictating that the ``CredentialResolver`` should fall back to the next available method. The default implementation does nothing, assuming the user has set the ``access_key/secret_key/token`` themselves. :returns: Whether credentials were found & set :rtype: Credentials Tr-r\r-r-r0rszCredentialProvider.loadc GsFg}|D]8}z|||Wqty>t|j|dYq0q|S)NrZcred_var)appendrrMETHOD)rSmappingZ key_namesfoundZkey_namer-r-r0_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)rhrirjrBCANONICAL_NAMErTrrEr-r-r-r0r?s  r?c@s:eZdZdZejfddZddZddZe dd Z d S) r]zcustom-processcCs||_||_d|_||_dSr+) _profile_name _load_config_loaded_config_popen)rSr5r3popenr-r-r0rTszProcessProvider.__init__csdjdurdS}|ddurDt|fddjSt|d|d|djdS)Nrcs Sr+)_retrieve_credentials_usingr-credential_processrSr-r0r1r2z&ProcessProvider.load..rrr )rrr r)_credential_processrLr=rrrBr{)rSZ creds_dictr-rMr0rs   zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|dz$|d |d | d | d d WSty}zt|jd|dWYd}~n d}~00dS)N)stdoutstderrrrrVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1r|r}r~rrz$Missing required key in response: %s)r rJ subprocessPIPE communicate returncoderrBdecoderrrr r=r) rSrNZ process_listprPrQparsedversionrr-r-r0rLs<    z+ProcessProvider._retrieve_credentials_usingcCs6|jdur||_|jdi|ji}|dS)NprofilesrN)rIrHr=rG)rSprofile_configr-r-r0rOs  z#ProcessProvider._credential_processN) rhrirjrBrTPopenrTrrLrrOr-r-r-r0r]s r]c@s$eZdZdZdZddZddZdS)r@ziam-roleZEc2InstanceMetadatacCs ||_dSr+) _role_fetcher)rSr(r-r-r0rTsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_namerr)r_Zretrieve_iam_role_credentialsrHrIrrrB)rSfetcherrrr-r-r0rszInstanceMetadataProvider.loadN)rhrirjrBrFrTrr-r-r-r0r@sr@c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r>env EnvironmentZAWS_ACCESS_KEY_IDZAWS_SECRET_ACCESS_KEYZAWS_SECURITY_TOKENZAWS_SESSION_TOKENZAWS_CREDENTIAL_EXPIRATIONNcCs$|durtj}||_|||_dS)a :param environ: The environment variables (defaults to ``os.environ`` if no value is provided). :param mapping: An optional mapping of variable names to environment variable names. Use this if you want to change the mapping of access_key->AWS_ACCESS_KEY_ID, etc. The dict can have up to 3 keys: ``access_key``, ``secret_key``, ``session_token``. N)renviron_build_mapping_mapping)rSrerCr-r-r0rT s zEnvProvider.__init__cCsi}|dur6|j|d<|j|d<|j|d<|j|d<nd|d|j|d<|d|j|d<|d|j|d<t|dts|dg|d<|d|j|d<|S)Nrrr r) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr=rqlist)rSrCZ var_mappingr-r-r0rf0s*    zEnvProvider._build_mappingcCs|j|jdd}|rtd|}|dd}|d}|durnt|}t|d|d|d |||jd St |d|d|d |jd SdSdS) zK Search for credentials in explicit environment variables. rz+Found credentials in environment variables.F)require_expiryrNrr )rrr) rer=rgrHinfo_create_credentials_fetcherrrrBr{)rSrrbrrr-r-r0rFs$     zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|s(tdd||d<dd}|sTtdd||d<d|d<dD] }|d}|rl||d<qqld|d<dd}|r||d<|r|stdd|S)Nrrmr@rr r)r=r)rnrrrZ token_env_varr rrerCrr-r0r gs8  zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rgrBre)rSr r-rrr0rqbs  z'EnvProvider._create_credentials_fetcher)NN) rhrirjrBrFrhrirjrkrTrfrrqr-r-r-r0r>s r>c@s2eZdZdZdZdZdZdZd ddZd d Z dS) rEzec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|durtj}|durt}||_||_dSr+)rrer_environ_parser)rSreparserr-r-r0rTs zOriginalEC2Provider.__init__cCshd|jvr`tj|jd}||}|j|vrdtd||j}||j}t |||j dSndSdS)zN Search for a credential file used by original EC2 CLI tools. rsz)Found credentials in AWS_CREDENTIAL_FILE.roN) rtrrrrurhrHrprir{rB)rSrrrrr-r-r0rs      zOriginalEC2Provider.load)NN) rhrirjrBrFZ CRED_FILE_ENVrhrirTrr-r-r-r0rEs rEc@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)r`zshared-credentials-fileZSharedCredentialsr7r8aws_security_tokenr9NcCs2||_|durd}||_|dur(tjj}||_dS)Nr")_creds_filenamerGr configloaderraw_config_parse _ini_parser)rSr_r5 ini_parserr-r-r0rTsz!SharedCredentialProvider.__init__cCsz||j}Wnty$YdS0|j|vr||j}|j|vrtd|j|||j|j\}}| |}t ||||j dSdS)Nz0Found credentials in shared credentials file: %sro) r{rxrrGrhrHrprEri_get_session_tokenr{rB)rSZavailable_credsr'rrr r-r-r0rs"      zSharedCredentialProvider.loadcCs$|jD]}||vr||SqdSr+rj)rSr'Z token_envvarr-r-r0r}s z+SharedCredentialProvider._get_session_token)NN) rhrirjrBrFrhrirjrTrr}r-r-r-r0r`s r`c@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)rcz0INI based config provider with profile sections.z config-fileZ SharedConfigr7r8rwr9NcCs&||_||_|durtjj}||_dS)a :param config_filename: The session configuration scoped to the current profile. This is available via ``session.config``. :param profile_name: The name of the current profile. :param config_parser: A config parser callable. N)_config_filenamerGrryr3_config_parser)rSrbr5Z config_parserr-r-r0rTs zConfigProvider.__init__cCsz||j}Wnty$YdS0|j|dvr|d|j}|j|vrtd|j|||j|j\}}| |}t ||||j dSndSdS)zr If there is are credentials in the configuration associated with the session, use those. Nr\z$Credentials found in config file: %sro) rrrrGrhrHrprErir}r{rB)rSr,r]rrr r-r-r0rs$    zConfigProvider.loadcCs$|jD]}||vr||SqdSr+r~)rSr]Z token_namer-r-r0r}s z!ConfigProvider._get_session_token)N) rhrirjrkrBrFrhrirjrTrr}r-r-r-r0rcs rcc@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)rFz boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botor7r8NcCs.|durtj}|durtjj}||_||_dSr+)rrerryrzrtr{)rSrer|r-r-r0rTs zBotoProvider.__init__c Cs|j|jvr|j|jg}n|j}|D]z}z||}WntyNYq&Yn0d|vr&|d}|j|vr&td||||j|j \}}t |||j dSq&dS)z; Look for credentials in boto config file. r{z)Found credentials in boto config file: %sroN) BOTO_CONFIG_ENVrtDEFAULT_CONFIG_FILENAMESr{rrhrHrprErir{rB)rSZpotential_locationsrr'rrrr-r-r0rs(     zBotoProvider.load)NN) rhrirjrBrFrrrhrirTrr-r-r-r0rF s rFc@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) rB assume-roleNrweb_identity_token_filercCs>||_||_||_||_||_i|_||_||_|jg|_dS)a :type load_config: callable :param load_config: A function that accepts no arguments, and when called, will return the full configuration dictionary for the session (``session.full_config``). :type client_creator: callable :param client_creator: A factory function that will create a client when called. Has the same interface as ``botocore.session.Session.create_client``. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in the CLI. :type profile_name: str :param profile_name: The name of the profile. :type prompter: callable :param prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type credential_sourcer: CanonicalNameCredentialSourcer :param credential_sourcer: A credential provider that takes a configuration, which is used to provide the source credentials for the STS call. N) r)rHrrG _prompterrI_credential_sourcer_profile_provider_builder_visited_profiles)rSr3r4r)r5Zprompterr6r7r-r-r0rTFs$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdSNr\)rHrIr=rG_has_assume_role_config_vars_load_creds_via_assume_role)rSr\r!r-r-r0r}s   zAssumeRoleProvider.loadcCs|j|vo|j|vSr+)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARrSr!r-r-r0rs z/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dur4||d<|d}|durN||d<|d}|durh||d<|d}|dur||d<t|j||d ||j|jd } | j} |durt| } t |j | t d S) Nrole_session_namer external_idZ ExternalIdr3r0r5r1r)r4r*rrr+r))rrr) _get_role_config_resolve_source_credentialsr=r%rrr)r rrrBrp) rSr5 role_configr*rrrr3r5rbZ refresherr-r-r0rsB     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d urzt| | d<WntyYn0|d ur|d urtd |d nB|d ur|d urt|jd dn"|d ur|||n |||| S)z?Retrieves and validates the role configuration for the profile.r\source_profilercredential_sourcer3rrr5)rrr3rrrNzDThe profile "%s" contains both source_profile and credential_source.rz#source_profile or credential_sourcer@) rIr=rrrrrB_validate_credential_source_validate_source_profile) rSr5r\r!rrrr3rrr5rr-r-r0rsL         z#AssumeRoleProvider._get_role_configcCs>|jdurtd||fd|j|s:td||fddS)Nz_The credential_source "%s" is specified in profile "%s", but no source provider was configured.rzCThe credential source "%s" referenced in profile "%s" is not valid.)rr is_supported)rSZparent_profilerr-r-r0rs  z.AssumeRoleProvider._validate_credential_sourcecCst||||gSr+)any_has_static_credentialsrrr-r-r0_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||vr(td||fd||}||jvr>dS||krTt||jd||slt||jddS)Nr\zFThe source_profile "%s" referenced in the profile "%s" does not exist.r)rZvisited_profiles)rIr=rrrr)rSZparent_profile_nameZsource_profile_namer\rr-r-r0rs*  z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nr8r7c3s|]}|vVqdSr+r-)rZ static_keyr!r-r0 'r2z=AssumeRoleProvider._has_static_credentials..)r)rSr!Z static_keysr-rr0r%sz*AssumeRoleProvider._has_static_credentialscCs<|d}|dur|||S|d}|j|||S)Nrr)r= _resolve_credentials_from_sourcerrA!_resolve_credentials_from_profile)rSrr5rrr-r-r0r)s  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dur~d}t ||d|S| |S)Nr\Tr8z.The source profile "%s" must have credentials.r) rIr=rr(_resolve_static_credentials_from_profilerr;rJrlrr)rSr5r\r!rLZ profile_chainr error_messager-r-r0r4s.   z4AssumeRoleProvider._resolve_credentials_from_profilec CsZzt|d|d|ddWStyT}zt|jt|dWYd}~n d}~00dS)Nr7r8r9rr@)r{r=rrrBstr)rSr!rr-r-r0rRs z;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dur$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %sr)rr*r)rSrr5rr-r-r0r]sz3AssumeRoleProvider._resolve_credentials_from_source)rhrirjrBrFrrZEXPIRY_WINDOW_SECONDSr)rTrrrrrrrrrrrrr-r-r-r0rB7s( 7 ,2 &  rBc@sReZdZdZdZddddZddd Zd d Zd d ZddZ ddZ ddZ dS)rdzassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZ AWS_ROLE_ARN)rrrFcCs:||_||_||_||_d|_||_|dur0t}||_dSr+)r)rHrrG_profile_config_disable_env_varsr_token_loader_cls)rSr3r4r5r)r9Ztoken_loader_clsr-r-r0rTus z*AssumeRoleWithWebIdentityProvider.__init__cCs|Sr+)_assume_role_with_web_identityr\r-r-r0rsz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdur.|}|di}||ji|_|j|Sr)rrHr=rG)rSkey loaded_configr\r-r-r0_get_profile_configs   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjvr.tj|SdSr+)r_CONFIG_TO_ENV_VARr=rre)rSrZenv_keyr-r-r0_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dur|S||Sr+)rr)rSrZ env_valuer-r-r0 _get_configs z-AssumeRoleWithWebIdentityProvider._get_configcCs||d}|sdS||}|d}|s8d}t|di}|d}|durV||d<t|j||||jd}t|j|jdS) NrrzThe provided profile or the current environment is configured to assume role with web identity but has no role ARN configured. Ensure that the profile has the role_arnconfiguration set or the AWS_ROLE_ARN env var is set.rrr)r4r<rrr)ra) rrrr:rr)rrBr )rSZ token_path token_loaderrrrrrbr-r-r0rs0      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) rhrirjrBrFrrTrrrrrr-r-r-r0rdls  rdc@s<eZdZddZddZddZddZd d Zd d Zd S)rDcCs ||_dSr+ _providersrSr;r-r-r0rTsz'CanonicalNameCredentialSourcer.__init__cCs|dd|jDvS)aLValidates a given source name. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: bool :returns: True if the credential provider is supported, False otherwise. cSsg|] }|jqSr-)rFrrYr-r-r0rr2z?CanonicalNameCredentialSourcer.is_supported..r)rS source_namer-r-r0rs z+CanonicalNameCredentialSourcer.is_supportedcCs$||}t|tr|S|S)aLoads source credentials based on the provided configuration. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: Credentials ) _get_providerrqrJrlr)rSrsourcer-r-r0r*s  z1CanonicalNameCredentialSourcer.source_credentialscCsV||}|dvr@|d}|dur@|dur4|St||gS|durRt|d|S)a#Return a credential provider by its canonical name. :type canonical_name: str :param canonical_name: The canonical name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )Z sharedconfigZsharedcredentialsrNname)_get_provider_by_canonical_namelower_get_provider_by_methodrJr )rScanonical_namerrKr-r-r0rs     z,CanonicalNameCredentialSourcer._get_providercCs2|jD]&}|j}|r||kr|SqdS)zReturn a credential provider by its canonical name. This function is strict, it does not attempt to address compatibility issues. N)rrFr)rSrrrr-r-r0r s z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"|jD]}|j|kr|SqdS)z0Return a credential provider by its METHOD name.N)rrB)rSrrr-r-r0rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) rhrirjrTrr*rrrr-r-r-r0rDs  & rDc@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)r?zcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|durtj}|durt}||_||_dSr+)rrerrt_fetcher)rSrerbr-r-r0rT$s zContainerProvider.__init__cCs$|j|jvs|j|jvr |SdSr+)ENV_VARrt ENV_VAR_FULL_retrieve_or_failr\r-r-r0r,szContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrr r)rrr rrr) _provided_relative_urirfull_urlrtrr_build_headers_create_fetcherrrBrs)rSfull_uriheadersrbrr-r-r0r2s   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dur"d|iSdS)N Authorization)rtr=ENV_VAR_AUTH_TOKEN)rSrZ auth_tokenr-r-r0rCs z ContainerProvider._build_headerscsfdd}|S)Nc szzjjd}WnFtyZ}z.tjd|ddtjt|dWYd}~n d}~00|d|d|d|d d S) N)rz'Error retrieving container metadata: %sTrrr|r}Tokenrr)rZretrieve_full_urirrHrIrrBr)rrrrrSr-r0 fetch_credsLs  z6ContainerProvider._create_fetcher..fetch_credsr-)rSrrrr-rr0rKsz!ContainerProvider._create_fetchercCs |j|jvSr+)rrtr\r-r-r0r^sz(ContainerProvider._provided_relative_uri)NN)rhrirjrBrFrrrrTrrrrrr-r-r-r0r?s r?c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rJcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. Nr:rr-r-r0rTcszCredentialResolver.__init__cCsJzdd|jD|}Wnty6t|dYn0|j||dS)a= Inserts a new instance of ``CredentialProvider`` into the chain that will be tried before an existing one. :param name: The short name of the credentials you'd like to insert the new credentials before. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` cSsg|] }|jqSr-rBrr-r-r0rzr2z4CredentialResolver.insert_before..rN)r;indexrr insertrSrZcredential_provideroffsetr-r-r0 insert_beforeks  z CredentialResolver.insert_beforecCs ||}|j|d|dS)a9 Inserts a new type of ``Credentials`` instance into the chain that will be tried after an existing one. :param name: The short name of the credentials you'd like to insert the new credentials after. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` rSN)_get_provider_offsetr;rrr-r-r0 insert_afters zCredentialResolver.insert_aftercCs6dd|jD}||vrdS||}|j|dS)z Removes a given ``Credentials`` instance from the chain. :param name: The short name of the credentials instance to remove. :type name: string cSsg|] }|jqSr-rrr-r-r0rr2z-CredentialResolver.remove..N)r;rpop)rSrZavailable_methodsrr-r-r0rGs  zCredentialResolver.removecCs|j||S)zReturn a credential provider by name. :type name: str :param name: The name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )r;rrSrr-r-r0 get_providers zCredentialResolver.get_providercCs:zdd|jD|WSty4t|dYn0dS)NcSsg|] }|jqSr-rrr-r-r0rr2z;CredentialResolver._get_provider_offset..r)r;rrr rr-r-r0rs z'CredentialResolver._get_provider_offsetcCs6|jD]*}td|j|}|dur|SqdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r;rHrIrBr)rSrrr-r-r0rls   z#CredentialResolver.load_credentialsN) rhrirjrTrrrGrrrlr-r-r-r0rJbs rJcs:eZdZdZd fdd ZddZddZd d ZZS) SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc s:||_||_||_||_||_||_tt|||dSr+) r _sso_region _role_name _account_id _start_url _token_loaderrrrT) rSZ start_url sso_regionr`Z account_idr4rr)rrr-r0rTs zSSOCredentialFetcher.__init__cCs>|j|j|jd}tj|ddd}t|d}||S)r)ZstartUrlroleName accountIdT),r)r separatorsr) rrrrrrr!r"rr#r-r-r0rs z&SSOCredentialFetcher._create_cache_keycCs$|d}tj|t}||jS)Ng@@)rn fromtimestamprru_UTC_DATE_FORMAT)rSZ timestamp_msZtimestamp_seconds timestampr-r-r0_parse_timestampsz%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}|j|j||jd}z|jfi|}Wn|j j ydt Yn0|d}d|d|d|d| |d d d }|S) z4Get credentials by calling SSO get role credentials.)r=r*ssor>)rrZ accessTokenZroleCredentialsZ accessKeyIdZsecretAccessKeyZ sessionTokenr)r|r}r~r)Z ProviderTyper{) r r rrrrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rSr'rryrrr-r-r0r s,    z%SSOCredentialFetcher._get_credentials)NNN) rhrirjrrTrrr rr-r-rr0rs rc@sLeZdZdZejejddddZgdZ d ddZ d d Z d d Z dS)rfrrrr)) sso_start_urlr sso_role_namesso_account_idNcCs@|durt|j}||_|dur$i}||_||_||_||_dSr+)r_SSO_TOKEN_CACHE_DIR _token_cacher)rHrrG)rSr3r4r5r)rer-r-r0rTs zSSOProvider.__init__cs|}|di}|j}||jitfdd|jDrDdSi}g}|jD]$}|vrl|||<qR||qR|rd|}td||fd|S)Nr\c3s|]}|vVqdSr+r-)rcr]r-r0r-r2z/SSOProvider._load_sso_config..rzSThe profile "%s" is configured to use SSO but is missing required configuration: %sr)rHr=rGall_SSO_CONFIG_VARSrArr)rSrr\r5r'Zmissing_config_varsZ config_varmissingr-rr0_load_sso_config's(    zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)Nrrrr)r))rr)ra) rrrrrr)rrBr )rSZ sso_configZ sso_fetcherr-r-r0rCs   zSSOProvider.load)NN) rhrirjrBrrrrrrrTrrr-r-r-r0rfs rf)NN)F)Qrrnloggingrr)rrrT collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrrZbotocore.configloaderrZbotocore.compatr r r Zbotocore.configr Zbotocore.exceptionsr rrrrrrrrZbotocore.utilsrrrrrr getLoggerrhrHrrNrrArmrprsrwrCrrrr{rrrrr%r:r?r]r@r>rEr`rcrFrBrdrDr?rJrrfr-r-r-r0s                       VD  3'E1P 9-Ft"*7*7YXEdH