o
    <&ßaÄ@ ã                   @   sX  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 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! 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'm*Z* d dl'm+Z+ d dl'm,Z, d dl'm-Z- e .e/¡Z0e	dg d¢ƒZ1d]dd„Z2G dd„ de3ƒZ4d d!„ Z5d"d#„ Z6d$d%„ Z7d^d'd(„Z8d)d*„ Z9d+d,„ Z:d-d.„ Z;G d/d0„ d0e3ƒZ<G d1d2„ d2e3ƒZ=G d3d4„ d4e=ƒZ>G d5d6„ d6e>ƒZ?G d7d8„ d8e3ƒZ@G d9d:„ d:e@ƒZAG d;d<„ d<eAƒZBG d=d>„ d>eAƒZCG d?d@„ d@e3ƒZDG dAdB„ dBeDƒZEG dCdD„ dDeDƒZFG dEdF„ dFeDƒZGG dGdH„ dHeDƒZHG dIdJ„ dJeDƒZIG dKdL„ dLeDƒZJG dMdN„ dNeDƒZKG dOdP„ dPeDƒZLG dQdR„ dReDƒZMG dSdT„ dTe3ƒZNG dUdV„ dVeDƒZOG dWdX„ dXe3ƒZPG dYdZ„ dZe@ƒZQG d[d\„ d\eDƒZRdS )_é    N)Ú
namedtuple)Údeepcopy)Úsha1)ÚPath©Úparse)ÚtzlocalÚtzutc)ÚUNSIGNED)Útotal_seconds)Úcompat_shell_split)ÚConfig)ÚUnknownCredentialError)ÚPartialCredentialsError)ÚConfigNotFound)ÚInvalidConfigError)ÚInfiniteLoopConfigError)ÚRefreshWithMFAUnsupportedError)ÚMetadataRetrievalError)ÚCredentialRetrievalError)ÚUnauthorizedSSOTokenError)ÚInstanceMetadataFetcherÚparse_key_val_file)ÚContainerMetadataFetcher)ÚFileWebIdentityTokenLoader)ÚSSOTokenLoader)Úresolve_imds_endpoint_modeÚReadOnlyCredentials©Ú
access_keyÚ
secret_keyÚtokenc              	      s  ˆ   d¡pd}ˆ   d¡}ˆ   d¡}ˆ  ¡  d¡du}ˆ   d¡tˆ ƒdœ}|du r*i }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ÚdefaultÚmetadata_service_timeoutÚmetadata_service_num_attemptsNÚec2_metadata_service_endpoint)r&   Ú"ec2_metadata_service_endpoint_mode)ÚtimeoutÚnum_attemptsÚ
user_agentÚconfig)Úiam_role_fetcher)ÚcacheÚregion_namec                      s   ˆ j S ©N)Úfull_config© ©Úsessionr1   ú6/usr/lib/python3/dist-packages/botocore/credentials.pyÚ<lambda>]   s    z,create_credential_resolver.<locals>.<lambda>)Úload_configÚclient_creatorr-   Úprofile_nameÚcredential_sourcerÚprofile_provider_builder©r8   Údisable_env_varszWSkipping environment variable credential check because profile name was explicitly set.©Ú	providers)Úget_config_variableÚinstance_variablesÚgetr   ÚEnvProviderÚContainerProviderÚInstanceMetadataProviderr   r*   ÚProfileProviderBuilderÚAssumeRoleProviderÚ_get_client_creatorÚCanonicalNameCredentialSourcerr>   ÚOriginalEC2ProviderÚBotoProviderÚremoveÚloggerÚdebugÚCredentialResolver)r3   r-   r.   r8   Úmetadata_timeoutr)   r<   Úimds_configÚenv_providerÚcontainer_providerÚinstance_metadata_providerr:   Úassume_role_providerÚpre_profileÚprofile_providersÚpost_profiler>   Úresolverr1   r2   r4   Úcreate_credential_resolver9   sl   

ÿÿýüÿÿ
ÿøþþü


rY   c                   @   sP   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 )rE   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)Úselfr3   r-   r.   Ússo_token_cacher1   r1   r4   Ú__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©r^   r8   r<   r1   r1   r4   r>       s   ÿùz ProfileProviderBuilder.providersc                    s   t |‡ fdd„d�S )Nc                      ó   ˆ j jS r/   ©rZ   r0   r1   ©r^   r1   r4   r5   ®   ó    zAProfileProviderBuilder._create_process_provider.<locals>.<lambda>)r8   r6   )ÚProcessProvider©r^   r8   r1   ri   r4   rd   «   s   
þz/ProfileProviderBuilder._create_process_providerc                 C   ó   | j  d¡}t||d�S )NÚcredentials_file)r8   Úcreds_filename)rZ   r?   ÚSharedCredentialProvider)r^   r8   Úcredential_filer1   r1   r4   rc   ±   ó
   þz9ProfileProviderBuilder._create_shared_credential_providerc                 C   rm   )NÚconfig_file)r8   Úconfig_filename)rZ   r?   ÚConfigProvider)r^   r8   rs   r1   r1   r4   re   ¸   rr   z.ProfileProviderBuilder._create_config_providerc                    s&   t ‡ fdd„tˆ jˆ jƒˆ j||d�S )Nc                      rg   r/   rh   r1   ri   r1   r4   r5   Á   rj   zFProfileProviderBuilder._create_web_identity_provider.<locals>.<lambda>)r6   r7   r-   r8   r<   )Ú!AssumeRoleWithWebIdentityProviderrG   rZ   r\   r[   rf   r1   ri   r4   ra   ¿   s   
ÿúz4ProfileProviderBuilder._create_web_identity_providerc                    s"   t ‡ fdd„ˆ jj|ˆ jˆ jd�S )Nc                      rg   r/   rh   r1   ri   r1   r4   r5   Ë   rj   z=ProfileProviderBuilder._create_sso_provider.<locals>.<lambda>)r6   r7   r8   r-   Útoken_cache)ÚSSOProviderrZ   Úcreate_clientr[   r]   rl   r1   ri   r4   rb   É   s   
ûz+ProfileProviderBuilder._create_sso_provider©NNN©F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r`   r>   rd   rc   re   ra   rb   r1   r1   r1   r4   rE   �   s    	
ÿ

rE   c                 C   s   t | ƒ}| ¡ S r/   )rY   Úload_credentials)r3   rX   r1   r1   r4   Úget_credentialsÓ   s   r�   c                   C   s   t j  tƒ ¡S r/   )ÚdatetimeÚnowr   r1   r1   r1   r4   Ú
_local_nowØ   ó   r„   c                 C   s   t | tjƒr| S t| ƒS r/   )Ú
isinstancer‚   r   )Úvaluer1   r1   r4   Ú_parse_if_neededÜ   s   rˆ   Fc                 C   s&   t | tjƒr|r|  ¡ S |  d¡S | S )Nz%Y-%m-%dT%H:%M:%S%Z)r†   r‚   Ú	isoformatÚstrftime)r‡   Úisor1   r1   r4   Ú_serialize_if_neededâ   s
   
rŒ   c                    ó   ‡ ‡fdd„}|S )Nc                    s*   dˆ i}|j di |¤Ž ˆj| fi |¤ŽS )Nr.   r1   )Úupdatery   )Úservice_nameÚkwargsÚcreate_client_kwargs©r.   r3   r1   r4   r7   ë   s   ÿz+_get_client_creator.<locals>.client_creatorr1   )r3   r.   r7   r1   r’   r4   rG   ê   s   rG   c                    r�   )Nc                     s:   ˆ j di ˆ¤Ž} | d }|d |d |d t|d ƒdœS )NÚCredentialsÚAccessKeyIdÚSecretAccessKeyÚSessionTokenÚ
Expiration©r   r    r!   Úexpiry_timer1   )Úassume_rolerŒ   )ÚresponseÚcredentials©ÚclientÚparamsr1   r4   Úrefreshö   s   
üz-create_assume_role_refresher.<locals>.refreshr1   )rž   rŸ   r    r1   r�   r4   Úcreate_assume_role_refresherõ   s   r¡   c                 C   s   G dd„ dt ƒ}|| ƒ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)r^   r    r1   r1   r4   r`     s   
z8create_mfa_serial_refresher.<locals>._Refresher.__init__c                 S   s   | j rtƒ ‚d| _ |  ¡ S ©NT)r£   r   r¢   ri   r1   r1   r4   Ú__call__  s   z8create_mfa_serial_refresher.<locals>._Refresher.__call__N)r|   r}   r~   r`   r¥   r1   r1   r1   r4   Ú
_Refresher  s    r¦   )Úobject)Úactual_refreshr¦   r1   r1   r4   Ú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.
    ú~ú.awsÚbotor-   Nc                 C   s   || _ |d u r
| j}|| _d S r/   )Ú_working_dirÚ_default_dumpsÚ_dumps)r^   Úworking_dirÚ
dumps_funcr1   r1   r4   r`   !  s   
zJSONFileCache.__init__c                 C   s   t j|td�S )N)r#   )ÚjsonÚdumpsrŒ   )r^   Úobjr1   r1   r4   r¯   '  r…   zJSONFileCache._default_dumpsc                 C   s   |   |¡}tj |¡S r/   )Ú_convert_cache_keyÚosÚpathÚisfile)r^   Ú	cache_keyÚ
actual_keyr1   r1   r4   Ú__contains__*  s   
zJSONFileCache.__contains__c              
   C   sb   |   |¡}zt|ƒ�}t |¡W  d  ƒ W S 1 sw   Y  W dS  tttfy0   t|ƒ‚w )z Retrieve value from a cache key.N)r¶   Úopenr³   ÚloadÚOSErrorÚ
ValueErrorÚIOErrorÚKeyError)r^   rº   r»   Úfr1   r1   r4   Ú__getitem__.  s   

(ÿÿzJSONFileCache.__getitem__c                 C   s8   |   |¡}zt|ƒ}| ¡  W d S  ty   t|ƒ‚w r/   )r¶   r   ÚunlinkÚFileNotFoundErrorrÂ   )r^   rº   r»   Úkey_pathr1   r1   r4   Ú__delitem__7  s   
ÿzJSONFileCache.__delitem__c              	   C   s¨   |   |¡}z|  |¡}W n ttfy   td| ƒ‚w tj | j¡s)t | j¡ t 	t 
|tjtjB d¡d¡�}| ¡  | |¡ W d   ƒ d S 1 sMw   Y  d S )Nz5Value cannot be cached, must be JSON serializable: %si€  Úw)r¶   r°   Ú	TypeErrorrÀ   r·   r¸   Úisdirr®   ÚmakedirsÚfdopenr½   ÚO_WRONLYÚO_CREATÚtruncateÚwrite)r^   rº   r‡   Úfull_keyÚfile_contentrÃ   r1   r1   r4   Ú__setitem__?  s&   
ÿÿ
ÿÿ"ýzJSONFileCache.__setitem__c                 C   s   t j | j|d ¡}|S )Nz.json)r·   r¸   Újoinr®   )r^   rº   Ú	full_pathr1   r1   r4   r¶   M  s   z JSONFileCache._convert_cache_key)r|   r}   r~   r   r·   r¸   Ú
expanduserrÕ   Ú	CACHE_DIRr`   r¯   r¼   rÄ   rÈ   rÔ   r¶   r1   r1   r1   r4   rª     s    	rª   c                   @   s.   e Zd ZdZ		d	dd„Zdd„ Zdd„ ZdS )
r“   a\  
    Holds the credentials needed to authenticate requests.

    :ivar access_key: The access key part of the credentials.
    :ivar secret_key: The secret key part of the credentials.
    :ivar token: The security token, valid only for session credentials.
    :ivar method: A string which identifies where the credentials
        were found.
    Nc                 C   s0   || _ || _|| _|d u rd}|| _|  ¡  d S )NÚexplicit)r   r    r!   ÚmethodÚ
_normalize)r^   r   r    r!   rÚ   r1   r1   r4   r`   ]  s   zCredentials.__init__c                 C   ó$   t j | j¡| _t j | j¡| _d S r/   )ÚbotocoreÚcompatÚensure_unicoder   r    ri   r1   r1   r4   rÛ   i  s   zCredentials._normalizec                 C   s   t | j| j| jƒS r/   )r   r   r    r!   ri   r1   r1   r4   Úget_frozen_credentialss  s   þz"Credentials.get_frozen_credentials©NN)r|   r}   r~   r   r`   rÛ   rà   r1   r1   r1   r4   r“   R  s    

ÿ
r“   c                   @   sÌ   e Zd ZdZdZd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.

    :ivar access_key: The access key part of the credentials.
    :ivar secret_key: The secret key part of the credentials.
    :ivar token: The security token, valid only for session credentials.
    :ivar method: A string which identifies where the credentials
        were found.
    é„  iX  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Û   )r^   r   r    r!   r™   Úrefresh_usingrÚ   Útime_fetcherr1   r1   r4   r`   ‹  s   
ÿzRefreshableCredentials.__init__c                 C   rÜ   r/   )rÝ   rÞ   rß   rå   ræ   ri   r1   r1   r4   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Ú   Úinstancer1   r1   r4   Úcreate_from_metadataž  s   úz+RefreshableCredentials.create_from_metadatac                 C   ó   |   ¡  | 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å   ri   r1   r1   r4   r   ª  ó   z!RefreshableCredentials.access_keyc                 C   ó
   || _ d S r/   )rå   ©r^   r‡   r1   r1   r4   r   ³  ó   
c                 C   rõ   rö   )r¢   ræ   ri   r1   r1   r4   r    ·  r÷   z!RefreshableCredentials.secret_keyc                 C   rø   r/   )ræ   rù   r1   r1   r4   r    À  rú   c                 C   rõ   rö   )r¢   rç   ri   r1   r1   r4   r!   Ä  r÷   zRefreshableCredentials.tokenc                 C   rø   r/   )rç   rù   r1   r1   r4   r!   Í  rú   c                 C   s   | j |  ¡  }t|ƒS r/   )rè   ré   r   )r^   Údeltar1   r1   r4   Ú_seconds_remainingÑ  s   z)RefreshableCredentials._seconds_remainingNc                 C   s:   | j du rdS |du 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ü   rL   rM   ©r^   Ú
refresh_inr1   r1   r4   Úrefresh_neededÕ  s   

z%RefreshableCredentials.refresh_neededc                 C   s   | j dd�S )Nr   )rÿ   )r   ri   r1   r1   r4   Ú_is_expired÷  s   z"RefreshableCredentials._is_expiredc                 C   sÔ   |   | j¡sd S | j d¡r7z"|   | j¡sW | j ¡  d S |   | j¡}| j|d� W | j ¡  d S | j ¡  w |   | j¡rh| j� |   | j¡sP	 W d   ƒ d S | jdd� W d   ƒ d S 1 saw   Y  d S d S )NF)Úis_mandatoryT)r   rý   rì   ÚacquireÚreleaseÚ_mandatory_refresh_timeoutÚ_protected_refresh)r^   Úis_mandatory_refreshr1   r1   r4   r¢   û  s*   ûÿþ"ýýzRefreshableCredentials._refreshc                 C   s„   z|   ¡ }W n ty!   |rdnd}tjd|dd� |r‚ Y d S w |  |¡ t| j| j| jƒ| _	|  
¡ r@d}t |¡ t|ƒ‚d S )NÚ	mandatoryÚadvisoryzARefreshing temporary credentials failed during %s refresh period.T©Úexc_infozLCredentials were refreshed, but the refreshed credentials are still expired.)rä   Ú	ExceptionrL   ÚwarningÚ_set_from_datar   rå   ræ   rç   rí   r  ÚRuntimeError)r^   r  rò   Úperiod_nameÚmsgr1   r1   r4   r    s(   þó
ÿ
÷z)RefreshableCredentials._protected_refreshc                 C   s   t | ƒS r/   r   )Útime_strr1   r1   r4   rð   9  s   z'RefreshableCredentials._expiry_datetimec                    sŠ   g d¢}ˆ s	|}n	‡ fdd„|D ƒ}|r"d}t | j|d |¡ d�‚ˆ d | _ˆ d | _ˆ d	 | _tˆ d
 ƒ| _t 	d| j¡ |  
¡  d S )Nr˜   c                    s   g | ]}|ˆ vr|‘qS r1   r1   )Ú.0Úk©Údatar1   r4   Ú
<listcomp>B  s    z9RefreshableCredentials._set_from_data.<locals>.<listcomp>z7Credential refresh failed, response did not contain: %sú, ©ÚproviderÚ	error_msgr   r    r!   r™   z(Retrieved credentials will expire at: %s)r   rÚ   rÕ   r   r    r!   r   rè   rL   rM   rÛ   )r^   r  Úexpected_keysÚmissing_keysÚmessager1   r  r4   r  =  s$   þ


ÿz%RefreshableCredentials._set_from_datac                 C   rõ   )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í   ri   r1   r1   r4   rà   S  s   "z-RefreshableCredentials.get_frozen_credentialsr/   )r|   r}   r~   r   rý   r  r„   r`   rÛ   Úclassmethodrô   Úpropertyr   Úsetterr    r!   rü   r   r  r¢   r  Ústaticmethodrð   r  rà   r1   r1   r1   r4   râ   y  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í   )r^   rî   rÚ   rï   r1   r1   r4   r`   ~  s   

z'DeferredRefreshableCredentials.__init__Nc                    s   | j d u rdS tt| ƒ |¡S r¤   )rí   Úsuperr#  r   rþ   ©Ú	__class__r1   r4   r   ‰  s
   

ÿz-DeferredRefreshableCredentials.refresh_neededr/   )r|   r}   r~   r   r„   r`   r   Ú__classcell__r1   r1   r%  r4   r#  y  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 u ri }|| _ |  ¡ | _|d u r| j}|| _d S r/   )r[   Ú_create_cache_keyÚ
_cache_keyÚDEFAULT_EXPIRY_WINDOW_SECONDSÚ_expiry_window_seconds)r^   r-   Úexpiry_window_secondsr1   r1   r4   r`   ”  s   

z CachedCredentialFetcher.__init__c                 C   ó   t dƒ‚)Nz_create_cache_key()©ÚNotImplementedErrorri   r1   r1   r4   r)  �  ó   z)CachedCredentialFetcher._create_cache_keyc                 C   s$   |  dd¡  tjjd¡}|  dd¡S )Nú:Ú_ú/)Úreplacer·   r¸   Úsep)r^   Úfilenamer1   r1   r4   Ú_make_file_safe   s   z'CachedCredentialFetcher._make_file_safec                 C   r.  )Nz_get_credentials()r/  ri   r1   r1   r4   Ú_get_credentials¥  r1  z(CachedCredentialFetcher._get_credentialsc                 C   ó   |   ¡ S r/   )Ú_get_cached_credentialsri   r1   r1   r4   Úfetch_credentials¨  r1  z)CachedCredentialFetcher.fetch_credentialsc                 C   s`   |   ¡ }|du 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)r‹   r”   r•   r–   r˜   )Ú_load_from_cacher9  Ú_write_to_cacherL   rM   rŒ   )r^   r›   ÚcredsÚ
expirationr1   r1   r4   r;  «  s   
üz/CachedCredentialFetcher._get_cached_credentialsc                 C   s8   | j | jv rt| j| j  ƒ}|  |¡s|S t d¡ d S )Nz6Credentials were found in cache, but they are expired.)r*  r[   r   r  rL   rM   )r^   r?  r1   r1   r4   r=  Á  s   
ÿz(CachedCredentialFetcher._load_from_cachec                 C   s   t |ƒ| j| j< d S r/   )r   r[   r*  )r^   r›   r1   r1   r4   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—   )rˆ   r   r„   r,  )r^   rœ   Úend_timeÚsecondsr1   r1   r4   r  Ï  s   
z#CachedCredentialFetcher._is_expiredrá   )r|   r}   r~   r+  r`   r)  r8  r9  r<  r;  r=  r>  r  r1   r1   r1   r4   r(  ‘  s    
	r(  c                       s2   e Zd Z		d‡ fdd„	Zdd„ Zdd„ Z‡  ZS )	ÚBaseAssumeRoleCredentialFetcherNc                    sj   || _ || _|d u ri | _nt|ƒ| _| j| jd< | j d¡| _d| _| js*|  ¡  tt	| ƒ 
||¡ d S )NÚRoleArnÚRoleSessionNameF)Ú_client_creatorÚ	_role_arnÚ_assume_kwargsr   rA   Ú_role_session_nameÚ_using_default_session_nameÚ_generate_assume_role_namer$  rC  r`   )r^   r7   Úrole_arnÚ
extra_argsr-   r-  r%  r1   r4   r`   ×  s   

ÿz(BaseAssumeRoleCredentialFetcher.__init__c                 C   s(   dt t ¡ ƒ | _| j| jd< d| _d S )Nzbotocore-session-%srE  T)ÚintÚtimerI  rH  rJ  ri   r1   r1   r4   rK  ë  s   
z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namec                 C   sZ   t | jƒ}| jr|d= d|v rt |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.
        rE  ÚPolicyT)Ú	sort_keysúutf-8)
r   rH  rJ  r³   Úloadsr´   r   ÚencodeÚ	hexdigestr8  ©r^   ÚargsÚargument_hashr1   r1   r4   r)  ð  s   

z1BaseAssumeRoleCredentialFetcher._create_cache_keyrz   )r|   r}   r~   r`   rK  r)  r'  r1   r1   r%  r4   rC  Ö  s    ÿrC  c                       s:   e Zd Z		d
‡ fdd„	Zdd„ Zdd„ Zdd	„ Z‡  ZS )ÚAssumeRoleCredentialFetcherNc                    s<   || _ || _| jdu rtj| _t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©rM  r-   r-  )Ú_source_credentialsÚ_mfa_prompterÚgetpassr$  rZ  r`   )r^   r7   Úsource_credentialsrL  rM  Úmfa_prompterr-   r-  r%  r1   r4   r`     s   "


þz$AssumeRoleCredentialFetcher.__init__c                 C   s    |   ¡ }|  ¡ }|jdi |¤ŽS )ú'Get credentials by calling assume role.Nr1   )Ú_assume_role_kwargsÚ_create_clientrš   )r^   r�   rž   r1   r1   r4   r9  4  s   z,AssumeRoleCredentialFetcher._get_credentialsc                 C   sT   t | jƒ}| d¡}|durd| }|  |¡}||d< | d¡}|dur(||d< |S )úAGet the arguments for assume role based on current configuration.ÚSerialNumberNzEnter MFA code for %s: Ú	TokenCodeÚDurationSeconds)r   rH  rA   r]  )r^   Úassume_role_kwargsÚ
mfa_serialÚpromptÚ
token_codeÚduration_secondsr1   r1   r4   rb  :  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à   rF  r   r    r!   )r^   Úfrozen_credentialsr1   r1   r4   rc  L  s   
üz*AssumeRoleCredentialFetcher._create_client)NNNN)r|   r}   r~   r`   r9  rb  rc  r'  r1   r1   r%  r4   rZ    s    þ,rZ  c                       s0   e Zd Z	d‡ fdd„	Zdd„ Zdd„ Z‡  ZS )	Ú*AssumeRoleWithWebIdentityCredentialFetcherNc                    s$   || _ t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$  rr  r`   )r^   r7   Úweb_identity_token_loaderrL  rM  r-   r-  r%  r1   r4   r`   Z  s
   

þz3AssumeRoleWithWebIdentityCredentialFetcher.__init__c                 C   s0   |   ¡ }ttd�}| jd|d�}|jdi |¤ŽS )ra  )Úsignature_versionrm  ©r+   Nr1   )rb  r   r
   rF  Úassume_role_with_web_identity)r^   r�   r+   rž   r1   r1   r4   r9  ~  s   
z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialsc                 C   s   t | jƒ}|  ¡ }||d< |S )rd  ÚWebIdentityToken)r   rH  rs  )r^   rh  Úidentity_tokenr1   r1   r4   rb  ‡  s   
z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargsrz   )r|   r}   r~   r`   r9  rb  r'  r1   r1   r%  r4   rr  W  s
    ÿ$	rr  c                   @   s.   e Zd ZdZdZddd„Zdd„ Zdd„ ZdS )	ÚCredentialProviderNc                 C   rø   r/   r2   )r^   r3   r1   r1   r4   r`   œ  ó   
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
        Tr1   ri   r1   r1   r4   r¾   Ÿ  s   zCredentialProvider.loadc              	   G   s@   g }|D ]}z	|  || ¡ W q ty   t| j|d�‚w |S )N©r  Úcred_var)ÚappendrÂ   r   ÚMETHOD)r^   ÚmappingÚ	key_namesÚfoundÚkey_namer1   r1   r4   Ú_extract_creds_from_mapping²  s   ÿÿz.CredentialProvider._extract_creds_from_mappingr/   )r|   r}   r~   r  ÚCANONICAL_NAMEr`   r¾   r„  r1   r1   r1   r4   rz  �  s    
rz  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 )rk   zcustom-processc                 C   s   || _ || _d | _|| _d S r/   )Ú_profile_nameÚ_load_configÚ_loaded_configÚ_popen)r^   r8   r6   Úpopenr1   r1   r4   r`   Á  s   
zProcessProvider.__init__c                    sd   ˆj ‰ ˆ d u r	d S ˆ ˆ ¡}| d¡d ur"t |‡ ‡fdd„ˆj¡S t|d |d | d¡ˆjd�S )Nr™   c                      s
   ˆ  ˆ ¡S r/   )Ú_retrieve_credentials_usingr1   ©Úcredential_processr^   r1   r4   r5   Ð  s   
 z&ProcessProvider.load.<locals>.<lambda>r   r    r!   )r   r    r!   rÚ   )Ú_credential_processr‹  rA   râ   rô   r  r“   )r^   Ú
creds_dictr1   rŒ  r4   r¾   Ç  s    
ýüzProcessProvider.loadc           	   
   C   sÐ   t |ƒ}| j|tjtjd�}| ¡ \}}|jdkr#t| j| d¡d�‚t	j
j | d¡¡}| dd¡}|dkr@t| jd| d�‚z|d	 |d
 | d¡| d¡dœW S  tyg } z	t| jd| d�‚d }~ww )N)ÚstdoutÚstderrr   rS  r  ÚVersionz<Version key not provided>é   zOUnsupported version '%s' for credential process provider, supported versions: 1r”   r•   r–   r—   r˜   z$Missing required key in response: %s)r   r‰  Ú
subprocessÚPIPEÚcommunicateÚ
returncoder   r  ÚdecoderÝ   rÞ   r³   rT  rA   rÂ   )	r^   r�  Úprocess_listÚpr�  r‘  ÚparsedÚversionÚer1   r1   r4   r‹  Û  s@   þ
ÿÿþüþ€ÿz+ProcessProvider._retrieve_credentials_usingc                 C   s6   | j d u r
|  ¡ | _ | j  di ¡ | ji ¡}| d¡S )NÚprofilesr�  )rˆ  r‡  rA   r†  )r^   Úprofile_configr1   r1   r4   rŽ  ú  s   

ÿ
ÿ
z#ProcessProvider._credential_processN)r|   r}   r~   r  r”  ÚPopenr`   r¾   r‹  r   rŽ  r1   r1   r1   r4   rk   ½  s    rk   c                   @   s$   e Zd ZdZdZdd„ Zdd„ ZdS )rD   ziam-roleÚEc2InstanceMetadatac                 C   rø   r/   )Ú_role_fetcher)r^   r,   r1   r1   r4   r`     r{  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î   )r¢  Úretrieve_iam_role_credentialsrL   rM   râ   rô   r  )r^   Úfetcherrò   r?  r1   r1   r4   r¾   
  s   ÿýzInstanceMetadataProvider.loadN)r|   r}   r~   r  r…  r`   r¾   r1   r1   r1   r4   rD     s
    rD   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 )rB   ÚenvÚEnvironmentÚAWS_ACCESS_KEY_IDÚAWS_SECRET_ACCESS_KEYÚAWS_SECURITY_TOKENÚAWS_SESSION_TOKENÚAWS_CREDENTIAL_EXPIRATIONNc                 C   s$   |du 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)r^   r®  r€  r1   r1   r4   r`   )  s   zEnvProvider.__init__c                 C   s    i }|d u r| j |d< | j|d< | j|d< | j|d< |S | d| j ¡|d< | d| j¡|d< | d| j¡|d< t|d tƒsE|d g|d< | d| j¡|d< |S )Nr   r    r!   r™   )Ú
ACCESS_KEYÚ
SECRET_KEYÚTOKENSÚEXPIRY_TIMErA   r†   Úlist)r^   r€  Úvar_mappingr1   r1   r4   r¯  9  s,   



öÿÿÿÿzEnvProvider._build_mappingc                 C   s�   | j  | jd d¡}|rFt d¡ |  ¡ }|dd�}|d }|dur7t|ƒ}t|d |d |d	 ||| jd
�S t	|d |d |d	 | j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Ú   )
r®  rA   r°  rL   ÚinfoÚ_create_credentials_fetcherr   râ   r  r“   )r^   r   r¦  rœ   r™   r1   r1   r4   r¾   O  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¡}|s*tˆˆd d�‚||d< d |d< ˆd D ]}ˆ   |d¡}|rF||d<  nq6d |d< ˆ   ˆd d¡}|rY||d< | re|setˆˆd d�‚|S )Nr   r·  r|  r    r!   r™   )rA   r   )r¸  rœ   r   r    Útoken_env_varr!   r™   ©r®  r€  rÚ   r1   r4   r<  p  s:   ÿÿþÿzBEnvProvider._create_credentials_fetcher.<locals>.fetch_credentials)T)r°  r  r®  )r^   r<  r1   r½  r4   r»  k  s
    z'EnvProvider._create_credentials_fetcherrá   )r|   r}   r~   r  r…  r±  r²  r³  r´  r`   r¯  r¾   r»  r1   r1   r1   r4   rB     s    
rB   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 )rI   zec2-credentials-fileÚ	Ec2ConfigÚAWS_CREDENTIAL_FILEÚAWSAccessKeyIdÚAWSSecretKeyNc                 C   s*   |d u rt j}|d u rt}|| _|| _d S r/   )r·   r®  r   Ú_environÚ_parser)r^   r®  Úparserr1   r1   r4   r`   ›  s   
zOriginalEC2Provider.__init__c                 C   sf   d| j v r1tj | j d ¡}|  |¡}| j|v r/t d¡ || j }|| j }t	||| j
d�S dS dS )zN
        Search for a credential file used by original EC2 CLI tools.
        r¿  z)Found credentials in AWS_CREDENTIAL_FILE.r¹  N)rÂ  r·   r¸   r×   rÃ  r±  rL   rº  r²  r“   r  )r^   rÖ   r?  r   r    r1   r1   r4   r¾   £  s   
ÿ




ûzOriginalEC2Provider.loadrá   )
r|   r}   r~   r  r…  ÚCRED_FILE_ENVr±  r²  r`   r¾   r1   r1   r1   r4   rI   “  s    
rI   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 )rp   zshared-credentials-fileÚSharedCredentialsrn  ro  Úaws_security_tokenrp  Nc                 C   s2   || _ |d u r	d}|| _|d u rtjj}|| _d S )Nr#   )Ú_creds_filenamer†  rÝ   ÚconfigloaderÚraw_config_parseÚ_ini_parser)r^   ro   r8   Ú
ini_parserr1   r1   r4   r`   À  s   
z!SharedCredentialProvider.__init__c                 C   sŒ   z|   | j¡}W n
 ty   Y d S w | j|v rB|| j }| j|v rDt d| j¡ |  || j| j¡\}}|  	|¡}t
|||| jd�S d S d S )Nz0Found credentials in shared credentials file: %sr¹  )rË  rÈ  r   r†  r±  rL   rº  r„  r²  Ú_get_session_tokenr“   r  )r^   Úavailable_credsr+   r   r    r!   r1   r1   r4   r¾   É  s(   ÿ


ÿ
ÿ
ÿøzSharedCredentialProvider.loadc                 C   ó$   | j D ]}||v r||   S qd S r/   ©r³  )r^   r+   Útoken_envvarr1   r1   r4   rÍ  Ù  ó
   
ÿÿz+SharedCredentialProvider._get_session_tokenrá   )r|   r}   r~   r  r…  r±  r²  r³  r`   r¾   rÍ  r1   r1   r1   r4   rp   µ  s    
	rp   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 )ru   z0INI based config provider with profile sections.zconfig-fileÚSharedConfigrn  ro  rÇ  rp  Nc                 C   s&   || _ || _|du 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É  r6   Ú_config_parser)r^   rt   r8   Úconfig_parserr1   r1   r4   r`   ë  s
   	
zConfigProvider.__init__c                 C   s”   z|   | j¡}W n
 ty   Y dS w | j|d v rH|d | j }| j|v rFt d| j¡ |  || j| j¡\}}|  	|¡}t
|||| jd�S 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: %sr¹  )rÕ  rÔ  r   r†  r±  rL   rº  r„  r²  rÍ  r“   r  )r^   r0   rŸ  r   r    r!   r1   r1   r4   r¾   ú  s(   ÿ
ÿ
ÿ
ÿú	zConfigProvider.loadc                 C   rÏ  r/   rÐ  )r^   rŸ  Ú
token_namer1   r1   r4   rÍ    rÒ  z!ConfigProvider._get_session_tokenr/   )r|   r}   r~   r   r  r…  r±  r²  r³  r`   r¾   rÍ  r1   r1   r1   r4   ru   ß  s    
ru   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 )rJ   zboto-configÚBoto2ConfigÚBOTO_CONFIGz/etc/boto.cfgz~/.botorn  ro  Nc                 C   s.   |d u rt j}|d u rtjj}|| _|| _d S r/   )r·   r®  rÝ   rÉ  rÊ  rÂ  rË  )r^   r®  rÌ  r1   r1   r4   r`     s   
zBotoProvider.__init__c              	   C   s¢   | j | jv r| j| j  g}n| j}|D ];}z|  |¡}W n	 ty%   Y qw d|v rN|d }| j|v rNt 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: %sr¹  N)ÚBOTO_CONFIG_ENVrÂ  ÚDEFAULT_CONFIG_FILENAMESrË  r   r±  rL   rº  r„  r²  r“   r  )r^   Úpotential_locationsr7  r+   rœ   r   r    r1   r1   r4   r¾   '  s.   þ
ÿ
ÿ
ÿ€ózBotoProvider.loadrá   )r|   r}   r~   r  r…  rÚ  rÛ  r±  r²  r`   r¾   r1   r1   r1   r4   rJ     s    
rJ   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 ) rF   úassume-roleNrL  Ú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‡  rF  r†  Ú	_prompterrˆ  Ú_credential_sourcerÚ_profile_provider_builderÚ_visited_profiles)r^   r6   r7   r-   r8   Úprompterr9   r:   r1   r1   r4   r`   O  s   $zAssumeRoleProvider.__init__c                 C   s@   |   ¡ | _| j di ¡}| | ji ¡}|  |¡r|  | j¡S d S ©Nrž  )r‡  rˆ  rA   r†  Ú_has_assume_role_config_varsÚ_load_creds_via_assume_role)r^   rž  r"   r1   r1   r4   r¾   †  s   

ÿzAssumeRoleProvider.loadc                 C   s   | j |v o	| j|vS r/   )ÚROLE_CONFIG_VARÚWEB_IDENTITY_TOKE_FILE_VAR©r^   r"   r1   r1   r4   rå  �  s   
úz/AssumeRoleProvider._has_assume_role_config_varsc                 C   sÆ   |   |¡}|  ||¡}i }| d¡}|d ur||d< | d¡}|d ur'||d< | d¡}|d ur4||d< | d¡}|d urA||d< t| j||d	 || j| jd
�}	|	j}
|d ur[t|
ƒ}
t	| j
|
td�S )NÚrole_session_namerE  Úexternal_idÚ
ExternalIdri  re  rl  rg  rL  )r7   r_  rL  rM  r`  r-   )rÚ   rî   rï   )Ú_get_role_configÚ_resolve_source_credentialsrA   rZ  rF  rß  r-   r<  r©   r#  r  r„   )r^   r8   Úrole_configr_  rM  rê  rë  ri  rl  r¦  Ú	refresherr1   r1   r4   ræ  —  sB   
ÿ



úýz.AssumeRoleProvider._load_creds_via_assume_rolec                 C   sü   | j  di ¡}|| }| d¡}|d }| d¡}| d¡}| d¡}| d¡}	| d¡}
||||	||d	œ}|
d
urLzt|
ƒ|d< W n	 tyK   Y nw |d
ur[|d
ur[td| d�‚|d
u rj|d
u rjt| jdd�‚|d
urv|  ||¡ |S |  ||¡ |S )z?Retrieves and validates the role configuration for the profile.rž  Úsource_profilerL  Úcredential_sourceri  rë  rê  rl  )rL  rë  ri  rê  rñ  rò  NzDThe profile "%s" contains both source_profile and credential_source.©r  z#source_profile or credential_sourcer|  )	rˆ  rA   rN  rÀ   r   r   r  Ú_validate_credential_sourceÚ_validate_source_profile)r^   r8   rž  r"   rñ  rL  rò  ri  rë  rê  rl  rï  r1   r1   r4   rí  Ã  sP   





ú	ÿÿþþÿþz#AssumeRoleProvider._get_role_configc                 C   s>   | j d u rtd||f d�‚| j  |¡std||f d�‚d S )Nz_The credential_source "%s" is specified in profile "%s", but no source provider was configured.ró  zCThe credential source "%s" referenced in profile "%s" is not valid.)rà  r   Úis_supported)r^   Úparent_profilerò  r1   r1   r4   rô  õ  s   
ÿÿÿÿÿÿz.AssumeRoleProvider._validate_credential_sourcec                 C   s   t |  |¡|  |¡gƒS r/   )ÚanyÚ_has_static_credentialsrå  ré  r1   r1   r4   Ú_source_profile_has_credentials  s   þz2AssumeRoleProvider._source_profile_has_credentialsc                 C   sp   | j  di ¡}||vrtd||f d�‚|| }|| jvrd S ||kr*t|| jd�‚|  |¡s6t|| jd�‚d S )Nrž  zFThe source_profile "%s" referenced in the profile "%s" does not exist.ró  )rñ  Úvisited_profiles)rˆ  rA   r   râ  r   rù  )r^   Úparent_profile_nameÚsource_profile_namerž  rñ  r1   r1   r4   rõ    s,   ÿÿþ
þ

þÿz+AssumeRoleProvider._validate_source_profilec                    s   ddg}t ‡ fdd„|D ƒƒS )Nro  rn  c                 3   s   � | ]}|ˆ v V  qd S r/   r1   )r  Ú
static_key©r"   r1   r4   Ú	<genexpr>0  ó   € z=AssumeRoleProvider._has_static_credentials.<locals>.<genexpr>)rø  )r^   r"   Ústatic_keysr1   rÿ  r4   rù  .  s   z*AssumeRoleProvider._has_static_credentialsc                 C   s<   |  d¡}|d ur|  ||¡S |d }| j |¡ |  |¡S )Nrò  rñ  )rA   Ú _resolve_credentials_from_sourcerâ  r~  Ú!_resolve_credentials_from_profile)r^   rï  r8   rò  rñ  r1   r1   r4   rî  2  s   
ÿ
z.AssumeRoleProvider._resolve_source_credentialsc                 C   sŒ   | j  di ¡}|| }|  |¡r| js|  |¡S |  |¡s"|  |¡sA| jj|dd�}t|ƒ}| ¡ }|d u r?d}t	|| d�‚|S |  
|¡S )Nrž  Tr;   z.The source profile "%s" must have credentials.ró  )rˆ  rA   rù  rá  Ú(_resolve_static_credentials_from_profilerå  r>   rN   r€   r   ræ  )r^   r8   rž  r"   rV   Úprofile_chainrœ   Úerror_messager1   r1   r4   r  =  s.   
ÿ

ÿþÿÿ
z4AssumeRoleProvider._resolve_credentials_from_profilec              
   C   sJ   zt |d |d | d¡d�W S  ty$ } z	t| jt|ƒd�‚d }~ww )Nrn  ro  rp  r   r|  )r“   rA   rÂ   r   r  Ústr)r^   r"   r�  r1   r1   r4   r  [  s   ý
ÿ€ÿz;AssumeRoleProvider._resolve_static_credentials_from_profilec                 C   s(   | j  |¡}|d u rt|d| d�‚|S )NzBNo credentials found in credential_source referenced in profile %sr  )rà  r_  r   )r^   rò  r8   rœ   r1   r1   r4   r  f  s   ÿÿýz3AssumeRoleProvider._resolve_credentials_from_source)r|   r}   r~   r  r…  rç  rè  ÚEXPIRY_WINDOW_SECONDSr^  r`   r¾   rå  ræ  rí  rô  rú  rõ  rù  rî  r  r  r  r1   r1   r1   r4   rF   @  s*    
þ7
,2&rF   c                   @   sX   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 )rv   zassume-role-with-web-identityNÚAWS_WEB_IDENTITY_TOKEN_FILEÚAWS_ROLE_SESSION_NAMEÚAWS_ROLE_ARN)rÞ  rê  rL  Fc                 C   s:   || _ || _|| _|| _d | _|| _|d u rt}|| _d S r/   )r-   r‡  rF  r†  Ú_profile_configÚ_disable_env_varsr   Ú_token_loader_cls)r^   r6   r7   r8   r-   r<   Útoken_loader_clsr1   r1   r4   r`   ~  s   	
z*AssumeRoleWithWebIdentityProvider.__init__c                 C   r:  r/   )Ú_assume_role_with_web_identityri   r1   r1   r4   r¾   ‘  r1  z&AssumeRoleWithWebIdentityProvider.loadc                 C   s:   | j d u r|  ¡ }| di ¡}| | ji ¡| _ | j  |¡S rä  )r  r‡  rA   r†  )r^   ÚkeyÚloaded_configrž  r1   r1   r4   Ú_get_profile_config”  s
   
z5AssumeRoleWithWebIdentityProvider._get_profile_configc                 C   s2   | j rd S | j |¡}|r|tjv rtj| S d S r/   )r  Ú_CONFIG_TO_ENV_VARrA   r·   r®  )r^   r  Úenv_keyr1   r1   r4   Ú_get_env_config›  s   
z1AssumeRoleWithWebIdentityProvider._get_env_configc                 C   s    |   |¡}|d ur|S |  |¡S r/   )r  r  )r^   r  Ú	env_valuer1   r1   r4   Ú_get_config£  s   

z-AssumeRoleWithWebIdentityProvider._get_configc                 C   s|   |   d¡}|s	d S |  |¡}|   d¡}|sd}t|d�‚i }|   d¡}|d ur+||d< t| j|||| jd�}t| j|jd�S )	NrÞ  rL  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ê  rE  )r7   rt  rL  rM  r-   r¤  )	r  r  r   rr  rF  r-   r#  r  r<  )r^   Ú
token_pathÚtoken_loaderrL  r  rM  rê  r¦  r1   r1   r4   r  ©  s0   


ÿ

û
þz@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN)r|   r}   r~   r  r…  r  r`   r¾   r  r  r  r  r1   r1   r1   r4   rv   u  s     ý
ùrv   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 )rH   c                 C   rø   r/   ©Ú
_providers©r^   r>   r1   r1   r4   r`   Ï  r{  z'CanonicalNameCredentialSourcer.__init__c                 C   s   |dd„ | j D ƒv 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   ó   g | ]}|j ‘qS r1   )r…  ©r  rš  r1   r1   r4   r  Ý  ó    z?CanonicalNameCredentialSourcer.is_supported.<locals>.<listcomp>r  )r^   Úsource_namer1   r1   r4   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_providerr†   rN   r€   r¾   )r^   r"  Úsourcer1   r1   r4   r_  ß  s   
	
z1CanonicalNameCredentialSourcer.source_credentialsc                 C   sV   |   |¡}| ¡ dv r |  d¡}|dur |du r|S t||gƒS |du r)t|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.
        )ÚsharedconfigÚsharedcredentialsrÝ  N©Úname)Ú_get_provider_by_canonical_nameÚlowerÚ_get_provider_by_methodrN   r   )r^   Úcanonical_namer  rT   r1   r1   r4   r#  í  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  r…  r*  )r^   r,  r  r(  r1   r1   r4   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  r  )r^   rÚ   r  r1   r1   r4   r+    s
   

ÿÿz6CanonicalNameCredentialSourcer._get_provider_by_methodN)	r|   r}   r~   r`   rö  r_  r#  r)  r+  r1   r1   r1   r4   rH   Î  s    &rH   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 )rC   zcontainer-roleÚEcsContainerÚ&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIÚ"AWS_CONTAINER_CREDENTIALS_FULL_URIÚ!AWS_CONTAINER_AUTHORIZATION_TOKENNc                 C   s,   |d u rt j}|d u rtƒ }|| _|| _d S r/   )r·   r®  r   rÂ  Ú_fetcher)r^   r®  r¦  r1   r1   r4   r`   -  s   
zContainerProvider.__init__c                 C   s$   | j | jv s| j| jv r|  ¡ S d S r/   )ÚENV_VARrÂ  ÚENV_VAR_FULLÚ_retrieve_or_failri   r1   r1   r4   r¾   5  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_urir1  Úfull_urlrÂ  r2  r3  Ú_build_headersÚ_create_fetcherrâ   r  rˆ   )r^   Úfull_uriÚheadersr¦  r?  r1   r1   r4   r4  ;  s   
úz#ContainerProvider._retrieve_or_failc                 C   s"   | j  | j¡}|d urd|iS d S )NÚAuthorization)rÂ  rA   ÚENV_VAR_AUTH_TOKEN)r^   Ú
auth_tokenr1   r1   r4   r7  L  s
   ÿÿz ContainerProvider._build_headersc                    s   ‡ ‡‡fdd„}|S )Nc               
      sn   z
ˆj jˆ ˆd�} W n ty' } ztjd|dd� tˆjt|ƒd�‚d }~ww | d | d | d | d	 d
œS )N)r:  z'Error retrieving container metadata: %sTr
  r  r”   r•   ÚTokenr—   r˜   )r1  Úretrieve_full_urir   rL   rM   r   r  r  )r›   r�  ©r9  r:  r^   r1   r4   Úfetch_credsT  s$   
ÿÿÿ€ýüz6ContainerProvider._create_fetcher.<locals>.fetch_credsr1   )r^   r9  r:  rA  r1   r@  r4   r8  S  s   z!ContainerProvider._create_fetcherc                 C   s   | j | jv S r/   )r2  rÂ  ri   r1   r1   r4   r5  f  s   z(ContainerProvider._provided_relative_urirá   )r|   r}   r~   r  r…  r2  r3  r<  r`   r¾   r4  r7  r8  r5  r1   r1   r1   r4   rC   &  s    
rC   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 )rN   c                 C   s
   || _ dS )zQ

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

        Nr=   r  r1   r1   r4   r`   k  s   
zCredentialResolver.__init__c                 C   sF   zdd„ | j D ƒ |¡}W n ty   t|d�‚w | 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   r  r1   ©r  r   r1   r1   r4   r  ‚  r!  z4CredentialResolver.insert_before.<locals>.<listcomp>r'  N)r>   ÚindexrÀ   r   Úinsert©r^   r(  Úcredential_providerÚoffsetr1   r1   r4   Úinsert_befores  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``
        r“  N)Ú_get_provider_offsetr>   rD  rE  r1   r1   r4   Úinsert_after‡  s   
zCredentialResolver.insert_afterc                 C   s6   dd„ | j D ƒ}||v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   r  r1   rB  r   r1   r1   r4   r  Ÿ  r!  z-CredentialResolver.remove.<locals>.<listcomp>N)r>   rC  Úpop)r^   r(  Úavailable_methodsrG  r1   r1   r4   rK   ˜  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>   rI  ©r^   r(  r1   r1   r4   Úget_provider§  s   
zCredentialResolver.get_providerc                 C   s2   zdd„ | j D ƒ |¡W S  ty   t|d�‚w )Nc                 S   r  r1   rB  r   r1   r1   r4   r  µ  r!  z;CredentialResolver._get_provider_offset.<locals>.<listcomp>r'  )r>   rC  rÀ   r   rM  r1   r1   r4   rI  ³  s
   
ÿz'CredentialResolver._get_provider_offsetc                 C   s6   | j D ]}t d|j¡ | ¡ }|du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>   rL   rM   r  r¾   )r^   r  r?  r1   r1   r4   r€   ¹  s   
ÿ	z#CredentialResolver.load_credentialsN)
r|   r}   r~   r`   rH  rJ  rK   rN  rI  r€   r1   r1   r1   r4   rN   j  s    rN   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	           	         s:   || _ || _|| _|| _|| _|| _tt| ƒ ||¡ d S r/   )	rF  Ú_sso_regionÚ
_role_nameÚ_account_idÚ
_start_urlÚ_token_loaderr$  rO  r`   )	r^   Ú	start_urlÚ
sso_regionr£  Ú
account_idr7   r  r-   r-  r%  r1   r4   r`   Ñ  s   
ÿzSSOCredentialFetcher.__init__c                 C   s>   | j | j| jdœ}tj|ddd�}t| d¡ƒ ¡ }|  |¡S )rP  )ÚstartUrlÚroleNameÚ	accountIdT)ú,r2  )rR  Ú
separatorsrS  )	rS  rQ  rR  r³   r´   r   rU  rV  r8  rW  r1   r1   r4   r)  Þ  s   ý

z&SSOCredentialFetcher._create_cache_keyc                 C   s$   |d }t j  |tƒ ¡}| | j¡S )Ng     @�@)r‚   Úfromtimestampr	   rŠ   Ú_UTC_DATE_FORMAT)r^   Útimestamp_msÚtimestamp_secondsÚ	timestampr1   r1   r4   Ú_parse_timestampñ  s   z%SSOCredentialFetcher._parse_timestampc                 C   s˜   t t| jd�}| jd|d�}| j| j|  | j¡dœ}z
|jdi |¤Ž}W n |j	j
y0   tƒ ‚w |d }d|d |d |d |  |d	 ¡d
œdœ}|S )z4Get credentials by calling SSO get role credentials.)ru  r.   Ússorv  )rY  rZ  ÚaccessTokenÚroleCredentialsÚaccessKeyIdÚsecretAccessKeyÚsessionTokenr@  )r”   r•   r–   r—   )ÚProviderTyper“   Nr1   )r   r
   rP  rF  rQ  rR  rT  rS  Úget_role_credentialsÚ
exceptionsÚUnauthorizedExceptionr   rb  )r^   r+   rž   r�   r›   rœ   r1   r1   r4   r9  ÷  s.   þ
ýÿüþ	z%SSOCredentialFetcher._get_credentialsrz   )	r|   r}   r~   r^  r`   r)  rb  r9  r'  r1   r1   r%  r4   rO  Î  s    þrO  c                   @   sN   e Zd ZdZej ej dddd¡¡Zg d¢Z		ddd„Z
d	d
„ Zdd„ ZdS )rx   rc  r«   r¬   r-   )Ússo_start_urlrV  Ússo_role_nameÚsso_account_idNc                 C   s@   |d u r	t | jƒ}|| _|d u ri }|| _|| _|| _|| _d S r/   )rª   Ú_SSO_TOKEN_CACHE_DIRÚ_token_cacher-   r‡  rF  r†  )r^   r6   r7   r8   r-   rw   r1   r1   r4   r`   #  s   

zSSOProvider.__init__c                    sœ   |   ¡ }| di ¡}| j}| | ji ¡‰ t‡ fdd„| jD ƒƒr"d S i }g }| jD ]}|ˆ v r6ˆ | ||< q)| |¡ q)|rLd |¡}td||f d�‚|S )Nrž  c                 3   s   � | ]}|ˆ vV  qd S r/   r1   )r  Úc©rŸ  r1   r4   r   5  r  z/SSOProvider._load_sso_config.<locals>.<genexpr>r  zSThe profile "%s" is configured to use SSO but is missing required configuration: %sró  )r‡  rA   r†  ÚallÚ_SSO_CONFIG_VARSr~  rÕ   r   )r^   r  rž  r8   r+   Úmissing_config_varsÚ
config_varÚmissingr1   rs  r4   Ú_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 )Nrm  rV  rn  ro  )r-   )r  r-   r¤  )	ry  rO  rF  r   rq  r-   r#  r  r<  )r^   Ú
sso_configÚsso_fetcherr1   r1   r4   r¾   K  s    
ù
þzSSOProvider.loadrá   )r|   r}   r~   r  r·   r¸   r×   rÕ   rp  ru  r`   ry  r¾   r1   r1   r1   r4   rx     s    ÿ
ÿrx   rá   r{   )SrO  r‚   Úloggingr·   r^  rê   r³   r”  Úcollectionsr   Úcopyr   Úhashlibr   Úpathlibr   Údateutil.parserr   Údateutil.tzr   r	   Úbotocore.configloaderrÝ   Úbotocore.compatr
   r   r   Úbotocore.configr   Úbotocore.exceptionsr   r   r   r   r   r   r   r   r   Úbotocore.utilsr   r   r   r   r   r   Ú	getLoggerr|   rL   r   rY   r§   rE   r�   r„   rˆ   rŒ   rG   r¡   r©   rª   r“   râ   r#  r(  rC  rZ  rr  rz  rk   rD   rB   rI   rp   ru   rJ   rF   rv   rH   rC   rN   rO  rx   r1   r1   r1   r4   Ú<module>   s˜   
ÿ
VD
;'  E1
Pÿ9-Ft"*7*  7YXDdH