B ݁[T@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlZddlmZddlmZddlZddlZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddl m!Z!m"Z"ddl m#Z#e$e%Z&e ddddgZ'dJddZ(ddZ)ddZ*ddZ+dKd d!Z,d"d#Z-d$d%Z.Gd&d'd'e/Z0Gd(d)d)e/Z1Gd*d+d+e1Z2Gd,d-d-e2Z3Gd.d/d/e/Z4Gd0d1d1e4Z5Gd2d3d3e/Z6Gd4d5d5e6Z7Gd6d7d7e6Z8Gd8d9d9e6Z9Gd:d;d;e6Z:Gdd?d?e6ZGdDdEdEe/Z?GdFdGdGe6Z@GdHdIdIe/ZAdS)LN) namedtuple)deepcopy)sha1)parse)tzlocal) total_seconds)compat_shell_split)UnknownCredentialError)PartialCredentialsError)ConfigNotFound)InvalidConfigError)InfiniteLoopConfigError)RefreshWithMFAUnsupportedError)MetadataRetrievalError)CredentialRetrievalError)InstanceMetadataFetcherparse_key_val_file)ContainerMetadataFetcherReadOnlyCredentials access_key secret_keytokenc sdp d}d}d}d}d}|dkrBi}t}t}tt||dd } tfd d j||t||| gd } || t ||d t |fdd dt ||dt t || g } ddk r| |tdt| d} | S)zCreate a default credential resolver. This creates a pre-configured credential resolver that includes the default lookup chain for credentials. profiledefaultcredentials_file config_fileZmetadata_service_timeoutZmetadata_service_num_attemptsN)timeout num_attempts user_agent)iam_role_fetchercsjS)N) full_config)sessionr!U/Users/kashii/Desktop/Projects/Workshops/worker-safety/lambda/botocore/credentials.pyLsz,create_credential_resolver..) load_configclient_creatorcache profile_namecredential_sourcer)creds_filenamer(csjS)N)r r!)r"r!r#r$\s)r(r%)config_filenamer(zWSkipping environment variable credential check because profile name was explicitly set.) providers)get_config_variable EnvProviderContainerProviderInstanceMetadataProviderrrAssumeRoleProvider create_clientCanonicalNameCredentialSourcerSharedCredentialProviderProcessProviderConfigProviderOriginalEC2Provider BotoProviderinstance_variablesgetremoveloggerdebugCredentialResolver) r"r'r(Zcredential_filerZmetadata_timeoutrZ env_providerZcontainer_providerZinstance_metadata_providerassume_role_providerr,resolverr!)r"r#create_credential_resolver3sL         rAcCst|}|S)N)rAload_credentials)r"r@r!r!r#get_credentials}srCcCstjtS)N)datetimenowrr!r!r!r# _local_nowsrFcCst|tjr|St|S)N) isinstancerDr)valuer!r!r#_parse_if_neededs rIFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rGrD isoformatstrftime)rHisor!r!r#_serialize_if_neededs   rMcsfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerM)response credentials)clientparamsr!r#refreshs  z-create_assume_role_refresher..refreshr!)rWrXrYr!)rWrXr#create_assume_role_refreshers rZcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)selfrYr!r!r#__init__sz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)r\rr[)r]r!r!r#__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)__name__ __module__ __qualname__r^r_r!r!r!r# _Refreshersrc)object)Zactual_refreshrcr!r!r#create_mfa_serial_refreshersrec@sVeZdZdZejejddddZefddZ dd Z d d Z d d Z ddZ dS) JSONFileCachezJSON file cache. This provides a dict like interface that stores JSON serializable objects. The objects are serialized to JSON and stored in a file. These values can be retrieved at a later time. ~z.awsZbotor'cCs ||_dS)N) _working_dir)r]Z working_dirr!r!r#r^szJSONFileCache.__init__cCs||}tj|S)N)_convert_cache_keyospathisfile)r] cache_key actual_keyr!r!r# __contains__s zJSONFileCache.__contains__c CsP||}yt| }t|SQRXWn"tttfk rJt|YnXdS)z Retrieve value from a cache key.N)riopenjsonloadOSError ValueErrorIOErrorKeyError)r]rmrnfr!r!r# __getitem__s   zJSONFileCache.__getitem__c Cs||}ytj|td}Wn$ttfk r@td|YnXtj|j s\t |j t t |tj tjBdd}|||WdQRXdS)N)rz5Value cannot be cached, must be JSON serializable: %siw)rirqdumpsrM TypeErrorrtrjrkisdirrhmakedirsfdopenrpO_WRONLYO_CREATtruncatewrite)r]rmrHZfull_keyZ file_contentrwr!r!r# __setitem__s   zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rjrkjoinrh)r]rm full_pathr!r!r#risz JSONFileCache._convert_cache_keyN)r`rarb__doc__rjrk expanduserrZ CACHE_DIRr^rorxrrir!r!r!r#rfs  rfc@s*eZdZdZd ddZddZddZdS) rNa\ Holds the credentials needed to authenticate requests. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. NcCs0||_||_||_|dkrd}||_|dS)Nexplicit)rrrmethod _normalize)r]rrrrr!r!r#r^szCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)r]r!r!r#rszCredentials._normalizecCst|j|j|jS)N)rrrr)r]r!r!r#get_frozen_credentialssz"Credentials.get_frozen_credentials)NN)r`rarbrr^rrr!r!r!r#rNs    rNc@seZdZdZdZdZefddZddZe dd Z e d d Z e j d d Z e d dZej ddZe ddZej ddZddZd$ddZddZddZddZeddZd d!Zd"d#ZdS)%RefreshableCredentialsa Holds the credentials needed to authenticate requests. In addition, it knows how to refresh itself. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. iiXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dS)N) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)r]rrrrS refresh_usingr time_fetcherr!r!r#r^s  zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)r]r!r!r#r+sz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)NrrrrS)rrrrSrr)_expiry_datetime)clsmetadatarrinstancer!r!r#create_from_metadata/s z+RefreshableCredentials.create_from_metadatacCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r[r)r]r!r!r#r;sz!RefreshableCredentials.access_keycCs ||_dS)N)r)r]rHr!r!r#rDscCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r[r)r]r!r!r#rHsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)r]rHr!r!r#rQscCs||jS)zWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )r[r)r]r!r!r#rUszRefreshableCredentials.tokencCs ||_dS)N)r)r]rHr!r!r#r^scCs|j|}t|S)N)rrr)r]deltar!r!r#_seconds_remainingbsz)RefreshableCredentials._seconds_remainingNcCs:|jdkrdS|dkr|j}||kr,dStddS)aCheck if a refresh is needed. A refresh is needed if the expiry time associated with the temporary credentials is less than the provided ``refresh_in``. If ``time_delta`` is not provided, ``self.advisory_refresh_needed`` will be used. For example, if your temporary credentials expire in 10 minutes and the provided ``refresh_in`` is ``15 * 60``, then this function will return ``True``. :type refresh_in: int :param refresh_in: The number of seconds before the credentials expire in which refresh attempts should be made. :return: True if refresh neeeded, False otherwise. NFz!Credentials need to be refreshed.T)r_advisory_refresh_timeoutrr<r=)r] refresh_inr!r!r#refresh_neededfs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)r]r!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)r]Zis_mandatory_refreshr!r!r#r[s       zRefreshableCredentials._refreshc Csy |}WnDtk rP}z&|r&dnd}tjd|dd|r@dSd}~XYnX||t|j|j|j|_ | rd}t|t |dS)N mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.T)exc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r Exceptionr<warning_set_from_datarrrrrr RuntimeError)r]rreZ period_namemsgr!r!r#rs      z)RefreshableCredentials._protected_refreshcCst|S)N)r)Ztime_strr!r!r#rsz'RefreshableCredentials._expiry_datetimecsddddg}s|}nfdd|D}|rHd}t|j|d|d d|_d|_d|_td|_t d |j| dS) NrrrrScsg|]}|kr|qSr!r!).0k)datar!r# sz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %sz, )provider error_msgz(Retrieved credentials will expire at: %s) rrrrrrrrr<r=r)r]rZ expected_keysZ missing_keysmessager!)rr#rs     z%RefreshableCredentials._set_from_datacCs||jS)aReturn immutable credentials. The ``access_key``, ``secret_key``, and ``token`` properties on this class will always check and refresh credentials if needed before returning the particular credentials. This has an edge case where you can get inconsistent credentials. Imagine this: # Current creds are "t1" tmp.access_key ---> expired? no, so return t1.access_key # ---- time is now expired, creds need refreshing to "t2" ---- tmp.secret_key ---> expired? yes, refresh and return t2.secret_key This means we're using the access key from t1 with the secret key from t2. To fix this issue, you can request a frozen credential object which is guaranteed not to change. The frozen credentials returned from this method should be used immediately and then discarded. The typical usage pattern would be:: creds = RefreshableCredentials(...) some_code = SomeSignerObject() # I'm about to sign the request. # The frozen credentials are only used for the # duration of generate_presigned_url and will be # immediately thrown away. request = some_code.sign_some_request( with_credentials=creds.get_frozen_credentials()) print("Signed request:", request) )r[r)r]r!r!r#rs"z-RefreshableCredentials.get_frozen_credentials)N)r`rarbrrrrFr^r classmethodrpropertyrsetterrrrrrr[r staticmethodrrrr!r!r!r#r s(      "! 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)r]rrrr!r!r#r^s z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||S)NT)rsuperrr)r]r) __class__r!r#rs  z-DeferredRefreshableCredentials.refresh_needed)N)r`rarbrrFr^r __classcell__r!r!)rr#r s rc@sVeZdZdddZddZddZd d Zd d Zd dZddZ ddZ ddZ dS)CachedCredentialFetcherNcCs&|dkr i}||_||_||_dS)N)_cache_create_cache_key _cache_key_expiry_window_seconds)r]r'expiry_window_secondsr!r!r#r^#s  z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)r]r!r!r#r*sz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerjrksep)r]filenamer!r!r#_make_file_safe-sz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)r]r!r!r#_get_credentials2sz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)r]r!r!r#fetch_credentials5sz)CachedCredentialFetcher.fetch_credentialscCs`|}|dkr$|}||n td|d}t|ddd}|d|d|d |d S) zGet up-to-date credentials. This will check the cache for up-to-date credentials, calling assume role if none are available. Nz*Credentials for role retrieved from cache.rNrRT)rLrOrPrQ)rrrrS)_load_from_cacher_write_to_cacher<r=rM)r]rUcredsZ expirationr!r!r#r8s  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrrrr<r=)r]rr!r!r#rNs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrr)r]rUr!r!r#rYsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rNrR)rIrrFr)r]rVZend_timesecondsr!r!r#r\sz#CachedCredentialFetcher._is_expired)Nr) r`rarbr^rrrrrrrrr!r!r!r#r"s  rcs>eZdZd fdd ZddZddZd d Zd d ZZS)AssumeRoleCredentialFetcherNcs||_||_||_|dkr"i|_n t||_|j|jd<|jd|_d|_|jsvdtt |_|j|jd<d|_||_ |j dkrt j |_ t t |||dS)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, NZRoleArnRoleSessionNameFzbotocore-session-%sT)_client_creator_source_credentialsZ _role_arn_assume_kwargsrr:Z_role_session_name_using_default_session_nameinttime _mfa_promptergetpassrrr^)r]r&source_credentialsrole_arn extra_args mfa_prompterr'r)rr!r#r^ds&"     z$AssumeRoleCredentialFetcher.__init__cCsZt|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) rrrrqloadsrzrencode hexdigestr)r]argsZ argument_hashr!r!r#rs z-AssumeRoleCredentialFetcher._create_cache_keycCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientrT)r]kwargsrWr!r!r#rsz,AssumeRoleCredentialFetcher._get_credentialscCs>|j}|d}|dk r:d|}||}t|}||d<|S)zAGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCode)rr:rr)r]Zassume_role_kwargs mfa_serialpromptZ token_coder!r!r#rs  z/AssumeRoleCredentialFetcher._assume_role_kwargscCs"|j}|jd|j|j|jdS)z2Create an STS client using the source credentials.sts)aws_access_key_idaws_secret_access_keyaws_session_token)rrrrrr)r]Zfrozen_credentialsr!r!r#rs  z*AssumeRoleCredentialFetcher._create_client)NNNr) r`rarbr^rrrrrr!r!)rr#rcs :rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r")r]r"r!r!r#r^szCredentialProvider.__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!r#rrszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendrvr METHOD)r]mappingZ key_namesfoundZkey_namer!r!r#_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)r`rarbrCANONICAL_NAMEr^rrrr!r!r!r#rs  rc@s:eZdZdZejfddZddZddZe dd Z d S) r5zcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)r]r(r%popenr!r!r#r^szProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)NrScs S)N)_retrieve_credentials_usingr!)credential_processr]r!r#r$sz&ProcessProvider.load..rrr)rrrr)_credential_processrr:rrrrN)r]Z creds_dictr!)rr]r#rr s  zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkrFt|j|ddt j j |d}| dd}|dkrt|jd|dy"|d |d | d | d d Stk r}zt|jd|dWdd}~XYnXdS)N)stdoutstderrrzutf-8)rrVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1rOrPrQrR)rrrrSz$Missing required key in response: %s)rr subprocessPIPE communicate returncoderrdecoderrrqrr:rv) r]rZ process_listprr parsedversionrr!r!r#r s0     z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr)rrr:r)r]profile_configr!r!r#r?s   z#ProcessProvider._credential_processN) r`rarbrr Popenr^rrrrrr!r!r!r#r5s r5c@s$eZdZdZdZddZddZdS)r0ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)r]rr!r!r#r^Lsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %sZ role_name)rr)rZretrieve_iam_role_credentialsr<r=rrr)r]fetcherrrr!r!r#rrOs  zInstanceMetadataProvider.loadN)r`rarbrrr^rrr!r!r!r#r0Hsr0c@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)r.envZ 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)rjenviron_build_mapping_mapping)r]rrr!r!r#r^ns zEnvProvider.__init__cCsi}|dkr6|j|d<|j|d<|j|d<|j|d<nd|d|j|d<|d|j|d<|d|j|d<t|dts|dg|d<|d|j|d<|S)NrrrrS) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr:rGlist)r]rZ var_mappingr!r!r#r~s"    zEnvProvider._build_mappingcCs|jd|jkrtd|}|dd}|d}|dk rft|}t|d|d|d|||jd St|d|d|d|jd SdSdS) zK Search for credentials in explicit environment variables. rz+Found credentials in environment variables.F)require_expiryrSNrr)rr)r) rrr<info_create_credentials_fetcherrrrrN)r]rrVrSr!r!r#rrs     zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}d}|dkr*tdd||d<d}|dkrXtdd||d<d}x"dD]}|krn|}PqnW||d<d}|r|dkrtdd||d<|S)Nr)rrrrrS)r:r )r"rVrrrZ token_env_varrS)rrrr!r#rs. zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rrr)r]rr!)rrrr#r$s z'EnvProvider._create_credentials_fetcher)NN) r`rarbrrrrrr r^rrrr$r!r!r!r#r.ds r.c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r7zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rjrr_environ_parser)r]rparserr!r!r#r^s zOriginalEC2Provider.__init__cCshd|jkr`tj|jd}||}|j|krdtd||j}||j}t |||j dSndSdS)zN Search for a credential file used by original EC2 CLI tools. r%z)Found credentials in AWS_CREDENTIAL_FILE.)rN) r&rjrkrr'rr<r#rrNr)r]rrrrr!r!r#rrs       zOriginalEC2Provider.load)NN) r`rarbrrZ CRED_FILE_ENVrrr^rrr!r!r!r#r7s r7c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)r4zshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr)_creds_filenamerr configloaderraw_config_parse _ini_parser)r]r*r( ini_parserr!r!r#r^sz!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) r-r*r rrr<r#rr_get_session_tokenrNr)r]Zavailable_credsconfigrrrr!r!r#rr s    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)r)r]r0Z token_envvarr!r!r#r/s z+SharedCredentialProvider._get_session_token)NN) r`rarbrrrrrr^rrr/r!r!r!r#r4s r4c@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)r6z0INI 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_filenamerrr+r%_config_parser)r]r+r(Z config_parserr!r!r#r^+s 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. Nrz$Credentials found in config file: %s)r) r2r1r rrr<r#rrr/rNr)r]r rrrrr!r!r#rr:s   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)r)r]rZ token_namer!r!r#r/Ps z!ConfigProvider._get_session_token)N) r`rarbrrrrrrr^rrr/r!r!r!r#r6s r6c@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r8z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rjrrr+r,r&r-)r]rr.r!r!r#r^_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. rNz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVr&DEFAULT_CONFIG_FILENAMESr-r rr<r#rrrNr)r]Zpotential_locationsrr0rVrrr!r!r#rrgs"   zBotoProvider.load)NN) r`rarbrrr3r4rrr^rrr!r!r!r#r8Vs r8c@seZdZdZdZdZdZejdfddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdS)r1z assume-roleNricCs8||_||_||_||_||_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_visited_profiles)r]r%r&r'r(Zprompterr)r!r!r#r^s#zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr)rrr:r_has_assume_role_config_vars_load_creds_via_assume_role)r]rrr!r!r#rrs   zAssumeRoleProvider.loadcCs |j|kS)N)ROLE_CONFIG_VAR)r]rr!r!r#r8sz/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dk r4||d<|d}|dk rN||d<|d}|dk rh||d<t|j||d||j|jd}|j} |dk rt| } t |j | t d S) Nrole_session_namer external_idZ ExternalIdrrr)r&rrrrr')rrr) _get_role_config_resolve_source_credentialsr:rrr5r'rrerrrF) r]r( role_configrrr;r<rrZ refresherr!r!r#r9s6     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |||| ||d} |d k r|d k rtd |d nB|d kr|d krt|jd d n"|d k r|||n |||| S)z?Retrieves and validates the role configuration for the profile.rsource_profilercredential_sourcerr<r;)rr<rr;r@rANzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr)rr:r r r_validate_credential_source_validate_source_profile) r]r(rrr@rrArr<r;r?r!r!r#r=s6         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.)r6r is_supported)r]Zparent_profilerAr!r!r#rB s  z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsr8)r]rr!r!r#_source_profile_has_credentials-sz2AssumeRoleProvider._source_profile_has_credentialscCs|jdi}||kr(td||fd||}||sHtd|d||jkrVdS||krlt||jd||st||jddS)NrzFThe source_profile "%s" referenced in the profile "%s" does not exist.)rz^The source_profile "%s" must specify either static credentials or an assume role configuration)r@Zvisited_profiles)rr:r rGr7r rF)r]Zparent_profile_nameZsource_profile_namerr@r!r!r#rC3s(     z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr!)rZ static_key)rr!r# esz=AssumeRoleProvider._has_static_credentials..)rE)r]rZ static_keysr!)rr#rFcsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)NrAr@)r: _resolve_credentials_from_sourcer7r!_resolve_credentials_from_profile)r]r?r(rAr@r!r!r#r>gs  z.AssumeRoleProvider._resolve_source_credentialscCs4|jdi}||}||r*||S||S)Nr)rr:rF(_resolve_static_credentials_from_profiler9)r]r(rrr!r!r#rJrs   z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr)rr)rNr:rvr rstr)r]rrr!r!r#rK{sz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)r6rr)r]rAr(rVr!r!r#rIs z3AssumeRoleProvider._resolve_credentials_from_source)r`rarbrrr:ZEXPIRY_WINDOW_SECONDSrr^rrr8r9r=rBrGrCrFr>rJrKrIr!r!r!r#r1s"4(+ 0   r1c@s<eZdZddZddZddZddZd d Zd d Zd S)r3cCs ||_dS)N) _providers)r]r,r!r!r#r^sz'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)rrr!r!r#rsz?CanonicalNameCredentialSourcer.is_supported..)rM)r] source_namer!r!r#rDs 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_providerrGr>rBrr)r]rNsourcer!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_methodr>r )r]canonical_namerr?r!r!r#rOs     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)rMrrS)r]rUrrQr!r!r#rRs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"x|jD]}|j|kr|SqWdS)z0Return a credential provider by its METHOD name.N)rMr)r]rrr!r!r#rTs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r`rarbr^rDrrOrRrTr!r!r!r#r3s  & r3c@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)rjrrr&_fetcher)r]rrr!r!r#r^s zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARr& ENV_VAR_FULL_retrieve_or_fail)r]r!r!r#rrszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)NrrrrS)rrrrrSr) _provided_relative_urirVfull_urlr&rWrX_build_headers_create_fetcherrrrI)r]full_uriheadersrrr!r!r#rYs   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)r&r:ENV_VAR_AUTH_TOKEN)r]r_Z 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)r_z'Error retrieving container metadata: %sT)r)rrrOrPTokenrR)rrrrS)rVZretrieve_full_urirr<r=rrrL)rUr)r^r_r]r!r# fetch_credssz6ContainerProvider._create_fetcher..fetch_credsr!)r]r^r_rcr!)r^r_r]r#r]sz!ContainerProvider._create_fetchercCs |j|jkS)N)rWr&)r]r!r!r#rZ.sz(ContainerProvider._provided_relative_uri)NN)r`rarbrrrWrXrar^rrrYr\r]rZr!r!r!r#r/s r/c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)r>cCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. N)r,)r]r,r!r!r#r^3szCredentialResolver.__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)rrr!r!r#rJsz4CredentialResolver.insert_before..)rQN)r,indexrtr insert)r]rQcredential_provideroffsetr!r!r# insert_before;s z CredentialResolver.insert_beforecCs ||}|j|d|dS)a9 Inserts a new type of ``Credentials`` instance into the chain that will be tried after an existing one. :param name: The short name of the credentials you'd like to insert the new credentials after. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` r N)_get_provider_offsetr,re)r]rQrfrgr!r!r# insert_afterOs 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)rrr!r!r#rgsz-CredentialResolver.remove..N)r,rdpop)r]rQZavailable_methodsrgr!r!r#r;`s  zCredentialResolver.removecCs|j||S)zReturn a credential provider by name. :type name: str :param name: The name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )r,ri)r]rQr!r!r# get_provideros zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr!)r)rrr!r!r#r}sz;CredentialResolver._get_provider_offset..)rQ)r,rdrtr )r]rQr!r!r#ri{sz'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)r,r<r=rrr)r]rrr!r!r#rBs  z#CredentialResolver.load_credentialsN) r`rarbr^rhrjr;rlrirBr!r!r!r#r>2s r>)N)F)BrrDloggingrjrrrqr  collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrbotocore.configloaderrbotocore.compatrrbotocore.exceptionsr r r r r rrrbotocore.utilsrrr getLoggerr`r<rrArCrFrIrMrZrerdrfrNrrrrrr5r0r.r7r4r6r8r1r3r/r>r!r!r!r#sv                   J -'Ar-Fo"*7*XE