B =@Sa?@sNddlZddlZddlZddlZddlZddlZddlZddlZddlm 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 ddddgZ/d^ddZ0Gdd d e1Z2d!d"Z3d#d$Z4d%d&Z5d_d(d)Z6d*d+Z7d,d-Z8d.d/Z9Gd0d1d1e1Z:Gd2d3d3e1Z;Gd4d5d5e;ZGd:d;d;e>Z?Gdd?d?e?ZAGd@dAdAe1ZBGdBdCdCeBZCGdDdEdEeBZDGdFdGdGeBZEGdHdIdIeBZFGdJdKdKeBZGGdLdMdMeBZHGdNdOdOeBZIGdPdQdQeBZJGdRdSdSeBZKGdTdUdUe1ZLGdVdWdWeBZMGdXdYdYe1ZNGdZd[d[e>ZOGd\d]d]eBZPdS)`N) namedtuple)deepcopy)sha1)parse)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}ddk }dtd}|dkrTi}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_namecsjS)N) full_config)sessionr*l/private/var/folders/fg/1jzmct0d7d72tjkvm_1nhqc5sw67yj/T/pip-unpacked-wheel-ef76ia09/botocore/credentials.py\z,create_credential_resolver..) load_configclient_creatorr' profile_namecredential_sourcerprofile_provider_builder)r1disable_env_varszWSkipping environment variable credential check because profile name was explicitly set.) providers)get_config_variableZinstance_variablesgetr EnvProviderContainerProviderInstanceMetadataProviderrr$ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr5OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r+r'r(r1Zmetadata_timeoutr#r4Z imds_configZ env_providerZcontainer_providerZinstance_metadata_providerr3assume_role_providerZ pre_profileprofile_providersZ post_profiler5resolverr*)r+r,create_credential_resolver8sV           rHc@sLeZdZdZdddZdddZdd Zd d Zd d ZddZ ddZ dS)r;aThis 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||_||_||_||_dS)N)_session_cache _region_name_sso_token_cache)selfr+r'r(Zsso_token_cacher*r*r,__init__szProfileProviderBuilder.__init__FcCs.|||||||||||gS)N)_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_provider)rMr1r4r*r*r,r5s z ProfileProviderBuilder.providerscst|fdddS)NcsjjS)N)rIr)r*)rMr*r,r-r.zAProfileProviderBuilder._create_process_provider..)r1r/)ProcessProvider)rMr1r*)rMr,rRsz/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r1creds_filename)rIr6SharedCredentialProvider)rMr1Zcredential_filer*r*r,rQs z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r1config_filename)rIr6ConfigProvider)rMr1rWr*r*r,rSs z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjS)N)rIr)r*)rMr*r,r-r.zFProfileProviderBuilder._create_web_identity_provider..)r/r0r'r1r4)!AssumeRoleWithWebIdentityProviderr=rIrKrJ)rMr1r4r*)rMr,rOs  z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)NcsjjS)N)rIr)r*)rMr*r,r-r.z=ProfileProviderBuilder._create_sso_provider..)r/r0r1r' token_cache) SSOProviderrI create_clientrJrL)rMr1r*)rMr,rPs  z+ProfileProviderBuilder._create_sso_provider)NNN)F) __name__ __module__ __qualname____doc__rNr5rRrQrSrOrPr*r*r*r,r;s    r;cCst|}|S)N)rHload_credentials)r+rGr*r*r,get_credentialssrccCstjtS)N)datetimenowrr*r*r*r, _local_nowsrfcCst|tjr|St|S)N) isinstancerdr)valuer*r*r,_parse_if_neededs riFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rgrd isoformatstrftime)rhisor*r*r,_serialize_if_neededs   rmcsfdd}|S)Ncs"di}|jf|j|f|S)Nr()updater])Z service_namekwargsZcreate_client_kwargs)r(r+r*r,r0s z+_get_client_creator..client_creatorr*)r+r(r0r*)r(r+r,r=sr=csfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerm)response credentials)clientparamsr*r,refreshs  z-create_assume_role_refresher..refreshr*)ryrzr{r*)ryrzr,create_assume_role_refreshers r|cCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rMr{r*r*r,rNsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)r~rr})rMr*r*r,__call__ sz8create_mfa_serial_refresher.._Refresher.__call__N)r^r_r`rNrr*r*r*r, _Refreshersr)object)Zactual_refreshrr*r*r,create_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. ~z.awsZbotor'NcCs||_|dkr|j}||_dS)N) _working_dir_default_dumps_dumps)rMZ working_dirZ dumps_funcr*r*r,rN szJSONFileCache.__init__cCstj|tdS)N)r )jsondumpsrm)rMobjr*r*r,r&szJSONFileCache._default_dumpscCs||}tj|S)N)_convert_cache_keyospathisfile)rM cache_key actual_keyr*r*r, __contains__)s zJSONFileCache.__contains__c CsP||}yt| }t|SQRXWn"tttfk rJt|YnXdS)z Retrieve value from a cache key.N)ropenrloadOSError ValueErrorIOErrorKeyError)rMrrfr*r*r, __getitem__-s   zJSONFileCache.__getitem__c Cs||}y||}Wn$ttfk r<td|YnXtj|jsXt|jt t |tj tj Bdd}| ||WdQRXdS)Nz5Value cannot be cached, must be JSON serializable: %siw)rr TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rMrrhZfull_keyZ file_contentrr*r*r, __setitem__6s   zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rMr full_pathr*r*r,rDsz JSONFileCache._convert_cache_key)r^r_r`rarr expanduserrZ CACHE_DIRrNrrrrrr*r*r*r,rs rc@s*eZdZdZd ddZddZddZdS) rpa\ 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||_||_||_|dkrd}||_|dS)Nexplicit)rrrmethod _normalize)rMrrrrr*r*r,rNTszCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)rMr*r*r,r`szCredentials._normalizecCst|j|j|jS)N)rrrr)rMr*r*r,get_frozen_credentialsjsz"Credentials.get_frozen_credentials)NN)r^r_r`rarNrrr*r*r*r,rpIs    rpc@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. iiXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dS)N) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rMrrrru refresh_usingr time_fetcherr*r*r,rNs  zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)rMr*r*r,rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrrru)rrrrurr)_expiry_datetime)clsmetadatarrinstancer*r*r,create_from_metadatas z+RefreshableCredentials.create_from_metadatacCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r}r)rMr*r*r,rsz!RefreshableCredentials.access_keycCs ||_dS)N)r)rMrhr*r*r,rscCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r}r)rMr*r*r,rsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)rMrhr*r*r,rscCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r}r)rMr*r*r,rszRefreshableCredentials.tokencCs ||_dS)N)r)rMrhr*r*r,rscCs|j|}t|S)N)rrr )rMdeltar*r*r,_seconds_remainingsz)RefreshableCredentials._seconds_remainingNcCs:|jdkrdS|dkr|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_timeoutrrBrC)rM refresh_inr*r*r,refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)rMr*r*r, _is_expiredsz"RefreshableCredentials._is_expiredc Cs||jsdS|jdrXz,||js.dS||j}|j|ddS|jXn:||jr|j"||js|dS|jddWdQRXdS)NF) is_mandatoryT)rrracquire_mandatory_refresh_timeout_protected_refreshrelease)rMZis_mandatory_refreshr*r*r,r}s       zRefreshableCredentials._refreshc Csy |}WnDtk rP}z&|r&dnd}tjd|dd|r@dSd}~XYnX||t|j|j|j|_ | rd}t|t |dS)N mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.T)exc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r ExceptionrBwarning_set_from_datarrrrrr RuntimeError)rMrreZ period_namemsgr*r*r,rs      z)RefreshableCredentials._protected_refreshcCst|S)N)r)Ztime_strr*r*r,r0sz'RefreshableCredentials._expiry_datetimecsddddg}s|}nfdd|D}|rHd}t|j|d|d d|_d|_d|_td|_t d |j| dS) Nrrrrucsg|]}|kr|qSr*r*).0k)datar*r, 9sz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %sz, )provider error_msgz(Retrieved credentials will expire at: %s) rrrrrrrrrBrCr)rMrZ expected_keysZ missing_keysmessager*)rr,r4s     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) )r}r)rMr*r*r,rJs"z-RefreshableCredentials.get_frozen_credentials)N)r^r_r`rarrrfrNr classmethodrpropertyrsetterrrrrrr}r staticmethodrrrr*r*r*r,rps(      "! 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|_ dS)N) rrrrrrrrrrr)rMrrrr*r*r,rNus z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||S)NT)rsuperrr)rMr) __class__r*r,rs  z-DeferredRefreshableCredentials.refresh_needed)N)r^r_r`rarfrNr __classcell__r*r*)rr,rps rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcheriNcCs4|dkr i}||_||_|dkr*|j}||_dS)N)rJ_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rMr'expiry_window_secondsr*r*r,rNs z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)rMr*r*r,rsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rMfilenamer*r*r,_make_file_safesz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)rMr*r*r,_get_credentialssz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)rMr*r*r,fetch_credentialssz)CachedCredentialFetcher.fetch_credentialscCs`|}|dkr$|}||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.rprtT)rlrqrrrs)rrrru)_load_from_cacher_write_to_cacherBrCrm)rMrwcreds expirationr*r*r,rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrJrrrBrC)rMrr*r*r,rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrJr)rMrwr*r*r,rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rprt)rir rfr)rMrxZend_timesecondsr*r*r,rsz#CachedCredentialFetcher._is_expired)NN) r^r_r`rrNrrrrrrrrr*r*r*r,rs  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|dkri|_n t||_|j|jd<|jd|_d|_|jsT|tt | ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr7_role_session_name_using_default_session_name_generate_assume_role_namerrrN)rMr0role_arn extra_argsr'r)rr*r,rNs   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srT)inttimerrr)rMr*r*r,rs z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namecCsZt|j}|jr|d=d|kr0t|d|d<tj|dd}t|d}| |S)zCreate a predictable cache key for the current configuration. The cache key is intended to be compatible with file names. rPolicyT) sort_keyszutf-8) rrrrloadsrrencode hexdigestr)rMargs argument_hashr*r*r,rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)r^r_r`rNrrrr*r*)rr,rsrcs6eZdZd fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs<||_||_|jdkrtj|_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, N)rr'r)_source_credentials _mfa_promptergetpassrr rN)rMr0source_credentialsrr mfa_prompterr'r)rr*r,rNs"  z$AssumeRoleCredentialFetcher.__init__cCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientrv)rMroryr*r*r,r+sz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dk r6d|}||}||d<|d}|dk rP||d<|S)zAGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rrr7r )rMassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr*r*r,r1s    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)rMZfrozen_credentialsr*r*r,rCs  z*AssumeRoleCredentialFetcher._create_client)NNNN)r^r_r`rNrrrrr*r*)rr,r 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, )rr'rN)_web_identity_token_loaderrrrN)rMr0web_identity_token_loaderrrr'r)rr*r,rNQs z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs,|}ttd}|jd|d}|jf|S)z'Get credentials by calling assume role.)signature_versionr)r%)rr rrZassume_role_with_web_identity)rMror%ryr*r*r,rus z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)zAGet the arguments for assume role based on current configuration.ZWebIdentityToken)rrr)rMrZidentity_tokenr*r*r,r~s z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)r^r_r`rNrrrr*r*)rr,rNs# rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r+)rMr+r*r*r,rNszCredentialProvider.__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*)rMr*r*r,rszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendrr METHOD)rMmappingZ key_namesfoundZkey_namer*r*r,_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)r^r_r`r#CANONICAL_NAMErNrr&r*r*r*r,r s  r c@s:eZdZdZejfddZddZddZe dd Z d S) rTzcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)rMr1r/popenr*r*r,rNszProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)Nrucs S)N)_retrieve_credentials_usingr*)credential_processrMr*r,r-r.z&ProcessProvider.load..rrr)rrrr)_credential_processr-r7rrr#rp)rMZ creds_dictr*)r.rMr,rs  zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|dy"|d |d | d | d d Stk r}zt|jd|dWdd}~XYnXdS)N)stdoutstderrrzutf-8)rrVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1rqrrrsrt)rrrruz$Missing required key in response: %s)r r+ subprocessPIPE communicate returncoderr#decoderrrrr7r) rMr.Z process_listpr0r1parsedversionrr*r*r,r-s0     z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr.)r*r)r7r()rMprofile_configr*r*r,r/s   z#ProcessProvider._credential_processN) r^r_r`r#r4PopenrNrr-rr/r*r*r*r,rTs rTc@s$eZdZdZdZddZddZdS)r:ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)rMr&r*r*r,rNsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_name)rr)r?Zretrieve_iam_role_credentialsrBrCrrr#)rMfetcherrrr*r*r,rs  zInstanceMetadataProvider.loadN)r^r_r`r#r'rNrr*r*r*r,r:sr:c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r8env EnvironmentZAWS_ACCESS_KEY_IDZAWS_SECRET_ACCESS_KEYZAWS_SECURITY_TOKENZAWS_SESSION_TOKENZAWS_CREDENTIAL_EXPIRATIONNcCs$|dkrtj}||_|||_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)rMrDr$r*r*r,rN s zEnvProvider.__init__cCsi}|dkr6|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)Nrrrru) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr7rglist)rMr$Z var_mappingr*r*r,rE0s"    zEnvProvider._build_mappingcCs|j|jdd}|rtd|}|dd}|d}|dk rnt|}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_expiryruNrr)rr)r) rDr7rFrBinfo_create_credentials_fetcherrrr#rp)rMrrArxrur*r*r,rFs      zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|s(tdd||d<dd}|sTtdd||d<d|d<x*dD]}|d}|rn||d<PqnWd|d<dd}|r||d<|r|stdd|S)NrrL)rr!rrru)r7r )rMrxrrZ token_env_varrru)rDr$rr*r,rgs2 zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rFr#rD)rMrr*)rDr$rr,rObs  z'EnvProvider._create_credentials_fetcher)NN) r^r_r`r#r'rGrHrIrJrNrErrOr*r*r*r,r8s r8c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r?zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rrDr_environ_parser)rMrDparserr*r*r,rNs zOriginalEC2Provider.__init__cCshd|jkr`tj|jd}||}|j|krdtd||j}||j}t |||j dSndSdS)zN Search for a credential file used by original EC2 CLI tools. rPz)Found credentials in AWS_CREDENTIAL_FILE.)rN) rQrrrrRrGrBrNrHrpr#)rMrrrrr*r*r,rs       zOriginalEC2Provider.load)NN) r^r_r`r#r'Z CRED_FILE_ENVrGrHrNrr*r*r*r,r?s r?c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rVzshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr )_creds_filenamer(r configloaderraw_config_parse _ini_parser)rMrUr1 ini_parserr*r*r,rNsz!SharedCredentialProvider.__init__cCsy||j}Wntk r$dSX|j|kr||j}|j|krtd|j|||j|j\}}| |}t ||||j dSdS)Nz0Found credentials in shared credentials file: %s)r) rXrUrr(rGrBrNr&rH_get_session_tokenrpr#)rMZavailable_credsr%rrrr*r*r,rs    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)rI)rMr%Z token_envvarr*r*r,rZs z+SharedCredentialProvider._get_session_token)NN) r^r_r`r#r'rGrHrIrNrrZr*r*r*r,rVs rVc@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)rYz0INI based config provider with profile sections.z config-fileZ SharedConfigrrrTrNcCs&||_||_|dkrtjj}||_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_filenamer(rrVr/_config_parser)rMrXr1Z config_parserr*r*r,rNs zConfigProvider.__init__cCsy||j}Wntk r$dSX|j|dkr|d|j}|j|krtd|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: %s)r) r\r[rr(rGrBrNr&rHrZrpr#)rMr)r=rrrr*r*r,rs   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)rI)rMr=Z token_namer*r*r,rZs z!ConfigProvider._get_session_token)N) r^r_r`rar#r'rGrHrIrNrrZr*r*r*r,rYs rYc@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r@z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rrDrrVrWrQrX)rMrDrYr*r*r,rNs zBotoProvider.__init__c Cs|j|jkr|j|jg}n|j}x~|D]v}y||}Wntk rPw(YnXd|kr(|d}|j|kr(td||||j|j \}}t |||j dSq(WdS)z; Look for credentials in boto config file. rpz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVrQDEFAULT_CONFIG_FILENAMESrXrrGrBrNr&rHrpr#)rMZpotential_locationsrr%rxrrr*r*r,rs"   zBotoProvider.load)NN) r^r_r`r#r'r]r^rGrHrNrr*r*r*r,r@ s r@c@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) r<z assume-roleNrweb_identity_token_fileicCs>||_||_||_||_||_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'r)rr( _prompterr*_credential_sourcer_profile_provider_builder_visited_profiles)rMr/r0r'r1Zprompterr2r3r*r*r,rNFs$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr<)r)r*r7r(_has_assume_role_config_vars_load_creds_via_assume_role)rMr<rr*r*r,r}s   zAssumeRoleProvider.loadcCs|j|ko|j|kS)N)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VAR)rMrr*r*r,rds z/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dk r4||d<|d}|dk rN||d<|d}|dk rh||d<|d}|dk r||d<t|j||d ||j|jd } | j} |dk rt| } t |j | t d S) Nrole_session_namer external_idZ ExternalIdrrrrr)r0rrrrr')rrr) _get_role_config_resolve_source_credentialsr7r rr`r'rrrr#rf) rMr1 role_configrrrhrirrrAZ refresherr*r*r,res<      z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d k ryt| | d<Wntk rYnX|d k r|d k rtd |d nB|d kr|d krt|jd dn"|d k r|||n |||| S)z?Retrieves and validates the role configuration for the profile.r<source_profilercredential_sourcerrirhr)rrirrhrmrnNzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr!) r*r7rrrr r#_validate_credential_source_validate_source_profile) rMr1r<rrmrrnrrirhrrlr*r*r,rjsB          z#AssumeRoleProvider._get_role_configcCs>|jdkrtd||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.)rar is_supported)rMZparent_profilernr*r*r,ros  z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsrd)rMrr*r*r,_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||kr(td||fd||}||jkr>dS||krTt||jd||slt||jddS)Nr<zFThe source_profile "%s" referenced in the profile "%s" does not exist.)r)rmZvisited_profiles)r*r7rrcrrs)rMZparent_profile_nameZsource_profile_namer<rmr*r*r,rps    z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr*)rZ static_key)rr*r, 'sz=AssumeRoleProvider._has_static_credentials..)rr)rMrZ static_keysr*)rr,rs%sz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)Nrnrm)r7 _resolve_credentials_from_sourcercr"!_resolve_credentials_from_profile)rMrlr1rnrmr*r*r,rk)s  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dkr~d}t ||d|S| |S)Nr<T)r1r4z.The source profile "%s" must have credentials.)r) r*r7rsrb(_resolve_static_credentials_from_profilerdr5rDrbrre)rMr1r<rrFZ profile_chainrx error_messager*r*r,rw4s$     z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr)rr!)rpr7rr r#str)rMrrr*r*r,rxRsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)rarr)rMrnr1rxr*r*r,rv]s z3AssumeRoleProvider._resolve_credentials_from_source)r^r_r`r#r'rfrgZEXPIRY_WINDOW_SECONDSr rNrrdrerjrortrprsrkrwrxrvr*r*r*r,r<7s& 5 ,2 &  r<c@sReZdZdZdZddddZddd Zd d Zd d ZddZ ddZ ddZ dS)rZzassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZ AWS_ROLE_ARN)r_rhrFcCs:||_||_||_||_d|_||_|dkr0t}||_dS)N)r'r)rr(_profile_config_disable_env_varsr_token_loader_cls)rMr/r0r1r'r4Ztoken_loader_clsr*r*r,rNus z*AssumeRoleWithWebIdentityProvider.__init__cCs|S)N)_assume_role_with_web_identity)rMr*r*r,rsz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdkr.|}|di}||ji|_|j|S)Nr<)r{r)r7r()rMkey loaded_configr<r*r*r,_get_profile_configs   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjkr.tj|SdS)N)r|_CONFIG_TO_ENV_VARr7rrD)rMrZenv_keyr*r*r,_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dk r|S||S)N)rr)rMrZ env_valuer*r*r, _get_configs z-AssumeRoleWithWebIdentityProvider._get_configcCs||d}|sdS||}|d}|s8d}t|di}|d}|dk rV||d<t|j||||jd}t|j|jdS) Nr_rzThe 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.)rrhr)r0rrrr')rr) rr}rrrr'rr#r)rMZ token_path token_loaderrrrrhrAr*r*r,r~s*      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) r^r_r`r#r'rrNrrrrr~r*r*r*r,rZls rZc@s<eZdZddZddZddZddZd d Zd d Zd S)r>cCs ||_dS)N) _providers)rMr5r*r*r,rNsz'CanonicalNameCredentialSourcer.__init__cCs|dd|jDkS)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*)r')rr9r*r*r,rsz?CanonicalNameCredentialSourcer.is_supported..)r)rM source_namer*r*r,rqs 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_providerrgrDrbr)rMrsourcer*r*r,rs  z1CanonicalNameCredentialSourcer.source_credentialscCsV||}|dkr@|d}|dk r@|dkr4|St||gS|dkrRt|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 sharedconfigZsharedcredentialsz assume-roleN)name)_get_provider_by_canonical_namelower_get_provider_by_methodrDr )rMcanonical_namerrEr*r*r,rs     z,CanonicalNameCredentialSourcer._get_providercCs2x,|jD]"}|j}|r||kr|SqWdS)zReturn a credential provider by its canonical name. This function is strict, it does not attempt to address compatibility issues. N)rr'r)rMrrrr*r*r,r s z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"x|jD]}|j|kr|SqWdS)z0Return a credential provider by its METHOD name.N)rr#)rMrrr*r*r,rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r^r_r`rNrqrrrrr*r*r*r,r>s  & r>c@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)r9zcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|dkrtj}|dkrt}||_||_dS)N)rrDrrQ_fetcher)rMrDrAr*r*r,rN$s zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARrQ ENV_VAR_FULL_retrieve_or_fail)rMr*r*r,r,szContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrrru)rrrrrur) _provided_relative_urirfull_urlrQrr_build_headers_create_fetcherrr#ri)rMfull_uriheadersrArr*r*r,r2s   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)rQr7ENV_VAR_AUTH_TOKEN)rMrZ auth_tokenr*r*r,rCsz ContainerProvider._build_headerscsfdd}|S)Nc sxyjjd}WnDtk rX}z&tjd|ddtjt|dWdd}~XYnX|d|d|d|d d S) N)rz'Error retrieving container metadata: %sT)r)rrrqrrTokenrt)rrrru)rZretrieve_full_urirrBrCrr#rz)rwr)rrrMr*r, fetch_credsLsz6ContainerProvider._create_fetcher..fetch_credsr*)rMrrrr*)rrrMr,rKsz!ContainerProvider._create_fetchercCs |j|jkS)N)rrQ)rMr*r*r,r^sz(ContainerProvider._provided_relative_uri)NN)r^r_r`r#r'rrrrNrrrrrr*r*r*r,r9s r9c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rDcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. N)r5)rMr5r*r*r,rNcszCredentialResolver.__init__cCsLydd|jD|}Wntk r8t|dYnX|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*)r#)rr9r*r*r,rzsz4CredentialResolver.insert_before..)rN)r5indexrr insert)rMrcredential_provideroffsetr*r*r, 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`` r3N)_get_provider_offsetr5r)rMrrrr*r*r, insert_afters zCredentialResolver.insert_aftercCs6dd|jD}||krdS||}|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*)r#)rr9r*r*r,rsz-CredentialResolver.remove..N)r5rpop)rMrZavailable_methodsrr*r*r,rAs  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. )r5r)rMrr*r*r, get_providers zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr*)r#)rr9r*r*r,rsz;CredentialResolver._get_provider_offset..)r)r5rrr )rMrr*r*r,rsz'CredentialResolver._get_provider_offsetcCs6x0|jD]&}td|j|}|dk r|SqWdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r5rBrCr#r)rMrrr*r*r,rbs  z#CredentialResolver.load_credentialsN) r^r_r`rNrrrArrrbr*r*r*r,rDbs rDcs:eZdZdZd fdd ZddZddZd d ZZS) SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc s:||_||_||_||_||_||_tt|||dS)N) r _sso_region _role_name _account_id _start_url _token_loaderrrrN) rMZ start_url sso_regionr@Z account_idr0rr'r)rr*r,rNs zSSOCredentialFetcher.__init__cCs>|j|j|jd}tj|ddd}t|d}||S)zCreate a predictable cache key for the current configuration. The cache key is intended to be compatible with file names. )ZstartUrlroleName accountIdT),r)r separatorszutf-8) rrrrrrrrr)rMrr r*r*r,rs  z&SSOCredentialFetcher._create_cache_keycCs$|d}tj|t}||jS)Ng@@)rd fromtimestamprrk_UTC_DATE_FORMAT)rMZ timestamp_msZtimestamp_seconds timestampr*r*r,_parse_timestampsz%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}|j|j||jd}y|jf|}Wn|j j k rbt YnX|d}d|d|d|d| |d d d }|S) z4Get credentials by calling SSO get role credentials.)rr(sso)r%)rrZ accessTokenZroleCredentialsZ accessKeyIdZsecretAccessKeyZ sessionTokenr)rqrrrsrt)Z ProviderTyperp) r rrrrrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rMr%ryrorwrxr*r*r,rs$  z%SSOCredentialFetcher._get_credentials)NNN) r^r_r`rrNrrrrr*r*)rr,rs  rc@sPeZdZdZejejddddZddddgZ dd d Z d d Z ddZ d S)r\rrz.awsr' sso_start_urlr sso_role_namesso_account_idNcCs@|dkrt|j}||_|dkr$i}||_||_||_||_dS)N)r_SSO_TOKEN_CACHE_DIR _token_cacher'r)rr()rMr/r0r1r'r[r*r*r,rNs zSSOProvider.__init__cs|}|di}|j}||jitfdd|jDrDdSi}g}x.|jD]$}|krn|||<qT||qTW|rd|}td||fd|S)Nr<c3s|]}|kVqdS)Nr*)rc)r=r*r,ru-sz/SSOProvider._load_sso_config..z, zSThe profile "%s" is configured to use SSO but is missing required configuration: %s)r)r)r7r(all_SSO_CONFIG_VARSr"rr)rMrr<r1r%Zmissing_config_varsZ config_varmissingr*)r=r,_load_sso_config's$   zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)Nrrrr)r')rr')rr) rrrrrr'rr#r)rMZ sso_configZ sso_fetcherr*r*r,rCs  zSSOProvider.load)NN) r^r_r`r#rrrrrrrNrrr*r*r*r,r\s r\)NN)F)Qrrdloggingrr rrr4 collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrrZbotocore.configloaderrZbotocore.compatrr r Zbotocore.configr Zbotocore.exceptionsr r rrrrrrrZbotocore.utilsrrrrrr getLoggerr^rBrrHrr;rcrfrirmr=r|rrrprrrrr rr rTr:r8r?rVrYr@r<rZr>r9rDrr\r*r*r*r,s                        VD  3'E1P 8-Ft"*7*7YXEdH