B ㊇c-E@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZmZddlZddlZddlmZddlmZmZdd lmZdd lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&dd l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.e/e0Z1e d dddgZ2dZ3dZ4dRddZ5GdddZ6ddZ7ddZ8ddZ9dSddZ: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)parse)tzlocaltzutc)UNSIGNED)compat_shell_split total_seconds)Config) ConfigNotFoundCredentialRetrievalErrorInfiniteLoopConfigErrorInvalidConfigErrorMetadataRetrievalErrorPartialCredentialsErrorRefreshWithMFAUnsupportedErrorUnauthorizedSSOTokenErrorUnknownCredentialError)SSOTokenProvider)ContainerMetadataFetcherFileWebIdentityTokenLoaderInstanceMetadataFetcher JSONFileCacheSSOTokenLoaderparse_key_val_fileresolve_imds_endpoint_modeReadOnlyCredentials access_key secret_keytokeniXic sdp d}d}d}ddk }dttd}|dkrVi}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_namecsjS)N) full_config)sessionr,o/private/var/folders/8c/hx9_v10d5x38qmnzt13b7b8j1k3n5b/T/pip-target-x6xd5gna/lib/python/botocore/credentials.pyjz,create_credential_resolver..) load_configclient_creatorr) profile_namecredential_sourcerprofile_provider_builder)r3disable_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_creatorCanonicalNameCredentialSourcerr7OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r-r)r*r3Zmetadata_timeoutr%r6Z imds_configZ env_providerZcontainer_providerZinstance_metadata_providerr5assume_role_providerZ pre_profileprofile_providersZ post_profiler7resolverr,)r-r.create_credential_resolverAsZ         rKc@sLeZdZdZdddZdddZdd Zd d Zd d ZddZ ddZ dS)r>aThis class handles the creation of profile based providers. NOTE: This class is only intended for internal use. This class handles the creation and ordering of the various credential providers that primarly source their configuration from the shared config. This is needed to enable sharing between the default credential chain and the source profile chain created by the assume role provider. NcCs||_||_||_||_dS)N)_session_cache _region_name_sso_token_cache)selfr-r)r*Zsso_token_cacher,r,r.__init__szProfileProviderBuilder.__init__FcCs.|||||||||||gS)N)_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_provider)rPr3r6r,r,r.r7sz ProfileProviderBuilder.providerscst|fdddS)NcsjjS)N)rLr+r,)rPr,r.r/r0zAProfileProviderBuilder._create_process_provider..)r3r1)ProcessProvider)rPr3r,)rPr.rUsz/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r3creds_filename)rLr8SharedCredentialProvider)rPr3Zcredential_filer,r,r.rTs z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r3config_filename)rLr8ConfigProvider)rPr3rZr,r,r.rVs z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjS)N)rLr+r,)rPr,r.r/r0zFProfileProviderBuilder._create_web_identity_provider..)r1r2r)r3r6)!AssumeRoleWithWebIdentityProviderr@rLrNrM)rPr3r6r,)rPr.rRs  z4ProfileProviderBuilder._create_web_identity_providercs*tfddjj|jjtjdS)NcsjjS)N)rLr+r,)rPr,r.r/r0z=ProfileProviderBuilder._create_sso_provider..)r1r2r3r) token_cachetoken_provider) SSOProviderrL create_clientrMrOr)rPr3r,)rPr.rSs z+ProfileProviderBuilder._create_sso_provider)NNN)F) __name__ __module__ __qualname____doc__rQr7rUrTrVrRrSr,r,r,r.r>s    r>cCst|}|S)N)rKload_credentials)r-rJr,r,r.get_credentialssrgcCstjtS)N)datetimenowrr,r,r,r. _local_nowsrjcCst|tjr|St|S)N) isinstancerhr)valuer,r,r._parse_if_neededs rmFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rkrh isoformatstrftime)rlisor,r,r._serialize_if_neededs   rqcsfdd}|S)Ncs"di}|jf|j|f|S)Nr*)updatera) service_namekwargsZcreate_client_kwargs)r*r-r,r.r2s z+_get_client_creator..client_creatorr,)r-r*r2r,)r*r-r.r@sr@csfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerq)response credentials)clientparamsr,r.refreshs  z-create_assume_role_refresher..refreshr,)r~rrr,)r~rr.create_assume_role_refreshers rcCsGddd}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rPrr,r,r.rQsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)rrr)rPr,r,r.__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)rbrcrdrQrr,r,r,r. _Refreshersrr,)Zactual_refreshrr,r,r.create_mfa_serial_refreshersrc@s*eZdZdZd ddZddZddZdS) ruap 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||_||_||_|dkrd}||_|dS)Nexplicit)rrr method _normalize)rPrrr rr,r,r.rQ4szCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)rPr,r,r.r?szCredentials._normalizecCst|j|j|jS)N)rrrr )rPr,r,r.get_frozen_credentialsIsz"Credentials.get_frozen_credentials)NN)rbrcrdrerQrrr,r,r,r.ru)s   ruc@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 ||||_ | dS)N) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rPrrr rz refresh_usingr time_fetcherr,r,r.rQds   zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)rPr,r,r.r{sz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrr rz)rrr rzrr)_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. )rr)rPr,r,r.rsz!RefreshableCredentials.access_keycCs ||_dS)N)r)rPrlr,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. )rr)rPr,r,r.rsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)rPrlr,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. )rr)rPr,r,r.r szRefreshableCredentials.tokencCs ||_dS)N)r)rPrlr,r,r.r scCs|j|}t|S)N)rrr )rPdeltar,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_timeoutrrErF)rP refresh_inr,r,r.refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)rPr,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)rPZis_mandatory_refreshr,r,r.rs       zRefreshableCredentials._refreshcCsy |}Wn6tk rB|r$dnd}tjd|dd|r>dSX||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 ExceptionrEwarning_set_from_datarrrrrr RuntimeError)rPrrZ 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) Nrrr rzcsg|]}|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) r rjoinrrr rrrErFr)rPrZ 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) )rr)rPr,r,r.r<s"z-RefreshableCredentials.get_frozen_credentials)N)rbrcrdrer:r"_DEFAULT_MANDATORY_REFRESH_TIMEOUTrrjrQr classmethodrpropertyrsetterrr rrrrr staticmethodrrrr,r,r,r.rOs(      "' 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)rPrrrr,r,r.rQhs z'DeferredRefreshableCredentials.__init__Ncs|jdkrdSt|S)NT)rsuperr)rPr) __class__r,r.rss z-DeferredRefreshableCredentials.refresh_needed)N)rbrcrdrerjrQr __classcell__r,r,)rr.rbs rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcheriNcCs4|dkr i}||_||_|dkr*|j}||_dS)N)rM_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rPr)expiry_window_secondsr,r,r.rQ|s z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)rPr,r,r.rsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replaceospathsep)rPfilenamer,r,r._make_file_safesz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)rPr,r,r._get_credentialssz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)rPr,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.ruryT)rprvrwrx)rrr rz)_load_from_cacher_write_to_cacherErFrq)rPr|creds expirationr,r,r.rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrMrrrErF)rPrr,r,r.rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrMr)rPr|r,r,r.rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rury)rmr rjr)rPr}end_timesecondsr,r,r.rsz#CachedCredentialFetcher._is_expired)NN) rbrcrdrrQrrrrrrrrr,r,r,r.rys  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsf||_||_|dkri|_n t||_|j|jd<|jd|_d|_|jsT|t ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr9_role_session_name_using_default_session_name_generate_assume_role_namerrQ)rPr2role_arn extra_argsr)r)rr,r.rQs  z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srT)inttimerrr)rPr,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) rrrjsonloadsdumpsrencode hexdigestr)rPargs argument_hashr,r,r.rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)rbrcrdrQrrrr,r,)rr.rs rcs6eZdZd fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs8||_||_|jdkrtj|_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, N)rr)r)_source_credentials _mfa_promptergetpassrrQ)rPr2source_credentialsrr mfa_prompterr)r)rr,r.rQs) z$AssumeRoleCredentialFetcher.__init__cCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientr{)rPrtr~r,r,r.r*sz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dk r6d|}||}||d<|d}|dk rP||d<|S)zAGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rrr9r)rPassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr,r,r.r0s    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 )rPZfrozen_credentialsr,r,r.rBs  z*AssumeRoleCredentialFetcher._create_client)NNNN)rbrcrdrQrrrrr,r,)rr.rs.rcs.eZdZdfdd ZddZddZZS) *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, )rr)rN)_web_identity_token_loaderrrQ)rPr2web_identity_token_loaderrrr)r)rr,r.rQPs$z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs,|}ttd}|jd|d}|jf|S)z'Get credentials by calling assume role.)signature_versionr)r')rr rrZassume_role_with_web_identity)rPrtr'r~r,r,r.r~s z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)zAGet the arguments for assume role based on current configuration.ZWebIdentityToken)rrr)rPrZidentity_tokenr,r,r.rs z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)rbrcrdrQrrrr,r,)rr.rMs ' rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r-)rPr-r,r,r.rQszCredentialProvider.__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,)rPr,r,r.loadszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendKeyErrorrMETHOD)rPmappingZ key_namesfoundZkey_namer,r,r._extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)rbrcrdr CANONICAL_NAMErQrrr,r,r,r.rs  rc@s:eZdZdZejfddZddZddZe dd Z d S) rWzcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)rPr3r1popenr,r,r.rQszProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)Nrzcs S)N)_retrieve_credentials_usingr,)credential_processrPr,r.r/r0z&ProcessProvider.load..rrr )rrr r)_credential_processrr9rrr ru)rPZ creds_dictr,)rrPr.rs  zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|d dy"|d |d | d | d dStk r}zt|jd|dWdd}~XYnXdS)N)stdoutstderrrzutf-8)rrVersionzzUnsupported version 'z8' for credential process provider, supported versions: 1rvrwrxry)rrr rzz"Missing required key in response: )r r subprocessPIPE communicate returncoder r decoderrrrr9r ) rPrZ process_listprrparsedversioner,r,r.rs,   z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr)rrr9r)rPprofile_configr,r,r.rs    z#ProcessProvider._credential_processN) rbrcrdr rPopenrQrrrrr,r,r,r.rWs #rWc@s$eZdZdZdZddZddZdS)r=ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)rPr(r,r,r.rQ sz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_name)rr)r(Zretrieve_iam_role_credentialsrEinforrr )rPfetcherrrr,r,r.rs  zInstanceMetadataProvider.loadN)rbrcrdr rrQrr,r,r,r.r= sr=c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r;env EnvironmentZAWS_ACCESS_KEY_IDZAWS_SECRET_ACCESS_KEYZAWS_SECURITY_TOKENZAWS_SESSION_TOKENZAWS_CREDENTIAL_EXPIRATIONNcCs$|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)rPr.r r,r,r.rQ0s 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)Nrrr rz) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr9rklist)rPr Z var_mappingr,r,r.r/@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_expiryrzNrr )rr)r) r.r9r0rEr*_create_credentials_fetcherrrr ru)rPrr+r}rzr,r,r.rXs*    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)Nrr6)rrrr rz)r9r)r7r}rrZ token_env_varr rz)r.r rr,r.r~s2 zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)r0r r.)rPrr,)r.r rr.r8ys #z'EnvProvider._create_credentials_fetcher)NN) rbrcrdr rr1r2r3r4rQr/rr8r,r,r,r.r;&s !r;c@s2eZdZdZdZdZdZdZd ddZd d Z dS) rBzec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rr.r_environ_parser)rPr.parserr,r,r.rQs 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. r9z)Found credentials in AWS_CREDENTIAL_FILE.)rN) r:rr expanduserr;r1rEr*r2rur )rP full_pathrrrr,r,r.rs       zOriginalEC2Provider.load)NN) rbrcrdr rZ CRED_FILE_ENVr1r2rQrr,r,r,r.rBs rBc@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rYzshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr")_creds_filenamerr configloaderraw_config_parse _ini_parser)rPrXr3 ini_parserr,r,r.rQsz!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) rCr@r rr1rEr*rr2_get_session_tokenrur )rPZavailable_credsr'rrr r,r,r.rs    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)r3)rPr'Z token_envvarr,r,r.rEs z+SharedCredentialProvider._get_session_token)NN) rbrcrdr rr1r2r3rQrrEr,r,r,r.rYs rYc@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)r\z0INI based config provider with profile sections.z config-fileZ SharedConfigrrr?rNcCs&||_||_|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_filenamerrrAr1_config_parser)rPr[r3Z config_parserr,r,r.rQs zConfigProvider.__init__cCsy||j}Wntk r$dSX|j|dkr|d|j}|j|krtd|j|||j|j\}}| |}t ||||j dSndSdS)zr If there is are credentials in the configuration associated with the session, use those. Nr%z$Credentials found in config file: %s)r) rGrFr rr1rEr*rr2rErur )rPr+r&rrr r,r,r.rs   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)r3)rPr&Z token_namer,r,r.rE+s z!ConfigProvider._get_session_token)N) rbrcrdrer rr1r2r3rQrrEr,r,r,r.r\s r\c@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)rCz boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rr.rrArBr:rC)rPr.rDr,r,r.rQ:s 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. ruz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVr:DEFAULT_CONFIG_FILENAMESrCr r1rEr*rr2rur )rPZpotential_locationsrr'r}rrr,r,r.rBs"   zBotoProvider.load)NN) rbrcrdr rrHrIr1r2rQrr,r,r,r.rC1s rCc@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) r?z assume-roleNrweb_identity_token_fileicCs>||_||_||_||_||_i|_||_||_|jg|_dS)a :type load_config: callable :param load_config: A function that accepts no arguments, and when called, will return the full configuration dictionary for the session (``session.full_config``). :type client_creator: callable :param client_creator: A factory function that will create a client when called. Has the same interface as ``botocore.session.Session.create_client``. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in the CLI. :type profile_name: str :param profile_name: The name of the profile. :type prompter: callable :param prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type credential_sourcer: CanonicalNameCredentialSourcer :param credential_sourcer: A credential provider that takes a configuration, which is used to provide the source credentials for the STS call. N) r)rrr _prompterr_credential_sourcer_profile_provider_builder_visited_profiles)rPr1r2r)r3Zprompterr4r5r,r,r.rQms+zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr%)rrr9r_has_assume_role_config_vars_load_creds_via_assume_role)rPr%r!r,r,r.rs   zAssumeRoleProvider.loadcCs|j|ko|j|kS)N)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VAR)rPr!r,r,r.rOs z/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dk r4||d<|d}|dk rN||d<|d}|dk rh||d<|d}|dk r||d<t|j||d ||j|jd } | j} |dk rt| } t |j | t d S) Nrole_session_namer external_idZ ExternalIdrrrrr)r2rrrrr))rrr) _get_role_config_resolve_source_credentialsr9rrrKr)rrrr rj) rPr3 role_configrrrSrTrrr+Z refresherr,r,r.rPs<      z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d k ryt| | d<Wntk rYnX|d k r|d k rtd |d nB|d kr|d krt|jd dn"|d k r|||n |||| S)z?Retrieves and validates the role configuration for the profile.r%source_profilercredential_sourcerrTrSr)rrTrrSrXrYNzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr) rr9r ValueErrorrrr _validate_credential_source_validate_source_profile) rPr3r%r!rXrrYrrTrSrrWr,r,r.rUs@         z#AssumeRoleProvider._get_role_configcCsJ|jdkr"td|d|dd|j|sFtd|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.)rLr is_supported)rPZparent_profilerYr,r,r.r[s   z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsrO)rPr!r,r,r._source_profile_has_credentials+sz2AssumeRoleProvider._source_profile_has_credentialscCsv|jdi}||kr.td|d|dd||}||jkrDdS||krZt||jd||srt||jddS)Nr%zThe source_profile "z" referenced in the profile "z" does not exist.)r)rXZvisited_profiles)rr9rrNrr_)rPZparent_profile_nameZsource_profile_namer%rXr,r,r.r\3s   z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr,)rZ static_key)r!r,r. [sz=AssumeRoleProvider._has_static_credentials..)r^)rPr!Z static_keysr,)r!r.r_Ysz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)NrYrX)r9 _resolve_credentials_from_sourcerNr !_resolve_credentials_from_profile)rPrWr3rYrXr,r,r.rV]s  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dkr~d}t ||d|S| |S)Nr%T)r3r6z.The source profile "%s" must have credentials.)r) rr9r_rM(_resolve_static_credentials_from_profilerOr7rGrfrrP)rPr3r%r!rIZ profile_chainr} error_messager,r,r.rchs&    z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr )rr)rur9r rr str)rPr!r$r,r,r.rdsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)rLrr )rPrYr3r}r,r,r.rbs z3AssumeRoleProvider._resolve_credentials_from_source)rbrcrdr rrQrRZEXPIRY_WINDOW_SECONDSrrQrrOrPrUr[r`r\r_rVrcrdrbr,r,r,r.r?^s( 6 ,1& ! r?c@sReZdZdZdZddddZddd Zd d Zd d ZddZ ddZ ddZ dS)r]zassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZ AWS_ROLE_ARN)rJrSrFcCs:||_||_||_||_d|_||_|dkr0t}||_dS)N)r)rrr_profile_config_disable_env_varsr_token_loader_cls)rPr1r2r3r)r6Ztoken_loader_clsr,r,r.rQs z*AssumeRoleWithWebIdentityProvider.__init__cCs|S)N)_assume_role_with_web_identity)rPr,r,r.rsz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdkr.|}|di}||ji|_|j|S)Nr%)rgrr9r)rPkey loaded_configr%r,r,r._get_profile_configs   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjkr.tj|SdS)N)rh_CONFIG_TO_ENV_VARr9rr.)rPrkZenv_keyr,r,r._get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dk r|S||S)N)rorm)rPrkZ 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) NrJrzThe 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.)rrSr)r2rrrr))rr) rprirrrr)rr r)rPZ token_path token_loaderrrrrSr+r,r,r.rjs*      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) rbrcrdr rrnrQrrmrorprjr,r,r,r.r]s r]c@s<eZdZddZddZddZddZd d Zd d Zd S)rAcCs ||_dS)N) _providers)rPr7r,r,r.rQsz'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)rr!r,r,r.rsz?CanonicalNameCredentialSourcer.is_supported..)rr)rP source_namer,r,r.r]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_providerrkrGrfr)rPrssourcer,r,r.rs  z1CanonicalNameCredentialSourcer.source_credentialscCsV||}|dkr@|d}|dk r@|dkr4|St||gS|dkrRt|d|S)a#Return a credential provider by its canonical name. :type canonical_name: str :param canonical_name: The canonical name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )Z sharedconfigZsharedcredentialsz assume-roleN)name)_get_provider_by_canonical_namelower_get_provider_by_methodrGr)rPcanonical_namerrHr,r,r.rts     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)rrrrx)rPrzrrvr,r,r.rwDs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"x|jD]}|j|kr|SqWdS)z0Return a credential provider by its METHOD name.N)rrr )rPrrr,r,r.ryPs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) rbrcrdrQr]rrtrwryr,r,r,r.rAs  & rAc@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)r<zcontainer-roleZ EcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|dkrtj}|dkrt}||_||_dS)N)rr.rr:_fetcher)rPr.r+r,r,r.rQ^s zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARr: ENV_VAR_FULL_retrieve_or_fail)rPr,r,r.rfszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrr rz)rrr rrzr) _provided_relative_urir{full_urlr:r|r}_build_headers_create_fetcherrr rm)rPfull_uriheadersr+rr,r,r.r~ls   z#ContainerProvider._retrieve_or_failcCs"|j|j}|dk rd|iSdS)N Authorization)r:r9ENV_VAR_AUTH_TOKEN)rPZ auth_tokenr,r,r.r}sz 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)rrrvrwTokenry)rrr rz)r{Zretrieve_full_urirrErFr r rf)r|r$)rrrPr,r. fetch_credss "z6ContainerProvider._create_fetcher..fetch_credsr,)rPrrrr,)rrrPr.rsz!ContainerProvider._create_fetchercCs |j|jkS)N)r|r:)rPr,r,r.rsz(ContainerProvider._provided_relative_uri)NN)rbrcrdr rr|r}rrQrr~rrrr,r,r,r.r<Ws r<c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rGcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. N)r7)rPr7r,r,r.rQszCredentialResolver.__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 )rr!r,r,r.rsz4CredentialResolver.insert_before..)rvN)r7indexrZrinsert)rPrvcredential_provideroffsetr,r,r. 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`` rN)_get_provider_offsetr7r)rPrvrrr,r,r. insert_afters zCredentialResolver.insert_aftercCs6dd|jD}||krdS||}|j|dS)z Removes a given ``Credentials`` instance from the chain. :param name: The short name of the credentials instance to remove. :type name: string cSsg|] }|jqSr,)r )rr!r,r,r.rsz-CredentialResolver.remove..N)r7rpop)rPrvZavailable_methodsrr,r,r.rDs  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. )r7r)rPrvr,r,r. get_providers zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr,)r )rr!r,r,r.rsz;CredentialResolver._get_provider_offset..)rv)r7rrZr)rPrvr,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)r7rErFr r)rPrrr,r,r.rfs  z#CredentialResolver.load_credentialsN) rbrcrdrQrrrDrrrfr,r,r,r.rGs rGcs:eZdZdZd fdd ZddZddZd d ZZS) SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc sB||_||_||_||_||_||_| |_| |_t ||dS)N) r _sso_region _role_name _account_id _start_url _token_loader_token_provider_sso_session_namerrQ) rP start_url sso_regionr) account_idr2rqr)rr_sso_session_name)rr,r.rQs zSSOCredentialFetcher.__init__cCsV|j|jd}|jr |j|d<n |j|d<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. )roleName accountIdZ sessionNameZstartUrlT),r)r separatorszutf-8) rrrrrrrrrr)rPrrr,r,r.rs   z&SSOCredentialFetcher._create_cache_keycCs$|d}tj|t}||jS)Ng@@)rh fromtimestamprro_UTC_DATE_FORMAT)rPZ timestamp_msZtimestamp_seconds timestampr,r,r._parse_timestamp0sz%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}|jr8|j}|j}n||j d}|j |j |d}y|j f|}Wn|j jk rtYnX|d}d|d|d|d ||d d d }|S) z4Get credentials by calling SSO get role credentials.)rr*sso)r' accessToken)rrrZroleCredentialsZ accessKeyIdZsecretAccessKeyZ sessionTokenr)rvrwrxry)Z ProviderTyperu)r rrrrZ load_tokenZget_frozen_tokenr rrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rPr'r~Zinitial_token_datar rtr|r}r,r,r.r6s,    z%SSOCredentialFetcher._get_credentials)NNNNN) rbrcrdrrQrrrrr,r,)rr.rs  rc@s\eZdZdZejejddddZdZ dZ e e Z ddd Z d d Z d d ZddZdS)r`r~z.awsr)) sso_role_namesso_account_id) sso_start_urlrNcCsF|dkrt|j}||_||_|dkr*i}||_||_||_||_dS)N)r_SSO_TOKEN_CACHE_DIR _token_cacherr)rrr)rPr1r2r3r)r^r_r,r,r.rQls  zSSOProvider.__init__c s|}|di}|j}||ji|di}tfdd|jDrPdS||\}}i}g}|j|} x,| D]$} | |kr|| || <qx|| qxW|rd|} t d|| fd|S)Nr% sso_sessionsc3s|]}|kVqdS)Nr,)rc)r&r,r.rasz/SSOProvider._load_sso_config..z, zSThe profile "%s" is configured to use SSO but is missing required configuration: %s)r) rr9rall_PROFILE_REQUIRED_CONFIG_VARS_resolve_sso_session_reference_ALL_REQUIRED_CONFIG_VARSr rr) rPrlr%r3rZresolved_configZ extra_reqsr'Zmissing_config_varsZall_required_configs config_varmissingr,)r&r._load_sso_configs.      zSSOProvider._load_sso_configc Cs|d}|dkr|dfS||kr8d|d}t|d|}||}xR|D]F\}}||||krd|d||d|d }t|d|||<qRW|d fS) N sso_sessionr,z+The specified sso-session does not exist: "")rzThe value for z" is inconsistent between profile (z) and sso-session (z).)r)r9rcopyitems) rPr&rrrr'r-rvalr,r,r.rs     z*SSOProvider._resolve_sso_session_referencecCsx|}|sdS|d|d|d|d|jt|jd|jd}d|kr^|d|d<|j|d <tf|}t|j|j d S) Nrrrr)r))rrr)rr2rqr)rrr_)rr) rrrrr)rrrr r)rPZ sso_configZfetcher_kwargsZ sso_fetcherr,r,r.rs"     zSSOProvider.load)NNN)rbrcrdr rrr=rrrZ_SSO_REQUIRED_CONFIG_VARSrrQrrrr,r,r,r.r`Zs $r`)NN)F)Trhrrloggingrrrr collectionsrrrhashlibrZdateutil.parserrZ dateutil.tzrrZbotocore.compatrZbotocore.configloaderrr r Zbotocore.configr Zbotocore.exceptionsr r rrrrrrrZbotocore.tokensrZbotocore.utilsrrrrrrr getLoggerrbrErrr:rKr>rgrjrmrqr@rrrurrrrrrrrWr=r;rBrYr\rCr?r]rAr<rGrr`r,r,r,r.sz      , $  ]I  &E5Z B.K~#.<-JYXEdZ