B 0`=@sBddlZddlZddlZddlZddlZddlZddlZddlZddlm 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*e+e,Z-e ddddgZ.d]ddZ/Gddde0Z1d d!Z2d"d#Z3d$d%Z4d^d'd(Z5d)d*Z6d+d,Z7d-d.Z8Gd/d0d0e0Z9Gd1d2d2e0Z:Gd3d4d4e:Z;Gd5d6d6e;ZGd;d<dZ?Gd=d>d>e>Z@Gd?d@d@e0ZAGdAdBdBeAZBGdCdDdDeAZCGdEdFdFeAZDGdGdHdHeAZEGdIdJdJeAZFGdKdLdLeAZGGdMdNdNeAZHGdOdPdPeAZIGdQdRdReAZJGdSdTdTe0ZKGdUdVdVeAZLGdWdXdXe0ZMGdYdZdZe=ZNGd[d\d\eAZOdS)_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)SSOTokenLoaderReadOnlyCredentials 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_namecsjS)N) full_config)sessionr'o/private/var/folders/sf/wxz_36012wxg_prv29r6623x5vlqx8/T/pip-target-tft40_m7/lib/python/botocore/credentials.pySz,create_credential_resolver..) load_configclient_creatorr$ profile_namecredential_sourcerprofile_provider_builder)r.disable_env_varszWSkipping environment variable credential check because profile name was explicitly set.) providers)get_config_variableZinstance_variablesget EnvProviderContainerProviderInstanceMetadataProviderrr"ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr2OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r(r$r%r.Zmetadata_timeoutr!r1Z env_providerZcontainer_providerZinstance_metadata_providerr0assume_role_providerZ pre_profileprofile_providersZ post_profiler2resolverr')r(r)create_credential_resolver7sL         rEc@sLeZdZdZdddZdddZdd Zd d Zd d ZddZ ddZ dS)r8aThis 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)rJr.r1r'r'r)r2s z ProfileProviderBuilder.providerscst|fdddS)NcsjjS)N)rFr&r')rJr'r)r*r+zAProfileProviderBuilder._create_process_provider..)r.r,)ProcessProvider)rJr.r')rJr)rOsz/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r.creds_filename)rFr3SharedCredentialProvider)rJr.Zcredential_filer'r'r)rNs z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r.config_filename)rFr3ConfigProvider)rJr.rTr'r'r)rPs z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjS)N)rFr&r')rJr'r)r*r+zFProfileProviderBuilder._create_web_identity_provider..)r,r-r$r.r1)!AssumeRoleWithWebIdentityProviderr:rFrHrG)rJr.r1r')rJr)rLs  z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)NcsjjS)N)rFr&r')rJr'r)r*r+z=ProfileProviderBuilder._create_sso_provider..)r,r-r.r$ token_cache) SSOProviderrF create_clientrGrI)rJr.r')rJr)rMs  z+ProfileProviderBuilder._create_sso_provider)NNN)F) __name__ __module__ __qualname____doc__rKr2rOrNrPrLrMr'r'r'r)r8s    r8cCst|}|S)N)rEload_credentials)r(rDr'r'r)get_credentialssr`cCstjtS)N)datetimenowrr'r'r'r) _local_nowsrccCst|tjr|St|S)N) 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%)updaterZ) service_namekwargsZcreate_client_kwargs)r%r(r'r)r-s z+_get_client_creator..client_creatorr')r(r%r-r')r%r(r)r:sr:csfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerj)response credentials)clientparamsr'r)refreshs  z-create_assume_role_refresher..refreshr')rwrxryr')rwrxr)create_assume_role_refreshers rzcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rJryr'r'r)rKsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)r|rr{)rJr'r'r)__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)r[r\r]rKr}r'r'r'r) _Refreshersr~)object)Zactual_refreshr~r'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 ||_dS)N) _working_dir)rJZ working_dirr'r'r)rKszJSONFileCache.__init__cCs||}tj|S)N)_convert_cache_keyospathisfile)rJ 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)ropenjsonloadOSError ValueErrorIOErrorKeyError)rJrrfr'r'r) __getitem__s   zJSONFileCache.__getitem__c Cs||}ytj|td}Wn$ttfk r@td|YnXtj|j s\t |j t t |tj tjBdd}|||WdQRXdS)N)rz5Value cannot be cached, must be JSON serializable: %siw)rrdumpsrj TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rJrreZfull_keyZ file_contentrr'r'r) __setitem__'s   zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rJr full_pathr'r'r)r5sz JSONFileCache._convert_cache_keyN)r[r\r]r^rr expanduserrZ CACHE_DIRrKrrrrr'r'r'r)r s  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)rJrrrrr'r'r)rKEszCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)rJr'r'r)rQszCredentials._normalizecCst|j|j|jS)N)rrrr)rJr'r'r)get_frozen_credentials[sz"Credentials.get_frozen_credentials)NN)r[r\r]r^rKrrr'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. iiXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dS)N) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rJrrrrs refresh_usingr time_fetcherr'r'r)rKss  zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)rJr'r'r)rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrrrs)rrrrsrr)_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)rJr'r'r)rsz!RefreshableCredentials.access_keycCs ||_dS)N)r)rJrer'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)rJr'r'r)rsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)rJrer'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)rJr'r'r)rszRefreshableCredentials.tokencCs ||_dS)N)r)rJrer'r'r)rscCs|j|}t|S)N)rrr )rJdeltar'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_timeoutrr?r@)rJ refresh_inr'r'r)refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)rJr'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)rJZis_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 Exceptionr?warning_set_from_datarrrrrr RuntimeError)rJrreZ period_namemsgr'r'r)rs      z)RefreshableCredentials._protected_refreshcCst|S)N)r)Ztime_strr'r'r)r!sz'RefreshableCredentials._expiry_datetimecsddddg}s|}nfdd|D}|rHd}t|j|d|d d|_d|_d|_td|_t d |j| dS) Nrrrrscsg|]}|kr|qSr'r').0k)datar'r) *sz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %sz, )provider error_msgz(Retrieved credentials will expire at: %s) rrrrrrrrr?r@r)rJrZ expected_keysZ missing_keysmessager')rr)r%s     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)rJr'r'r)r;s"z-RefreshableCredentials.get_frozen_credentials)N)r[r\r]r^rrrcrKr classmethodrpropertyrsetterrrrrrr{r staticmethodrrrr'r'r'r)ras(      "! 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)rJrrrr'r'r)rKfs z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||S)NT)rsuperrr)rJr) __class__r'r)rqs  z-DeferredRefreshableCredentials.refresh_needed)N)r[r\r]r^rcrKr __classcell__r'r')rr)ras rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcheriNcCs4|dkr i}||_||_|dkr*|j}||_dS)N)rG_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rJr$expiry_window_secondsr'r'r)rK|s z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)rJr'r'r)rsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rJfilenamer'r'r)_make_file_safesz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)rJr'r'r)_get_credentialssz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)rJr'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)rirorprq)rrrrs)_load_from_cacher_write_to_cacher?r@rj)rJrucreds expirationr'r'r)rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrGrrr?r@)rJrr'r'r)rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrGr)rJrur'r'r)rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rnrr)rfr rcr)rJrvZend_timesecondsr'r'r)rsz#CachedCredentialFetcher._is_expired)NN) r[r\r]rrKrrrrrrrrr'r'r'r)rys  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|dkri|_n t||_|j|jd<|jd|_d|_|jsT|tt | ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr4_role_session_name_using_default_session_name_generate_assume_role_namerrrK)rJr-role_arn extra_argsr$r)rr'r)rKs   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srT)inttimerrr)rJr'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)rJargs argument_hashr'r'r)rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)r[r\r]rKrrrr'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_promptergetpassrrrK)rJr-source_credentialsrr mfa_prompterr$r)rr'r)rKs"  z$AssumeRoleCredentialFetcher.__init__cCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientrt)rJrmrwr'r'r)rsz,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)rrr4r)rJassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr'r'r)r "s    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)rJZfrozen_credentialsr'r'r)r 4s  z*AssumeRoleCredentialFetcher._create_client)NNNN)r[r\r]rKrr r rr'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, )rr$rN)_web_identity_token_loaderrrrK)rJr-web_identity_token_loaderrrr$r)rr'r)rKBs z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs,|}ttd}|jd|d}|jf|S)z'Get credentials by calling assume role.)signature_versionr)config)r r rrZassume_role_with_web_identity)rJrmrrwr'r'r)rfs z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)zAGet the arguments for assume role based on current configuration.ZWebIdentityToken)rrr)rJrZidentity_tokenr'r'r)r os z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)r[r\r]rKrr rr'r')rr)r?s# rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r()rJr(r'r'r)rKszCredentialProvider.__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')rJr'r'r)rszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendrr METHOD)rJmappingZ key_namesfoundZkey_namer'r'r)_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)r[r\r]rCANONICAL_NAMErKrr"r'r'r'r)rxs  rc@s:eZdZdZejfddZddZddZe dd Z d S) rQzcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)rJr.r,popenr'r'r)rKszProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)Nrscs S)N)_retrieve_credentials_usingr')credential_processrJr'r)r*r+z&ProcessProvider.load..rrr)rrrr)_credential_processr)r4rrrrn)rJZ creds_dictr')r*rJr)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: 1rorprqrr)rrrrsz$Missing required key in response: %s)r r' subprocessPIPE communicate returncoderrdecoderrrrr4r) rJr*Z process_listpr,r-parsedversionrr'r'r)r)s0     z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr*)r&r%r4r$)rJprofile_configr'r'r)r+s   z#ProcessProvider._credential_processN) r[r\r]rr0PopenrKrr)rr+r'r'r'r)rQs rQc@s$eZdZdZdZddZddZdS)r7ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)rJr#r'r'r)rKsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_name)rr)r;Zretrieve_iam_role_credentialsr?r@rrr)rJfetcherrrr'r'r)rs  zInstanceMetadataProvider.loadN)r[r\r]rr#rKrr'r'r'r)r7sr7c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r5env 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)rJr@r r'r'r)rKs 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)Nrrrrs) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr4rdlist)rJr Z var_mappingr'r'r)rA!s"    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_expiryrsNrr)rr)r) r@r4rBr?info_create_credentials_fetcherrrrrn)rJrr=rvrsr'r'r)r7s      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)NrrH)rrrrrs)r4r )rIrvrrZ token_env_varrrs)r@r rr'r)rXs2 zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rBrr@)rJrr')r@r rr)rKSs  z'EnvProvider._create_credentials_fetcher)NN) r[r\r]rr#rCrDrErFrKrArrKr'r'r'r)r5s r5c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r<zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rr@r_environ_parser)rJr@parserr'r'r)rKs 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. rLz)Found credentials in AWS_CREDENTIAL_FILE.)rN) rMrrrrNrCr?rJrDrnr)rJrrrrr'r'r)rs       zOriginalEC2Provider.load)NN) r[r\r]rr#Z CRED_FILE_ENVrCrDrKrr'r'r'r)r<{s r<c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rSzshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr)_creds_filenamer$r configloaderraw_config_parse _ini_parser)rJrRr. ini_parserr'r'r)rKsz!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) rTrQrr$rCr?rJr"rD_get_session_tokenrnr)rJZavailable_credsrrrrr'r'r)rs    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)rE)rJrZ token_envvarr'r'r)rVs z+SharedCredentialProvider._get_session_token)NN) r[r\r]rr#rCrDrErKrrVr'r'r'r)rSs rSc@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)rVz0INI based config provider with profile sections.z config-fileZ SharedConfigrrrPrNcCs&||_||_|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$rrRr,_config_parser)rJrUr.Z config_parserr'r'r)rKs 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. Nr8z$Credentials found in config file: %s)r) rXrWrr$rCr?rJr"rDrVrnr)rJr&r9rrrr'r'r)rs   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)rE)rJr9Z token_namer'r'r)rVs z!ConfigProvider._get_session_token)N) r[r\r]r^rr#rCrDrErKrrVr'r'r'r)rVs rVc@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r=z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rr@rrRrSrMrT)rJr@rUr'r'r)rKs 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. rnz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVrMDEFAULT_CONFIG_FILENAMESrTrrCr?rJr"rDrnr)rJZpotential_locationsrrrvrrr'r'r)rs"   zBotoProvider.load)NN) r[r\r]rr#rYrZrCrDrKrr'r'r'r)r=s r=c@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) r9z 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)rJr,r-r$r.Zprompterr/r0r'r'r)rK7s$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr8)r%r&r4r$_has_assume_role_config_vars_load_creds_via_assume_role)rJr8rr'r'r)rns   zAssumeRoleProvider.loadcCs|j|ko|j|kS)N)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VAR)rJrr'r'r)r`us 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 ExternalIdrr rrr)r-r rrr r$)rrr) _get_role_config_resolve_source_credentialsr4rrr\r$rrrrrc) rJr. role_configr rrdrerrr=Z refresherr'r'r)ras<      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.r8source_profilercredential_sourcerrerdr)rrerrdrirjNzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr) r&r4rrrr r_validate_credential_source_validate_source_profile) rJr.r8rrirrjrrerdrrhr'r'r)rfsB          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.)r]r is_supported)rJZparent_profilerjr'r'r)rks  z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsr`)rJrr'r'r)_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||kr(td||fd||}||jkr>dS||krTt||jd||slt||jddS)Nr8zFThe source_profile "%s" referenced in the profile "%s" does not exist.)r)riZvisited_profiles)r&r4rr_rro)rJZparent_profile_nameZsource_profile_namer8rir'r'r)rls    z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr')rZ static_key)rr'r) sz=AssumeRoleProvider._has_static_credentials..)rn)rJrZ static_keysr')rr)rosz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)Nrjri)r4 _resolve_credentials_from_sourcer_r!_resolve_credentials_from_profile)rJrhr.rjrir'r'r)rgs  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dkr~d}t ||d|S| |S)Nr8T)r.r1z.The source profile "%s" must have credentials.)r) r&r4ror^(_resolve_static_credentials_from_profiler`r2rAr_rra)rJr.r8rrCZ profile_chainrv error_messager'r'r)rs%s$     z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr)rr)rnr4rr rstr)rJrrr'r'r)rtCsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)r]r r)rJrjr.rvr'r'r)rrNs z3AssumeRoleProvider._resolve_credentials_from_source)r[r\r]rr#rbrcZEXPIRY_WINDOW_SECONDSrrKrr`rarfrkrprlrorgrsrtrrr'r'r'r)r9(s& 5 ,2 &  r9c@sReZdZdZdZddddZddd Zd d Zd d ZddZ ddZ ddZ dS)rWzassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZ AWS_ROLE_ARN)r[rdrFcCs:||_||_||_||_d|_||_|dkr0t}||_dS)N)r$r%rr$_profile_config_disable_env_varsr_token_loader_cls)rJr,r-r.r$r1Ztoken_loader_clsr'r'r)rKfs z*AssumeRoleWithWebIdentityProvider.__init__cCs|S)N)_assume_role_with_web_identity)rJr'r'r)rysz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdkr.|}|di}||ji|_|j|S)Nr8)rwr%r4r$)rJkey loaded_configr8r'r'r)_get_profile_config|s   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjkr.tj|SdS)N)rx_CONFIG_TO_ENV_VARr4rr@)rJr{Zenv_keyr'r'r)_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dk r|S||S)N)rr})rJr{Z 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.)rrdr)r-rrrr$)rr) rryrrrr$rrr)rJZ token_path token_loaderrrrrdr=r'r'r)rzs*      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) r[r\r]rr#r~rKrr}rrrzr'r'r'r)rW]s rWc@s<eZdZddZddZddZddZd d Zd d Zd S)r;cCs ||_dS)N) _providers)rJr2r'r'r)rKsz'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#)rr5r'r'r)rsz?CanonicalNameCredentialSourcer.is_supported..)r)rJ source_namer'r'r)rms 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_providerrdrAr_r)rJrsourcer'r'r)r s  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_methodrAr )rJcanonical_namerrBr'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)rJrrrr'r'r)rs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"x|jD]}|j|kr|SqWdS)z0Return a credential provider by its METHOD name.N)rr)rJrrr'r'r)rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r[r\r]rKrmr rrrr'r'r'r)r;s  & r;c@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)r6zcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|dkrtj}|dkrt}||_||_dS)N)rr@rrM_fetcher)rJr@r=r'r'r)rKs zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARrM ENV_VAR_FULL_retrieve_or_fail)rJr'r'r)rszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrrrs)rrrrrsr) _provided_relative_urirfull_urlrMrr_build_headers_create_fetcherrrrf)rJfull_uriheadersr=rr'r'r)r#s   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)rMr4ENV_VAR_AUTH_TOKEN)rJrZ auth_tokenr'r'r)r4sz 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)rrrorpTokenrr)rrrrs)rZretrieve_full_urirr?r@rrrv)rur)rrrJr'r) fetch_creds=sz6ContainerProvider._create_fetcher..fetch_credsr')rJrrrr')rrrJr)r<sz!ContainerProvider._create_fetchercCs |j|jkS)N)rrM)rJr'r'r)rOsz(ContainerProvider._provided_relative_uri)NN)r[r\r]rr#rrrrKrrrrrr'r'r'r)r6s r6c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rAcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. N)r2)rJr2r'r'r)rKTszCredentialResolver.__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)rr5r'r'r)rksz4CredentialResolver.insert_before..)rN)r2indexrr insert)rJrcredential_provideroffsetr'r'r) insert_before\s 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_offsetr2r)rJrrrr'r'r) insert_afterps 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)rr5r'r'r)rsz-CredentialResolver.remove..N)r2rpop)rJrZavailable_methodsrr'r'r)r>s  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. )r2r)rJrr'r'r) get_providers zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr')r)rr5r'r'r)rsz;CredentialResolver._get_provider_offset..)r)r2rrr )rJrr'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)r2r?r@rr)rJrrr'r'r)r_s  z#CredentialResolver.load_credentialsN) r[r\r]rKrrr>rrr_r'r'r'r)rASs rAcs6eZdZd fdd ZddZddZdd ZZS) SSOCredentialFetcherNc s:||_||_||_||_||_||_tt|||dS)N) r _sso_region _role_name _account_id _start_url _token_loaderrrrK) rJZ start_url sso_regionr<Z account_idr-rr$r)rr'r)rKs 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)rJrrr'r'r)rs  z&SSOCredentialFetcher._create_cache_keycCs |d}tj|t}t|S)Ng@@)ra fromtimestamprrj)rJZ 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)rorprqrr)Z ProviderTypern) r rrrrrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rJrrwrmrurvr'r'r)rs$  z%SSOCredentialFetcher._get_credentials)NNN)r[r\r]rKrrrrr'r')rr)rs  rc@sPeZdZdZejejddddZddddgZ dd d Z d d Z ddZ d S)rYrrz.awsr$ sso_start_urlr sso_role_namesso_account_idNcCs@|dkrt|j}||_|dkr$i}||_||_||_||_dS)N)r_SSO_TOKEN_CACHE_DIR _token_cacher$r%rr$)rJr,r-r.r$rXr'r'r)rK s zSSOProvider.__init__cs|}|di}|j}||jitfdd|jDrDdSi}g}x.|jD]$}|krn|||<qT||qTW|rd|}td||fd|S)Nr8c3s|]}|kVqdS)Nr')rc)r9r'r)rqsz/SSOProvider._load_sso_config..z, zSThe profile "%s" is configured to use SSO but is missing required configuration: %s)r)r%r4r$all_SSO_CONFIG_VARSrrr)rJr|r8r.rZmissing_config_varsZ config_varmissingr')r9r)_load_sso_configs$   zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)Nrrrr)r$)rr$)rr) rrrrrr$rrr)rJZ sso_configZ sso_fetcherr'r'r)r3s  zSSOProvider.load)NN) r[r\r]rrrrrrrrKrrr'r'r'r)rYs rY)NN)F)Prraloggingrrrrr0 collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrrZbotocore.configloaderrZbotocore.compatrr r Zbotocore.configr Zbotocore.exceptionsr r rrrrrrrZbotocore.utilsrrrrr getLoggerr[r?rrErr8r`rcrfrjr:rzrrrnrrrrrrrrQr7r5r<rSrVr=r9rWr;r6rArrYr'r'r'r)s                       ND  -'E1P 8-Ft"*7*7YXEdG