B \@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 8/tmp/pip-build-uw_ogi45/botocore/botocore/credentials.pyLz,create_credential_resolver..) load_configclient_creatorcache profile_namecredential_sourcer)creds_filenamer(csjS)N)rr )r!r r"r#\r$)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_nowsrCcCst|tjr|St|S)N) isinstancerAr)valuer r r"_parse_if_neededs rFFcCs&t|tjr"|r|S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rDrA isoformatstrftime)rEisor r r"_serialize_if_neededs   rJcsfdd}|S)Ncs6jf}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expiration)rrr expiry_time) assume_rolerJ)response credentials)clientparamsr r"refreshs  z-create_assume_role_refresher..refreshr )rTrUrVr )rTrUr"create_assume_role_refreshers rWcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)selfrVr r r"__init__sz8create_mfa_serial_refresher.._Refresher.__init__cSs|jr td|_|S)NT)rYrrX)rZr r r"__call__sz8create_mfa_serial_refresher.._Refresher.__call__N)__name__ __module__ __qualname__r[r\r r r r" _Refreshersr`)object)Zactual_refreshr`r r r"create_mfa_serial_refreshersrbc@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)rZZ working_dirr r r"r[szJSONFileCache.__init__cCs||}tj|S)N)_convert_cache_keyospathisfile)rZ 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)rfopenjsonloadOSError ValueErrorIOErrorKeyError)rZrjrkfr 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)rfrndumpsrJ TypeErrorrqrgrhisdirremakedirsfdopenrmO_WRONLYO_CREATtruncatewrite)rZrjrEZfull_keyZ file_contentrtr r r" __setitem__s   zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rgrhjoinre)rZrj full_pathr r r"rfsz JSONFileCache._convert_cache_keyN)r]r^r___doc__rgrh expanduserrZ CACHE_DIRr[rlrurrfr r r r"rcs  rcc@s*eZdZdZd ddZddZddZdS) rKa\ 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)rZrrrrr r r"r[szCredentials.__init__cCs$tj|j|_tj|j|_dS)N)botocorecompatensure_unicoderr)rZr r r"rszCredentials._normalizecCst|j|j|jS)N)rrrr)rZr r r"get_frozen_credentialssz"Credentials.get_frozen_credentials)NN)r]r^r_rr[rrr r r r"rKs    rKc@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)rZrrrrP refresh_usingr time_fetcherr r r"r[s  zRefreshableCredentials.__init__cCs$tj|j|_tj|j|_dS)N)rrrrr)rZr r r"r+sz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)NrrrrP)rrrrPrr)_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. )rXr)rZr r r"r;sz!RefreshableCredentials.access_keycCs ||_dS)N)r)rZrEr 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. )rXr)rZr r r"rHsz!RefreshableCredentials.secret_keycCs ||_dS)N)r)rZrEr 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. )rXr)rZr r r"rUszRefreshableCredentials.tokencCs ||_dS)N)r)rZrEr r r"r^scCs|j|}t|S)N)rrr)rZdeltar 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_timeoutrr9r:)rZ refresh_inr r r"refresh_neededfs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)r)rZr 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)rZZis_mandatory_refreshr r r"rXs       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 Exceptionr9warning_set_from_datarrrrrr RuntimeError)rZrreZ 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) NrrrrPcsg|]}|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) rrrrrrrrr9r:r)rZrZ 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) )rXr)rZr r r"rs"z-RefreshableCredentials.get_frozen_credentials)N)r]r^r_rrrrCr[r classmethodrpropertyrsetterrrrrrrXr 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)rZrrrr r r"r[s z'DeferredRefreshableCredentials.__init__Ncs|jdkrdStt||S)NT)rsuperrr)rZr) __class__r r"rs  z-DeferredRefreshableCredentials.refresh_needed)N)r]r^r_rrCr[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)rZr'expiry_window_secondsr r r"r[#s  z CachedCredentialFetcher.__init__cCs tddS)Nz_create_cache_key())NotImplementedError)rZr r r"r*sz)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacergrhsep)rZfilenamer r r"_make_file_safe-sz'CachedCredentialFetcher._make_file_safecCs tddS)Nz_get_credentials())r)rZr r r"_get_credentials2sz(CachedCredentialFetcher._get_credentialscCs|S)N)_get_cached_credentials)rZr 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.rKrOT)rIrLrMrN)rrrrP)_load_from_cacher_write_to_cacher9r:rJ)rZrRcredsZ expirationr r r"r8s  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jkr4t|j|j}||s*|StddS)Nz6Credentials were found in cache, but they are expired.)rrrrr9r:)rZrr r r"rNs  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dS)N)rrr)rZrRr r r"rYsz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rKrO)rFrrCr)rZrSend_timesecondsr r r"r\sz#CachedCredentialFetcher._is_expired)Nr) r]r^r_r[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_kwargsrr7Z_role_session_name_using_default_session_nameinttime _mfa_promptergetpassrrr[)rZr&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) rrrrnloadsrwrencode hexdigestr)rZargsZ argument_hashr r r"rs z-AssumeRoleCredentialFetcher._create_cache_keycCs|}|}|jf|S)z'Get credentials by calling assume role.)_assume_role_kwargs_create_clientrQ)rZkwargsrTr 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)rrr7r)rZZassume_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)rZZfrozen_credentialsr r r"rs  z*AssumeRoleCredentialFetcher._create_client)NNNr) r]r^r_r[rrrrrr r )rr"rcs :rc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCs ||_dS)N)r!)rZr!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 )rZr r r"roszCredentialProvider.loadc GsLg}xB|D]:}y|||Wq tk rBt|j|dYq Xq W|S)N)rcred_var)appendrsr METHOD)rZmappingZ key_namesfoundZkey_namer r r"_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mapping)N)r]r^r_rCANONICAL_NAMEr[rorr r r r"rs  rc@s:eZdZdZejfddZddZddZe dd Z d S) r3zcustom-processcCs||_||_d|_||_dS)N) _profile_name _load_config_loaded_config_popen)rZr(r%popenr r r"r[ szProcessProvider.__init__csdjdkrdS}|ddk rDt|fddjSt|d|d|djdS)NrPcs S)N)_retrieve_credentials_usingr )credential_processrZr r"r#r$z&ProcessProvider.load..rrr)rrrr)_credential_processrr7rrrrK)rZZ creds_dictr )rrZr"ros  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: 1rLrMrNrO)rrrrPz$Missing required key in response: %s)rr subprocessPIPE communicate returncoderrdecoderrrnrr7rs) rZrZ process_listprr parsedversionrr r r"r$s0     z+ProcessProvider._retrieve_credentials_usingcCs6|jdkr||_|jdi|ji}|dS)Nprofilesr)rrr7r)rZprofile_configr r r"rCs   z#ProcessProvider._credential_processN) r]r^r_rr Popenr[rorrrr r r r"r3s r3c@s$eZdZdZdZddZddZdS)r/ziam-roleZEc2InstanceMetadatacCs ||_dS)N) _role_fetcher)rZrr r r"r[Psz!InstanceMetadataProvider.__init__cCs>|j}|}|sdStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %sZ role_name)rr)rZretrieve_iam_role_credentialsr9r:rrr)rZfetcherrrr r r"roSs  zInstanceMetadataProvider.loadN)r]r^r_rrr[ror 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)rgenviron_build_mapping_mapping)rZrrr r r"r[rs 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)NrrrrP) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMEr7rDlist)rZrZ var_mappingr r r"rs"    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_expiryrPNrr)rr)r) rr7rr9info_create_credentials_fetcherrrrrK)rZrrrSrPr r r"ros      zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|s(tdd||d<dd}|sTtdd||d<d|d<x*dD]}|d}|rn||d<PqnWd|d<dd}|r||d<|r|stdd|S)Nrr#)rrrrrP)r7r )r$rSrrZ token_env_varrrP)rrrr r"rs2 zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rrr)rZrr )rrrr"r&s  z'EnvProvider._create_credentials_fetcher)NN) r]r^r_rrrrr r!r[rror&r r r r"r-hs r-c@s2eZdZdZdZdZdZdZd ddZd d Z dS) r5zec2-credentials-fileZ Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZ AWSSecretKeyNcCs*|dkrtj}|dkrt}||_||_dS)N)rgrr_environ_parser)rZrparserr 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(rgrhrr)rr9r%rrKr)rZrrrrr r r"ros       zOriginalEC2Provider.load)NN) r]r^r_rrZ CRED_FILE_ENVrrr[ror r r r"r5s r5c@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)r2zshared-credentials-fileZSharedCredentialsrraws_security_tokenrNcCs2||_|dkrd}||_|dkr(tjj}||_dS)Nr)_creds_filenamerr configloaderraw_config_parse _ini_parser)rZr*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 rrr9r%rr_get_session_tokenrKr)rZZavailable_credsconfigrrrr r r"ros    zSharedCredentialProvider.loadcCs$x|jD]}||kr||SqWdS)N)r )rZr2Z token_envvarr r r"r1"s z+SharedCredentialProvider._get_session_token)NN) r]r^r_rrrrr r[ror1r r r r"r2s r2c@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)r4z0INI 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)rZr+r(Z config_parserr r r"r[4s 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) r4r3r rrr9r%rrr1rKr)rZrrrrrr r r"roCs   zConfigProvider.loadcCs$x|jD]}||kr||SqWdS)N)r )rZrZ token_namer r r"r1Ys z!ConfigProvider._get_session_token)N) r]r^r_rrrrrr r[ror1r r r r"r4(s r4c@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)r6z boto-configZ Boto2ConfigZ BOTO_CONFIGz /etc/boto.cfgz~/.botorrNcCs.|dkrtj}|dkrtjj}||_||_dS)N)rgrrr-r.r(r/)rZrr0r r r"r[hs 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. rKz)Found credentials in boto config file: %s)rN) BOTO_CONFIG_ENVr(DEFAULT_CONFIG_FILENAMESr/r rr9r%rrrKr)rZZpotential_locationsrr2rSrrr r r"rops"   zBotoProvider.load)NN) r]r^r_rrr5r6rrr[ror r r r"r6_s r6c@seZdZdZdZdZdZejdfddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdS)r0z 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)rZr%r&r'r(Zprompterr)r r r"r[s#zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r<||jSdS)Nr)rrr7r_has_assume_role_config_vars_load_creds_via_assume_role)rZrrr r r"ros   zAssumeRoleProvider.loadcCs |j|kS)N)ROLE_CONFIG_VAR)rZrr r r"r:sz/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_credentialsr7rrr7r'rrbrrrC) rZr( role_configrrr=r>rrrZ refresherr r r"r;s<      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=rBrCNzDThe profile "%s" contains both source_profile and credential_source.)rz#source_profile or credential_source)rr) rr7rrqr r r_validate_credential_source_validate_source_profile) rZr(rrrBrrCrr>r=rrAr 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.)r8r is_supported)rZZparent_profilerCr r r"rD4s  z.AssumeRoleProvider._validate_credential_sourcecCst||||gS)N)any_has_static_credentialsr:)rZrr r r"_source_profile_has_credentialsAsz2AssumeRoleProvider._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)rBZvisited_profiles)rr7r rIr9r rH)rZZparent_profile_nameZsource_profile_namerrBr r r"rEGs(     z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrrc3s|]}|kVqdS)Nr )rZ static_key)rr r" ysz=AssumeRoleProvider._has_static_credentials..)rG)rZrZ static_keysr )rr"rHwsz*AssumeRoleProvider._has_static_credentialscCs<|d}|dk r|||S|d}|j|||S)NrCrB)r7 _resolve_credentials_from_sourcer9r!_resolve_credentials_from_profile)rZrAr(rCrBr r r"r@{s  z.AssumeRoleProvider._resolve_source_credentialscCs4|jdi}||}||r*||S||S)Nr)rr7rH(_resolve_static_credentials_from_profiler;)rZr(rrr r r"rLs   z4AssumeRoleProvider._resolve_credentials_from_profilec CsVyt|d|d|ddStk rP}zt|jt|dWdd}~XYnXdS)Nrrr)rrr)rr)rKr7rsr rstr)rZrrr r r"rMsz;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|dkr$t|d|d|S)NzBNo credentials found in credential_source referenced in profile %s)rr)r8rr)rZrCr(rSr r r"rKs z3AssumeRoleProvider._resolve_credentials_from_source)r]r^r_rrr<ZEXPIRY_WINDOW_SECONDSrr[ror:r;r?rDrIrErHr@rLrMrKr r r r"r0s"4,2 0   r0c@s<eZdZddZddZddZddZd d Zd d Zd S)r1cCs ||_dS)N) _providers)rZr,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..)rO)rZ source_namer r r"rFs 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_providerrDr;r?ro)rZrPsourcer 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 )rZcanonical_namerr<r r r"rQs     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)rOrrU)rZrWrrSr r r"rTs z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"x|jD]}|j|kr|SqWdS)z0Return a credential provider by its METHOD name.N)rOr)rZrrr r r"rVs  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r]r^r_r[rFrrQrTrVr r r r"r1s  & r1c@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)rgrrr(_fetcher)rZrrr r r"r[s zContainerProvider.__init__cCs$|j|jks|j|jkr |SdS)N)ENV_VARr( ENV_VAR_FULL_retrieve_or_fail)rZr r r"roszContainerProvider.loadcCsn|r|j|j|j}n |j|j}|}|||}|}t|d|d|d|j t |d|dS)NrrrrP)rrrrrPr) _provided_relative_urirXfull_urlr(rYrZ_build_headers_create_fetcherrrrF)rZfull_uriheadersrrr r r"r[s   z#ContainerProvider._retrieve_or_failcCs&i}|j|j}|dk r"d|iSdS)N Authorization)r(r7ENV_VAR_AUTH_TOKEN)rZraZ 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)raz'Error retrieving container metadata: %sT)r)rrrLrMTokenrO)rrrrP)rXZretrieve_full_urirr9r:rrrN)rRr)r`rarZr r" fetch_creds0sz6ContainerProvider._create_fetcher..fetch_credsr )rZr`rarer )r`rarZr"r_/sz!ContainerProvider._create_fetchercCs |j|jkS)N)rYr()rZr r r"r\Bsz(ContainerProvider._provided_relative_uri)NN)r]r^r_rrrYrZrcr[ror[r^r_r\r 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,)rZr,r r r"r[GszCredentialResolver.__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"r^sz4CredentialResolver.insert_before..)rSN)r,indexrqr insert)rZrScredential_provideroffsetr r r" insert_beforeOs 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,rg)rZrSrhrir r r" insert_aftercs 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"r{sz-CredentialResolver.remove..N)r,rfpop)rZrSZavailable_methodsrir r r"r8ts  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,rk)rZrSr r r" get_providers zCredentialResolver.get_providercCs:ydd|jD|Stk r4t|dYnXdS)NcSsg|] }|jqSr )r)rrr r r"rsz;CredentialResolver._get_provider_offset..)rS)r,rfrqr )rZrSr r r"rksz'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,r9r:rro)rZrrr r r"r?s  z#CredentialResolver.load_credentialsN) r]r^r_r[rjrlr8rnrkr?r r r r"r;Fs r;)N)F)BrrAloggingrgrrrnr  collectionsrcopyrhashlibrZdateutil.parserrZ dateutil.tzrZbotocore.configloaderrZbotocore.compatrrZbotocore.exceptionsr r r r r rrrZbotocore.utilsrrr getLoggerr]r9rr>r@rCrFrJrWrbrarcrKrrrrrr3r/r-r5r2r4r6r0r1r.r;r r r r"sv                   J -'Av-Ft"*7*"XE