B w\a@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. profiledefaultZcredentials_file config_fileZmetadata_service_timeoutZmetadata_service_num_attemptsN)timeout num_attempts user_agent)iam_role_fetchercsjS)N) full_config)sessionr n/private/var/folders/j5/hv2kzfgs4sl6jnf70fy_2vrc4p3c_b/T/pip-install-d8kq1y21/botocore/botocore/credentials.pyLsz,create_credential_resolver..) load_configclient_creatorcache profile_namecredential_sourcer)creds_filenamer'csjS)N)rr )r!r r"r#\s)r'r$)config_filenamer'zWSkipping environment variable credential check because profile name was explicitly set.) providers)Zget_config_variable EnvProviderContainerProviderInstanceMetadataProviderrrAssumeRoleProviderZ create_clientCanonicalNameCredentialSourcerSharedCredentialProviderProcessProviderConfigProviderOriginalEC2Provider BotoProviderZinstance_variablesgetremoveloggerdebugCredentialResolver) r!r&r'Zcredential_filerZmetadata_timeoutrZ env_providerZcontainer_providerZinstance_metadata_providerassume_role_providerr+resolverr )r!r"create_credential_resolver3sL         r=cCst|}|S)N)r=load_credentials)r!r<r r r"get_credentials}sr?cCstjtS)N)datetimenowrr r r r" _local_nowsrBcCst|tjr|St|S)N) isinstancer@r)valuer r r"_parse_if_neededs rEFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rCr@ isoformatstrftime)rDisor r r"_serialize_if_neededs   rIcsfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerI)response credentials)clientparamsr r"refreshs  z-create_assume_role_refresher..refreshr )rSrTrUr )rSrTr"create_assume_role_refreshers rVcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)selfrUr r r"__init__sz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)rXrrW)rYr r r"__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)__name__ __module__ __qualname__rZr[r r r r" _Refreshersr_)object)Zactual_refreshr_r r r"create_mfa_serial_refreshersrac@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)rYZ working_dirr r r"rZszJSONFileCache.__init__cCs||}tj|S)N)_convert_cache_keyospathisfile)rY 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)reopenjsonloadOSError ValueErrorIOErrorKeyError)rYrirjfr 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)rermdumpsrI TypeErrorrprfrgisdirrdmakedirsfdopenrlO_WRONLYO_CREATtruncatewrite)rYrirDZfull_keyZ file_contentrsr r r" __setitem__s   zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rfrgjoinrd)rYri full_pathr r r"resz JSONFileCache._convert_cache_keyN)r\r]r^__doc__rfrg expanduserrZ CACHE_DIRrZrkrtrrer r r r"rbs  rbc@s*eZdZdZd ddZddZddZdS) rJa\ 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)rYrrrrr r r"rZszCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)rYr r r"rszCredentials._normalizecCst|j|j|jS)N)rrrr)rYr r r"get_frozen_credentialssz"Credentials.get_frozen_credentials)NN)r\r]r^rrZrrr r r r"rJs    rJc@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)rYrrrrO refresh_usingr time_fetcherr r r"rZs  zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)rYr r r"r+sz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)NrrrrO)rrrrOrr)_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. )rWr)rYr r r"r;sz!RefreshableCredentials.access_keycCs ||_dS)N)r)rYrDr 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. )rWr)rYr r r"rHsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)rYrDr 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. )rWr)rYr r r"rUszRefreshableCredentials.tokencCs ||_dS)N)r)rYrDr r r"r^scCs|j|}t|S)N)rrr)rYdeltar 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_timeoutrr8r9)rY refresh_inr r r"refresh_neededfs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)rYr 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)rYZis_mandatory_refreshr r r"rWs       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 Exceptionr8warning_set_from_datarrrrrr RuntimeError)rYrreZ 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) NrrrrOcsg|]}|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) rrrrrrrrr8r9r)rYrZ 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) )rWr)rYr r r"rs"z-RefreshableCredentials.get_frozen_credentials)N)r\r]r^rrrrBrZr classmethodrpropertyrsetterrrrrrrWr 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)rYrrrr r r"rZs z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||S)NT)rsuperrr)rYr) __class__r r"rs  z-DeferredRefreshableCredentials.refresh_needed)N)r\r]r^rrBrZr __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)rYr&expiry_window_secondsr r r"rZ#s  z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)rYr r r"r*sz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerfrgsep)rYfilenamer r r"_make_file_safe-sz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)rYr r r"_get_credentials2sz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)rYr 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.rJrNT)rHrKrLrM)rrrrO)_load_from_cacher_write_to_cacher8r9rI)rYrQcredsZ expirationr r r"r8s  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrrrr8r9)rYrr r r"rNs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrr)rYrQr r r"rYsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rJrN)rErrBr)rYrRend_timesecondsr r r"r\sz#CachedCredentialFetcher._is_expired)Nr) r\r]r^rZrrrrrrrrr 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_kwargsrr6Z_role_session_name_using_default_session_nameinttime _mfa_promptergetpassrrrZ)rYr%source_credentialsrole_arn extra_args mfa_prompterr&r)rr r"rZds&"     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) rrrrmloadsrvrencode hexdigestr)rYargsZ argument_hashr r r"rs z-AssumeRoleCredentialFetcher._create_cache_keycCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientrP)rYkwargsrSr r r"rsz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|dk r6d|}||}||d<|d}|dk rP||d<|S)zAGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: Z TokenCodeDurationSeconds)rrr6r)rYZassume_role_kwargs mfa_serialpromptZ token_codeduration_secondsr 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)rYZfrozen_credentialsr r r"rs  z*AssumeRoleCredentialFetcher._create_client)NNNr) r\r]r^rZrrrrrr r )rr"rcs :rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r!)rYr!r r r"rZszCredentialProvider.__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 )rYr r r"rnszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendrrr METHOD)rYmappingZ key_namesfoundZkey_namer r r"_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)r\r]r^rCANONICAL_NAMErZrnrr r r r"rs  rc@s:eZdZdZejfddZddZddZe dd Z d S) r2zcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)rYr'r$popenr r r"rZ szProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)NrOcs S)N)_retrieve_credentials_usingr )credential_processrYr r"r#sz&ProcessProvider.load..rrr)rrrr)_credential_processrr6rrrrJ)rYZ creds_dictr )rrYr"rns  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: 1rKrLrMrN)rrrrOz$Missing required key in response: %s)rr subprocessPIPE communicate returncoderrdecoderrrmrr6rr) rYrZ process_listprrparsedversionrr r r"r$s0     z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr)rrr6r)rYprofile_configr r r"rCs   z#ProcessProvider._credential_processN) r\r]r^rr PopenrZrnrrrr r r r"r2s r2c@s$eZdZdZdZddZddZdS)r.ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)rYrr r r"rZPsz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %sZ role_name)rr)rZretrieve_iam_role_credentialsr8r9rrr)rYfetcherrrr r r"rnSs  zInstanceMetadataProvider.loadN)r\r]r^rrrZrnr r r r"r.Lsr.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)rfenviron_build_mapping_mapping)rYrrr r r"rZrs 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)NrrrrO) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr6rClist)rYrZ var_mappingr r r"rs"    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_expiryrONrr)rr)r) rrr8info_create_credentials_fetcherrrrrJ)rYrrRrOr r r"rns     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)rrrrrO)r6r )r"rRrrrZ token_env_varrO)rrrr r"rs. zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rrr)rYrr )rrrr"r$s z'EnvProvider._create_credentials_fetcher)NN) r\r]r^rrrrrr rZrrnr$r r r r"r,hs r,c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r4zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rfrr_environ_parser)rYrparserr r r"rZs 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&rfrgrr'rr8r#rrJr)rYrrrrr r r"rns       zOriginalEC2Provider.load)NN) r\r]r^rrZ CRED_FILE_ENVrrrZrnr r r r"r4s r4c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)r1zshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr)_creds_filenamerr configloaderraw_config_parse _ini_parser)rYr)r' ini_parserr r r"rZsz!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 rrr8r#rr_get_session_tokenrJr)rYZavailable_credsconfigrrrr r r"rn s    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)r)rYr0Z token_envvarr r r"r/s z+SharedCredentialProvider._get_session_token)NN) r\r]r^rrrrrrZrnr/r r r r"r1s r1c@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)r3z0INI 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)rYr*r'Z config_parserr r r"rZ/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 rrr8r#rrr/rJr)rYrrrrrr r r"rn>s   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)r)rYrZ token_namer r r"r/Ts z!ConfigProvider._get_session_token)N) r\r]r^rrrrrrrZrnr/r r r r"r3#s r3c@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r5z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rfrrr+r,r&r-)rYrr.r r r"rZcs 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. rJz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVr&DEFAULT_CONFIG_FILENAMESr-r rr8r#rrrJr)rYZpotential_locationsrr0rRrrr r r"rnks"   zBotoProvider.load)NN) r\r]r^rrr3r4rrrZrnr r r r"r5Zs r5c@seZdZdZdZdZdZejdfddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdS)r/z 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)rYr$r%r&r'Zprompterr(r r r"rZs#zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr)rrr6r_has_assume_role_config_vars_load_creds_via_assume_role)rYrrr r r"rns   zAssumeRoleProvider.loadcCs |j|kS)N)ROLE_CONFIG_VAR)rYrr r r"r8sz/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)r%rrrrr&)rrr) _get_role_config_resolve_source_credentialsr6rrr5r&rrarrrB) rYr' role_configrrr;r<rrrZ refresherr r r"r9s<      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.rsource_profilercredential_sourcerr<r;r)rr<rr;r@rANzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr) rr6rrpr r r_validate_credential_source_validate_source_profile) rYr'rrr@rrArr<r;rr?r r r"r=sB          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)rYZparent_profilerAr r r"rB/s  z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsr8)rYrr 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)rr6r rGr7r rF)rYZparent_profile_nameZsource_profile_namerr@r r r"rCBs(     z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr )rZ static_key)rr r" tsz=AssumeRoleProvider._has_static_credentials..)rE)rYrZ static_keysr )rr"rFrsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)NrAr@)r6 _resolve_credentials_from_sourcer7r!_resolve_credentials_from_profile)rYr?r'rAr@r r r"r>vs  z.AssumeRoleProvider._resolve_source_credentialscCs4|jdi}||}||r*||S||S)Nr)rr6rF(_resolve_static_credentials_from_profiler9)rYr'rrr r r"rJs   z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr)rr)rJr6rrr rstr)rYrrr r r"rKsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)r6rr)rYrAr'rRr r r"rIs z3AssumeRoleProvider._resolve_credentials_from_source)r\r]r^rrr:ZEXPIRY_WINDOW_SECONDSrrZrnr8r9r=rBrGrCrFr>rJrKrIr r r r"r/s"4,2 0   r/c@s<eZdZddZddZddZddZd d Zd d Zd S)r0cCs ||_dS)N) _providers)rYr+r r r"rZsz'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)rY 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_providerrCr:r>rn)rYrNsourcer 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 )rYcanonical_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)rYrUrrQr 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)rYrrr r r"rTs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r\r]r^rZrDrrOrRrTr r r r"r0s  & r0c@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)rfrrr&_fetcher)rYrrr r r"rZs zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARr& ENV_VAR_FULL_retrieve_or_fail)rYr r r"rn szContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)NrrrrO)rrrrrOr) _provided_relative_urirVfull_urlr&rWrX_build_headers_create_fetcherrrrE)rYfull_uriheadersrrr r r"rYs   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)r&r6ENV_VAR_AUTH_TOKEN)rYr_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)rrrKrLTokenrN)rrrrO)rVZretrieve_full_urirr8r9rrrL)rQr)r^r_rYr r" fetch_creds+sz6ContainerProvider._create_fetcher..fetch_credsr )rYr^r_rcr )r^r_rYr"r]*sz!ContainerProvider._create_fetchercCs |j|jkS)N)rWr&)rYr r r"rZ=sz(ContainerProvider._provided_relative_uri)NN)r\r]r^rrrWrXrarZrnrYr\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+)rYr+r r r"rZBszCredentialResolver.__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"rYsz4CredentialResolver.insert_before..)rQN)r+indexrpr insert)rYrQcredential_provideroffsetr r r" insert_beforeJs 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)rYrQrfrgr r r" insert_after^s 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"rvsz-CredentialResolver.remove..N)r+rdpop)rYrQZavailable_methodsrgr r r"r7os  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)rYrQr r r" get_provider~s zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr )r)rrr r r"rsz;CredentialResolver._get_provider_offset..)rQ)r+rdrpr )rYrQr r r"risz'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+r8r9rrn)rYrrr r r"r>s  z#CredentialResolver.load_credentialsN) r\r]r^rZrhrjr7rlrir>r r r r"r:As r:)N)F)Brr@loggingrfrrrmr  collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrZbotocore.configloaderrZbotocore.compatrrZbotocore.exceptionsr r r r r rrrZbotocore.utilsrrr getLoggerr\r8rr=r?rBrErIrVrar`rbrJrrrrrr2r.r,r4r1r3r5r/r0r-r:r r r r"sv                   J -'Av-Fo"*7*"XE