U kY!_=@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)sha1parse)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_namecsjSN) full_configsessionr)l/private/var/folders/2d/2jcwkxfx4hj39rq32sgz27wh9m_5lk/T/pip-unpacked-wheel-59b8s650/botocore/credentials.pySz,create_credential_resolver..) load_configclient_creatorr% profile_namecredential_sourcerprofile_provider_builderr1disable_env_varszWSkipping environment variable credential check because profile name was explicitly set. providers)get_config_variableZinstance_variablesget EnvProviderContainerProviderInstanceMetadataProviderrr#ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr7OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r+r%r&r1Zmetadata_timeoutr"r5Z env_providerZcontainer_providerZinstance_metadata_providerr3assume_role_providerZ pre_profileprofile_providersZ post_profiler7resolverr)r*r,create_credential_resolver7sd        rJc@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||_||_||_||_dSr')_session_cache _region_name_sso_token_cache)selfr+r%r&Zsso_token_cacher)r)r,__init__szProfileProviderBuilder.__init__FcCs.|||||||||||gSr')_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_providerrOr1r5r)r)r,r7sz ProfileProviderBuilder.providerscst|fdddS)NcsjjSr'rKr(r)rOr)r,r-r.zAProfileProviderBuilder._create_process_provider..)r1r/)ProcessProviderrOr1r)rXr,rTs z/ProfileProviderBuilder._create_process_providercCs|jd}t||dS)NZcredentials_file)r1creds_filename)rKr8SharedCredentialProvider)rOr1Zcredential_filer)r)r,rSs  z9ProfileProviderBuilder._create_shared_credential_providercCs|jd}t||dS)N config_file)r1config_filename)rKr8ConfigProvider)rOr1r]r)r)r,rUs  z.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)NcsjjSr'rWr)rXr)r,r-r.zFProfileProviderBuilder._create_web_identity_provider..)r/r0r%r1r5)!AssumeRoleWithWebIdentityProviderr?rKrMrLrVr)rXr,rQs z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)NcsjjSr'rWr)rXr)r,r-r.z=ProfileProviderBuilder._create_sso_provider..)r/r0r1r% token_cache) SSOProviderrK create_clientrLrNrZr)rXr,rRs z+ProfileProviderBuilder._create_sso_provider)NNN)F) __name__ __module__ __qualname____doc__rPr7rTrSrUrQrRr)r)r)r,r=s    r=cCst|}|Sr')rJload_credentials)r+rIr)r)r,get_credentialssricCstjtSr')datetimenowrr)r)r)r, _local_nowsrlcCst|tjr|St|Sr') isinstancerjr)valuer)r)r,_parse_if_neededs roFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rmrj isoformatstrftime)rnisor)r)r,_serialize_if_neededs   rscsfdd}|S)Ncs"di}|jf|j|f|S)Nr&)updaterc)Z service_namekwargsZcreate_client_kwargsr&r+r)r,r0s  z+_get_client_creator..client_creatorr))r+r&r0r)rvr,r?sr?csfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expirationrrr expiry_time) assume_rolers)response credentialsclientparamsr)r,refreshs  z-create_assume_role_refresher..refreshr))rrrr)rr,create_assume_role_refreshers rcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)rOrr)r)r,rPsz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|SNT)rrrrXr)r)r,__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)rdrerfrPrr)r)r)r, _Refreshersr)object)Zactual_refreshrr)r)r,create_mfa_serial_refreshersrc@sVeZdZdZejejddddZefddZ dd Z d d Z d d Z ddZ dS) JSONFileCachezJSON file cache. This provides a dict like interface that stores JSON serializable objects. The objects are serialized to JSON and stored in a file. These values can be retrieved at a later time. ~.awsZbotor%cCs ||_dSr') _working_dir)rOZ working_dirr)r)r,rPszJSONFileCache.__init__cCs||}tj|Sr')_convert_cache_keyospathisfile)rO cache_key actual_keyr)r)r, __contains__s zJSONFileCache.__contains__c Cs^||}z,t|}t|W5QRWSQRXWn"tttfk rXt|YnXdS)z Retrieve value from a cache key.N)ropenjsonloadOSError ValueErrorIOErrorKeyError)rOrrfr)r)r, __getitem__s   "zJSONFileCache.__getitem__c Cs||}ztj|td}Wn$ttfk r@td|YnXtj|j s\t |j t t |tj tjBdd}|||W5QRXdS)N)r z5Value cannot be cached, must be JSON serializable: %siw)rrdumpsrs TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)rOrrnZfull_keyZ file_contentrr)r)r, __setitem__'s$     zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)rOr full_pathr)r)r,r5sz JSONFileCache._convert_cache_keyN)rdrerfrgrr expanduserrZ CACHE_DIRrPrrrrr)r)r)r,r s  rc@s*eZdZdZd ddZddZddZdS) rwa\ 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)rOrrrrr)r)r,rPEszCredentials.__init__cCs$tj|j|_tj|j|_dSr')botocorecompatensure_unicoderrrXr)r)r,rQszCredentials._normalizecCst|j|j|jSr')rrrrrXr)r)r,get_frozen_credentials[sz"Credentials.get_frozen_credentials)NN)rdrerfrgrPrrr)r)r)r,rw:s    rwc@seZdZdZdZdZefddZddZe dd Z e d d Z e j d d Z e d dZej ddZe ddZej ddZddZd$ddZddZddZddZeddZd d!Zd"d#ZdS)%RefreshableCredentialsa Holds the credentials needed to authenticate requests. In addition, it knows how to refresh itself. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. iXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dSr') _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)rOrrrr} refresh_usingr time_fetcherr)r)r,rPss zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dSr')rrrrrrXr)r)r,rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrrrr})rrrr}rr)_expiry_datetime)clsmetadatarrinstancer)r)r,create_from_metadatas z+RefreshableCredentials.create_from_metadatacCs||jSzWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )rrrXr)r)r,rsz!RefreshableCredentials.access_keycCs ||_dSr')rrOrnr)r)r,rscCs||jSr)rrrXr)r)r,rsz!RefreshableCredentials.secret_keycCs ||_dSr')rrr)r)r,rscCs||jSr)rrrXr)r)r,rszRefreshableCredentials.tokencCs ||_dSr')rrr)r)r,rscCs|j|}t|Sr')rrr )rOdeltar)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_timeoutrrDrErO refresh_inr)r)r,refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)rrXr)r)r, _is_expiredsz"RefreshableCredentials._is_expiredc Cs||jsdS|jdr`z4||js2W$dS||j}|j|dWdS|jXnD||jr|j,||jsW5QRdS|jddW5QRXdS)NF) is_mandatoryT)rrracquirerelease_mandatory_refresh_timeout_protected_refresh)rOZis_mandatory_refreshr)r)r,rs"      zRefreshableCredentials._refreshc Csz |}WnJtk rV}z,|r&dnd}tjd|dd|r@WYdSd}~XYnX||t|j|j|j|_ | rd}t|t |dS)N mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.Texc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r ExceptionrDwarning_set_from_datarrrrrr RuntimeError)rOrreZ period_namemsgr)r)r,rs*    z)RefreshableCredentials._protected_refreshcCst|Sr'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) Nrrrr}csg|]}|kr|qSr)r)).0kdatar)r, *sz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %s, provider error_msgz(Retrieved credentials will expire at: %s) rrrrrrrrrDrEr)rOrZ 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) )rrrXr)r)r,r;s"z-RefreshableCredentials.get_frozen_credentials)N)rdrerfrgrrrlrPr classmethodrpropertyrsetterrrrrrrr 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|_ dSr') rrrrrrrrrrr)rOrrrr)r)r,rPfs z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||Sr)rsuperrrr __class__r)r,rqs   z-DeferredRefreshableCredentials.refresh_needed)N)rdrerfrgrlrPr __classcell__r)r)rr,ras rc@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcherrNcCs4|dkr i}||_||_|dkr*|j}||_dSr')rL_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rOr%expiry_window_secondsr)r)r,rP|s z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key()NotImplementedErrorrXr)r)r,rsz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)rOfilenamer)r)r,_make_file_safesz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials()rrXr)r)r,_get_credentialssz(CachedCredentialFetcher._get_credentialscCs|Sr')_get_cached_credentialsrXr)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.rwr{T)rrrxryrzr|)_load_from_cacher_write_to_cacherDrErs)rOrcreds expirationr)r)r,rs  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrLrrrDrE)rOrr)r)r,rs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dSr')rrLr)rOrr)r)r,rsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rwr{)ror rlr)rOrZend_timesecondsr)r)r,rsz#CachedCredentialFetcher._is_expired)NN) rdrerfrrPrrrrrrrrr)r)r)r,rys  rcs.eZdZdfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|dkri|_n t||_|j|jd<|jd|_d|_|jsT|tt | ||dS)NZRoleArnRoleSessionNameF) _client_creatorZ _role_arn_assume_kwargsrr9_role_session_name_using_default_session_name_generate_assume_role_namerr rP)rOr0role_arn extra_argsr%rrr)r,rPs   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%sr T)inttimerr rrXr)r)r,rs z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namecCsZt|j}|jr|d=d|kr0t|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 rrloadsrrencode hexdigestrrOargsZ argument_hashr)r)r,rs z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)rdrerfrPrrrr)r)rr,r s r cs6eZdZd fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs<||_||_|jdkrtj|_tt|j|||||ddS)a :type client_creator: callable :param client_creator: A callable that creates a client taking arguments like ``Session.create_client``. :type source_credentials: Credentials :param source_credentials: The credentials to use to create the client for the call to AssumeRole. :type role_arn: str :param role_arn: The ARN of the role to be assumed. :type extra_args: dict :param extra_args: Any additional arguments to add to the assume role request using the format of the botocore operation. Possible keys include, but may not be limited to, DurationSeconds, Policy, SerialNumber, ExternalId and RoleSessionName. :type mfa_prompter: callable :param mfa_prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in aws-cli. :type expiry_window_seconds: int :param expiry_window_seconds: The amount of time, in seconds, Nrr%r)_source_credentials _mfa_promptergetpassrrrP)rOr0source_credentialsrr mfa_prompterr%rrr)r,rPs"  z$AssumeRoleCredentialFetcher.__init__cCs|}|}|jf|S)'Get credentials by calling assume role.)_assume_role_kwargs_create_clientr~)rOrurr)r)r,rsz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dk r6d|}||}||d<|d}|dk rP||d<|S)AGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rr r9r!)rOassume_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)r rr rrr)rOZfrozen_credentialsr)r)r,r'4s z*AssumeRoleCredentialFetcher._create_client)NNNN)rdrerfrPrr&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, rN)_web_identity_token_loaderrr3rP)rOr0web_identity_token_loaderrrr%rrr)r,rPBs z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs,|}ttd}|jd|d}|jf|S)r%)signature_versionr/config)r&r r r Zassume_role_with_web_identity)rOrur8rr)r)r,rfs z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)r(ZWebIdentityToken)rr r4)rOr+Zidentity_tokenr)r)r,r&os z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)rdrerfrPrr&rr)r)rr,r3?s $ r3c@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dSr'r*)rOr+r)r)r,rPszCredentialProvider.__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)rXr)r)r,rszCredentialProvider.loadc GsHg}|D]:}z|||Wqtk r@t|j|dYqXq|S)NrZcred_var)appendrrMETHOD)rOmappingZ key_namesfoundZkey_namer)r)r,_extract_creds_from_mappingsz.CredentialProvider._extract_creds_from_mapping)N)rdrerfr<CANONICAL_NAMErPrr?r)r)r)r,r9xs  r9c@s:eZdZdZejfddZddZddZe dd Z d S) rYzcustom-processcCs||_||_d|_||_dSr') _profile_name _load_config_loaded_config_popen)rOr1r/popenr)r)r,rPszProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)Nr}cs Sr')_retrieve_credentials_usingr)credential_processrOr)r,r-r.z&ProcessProvider.load..rrr)rrrr)_credential_processrFr9rrr<rw)rOZ creds_dictr)rGr,rs   zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|dz$|d |d | d | d d WStk r}zt|jd|dW5d}~XYnXdS)N)stdoutstderrrrrVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1rxryrzr{r|z$Missing required key in response: %s)r rD subprocessPIPE communicate returncoderr<decoderrrrr9r) rOrHZ process_listprJrKparsedversionrr)r)r,rFs>   z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)NprofilesrH)rCrBr9rA)rOprofile_configr)r)r,rIs  z#ProcessProvider._credential_processN) rdrerfr<rNPopenrPrrFrrIr)r)r)r,rYs rYc@s$eZdZdZdZddZddZdS)r<ziam-roleZEc2InstanceMetadatacCs ||_dSr') _role_fetcher)rOr$r)r)r,rPsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_namerr)rYZretrieve_iam_role_credentialsrDrErrr<)rOfetcherrrr)r)r,rszInstanceMetadataProvider.loadN)rdrerfr<r@rPrr)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)rOr_r=r)r)r,rPs 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)Nrrrr}) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr9rmlist)rOr=Z var_mappingr)r)r,r`!s2    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_expiryr}Nrr)rrr) r_r9rarDinfo_create_credentials_fetcherrrr<rw)rOrr\rr}r)r)r,r7s.  zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|s(tdd||d<dd}|sTtdd||d<d|d<dD] }|d}|rl||d<qqld|d<dd}|r||d<|r|stdd|S)Nrrgr:rrr})r9r)rhrrrZ token_env_varrr}r_r=rr)r,rXs>  zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rar<r_)rOrr)rlr,rkSs  z'EnvProvider._create_credentials_fetcher)NN) rdrerfr<r@rbrcrdrerPr`rrkr)r)r)r,r:s r:c@s2eZdZdZdZdZdZdZd ddZd d Z dS) rAzec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dSr')rr_r_environ_parser)rOr_parserr)r)r,rPs 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. rmz)Found credentials in AWS_CREDENTIAL_FILE.riN) rnrrrrorbrDrjrcrwr<)rOrrrrr)r)r,rs      zOriginalEC2Provider.load)NN) rdrerfr<r@Z CRED_FILE_ENVrbrcrPrr)r)r)r,rA{s rAc@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)r\zshared-credentials-fileZSharedCredentialsr0r1aws_security_tokenr2NcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr )_creds_filenamerAr configloaderraw_config_parse _ini_parser)rOr[r1 ini_parserr)r)r,rPsz!SharedCredentialProvider.__init__cCsz||j}Wntk r&YdSX|j|kr||j}|j|krtd|j|||j|j\}}| |}t ||||j dSdS)Nz0Found credentials in shared credentials file: %sri) rurrrrArbrDrjr?rc_get_session_tokenrwr<)rOZavailable_credsr8rrrr)r)r,rs&    zSharedCredentialProvider.loadcCs$|jD]}||kr||SqdSr'rd)rOr8Z token_envvarr)r)r,rws z+SharedCredentialProvider._get_session_token)NN) rdrerfr<r@rbrcrdrPrrwr)r)r)r,r\s r\c@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)r_z0INI based config provider with profile sections.z config-fileZ SharedConfigr0r1rqr2NcCs&||_||_|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_filenamerArrsr/_config_parser)rOr^r1Z config_parserr)r)r,rPs zConfigProvider.__init__cCsz||j}Wntk r&YdSX|j|dkr|d|j}|j|krtd|j|||j|j\}}| |}t ||||j dSndSdS)zr If there is are credentials in the configuration associated with the session, use those. NrVz$Credentials found in config file: %sri) rzryrrArbrDrjr?rcrwrwr<)rOr(rWrrrr)r)r,rs(  zConfigProvider.loadcCs$|jD]}||kr||SqdSr'rx)rOrWZ token_namer)r)r,rws z!ConfigProvider._get_session_token)N) rdrerfrgr<r@rbrcrdrPrrwr)r)r)r,r_s r_c@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)rBz boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botor0r1NcCs.|dkrtj}|dkrtjj}||_||_dSr')rr_rrsrtrnru)rOr_rvr)r)r,rPs zBotoProvider.__init__c Cs|j|jkr|j|jg}n|j}|D]|}z||}Wntk rPYq&YnXd|kr&|d}|j|kr&td||||j|j \}}t |||j dSq&dS)z; Look for credentials in boto config file. rwz)Found credentials in boto config file: %sriN) BOTO_CONFIG_ENVrnDEFAULT_CONFIG_FILENAMESrurrbrDrjr?rcrwr<)rOZpotential_locationsrr8rrrr)r)r,rs,   zBotoProvider.load)NN) rdrerfr<r@r{r|rbrcrPrr)r)r)r,rBs rBc@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) r> assume-roleNrweb_identity_token_filercCs>||_||_||_||_||_i|_||_||_|jg|_dS)a :type load_config: callable :param load_config: A function that accepts no arguments, and when called, will return the full configuration dictionary for the session (``session.full_config``). :type client_creator: callable :param client_creator: A factory function that will create a client when called. Has the same interface as ``botocore.session.Session.create_client``. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in the CLI. :type profile_name: str :param profile_name: The name of the profile. :type prompter: callable :param prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type credential_sourcer: CanonicalNameCredentialSourcer :param credential_sourcer: A credential provider that takes a configuration, which is used to provide the source credentials for the STS call. N) r%rBr rA _prompterrC_credential_sourcer_profile_provider_builder_visited_profiles)rOr/r0r%r1Zprompterr2r3r)r)r,rP7s$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdSNrV)rBrCr9rA_has_assume_role_config_vars_load_creds_via_assume_role)rOrVrr)r)r,rns   zAssumeRoleProvider.loadcCs|j|ko|j|kSr')ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARrOrr)r)r,rus 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 ExternalIdr,r)r.r*r)r0r#rrr$r%)rrr) _get_role_config_resolve_source_credentialsr9rr rr%rrrr<rl) rOr1 role_configr#rrrr,r.r\Z refresherr)r)r,rsD     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d k rzt| | d<Wntk rYnX|d k r|d k rtd |d nB|d kr|d krt|jd dn"|d k r|||n |||| S)z?Retrieves and validates the role configuration for the profile.rVsource_profilercredential_sourcer,rrr.)rrr,rrrNzDThe profile "%s" contains both source_profile and credential_source.rz#source_profile or credential_sourcer:) rCr9rrrrr<_validate_credential_source_validate_source_profile) rOr1rVrrrrr,rrr.rr)r)r,rsN        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.)rr is_supported)rOZparent_profilerr)r)r,rs  z.AssumeRoleProvider._validate_credential_sourcecCst||||gSr')any_has_static_credentialsrrr)r)r,_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||kr(td||fd||}||jkr>dS||krTt||jd||slt||jddS)NrVzFThe source_profile "%s" referenced in the profile "%s" does not exist.r)rZvisited_profiles)rCr9rrrr)rOZparent_profile_nameZsource_profile_namerVrr)r)r,rs,  z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nr1r0c3s|]}|kVqdSr'r))rZ static_keyrr)r, sz=AssumeRoleProvider._has_static_credentials..)r)rOrZ static_keysr)rr,rsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)Nrr)r9 _resolve_credentials_from_sourcerr;!_resolve_credentials_from_profile)rOrr1rrr)r)r,rs  z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r0|js0||S||sD||s|jj|dd}t|}|}|dkr~d}t ||d|S| |S)NrVTr4z.The source profile "%s" must have credentials.r) rCr9rr(_resolve_static_credentials_from_profilerr7rFrhrr)rOr1rVrrHZ profile_chainr error_messager)r)r,r%s.   z4AssumeRoleProvider._resolve_credentials_from_profilec CsXzt|d|d|ddWStk rR}zt|jt|dW5d}~XYnXdS)Nr0r1r2)rrrr:)rwr9rrr<str)rOrrr)r)r,rCsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %sr)rr#r)rOrr1rr)r)r,rNsz3AssumeRoleProvider._resolve_credentials_from_source)rdrerfr<r@rrZEXPIRY_WINDOW_SECONDSr"rPrrrrrrrrrrrrr)r)r)r,r>(s* 7 ,2 &  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)r~rrFcCs:||_||_||_||_d|_||_|dkr0t}||_dSr')r%rBr rA_profile_config_disable_env_varsr_token_loader_cls)rOr/r0r1r%r5Ztoken_loader_clsr)r)r,rPfs z*AssumeRoleWithWebIdentityProvider.__init__cCs|Sr')_assume_role_with_web_identityrXr)r)r,rysz&AssumeRoleWithWebIdentityProvider.loadcCs:|jdkr.|}|di}||ji|_|j|Sr)rrBr9rA)rOkey loaded_configrVr)r)r,_get_profile_config|s   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jr dS|j|}|r.|tjkr.tj|SdSr')r_CONFIG_TO_ENV_VARr9rr_)rOrZenv_keyr)r)r,_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dk r|S||Sr')rr)rOrZ 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.rrr )r0r5rrr%r[) rrrr3r r%rr<r)rOZ token_path token_loaderrrrrr\r)r)r,rs0      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) rdrerfr<r@rrPrrrrrr)r)r)r,r`]s  r`c@s<eZdZddZddZddZddZd d Zd d Zd S)r@cCs ||_dSr' _providersrOr7r)r)r,rPsz'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@rrSr)r)r,rsz?CanonicalNameCredentialSourcer.is_supported..r)rO source_namer)r)r,rs z+CanonicalNameCredentialSourcer.is_supportedcCs$||}t|tr|S|S)aLoads source credentials based on the provided configuration. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: Credentials ) _get_providerrmrFrhr)rOrsourcer)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 sharedconfigZsharedcredentialsr}Nname)_get_provider_by_canonical_namelower_get_provider_by_methodrFr )rOcanonical_namerrGr)r)r,rs     z,CanonicalNameCredentialSourcer._get_providercCs2|jD]&}|j}|r||kr|SqdS)zReturn a credential provider by its canonical name. This function is strict, it does not attempt to address compatibility issues. N)rr@r)rOrrrr)r)r,rs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"|jD]}|j|kr|SqdS)z0Return a credential provider by its METHOD name.N)rr<)rOrrr)r)r,rs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) rdrerfrPrr#rrrr)r)r)r,r@s  & r@c@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}||_||_dSr')rr_rrn_fetcher)rOr_r\r)r)r,rPs zContainerProvider.__init__cCs$|j|jks|j|jkr |SdSr')ENV_VARrn ENV_VAR_FULL_retrieve_or_failrXr)r)r,rszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrrrr})rrrrr}r) _provided_relative_urirfull_urlrnrr_build_headers_create_fetcherrr<ro)rOfull_uriheadersr\rr)r)r,r#s   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)rnr9ENV_VAR_AUTH_TOKEN)rOrZ auth_tokenr)r)r,r4s z ContainerProvider._build_headerscsfdd}|S)Nc sxzjjd}WnDtk rX}z&tjd|ddtjt|dW5d}~XYnX|d|d|d|d d S) N)rz'Error retrieving container metadata: %sTrrrxryTokenr{r|)rZretrieve_full_urirrDrErr<r)rrrrrOr)r, fetch_creds=s" z6ContainerProvider._create_fetcher..fetch_credsr))rOrrrr)rr,r<sz!ContainerProvider._create_fetchercCs |j|jkSr')rrnrXr)r)r,rOsz(ContainerProvider._provided_relative_uri)NN)rdrerfr<r@rrrrPrrrrrr)r)r)r,r;s r;c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rFcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. Nr6rr)r)r,rPTszCredentialResolver.__init__cCsLzdd|jD|}Wntk r8t|dYnX|j||dS)a= Inserts a new instance of ``CredentialProvider`` into the chain that will be tried before an existing one. :param name: The short name of the credentials you'd like to insert the new credentials before. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` cSsg|] }|jqSr)r<rr)r)r,rksz4CredentialResolver.insert_before..rN)r7indexrr insertrOrZcredential_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`` rMN)_get_provider_offsetr7rrr)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)rrr)r)r,rsz-CredentialResolver.remove..N)r7rpop)rOrZavailable_methodsrr)r)r,rCs  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. )r7rrOrr)r)r, get_providers zCredentialResolver.get_providercCs<zdd|jD|WStk r6t|dYnXdS)NcSsg|] }|jqSr)rrr)r)r,rsz;CredentialResolver._get_provider_offset..r)r7rrr rr)r)r,rsz'CredentialResolver._get_provider_offsetcCs6|jD]*}td|j|}|dk r|SqdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r7rDrEr<r)rOrrr)r)r,rhs   z#CredentialResolver.load_credentialsN) rdrerfrPrrrCrrrhr)r)r)r,rFSs rFcs6eZdZd fdd ZddZddZdd ZZS) SSOCredentialFetcherNc s:||_||_||_||_||_||_tt|||dSr') r  _sso_region _role_name _account_id _start_url _token_loaderrrrP) rOZ start_url sso_regionrZZ account_idr0rr%rrr)r,rPs zSSOCredentialFetcher.__init__cCs>|j|j|jd}tj|ddd}t|d}||S)r)ZstartUrlroleName accountIdT),r)r separatorsr) rrrrrrrrrrr)r)r,rs z&SSOCredentialFetcher._create_cache_keycCs |d}tj|t}t|S)Ng@@)rj fromtimestamprrs)rOZ timestamp_msZtimestamp_seconds timestampr)r)r,_parse_timestampsz%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}|j|j||jd}z|jf|}Wn|j j k rbt YnX|d}d|d|d|d| |d d d }|S) z4Get credentials by calling SSO get role credentials.)r6r&ssor7)rrZ accessTokenZroleCredentialsZ accessKeyIdZsecretAccessKeyZ sessionTokenr)rxryrzr{)Z ProviderTyperw) r r rr rrrrZget_role_credentials exceptionsZUnauthorizedExceptionrr)rOr8rrurrr)r)r,rs,    z%SSOCredentialFetcher._get_credentials)NNN)rdrerfrPrrrrr)r)rr,rsrc@sPeZdZdZejejddddZddddgZ dd d Z d d Z ddZ d S)rbrrrr% sso_start_urlr sso_role_namesso_account_idNcCs@|dkrt|j}||_|dkr$i}||_||_||_||_dSr')r_SSO_TOKEN_CACHE_DIR _token_cacher%rBr rA)rOr/r0r1r%rar)r)r,rP s zSSOProvider.__init__cs|}|di}|j}||jitfdd|jDrDdSi}g}|jD]$}|krl|||<qR||qR|rd|}td||fd|S)NrVc3s|]}|kVqdSr'r))rcrWr)r,rsz/SSOProvider._load_sso_config..rzSThe profile "%s" is configured to use SSO but is missing required configuration: %sr)rBr9rAall_SSO_CONFIG_VARSr;rr)rOrrVr1r8Zmissing_config_varsZ config_varmissingr)rr,_load_sso_configs(    zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)Nrrrr)r%)rr%r[) rrr rrr%rr<r)rOZ sso_configZ sso_fetcherr)r)r,r3s   zSSOProvider.load)NN) rdrerfr<rrrrrrrPrrr)r)r)r,rbs rb)NN)F)Prrjloggingrr"rrrN collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrrZbotocore.configloaderrZbotocore.compatr r r Zbotocore.configr Zbotocore.exceptionsr rrrrrrrrZbotocore.utilsrrrrr getLoggerrdrDrrJrr=rirlrorsr?rrrrwrrrr rr3r9rYr<r:rAr\r_rBr>r`r@r;rFrrbr)r)r)r,s                      ND  -'E1P 9-Ft"*7*7YXEdG