U
    ³.¬b7C ã                   @   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 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(m)Z)m*Z*m+Z+m,Z,m-Z- e .e/¡Z0e	ddddgƒZ1dZ2dZ3dTdd„Z4G dd„ dƒZ5dd„ Z6dd„ Z7dd„ Z8dUdd„Z9d d!„ Z:d"d#„ Z;d$d%„ Z<G d&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 d0d1„ d1eAƒZBG d2d3„ d3eBƒZCG d4d5„ d5eBƒZDG d6d7„ d7ƒZEG d8d9„ d9eEƒZFG d:d;„ d;eEƒZGG d<d=„ d=eEƒZHG d>d?„ d?eEƒZIG d@dA„ dAeEƒZJG dBdC„ dCeEƒZKG dDdE„ dEeEƒZLG dFdG„ dGeEƒZMG dHdI„ dIeEƒZNG dJdK„ dKƒZOG dLdM„ dMeEƒZPG dNdO„ dOƒZQG dPdQ„ dQeAƒZRG dRdS„ dSeEƒZSdS )Vé    N)Ú
namedtuple)Údeepcopy)Úsha1)ÚPath©Úparse)ÚtzlocalÚtzutc)ÚUNSIGNED)Úcompat_shell_splitÚtotal_seconds)ÚConfig)	ÚConfigNotFoundÚCredentialRetrievalErrorÚInfiniteLoopConfigErrorÚInvalidConfigErrorÚMetadataRetrievalErrorÚPartialCredentialsErrorÚRefreshWithMFAUnsupportedErrorÚUnauthorizedSSOTokenErrorÚUnknownCredentialError)ÚContainerMetadataFetcherÚFileWebIdentityTokenLoaderÚInstanceMetadataFetcherÚ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 )z¢Create 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-7df6wvge/botocore/credentials.pyÚ<lambda>i   ó    z,create_credential_resolver.<locals>.<lambda>)Úload_configÚclient_creatorr*   Úprofile_nameÚcredential_sourcerÚprofile_provider_builder©r6   Ú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)r0   r*   r+   r6   Zmetadata_timeoutr&   r:   Zimds_configZenv_providerZcontainer_providerZinstance_metadata_providerr8   Úassume_role_providerZpre_profileÚprofile_providersZpost_profiler<   Úresolverr.   r/   r1   Úcreate_credential_resolver@   sv    

ÿÿù
üÿ	  ÿ
ÿøþþü
ÿ
rP   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 )rC   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)Úselfr0   r*   r+   Zsso_token_cacher.   r.   r1   Ú__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©rU   r6   r:   r.   r.   r1   r<   °   s    þøz ProfileProviderBuilder.providersc                    s   t |‡ fdd„d�S )Nc                      s   ˆ j jS r,   ©rQ   r-   r.   ©rU   r.   r1   r2   ¿   r3   zAProfileProviderBuilder._create_process_provider.<locals>.<lambda>)r6   r4   )ÚProcessProvider©rU   r6   r.   r^   r1   rZ   ¼   s    
þz/ProfileProviderBuilder._create_process_providerc                 C   s   | j  d¡}t||d�S )NZcredentials_file)r6   Úcreds_filename)rQ   r=   ÚSharedCredentialProvider)rU   r6   Zcredential_filer.   r.   r1   rY   Â   s
    þz9ProfileProviderBuilder._create_shared_credential_providerc                 C   s   | j  d¡}t||d�S )NÚconfig_file)r6   Úconfig_filename)rQ   r=   ÚConfigProvider)rU   r6   rc   r.   r.   r1   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.   r1   r2   Ò   r3   zFProfileProviderBuilder._create_web_identity_provider.<locals>.<lambda>)r4   r5   r*   r6   r:   )Ú!AssumeRoleWithWebIdentityProviderrE   rQ   rS   rR   r\   r.   r^   r1   rW   Ð   s    
 ÿùz4ProfileProviderBuilder._create_web_identity_providerc                    s"   t ‡ fdd„ˆ jj|ˆ jˆ jd�S )Nc                      s   ˆ j jS r,   r]   r.   r^   r.   r1   r2   Ý   r3   z=ProfileProviderBuilder._create_sso_provider.<locals>.<lambda>)r4   r5   r6   r*   Útoken_cache)ÚSSOProviderrQ   Úcreate_clientrR   rT   r`   r.   r^   r1   rX   Û   s    
ûz+ProfileProviderBuilder._create_sso_provider)NNN)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rV   r<   rZ   rY   r[   rW   rX   r.   r.   r.   r1   rC   �   s        ÿ

rC   c                 C   s   t | ƒ}| ¡ S r,   )rP   Úload_credentials)r0   rO   r.   r.   r1   Úget_credentialså   s    ro   c                   C   s   t j  tƒ ¡S r,   )ÚdatetimeÚnowr   r.   r.   r.   r1   Ú
_local_nowê   s    rr   c                 C   s   t | tjƒr| S t| ƒS r,   )Ú
isinstancerp   r   )Úvaluer.   r.   r1   Ú_parse_if_neededî   s    ru   Fc                 C   s&   t | tjƒr"|r|  ¡ S |  d¡S | S )Nz%Y-%m-%dT%H:%M:%S%Z)rs   rp   Ú	isoformatÚstrftime)rt   Úisor.   r.   r1   Ú_serialize_if_neededô   s
    
ry   c                    s   ‡ ‡fdd„}|S )Nc                    s"   dˆ i}|j f |Ž ˆj| f|ŽS )Nr+   )Úupdateri   )Zservice_nameÚkwargsZcreate_client_kwargs©r+   r0   r.   r1   r5   ý   s    z+_get_client_creator.<locals>.client_creatorr.   )r0   r+   r5   r.   r|   r1   rE   ü   s    rE   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_rolery   )ÚresponseÚcredentials©ÚclientÚparamsr.   r1   Úrefresh  s    
üz-create_assume_role_refresher.<locals>.refreshr.   )rˆ   r‰   rŠ   r.   r‡   r1   Ú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)rU   rŠ   r.   r.   r1   rV     s    z8create_mfa_serial_refresher.<locals>._Refresher.__init__c                 S   s   | j rtƒ ‚d| _ |  ¡ S ©NT)r�   r   rŒ   r^   r.   r.   r1   Ú__call__  s    z8create_mfa_serial_refresher.<locals>._Refresher.__call__N)rj   rk   rl   rV   r�   r.   r.   r.   r1   Ú
_Refresher  s   r�   r.   )Zactual_refreshr�   r.   r.   r1   Úcreate_mfa_serial_refresher  s    r‘   c                   @   sh   e Zd ZdZej ej dddd¡¡Zedfdd„Z	d	d
„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚJSONFileCachezÙJSON 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.
    ú~ú.awsZbotor*   Nc                 C   s   || _ |d kr| j}|| _d S r,   )Ú_working_dirÚ_default_dumpsÚ_dumps)rU   Zworking_dirZ
dumps_funcr.   r.   r1   rV   1  s    zJSONFileCache.__init__c                 C   s   t j|td�S )N)r#   )ÚjsonÚdumpsry   )rU   Úobjr.   r.   r1   r–   7  s    zJSONFileCache._default_dumpsc                 C   s   |   |¡}tj |¡S r,   )Ú_convert_cache_keyÚosÚpathÚisfile)rU   Ú	cache_keyÚ
actual_keyr.   r.   r1   Ú__contains__:  s    
zJSONFileCache.__contains__c              
   C   s\   |   |¡}z,t|ƒ�}t |¡W  5 Q R £ W S Q R X W n  ttfk
rV   t|ƒ‚Y nX dS )z Retrieve value from a cache key.N)r›   Úopenr˜   ÚloadÚOSErrorÚ
ValueErrorÚKeyError)rU   rŸ   r    Úfr.   r.   r1   Ú__getitem__>  s    

"zJSONFileCache.__getitem__c                 C   s@   |   |¡}zt|ƒ}| ¡  W n tk
r:   t|ƒ‚Y nX d S r,   )r›   r   ÚunlinkÚFileNotFoundErrorr¦   )rU   rŸ   r    Zkey_pathr.   r.   r1   Ú__delitem__G  s    
zJSONFileCache.__delitem__c              	   C   sš   |   |¡}z|  |¡}W n& ttfk
r>   td|› �ƒ‚Y nX tj | j¡sZt | j¡ t 	t 
|tjtjB d¡d¡�}| ¡  | |¡ W 5 Q R X d S )Nz3Value cannot be cached, must be JSON serializable: i€  Úw)r›   r—   Ú	TypeErrorr¥   rœ   r�   Úisdirr•   ÚmakedirsÚfdopenr¢   ÚO_WRONLYÚO_CREATÚtruncateÚwrite)rU   rŸ   rt   Zfull_keyZfile_contentr§   r.   r.   r1   Ú__setitem__O  s     
ÿ
 ÿzJSONFileCache.__setitem__c                 C   s   t j | j|d ¡}|S )Nz.json)rœ   r�   Újoinr•   )rU   rŸ   Ú	full_pathr.   r.   r1   r›   `  s    z JSONFileCache._convert_cache_key)rj   rk   rl   rm   rœ   r�   Ú
expanduserr¶   Z	CACHE_DIRrV   r–   r¡   r¨   r«   rµ   r›   r.   r.   r.   r1   r’   '  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)rU   r   r   r    rº   r.   r.   r1   rV   p  s    zCredentials.__init__c                 C   s$   t j | j¡| _t j | j¡| _d S r,   )ÚbotocoreÚcompatÚensure_unicoder   r   r^   r.   r.   r1   r»   {  s    zCredentials._normalizec                 C   s   t | j| j| jƒS r,   )r   r   r   r    r^   r.   r.   r1   Úget_frozen_credentials…  s
      ÿz"Credentials.get_frozen_credentials)NN)rj   rk   rl   rm   rV   r»   r¿   r.   r.   r.   r1   r}   e  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»   )rU   r   r   r    rƒ   Úrefresh_usingrº   Útime_fetcherr.   r.   r1   rV      s    

  ÿzRefreshableCredentials.__init__c                 C   s$   t j | j¡| _t j | j¡| _d S r,   )r¼   r½   r¾   rÂ   rÃ   r^   r.   r.   r1   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.   r1   Úcreate_from_metadata»  s    úz+RefreshableCredentials.create_from_metadatac                 C   s   |   ¡  | jS ©zÄWarning: 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.   r1   r   Ç  s    z!RefreshableCredentials.access_keyc                 C   s
   || _ d S r,   )rÂ   ©rU   rt   r.   r.   r1   r   Ð  s    c                 C   s   |   ¡  | jS rÒ   )rŒ   rÃ   r^   r.   r.   r1   r   Ô  s    z!RefreshableCredentials.secret_keyc                 C   s
   || _ d S r,   )rÃ   rÓ   r.   r.   r1   r   Ý  s    c                 C   s   |   ¡  | jS rÒ   )rŒ   rÄ   r^   r.   r.   r1   r    á  s    zRefreshableCredentials.tokenc                 C   s
   || _ d S r,   )rÄ   rÓ   r.   r.   r1   r    ê  s    c                 C   s   | j |  ¡  }t|ƒS r,   )rÅ   rÆ   r   )rU   Údeltar.   r.   r1   Ú_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Õ   rJ   rK   ©rU   Ú
refresh_inr.   r.   r1   Úrefresh_neededò  s    

z%RefreshableCredentials.refresh_neededc                 C   s   | j dd�S )Nr   )rØ   )rÙ   r^   r.   r.   r1   Ú_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¡sŽW 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)rU   Zis_mandatory_refreshr.   r.   r1   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ƒ| _	|  
¡ r‚d}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Á   Ú	ExceptionrJ   ÚwarningÚ_set_from_datar   rÂ   rÃ   rÄ   rÊ   rÚ   ÚRuntimeError)rU   rÛ   rÏ   Zperiod_nameÚmsgr.   r.   r1   rß   6  s.    ü
  ÿÿ
z)RefreshableCredentials._protected_refreshc                 C   s   t | ƒS r,   r   )Ztime_strr.   r.   r1   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.   r1   Ú
<listcomp>f  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º   r¶   r   r   r    r   rÅ   rJ   rK   r»   )rU   rë   Zexpected_keysZmissing_keysÚmessager.   rê   r1   rå   a  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.   r1   r¿   x  s    "z-RefreshableCredentials.get_frozen_credentials)N)rj   rk   rl   rm   r?   rÖ   Ú"_DEFAULT_MANDATORY_REFRESH_TIMEOUTrÞ   rr   rV   r»   ÚclassmethodrÑ   Úpropertyr   Úsetterr   r    rÕ   rÙ   rÚ   rŒ   rß   ÚstaticmethodrÍ   rå   r¿   r.   r.   r.   r1   rÀ   ‹  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Ê   )rU   rË   rº   rÌ   r.   r.   r1   rV   ¤  s    
z'DeferredRefreshableCredentials.__init__Nc                    s   | j d krdS tƒ  |¡S rŽ   )rÊ   ÚsuperrÙ   r×   ©Ú	__class__r.   r1   rÙ   ¯  s    
z-DeferredRefreshableCredentials.refresh_needed)N)rj   rk   rl   rm   rr   rV   rÙ   Ú__classcell__r.   r.   rù   r1   r÷   ž  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,   )rR   Ú_create_cache_keyÚ
_cache_keyÚDEFAULT_EXPIRY_WINDOW_SECONDSÚ_expiry_window_seconds)rU   r*   Úexpiry_window_secondsr.   r.   r1   rV   ¸  s    
z CachedCredentialFetcher.__init__c                 C   s   t dƒ‚d S )Nz_create_cache_key()©ÚNotImplementedErrorr^   r.   r.   r1   rý   Á  s    z)CachedCredentialFetcher._create_cache_keyc                 C   s$   |  dd¡  tjjd¡}|  dd¡S )Nú:Ú_ú/)Úreplacerœ   r�   Úsep)rU   Úfilenamer.   r.   r1   Ú_make_file_safeÄ  s    z'CachedCredentialFetcher._make_file_safec                 C   s   t dƒ‚d S )Nz_get_credentials()r  r^   r.   r.   r1   Ú_get_credentialsÉ  s    z(CachedCredentialFetcher._get_credentialsc                 C   s   |   ¡ S r,   )Ú_get_cached_credentialsr^   r.   r.   r1   Ú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 )z–Get 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)rx   r~   r   r€   r‚   )Ú_load_from_cacher  Ú_write_to_cacherJ   rK   ry   )rU   r…   ÚcredsÚ
expirationr.   r.   r1   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þ   rR   r   rÚ   rJ   rK   )rU   r  r.   r.   r1   r  å  s    
ÿz(CachedCredentialFetcher._load_from_cachec                 C   s   t |ƒ| j| j< d S r,   )r   rR   rþ   )rU   r…   r.   r.   r1   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�   )ru   r   rr   r   )rU   r†   Zend_timeÚsecondsr.   r.   r1   rÚ   ó  s    z#CachedCredentialFetcher._is_expired)NN)rj   rk   rl   rÿ   rV   rý   r
  r  r  r  r  r  rÚ   r.   r.   r.   r1   rü   µ  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ø   rV   )rU   r5   Úrole_arnÚ
extra_argsr*   r  rù   r.   r1   rV   û  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.   r1   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  r˜   Úloadsr™   r   ÚencodeÚ	hexdigestr
  ©rU   ÚargsZargument_hashr.   r.   r1   rý     s    
z1BaseAssumeRoleCredentialFetcher._create_cache_key)NNN)rj   rk   rl   rV   r  rý   rû   r.   r.   rù   r1   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ø   rV   )rU   r5   Úsource_credentialsr  r  Úmfa_prompterr*   r  rù   r.   r1   rV   0  s    )
ûz$AssumeRoleCredentialFetcher.__init__c                 C   s   |   ¡ }|  ¡ }|jf |ŽS )ú'Get credentials by calling assume role.)Ú_assume_role_kwargsÚ_create_clientr„   )rU   r{   rˆ   r.   r.   r1   r  f  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*  )rU   Úassume_role_kwargsÚ
mfa_serialÚpromptZ
token_codeÚduration_secondsr.   r.   r1   r/  l  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    )rU   Zfrozen_credentialsr.   r.   r1   r0  ~  s    
üz*AssumeRoleCredentialFetcher._create_client)NNNN)rj   rk   rl   rV   r  r/  r0  rû   r.   r.   rù   r1   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ø   rV   )rU   r5   Úweb_identity_token_loaderr  r  r*   r  rù   r.   r1   rV   Œ  s    $ûz3AssumeRoleWithWebIdentityCredentialFetcher.__init__c                 C   s,   |   ¡ }ttd�}| jd|d�}|jf |ŽS )r.  )Úsignature_versionr8  ©r(   )r/  r   r
   r  Zassume_role_with_web_identity)rU   r{   r(   rˆ   r.   r.   r1   r  º  s    
z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialsc                 C   s   t | jƒ}|  ¡ }||d< |S )r1  ZWebIdentityToken)r   r  r=  )rU   r4  Zidentity_tokenr.   r.   r1   r/  Ã  s    
z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargs)NNN)rj   rk   rl   rV   r  r/  rû   r.   r.   rù   r1   r<  ‰  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,   r/   )rU   r0   r.   r.   r1   rV   Ø  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.   r1   r£   Û  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)Úappendr¦   r   ÚMETHOD)rU   ÚmappingZ	key_namesÚfoundZkey_namer.   r.   r1   Ú_extract_creds_from_mappingî  s     ÿz.CredentialProvider._extract_creds_from_mapping)N)rj   rk   rl   rD  ÚCANONICAL_NAMErV   r£   rG  r.   r.   r.   r1   rA  Ì  s
   
rA  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)rU   r6   r4   Úpopenr.   r.   r1   rV   þ  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_processrU   r.   r1   r2     r3   z&ProcessProvider.load.<locals>.<lambda>r   r   r    )r   r   r    rº   )Ú_credential_processrN  r>   rÀ   rÑ   rD  r}   )rU   Z
creds_dictr.   rO  r1   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r„t| 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   rL  Ú
subprocessÚPIPEÚcommunicateÚ
returncoder   rD  Údecoder¼   r½   r˜   r"  r>   r¦   )	rU   rP  Zprocess_listÚprR  rS  ÚparsedÚversionÚer.   r.   r1   rN    s<      ÿ
 ÿ
ýüþz+ProcessProvider._retrieve_credentials_usingc                 C   s6   | j d kr|  ¡ | _ | j  di ¡ | ji ¡}| d¡S )NÚprofilesrP  )rK  rJ  r>   rI  )rU   Úprofile_configr.   r.   r1   rQ  ;  s    

 ÿz#ProcessProvider._credential_processN)rj   rk   rl   rD  rV  ÚPopenrV   r£   rN  rô   rQ  r.   r.   r.   r1   r_   ú  s   #r_   c                   @   s$   e Zd ZdZdZdd„ Zdd„ ZdS )rB   ziam-roleZEc2InstanceMetadatac                 C   s
   || _ d S r,   )Ú_role_fetcher)rU   r)   r.   r.   r1   rV   I  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Ë   )rb  Zretrieve_iam_role_credentialsrJ   rK   rÀ   rÑ   rD  )rU   ÚfetcherrÏ   r  r.   r.   r1   r£   L  s     ÿýzInstanceMetadataProvider.loadN)rj   rk   rl   rD  rH  rV   r£   r.   r.   r.   r1   rB   E  s   rB   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 )r@   Ú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)rU   rh  rE  r.   r.   r1   rV   l  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>   rs   Úlist)rU   rE  Zvar_mappingr.   r.   r1   ri  |  s,    


 ÿ ÿ ÿzEnvProvider._build_mappingc                 C   s”   | j  | jd d¡}|rŒt 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º   )
rh  r>   rj  rJ   ÚinfoÚ_create_credentials_fetcherr   rÀ   rD  r}   )rU   r   re  r†   rƒ   r.   r.   r1   r£   ”  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<  qŽqld |d< ˆ   ˆd d¡}|r²||d< | rÊ|sÊtˆˆd d�‚|S )Nr   rp  rB  r   r    rƒ   )r>   r   )rq  r†   r   r   Ztoken_env_varr    rƒ   ©rh  rE  rº   r.   r1   r  º  s>     ÿ ÿ ÿzBEnvProvider._create_credentials_fetcher.<locals>.fetch_credentials)T)rj  rD  rh  )rU   r  r.   ru  r1   rt  µ  s
    #z'EnvProvider._create_credentials_fetcher)NN)rj   rk   rl   rD  rH  rk  rl  rm  rn  rV   ri  r£   rt  r.   r.   r.   r1   r@   b  s   
!r@   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 )rG   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œ   rh  r   Ú_environÚ_parser)rU   rh  Úparserr.   r.   r1   rV   è  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.
        rv  z)Found credentials in AWS_CREDENTIAL_FILE.rr  N)rw  rœ   r�   r¸   rx  rk  rJ   rs  rl  r}   rD  )rU   r·   r  r   r   r.   r.   r1   r£   ð  s    
ÿ




zOriginalEC2Provider.load)NN)
rj   rk   rl   rD  rH  ZCRED_FILE_ENVrk  rl  rV   r£   r.   r.   r.   r1   rG   à  s   
rG   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 )rb   zshared-credentials-fileZSharedCredentialsr9  r:  Úaws_security_tokenr;  Nc                 C   s2   || _ |d krd}|| _|d kr(tjj}|| _d S )Nr#   )Ú_creds_filenamerI  r¼   ÚconfigloaderÚraw_config_parseÚ_ini_parser)rU   ra   r6   Ú
ini_parserr.   r.   r1   rV     s    z!SharedCredentialProvider.__init__c                 C   sŠ   z|   | j¡}W n tk
r&   Y d S X | j|kr†|| j }| j|kr†t d| j¡ |  || j| j¡\}}|  	|¡}t
|||| jd�S d S )Nz0Found credentials in shared credentials file: %srr  )r~  r{  r   rI  rk  rJ   rs  rG  rl  Ú_get_session_tokenr}   rD  )rU   Zavailable_credsr(   r   r   r    r.   r.   r1   r£     s.    


þ  ÿ
   ÿzSharedCredentialProvider.loadc                 C   s$   | j D ]}||kr||   S qd S r,   ©rm  )rU   r(   Ztoken_envvarr.   r.   r1   r€  +  s    
z+SharedCredentialProvider._get_session_token)NN)rj   rk   rl   rD  rH  rk  rl  rm  rV   r£   r€  r.   r.   r.   r1   rb     s   
	rb   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 )re   z0INI based config provider with profile sections.zconfig-fileZSharedConfigr9  r:  rz  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_filenamerI  r¼   r|  r4   Ú_config_parser)rU   rd   r6   Zconfig_parserr.   r.   r1   rV   >  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r”t 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.
        Nr_  z$Credentials found in config file: %srr  )rƒ  r‚  r   rI  rk  rJ   rs  rG  rl  r€  r}   rD  )rU   r-   r`  r   r   r    r.   r.   r1   r£   M  s0    
þ  ÿ
   ÿzConfigProvider.loadc                 C   s$   | j D ]}||kr||   S qd S r,   r�  )rU   r`  Z
token_namer.   r.   r1   r€  g  s    
z!ConfigProvider._get_session_token)N)rj   rk   rl   rm   rD  rH  rk  rl  rm  rV   r£   r€  r.   r.   r.   r1   re   1  s   
re   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 )rH   zboto-configZBoto2ConfigZBOTO_CONFIGz/etc/boto.cfgz~/.botor9  r:  Nc                 C   s.   |d krt j}|d krtjj}|| _|| _d S r,   )rœ   rh  r¼   r|  r}  rw  r~  )rU   rh  r  r.   r.   r1   rV   v  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: %srr  N)ÚBOTO_CONFIG_ENVrw  ÚDEFAULT_CONFIG_FILENAMESr~  r   rk  rJ   rs  rG  rl  r}   rD  )rU   Zpotential_locationsr	  r(   r†   r   r   r.   r.   r1   r£   ~  s2    

 ÿ  ÿ  ÿzBotoProvider.load)NN)rj   rk   rl   rD  rH  r„  r…  rk  rl  rV   r£   r.   r.   r.   r1   rH   m  s   
rH   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 ) rD   ú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*   rJ  r  rI  Ú	_prompterrK  Ú_credential_sourcerÚ_profile_provider_builderÚ_visited_profiles)rU   r4   r5   r*   r6   Zprompterr7   r8   r.   r.   r1   rV   ©  s    +zAssumeRoleProvider.__init__c                 C   s@   |   ¡ | _| j di ¡}| | ji ¡}|  |¡r<|  | j¡S d S ©Nr_  )rJ  rK  r>   rI  Ú_has_assume_role_config_varsÚ_load_creds_via_assume_role)rU   r_  r"   r.   r.   r1   r£   ç  s
    

zAssumeRoleProvider.loadc                 C   s   | j |ko| j|kS r,   )ÚROLE_CONFIG_VARÚWEB_IDENTITY_TOKE_FILE_VAR©rU   r"   r.   r.   r1   r�  î  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	r¶t|
ƒ}
t	| j
|
td�S )NÚrole_session_namer  Úexternal_idZ
ExternalIdr5  r2  r7  r3  r  )r5   r,  r  r  r-  r*   )rº   rË   rÌ   )Ú_get_role_configÚ_resolve_source_credentialsr>   r'  r  rˆ  r*   r  r‘   r÷   rD  rr   )rU   r6   Úrole_configr,  r  r’  r“  r5  r7  re  Z	refresherr.   r.   r1   rŽ  ù  sD    
 ÿ



úýz.AssumeRoleProvider._load_creds_via_assume_rolec                 C   s   | j  di ¡}|| }| d¡}|d }| d¡}| d¡}| d¡}| d¡}	| d¡}
||||	||d	œ}|
d
k	ršzt|
ƒ|d< W n tk
r˜   Y nX |d
k	rº|d
k	rºtd| d�‚nB|d
krÚ|d
krÚt| jdd�‚n"|d
k	rð|  ||¡ n|  ||¡ |S )z?Retrieves and validates the role configuration for the profile.r_  Úsource_profiler  Úcredential_sourcer5  r“  r’  r7  )r  r“  r5  r’  r—  r˜  NzDThe profile "%s" contains both source_profile and credential_source.©rð   z#source_profile or credential_sourcerB  )	rK  r>   r  r¥   r   r   rD  Ú_validate_credential_sourceÚ_validate_source_profile)rU   r6   r_  r"   r—  r  r˜  r5  r“  r’  r7  r–  r.   r.   r1   r”  %  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.)r‰  r   Úis_supported)rU   Zparent_profiler˜  r.   r.   r1   rš  V  s    
þþz.AssumeRoleProvider._validate_credential_sourcec                 C   s   t |  |¡|  |¡gƒS r,   )ÚanyÚ_has_static_credentialsr�  r‘  r.   r.   r1   Ú_source_profile_has_credentialsg  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 )Nr_  zThe source_profile "z" referenced in the profile "z" does not exist.r™  )r—  Zvisited_profiles)rK  r>   r   r‹  r   rž  )rU   Zparent_profile_nameZsource_profile_namer_  r—  r.   r.   r1   r›  o  s$    þ
þ

þz+AssumeRoleProvider._validate_source_profilec                    s   ddg}t ‡ fdd„|D ƒƒS )Nr:  r9  c                 3   s   | ]}|ˆ kV  qd S r,   r.   )rè   Z
static_key©r"   r.   r1   Ú	<genexpr>—  s     z=AssumeRoleProvider._has_static_credentials.<locals>.<genexpr>)r�  )rU   r"   Zstatic_keysr.   r   r1   rž  •  s    z*AssumeRoleProvider._has_static_credentialsc                 C   s<   |  d¡}|d k	r|  ||¡S |d }| j |¡ |  |¡S )Nr˜  r—  )r>   Ú _resolve_credentials_from_sourcer‹  rC  Ú!_resolve_credentials_from_profile)rU   r–  r6   r˜  r—  r.   r.   r1   r•  ™  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 )Nr_  Tr9   z.The source profile "%s" must have credentials.r™  )rK  r>   rž  rŠ  Ú(_resolve_static_credentials_from_profiler�  r<   rL   rn   r   rŽ  )rU   r6   r_  r"   rN   Zprofile_chainr†   Úerror_messager.   r.   r1   r£  ¤  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 )Nr9  r:  r;  )r   r   r    rB  )r}   r>   r¦   r   rD  Ústr)rU   r"   r^  r.   r.   r1   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î   )r‰  r,  r   )rU   r˜  r6   r†   r.   r.   r1   r¢  Ñ  s    ÿÿýz3AssumeRoleProvider._resolve_credentials_from_source)rj   rk   rl   rD  rH  r�  r�  ZEXPIRY_WINDOW_SECONDSr+  rV   r£   r�  rŽ  r”  rš  rŸ  r›  rž  r•  r£  r¤  r¢  r.   r.   r.   r1   rD   š  s*   ø
>,1&!rD   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 )rf   zassume-role-with-web-identityNZAWS_WEB_IDENTITY_TOKEN_FILEZAWS_ROLE_SESSION_NAMEZAWS_ROLE_ARN)r‡  r’  r  Fc                 C   s:   || _ || _|| _|| _d | _|| _|d kr0t}|| _d S r,   )r*   rJ  r  rI  Ú_profile_configÚ_disable_env_varsr   Ú_token_loader_cls)rU   r4   r5   r6   r*   r:   Ztoken_loader_clsr.   r.   r1   rV   ë  s    	z*AssumeRoleWithWebIdentityProvider.__init__c                 C   s   |   ¡ S r,   )Ú_assume_role_with_web_identityr^   r.   r.   r1   r£   þ  s    z&AssumeRoleWithWebIdentityProvider.loadc                 C   s:   | j d kr.|  ¡ }| di ¡}| | ji ¡| _ | j  |¡S rŒ  )r§  rJ  r>   rI  )rU   ÚkeyÚloaded_configr_  r.   r.   r1   Ú_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œ   rh  )rU   r«  Zenv_keyr.   r.   r1   Ú_get_env_config  s    
z1AssumeRoleWithWebIdentityProvider._get_env_configc                 C   s    |   |¡}|d k	r|S |  |¡S r,   )r¯  r­  )rU   r«  Z	env_valuer.   r.   r1   Ú_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 )	Nr‡  r  zÜThe 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™  r’  r  )r5   r>  r  r  r*   rd  )	r°  r©  r   r<  r  r*   r÷   rD  r  )rU   Z
token_pathÚtoken_loaderr  rð   r  r’  re  r.   r.   r1   rª    s0    


ÿ

û
þz@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN)rj   rk   rl   rD  rH  r®  rV   r£   r­  r¯  r°  rª  r.   r.   r.   r1   rf   â  s   ý   ù
rf   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 )rF   c                 C   s
   || _ d S r,   ©Ú
_providers©rU   r<   r.   r.   r1   rV   <  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.   )rH  ©rè   r[  r.   r.   r1   rì   J  s     z?CanonicalNameCredentialSourcer.is_supported.<locals>.<listcomp>r²  )rU   Úsource_namer.   r.   r1   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_providerrs   rL   rn   r£   )rU   r¶  Úsourcer.   r.   r1   r,  L  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sharedcredentialsr†  N©Úname)Ú_get_provider_by_canonical_nameÚlowerÚ_get_provider_by_methodrL   r   )rU   Úcanonical_namerï   rM   r.   r.   r1   r·  Z  s    

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

        This function is strict, it does not attempt to address
        compatibility issues.
        N)r³  rH  r¼  )rU   r¾  rï   rº  r.   r.   r1   r»  €  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³  rD  )rU   rº   rï   r.   r.   r1   r½  Œ  s    

z6CanonicalNameCredentialSourcer._get_provider_by_methodN)	rj   rk   rl   rV   rœ  r,  r·  r»  r½  r.   r.   r.   r1   rF   ;  s   &rF   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 )rA   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œ   rh  r   rw  Ú_fetcher)rU   rh  re  r.   r.   r1   rV   š  s    zContainerProvider.__init__c                 C   s$   | j | jks| j| jkr |  ¡ S d S r,   )ÚENV_VARrw  ÚENV_VAR_FULLÚ_retrieve_or_failr^   r.   r.   r1   r£   ¢  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_urlrw  rÀ  rÁ  Ú_build_headersÚ_create_fetcherrÀ   rD  ru   )rU   Úfull_uriÚheadersre  r  r.   r.   r1   rÂ  ¨  s    
úz#ContainerProvider._retrieve_or_failc                 C   s"   | j  | j¡}|d k	rd|iS d S )NÚAuthorization)rw  r>   ÚENV_VAR_AUTH_TOKEN)rU   Z
auth_tokenr.   r.   r1   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   rJ   rK   r   rD  r¦  )r…   r^  ©rÇ  rÈ  rU   r.   r1   Úfetch_creds¿  s(     ÿ
  ÿ ÿüz6ContainerProvider._create_fetcher.<locals>.fetch_credsr.   )rU   rÇ  rÈ  rÍ  r.   rÌ  r1   rÆ  ¾  s    z!ContainerProvider._create_fetcherc                 C   s   | j | jkS r,   )rÀ  rw  r^   r.   r.   r1   rÃ  Ô  s    z(ContainerProvider._provided_relative_uri)NN)rj   rk   rl   rD  rH  rÀ  rÁ  rÊ  rV   r£   rÂ  rÅ  rÆ  rÃ  r.   r.   r.   r1   rA   “  s   
rA   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 )rL   c                 C   s
   || _ dS )zQ

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

        Nr;   r´  r.   r.   r1   rV   Ù  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.   ©rD  rµ  r.   r.   r1   rì   ð  s     z4CredentialResolver.insert_before.<locals>.<listcomp>r¹  N)r<   Úindexr¥   r   Úinsert©rU   rº  Zcredential_providerÚoffsetr.   r.   r1   Ú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``
        rU  N)Ú_get_provider_offsetr<   rÐ  rÑ  r.   r.   r1   Ú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.   r1   rì     s     z-CredentialResolver.remove.<locals>.<listcomp>N)r<   rÏ  Úpop)rU   rº  Zavailable_methodsrÒ  r.   r.   r1   rI     s
    
zCredentialResolver.removec                 C   s   | j |  |¡ S )z÷Return 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Ô  ©rU   rº  r.   r.   r1   Ú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.   r1   rì   #  s     z;CredentialResolver._get_provider_offset.<locals>.<listcomp>r¹  )r<   rÏ  r¥   r   r×  r.   r.   r1   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<   rJ   rK   rD  r£   )rU   rï   r  r.   r.   r1   rn   '  s    

z#CredentialResolver.load_credentialsN)
rj   rk   rl   rV   rÓ  rÕ  rI   rØ  rÔ  rn   r.   r.   r.   r1   rL   Ø  s   rL   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	           	         s6   || _ || _|| _|| _|| _|| _tƒ  ||¡ d S r,   )r  Ú_sso_regionÚ
_role_nameÚ_account_idÚ
_start_urlÚ_token_loaderrø   rV   )	rU   Z	start_urlÚ
sso_regionrc  Z
account_idr5   r±  r*   r  rù   r.   r1   rV   ?  s    zSSOCredentialFetcher.__init__c                 C   s>   | j | j| jdœ}tj|ddd�}t| d¡ƒ ¡ }|  |¡S )r  )ZstartUrlÚroleNameÚ	accountIdT)ú,r  )r   Ú
separatorsr!  )	rÝ  rÛ  rÜ  r˜   r™   r   r#  r$  r
  r%  r.   r.   r1   rý   R  s    ý
z&SSOCredentialFetcher._create_cache_keyc                 C   s$   |d }t j  |tƒ ¡}| | j¡S )Ng     @�@)rp   Úfromtimestampr	   rw   Ú_UTC_DATE_FORMAT)rU   Ztimestamp_msZtimestamp_secondsÚ	timestampr.   r.   r1   Ú_parse_timestampe  s    z%SSOCredentialFetcher._parse_timestampc                 C   sš   t t| jd�}| jd|d�}| j| j|  | j¡dœ}z|jf |Ž}W n |j	j
k
rb   tƒ ‚Y nX |d }d|d |d |d |  |d	 ¡d
œdœ}|S )z4Get credentials by calling SSO get role credentials.)r?  r+   Ússor@  )rà  rá  ZaccessTokenZroleCredentialsZaccessKeyIdZsecretAccessKeyZsessionTokenr  )r~   r   r€   r�   )ZProviderTyper}   )r   r
   rÚ  r  rÛ  rÜ  rÞ  rÝ  Zget_role_credentialsÚ
exceptionsZUnauthorizedExceptionr   rç  )rU   r(   rˆ   r{   r…   r†   r.   r.   r1   r  k  s,    þ
ýüþ	z%SSOCredentialFetcher._get_credentials)NNN)	rj   rk   rl   rå  rV   rý   rç  r  rû   r.   r.   rù   r1   rÙ  <  s   	   ÷rÙ  c                   @   sP   e Zd ZdZej ej dddd¡¡ZddddgZ	dd
d„Z
dd„ Zdd„ Zd	S )rh   rè  r“   r”   r*   Ússo_start_urlrß  Ússo_role_nameÚsso_account_idNc                 C   s@   |d krt | jƒ}|| _|d kr$i }|| _|| _|| _|| _d S r,   )r’   Ú_SSO_TOKEN_CACHE_DIRÚ_token_cacher*   rJ  r  rI  )rU   r4   r5   r6   r*   rg   r.   r.   r1   rV   —  s    
zSSOProvider.__init__c                    sœ   |   ¡ }| di ¡}| j}| | ji ¡‰ t‡ fdd„| jD ƒƒrDd S i }g }| jD ]$}|ˆ krlˆ | ||< qR| |¡ qR|r˜d |¡}td||f d�‚|S )Nr_  c                 3   s   | ]}|ˆ kV  qd S r,   r.   )rè   Úc©r`  r.   r1   r¡  ¯  s     z/SSOProvider._load_sso_config.<locals>.<genexpr>rí   zSThe profile "%s" is configured to use SSO but is missing required configuration: %sr™  )rJ  r>   rI  ÚallÚ_SSO_CONFIG_VARSrC  r¶   r   )rU   r¬  r_  r6   r(   Zmissing_config_varsZ
config_varÚmissingr.   rð  r1   Ú_load_sso_config©  s(    

ÿþzSSOProvider._load_sso_configc              	   C   sR   |   ¡ }|sd S t|d |d |d |d | jt| jd�| jd�}t| j|jd�S )Nrê  rß  rë  rì  )r*   )r±  r*   rd  )	rô  rÙ  r  r   rî  r*   r÷   rD  r  )rU   Z
sso_configZsso_fetcherr.   r.   r1   r£   Å  s     
ù
þzSSOProvider.load)NN)rj   rk   rl   rD  rœ   r�   r¸   r¶   rí  rò  rV   rô  r£   r.   r.   r.   r1   rh   Š  s   ÿü  ú
rh   )NN)F)Trp   r+  r˜   Úloggingrœ   rV  rÇ   r  Úcollectionsr   Úcopyr   Úhashlibr   Úpathlibr   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.utilsr   r   r   r   r   r   Ú	getLoggerrj   rJ   r   rò   r?   rP   rC   ro   rr   ru   ry   rE   r‹   r‘   r’   r}   rÀ   r÷   rü   r  r'  r<  rA  r_   rB   r@   rG   rb   re   rH   rD   rf   rF   rA   rL   rÙ  rh   r.   r.   r.   r1   Ú<module>   s‚   , 	
 ÿ
]H
	>&  E5Z
ÿC.K~#.<-  JYXEdN