U m^'@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlZddlZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$m%Z%ddl#m&Z&ddl#m'Z'e(e)Z*e ddddgZ+dWddZ,Gddde-Z.ddZ/d d!Z0d"d#Z1dXd%d&Z2d'd(Z3d)d*Z4d+d,Z5Gd-d.d.e-Z6Gd/d0d0e-Z7Gd1d2d2e7Z8Gd3d4d4e8Z9Gd5d6d6e-Z:Gd7d8d8e:Z;Gd9d:d:e;Zd>e-Z>Gd?d@d@e>Z?GdAdBdBe>Z@GdCdDdDe>ZAGdEdFdFe>ZBGdGdHdHe>ZCGdIdJdJe>ZDGdKdLdLe>ZEGdMdNdNe>ZFGdOdPdPe>ZGGdQdRdRe-ZHGdSdTdTe>ZIGdUdVdVe-ZJdS)YN) namedtuple)deepcopy)sha1parse)tzlocal)UNSIGNED) total_seconds)compat_shell_split)Config)UnknownCredentialError)PartialCredentialsError)ConfigNotFound)InvalidConfigError)InfiniteLoopConfigError)RefreshWithMFAUnsupportedError)MetadataRetrievalError)CredentialRetrievalError)InstanceMetadataFetcherparse_key_val_file)ContainerMetadataFetcher)FileWebIdentityTokenLoaderReadOnlyCredentials access_key secret_keytokenc sdp d}d}d}ddk }|dkr@i}t}t}tt||dd} t||d} t fd d t |||t ||| g| d } || g} | j ||d } t t|| g}| | |}|r||td t|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_attemptsN)timeout num_attempts user_agent)iam_role_fetcher)cache region_namecsjSN) full_configsessionr&n/private/var/folders/sd/whlwsn6x1_qgglc0mjv25_695qk2gl/T/pip-install-4zq3fp6i/botocore/botocore/credentials.pyQz,create_credential_resolver..) load_configclient_creatorr" profile_namecredential_sourcerprofile_provider_builderr.disable_env_varszWSkipping environment variable credential check because profile name was explicitly set. providers)get_config_variableZinstance_variablesget EnvProviderContainerProviderInstanceMetadataProviderrr ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr4OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r(r"r#r.Zmetadata_timeoutrr2Z env_providerZcontainer_providerZinstance_metadata_providerr0assume_role_providerZ pre_profileprofile_providersZ post_profiler4resolverr&r'r)create_credential_resolver5sd        rGc@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ 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||_||_||_dSr$)_session_cache _region_name)selfr(r"r#r&r&r)__init__szProfileProviderBuilder.__init__FcCs&|||||||||gSr$)_create_web_identity_provider"_create_shared_credential_provider_create_process_provider_create_config_providerrKr.r2r&r&r)r4sz ProfileProviderBuilder.providerscst|fdddS)NcsjjSr$rHr%r&rKr&r)r*r+zAProfileProviderBuilder._create_process_provider..)r.r,)ProcessProvider)rKr.r&rSr)rOs z/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r.creds_filename)rHr5SharedCredentialProvider)rKr.Zcredential_filer&r&r)rNs  z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r.config_filename)rHr5ConfigProvider)rKr.rWr&r&r)rPs  z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjSr$rRr&rSr&r)r*r+zFProfileProviderBuilder._create_web_identity_provider..)r,r-r"r.r2)!AssumeRoleWithWebIdentityProviderr<rHrJrIrQr&rSr)rMs z4ProfileProviderBuilder._create_web_identity_provider)NN)F) __name__ __module__ __qualname____doc__rLr4rOrNrPrMr&r&r&r)r:s  r:cCst|}|Sr$)rGload_credentials)r(rFr&r&r)get_credentialssr`cCstjtSr$)datetimenowrr&r&r&r) _local_nowsrccCst|tjr|St|Sr$) isinstancerar)valuer&r&r)_parse_if_neededs rfFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rdra isoformatstrftime)reisor&r&r)_serialize_if_neededs   rjcsfdd}|S)Ncs"di}|jf|j|f|S)Nr#)updateZ create_client)Z service_namekwargsZcreate_client_kwargsr#r(r&r)r-s  z+_get_client_creator..client_creatorr&)r(r#r-r&rmr)r<sr<csfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expirationrrr expiry_time) assume_rolerj)response credentialsclientparamsr&r)refreshs  z-create_assume_role_refresher..refreshr&)ryrzr{r&rxr)create_assume_role_refreshers r|cCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rKr{r&r&r)rLsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|SNT)r~rr}rSr&r&r)__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)r[r\r]rLrr&r&r&r) _Refreshersr)object)Zactual_refreshrr&r&r)create_mfa_serial_refreshersrc@sVeZdZdZejejddddZefddZ dd Z d d Z d d Z ddZ dS) 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"cCs ||_dSr$) _working_dir)rKZ working_dirr&r&r)rL szJSONFileCache.__init__cCs||}tj|Sr$)_convert_cache_keyospathisfile)rK cache_key actual_keyr&r&r) __contains__ s zJSONFileCache.__contains__c Cs^||}z,t|}t|W5QRWSQRXWn"tttfk rXt|YnXdS)z Retrieve value from a cache key.N)ropenjsonloadOSError ValueErrorIOErrorKeyError)rKrrfr&r&r) __getitem__s   "zJSONFileCache.__getitem__c Cs||}ztj|td}Wn$ttfk r@td|YnXtj|j s\t |j t t |tj tjBdd}|||W5QRXdS)N)rz5Value cannot be cached, must be JSON serializable: %siw)rrdumpsrj TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rKrreZfull_keyZ file_contentrr&r&r) __setitem__s$     zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rKr full_pathr&r&r)r'sz JSONFileCache._convert_cache_keyN)r[r\r]r^rr expanduserrZ CACHE_DIRrLrrrrr&r&r&r)rs  rc@s*eZdZdZd ddZddZddZdS) rna\ 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)rKrrrrr&r&r)rL7szCredentials.__init__cCs$tj|j|_tj|j|_dSr$)botocorecompatensure_unicoderrrSr&r&r)rCszCredentials._normalizecCst|j|j|jSr$)rrrrrSr&r&r)get_frozen_credentialsMsz"Credentials.get_frozen_credentials)NN)r[r\r]r^rLrrr&r&r&r)rn,s    rnc@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)rKrrrrt refresh_usingr time_fetcherr&r&r)rLes zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dSr$)rrrrrrSr&r&r)rtsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrrrt)rrrrtrr)_expiry_datetime)clsmetadatarrinstancer&r&r)create_from_metadataxs 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. )r}rrSr&r&r)rsz!RefreshableCredentials.access_keycCs ||_dSr$)rrKrer&r&r)rscCs||jSr)r}rrSr&r&r)rsz!RefreshableCredentials.secret_keycCs ||_dSr$)rrr&r&r)rscCs||jSr)r}rrSr&r&r)rszRefreshableCredentials.tokencCs ||_dSr$)rrr&r&r)rscCs|j|}t|Sr$)rrr )rKdeltar&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 neeeded, False otherwise. NFz!Credentials need to be refreshed.T)r_advisory_refresh_timeoutrrArBrK refresh_inr&r&r)refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)rrSr&r&r) _is_expiredsz"RefreshableCredentials._is_expiredc Cs||jsdS|jdr`z4||js2W$dS||j}|j|dWdS|jXnD||jr|j,||jsW5QRdS|jddW5QRXdS)NF) is_mandatoryT)rrracquirerelease_mandatory_refresh_timeout_protected_refresh)rKZis_mandatory_refreshr&r&r)r}s"      zRefreshableCredentials._refreshc Csz |}WnJtk rV}z,|r&dnd}tjd|dd|r@WYdSd}~XYnX||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 ExceptionrAwarning_set_from_datarrrrrr RuntimeError)rKrreZ period_namemsgr&r&r)rs*    z)RefreshableCredentials._protected_refreshcCst|Sr$r)Ztime_strr&r&r)rsz'RefreshableCredentials._expiry_datetimecsddddg}s|}nfdd|D}|rHd}t|j|d|d d|_d|_d|_td|_t d |j| dS) Nrrrrtcsg|]}|kr|qSr&r&).0kdatar&r) sz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %sz, provider error_msgz(Retrieved credentials will expire at: %s) rrrrrrrrrArBr)rKrZ expected_keysZ missing_keysmessager&rr)rs$     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}rrSr&r&r)r-s"z-RefreshableCredentials.get_frozen_credentials)N)r[r\r]r^rrrcrLr classmethodrpropertyrsetterrrrrrr}r staticmethodrrrr&r&r&r)rSs:          "! 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)rKrrrr&r&r)rLXs z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||Sr)rsuperrrr __class__r&r)rcs   z-DeferredRefreshableCredentials.refresh_needed)N)r[r\r]r^rcrLr __classcell__r&r&rr)rSs rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcherrNcCs4|dkr i}||_||_|dkr*|j}||_dSr$)rI_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rKr"expiry_window_secondsr&r&r)rLns z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key()NotImplementedErrorrSr&r&r)rwsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rKfilenamer&r&r)_make_file_safezsz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials()rrSr&r&r)_get_credentialssz(CachedCredentialFetcher._get_credentialscCs|Sr$)_get_cached_credentialsrSr&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.rnrrT)rirorprqrs)_load_from_cacher_write_to_cacherArBrj)rKrvcredsZ expirationr&r&r)rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrIrrrArB)rKrr&r&r)rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dSr$)rrIr)rKrvr&r&r)rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rnrr)rfr rcr)rKrwZend_timesecondsr&r&r)rsz#CachedCredentialFetcher._is_expired)NN) r[r\r]rrLrrrrrrrrr&r&r&r)rks  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|dkri|_n t||_|j|jd<|jd|_d|_|jsT|tt | ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr6_role_session_name_using_default_session_name_generate_assume_role_namerrrL)rKr-role_arn extra_argsr"rrr&r)rLs   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srT)inttimerrrrSr&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_keysutf-8) rrrrloadsrrencode hexdigestr)rKargsZ argument_hashr&r&r)rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)r[r\r]rLrrrr&r&rr)rs rcs6eZdZd 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, Nrr"r)_source_credentials _mfa_promptergetpassrrrL)rKr-source_credentialsrr mfa_prompterr"rrr&r)rLs"  z$AssumeRoleCredentialFetcher.__init__cCs|}|}|jf|S)'Get credentials by calling assume role.)_assume_role_kwargs_create_clientru)rKrlryr&r&r)rsz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dk r6d|}||}||d<|d}|dk rP||d<|S)AGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rrr6r)rKassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr&r&r)rs    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)rrrrrr)rKZfrozen_credentialsr&r&r)r&s z*AssumeRoleCredentialFetcher._create_client)NNNN)r[r\r]rLrrrrr&r&rr)rs,rcs.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, rN)_web_identity_token_loaderrr%rL)rKr-web_identity_token_loaderrrr"rrr&r)rL4s z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs,|}ttd}|jd|d}|jf|S)r)Zsignature_versionr!)config)rr rrZassume_role_with_web_identity)rKrlr(ryr&r&r)rXs z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)rZWebIdentityToken)rrr&)rKrZidentity_tokenr&r&r)ras z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)r[r\r]rLrrrr&r&rr)r%1s $ r%c@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dSr$r')rKr(r&r&r)rLvszCredentialProvider.__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&rSr&r&r)ryszCredentialProvider.loadc GsHg}|D]:}z|||Wqtk r@t|j|dYqXq|S)NrZcred_var)appendrr METHOD)rKmappingZ key_namesfoundZkey_namer&r&r)_extract_creds_from_mappingsz.CredentialProvider._extract_creds_from_mapping)N)r[r\r]r,CANONICAL_NAMErLrr/r&r&r&r)r)js  r)c@s:eZdZdZejfddZddZddZe dd Z d S) rTzcustom-processcCs||_||_d|_||_dSr$) _profile_name _load_config_loaded_config_popen)rKr.r,popenr&r&r)rLszProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)Nrtcs Sr$)_retrieve_credentials_usingr&credential_processrKr&r)r*r+z&ProcessProvider.load..rrr)rrrr)_credential_processr6r6rrr,rn)rKZ creds_dictr&r7r)rs   zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|dz$|d |d | d | d d WStk r}zt|jd|dW5d}~XYnXdS)N)stdoutstderrrr rVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1rorprqrrrsz$Missing required key in response: %s)r r4 subprocessPIPE communicate returncoderr,decoderrrr r6r) rKr8Z process_listpr:r;parsedversionrr&r&r)r6s>   z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr8)r3r2r6r1)rKprofile_configr&r&r)r9s  z#ProcessProvider._credential_processN) r[r\r]r,r>PopenrLrr6rr9r&r&r&r)rTs rTc@s$eZdZdZdZddZddZdS)r9ziam-roleZEc2InstanceMetadatacCs ||_dSr$) _role_fetcher)rKr!r&r&r)rLsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %sZ role_namerr)rIZretrieve_iam_role_credentialsrArBrrr,)rKfetcherrrr&r&r)rszInstanceMetadataProvider.loadN)r[r\r]r,r0rLrr&r&r&r)r9sr9c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r7env 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)rKrNr-r&r&r)rLs 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)Nrrrrt) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr6rdlist)rKr-Z var_mappingr&r&r)rOs2    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_expiryrtNrr)rrr) rNr6rPrAinfo_create_credentials_fetcherrrr,rn)rKrrKrwrtr&r&r)r)s.  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)NrrVr*rrrt)r6r )rWrwrrZ token_env_varrrtrNr-rr&r)rJs>  zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rPr,rN)rKrr&r[r)rZEs  z'EnvProvider._create_credentials_fetcher)NN) r[r\r]r,r0rQrRrSrTrLrOrrZr&r&r&r)r7s r7c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r>zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dSr$)rrNr_environ_parser)rKrNparserr&r&r)rLus 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. r\z)Found credentials in AWS_CREDENTIAL_FILE.rXN) r]rrrr^rQrArYrRrnr,)rKrrrrr&r&r)r}s      zOriginalEC2Provider.load)NN) r[r\r]r,r0Z CRED_FILE_ENVrQrRrLrr&r&r&r)r>ms r>c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rVzshared-credentials-fileZSharedCredentialsr"r#aws_security_tokenr$NcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr)_creds_filenamer1r configloaderraw_config_parse _ini_parser)rKrUr. ini_parserr&r&r)rLsz!SharedCredentialProvider.__init__cCsz||j}Wntk r&YdSX|j|kr||j}|j|krtd|j|||j|j\}}| |}t ||||j dSdS)Nz0Found credentials in shared credentials file: %srX) rdrarr1rQrArYr/rR_get_session_tokenrnr,)rKZavailable_credsr(rrrr&r&r)rs&    zSharedCredentialProvider.loadcCs$|jD]}||kr||SqdSr$rS)rKr(Z token_envvarr&r&r)rfs z+SharedCredentialProvider._get_session_token)NN) r[r\r]r,r0rQrRrSrLrrfr&r&r&r)rVs rVc@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)rYz0INI based config provider with profile sections.z config-fileZ SharedConfigr"r#r`r$NcCs&||_||_|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_filenamer1rrbr,_config_parser)rKrXr.Z config_parserr&r&r)rLs zConfigProvider.__init__cCsz||j}Wntk r&YdSX|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. NrFz$Credentials found in config file: %srX) rirhrr1rQrArYr/rRrfrnr,)rKr%rGrrrr&r&r)rs(  zConfigProvider.loadcCs$|jD]}||kr||SqdSr$rg)rKrGZ token_namer&r&r)rfs z!ConfigProvider._get_session_token)N) r[r\r]r^r,r0rQrRrSrLrrfr&r&r&r)rYs rYc@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r?z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botor"r#NcCs.|dkrtj}|dkrtjj}||_||_dSr$)rrNrrbrcr]rd)rKrNrer&r&r)rLs zBotoProvider.__init__c Cs|j|jkr|j|jg}n|j}|D]|}z||}Wntk rPYq&YnXd|kr&|d}|j|kr&td||||j|j \}}t |||j dSq&dS)z; Look for credentials in boto config file. rnz)Found credentials in boto config file: %srXN) BOTO_CONFIG_ENVr]DEFAULT_CONFIG_FILENAMESrdrrQrArYr/rRrnr,)rKZpotential_locationsrr(rwrrr&r&r)rs,   zBotoProvider.load)NN) r[r\r]r,r0rjrkrQrRrLrr&r&r&r)r?s r?c@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) r; 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"r2rr1 _prompterr3_credential_sourcer_profile_provider_builder_visited_profiles)rKr,r-r"r.Zprompterr/r0r&r&r)rL)s$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdSNrF)r2r3r6r1_has_assume_role_config_vars_load_creds_via_assume_role)rKrFrr&r&r)r`s   zAssumeRoleProvider.loadcCs|j|ko|j|kSr$)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARrKrr&r&r)rsgs 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 ExternalIdrrr rr)r-rrrrr")rrr) _get_role_config_resolve_source_credentialsr6rrrnr"rrrr,rc) rKr. role_configrrrxryrr rKZ refresherr&r&r)rtqsD     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d k rzt| | 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.rFsource_profilercredential_sourcerryrxr )rryrrxr}r~NzDThe profile "%s" contains both source_profile and credential_source.rz#source_profile or credential_sourcer*) r3r6rrrr r,_validate_credential_source_validate_source_profile) rKr.rFrr}rr~rryrxr r|r&r&r)rzsN        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.)ror is_supported)rKZparent_profiler~r&r&r)rs  z.AssumeRoleProvider._validate_credential_sourcecCst||||gSr$)any_has_static_credentialsrsrwr&r&r)_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||kr(td||fd||}||jkr>dS||krTt||jd||slt||jddS)NrFzFThe source_profile "%s" referenced in the profile "%s" does not exist.r)r}Zvisited_profiles)r3r6rrqrr)rKZparent_profile_nameZsource_profile_namerFr}r&r&r)rs,  z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nr#r"c3s|]}|kVqdSr$r&)rZ static_keyrr&r) sz=AssumeRoleProvider._has_static_credentials..)r)rKrZ static_keysr&rr)rsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)Nr~r})r6 _resolve_credentials_from_sourcerqr+!_resolve_credentials_from_profile)rKr|r.r~r}r&r&r)r{ s  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dkr~d}t ||d|S| |S)NrFTr1z.The source profile "%s" must have credentials.r) r3r6rrp(_resolve_static_credentials_from_profilersr4rCr_rrt)rKr.rFrrEZ profile_chainrw error_messager&r&r)rs.   z4AssumeRoleProvider._resolve_credentials_from_profilec CsXzt|d|d|ddWStk rR}zt|jt|dW5d}~XYnXdS)Nr"r#r$)rrrr*)rnr6rr r,str)rKrrr&r&r)r5sz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %sr)rorr)rKr~r.rwr&r&r)r@sz3AssumeRoleProvider._resolve_credentials_from_source)r[r\r]r,r0rurvZEXPIRY_WINDOW_SECONDSrrLrrsrtrzrrrrr{rrrr&r&r&r)r;s* 7 ,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)rmrxrFcCs:||_||_||_||_d|_||_|dkr0t}||_dSr$)r"r2rr1_profile_config_disable_env_varsr_token_loader_cls)rKr,r-r.r"r2Ztoken_loader_clsr&r&r)rLXs z*AssumeRoleWithWebIdentityProvider.__init__cCs|Sr$)_assume_role_with_web_identityrSr&r&r)rksz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdkr.|}|di}||ji|_|j|Srr)rr2r6r1)rKkeyZ loaded_configrFr&r&r)_get_profile_configns   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjkr.tj|SdSr$)r_CONFIG_TO_ENV_VARr6rrN)rKrZenv_keyr&r&r)_get_env_configus   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dk r|S||Sr$)rr)rKrZ env_valuer&r&r) _get_config}s z-AssumeRoleWithWebIdentityProvider._get_configcCs||d}|sdS||}|d}|s8d}t|di}|d}|dk rV||d<t|j||||jd}t|j|jdS) NrmrzThe 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.rrxr)r-r'rrr"rJ) rrrr%rr"rr,r)rKZ token_pathZ token_loaderrrrrxrKr&r&r)rs0      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) r[r\r]r,r0rrLrrrrrr&r&r&r)rZOs  rZc@s<eZdZddZddZddZddZd d Zd d Zd S)r=cCs ||_dSr$ _providersrKr4r&r&r)rLsz'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&)r0rrCr&r&r)rsz?CanonicalNameCredentialSourcer.is_supported..r)rK source_namer&r&r)rs 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_providerrdrCr_r)rKrsourcer&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 sharedconfigZsharedcredentialsrlNname)_get_provider_by_canonical_namelower_get_provider_by_methodrCr )rKcanonical_namerrDr&r&r)rs     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)rr0r)rKrrrr&r&r)rs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"|jD]}|j|kr|SqdS)z0Return a credential provider by its METHOD name.N)rr,)rKrrr&r&r)rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r[r\r]rLrrrrrr&r&r&r)r=s  & r=c@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)r8zcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|dkrtj}|dkrt}||_||_dSr$)rrNrr]_fetcher)rKrNrKr&r&r)rLs zContainerProvider.__init__cCs$|j|jks|j|jkr |SdSr$)ENV_VARr] ENV_VAR_FULL_retrieve_or_failrSr&r&r)rszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrrrt)rrrrrtr) _provided_relative_urirfull_urlr]rr_build_headers_create_fetcherrr,rf)rKfull_uriheadersrKrr&r&r)rs   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)r]r6ENV_VAR_AUTH_TOKEN)rKrZ auth_tokenr&r&r)r&s z ContainerProvider._build_headerscsfdd}|S)Nc sxzjjd}WnDtk rX}z&tjd|ddtjt|dW5d}~XYnX|d|d|d|d d S) N)rz'Error retrieving container metadata: %sTrrrorpTokenrrrs)rZretrieve_full_urirrArBrr,r)rvrrrrKr&r) fetch_creds/s" z6ContainerProvider._create_fetcher..fetch_credsr&)rKrrrr&rr)r.sz!ContainerProvider._create_fetchercCs |j|jkSr$)rr]rSr&r&r)rAsz(ContainerProvider._provided_relative_uri)NN)r[r\r]r,r0rrrrLrrrrrr&r&r&r)r8s r8c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rCcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. Nr3rr&r&r)rLFszCredentialResolver.__init__cCsLzdd|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,rr&r&r)r]sz4CredentialResolver.insert_before..rN)r4indexrr insertrKrZcredential_provideroffsetr&r&r) insert_beforeNs 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`` r=N)_get_provider_offsetr4rrr&r&r) insert_afterbs 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&rrr&r&r)rzsz-CredentialResolver.remove..N)r4rpop)rKrZavailable_methodsrr&r&r)r@ss  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. )r4rrKrr&r&r) get_providers zCredentialResolver.get_providercCs<zdd|jD|WStk r6t|dYnXdS)NcSsg|] }|jqSr&rrr&r&r)rsz;CredentialResolver._get_provider_offset..r)r4rrr rr&r&r)rsz'CredentialResolver._get_provider_offsetcCs6|jD]*}td|j|}|dk r|SqdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r4rArBr,r)rKrrr&r&r)r_s   z#CredentialResolver.load_credentialsN) r[r\r]rLrrr@rrr_r&r&r&r)rCEs rC)NN)F)Krraloggingrrrrr> collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrZbotocore.configloaderrZbotocore.compatrr r Zbotocore.configr Zbotocore.exceptionsr r rrrrrrZbotocore.utilsrrrr getLoggerr[rArrGrr:r`rcrfrjr<r|rrrnrrrrrr%r)rTr9r7r>rVrYr?r;rZr=r8rCr&r&r&r)s                     N8  -'E1P 9-Ft"*7*7YXE