o <&a@@sXddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlmZmZddlZddlZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddl'm(Z(m)Z)ddl'm*Z*ddl'm+Z+ddl'm,Z,ddl'm-Z-e.e/Z0e dgdZ1d]ddZ2Gddde3Z4d d!Z5d"d#Z6d$d%Z7d^d'd(Z8d)d*Z9d+d,Z:d-d.Z;Gd/d0d0e3ZGd5d6d6e>Z?Gd7d8d8e3Z@Gd9d:d:e@ZAGd;d<dd>eAZCGd?d@d@e3ZDGdAdBdBeDZEGdCdDdDeDZFGdEdFdFeDZGGdGdHdHeDZHGdIdJdJeDZIGdKdLdLeDZJGdMdNdNeDZKGdOdPdPeDZLGdQdRdReDZMGdSdTdTe3ZNGdUdVdVeDZOGdWdXdXe3ZPGdYdZdZe@ZQGd[d\d\eDZRdS)_N) namedtuple)deepcopy)sha1)Pathparse)tzlocaltzutc)UNSIGNED) total_seconds)compat_shell_split)Config)UnknownCredentialError)PartialCredentialsError)ConfigNotFound)InvalidConfigError)InfiniteLoopConfigError)RefreshWithMFAUnsupportedError)MetadataRetrievalError)CredentialRetrievalError)UnauthorizedSSOTokenError)InstanceMetadataFetcherparse_key_val_file)ContainerMetadataFetcher)FileWebIdentityTokenLoader)SSOTokenLoader)resolve_imds_endpoint_modeReadOnlyCredentials access_key secret_keytokenc s dpd}d}d}ddu}dtd}|dur*i}t}t} tt|||dd } t ||d } t fd d t |||t || | g| d } || g} | j ||d}tt| | g}| ||}|r||tdt|d}|S)zCreate a default credential resolver. This creates a pre-configured credential resolver that includes the default lookup chain for credentials. profiledefaultmetadata_service_timeoutmetadata_service_num_attemptsNec2_metadata_service_endpoint)r&"ec2_metadata_service_endpoint_mode)timeout num_attempts user_agentconfig)iam_role_fetcher)cache region_namecsjSN) full_configsessionr16/usr/lib/python3/dist-packages/botocore/credentials.py]sz,create_credential_resolver..) load_configclient_creatorr- profile_namecredential_sourcerprofile_provider_builderr8disable_env_varszWSkipping environment variable credential check because profile name was explicitly set. providers)get_config_variableinstance_variablesgetr EnvProviderContainerProviderInstanceMetadataProviderrr*ProfileProviderBuilderAssumeRoleProvider_get_client_creatorCanonicalNameCredentialSourcerr>OriginalEC2Provider BotoProviderremoveloggerdebugCredentialResolver)r3r-r.r8metadata_timeoutr)r< imds_config env_providercontainer_providerinstance_metadata_providerr:assume_role_provider pre_profileprofile_providers post_profiler>resolverr1r2r4create_credential_resolver9sl        rYc@sPeZdZdZ  dddZdddZdd Zd d Zd d ZddZ ddZ dS)rEaThis 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. NcCs||_||_||_||_dSr/)_session_cache _region_name_sso_token_cache)selfr3r-r.sso_token_cacher1r1r4__init__s zProfileProviderBuilder.__init__FcCs.|||||||||||gSr/)_create_web_identity_provider_create_sso_provider"_create_shared_credential_provider_create_process_provider_create_config_providerr^r8r<r1r1r4r>sz ProfileProviderBuilder.providerscst|fdddS)NcjjSr/rZr0r1r^r1r4r5zAProfileProviderBuilder._create_process_provider..)r8r6)ProcessProviderr^r8r1rir4rds z/ProfileProviderBuilder._create_process_providercC|jd}t||dS)Ncredentials_file)r8creds_filename)rZr?SharedCredentialProvider)r^r8credential_filer1r1r4rc z9ProfileProviderBuilder._create_shared_credential_providercCrm)N config_file)r8config_filename)rZr?ConfigProvider)r^r8rsr1r1r4rerrz.ProfileProviderBuilder._create_config_providercs&tfddtjjj||dS)Ncrgr/rhr1rir1r4r5rjzFProfileProviderBuilder._create_web_identity_provider..)r6r7r-r8r<)!AssumeRoleWithWebIdentityProviderrGrZr\r[rfr1rir4ras z4ProfileProviderBuilder._create_web_identity_providercs"tfddjj|jjdS)Ncrgr/rhr1rir1r4r5rjz=ProfileProviderBuilder._create_sso_provider..)r6r7r8r- token_cache) SSOProviderrZ create_clientr[r]rlr1rir4rbs z+ProfileProviderBuilder._create_sso_providerNNNF) __name__ __module__ __qualname____doc__r`r>rdrcrerarbr1r1r1r4rEs    rEcCst|}|Sr/)rYload_credentials)r3rXr1r1r4get_credentialssrcCstjtSr/)datetimenowrr1r1r1r4 _local_nowrcCst|tjr|St|Sr/) isinstancerr)valuer1r1r4_parse_if_neededs rFcCs&t|tjr|r |S|dS|S)Nz%Y-%m-%dT%H:%M:%S%Z)rr isoformatstrftime)risor1r1r4_serialize_if_neededs  rcfdd}|S)Ncs*di}|jdi|j|fi|S)Nr.r1)updatery) service_namekwargscreate_client_kwargsr.r3r1r4r7sz+_get_client_creator..client_creatorr1)r3r.r7r1rr4rGsrGcr)Ncs:jdi}|d}|d|d|dt|ddS)N Credentials AccessKeyIdSecretAccessKey SessionToken Expirationrr r! expiry_timer1) assume_roler)response credentialsclientparamsr1r4refreshs z-create_assume_role_refresher..refreshr1)rrrr1rr4create_assume_role_refreshers rcCsGdddt}||S)Nc@seZdZddZddZdS)z/create_mfa_serial_refresher.._RefreshercSs||_d|_dS)NF)_refresh_has_been_called)r^rr1r1r4r`s z8create_mfa_serial_refresher.._Refresher.__init__cSs|jrtd|_|SNT)rrrrir1r1r4__call__ sz8create_mfa_serial_refresher.._Refresher.__call__N)r|r}r~r`rr1r1r1r4 _Refreshers r)object)actual_refreshrr1r1r4create_mfa_serial_refreshersrc@sheZdZdZejejddddZedfddZ d d Z d d Z d dZ ddZ ddZddZdS) JSONFileCachezJSON file cache. This provides a dict like interface that stores JSON serializable objects. The objects are serialized to JSON and stored in a file. These values can be retrieved at a later time. ~.awsbotor-NcCs||_|dur |j}||_dSr/) _working_dir_default_dumps_dumps)r^ working_dir dumps_funcr1r1r4r`!s zJSONFileCache.__init__cCstj|tdS)N)r#)jsondumpsr)r^objr1r1r4r'rzJSONFileCache._default_dumpscCs||}tj|Sr/)_convert_cache_keyospathisfile)r^ cache_key actual_keyr1r1r4 __contains__*s  zJSONFileCache.__contains__c Csb||}zt|}t|WdWS1swYWdStttfy0t|w)z Retrieve value from a cache key.N)ropenrloadOSError ValueErrorIOErrorKeyError)r^rrfr1r1r4 __getitem__.s  (zJSONFileCache.__getitem__cCs8||}z t|}|WdStyt|wr/)rrunlinkFileNotFoundErrorr)r^rrkey_pathr1r1r4 __delitem__7s  zJSONFileCache.__delitem__c Cs||}z||}Wnttfytd|wtj|js)t|jt t |tj tj Bdd}| ||WddS1sMwYdS)Nz5Value cannot be cached, must be JSON serializable: %siw)rr TypeErrorrrrisdirrmakedirsfdopenrO_WRONLYO_CREATtruncatewrite)r^rrfull_key file_contentrr1r1r4 __setitem__?s&     "zJSONFileCache.__setitem__cCstj|j|d}|S)Nz.json)rrjoinr)r^r full_pathr1r1r4rMsz JSONFileCache._convert_cache_key)r|r}r~rrr expanduserr CACHE_DIRr`rrrrrrr1r1r1r4rs  rc@s.eZdZdZ  d ddZddZddZdS) ra\ Holds the credentials needed to authenticate requests. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. NcCs0||_||_||_|durd}||_|dS)Nexplicit)rr r!method _normalize)r^rr r!rr1r1r4r`]s zCredentials.__init__cC$tj|j|_tj|j|_dSr/)botocorecompatensure_unicoderr rir1r1r4riszCredentials._normalizecCst|j|j|jSr/)rrr r!rir1r1r4get_frozen_credentialsssz"Credentials.get_frozen_credentialsNN)r|r}r~rr`rrr1r1r1r4rRs   rc@seZdZdZdZdZefddZddZe dd Z e d d Z e j d d Z e d dZej ddZe ddZej ddZddZd$ddZddZddZddZeddZd d!Zd"d#ZdS)%RefreshableCredentialsa Holds the credentials needed to authenticate requests. In addition, it knows how to refresh itself. :ivar access_key: The access key part of the credentials. :ivar secret_key: The secret key part of the credentials. :ivar token: The security token, valid only for session credentials. :ivar method: A string which identifies where the credentials were found. iXcCsN||_||_||_||_||_||_t|_||_ t ||||_ | dSr/) _refresh_using _access_key _secret_key_token _expiry_time _time_fetcher threadingLock _refresh_lockrr_frozen_credentialsr)r^rr r!r refresh_usingr time_fetcherr1r1r4r`s  zRefreshableCredentials.__init__cCrr/)rrrrrrir1r1r4rsz!RefreshableCredentials._normalizecCs.||d|d|d||d||d}|S)Nrr r!r)rr r!rrr)_expiry_datetime)clsmetadatarrinstancer1r1r4create_from_metadatas z+RefreshableCredentials.create_from_metadatacC||jSzWarning: Using this property can lead to race conditions if you access another property subsequently along the refresh boundary. Please use get_frozen_credentials instead. )rrrir1r1r4rz!RefreshableCredentials.access_keycC ||_dSr/)rr^rr1r1r4r cCrr)rrrir1r1r4r rz!RefreshableCredentials.secret_keycCrr/)rrr1r1r4r rcCrr)rrrir1r1r4r!rzRefreshableCredentials.tokencCrr/)rrr1r1r4r!rcCs|j|}t|Sr/)rrr )r^deltar1r1r4_seconds_remainingsz)RefreshableCredentials._seconds_remainingNcCs:|jdurdS|dur|j}||krdStddS)aCheck if a refresh is needed. A refresh is needed if the expiry time associated with the temporary credentials is less than the provided ``refresh_in``. If ``time_delta`` is not provided, ``self.advisory_refresh_needed`` will be used. For example, if your temporary credentials expire in 10 minutes and the provided ``refresh_in`` is ``15 * 60``, then this function will return ``True``. :type refresh_in: int :param refresh_in: The number of seconds before the credentials expire in which refresh attempts should be made. :return: True if refresh needed, False otherwise. NFz!Credentials need to be refreshed.T)r_advisory_refresh_timeoutrrLrMr^ refresh_inr1r1r4refresh_neededs   z%RefreshableCredentials.refresh_neededcCs |jddS)Nr)r)rrir1r1r4 _is_expireds z"RefreshableCredentials._is_expiredcCs||jsdS|jdr7z"||jsW|jdS||j}|j|dW|jdS|jw||jrh|j||jsP WddS|jddWddS1sawYdSdS)NF) is_mandatoryT)rrracquirerelease_mandatory_refresh_timeout_protected_refresh)r^is_mandatory_refreshr1r1r4rs*      "zRefreshableCredentials._refreshcCsz|}Wnty!|rdnd}tjd|dd|rYdSw||t|j|j|j|_ | r@d}t|t |dS)N mandatoryadvisoryzARefreshing temporary credentials failed during %s refresh period.Texc_infozLCredentials were refreshed, but the refreshed credentials are still expired.) r ExceptionrLwarning_set_from_datarrrrrr RuntimeError)r^rr period_namemsgr1r1r4rs(      z)RefreshableCredentials._protected_refreshcCst|Sr/r)time_strr1r1r4r9sz'RefreshableCredentials._expiry_datetimecsgd}s |}n fdd|D}|r"d}t|j|d|dd|_d|_d |_td |_t d |j| dS) Nrcsg|]}|vr|qSr1r1).0kdatar1r4 Bsz9RefreshableCredentials._set_from_data..z7Credential refresh failed, response did not contain: %s, provider error_msgrr r!rz(Retrieved credentials will expire at: %s) rrrrr r!rrrLrMr)r^r expected_keys missing_keysmessager1rr4r=s$     z%RefreshableCredentials._set_from_datacCr)aReturn immutable credentials. The ``access_key``, ``secret_key``, and ``token`` properties on this class will always check and refresh credentials if needed before returning the particular credentials. This has an edge case where you can get inconsistent credentials. Imagine this: # Current creds are "t1" tmp.access_key ---> expired? no, so return t1.access_key # ---- time is now expired, creds need refreshing to "t2" ---- tmp.secret_key ---> expired? yes, refresh and return t2.secret_key This means we're using the access key from t1 with the secret key from t2. To fix this issue, you can request a frozen credential object which is guaranteed not to change. The frozen credentials returned from this method should be used immediately and then discarded. The typical usage pattern would be:: creds = RefreshableCredentials(...) some_code = SomeSignerObject() # I'm about to sign the request. # The frozen credentials are only used for the # duration of generate_presigned_url and will be # immediately thrown away. request = some_code.sign_some_request( with_credentials=creds.get_frozen_credentials()) print("Signed request:", request) )rrrir1r1r4rSs"z-RefreshableCredentials.get_frozen_credentialsr/)r|r}r~rrrrr`r classmethodrpropertyrsetterr r!rrrrr staticmethodrrrr1r1r1r4rys<          "!  rcs.eZdZdZefddZdfdd ZZS)DeferredRefreshableCredentialszyRefreshable credentials that don't require initial credentials. refresh_using will be called upon first access. cCs>||_d|_d|_d|_d|_||_t|_||_ d|_ dSr/) rrrrrrrrrrr)r^rrrr1r1r4r`~s  z'DeferredRefreshableCredentials.__init__Ncs|jdurdStt||Sr)rsuperr#rr __class__r1r4rs  z-DeferredRefreshableCredentials.refresh_neededr/)r|r}r~rrr`r __classcell__r1r1r%r4r#ys  r#c@sZeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)CachedCredentialFetcherrNcCs4|duri}||_||_|dur|j}||_dSr/)r[_create_cache_key _cache_keyDEFAULT_EXPIRY_WINDOW_SECONDS_expiry_window_seconds)r^r-expiry_window_secondsr1r1r4r`s  z CachedCredentialFetcher.__init__cCtd)Nz_create_cache_key()NotImplementedErrorrir1r1r4r)z)CachedCredentialFetcher._create_cache_keycCs$|ddtjjd}|ddS)N:_/)replacerrsep)r^filenamer1r1r4_make_file_safes z'CachedCredentialFetcher._make_file_safecCr.)Nz_get_credentials()r/rir1r1r4_get_credentialsr1z(CachedCredentialFetcher._get_credentialscC|Sr/)_get_cached_credentialsrir1r1r4fetch_credentialsr1z)CachedCredentialFetcher.fetch_credentialscCs`|}|dur|}||ntd|d}t|ddd}|d|d|d |d S) zGet up-to-date credentials. This will check the cache for up-to-date credentials, calling assume role if none are available. Nz*Credentials for role retrieved from cache.rrT)rrrrr)_load_from_cacher9_write_to_cacherLrMr)r^rcreds expirationr1r1r4r;s  z/CachedCredentialFetcher._get_cached_credentialscCs8|j|jvrt|j|j}||s|StddS)Nz6Credentials were found in cache, but they are expired.)r*r[rrrLrM)r^r?r1r1r4r=s  z(CachedCredentialFetcher._load_from_cachecCst||j|j<dSr/)rr[r*)r^rr1r1r4r>sz'CachedCredentialFetcher._write_to_cachecCs(t|dd}t|t}||jkS)z!Check if credentials are expired.rr)rr rr,)r^rend_timesecondsr1r1r4rs z#CachedCredentialFetcher._is_expiredr) r|r}r~r+r`r)r8r9r<r;r=r>rr1r1r1r4r(s   r(cs2eZdZ  dfdd ZddZddZZS) BaseAssumeRoleCredentialFetcherNcsj||_||_|duri|_nt||_|j|jd<|jd|_d|_|js*|tt | ||dS)NRoleArnRoleSessionNameF) _client_creator _role_arn_assume_kwargsrrA_role_session_name_using_default_session_name_generate_assume_role_namer$rCr`)r^r7role_arn extra_argsr-r-r%r1r4r`s   z(BaseAssumeRoleCredentialFetcher.__init__cCs(dtt|_|j|jd<d|_dS)Nzbotocore-session-%srET)inttimerIrHrJrir1r1r4rKs  z:BaseAssumeRoleCredentialFetcher._generate_assume_role_namecCsZt|j}|jr |d=d|vrt|d|d<tj|dd}t|d}| |S)Create a predictable cache key for the current configuration. The cache key is intended to be compatible with file names. rEPolicyT) sort_keysutf-8) rrHrJrloadsrrencode hexdigestr8r^args argument_hashr1r1r4r)s  z1BaseAssumeRoleCredentialFetcher._create_cache_keyrz)r|r}r~r`rKr)r'r1r1r%r4rCs rCcs:eZdZ  d fdd ZddZddZdd ZZS) AssumeRoleCredentialFetcherNcs<||_||_|jdurtj|_tt|j|||||ddS)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, NrMr-r-)_source_credentials _mfa_promptergetpassr$rZr`)r^r7source_credentialsrLrM mfa_prompterr-r-r%r1r4r`s"   z$AssumeRoleCredentialFetcher.__init__cCs |}|}|jdi|S)'Get credentials by calling assume role.Nr1)_assume_role_kwargs_create_clientr)r^rrr1r1r4r94sz,AssumeRoleCredentialFetcher._get_credentialscCsTt|j}|d}|durd|}||}||d<|d}|dur(||d<|S)AGet the arguments for assume role based on current configuration. SerialNumberNzEnter MFA code for %s: TokenCodeDurationSeconds)rrHrAr])r^assume_role_kwargs mfa_serialprompt token_codeduration_secondsr1r1r4rb:s    z/AssumeRoleCredentialFetcher._assume_role_kwargscCs"|j}|jd|j|j|jdS)z2Create an STS client using the source credentials.sts)aws_access_key_idaws_secret_access_keyaws_session_token)r\rrFrr r!)r^frozen_credentialsr1r1r4rcLs z*AssumeRoleCredentialFetcher._create_client)NNNN)r|r}r~r`r9rbrcr'r1r1r%r4rZs,rZcs0eZdZ dfdd ZddZddZZS) *AssumeRoleWithWebIdentityCredentialFetcherNcs$||_tt|j|||||ddS)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$rrr`)r^r7web_identity_token_loaderrLrMr-r-r%r1r4r`Zs   z3AssumeRoleWithWebIdentityCredentialFetcher.__init__cCs0|}ttd}|jd|d}|jdi|S)ra)signature_versionrmr+Nr1)rbr r rFassume_role_with_web_identity)r^rr+rr1r1r4r9~s z;AssumeRoleWithWebIdentityCredentialFetcher._get_credentialscCst|j}|}||d<|S)rdWebIdentityToken)rrHrs)r^rhidentity_tokenr1r1r4rbs z>AssumeRoleWithWebIdentityCredentialFetcher._assume_role_kwargsrz)r|r}r~r`r9rbr'r1r1r%r4rrWs $ rrc@s.eZdZdZdZdddZddZddZdS) CredentialProviderNcCrr/r2)r^r3r1r1r4r` zCredentialProvider.__init__cCsdS)a~ Loads the credentials from their source & sets them on the object. Subclasses should implement this method (by reading from disk, the environment, the network or wherever), returning ``True`` if they were found & loaded. If not found, this method should return ``False``, indictating that the ``CredentialResolver`` should fall back to the next available method. The default implementation does nothing, assuming the user has set the ``access_key/secret_key/token`` themselves. :returns: Whether credentials were found & set :rtype: Credentials Tr1rir1r1r4rszCredentialProvider.loadc Gs@g}|D]}z |||Wqtyt|j|dw|S)Nrcred_var)appendrrMETHOD)r^mapping key_namesfoundkey_namer1r1r4_extract_creds_from_mappings z.CredentialProvider._extract_creds_from_mappingr/)r|r}r~rCANONICAL_NAMEr`rrr1r1r1r4rzs   rzc@s:eZdZdZejfddZddZddZe dd Z d S) rkzcustom-processcCs||_||_d|_||_dSr/) _profile_name _load_config_loaded_config_popen)r^r8r6popenr1r1r4r`s zProcessProvider.__init__csdjdur dS}|ddur"t|fddjSt|d|d|djdS)Nrcs Sr/)_retrieve_credentials_usingr1credential_processr^r1r4r5s z&ProcessProvider.load..rr r!)rr r!r)_credential_processrrArrrr)r^ creds_dictr1rr4rs   zProcessProvider.loadc Cst|}|j|tjtjd}|\}}|jdkr#t|j|ddt j j |d}| dd}|dkr@t|jd|dz|d |d | d | d d WStyg}z t|jd|dd}~ww)N)stdoutstderrrrSrVersionzzOUnsupported version '%s' for credential process provider, supported versions: 1rrrrrz$Missing required key in response: %s)r r subprocessPIPE communicate returncoderrdecoderrrrTrAr) r^r process_listprrparsedversioner1r1r4rs@    z+ProcessProvider._retrieve_credentials_usingcCs6|jdur ||_|jdi|ji}|dS)Nprofilesr)rrrAr)r^profile_configr1r1r4rs    z#ProcessProvider._credential_processN) r|r}r~rrPopenr`rrr rr1r1r1r4rksrkc@s$eZdZdZdZddZddZdS)rDziam-roleEc2InstanceMetadatacCrr/) _role_fetcher)r^r,r1r1r4r`r{z!InstanceMetadataProvider.__init__cCs>|j}|}|s dStd|dtj||j|jd}|S)Nz#Found credentials from IAM Role: %s role_namerr)rretrieve_iam_role_credentialsrLrMrrr)r^fetcherrr?r1r1r4r szInstanceMetadataProvider.loadN)r|r}r~rrr`rr1r1r1r4rDs  rDc@sJeZdZdZdZdZdZddgZdZdd d Z d d Z d dZ ddZ dS)rBenv EnvironmentAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SECURITY_TOKENAWS_SESSION_TOKENAWS_CREDENTIAL_EXPIRATIONNcCs$|durtj}||_|||_dS)a :param environ: The environment variables (defaults to ``os.environ`` if no value is provided). :param mapping: An optional mapping of variable names to environment variable names. Use this if you want to change the mapping of access_key->AWS_ACCESS_KEY_ID, etc. The dict can have up to 3 keys: ``access_key``, ``secret_key``, ``session_token``. N)renviron_build_mapping_mapping)r^rrr1r1r4r`)s zEnvProvider.__init__cCsi}|dur|j|d<|j|d<|j|d<|j|d<|S|d|j|d<|d|j|d<|d|j|d<t|dtsE|dg|d<|d|j|d<|S)Nrr r!r) ACCESS_KEY SECRET_KEYTOKENS EXPIRY_TIMErArlist)r^r var_mappingr1r1r4r9s,     zEnvProvider._build_mappingcCs|j|jdd}|rFtd|}|dd}|d}|dur7t|}t|d|d|d |||jd St |d|d|d |jd SdS) zK Search for credentials in explicit environment variables. rz+Found credentials in environment variables.F)require_expiryrNr r!)rrr) rrArrLinfo_create_credentials_fetcherrrrr)r^rrrrr1r1r4rOs$     zEnvProvider.loadcs(|j|j|jdfdd }|S)NTcsi}dd}|stdd||d<dd}|s*tdd||d<d|d<dD]}|d}|rF||d<nq6d|d<dd}|rY||d<|re|setdd|S)Nrrr|r r!r)rAr)rrrr token_env_varr!rrrrr1r4r<ps:  zBEnvProvider._create_credentials_fetcher..fetch_credentials)T)rrr)r^r<r1rr4rks  z'EnvProvider._create_credentials_fetcherr) r|r}r~rrrrrrr`rrrr1r1r1r4rBs  rBc@s2eZdZdZdZdZdZdZd ddZd d Z dS) rIzec2-credentials-file Ec2ConfigAWS_CREDENTIAL_FILEAWSAccessKeyId AWSSecretKeyNcCs*|durtj}|dur t}||_||_dSr/)rrr_environ_parser)r^rparserr1r1r4r`s  zOriginalEC2Provider.__init__cCsfd|jvr1tj|jd}||}|j|vr/td||j}||j}t |||j dSdSdS)zN Search for a credential file used by original EC2 CLI tools. rz)Found credentials in AWS_CREDENTIAL_FILE.rN) rrrrrrrLrrrr)r^rr?rr r1r1r4rs      zOriginalEC2Provider.loadr) r|r}r~rr CRED_FILE_ENVrrr`rr1r1r1r4rIs  rIc@s>eZdZdZdZdZdZddgZddd Zd d Z d d Z dS)rpzshared-credentials-fileSharedCredentialsrnroaws_security_tokenrpNcCs2||_|dur d}||_|durtjj}||_dS)Nr#)_creds_filenamerr configloaderraw_config_parse _ini_parser)r^ror8 ini_parserr1r1r4r`s z!SharedCredentialProvider.__init__cCsz||j}Wn tyYdSw|j|vrB||j}|j|vrDtd|j|||j|j\}}| |}t ||||j dSdSdS)Nz0Found credentials in shared credentials file: %sr) rrrrrrLrrr_get_session_tokenrr)r^available_credsr+rr r!r1r1r4rs(      zSharedCredentialProvider.loadcC$|jD] }||vr||SqdSr/r)r^r+ token_envvarr1r1r4r  z+SharedCredentialProvider._get_session_tokenr) r|r}r~rrrrrr`rrr1r1r1r4rps  rpc@sBeZdZdZdZdZdZdZddgZdd d Z d d Z d dZ dS)ruz0INI based config provider with profile sections.z config-file SharedConfigrnrorrpNcCs&||_||_|durtjj}||_dS)a :param config_filename: The session configuration scoped to the current profile. This is available via ``session.config``. :param profile_name: The name of the current profile. :param config_parser: A config parser callable. N)_config_filenamerrrr6_config_parser)r^rtr8 config_parserr1r1r4r`s   zConfigProvider.__init__cCsz||j}Wn tyYdSw|j|dvrH|d|j}|j|vrFtd|j|||j|j\}}| |}t ||||j dSdSdS)zr If there is are credentials in the configuration associated with the session, use those. Nrz$Credentials found in config file: %sr) rrrrrrLrrrrrr)r^r0rrr r!r1r1r4rs(     zConfigProvider.loadcCrr/r)r^r token_namer1r1r4rrz!ConfigProvider._get_session_tokenr/) r|r}r~rrrrrrr`rrr1r1r1r4rus  ruc@s:eZdZdZdZdZddgZdZdZd d d Z d d Z dS)rJz boto-config Boto2Config BOTO_CONFIGz /etc/boto.cfgz~/.botornroNcCs.|durtj}|durtjj}||_||_dSr/)rrrrrrr)r^rrr1r1r4r`s  zBotoProvider.__init__c Cs|j|jvr|j|jg}n|j}|D];}z||}Wn ty%Yqwd|vrN|d}|j|vrNtd||||j|j \}}t |||j dSqdS)z; Look for credentials in boto config file. rz)Found credentials in boto config file: %srN) BOTO_CONFIG_ENVrDEFAULT_CONFIG_FILENAMESrrrrLrrrrr)r^potential_locationsr7r+rrr r1r1r4r's.     zBotoProvider.loadr) r|r}r~rrrrrrr`rr1r1r1r4rJs  rJc@seZdZdZdZdZdZdZejddfddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZddZdS) rF assume-roleNrLweb_identity_token_filercCs>||_||_||_||_||_i|_||_||_|jg|_dS)a :type load_config: callable :param load_config: A function that accepts no arguments, and when called, will return the full configuration dictionary for the session (``session.full_config``). :type client_creator: callable :param client_creator: A factory function that will create a client when called. Has the same interface as ``botocore.session.Session.create_client``. :type cache: dict :param cache: An object that supports ``__getitem__``, ``__setitem__``, and ``__contains__``. An example of this is the ``JSONFileCache`` class in the CLI. :type profile_name: str :param profile_name: The name of the profile. :type prompter: callable :param prompter: A callable that returns input provided by the user (i.e raw_input, getpass.getpass, etc.). :type credential_sourcer: CanonicalNameCredentialSourcer :param credential_sourcer: A credential provider that takes a configuration, which is used to provide the source credentials for the STS call. N) r-rrFr _prompterr_credential_sourcer_profile_provider_builder_visited_profiles)r^r6r7r-r8prompterr9r:r1r1r4r`Os$zAssumeRoleProvider.__init__cCs@||_|jdi}||ji}||r||jSdSNr)rrrAr_has_assume_role_config_vars_load_creds_via_assume_role)r^rr"r1r1r4rs   zAssumeRoleProvider.loadcCs|j|vo |j|vSr/)ROLE_CONFIG_VARWEB_IDENTITY_TOKE_FILE_VARr^r"r1r1r4rs z/AssumeRoleProvider._has_assume_role_config_varsc Cs||}|||}i}|d}|dur||d<|d}|dur'||d<|d}|dur4||d<|d}|durA||d<t|j||d ||j|jd } | j} |dur[t| } t |j | t d S) Nrole_session_namerE external_id ExternalIdrirerlrgrL)r7r_rLrMr`r-)rrr) _get_role_config_resolve_source_credentialsrArZrFrr-r<rr#rr) r^r8 role_configr_rMrrrirlr refresherr1r1r4rsB     z.AssumeRoleProvider._load_creds_via_assume_rolec Cs|jdi}||}|d}|d}|d}|d}|d}|d} |d} |||| ||d } | d urLzt| | d<Wn tyKYnw|d ur[|d ur[td |d |d urj|d urjt|jd d|d urv|||| S|||| S)z?Retrieves and validates the role configuration for the profile.rsource_profilerLcredential_sourcerirrrl)rLrrirrrNzDThe profile "%s" contains both source_profile and credential_source.rz#source_profile or credential_sourcer|) rrArNrrrr_validate_credential_source_validate_source_profile) r^r8rr"rrLrrirrrlrr1r1r4rsP         z#AssumeRoleProvider._get_role_configcCs>|jdurtd||fd|j|std||fddS)Nz_The credential_source "%s" is specified in profile "%s", but no source provider was configured.rzCThe credential source "%s" referenced in profile "%s" is not valid.)rr is_supported)r^parent_profilerr1r1r4rs  z.AssumeRoleProvider._validate_credential_sourcecCst||||gSr/)any_has_static_credentialsrrr1r1r4_source_profile_has_credentialssz2AssumeRoleProvider._source_profile_has_credentialscCsp|jdi}||vrtd||fd||}||jvrdS||kr*t||jd||s6t||jddS)NrzFThe source_profile "%s" referenced in the profile "%s" does not exist.r)rvisited_profiles)rrArrrr)r^parent_profile_namesource_profile_namerrr1r1r4rs,  z+AssumeRoleProvider._validate_source_profilecsddg}tfdd|DS)Nrornc3s|]}|vVqdSr/r1)r static_keyr"r1r4 0z=AssumeRoleProvider._has_static_credentials..)r)r^r" static_keysr1rr4r.sz*AssumeRoleProvider._has_static_credentialscCs<|d}|dur|||S|d}|j|||S)Nrr)rA _resolve_credentials_from_sourcerr~!_resolve_credentials_from_profile)r^rr8rrr1r1r4r2s   z.AssumeRoleProvider._resolve_source_credentialscCs|jdi}||}||r|js||S||s"||sA|jj|dd}t|}|}|dur?d}t ||d|S| |S)NrTr;z.The source profile "%s" must have credentials.r) rrArr(_resolve_static_credentials_from_profilerr>rNrrr)r^r8rr"rV profile_chainr error_messager1r1r4r=s.    z4AssumeRoleProvider._resolve_credentials_from_profilec CsJzt|d|d|ddWSty$}z t|jt|dd}~ww)Nrnrorprr|)rrArrrstr)r^r"rr1r1r4r[s z;AssumeRoleProvider._resolve_static_credentials_from_profilecCs(|j|}|durt|d|d|S)NzBNo credentials found in credential_source referenced in profile %sr)rr_r)r^rr8rr1r1r4rfsz3AssumeRoleProvider._resolve_credentials_from_source)r|r}r~rrrrEXPIRY_WINDOW_SECONDSr^r`rrrrrrrrrrrrr1r1r1r4rF@s* 7 ,2 &  rFc@sXeZdZdZdZddddZ   ddd Zd d Zd d ZddZ ddZ ddZ dS)rvzassume-role-with-web-identityNAWS_WEB_IDENTITY_TOKEN_FILEAWS_ROLE_SESSION_NAME AWS_ROLE_ARN)rrrLFcCs:||_||_||_||_d|_||_|durt}||_dSr/)r-rrFr_profile_config_disable_env_varsr_token_loader_cls)r^r6r7r8r-r<token_loader_clsr1r1r4r`~s  z*AssumeRoleWithWebIdentityProvider.__init__cCr:r/)_assume_role_with_web_identityrir1r1r4rr1z&AssumeRoleWithWebIdentityProvider.loadcCs:|jdur|}|di}||ji|_|j|Sr)r rrAr)r^key loaded_configrr1r1r4_get_profile_configs   z5AssumeRoleWithWebIdentityProvider._get_profile_configcCs2|jrdS|j|}|r|tjvrtj|SdSr/)r_CONFIG_TO_ENV_VARrArr)r^renv_keyr1r1r4_get_env_configs   z1AssumeRoleWithWebIdentityProvider._get_env_configcCs ||}|dur |S||Sr/)rr)r^r env_valuer1r1r4 _get_configs  z-AssumeRoleWithWebIdentityProvider._get_configcCs||d}|s dS||}|d}|sd}t|di}|d}|dur+||d<t|j||||jd}t|j|jdS) NrrLzThe 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.rrrE)r7rtrLrMr-r) rrrrrrFr-r#rr<)r^ token_path token_loaderrLrrMrrr1r1r4rs0      z@AssumeRoleWithWebIdentityProvider._assume_role_with_web_identity)NFN) r|r}r~rrrr`rrrrrr1r1r1r4rvus    rvc@s<eZdZddZddZddZddZd d Zd d Zd S)rHcCrr/ _providersr^r>r1r1r4r`r{z'CanonicalNameCredentialSourcer.__init__cCs|dd|jDvS)aLValidates a given source name. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: bool :returns: True if the credential provider is supported, False otherwise. cSg|]}|jqSr1)rrrr1r1r4rz?CanonicalNameCredentialSourcer.is_supported..r)r^ source_namer1r1r4rs z+CanonicalNameCredentialSourcer.is_supportedcCs$||}t|tr|S|S)aLoads source credentials based on the provided configuration. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: Credentials ) _get_providerrrNrr)r^r"sourcer1r1r4r_s z1CanonicalNameCredentialSourcer.source_credentialscCsV||}|dvr |d}|dur |dur|St||gS|dur)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. ) sharedconfigsharedcredentialsrNname)_get_provider_by_canonical_namelower_get_provider_by_methodrNr)r^canonical_namerrTr1r1r4r#s    z,CanonicalNameCredentialSourcer._get_providercCs2|jD]}|j}|r||kr|SqdS)zReturn a credential provider by its canonical name. This function is strict, it does not attempt to address compatibility issues. N)rrr*)r^r,rr(r1r1r4r)s z>CanonicalNameCredentialSourcer._get_provider_by_canonical_namecCs"|jD] }|j|kr|SqdS)z0Return a credential provider by its METHOD name.N)rr)r^rrr1r1r4r+s  z6CanonicalNameCredentialSourcer._get_provider_by_methodN) r|r}r~r`rr_r#r)r+r1r1r1r4rHs & rHc@sReZdZdZdZdZdZdZdddZd d Z d d Z d dZ ddZ ddZ dS)rCzcontainer-role EcsContainer&AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"AWS_CONTAINER_CREDENTIALS_FULL_URI!AWS_CONTAINER_AUTHORIZATION_TOKENNcCs,|durtj}|durt}||_||_dSr/)rrrr_fetcher)r^rrr1r1r4r`-s  zContainerProvider.__init__cCs$|j|jvs |j|jvr|SdSr/)ENV_VARr ENV_VAR_FULL_retrieve_or_failrir1r1r4r5szContainerProvider.loadcCsn|r|j|j|j}n|j|j}|}|||}|}t|d|d|d|j t |d|dS)Nrr r!r)rr r!rrr) _provided_relative_urir1full_urlrr2r3_build_headers_create_fetcherrrr)r^full_uriheadersrr?r1r1r4r4;s   z#ContainerProvider._retrieve_or_failcCs"|j|j}|durd|iSdS)N Authorization)rrAENV_VAR_AUTH_TOKEN)r^ auth_tokenr1r1r4r7Ls z ContainerProvider._build_headerscsfdd}|S)Nc snz jjd}Wnty'}ztjd|ddtjt|dd}~ww|d|d|d|d d S) N)r:z'Error retrieving container metadata: %sTr rrrTokenrr)r1retrieve_full_urirrLrMrrr)rrr9r:r^r1r4 fetch_credsTs$ z6ContainerProvider._create_fetcher..fetch_credsr1)r^r9r:rAr1r@r4r8Ssz!ContainerProvider._create_fetchercCs |j|jvSr/)r2rrir1r1r4r5fs z(ContainerProvider._provided_relative_urir)r|r}r~rrr2r3r<r`rr4r7r8r5r1r1r1r4rC&s  rCc@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rNcCs ||_dS)zQ :param providers: A list of ``CredentialProvider`` instances. Nr=rr1r1r4r`ks zCredentialResolver.__init__cCsFz dd|jD|}Wn tyt|dw|j||dS)a= Inserts a new instance of ``CredentialProvider`` into the chain that will be tried before an existing one. :param name: The short name of the credentials you'd like to insert the new credentials before. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` cSrr1rr r1r1r4rr!z4CredentialResolver.insert_before..r'N)r>indexrrinsertr^r(credential_provideroffsetr1r1r4 insert_beforess   z CredentialResolver.insert_beforecCs ||}|j|d|dS)a9 Inserts a new type of ``Credentials`` instance into the chain that will be tried after an existing one. :param name: The short name of the credentials you'd like to insert the new credentials after. (ex. ``env`` or ``config``). Existing names & ordering can be discovered via ``self.available_methods``. :type name: string :param cred_instance: An instance of the new ``Credentials`` object you'd like to add to the chain. :type cred_instance: A subclass of ``Credentials`` rN)_get_provider_offsetr>rDrEr1r1r4 insert_afters zCredentialResolver.insert_aftercCs6dd|jD}||vrdS||}|j|dS)z Removes a given ``Credentials`` instance from the chain. :param name: The short name of the credentials instance to remove. :type name: string cSrr1rBr r1r1r4rr!z-CredentialResolver.remove..N)r>rCpop)r^r(available_methodsrGr1r1r4rKs  zCredentialResolver.removecCs|j||S)zReturn a credential provider by name. :type name: str :param name: The name of the provider. :raises UnknownCredentialError: Raised if no credential provider by the provided name is found. )r>rIr^r(r1r1r4 get_providers zCredentialResolver.get_providercCs2z dd|jD|WStyt|dw)NcSrr1rBr r1r1r4rr!z;CredentialResolver._get_provider_offset..r')r>rCrrrMr1r1r4rIs   z'CredentialResolver._get_provider_offsetcCs6|jD]}td|j|}|dur|SqdS)zw Goes through the credentials chain, returning the first ``Credentials`` that could be loaded. zLooking for credentials via: %sN)r>rLrMrr)r^rr?r1r1r4rs  z#CredentialResolver.load_credentialsN) r|r}r~r`rHrJrKrNrIrr1r1r1r4rNjs rNcs>eZdZdZ  d fdd ZddZddZd d ZZS) SSOCredentialFetcherz%Y-%m-%dT%H:%M:%SZNc s:||_||_||_||_||_||_tt|||dSr/) rF _sso_region _role_name _account_id _start_url _token_loaderr$rOr`) r^ start_url sso_regionr account_idr7rr-r-r%r1r4r`s zSSOCredentialFetcher.__init__cCs>|j|j|jd}tj|ddd}t|d}||S)rP)startUrlroleName accountIdT),r2)rR separatorsrS) rSrQrRrrrrUrVr8rWr1r1r4r)s  z&SSOCredentialFetcher._create_cache_keycCs$|d}tj|t}||jS)Ng@@)r fromtimestampr r_UTC_DATE_FORMAT)r^ timestamp_mstimestamp_seconds timestampr1r1r4_parse_timestamps z%SSOCredentialFetcher._parse_timestampcCstt|jd}|jd|d}|j|j||jd}z |jd i|}Wn |j j y0t w|d}d|d|d|d| |d d d }|S)z4Get credentials by calling SSO get role credentials.)rur.ssorv)rYrZ accessTokenroleCredentials accessKeyIdsecretAccessKey sessionTokenr@)rrrr) ProviderTyperNr1) r r rPrFrQrRrTrSget_role_credentials exceptionsUnauthorizedExceptionrrb)r^r+rrrrr1r1r4r9s.   z%SSOCredentialFetcher._get_credentialsrz) r|r}r~r^r`r)rbr9r'r1r1r%r4rOs rOc@sNeZdZdZejejddddZgdZ d ddZ d d Z d d Z dS)rxrcrrr-) sso_start_urlrV sso_role_namesso_account_idNcCs@|dur t|j}||_|duri}||_||_||_||_dSr/)r_SSO_TOKEN_CACHE_DIR _token_cacher-rrFr)r^r6r7r8r-rwr1r1r4r`#s  zSSOProvider.__init__cs|}|di}|j}||jitfdd|jDr"dSi}g}|jD]}|vr6|||<q)||q)|rLd|}td||fd|S)Nrc3s|]}|vVqdSr/r1)rcrr1r4r5rz/SSOProvider._load_sso_config..rzSThe profile "%s" is configured to use SSO but is missing required configuration: %sr)rrArall_SSO_CONFIG_VARSr~rr)r^rrr8r+missing_config_vars config_varmissingr1rsr4_load_sso_config/s(    zSSOProvider._load_sso_configc CsR|}|sdSt|d|d|d|d|jt|jd|jd}t|j|jdS)NrmrVrnro)r-)rr-r) ryrOrFrrqr-r#rr<)r^ sso_config sso_fetcherr1r1r4rKs   zSSOProvider.loadr) r|r}r~rrrrrrprur`ryrr1r1r1r4rxs  rxrr{)SrOrloggingrr^rrr collectionsrcopyrhashlibrpathlibrdateutil.parserr dateutil.tzrr botocore.configloaderrbotocore.compatr r r botocore.configr botocore.exceptionsrrrrrrrrrbotocore.utilsrrrrrr getLoggerr|rLrrYrrErrrrrGrrrrrr#r(rCrZrrrzrkrDrBrIrprurJrFrvrHrCrNrOrxr1r1r1r4s                         VD  ;'E1 P9-Ft"*7*7YXDdH