U
    M8c-E                    @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZ d dlZd dlZd dlmZ d dlmZmZ d d	lmZ d d
lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ d dl%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. e/e0Z1e	ddddgZ2dZ3dZ4dRddZ5G dd dZ6dd Z7dd Z8dd Z9dSddZ:d d! Z;d"d# Z<d$d% Z=G d&d' d'Z>G d(d) d)e>Z?G d*d+ d+e?Z@G d,d- d-ZAG d.d/ d/eAZBG d0d1 d1eBZCG d2d3 d3eBZDG d4d5 d5ZEG d6d7 d7eEZFG d8d9 d9eEZGG d:d; d;eEZHG d<d= d=eEZIG d>d? d?eEZJG d@dA dAeEZKG dBdC dCeEZLG dDdE dEeEZMG dFdG dGeEZNG dHdI dIZOG dJdK dKeEZPG dLdM dMZQG dNdO dOeAZRG dPdQ dQeEZSdS )T    N)
namedtuple)deepcopy)sha1parse)tzlocaltzutc)UNSIGNED)compat_shell_splittotal_seconds)Config)	ConfigNotFoundCredentialRetrievalErrorInfiniteLoopConfigErrorInvalidConfigErrorMetadataRetrievalErrorPartialCredentialsErrorRefreshWithMFAUnsupportedErrorUnauthorizedSSOTokenErrorUnknownCredentialError)SSOTokenProvider)ContainerMetadataFetcherFileWebIdentityTokenLoaderInstanceMetadataFetcherJSONFileCacheSSOTokenLoaderparse_key_val_fileresolve_imds_endpoint_modeReadOnlyCredentials
access_key
secret_keytokeniX    c              	      s    dpd}  d}  d}  ddk	}  dt td}|dkrVi }t }t }	tt|| 	 |dd	}
t
 ||d
}t fddt |||t||	|
g|d}||g}|j||d}t t |	|
g}|| | }|r|| td t|d}|S )zCreate a default credential resolver.

    This creates a pre-configured credential resolver
    that includes the default lookup chain for
    credentials.

    profiledefaultZmetadata_service_timeoutZmetadata_service_num_attemptsNec2_metadata_service_endpoint)r%   Z"ec2_metadata_service_endpoint_modeZec2_credential_refresh_window)timeoutnum_attempts
user_agentconfig)iam_role_fetcher)cacheregion_namec                      s    j S N)full_config sessionr/   8/tmp/pip-unpacked-wheel-ozje0y8b/botocore/credentials.py<lambda>j       z,create_credential_resolver.<locals>.<lambda>)load_configclient_creatorr+   profile_namecredential_sourcerprofile_provider_builderr7   disable_env_varszWSkipping environment variable credential check because profile name was explicitly set.	providers)get_config_variableZinstance_variablesgetr   !_DEFAULT_ADVISORY_REFRESH_TIMEOUTEnvProviderContainerProviderInstanceMetadataProviderr   r(   ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr=   OriginalEC2ProviderBotoProviderremoveloggerdebugCredentialResolver)r1   r+   r,   r7   Zmetadata_timeoutr'   r;   Zimds_configZenv_providerZcontainer_providerZinstance_metadata_providerr9   assume_role_providerZpre_profileprofile_providersZpost_profiler=   resolverr/   r0   r2   create_credential_resolverA   sv    


	  


rQ   c                   @   sL   e Zd ZdZdddZdddZdd	 Zd
d Zdd Zdd Z	dd Z
dS )rD   a  This 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.
    Nc                 C   s   || _ || _|| _|| _d S r-   )_session_cache_region_name_sso_token_cache)selfr1   r+   r,   Zsso_token_cacher/   r/   r2   __init__   s    zProfileProviderBuilder.__init__Fc                 C   s.   |  ||| || || || |gS r-   )_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_providerrV   r7   r;   r/   r/   r2   r=      s    z ProfileProviderBuilder.providersc                    s   t | fdddS )Nc                      s    j jS r-   rR   r.   r/   rV   r/   r2   r3      r4   zAProfileProviderBuilder._create_process_provider.<locals>.<lambda>)r7   r5   )ProcessProviderrV   r7   r/   r_   r2   r[      s    
z/ProfileProviderBuilder._create_process_providerc                 C   s   | j d}t||dS )NZcredentials_file)r7   creds_filename)rR   r>   SharedCredentialProvider)rV   r7   Zcredential_filer/   r/   r2   rZ      s
    z9ProfileProviderBuilder._create_shared_credential_providerc                 C   s   | j d}t||dS )Nconfig_file)r7   config_filename)rR   r>   ConfigProvider)rV   r7   rd   r/   r/   r2   r\      s
    z.ProfileProviderBuilder._create_config_providerc                    s&   t  fddt j j j||dS )Nc                      s    j jS r-   r^   r/   r_   r/   r2   r3      r4   zFProfileProviderBuilder._create_web_identity_provider.<locals>.<lambda>)r5   r6   r+   r7   r;   )!AssumeRoleWithWebIdentityProviderrF   rR   rT   rS   r]   r/   r_   r2   rX      s    
 z4ProfileProviderBuilder._create_web_identity_providerc                    s*   t  fdd jj| j jt jdS )Nc                      s    j jS r-   r^   r/   r_   r/   r2   r3      r4   z=ProfileProviderBuilder._create_sso_provider.<locals>.<lambda>)r5   r6   r7   r+   token_cachetoken_provider)SSOProviderrR   create_clientrS   rU   r   ra   r/   r_   r2   rY      s    
z+ProfileProviderBuilder._create_sso_provider)NNN)F)__name__
__module____qualname____doc__rW   r=   r[   rZ   r\   rX   rY   r/   r/   r/   r2   rD      s        

rD   c                 C   s   t | }| S r-   )rQ   load_credentials)r1   rP   r/   r/   r2   get_credentials   s    rq   c                   C   s   t j t S r-   )datetimenowr   r/   r/   r/   r2   
_local_now   s    rt   c                 C   s   t | tjr| S t| S r-   )
isinstancerr   r   )valuer/   r/   r2   _parse_if_needed   s    rw   Fc                 C   s&   t | tjr"|r|  S | dS | S )Nz%Y-%m-%dT%H:%M:%S%Z)ru   rr   	isoformatstrftime)rv   isor/   r/   r2   _serialize_if_needed   s
    
r{   c                    s    fdd}|S )Nc                    s"   d i}|j f | j| f|S )Nr,   )updaterk   )Zservice_namekwargsZcreate_client_kwargsr,   r1   r/   r2   r6      s    z+_get_client_creator.<locals>.client_creatorr/   )r1   r,   r6   r/   r~   r2   rF      s    rF   c                    s    fdd}|S )Nc                     s6    j f } | d }|d |d |d t|d dS )NCredentialsAccessKeyIdSecretAccessKeySessionToken
Expirationr   r    r!   expiry_time)assume_roler{   )responsecredentialsclientparamsr/   r2   refresh  s    
z-create_assume_role_refresher.<locals>.refreshr/   )r   r   r   r/   r   r2   create_assume_role_refresher  s    r   c                 C   s   G dd d}|| S )Nc                   @   s   e Zd Zdd Zdd ZdS )z/create_mfa_serial_refresher.<locals>._Refresherc                 S   s   || _ d| _d S )NF)_refresh_has_been_called)rV   r   r/   r/   r2   rW     s    z8create_mfa_serial_refresher.<locals>._Refresher.__init__c                 S   s   | j rt d| _ |  S NT)r   r   r   r_   r/   r/   r2   __call__  s    z8create_mfa_serial_refresher.<locals>._Refresher.__call__N)rl   rm   rn   rW   r   r/   r/   r/   r2   
_Refresher  s   r   r/   )Zactual_refreshr   r/   r/   r2   create_mfa_serial_refresher  s    r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
r   ap  
    Holds the credentials needed to authenticate requests.

    :param str access_key: The access key part of the credentials.
    :param str secret_key: The secret key part of the credentials.
    :param str token: The security token, valid only for session credentials.
    :param str method: A string which identifies where the credentials
        were found.
    Nc                 C   s0   || _ || _|| _|d krd}|| _|   d S )Nexplicit)r   r    r!   method
_normalize)rV   r   r    r!   r   r/   r/   r2   rW   4  s    zCredentials.__init__c                 C   s$   t j| j| _t j| j| _d S r-   )botocorecompatensure_unicoder   r    r_   r/   r/   r2   r   ?  s    zCredentials._normalizec                 C   s   t | j| j| jS r-   )r   r   r    r!   r_   r/   r/   r2   get_frozen_credentialsI  s
      z"Credentials.get_frozen_credentials)NN)rl   rm   rn   ro   rW   r   r   r/   r/   r/   r2   r   )  s   


r   c                   @   s   e Zd ZdZeZeZefddZ	dd Z
edd Zedd	 Zejd
d	 Zedd Zejdd Zedd Zejdd Zdd Zd"ddZdd Zdd Zdd Zedd Zdd Zd d! ZdS )#RefreshableCredentialsa@  
    Holds the credentials needed to authenticate requests. In addition, it
    knows how to refresh itself.

    :param str access_key: The access key part of the credentials.
    :param str secret_key: The secret key part of the credentials.
    :param str token: The security token, valid only for session credentials.
    :param function refresh_using: Callback function to refresh the credentials.
    :param str method: A string which identifies where the credentials
        were found.
    :param function time_fetcher: Callback function to retrieve current time.
    c                 C   sN   || _ || _|| _|| _|| _|| _t | _|| _	t
|||| _|   d S r-   )_refresh_using_access_key_secret_key_token_expiry_time_time_fetcher	threadingLock_refresh_lockr   r   _frozen_credentialsr   )rV   r   r    r!   r   refresh_usingr   time_fetcherr/   r/   r2   rW   d  s    

  zRefreshableCredentials.__init__c                 C   s$   t j| j| _t j| j| _d S r-   )r   r   r   r   r   r_   r/   r/   r2   r   {  s    z!RefreshableCredentials._normalizec                 C   s.   | |d |d |d |  |d ||d}|S )Nr   r    r!   r   )r   r    r!   r   r   r   )_expiry_datetime)clsmetadatar   r   instancer/   r/   r2   create_from_metadata  s    z+RefreshableCredentials.create_from_metadatac                 C   s   |    | jS 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/   r2   r     s    z!RefreshableCredentials.access_keyc                 C   s
   || _ d S r-   )r   rV   rv   r/   r/   r2   r     s    c                 C   s   |    | jS r   )r   r   r_   r/   r/   r2   r      s    z!RefreshableCredentials.secret_keyc                 C   s
   || _ d S r-   )r   r   r/   r/   r2   r      s    c                 C   s   |    | jS r   )r   r   r_   r/   r/   r2   r!     s    zRefreshableCredentials.tokenc                 C   s
   || _ d S r-   )r   r   r/   r/   r2   r!     s    c                 C   s   | j |   }t|S r-   )r   r   r   )rV   deltar/   r/   r2   _seconds_remaining  s    z)RefreshableCredentials._seconds_remainingNc                 C   s:   | j dkrdS |dkr| j}|  |kr,dS td dS )a  Check 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_timeoutr   rK   rL   rV   
refresh_inr/   r/   r2   refresh_needed  s    

z%RefreshableCredentials.refresh_neededc                 C   s   | j ddS )Nr   )r   )r   r_   r/   r/   r2   _is_expired  s    z"RefreshableCredentials._is_expiredc              	   C   s   |  | jsd S | jdr`z4|  | js2W $d S |  | j}| j|d W d S | j  X nD|  | jr| j, |  | jsW 5 Q R  d S | jdd W 5 Q R X d S )NF)is_mandatoryT)r   r   r   acquirerelease_mandatory_refresh_timeout_protected_refresh)rV   Zis_mandatory_refreshr/   r/   r2   r     s"    zRefreshableCredentials._refreshc                 C   s   z|   }W n8 tk
rD   |r$dnd}tjd|dd |r> Y d S X | | t| j| j| j| _	| 
 rd}t| t|d S )N	mandatoryZadvisoryzARefreshing temporary credentials failed during %s refresh period.Texc_infozLCredentials were refreshed, but the refreshed credentials are still expired.)r   	ExceptionrK   warning_set_from_datar   r   r   r   r   r   RuntimeError)rV   r   r   Zperiod_namemsgr/   r/   r2   r     s.    
  
z)RefreshableCredentials._protected_refreshc                 C   s   t | S r-   r   )Ztime_strr/   r/   r2   r   !  s    z'RefreshableCredentials._expiry_datetimec                    s   ddddg} s|}n fdd|D }|rHd}t | j|d| d	 d | _ d | _ d | _t d | _t	d
| j | 
  d S )Nr   r    r!   r   c                    s   g | ]}| kr|qS r/   r/   ).0kdatar/   r2   
<listcomp>*  s      z9RefreshableCredentials._set_from_data.<locals>.<listcomp>z7Credential refresh failed, response did not contain: %s, provider	error_msgz(Retrieved credentials will expire at: %s)r   r   joinr   r    r!   r   r   rK   rL   r   )rV   r   Zexpected_keysZmissing_keysmessager/   r   r2   r   %  s&    


 z%RefreshableCredentials._set_from_datac                 C   s   |    | jS )a  Return 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/   r2   r   <  s    "z-RefreshableCredentials.get_frozen_credentials)N)rl   rm   rn   ro   r@   r   "_DEFAULT_MANDATORY_REFRESH_TIMEOUTr   rt   rW   r   classmethodr   propertyr   setterr    r!   r   r   r   r   r   staticmethodr   r   r   r/   r/   r/   r2   r   O  s:   









"'
r   c                       s.   e Zd ZdZefddZd fdd	Z  ZS )DeferredRefreshableCredentialszyRefreshable credentials that don't require initial credentials.

    refresh_using will be called upon first access.
    c                 C   s>   || _ d | _d | _d | _d | _|| _t | _|| _	d | _
d S r-   )r   r   r   r   r   r   r   r   r   r   r   )rV   r   r   r   r/   r/   r2   rW   h  s    
z'DeferredRefreshableCredentials.__init__Nc                    s   | j d krdS t |S r   )r   superr   r   	__class__r/   r2   r   s  s    
z-DeferredRefreshableCredentials.refresh_needed)N)rl   rm   rn   ro   rt   rW   r   __classcell__r/   r/   r   r2   r   b  s   r   c                   @   sZ   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdS )CachedCredentialFetcherr"   Nc                 C   s4   |d kri }|| _ |  | _|d kr*| j}|| _d S r-   )rS   _create_cache_key
_cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)rV   r+   expiry_window_secondsr/   r/   r2   rW   |  s    
z CachedCredentialFetcher.__init__c                 C   s   t dd S )Nz_create_cache_key()NotImplementedErrorr_   r/   r/   r2   r     s    z)CachedCredentialFetcher._create_cache_keyc                 C   s$   | dd tjjd}| ddS )N:_/)replaceospathsep)rV   filenamer/   r/   r2   _make_file_safe  s    z'CachedCredentialFetcher._make_file_safec                 C   s   t dd S )Nz_get_credentials()r   r_   r/   r/   r2   _get_credentials  s    z(CachedCredentialFetcher._get_credentialsc                 C   s   |   S r-   )_get_cached_credentialsr_   r/   r/   r2   fetch_credentials  s    z)CachedCredentialFetcher.fetch_credentialsc                 C   s`   |   }|dkr$|  }| | n
td |d }t|d dd}|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.r   r   T)rz   r   r   r   r   )_load_from_cacher   _write_to_cacherK   rL   r{   )rV   r   creds
expirationr/   r/   r2   r     s    
z/CachedCredentialFetcher._get_cached_credentialsc                 C   s8   | j | jkr4t| j| j  }| |s*|S td d S )Nz6Credentials were found in cache, but they are expired.)r   rS   r   r   rK   rL   )rV   r   r/   r/   r2   r     s    
z(CachedCredentialFetcher._load_from_cachec                 C   s   t || j| j< d S r-   )r   rS   r   )rV   r   r/   r/   r2   r     s    z'CachedCredentialFetcher._write_to_cachec                 C   s(   t |d d }t|t  }|| jk S )z!Check if credentials are expired.r   r   )rw   r   rt   r   )rV   r   Zend_timesecondsr/   r/   r2   r     s    z#CachedCredentialFetcher._is_expired)NN)rl   rm   rn   r   rW   r   r   r   r   r   r   r   r   r/   r/   r/   r2   r   y  s   
	r   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	BaseAssumeRoleCredentialFetcherNc                    sf   || _ || _|d kri | _n
t|| _| j| jd< | jd| _d| _| jsT|   t 	|| d S )NZRoleArnRoleSessionNameF)
_client_creatorZ	_role_arn_assume_kwargsr   r?   _role_session_name_using_default_session_name_generate_assume_role_namer   rW   )rV   r6   role_arn
extra_argsr+   r   r   r/   r2   rW     s    
z(BaseAssumeRoleCredentialFetcher.__init__c                 C   s(   dt t  | _| j| jd< d| _d S )Nzbotocore-session-%sr   T)inttimer   r   r   r_   r/   r/   r2   r     s    z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namec                 C   sZ   t | j}| jr|d= d|kr0t|d |d< tj|dd}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_keysutf-8)
r   r   r   jsonloadsdumpsr   encode	hexdigestr   rV   argsZargument_hashr/   r/   r2   r     s    
z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)rl   rm   rn   rW   r   r   r   r/   r/   r   r2   r     s      r   c                       s6   e Zd Zd
 fdd	Zdd Zdd Zdd	 Z  ZS )AssumeRoleCredentialFetcherNc                    s8   || _ || _| jdkrtj| _t j|||||d dS )a  
        :type client_creator: callable
        :param client_creator: A callable that creates a client taking
            arguments like ``Session.create_client``.

        :type source_credentials: Credentials
        :param source_credentials: The credentials to use to create the
            client for the call to AssumeRole.

        :type role_arn: str
        :param role_arn: The ARN of the role to be assumed.

        :type extra_args: dict
        :param extra_args: Any additional arguments to add to the assume
            role request using the format of the botocore operation.
            Possible keys include, but may not be limited to,
            DurationSeconds, Policy, SerialNumber, ExternalId and
            RoleSessionName.

        :type mfa_prompter: callable
        :param mfa_prompter: A callable that returns input provided by the
            user (i.e raw_input, getpass.getpass, etc.).

        :type cache: dict
        :param cache: An object that supports ``__getitem__``,
            ``__setitem__``, and ``__contains__``.  An example of this is
            the ``JSONFileCache`` class in aws-cli.

        :type expiry_window_seconds: int
        :param expiry_window_seconds: The amount of time, in seconds,
        Nr   r+   r   )_source_credentials_mfa_promptergetpassr   rW   )rV   r6   source_credentialsr   r   mfa_prompterr+   r   r   r/   r2   rW     s    )
z$AssumeRoleCredentialFetcher.__init__c                 C   s   |   }|  }|jf |S )'Get credentials by calling assume role.)_assume_role_kwargs_create_clientr   )rV   r}   r   r/   r/   r2   r   *  s    z,AssumeRoleCredentialFetcher._get_credentialsc                 C   sT   t | j}|d}|dk	r6d| }| |}||d< |d}|dk	rP||d< |S )AGet the arguments for assume role based on current configuration.SerialNumberNzEnter MFA code for %s: Z	TokenCodeDurationSeconds)r   r   r?   r
  )rV   assume_role_kwargs
mfa_serialpromptZ
token_codeduration_secondsr/   r/   r2   r  0  s    



z/AssumeRoleCredentialFetcher._assume_role_kwargsc                 C   s"   | j  }| jd|j|j|jdS )z2Create an STS client using the source credentials.sts)aws_access_key_idaws_secret_access_keyaws_session_token)r	  r   r   r   r    r!   )rV   Zfrozen_credentialsr/   r/   r2   r  B  s    
z*AssumeRoleCredentialFetcher._create_client)NNNN)rl   rm   rn   rW   r   r  r  r   r/   r/   r   r2   r    s       6r  c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	*AssumeRoleWithWebIdentityCredentialFetcherNc                    s    || _ t j|||||d dS )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,
        r  N)_web_identity_token_loaderr   rW   )rV   r6   web_identity_token_loaderr   r   r+   r   r   r/   r2   rW   P  s    $z3AssumeRoleWithWebIdentityCredentialFetcher.__init__c                 C   s,   |   }ttd}| jd|d}|jf |S )r  )signature_versionr  r)   )r  r   r	   r   Zassume_role_with_web_identity)rV   r}   r)   r   r/   r/   r2   r   ~  s    
z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialsc                 C   s   t | j}|  }||d< |S )r  ZWebIdentityToken)r   r   r  )rV   r  Zidentity_tokenr/   r/   r2   r    s    
z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)rl   rm   rn   rW   r   r  r   r/   r/   r   r2   r  M  s      .	r  c                   @   s.   e Zd ZdZdZdddZdd Zdd ZdS )	CredentialProviderNc                 C   s
   || _ d S r-   r0   )rV   r1   r/   r/   r2   rW     s    zCredentialProvider.__init__c                 C   s   dS )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/   r2   load  s    zCredentialProvider.loadc              	   G   sH   g }|D ]:}z| ||  W q tk
r@   t| j|dY qX q|S )Nr   Zcred_var)appendKeyErrorr   METHOD)rV   mappingZ	key_namesfoundZkey_namer/   r/   r2   _extract_creds_from_mapping  s     z.CredentialProvider._extract_creds_from_mapping)N)rl   rm   rn   r&  CANONICAL_NAMErW   r"  r)  r/   r/   r/   r2   r!    s
   
r!  c                   @   s:   e Zd ZdZejfddZdd Zdd Ze	dd	 Z
d
S )r`   zcustom-processc                 C   s   || _ || _d | _|| _d S r-   )_profile_name_load_config_loaded_config_popen)rV   r7   r5   popenr/   r/   r2   rW     s    zProcessProvider.__init__c                    sd   j   d krd S  }|dd k	rDt| fddjS t|d |d |djdS )Nr   c                      s
     S r-   )_retrieve_credentials_usingr/   credential_processrV   r/   r2   r3     r4   z&ProcessProvider.load.<locals>.<lambda>r   r    r!   )r   r    r!   r   )_credential_processr0  r?   r   r   r&  r   )rV   Z
creds_dictr/   r1  r2   r"    s     
zProcessProvider.loadc           	   
   C   s   t |}| j|tjtjd}| \}}|jdkrFt| j|ddt	j
j|d}|dd}|dkrt| jd| d	dz$|d
 |d |d|ddW S  tk
r } zt| jd| dW 5 d }~X Y nX d S )N)stdoutstderrr   r   r   Versionz<Version key not provided>   zUnsupported version 'z8' for credential process provider, supported versions: 1r   r   r   r   r   z"Missing required key in response: )r
   r.  
subprocessPIPEcommunicate
returncoder   r&  decoder   r   r   r  r?   r%  )	rV   r2  Zprocess_listpr4  r5  parsedversioner/   r/   r2   r0    s<      
 
z+ProcessProvider._retrieve_credentials_usingc                 C   s6   | j d kr|  | _ | j di | ji }|dS )Nprofilesr2  )r-  r,  r?   r+  )rV   profile_configr/   r/   r2   r3    s    

 z#ProcessProvider._credential_processN)rl   rm   rn   r&  r8  PopenrW   r"  r0  r   r3  r/   r/   r/   r2   r`     s   #r`   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )rC   ziam-roleZEc2InstanceMetadatac                 C   s
   || _ d S r-   )_role_fetcher)rV   r*   r/   r/   r2   rW     s    z!InstanceMetadataProvider.__init__c                 C   s>   | j }| }|sd S td|d  tj|| j|jd}|S )Nz#Found credentials from IAM Role: %s	role_namer   r   )rD  Zretrieve_iam_role_credentialsrK   infor   r   r&  )rV   fetcherr   r   r/   r/   r2   r"    s     zInstanceMetadataProvider.loadN)rl   rm   rn   r&  r*  rW   r"  r/   r/   r/   r2   rC   	  s   rC   c                   @   sJ   e Zd ZdZdZdZdZddgZdZdd	d
Z	dd Z
dd Zdd ZdS )rA   envEnvironmentZAWS_ACCESS_KEY_IDZAWS_SECRET_ACCESS_KEYZAWS_SECURITY_TOKENZAWS_SESSION_TOKENZAWS_CREDENTIAL_EXPIRATIONNc                 C   s$   |dkrt j}|| _| || _dS )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)r   environ_build_mapping_mapping)rV   rK  r'  r/   r/   r2   rW   0  s    zEnvProvider.__init__c                 C   s   i }|d kr6| j |d< | j|d< | j|d< | j|d< nd|d| j |d< |d| j|d< |d| j|d< t|d ts|d g|d< |d| j|d< |S )Nr   r    r!   r   )
ACCESS_KEY
SECRET_KEYTOKENSEXPIRY_TIMEr?   ru   list)rV   r'  Zvar_mappingr/   r/   r2   rL  @  s,    


   zEnvProvider._build_mappingc                 C   s   | j | jd d}|rtd |  }|dd}|d }|dk	rnt|}t|d |d |d	 ||| jd
S t	|d |d |d	 | jdS dS dS )zK
        Search for credentials in explicit environment variables.
        r    z+Found credentials in environment variables.F)require_expiryr   Nr    r!   )r   r   r   )
rK  r?   rM  rK   rG  _create_credentials_fetcherr   r   r&  r   )rV   r   rH  r   r   r/   r/   r2   r"  X  s.    

	zEnvProvider.loadc                    s(   | j | j| j d fdd	}|S )NTc                    s   i }  d d}|s(td d||d<   d d}|sTtd d||d< d |d< d D ] }  |d}|rl||d<  qqld |d<   d d}|r||d< | r|std d|S )Nr   rS  r#  r    r!   r   )r?   r   )rT  r   r   r    Ztoken_env_varr!   r   rK  r'  r   r/   r2   r   ~  s>       zBEnvProvider._create_credentials_fetcher.<locals>.fetch_credentials)T)rM  r&  rK  )rV   r   r/   rW  r2   rV  y  s
    #z'EnvProvider._create_credentials_fetcher)NN)rl   rm   rn   r&  r*  rN  rO  rP  rQ  rW   rL  r"  rV  r/   r/   r/   r2   rA   &  s   
!rA   c                   @   s2   e Zd ZdZdZdZdZdZdddZd	d
 Z	dS )rH   zec2-credentials-fileZ	Ec2ConfigAWS_CREDENTIAL_FILEZAWSAccessKeyIdZAWSSecretKeyNc                 C   s*   |d krt j}|d krt}|| _|| _d S r-   )r   rK  r   _environ_parser)rV   rK  parserr/   r/   r2   rW     s    zOriginalEC2Provider.__init__c                 C   sh   d| j kr`tj| j d }| |}| j|krdtd || j }|| j }t	||| j
dS ndS dS )zN
        Search for a credential file used by original EC2 CLI tools.
        rX  z)Found credentials in AWS_CREDENTIAL_FILE.rU  N)rY  r   r   
expanduserrZ  rN  rK   rG  rO  r   r&  )rV   	full_pathr   r   r    r/   r/   r2   r"    s    





zOriginalEC2Provider.load)NN)
rl   rm   rn   r&  r*  ZCRED_FILE_ENVrN  rO  rW   r"  r/   r/   r/   r2   rH     s   
rH   c                   @   s>   e Zd ZdZdZdZdZddgZddd	Zd
d Z	dd Z
dS )rc   zshared-credentials-fileZSharedCredentialsr  r  aws_security_tokenr  Nc                 C   s2   || _ |d krd}|| _|d kr(tjj}|| _d S )Nr$   )_creds_filenamer+  r   configloaderraw_config_parse_ini_parser)rV   rb   r7   
ini_parserr/   r/   r2   rW     s    z!SharedCredentialProvider.__init__c                 C   s   z|  | j}W n tk
r&   Y d S X | j|kr|| j }| j|krtd| j | || j| j\}}| 	|}t
|||| jdS d S )Nz0Found credentials in shared credentials file: %srU  )rb  r_  r   r+  rN  rK   rG  r)  rO  _get_session_tokenr   r&  )rV   Zavailable_credsr)   r   r    r!   r/   r/   r2   r"    s.    


  
   zSharedCredentialProvider.loadc                 C   s$   | j D ]}||kr||   S qd S r-   rP  )rV   r)   Ztoken_envvarr/   r/   r2   rd    s    
z+SharedCredentialProvider._get_session_token)NN)rl   rm   rn   r&  r*  rN  rO  rP  rW   r"  rd  r/   r/   r/   r2   rc     s   
	rc   c                   @   sB   e Zd ZdZdZdZdZdZddgZdd	d
Z	dd Z
dd ZdS )rf   z0INI based config provider with profile sections.zconfig-fileZSharedConfigr  r  r^  r  Nc                 C   s&   || _ || _|dkrtjj}|| _dS )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_filenamer+  r   r`  r5   _config_parser)rV   re   r7   Zconfig_parserr/   r/   r2   rW     s
    	zConfigProvider.__init__c                 C   s   z|  | j}W n tk
r&   Y dS X | j|d kr|d | j }| j|krtd| j | || j| j\}}| 	|}t
|||| jdS ndS dS )zr
        If there is are credentials in the configuration associated with
        the session, use those.
        NrA  z$Credentials found in config file: %srU  )rg  rf  r   r+  rN  rK   rG  r)  rO  rd  r   r&  )rV   r.   rB  r   r    r!   r/   r/   r2   r"    s0    
  
   zConfigProvider.loadc                 C   s$   | j D ]}||kr||   S qd S r-   re  )rV   rB  Z
token_namer/   r/   r2   rd  +  s    
z!ConfigProvider._get_session_token)N)rl   rm   rn   ro   r&  r*  rN  rO  rP  rW   r"  rd  r/   r/   r/   r2   rf     s   
rf   c                   @   s:   e Zd ZdZdZdZddgZdZdZdd	d
Z	dd Z
dS )rI   zboto-configZBoto2ConfigZBOTO_CONFIGz/etc/boto.cfgz~/.botor  r  Nc                 C   s.   |d krt j}|d krtjj}|| _|| _d S r-   )r   rK  r   r`  ra  rY  rb  )rV   rK  rc  r/   r/   r2   rW   :  s    zBotoProvider.__init__c              	   C   s   | j | jkr| j| j  g}n| j}|D ]|}z| |}W n tk
rP   Y q&Y nX d|kr&|d }| j|kr&td| | || j| j	\}}t
||| jd  S q&dS )z;
        Look for credentials in boto config file.
        r   z)Found credentials in boto config file: %srU  N)BOTO_CONFIG_ENVrY  DEFAULT_CONFIG_FILENAMESrb  r   rN  rK   rG  r)  rO  r   r&  )rV   Zpotential_locationsr   r)   r   r   r    r/   r/   r2   r"  B  s2    

     zBotoProvider.load)NN)rl   rm   rn   r&  r*  rh  ri  rN  rO  rW   r"  r/   r/   r/   r2   rI   1  s   
rI   c                   @   s   e Zd ZdZdZdZdZdZejddfddZ	dd	 Z
d
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS ) rE   assume-roleNr   web_identity_token_filer"   c                 C   s>   || _ || _|| _|| _|| _i | _|| _|| _| jg| _dS )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+   r,  r   r+  	_prompterr-  _credential_sourcer_profile_provider_builder_visited_profiles)rV   r5   r6   r+   r7   Zprompterr8   r9   r/   r/   r2   rW   m  s    +zAssumeRoleProvider.__init__c                 C   s@   |   | _| jdi }|| ji }| |r<| | jS d S NrA  )r,  r-  r?   r+  _has_assume_role_config_vars_load_creds_via_assume_role)rV   rA  r#   r/   r/   r2   r"    s
    

zAssumeRoleProvider.loadc                 C   s   | j |ko| j|kS r-   )ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARrV   r#   r/   r/   r2   rq    s    
z/AssumeRoleProvider._has_assume_role_config_varsc                 C   s   |  |}| ||}i }|d}|d k	r4||d< |d}|d k	rN||d< |d}|d k	rh||d< |d}|d k	r||d< t| j||d	 || j| jd
}	|	j}
|d k	rt|
}
t	| j
|
tdS )Nrole_session_namer   external_idZ
ExternalIdr  r  r  r  r   )r6   r  r   r   r  r+   )r   r   r   )_get_role_config_resolve_source_credentialsr?   r  r   rl  r+   r   r   r   r&  rt   )rV   r7   role_configr  r   rv  rw  r  r  rH  Z	refresherr/   r/   r2   rr    sD    
 



z.AssumeRoleProvider._load_creds_via_assume_rolec                 C   s   | j di }|| }|d}|d }|d}|d}|d}|d}	|d}
||||	||d	}|
d
k	rzt|
|d< W n tk
r   Y nX |d
k	r|d
k	rtd| dnB|d
kr|d
krt| jddn"|d
k	r| || n| || |S )z?Retrieves and validates the role configuration for the profile.rA  source_profiler   credential_sourcer  rw  rv  r  )r   rw  r  rv  r{  r|  NzDThe profile "%s" contains both source_profile and credential_source.r   z#source_profile or credential_sourcer#  )	r-  r?   r   
ValueErrorr   r   r&  _validate_credential_source_validate_source_profile)rV   r7   rA  r#   r{  r   r|  r  rw  rv  r  rz  r/   r/   r2   rx    sH    





	z#AssumeRoleProvider._get_role_configc                 C   sJ   | j d kr"td| d| dd| j |sFtd| d| ddd S )NzThe credential_source "z" is specified in profile "z)", but no source provider was configured.r}  zThe credential source "z" referenced in profile "z" is not valid.)rm  r   is_supported)rV   Zparent_profiler|  r/   r/   r2   r    s    
z.AssumeRoleProvider._validate_credential_sourcec                 C   s   t | || |gS r-   )any_has_static_credentialsrq  ru  r/   r/   r2   _source_profile_has_credentials+  s
    z2AssumeRoleProvider._source_profile_has_credentialsc                 C   sv   | j di }||kr.td| d| dd|| }|| jkrDd S ||krZt|| jd| |srt|| jdd S )NrA  zThe source_profile "z" referenced in the profile "z" does not exist.r}  )r{  Zvisited_profiles)r-  r?   r   ro  r   r  )rV   Zparent_profile_nameZsource_profile_namerA  r{  r/   r/   r2   r  3  s$    


z+AssumeRoleProvider._validate_source_profilec                    s   ddg}t  fdd|D S )Nr  r  c                 3   s   | ]}| kV  qd S r-   r/   )r   Z
static_keyr#   r/   r2   	<genexpr>[  s     z=AssumeRoleProvider._has_static_credentials.<locals>.<genexpr>)r  )rV   r#   Zstatic_keysr/   r  r2   r  Y  s    z*AssumeRoleProvider._has_static_credentialsc                 C   s<   | d}|d k	r| ||S |d }| j| | |S )Nr|  r{  )r?    _resolve_credentials_from_sourcero  r$  !_resolve_credentials_from_profile)rV   rz  r7   r|  r{  r/   r/   r2   ry  ]  s    
 z.AssumeRoleProvider._resolve_source_credentialsc                 C   s   | j di }|| }| |r0| js0| |S | |sD| |s| jj|dd}t|}| }|d kr~d}t	|| d|S | 
|S )NrA  Tr:   z.The source profile "%s" must have credentials.r}  )r-  r?   r  rn  (_resolve_static_credentials_from_profilerq  r=   rM   rp   r   rr  )rV   r7   rA  r#   rO   Zprofile_chainr   error_messager/   r/   r2   r  h  s4    
z4AssumeRoleProvider._resolve_credentials_from_profilec              
   C   sX   zt |d |d |ddW S  tk
rR } zt| jt|dW 5 d }~X Y nX d S )Nr  r  r  )r   r    r!   r#  )r   r?   r%  r   r&  str)rV   r#   r@  r/   r/   r2   r    s     z;AssumeRoleProvider._resolve_static_credentials_from_profilec                 C   s(   | j |}|d kr$t|d| d|S )NzBNo credentials found in credential_source referenced in profile %sr   )rm  r  r   )rV   r|  r7   r   r/   r/   r2   r    s    z3AssumeRoleProvider._resolve_credentials_from_source)rl   rm   rn   r&  r*  rs  rt  ZEXPIRY_WINDOW_SECONDSr  rW   r"  rq  rr  rx  r  r  r  r  ry  r  r  r  r/   r/   r/   r2   rE   ^  s*   
>,1&!rE   c                   @   sR   e Zd ZdZdZddddZddd	Zd
d Zdd Zdd Z	dd Z
dd ZdS )rg   zassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZAWS_ROLE_ARN)rk  rv  r   Fc                 C   s:   || _ || _|| _|| _d | _|| _|d kr0t}|| _d S r-   )r+   r,  r   r+  _profile_config_disable_env_varsr   _token_loader_cls)rV   r5   r6   r7   r+   r;   Ztoken_loader_clsr/   r/   r2   rW     s    	z*AssumeRoleWithWebIdentityProvider.__init__c                 C   s   |   S r-   )_assume_role_with_web_identityr_   r/   r/   r2   r"    s    z&AssumeRoleWithWebIdentityProvider.loadc                 C   s:   | j d kr.|  }|di }|| ji | _ | j |S rp  )r  r,  r?   r+  )rV   keyloaded_configrA  r/   r/   r2   _get_profile_config  s
    
z5AssumeRoleWithWebIdentityProvider._get_profile_configc                 C   s2   | j r
d S | j|}|r.|tjkr.tj| S d S r-   )r  _CONFIG_TO_ENV_VARr?   r   rK  )rV   r  Zenv_keyr/   r/   r2   _get_env_config  s    
z1AssumeRoleWithWebIdentityProvider._get_env_configc                 C   s    |  |}|d k	r|S | |S r-   )r  r  )rV   r  Z	env_valuer/   r/   r2   _get_config  s    
z-AssumeRoleWithWebIdentityProvider._get_configc                 C   s|   |  d}|sd S | |}|  d}|s8d}t|di }|  d}|d k	rV||d< t| j|||| jd}t| j|jdS )	Nrk  r   zThe 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.r}  rv  r   )r6   r  r   r   r+   rF  )	r  r  r   r  r   r+   r   r&  r   )rV   Z
token_pathtoken_loaderr   r   r   rv  rH  r/   r/   r2   r    s0    





z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN)rl   rm   rn   r&  r*  r  rW   r"  r  r  r  r  r/   r/   r/   r2   rg     s      
rg   c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )rG   c                 C   s
   || _ d S r-   
_providersrV   r=   r/   r/   r2   rW      s    z'CanonicalNameCredentialSourcer.__init__c                 C   s   |dd | j D kS )aL  Validates 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.
        c                 S   s   g | ]
}|j qS r/   )r*  r   r=  r/   r/   r2   r     s     z?CanonicalNameCredentialSourcer.is_supported.<locals>.<listcomp>r  )rV   source_namer/   r/   r2   r    s    z+CanonicalNameCredentialSourcer.is_supportedc                 C   s$   |  |}t|tr| S | S )a  Loads 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_providerru   rM   rp   r"  )rV   r  sourcer/   r/   r2   r    s    	

z1CanonicalNameCredentialSourcer.source_credentialsc                 C   sV   |  |}| dkr@| d}|dk	r@|dkr4|S t||gS |dkrRt|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sharedconfigZsharedcredentialsrj  Nname)_get_provider_by_canonical_namelower_get_provider_by_methodrM   r   )rV   canonical_namer   rN   r/   r/   r2   r    s    



z,CanonicalNameCredentialSourcer._get_providerc                 C   s2   | j D ]&}|j}|r| | kr|  S qdS )zReturn a credential provider by its canonical name.

        This function is strict, it does not attempt to address
        compatibility issues.
        N)r  r*  r  )rV   r  r   r  r/   r/   r2   r  D  s    
z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namec                 C   s"   | j D ]}|j|kr|  S qdS )z0Return a credential provider by its METHOD name.N)r  r&  )rV   r   r   r/   r/   r2   r  P  s    

z6CanonicalNameCredentialSourcer._get_provider_by_methodN)	rl   rm   rn   rW   r  r  r  r  r  r/   r/   r/   r2   rG     s   &rG   c                   @   sR   e Zd ZdZdZdZdZdZdddZd	d
 Z	dd Z
dd Zdd Zdd ZdS )rB   zcontainer-roleZEcsContainerZ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIZ"AWS_CONTAINER_CREDENTIALS_FULL_URIZ!AWS_CONTAINER_AUTHORIZATION_TOKENNc                 C   s,   |d krt j}|d krt }|| _|| _d S r-   )r   rK  r   rY  _fetcher)rV   rK  rH  r/   r/   r2   rW   ^  s    zContainerProvider.__init__c                 C   s$   | j | jks| j| jkr |  S d S r-   )ENV_VARrY  ENV_VAR_FULL_retrieve_or_failr_   r/   r/   r2   r"  f  s    zContainerProvider.loadc                 C   sn   |   r| j| j| j }n| j| j }|  }| ||}| }t|d |d |d | j	t
|d |dS )Nr   r    r!   r   )r   r    r!   r   r   r   )_provided_relative_urir  full_urlrY  r  r  _build_headers_create_fetcherr   r&  rw   )rV   full_uriheadersrH  r   r/   r/   r2   r  l  s    
z#ContainerProvider._retrieve_or_failc                 C   s"   | j | j}|d k	rd|iS d S )NAuthorization)rY  r?   ENV_VAR_AUTH_TOKEN)rV   Z
auth_tokenr/   r/   r2   r  }  s    z ContainerProvider._build_headersc                    s    fdd}|S )Nc               
      sx   zj j d} W nD tk
rX } z&tjd|dd tjt|dW 5 d }~X Y nX | d | d | d | d	 d
S )N)r  z'Error retrieving container metadata: %sTr   r   r   r   Tokenr   r   )r  Zretrieve_full_urir   rK   rL   r   r&  r  )r   r@  r  r  rV   r/   r2   fetch_creds  s(     
   z6ContainerProvider._create_fetcher.<locals>.fetch_credsr/   )rV   r  r  r  r/   r  r2   r    s    z!ContainerProvider._create_fetcherc                 C   s   | j | jkS r-   )r  rY  r_   r/   r/   r2   r    s    z(ContainerProvider._provided_relative_uri)NN)rl   rm   rn   r&  r*  r  r  r  rW   r"  r  r  r  r  r/   r/   r/   r2   rB   W  s   
rB   c                   @   sD   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dS )rM   c                 C   s
   || _ dS )zQ

        :param providers: A list of ``CredentialProvider`` instances.

        Nr<   r  r/   r/   r2   rW     s    zCredentialResolver.__init__c                 C   sL   zdd | j D |}W n tk
r8   t|dY nX | j || dS )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``
        c                 S   s   g | ]
}|j qS r/   r&  r  r/   r/   r2   r     s     z4CredentialResolver.insert_before.<locals>.<listcomp>r  N)r=   indexr~  r   insertrV   r  Zcredential_provideroffsetr/   r/   r2   insert_before  s
    z CredentialResolver.insert_beforec                 C   s    |  |}| j|d | dS )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``
        r7  N)_get_provider_offsetr=   r  r  r/   r/   r2   insert_after  s    
zCredentialResolver.insert_afterc                 C   s6   dd | j D }||krdS ||}| j | dS )z
        Removes a given ``Credentials`` instance from the chain.

        :param name: The short name of the credentials instance to remove.
        :type name: string
        c                 S   s   g | ]
}|j qS r/   r  r  r/   r/   r2   r     s     z-CredentialResolver.remove.<locals>.<listcomp>N)r=   r  pop)rV   r  Zavailable_methodsr  r/   r/   r2   rJ     s
    
zCredentialResolver.removec                 C   s   | 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=   r  rV   r  r/   r/   r2   get_provider  s    
zCredentialResolver.get_providerc                 C   s<   zdd | j D |W S  tk
r6   t|dY nX d S )Nc                 S   s   g | ]
}|j qS r/   r  r  r/   r/   r2   r     s     z;CredentialResolver._get_provider_offset.<locals>.<listcomp>r  )r=   r  r~  r   r  r/   r/   r2   r    s    z'CredentialResolver._get_provider_offsetc                 C   s6   | j D ]*}td|j | }|dk	r|  S qdS )zw
        Goes through the credentials chain, returning the first ``Credentials``
        that could be loaded.
        zLooking for credentials via: %sN)r=   rK   rL   r&  r"  )rV   r   r   r/   r/   r2   rp     s    

z#CredentialResolver.load_credentialsN)
rl   rm   rn   rW   r  r  rJ   r  r  rp   r/   r/   r/   r2   rM     s   rM   c                       s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc                    sB   || _ || _|| _|| _|| _|| _|	| _|
| _t 	|| d S r-   )
r   _sso_region
_role_name_account_id
_start_url_token_loader_token_provider_sso_session_namer   rW   )rV   	start_url
sso_regionrE  
account_idr6   r  r+   r   ri   sso_session_namer   r/   r2   rW     s    zSSOCredentialFetcher.__init__c                 C   sV   | j | jd}| jr | j|d< n
| j|d< tj|ddd}t|d }| 	|S )r   )roleName	accountIdZsessionNameZstartUrlT),r   )r   
separatorsr   )
r  r  r  r  r   r  r   r  r  r   r  r/   r/   r2   r     s    
z&SSOCredentialFetcher._create_cache_keyc                 C   s$   |d }t j |t }|| jS )Ng     @@)rr   fromtimestampr   ry   _UTC_DATE_FORMAT)rV   Ztimestamp_msZtimestamp_seconds	timestampr/   r/   r2   _parse_timestamp0  s    z%SSOCredentialFetcher._parse_timestampc                 C   s   t t| jd}| jd|d}| jr8| j }| j}n| | j	d }| j
| j|d}z|jf |}W n |jjk
r   t Y nX |d }d|d |d |d	 | |d
 dd}|S )z4Get credentials by calling SSO get role credentials.)r  r,   ssor   accessToken)r  r  r  ZroleCredentialsZaccessKeyIdZsecretAccessKeyZsessionTokenr   )r   r   r   r   )ZProviderTyper   )r   r	   r  r   r  Z
load_tokenZget_frozen_tokenr!   r  r  r  r  Zget_role_credentials
exceptionsZUnauthorizedExceptionr   r  )rV   r)   r   Zinitial_token_datar!   r}   r   r   r/   r/   r2   r   6  s4    
	z%SSOCredentialFetcher._get_credentials)NNNNN)	rl   rm   rn   r  rW   r   r  r   r   r/   r/   r   r2   r     s   	     r  c                   @   s\   e Zd ZdZejejddddZdZ	dZ
e	e
 Zddd	Zd
d Zdd Zdd ZdS )rj   r  ~z.awsr+   )sso_role_namesso_account_id)sso_start_urlr  Nc                 C   sF   |d krt | j}|| _|| _|d kr*i }|| _|| _|| _|| _d S r-   )r   _SSO_TOKEN_CACHE_DIR_token_cacher  r+   r,  r   r+  )rV   r5   r6   r7   r+   rh   ri   r/   r/   r2   rW   l  s    	
zSSOProvider.__init__c                    s   |   }|di }| j}|| ji  |di }t fdd| jD rPd S |  |\}}i }g }| j| }	|	D ]$}
|
|kr||
 ||
< qv||
 qv|rd|}t	d||f d|S )NrA  sso_sessionsc                 3   s   | ]}| kV  qd S r-   r/   )r   crB  r/   r2   r    s    z/SSOProvider._load_sso_config.<locals>.<genexpr>r   zSThe profile "%s" is configured to use SSO but is missing required configuration: %sr}  )
r,  r?   r+  all_PROFILE_REQUIRED_CONFIG_VARS_resolve_sso_session_reference_ALL_REQUIRED_CONFIG_VARSr$  r   r   )rV   r  rA  r7   r  Zresolved_configZ
extra_reqsr)   Zmissing_config_varsZall_required_configs
config_varmissingr/   r  r2   _load_sso_config  s8     

zSSOProvider._load_sso_configc           	      C   s   | d}|d kr|dfS ||kr8d| d}t|d| }|| }| D ]F\}}| |||krd| d||  d| d	}t|d|||< qP|d
fS )Nsso_sessionr/   z+The specified sso-session does not exist: ""r}  zThe value for z" is inconsistent between profile (z) and sso-session (z).)r  )r?   r   copyitems)	rV   rB  r  r  r   r)   r1   r  valr/   r/   r2   r    s    



z*SSOProvider._resolve_sso_session_referencec                 C   sx   |   }|sd S |d |d |d |d | jt| jd| jd}d|kr^|d |d< | j|d	< tf |}t| j|j	d
S )Nr  r  r  r  )r+   )r  r  rE  r  r6   r  r+   r  r  ri   rF  )
r  r   r   r  r+   r  r  r   r&  r   )rV   Z
sso_configZfetcher_kwargsZsso_fetcherr/   r/   r2   r"    s&    
	

zSSOProvider.load)NNN)rl   rm   rn   r&  r   r   r\  r   r  r  Z_SSO_REQUIRED_CONFIG_VARSr  rW   r  r  r"  r/   r/   r/   r2   rj   Z  s   	   
$rj   )NN)F)Trr   r  r   loggingr   r8  r   r   collectionsr   r  r   hashlibr   Zdateutil.parserr   Zdateutil.tzr   r   Zbotocore.compatr   Zbotocore.configloaderr	   r
   r   Zbotocore.configr   Zbotocore.exceptionsr   r   r   r   r   r   r   r   r   Zbotocore.tokensr   Zbotocore.utilsr   r   r   r   r   r   r   	getLoggerrl   rK   r   r   r@   rQ   rD   rq   rt   rw   r{   rF   r   r   r   r   r   r   r   r  r  r!  r`   rC   rA   rH   rc   rf   rI   rE   rg   rG   rB   rM   r  rj   r/   r/   r/   r2   <module>   s   ,$

 
]I
	&  E5Z
C.K~#.<-  JYXEdZ