o ?cC@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlmZmZddlZddlZddlmZdd lmZmZdd lmZdd lmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-e.e/Z0e d gdZ1dZ2dZ3dRddZ4GdddZ5ddZ6ddZ7ddZ8dSddZ9ddZ:d d!Z;d"d#ZGd(d)d)e>Z?Gd*d+d+e?Z@Gd,d-d-ZAGd.d/d/eAZBGd0d1d1eBZCGd2d3d3eBZDGd4d5d5ZEGd6d7d7eEZFGd8d9d9eEZGGd:d;d;eEZHGdd?d?eEZJGd@dAdAeEZKGdBdCdCeEZLGdDdEdEeEZMGdFdGdGeEZNGdHdIdIZOGdJdKdKeEZPGdLdMdMZQGdNdOdOeAZRGdPdQdQeEZSdS)TN) namedtuple)deepcopy)sha1)Pathparse)tzlocaltzutc)UNSIGNED)compat_shell_split total_seconds)Config) ConfigNotFoundCredentialRetrievalErrorInfiniteLoopConfigErrorInvalidConfigErrorMetadataRetrievalErrorPartialCredentialsErrorRefreshWithMFAUnsupportedErrorUnauthorizedSSOTokenErrorUnknownCredentialError)ContainerMetadataFetcherFileWebIdentityTokenLoaderInstanceMetadataFetcherSSOTokenLoaderparse_key_val_fileresolve_imds_endpoint_modeReadOnlyCredentials access_key secret_keytokeniXc sdpd}d}d}ddu}dttd}|dur+i}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_modeZec2_credential_refresh_window)timeout num_attempts user_agentconfig)iam_role_fetcher)cache region_namecsjSN) full_configsessionr/o/private/var/folders/cw/wlscbxl13mj6wd668h7l9g9sllkg5j/T/pip-target-b31awkwq/lib/python/botocore/credentials.pyisz,create_credential_resolver..) load_configclient_creatorr+ profile_namecredential_sourcerprofile_provider_builderr6disable_env_varszWSkipping environment variable credential check because profile name was explicitly set. providers)get_config_variableZinstance_variablesgetr!_DEFAULT_ADVISORY_REFRESH_TIMEOUT EnvProviderContainerProviderInstanceMetadataProviderrr(ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr<OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r1r+r,r6Zmetadata_timeoutr'r:Z imds_configZ env_providerZcontainer_providerZinstance_metadata_providerr8assume_role_providerZ pre_profileprofile_providersZ post_profiler<resolverr/r0r2create_credential_resolver@sr         rPc@sNeZdZdZ dddZdddZdd Zd d Zd d ZddZ ddZ dS)rCaThis class handles the creation of profile based providers. NOTE: This class is only intended for internal use. This class handles the creation and ordering of the various credential providers that primarly source their configuration from the shared config. This is needed to enable sharing between the default credential chain and the source profile chain created by the assume role provider. NcCs||_||_||_||_dSr-)_session_cache _region_name_sso_token_cache)selfr1r+r,Zsso_token_cacher/r/r2__init__s zProfileProviderBuilder.__init__FcCs.|||||||||||gSr-)_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_providerrUr6r:r/r/r2r<sz ProfileProviderBuilder.providerscst|fdddS)NcjjSr-rQr.r/rUr/r2r3zAProfileProviderBuilder._create_process_provider..)r6r4)ProcessProviderrUr6r/r_r2rZs z/ProfileProviderBuilder._create_process_providercC|jd}t||dS)NZcredentials_file)r6creds_filename)rQr=SharedCredentialProvider)rUr6Zcredential_filer/r/r2rY z9ProfileProviderBuilder._create_shared_credential_providercCrc)N config_file)r6config_filename)rQr=ConfigProvider)rUr6rgr/r/r2r[rfz.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)Ncr]r-r^r/r_r/r2r3r`zFProfileProviderBuilder._create_web_identity_provider..)r4r5r+r6r:)!AssumeRoleWithWebIdentityProviderrErQrSrRr\r/r_r2rWs z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)Ncr]r-r^r/r_r/r2r3r`z=ProfileProviderBuilder._create_sso_provider..)r4r5r6r+ token_cache) SSOProviderrQ create_clientrRrTrbr/r_r2rXs z+ProfileProviderBuilder._create_sso_providerNNNF) __name__ __module__ __qualname____doc__rVr<rZrYr[rWrXr/r/r/r2rCs   rCcCst|}|Sr-)rPload_credentials)r1rOr/r/r2get_credentialssrucCstjtSr-)datetimenowrr/r/r/r2 _local_nowrxcCst|tjr|St|Sr-) isinstancervr)valuer/r/r2_parse_if_neededs r|FcCs&t|tjr|r |S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rzrv isoformatstrftime)r{isor/r/r2_serialize_if_neededs  rcfdd}|S)Ncs*di}|jdi|j|fi|S)Nr,r/)updaterm)Z service_namekwargsZcreate_client_kwargsr,r1r/r2r5sz+_get_client_creator..client_creatorr/)r1r,r5r/rr2rEsrEcr)Ncs:jdi}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expirationrr r! expiry_timer/) assume_roler)response credentialsclientparamsr/r2refreshs z-create_assume_role_refresher..refreshr/)rrrr/rr2create_assume_role_refreshers rcCsGddd}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rUrr/r/r2rVs z8create_mfa_serial_refresher.._Refresher.__init__cSs|jrtd|_|SNT)rrrr_r/r/r2__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)rprqrrrVrr/r/r/r2 _Refreshers rr/)Zactual_refreshrr/r/r2create_mfa_serial_refreshersrc@sheZdZdZejejddddZedfddZ d d Z d d Z d dZ ddZ ddZddZdS) JSONFileCachezJSON file cache. This provides a dict like interface that stores JSON serializable objects. The objects are serialized to JSON and stored in a file. These values can be retrieved at a later time. ~.awsZbotor+NcCs||_|dur |j}||_dSr-) _working_dir_default_dumps_dumps)rUZ working_dirZ dumps_funcr/r/r2rV1s zJSONFileCache.__init__cCstj|tdS)N)r$)jsondumpsr)rUobjr/r/r2r7ryzJSONFileCache._default_dumpscCs||}tj|Sr-)_convert_cache_keyospathisfile)rU cache_key actual_keyr/r/r2 __contains__:s  zJSONFileCache.__contains__c Cs`||}zt|}t|WdWS1swYWdSttfy/t|w)z Retrieve value from a cache key.N)ropenrloadOSError ValueErrorKeyError)rUrrfr/r/r2 __getitem__>s  (zJSONFileCache.__getitem__cCs8||}z t|}|WdStyt|wr-)rrunlinkFileNotFoundErrorr)rUrrZkey_pathr/r/r2 __delitem__Gs  zJSONFileCache.__delitem__c Cs||}z||}Wnttfytd|wtj|js*t|jt t |tj tj Bdd}| ||WddS1sNwYdS)Nz3Value cannot be cached, must be JSON serializable: iw)rr TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rUrr{Zfull_keyZ file_contentrr/r/r2 __setitem__Os&   "zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rUr full_pathr/r/r2r`sz JSONFileCache._convert_cache_key)rprqrrrsrr expanduserrZ CACHE_DIRrVrrrrrrr/r/r/r2r's  rc@s*eZdZdZd ddZddZddZdS) rap Holds the credentials needed to authenticate requests. :param str access_key: The access key part of the credentials. :param str secret_key: The secret key part of the credentials. :param str token: The security token, valid only for session credentials. :param str method: A string which identifies where the credentials were found. NcCs0||_||_||_|durd}||_|dS)NZexplicit)rr r!method _normalize)rUrr r!rr/r/r2rVps zCredentials.__init__cC$tj|j|_tj|j|_dSr-)botocorecompatensure_unicoderr r_r/r/r2r{szCredentials._normalizecCst|j|j|jSr-)rrr r!r_r/r/r2get_frozen_credentialss z"Credentials.get_frozen_credentialsNN)rprqrrrsrVrrr/r/r/r2res   rc@seZdZdZeZeZefddZ ddZ e ddZ e dd Zejd d Ze d d Zejd d Ze ddZejddZddZd"ddZddZddZddZeddZddZd d!ZdS)#RefreshableCredentialsa@ Holds the credentials needed to authenticate requests. In addition, it knows how to refresh itself. :param str access_key: The access key part of the credentials. :param str secret_key: The secret key part of the credentials. :param str token: The security token, valid only for session credentials. :param function refresh_using: Callback function to refresh the credentials. :param str method: A string which identifies where the credentials were found. :param function time_fetcher: Callback function to retrieve current time. cCsN||_||_||_||_||_||_t|_||_ t ||||_ | dSr-) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rUrr r!r refresh_usingr time_fetcherr/r/r2rVs   zRefreshableCredentials.__init__cCrr-)rrrrrr_r/r/r2rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrr r!r)rr r!rrr)_expiry_datetime)clsmetadatarrinstancer/r/r2create_from_metadatas z+RefreshableCredentials.create_from_metadatacC||jSzWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )rrr_r/r/r2rz!RefreshableCredentials.access_keycC ||_dSr-)rrUr{r/r/r2r cCrr)rrr_r/r/r2r rz!RefreshableCredentials.secret_keycCrr-)rrr/r/r2r rcCrr)rrr_r/r/r2r!rzRefreshableCredentials.tokencCrr-)rrr/r/r2r!rcCs|j|}t|Sr-)rrr )rUdeltar/r/r2_seconds_remainingsz)RefreshableCredentials._seconds_remainingNcCs:|jdurdS|dur|j}||krdStddS)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_timeoutrrJrKrU refresh_inr/r/r2refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)rr_r/r/r2 _is_expireds z"RefreshableCredentials._is_expiredcCs||jsdS|jdr7z"||jsW|jdS||j}|j|dW|jdS|jw||jrh|j||jsP WddS|jddWddS1sawYdSdS)NF) is_mandatoryT)rrracquirerelease_mandatory_refresh_timeout_protected_refresh)rUZis_mandatory_refreshr/r/r2rs*      "zRefreshableCredentials._refreshcCsz|}Wnty!|rdnd}tjd|dd|rYdSw||t|j|j|j|_ | r@d}t|t |dS)N mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.Texc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r ExceptionrJwarning_set_from_datarrrrrr RuntimeError)rUrrZ period_namemsgr/r/r2r6s.      z)RefreshableCredentials._protected_refreshcCst|Sr-r)Ztime_strr/r/r2r]sz'RefreshableCredentials._expiry_datetimecsgd}s |}n fdd|D}|r"d}t|j|d|dd|_d|_d |_td |_t d |j| dS) Nrcsg|]}|vr|qSr/r/).0kdatar/r2 fsz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %s, provider error_msgrr r!rz(Retrieved credentials will expire at: %s) rrrrr r!rrrJrKr)rUrZ expected_keysZ missing_keysmessager/rr2ras$     z%RefreshableCredentials._set_from_datacCr)aReturn immutable credentials. The ``access_key``, ``secret_key``, and ``token`` properties on this class will always check and refresh credentials if needed before returning the particular credentials. This has an edge case where you can get inconsistent credentials. Imagine this: # Current creds are "t1" tmp.access_key ---> expired? no, so return t1.access_key # ---- time is now expired, creds need refreshing to "t2" ---- tmp.secret_key ---> expired? yes, refresh and return t2.secret_key This means we're using the access key from t1 with the secret key from t2. To fix this issue, you can request a frozen credential object which is guaranteed not to change. The frozen credentials returned from this method should be used immediately and then discarded. The typical usage pattern would be:: creds = RefreshableCredentials(...) some_code = SomeSignerObject() # I'm about to sign the request. # The frozen credentials are only used for the # duration of generate_presigned_url and will be # immediately thrown away. request = some_code.sign_some_request( with_credentials=creds.get_frozen_credentials()) print("Signed request:", request) )rrr_r/r/r2rxs"z-RefreshableCredentials.get_frozen_credentialsr-)rprqrrrsr?r"_DEFAULT_MANDATORY_REFRESH_TIMEOUTrrxrVr classmethodrpropertyrsetterr r!rrrrr staticmethodrrrr/r/r/r2rs<         "'  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)rUrrrr/r/r2rVs  z'DeferredRefreshableCredentials.__init__Ncs|jdurdSt|Sr)rsuperrr __class__r/r2rs  z-DeferredRefreshableCredentials.refresh_neededr-)rprqrrrsrxrVr __classcell__r/r/rr2rs  rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcherr"NcCs4|duri}||_||_|dur|j}||_dSr-)rR_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rUr+expiry_window_secondsr/r/r2rVs  z CachedCredentialFetcher.__init__cCtd)Nz_create_cache_key()NotImplementedErrorr_r/r/r2r z)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rUfilenamer/r/r2_make_file_safes z'CachedCredentialFetcher._make_file_safecCr)Nz_get_credentials()rr_r/r/r2_get_credentialsrz(CachedCredentialFetcher._get_credentialscC|Sr-)_get_cached_credentialsr_r/r/r2fetch_credentialsrz)CachedCredentialFetcher.fetch_credentialscCs`|}|dur|}||ntd|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.rrT)rrrrr)_load_from_cacher_write_to_cacherJrKr)rUrcreds expirationr/r/r2rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jvrt|j|j}||s|StddS)Nz6Credentials were found in cache, but they are expired.)r rRrrrJrK)rUr r/r/r2rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dSr-)rrRr )rUrr/r/r2rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rr)r|r rxr )rUrend_timesecondsr/r/r2rs z#CachedCredentialFetcher._is_expiredr) rprqrrr rVr rrrrrrrr/r/r/r2r s   r c4eZdZ   dfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsf||_||_|duri|_nt||_|j|jd<|jd|_d|_|js*|t ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr>_role_session_name_using_default_session_name_generate_assume_role_namerrV)rUr5role_arn extra_argsr+rrr/r2rVs  z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%sr&T)inttimer)r(r*r_r/r/r2r+s  z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namecCsZt|j}|jr |d=d|vrt|d|d<tj|dd}t|d}| |S)Create a predictable cache key for the current configuration. The cache key is intended to be compatible with file names. r&PolicyT) sort_keysutf-8) rr(r*rloadsrrencode hexdigestrrUargsZ argument_hashr/r/r2r s  z1BaseAssumeRoleCredentialFetcher._create_cache_keyrn)rprqrrrVr+r rr/r/rr2r%sr%cs>eZdZ    d fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs8||_||_|jdurtj|_tj|||||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, Nr-r+r)_source_credentials _mfa_promptergetpassrrV)rUr5source_credentialsr,r- mfa_prompterr+rrr/r2rV0s)  z$AssumeRoleCredentialFetcher.__init__cCs |}|}|jdi|S)'Get credentials by calling assume role.Nr/)_assume_role_kwargs_create_clientr)rUrrr/r/r2rfsz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|durd|}||}||d<|d}|dur(||d<|S)AGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rr(r>r<)rUassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr/r/r2rAls    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;rr'rr r!)rUZfrozen_credentialsr/r/r2rB~s z*AssumeRoleCredentialFetcher._create_client)NNNN)rprqrrrVrrArBrr/r/rr2r9/s6r9cr$) *AssumeRoleWithWebIdentityCredentialFetcherNcs ||_tj|||||ddS)aG :type client_creator: callable :param client_creator: A callable that creates a client taking arguments like ``Session.create_client``. :type web_identity_token_loader: callable :param web_identity_token_loader: A callable that takes no arguments and returns a web identity token str. :type role_arn: str :param role_arn: The ARN of the role to be assumed. :type extra_args: dict :param extra_args: Any additional arguments to add to the assume role request using the format of the botocore operation. Possible keys include, but may not be limited to, DurationSeconds, Policy, SerialNumber, ExternalId and RoleSessionName. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in aws-cli. :type expiry_window_seconds: int :param expiry_window_seconds: The amount of time, in seconds, r:N)_web_identity_token_loaderrrV)rUr5web_identity_token_loaderr,r-r+rrr/r2rVs$ z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs0|}ttd}|jd|d}|jdi|S)r@)signature_versionrJr)Nr/)rAr r r'Zassume_role_with_web_identity)rUrr)rr/r/r2rs z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)rCZWebIdentityToken)rr(rO)rUrFZidentity_tokenr/r/r2rAs z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargsrn)rprqrrrVrrArr/r/rr2rNs. rNc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCrr-r0)rUr1r/r/r2rV zCredentialProvider.__init__cCsdS)a~ Loads the credentials from their source & sets them on the object. Subclasses should implement this method (by reading from disk, the environment, the network or wherever), returning ``True`` if they were found & loaded. If not found, this method should return ``False``, indictating that the ``CredentialResolver`` should fall back to the next available method. The default implementation does nothing, assuming the user has set the ``access_key/secret_key/token`` themselves. :returns: Whether credentials were found & set :rtype: Credentials Tr/r_r/r/r2rszCredentialProvider.loadc Gs@g}|D]}z |||Wqtyt|j|dw|S)NrZcred_var)appendrrMETHOD)rUmappingZ key_namesfoundZkey_namer/r/r2_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mappingr-)rprqrrrWCANONICAL_NAMErVrrZr/r/r/r2rSs   rSc@s:eZdZdZejfddZddZddZe dd Z d S) razcustom-processcCs||_||_d|_||_dSr-) _profile_name _load_config_loaded_config_popen)rUr6r4popenr/r/r2rVs zProcessProvider.__init__csdjdur dS}|ddur"t|fddjSt|d|d|djdS)Nrcs Sr-)_retrieve_credentials_usingr/credential_processrUr/r2r3 s z&ProcessProvider.load..rr r!)rr r!r)_credential_processrar>rrrWr)rUZ creds_dictr/rbr2rs   zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkr#t|j|ddt j j |d}| dd}|dkrBt|jd|d dz|d |d | d | d dWStyj}z t|jd|dd}~ww)N)stdoutstderrrr3rVersionzzUnsupported version 'z8' for credential process provider, supported versions: 1rrrrrz"Missing required key in response: )r r_ subprocessPIPE communicate returncoderrWdecoderrrr4r>r) rUrcZ process_listprerfparsedversioner/r/r2ras:      z+ProcessProvider._retrieve_credentials_usingcCs6|jdur ||_|jdi|ji}|dS)Nprofilesrc)r^r]r>r\)rUprofile_configr/r/r2rd;s   z#ProcessProvider._credential_processN) rprqrrrWriPopenrVrrarrdr/r/r/r2ras#rac@s$eZdZdZdZddZddZdS)rBziam-roleZEc2InstanceMetadatacCrr-) _role_fetcher)rUr*r/r/r2rVIrTz!InstanceMetadataProvider.__init__cCs>|j}|}|s dStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_namerr)ruZretrieve_iam_role_credentialsrJinforrrW)rUfetcherrr r/r/r2rLszInstanceMetadataProvider.loadN)rprqrrrWr[rVrr/r/r/r2rBEs  rBc@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r@env EnvironmentZAWS_ACCESS_KEY_IDZAWS_SECRET_ACCESS_KEYZAWS_SECURITY_TOKENZAWS_SESSION_TOKENZAWS_CREDENTIAL_EXPIRATIONNcCs$|durtj}||_|||_dS)a :param environ: The environment variables (defaults to ``os.environ`` if no value is provided). :param mapping: An optional mapping of variable names to environment variable names. Use this if you want to change the mapping of access_key->AWS_ACCESS_KEY_ID, etc. The dict can have up to 3 keys: ``access_key``, ``secret_key``, ``session_token``. N)renviron_build_mapping_mapping)rUr|rXr/r/r2rVls zEnvProvider.__init__cCsi}|dur|j|d<|j|d<|j|d<|j|d<|S|d|j|d<|d|j|d<|d|j|d<t|dtsE|dg|d<|d|j|d<|S)Nrr r!r) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr>rzlist)rUrXZ var_mappingr/r/r2r}|s(    zEnvProvider._build_mappingcCs|j|jdd}|rFtd|}|dd}|d}|dur7t|}t|d|d|d |||jd St |d|d|d |jd SdS) zK Search for credentials in explicit environment variables. rz+Found credentials in environment variables.F)require_expiryrNr r!)rrr) r|r>r~rJrx_create_credentials_fetcherrrrWr)rUrryrrr/r/r2rs.   zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|stdd||d<dd}|s*tdd||d<d|d<dD]}|d}|rF||d<nq6d|d<dd}|rY||d<|re|setdd|S)NrrrUr r!r)r>r)rrrr Z token_env_varr!rr|rXrr/r2rs:  zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)r~rWr|)rUrr/rr2rs #z'EnvProvider._create_credentials_fetcherr) rprqrrrWr[rrrrrVr}rrr/r/r/r2r@bs  !r@c@s2eZdZdZdZdZdZdZd ddZd d Z dS) rGzec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|durtj}|dur t}||_||_dSr-)rr|r_environ_parser)rUr|parserr/r/r2rVs  zOriginalEC2Provider.__init__cCsfd|jvr1tj|jd}||}|j|vr/td||j}||j}t |||j dSdSdS)zN Search for a credential file used by original EC2 CLI tools. rz)Found credentials in AWS_CREDENTIAL_FILE.rN) rrrrrrrJrxrrrW)rUrr rr r/r/r2rs      zOriginalEC2Provider.loadr) rprqrrrWr[Z CRED_FILE_ENVrrrVrr/r/r/r2rGs  rGc@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rezshared-credentials-fileZSharedCredentialsrKrLaws_security_tokenrMNcCs2||_|dur d}||_|durtjj}||_dS)Nr$)_creds_filenamer\r configloaderraw_config_parse _ini_parser)rUrdr6 ini_parserr/r/r2rVs z!SharedCredentialProvider.__init__cCsz||j}Wn tyYdSw|j|vrB||j}|j|vrDtd|j|||j|j\}}| |}t ||||j dSdSdS)Nz0Found credentials in shared credentials file: %sr) rrrr\rrJrxrZr_get_session_tokenrrW)rUZavailable_credsr)rr r!r/r/r2rs*       zSharedCredentialProvider.loadcC$|jD] }||vr||SqdSr-r)rUr)Z token_envvarr/r/r2r+  z+SharedCredentialProvider._get_session_tokenr) rprqrrrWr[rrrrVrrr/r/r/r2res  rec@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)riz0INI based config provider with profile sections.z config-fileZ SharedConfigrKrLrrMNcCs&||_||_|durtjj}||_dS)a :param config_filename: The session configuration scoped to the current profile. This is available via ``session.config``. :param profile_name: The name of the current profile. :param config_parser: A config parser callable. N)_config_filenamer\rrr4_config_parser)rUrhr6Z config_parserr/r/r2rV>s   zConfigProvider.__init__cCsz||j}Wn tyYdSw|j|dvrH|d|j}|j|vrFtd|j|||j|j\}}| |}t ||||j dSdSdS)zr If there is are credentials in the configuration associated with the session, use those. Nrrz$Credentials found in config file: %sr) rrrr\rrJrxrZrrrrW)rUr.rsrr r!r/r/r2rMs*      zConfigProvider.loadcCrr-r)rUrsZ token_namer/r/r2rgrz!ConfigProvider._get_session_tokenr-) rprqrrrsrWr[rrrrVrrr/r/r/r2ri1s  ric@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)rHz boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorKrLNcCs.|durtj}|durtjj}||_||_dSr-)rr|rrrrr)rUr|rr/r/r2rVvs  zBotoProvider.__init__c Cs|j|jvr|j|jg}n|j}|D];}z||}Wn ty%Yqwd|vrN|d}|j|vrNtd||||j|j \}}t |||j dSqdS)z; Look for credentials in boto config file. rz)Found credentials in boto config file: %srN) BOTO_CONFIG_ENVrDEFAULT_CONFIG_FILENAMESrrrrJrxrZrrrW)rUZpotential_locationsrr)rrr r/r/r2r~s.     zBotoProvider.loadr) rprqrrrWr[rrrrrVrr/r/r/r2rHms  rHc@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) rD assume-roleNr,web_identity_token_filer"cCs>||_||_||_||_||_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]r'r\ _prompterr^_credential_sourcer_profile_provider_builder_visited_profiles)rUr4r5r+r6Zprompterr7r8r/r/r2rVs+zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r||jSdSNrr)r]r^r>r\_has_assume_role_config_vars_load_creds_via_assume_role)rUrrr#r/r/r2rs   zAssumeRoleProvider.loadcCs|j|vo |j|vSr-)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARrUr#r/r/r2rs z/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dur||d<|d}|dur'||d<|d}|dur4||d<|d}|durA||d<t|j||d ||j|jd } | j} |dur[t| } t |j | t d S) Nrole_session_namer& external_idZ ExternalIdrGrDrIrEr,)r5r>r,r-r?r+)rrr) _get_role_config_resolve_source_credentialsr>r9r'rr+rrrrWrx) rUr6 role_configr>r-rrrGrIryZ refresherr/r/r2rsB     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d urLzt| | d<Wn tyKYnw|d ur[|d ur[td |d |d urj|d urjt|jd d|d urv|||| S|||| S)z?Retrieves and validates the role configuration for the profile.rrsource_profiler,credential_sourcerGrrrI)r,rrGrrrNzDThe profile "%s" contains both source_profile and credential_source.rz#source_profile or credential_sourcerU) r^r>r.rrrrW_validate_credential_source_validate_source_profile) rUr6rrr#rr,rrGrrrIrr/r/r2r%sL          z#AssumeRoleProvider._get_role_configcCsJ|jdurtd|d|dd|j|s#td|d|dddS)NzThe credential_source "z" is specified in profile "z)", but no source provider was configured.rzThe credential source "z" referenced in profile "z" is not valid.)rr is_supported)rUZparent_profilerr/r/r2rVs  z.AssumeRoleProvider._validate_credential_sourcecCst||||gSr-)any_has_static_credentialsrrr/r/r2_source_profile_has_credentialsgs z2AssumeRoleProvider._source_profile_has_credentialscCsv|jdi}||vrtd|d|dd||}||jvr"dS||kr-t||jd||s9t||jddS)NrrzThe source_profile "z" referenced in the profile "z" does not exist.r)rZvisited_profiles)r^r>rrrr)rUZparent_profile_nameZsource_profile_namerrrr/r/r2ros*  z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)NrLrKc3s|]}|vVqdSr-r/)rZ static_keyr#r/r2 z=AssumeRoleProvider._has_static_credentials..)r)rUr#Z static_keysr/rr2rsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dur|||S|d}|j|||S)Nrr)r> _resolve_credentials_from_sourcerrV!_resolve_credentials_from_profile)rUrr6rrr/r/r2rs   z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r|js||S||s"||sA|jj|dd}t|}|}|dur?d}t ||d|S| |S)NrrTr9z.The source profile "%s" must have credentials.r) r^r>rr(_resolve_static_credentials_from_profilerr<rLrtrr)rUr6rrr#rNZ profile_chainr error_messager/r/r2rs4  z4AssumeRoleProvider._resolve_credentials_from_profilec CsJzt|d|d|ddWSty$}z t|jt|dd}~ww)NrKrLrMrrU)rr>rrrWstr)rUr#rqr/r/r2rs z;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|durt|d|d|S)NzBNo credentials found in credential_source referenced in profile %sr)rr>r)rUrr6rr/r/r2rsz3AssumeRoleProvider._resolve_credentials_from_source)rprqrrrWr[rrZEXPIRY_WINDOW_SECONDSr=rVrrrrrrrrrrrrr/r/r/r2rDs, > ,1& ! rDc@sXeZdZdZdZddddZ   ddd Zd d Zd d ZddZ ddZ ddZ dS)rjzassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZ AWS_ROLE_ARN)rrr,FcCs:||_||_||_||_d|_||_|durt}||_dSr-)r+r]r'r\_profile_config_disable_env_varsr_token_loader_cls)rUr4r5r6r+r:Ztoken_loader_clsr/r/r2rVs  z*AssumeRoleWithWebIdentityProvider.__init__cCrr-)_assume_role_with_web_identityr_r/r/r2rrz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdur|}|di}||ji|_|j|Sr)rr]r>r\)rUkey loaded_configrrr/r/r2_get_profile_configs   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jrdS|j|}|r|tjvrtj|SdSr-)r_CONFIG_TO_ENV_VARr>rr|)rUrZenv_keyr/r/r2_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dur |S||Sr-)rr)rUrZ env_valuer/r/r2 _get_configs  z-AssumeRoleWithWebIdentityProvider._get_configcCs||d}|s dS||}|d}|sd}t|di}|d}|dur+||d<t|j||||jd}t|j|jdS) Nrr,zThe provided profile or the current environment is configured to assume role with web identity but has no role ARN configured. Ensure that the profile has the role_arnconfiguration set or the AWS_ROLE_ARN env var is set.rrr&)r5rPr,r-r+rw) rrrrNr'r+rrWr)rUZ token_path token_loaderr,rr-rryr/r/r2rs0      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) rprqrrrWr[rrVrrrrrr/r/r/r2rjs    rjc@s<eZdZddZddZddZddZd d Zd d Zd S)rFcCrr- _providersrUr<r/r/r2rV<rTz'CanonicalNameCredentialSourcer.__init__cCs|dd|jDvS)aLValidates a given source name. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: bool :returns: True if the credential provider is supported, False otherwise. cSg|]}|jqSr/)r[rrnr/r/r2rJz?CanonicalNameCredentialSourcer.is_supported..r)rU source_namer/r/r2r?s 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_providerrzrLrtr)rUrsourcer/r/r2r>Ls z1CanonicalNameCredentialSourcer.source_credentialscCsV||}|dvr |d}|dur |dur|St||gS|dur)t|d|S)a#Return a credential provider by its canonical name. :type canonical_name: str :param canonical_name: The canonical name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )Z sharedconfigZsharedcredentialsrNname)_get_provider_by_canonical_namelower_get_provider_by_methodrLr)rUcanonical_namerrMr/r/r2rZs    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)rr[r)rUrrrr/r/r2rs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"|jD] }|j|kr|SqdS)z0Return a credential provider by its METHOD name.N)rrW)rUrrr/r/r2rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) rprqrrrVrr>rrrr/r/r/r2rF;s & rFc@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)rAzcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|durtj}|durt}||_||_dSr-)rr|rr_fetcher)rUr|ryr/r/r2rVs  zContainerProvider.__init__cCs$|j|jvs |j|jvr|SdSr-)ENV_VARr ENV_VAR_FULL_retrieve_or_failr_r/r/r2rszContainerProvider.loadcCsn|r|j|j|j}n|j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrr r!r)rr r!rrr) _provided_relative_urirfull_urlrrr_build_headers_create_fetcherrrWr|)rUfull_uriheadersryr r/r/r2rs   z#ContainerProvider._retrieve_or_failcCs"|j|j}|durd|iSdS)N Authorization)rr>ENV_VAR_AUTH_TOKEN)rUZ auth_tokenr/r/r2rsz ContainerProvider._build_headerscsfdd}|S)Nc snz jjd}Wnty'}ztjd|ddtjt|dd}~ww|d|d|d|d d S) N)rz'Error retrieving container metadata: %sTrrrrTokenrr)rZretrieve_full_urirrJrKrrWr)rrqrrrUr/r2 fetch_credss$  z6ContainerProvider._create_fetcher..fetch_credsr/)rUrrrr/rr2rsz!ContainerProvider._create_fetchercCs |j|jvSr-)rrr_r/r/r2rs z(ContainerProvider._provided_relative_urir)rprqrrrWr[rrrrVrrrrrr/r/r/r2rAs  rAc@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rLcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. Nr;rr/r/r2rVs zCredentialResolver.__init__cCsFz dd|jD|}Wn tyt|dw|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`` cSrr/rWrr/r/r2rrz4CredentialResolver.insert_before..rN)r<indexrrinsertrUrZcredential_provideroffsetr/r/r2 insert_befores   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`` rhN)_get_provider_offsetr<rrr/r/r2 insert_afters zCredentialResolver.insert_aftercCs6dd|jD}||vrdS||}|j|dS)z Removes a given ``Credentials`` instance from the chain. :param name: The short name of the credentials instance to remove. :type name: string cSrr/rrr/r/r2r rz-CredentialResolver.remove..N)r<rpop)rUrZavailable_methodsrr/r/r2rIs  zCredentialResolver.removecCs|j||S)zReturn a credential provider by name. :type name: str :param name: The name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )r<rrUrr/r/r2 get_providers zCredentialResolver.get_providercCs2z dd|jD|WStyt|dw)NcSrr/rrr/r/r2r#rz;CredentialResolver._get_provider_offset..r)r<rrrrr/r/r2r!s   z'CredentialResolver._get_provider_offsetcCs6|jD]}td|j|}|dur|SqdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r<rJrKrWr)rUrr r/r/r2rt's  z#CredentialResolver.load_credentialsN) rprqrrrVrrrIrrrtr/r/r/r2rLs rLcs@eZdZdZ   d fdd ZddZddZd d ZZS) SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc s6||_||_||_||_||_||_t||dSr-)r' _sso_region _role_name _account_id _start_url _token_loaderrrV) rUZ start_url sso_regionrvZ account_idr5rr+rrr/r2rV?s zSSOCredentialFetcher.__init__cCs>|j|j|jd}tj|ddd}t|d}||S)r0)ZstartUrlroleName accountIdT),r)r2 separatorsr3) rrrrrrr5r6rr7r/r/r2r Rs  z&SSOCredentialFetcher._create_cache_keycCs$|d}tj|t}||jS)Ng@@)rv fromtimestampr r~_UTC_DATE_FORMAT)rUZ timestamp_msZtimestamp_seconds timestampr/r/r2_parse_timestampes z%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}||j}|j|j|dd}z |jdi|}Wn |j j y4t w|d}d|d|d|d | |d d d }|S)z4Get credentials by calling SSO get role credentials.)rQr,ssorR accessToken)rrrZroleCredentialsZ accessKeyIdZsecretAccessKeyZ sessionTokenr!)rrrr)Z ProviderTyperNr/) r r rr'rrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rUr)rZ token_dictrrrr/r/r2rks0   z%SSOCredentialFetcher._get_credentialsrn) rprqrrrrVr rrrr/r/rr2r<s rc@sPeZdZdZejejddddZgdZ  d ddZ d d Z d d Z dS)rlrrrr+) sso_start_urlr sso_role_namesso_account_idNcCs@|dur t|j}||_|duri}||_||_||_||_dSr-)r_SSO_TOKEN_CACHE_DIR _token_cacher+r]r'r\)rUr4r5r6r+rkr/r/r2rVs  zSSOProvider.__init__c s|}|di}|j}||jid}tfdd|Dr#dSi}g}|jD]}|vr7|||<q*||q*|rMd|}td||fd|S)Nrr)rrc3s|]}|vVqdSr-r/)rcrsr/r2rrz/SSOProvider._load_sso_config..rzSThe profile "%s" is configured to use SSO but is missing required configuration: %sr)r]r>r\all_SSO_CONFIG_VARSrVrr) rUrrrr6Z sso_cred_varsr)Zmissing_config_varsZ config_varmissingr/r r2_load_sso_configs*    zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)Nrrrr)r+)rr+rw) r rr'rrr+rrWr)rUZ sso_configZ sso_fetcherr/r/r2rs   zSSOProvider.loadr) rprqrrrWrrrrrr rVr rr/r/r/r2rls   rlrro)Trvr=rloggingrrirr/ collectionsrcopyrhashlibrpathlibrZdateutil.parserrZ dateutil.tzrr Zbotocore.compatrZbotocore.configloaderr r r Zbotocore.configr Zbotocore.exceptionsrrrrrrrrrZbotocore.utilsrrrrrr getLoggerrprJrrr?rPrCrurxr|rrErrrrrrr r%r9rNrSrarBr@rGrerirHrDrjrFrArLrrlr/r/r/r2s        ,  ]H  >&E5 ZC.K~#.<-JYXEdO