credentials.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  1. # Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
  2. # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"). You
  5. # may not use this file except in compliance with the License. A copy of
  6. # the License is located at
  7. #
  8. # http://aws.amazon.com/apache2.0/
  9. #
  10. # or in the "license" file accompanying this file. This file is
  11. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. # ANY KIND, either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the License.
  14. import time
  15. import datetime
  16. import logging
  17. import os
  18. import getpass
  19. import threading
  20. import json
  21. import subprocess
  22. from collections import namedtuple
  23. from copy import deepcopy
  24. from hashlib import sha1
  25. from dateutil.parser import parse
  26. from dateutil.tz import tzlocal, tzutc
  27. import botocore.configloader
  28. import botocore.compat
  29. from botocore import UNSIGNED
  30. from botocore.compat import total_seconds
  31. from botocore.compat import compat_shell_split
  32. from botocore.config import Config
  33. from botocore.exceptions import UnknownCredentialError
  34. from botocore.exceptions import PartialCredentialsError
  35. from botocore.exceptions import ConfigNotFound
  36. from botocore.exceptions import InvalidConfigError
  37. from botocore.exceptions import InfiniteLoopConfigError
  38. from botocore.exceptions import RefreshWithMFAUnsupportedError
  39. from botocore.exceptions import MetadataRetrievalError
  40. from botocore.exceptions import CredentialRetrievalError
  41. from botocore.exceptions import UnauthorizedSSOTokenError
  42. from botocore.utils import InstanceMetadataFetcher, parse_key_val_file
  43. from botocore.utils import ContainerMetadataFetcher
  44. from botocore.utils import FileWebIdentityTokenLoader
  45. from botocore.utils import SSOTokenLoader
  46. logger = logging.getLogger(__name__)
  47. ReadOnlyCredentials = namedtuple('ReadOnlyCredentials',
  48. ['access_key', 'secret_key', 'token'])
  49. def create_credential_resolver(session, cache=None, region_name=None):
  50. """Create a default credential resolver.
  51. This creates a pre-configured credential resolver
  52. that includes the default lookup chain for
  53. credentials.
  54. """
  55. profile_name = session.get_config_variable('profile') or 'default'
  56. metadata_timeout = session.get_config_variable('metadata_service_timeout')
  57. num_attempts = session.get_config_variable('metadata_service_num_attempts')
  58. disable_env_vars = session.instance_variables().get('profile') is not None
  59. imds_config = {
  60. 'ec2_metadata_service_endpoint': session.get_config_variable(
  61. 'ec2_metadata_service_endpoint'),
  62. 'imds_use_ipv6': session.get_config_variable('imds_use_ipv6')
  63. }
  64. if cache is None:
  65. cache = {}
  66. env_provider = EnvProvider()
  67. container_provider = ContainerProvider()
  68. instance_metadata_provider = InstanceMetadataProvider(
  69. iam_role_fetcher=InstanceMetadataFetcher(
  70. timeout=metadata_timeout,
  71. num_attempts=num_attempts,
  72. user_agent=session.user_agent(),
  73. config=imds_config)
  74. )
  75. profile_provider_builder = ProfileProviderBuilder(
  76. session, cache=cache, region_name=region_name)
  77. assume_role_provider = AssumeRoleProvider(
  78. load_config=lambda: session.full_config,
  79. client_creator=_get_client_creator(session, region_name),
  80. cache=cache,
  81. profile_name=profile_name,
  82. credential_sourcer=CanonicalNameCredentialSourcer([
  83. env_provider, container_provider, instance_metadata_provider
  84. ]),
  85. profile_provider_builder=profile_provider_builder,
  86. )
  87. pre_profile = [
  88. env_provider,
  89. assume_role_provider,
  90. ]
  91. profile_providers = profile_provider_builder.providers(
  92. profile_name=profile_name,
  93. disable_env_vars=disable_env_vars,
  94. )
  95. post_profile = [
  96. OriginalEC2Provider(),
  97. BotoProvider(),
  98. container_provider,
  99. instance_metadata_provider,
  100. ]
  101. providers = pre_profile + profile_providers + post_profile
  102. if disable_env_vars:
  103. # An explicitly provided profile will negate an EnvProvider.
  104. # We will defer to providers that understand the "profile"
  105. # concept to retrieve credentials.
  106. # The one edge case if is all three values are provided via
  107. # env vars:
  108. # export AWS_ACCESS_KEY_ID=foo
  109. # export AWS_SECRET_ACCESS_KEY=bar
  110. # export AWS_PROFILE=baz
  111. # Then, just like our client() calls, the explicit credentials
  112. # will take precedence.
  113. #
  114. # This precedence is enforced by leaving the EnvProvider in the chain.
  115. # This means that the only way a "profile" would win is if the
  116. # EnvProvider does not return credentials, which is what we want
  117. # in this scenario.
  118. providers.remove(env_provider)
  119. logger.debug('Skipping environment variable credential check'
  120. ' because profile name was explicitly set.')
  121. resolver = CredentialResolver(providers=providers)
  122. return resolver
  123. class ProfileProviderBuilder(object):
  124. """This class handles the creation of profile based providers.
  125. NOTE: This class is only intended for internal use.
  126. This class handles the creation and ordering of the various credential
  127. providers that primarly source their configuration from the shared config.
  128. This is needed to enable sharing between the default credential chain and
  129. the source profile chain created by the assume role provider.
  130. """
  131. def __init__(self, session, cache=None, region_name=None,
  132. sso_token_cache=None):
  133. self._session = session
  134. self._cache = cache
  135. self._region_name = region_name
  136. self._sso_token_cache = sso_token_cache
  137. def providers(self, profile_name, disable_env_vars=False):
  138. return [
  139. self._create_web_identity_provider(
  140. profile_name, disable_env_vars,
  141. ),
  142. self._create_sso_provider(profile_name),
  143. self._create_shared_credential_provider(profile_name),
  144. self._create_process_provider(profile_name),
  145. self._create_config_provider(profile_name),
  146. ]
  147. def _create_process_provider(self, profile_name):
  148. return ProcessProvider(
  149. profile_name=profile_name,
  150. load_config=lambda: self._session.full_config,
  151. )
  152. def _create_shared_credential_provider(self, profile_name):
  153. credential_file = self._session.get_config_variable('credentials_file')
  154. return SharedCredentialProvider(
  155. profile_name=profile_name,
  156. creds_filename=credential_file,
  157. )
  158. def _create_config_provider(self, profile_name):
  159. config_file = self._session.get_config_variable('config_file')
  160. return ConfigProvider(
  161. profile_name=profile_name,
  162. config_filename=config_file,
  163. )
  164. def _create_web_identity_provider(self, profile_name, disable_env_vars):
  165. return AssumeRoleWithWebIdentityProvider(
  166. load_config=lambda: self._session.full_config,
  167. client_creator=_get_client_creator(
  168. self._session, self._region_name),
  169. cache=self._cache,
  170. profile_name=profile_name,
  171. disable_env_vars=disable_env_vars,
  172. )
  173. def _create_sso_provider(self, profile_name):
  174. return SSOProvider(
  175. load_config=lambda: self._session.full_config,
  176. client_creator=self._session.create_client,
  177. profile_name=profile_name,
  178. cache=self._cache,
  179. token_cache=self._sso_token_cache,
  180. )
  181. def get_credentials(session):
  182. resolver = create_credential_resolver(session)
  183. return resolver.load_credentials()
  184. def _local_now():
  185. return datetime.datetime.now(tzlocal())
  186. def _parse_if_needed(value):
  187. if isinstance(value, datetime.datetime):
  188. return value
  189. return parse(value)
  190. def _serialize_if_needed(value, iso=False):
  191. if isinstance(value, datetime.datetime):
  192. if iso:
  193. return value.isoformat()
  194. return value.strftime('%Y-%m-%dT%H:%M:%S%Z')
  195. return value
  196. def _get_client_creator(session, region_name):
  197. def client_creator(service_name, **kwargs):
  198. create_client_kwargs = {
  199. 'region_name': region_name
  200. }
  201. create_client_kwargs.update(**kwargs)
  202. return session.create_client(service_name, **create_client_kwargs)
  203. return client_creator
  204. def create_assume_role_refresher(client, params):
  205. def refresh():
  206. response = client.assume_role(**params)
  207. credentials = response['Credentials']
  208. # We need to normalize the credential names to
  209. # the values expected by the refresh creds.
  210. return {
  211. 'access_key': credentials['AccessKeyId'],
  212. 'secret_key': credentials['SecretAccessKey'],
  213. 'token': credentials['SessionToken'],
  214. 'expiry_time': _serialize_if_needed(credentials['Expiration']),
  215. }
  216. return refresh
  217. def create_mfa_serial_refresher(actual_refresh):
  218. class _Refresher(object):
  219. def __init__(self, refresh):
  220. self._refresh = refresh
  221. self._has_been_called = False
  222. def __call__(self):
  223. if self._has_been_called:
  224. # We can explore an option in the future to support
  225. # reprompting for MFA, but for now we just error out
  226. # when the temp creds expire.
  227. raise RefreshWithMFAUnsupportedError()
  228. self._has_been_called = True
  229. return self._refresh()
  230. return _Refresher(actual_refresh)
  231. class JSONFileCache(object):
  232. """JSON file cache.
  233. This provides a dict like interface that stores JSON serializable
  234. objects.
  235. The objects are serialized to JSON and stored in a file. These
  236. values can be retrieved at a later time.
  237. """
  238. CACHE_DIR = os.path.expanduser(os.path.join('~', '.aws', 'boto', 'cache'))
  239. def __init__(self, working_dir=CACHE_DIR, dumps_func=None):
  240. self._working_dir = working_dir
  241. if dumps_func is None:
  242. dumps_func = self._default_dumps
  243. self._dumps = dumps_func
  244. def _default_dumps(self, obj):
  245. return json.dumps(obj, default=_serialize_if_needed)
  246. def __contains__(self, cache_key):
  247. actual_key = self._convert_cache_key(cache_key)
  248. return os.path.isfile(actual_key)
  249. def __getitem__(self, cache_key):
  250. """Retrieve value from a cache key."""
  251. actual_key = self._convert_cache_key(cache_key)
  252. try:
  253. with open(actual_key) as f:
  254. return json.load(f)
  255. except (OSError, ValueError, IOError):
  256. raise KeyError(cache_key)
  257. def __setitem__(self, cache_key, value):
  258. full_key = self._convert_cache_key(cache_key)
  259. try:
  260. file_content = self._dumps(value)
  261. except (TypeError, ValueError):
  262. raise ValueError("Value cannot be cached, must be "
  263. "JSON serializable: %s" % value)
  264. if not os.path.isdir(self._working_dir):
  265. os.makedirs(self._working_dir)
  266. with os.fdopen(os.open(full_key,
  267. os.O_WRONLY | os.O_CREAT, 0o600), 'w') as f:
  268. f.truncate()
  269. f.write(file_content)
  270. def _convert_cache_key(self, cache_key):
  271. full_path = os.path.join(self._working_dir, cache_key + '.json')
  272. return full_path
  273. class Credentials(object):
  274. """
  275. Holds the credentials needed to authenticate requests.
  276. :ivar access_key: The access key part of the credentials.
  277. :ivar secret_key: The secret key part of the credentials.
  278. :ivar token: The security token, valid only for session credentials.
  279. :ivar method: A string which identifies where the credentials
  280. were found.
  281. """
  282. def __init__(self, access_key, secret_key, token=None,
  283. method=None):
  284. self.access_key = access_key
  285. self.secret_key = secret_key
  286. self.token = token
  287. if method is None:
  288. method = 'explicit'
  289. self.method = method
  290. self._normalize()
  291. def _normalize(self):
  292. # Keys would sometimes (accidentally) contain non-ascii characters.
  293. # It would cause a confusing UnicodeDecodeError in Python 2.
  294. # We explicitly convert them into unicode to avoid such error.
  295. #
  296. # Eventually the service will decide whether to accept the credential.
  297. # This also complies with the behavior in Python 3.
  298. self.access_key = botocore.compat.ensure_unicode(self.access_key)
  299. self.secret_key = botocore.compat.ensure_unicode(self.secret_key)
  300. def get_frozen_credentials(self):
  301. return ReadOnlyCredentials(self.access_key,
  302. self.secret_key,
  303. self.token)
  304. class RefreshableCredentials(Credentials):
  305. """
  306. Holds the credentials needed to authenticate requests. In addition, it
  307. knows how to refresh itself.
  308. :ivar access_key: The access key part of the credentials.
  309. :ivar secret_key: The secret key part of the credentials.
  310. :ivar token: The security token, valid only for session credentials.
  311. :ivar method: A string which identifies where the credentials
  312. were found.
  313. """
  314. # The time at which we'll attempt to refresh, but not
  315. # block if someone else is refreshing.
  316. _advisory_refresh_timeout = 15 * 60
  317. # The time at which all threads will block waiting for
  318. # refreshed credentials.
  319. _mandatory_refresh_timeout = 10 * 60
  320. def __init__(self, access_key, secret_key, token,
  321. expiry_time, refresh_using, method,
  322. time_fetcher=_local_now):
  323. self._refresh_using = refresh_using
  324. self._access_key = access_key
  325. self._secret_key = secret_key
  326. self._token = token
  327. self._expiry_time = expiry_time
  328. self._time_fetcher = time_fetcher
  329. self._refresh_lock = threading.Lock()
  330. self.method = method
  331. self._frozen_credentials = ReadOnlyCredentials(
  332. access_key, secret_key, token)
  333. self._normalize()
  334. def _normalize(self):
  335. self._access_key = botocore.compat.ensure_unicode(self._access_key)
  336. self._secret_key = botocore.compat.ensure_unicode(self._secret_key)
  337. @classmethod
  338. def create_from_metadata(cls, metadata, refresh_using, method):
  339. instance = cls(
  340. access_key=metadata['access_key'],
  341. secret_key=metadata['secret_key'],
  342. token=metadata['token'],
  343. expiry_time=cls._expiry_datetime(metadata['expiry_time']),
  344. method=method,
  345. refresh_using=refresh_using
  346. )
  347. return instance
  348. @property
  349. def access_key(self):
  350. """Warning: Using this property can lead to race conditions if you
  351. access another property subsequently along the refresh boundary.
  352. Please use get_frozen_credentials instead.
  353. """
  354. self._refresh()
  355. return self._access_key
  356. @access_key.setter
  357. def access_key(self, value):
  358. self._access_key = value
  359. @property
  360. def secret_key(self):
  361. """Warning: Using this property can lead to race conditions if you
  362. access another property subsequently along the refresh boundary.
  363. Please use get_frozen_credentials instead.
  364. """
  365. self._refresh()
  366. return self._secret_key
  367. @secret_key.setter
  368. def secret_key(self, value):
  369. self._secret_key = value
  370. @property
  371. def token(self):
  372. """Warning: Using this property can lead to race conditions if you
  373. access another property subsequently along the refresh boundary.
  374. Please use get_frozen_credentials instead.
  375. """
  376. self._refresh()
  377. return self._token
  378. @token.setter
  379. def token(self, value):
  380. self._token = value
  381. def _seconds_remaining(self):
  382. delta = self._expiry_time - self._time_fetcher()
  383. return total_seconds(delta)
  384. def refresh_needed(self, refresh_in=None):
  385. """Check if a refresh is needed.
  386. A refresh is needed if the expiry time associated
  387. with the temporary credentials is less than the
  388. provided ``refresh_in``. If ``time_delta`` is not
  389. provided, ``self.advisory_refresh_needed`` will be used.
  390. For example, if your temporary credentials expire
  391. in 10 minutes and the provided ``refresh_in`` is
  392. ``15 * 60``, then this function will return ``True``.
  393. :type refresh_in: int
  394. :param refresh_in: The number of seconds before the
  395. credentials expire in which refresh attempts should
  396. be made.
  397. :return: True if refresh needed, False otherwise.
  398. """
  399. if self._expiry_time is None:
  400. # No expiration, so assume we don't need to refresh.
  401. return False
  402. if refresh_in is None:
  403. refresh_in = self._advisory_refresh_timeout
  404. # The credentials should be refreshed if they're going to expire
  405. # in less than 5 minutes.
  406. if self._seconds_remaining() >= refresh_in:
  407. # There's enough time left. Don't refresh.
  408. return False
  409. logger.debug("Credentials need to be refreshed.")
  410. return True
  411. def _is_expired(self):
  412. # Checks if the current credentials are expired.
  413. return self.refresh_needed(refresh_in=0)
  414. def _refresh(self):
  415. # In the common case where we don't need a refresh, we
  416. # can immediately exit and not require acquiring the
  417. # refresh lock.
  418. if not self.refresh_needed(self._advisory_refresh_timeout):
  419. return
  420. # acquire() doesn't accept kwargs, but False is indicating
  421. # that we should not block if we can't acquire the lock.
  422. # If we aren't able to acquire the lock, we'll trigger
  423. # the else clause.
  424. if self._refresh_lock.acquire(False):
  425. try:
  426. if not self.refresh_needed(self._advisory_refresh_timeout):
  427. return
  428. is_mandatory_refresh = self.refresh_needed(
  429. self._mandatory_refresh_timeout)
  430. self._protected_refresh(is_mandatory=is_mandatory_refresh)
  431. return
  432. finally:
  433. self._refresh_lock.release()
  434. elif self.refresh_needed(self._mandatory_refresh_timeout):
  435. # If we're within the mandatory refresh window,
  436. # we must block until we get refreshed credentials.
  437. with self._refresh_lock:
  438. if not self.refresh_needed(self._mandatory_refresh_timeout):
  439. return
  440. self._protected_refresh(is_mandatory=True)
  441. def _protected_refresh(self, is_mandatory):
  442. # precondition: this method should only be called if you've acquired
  443. # the self._refresh_lock.
  444. try:
  445. metadata = self._refresh_using()
  446. except Exception as e:
  447. period_name = 'mandatory' if is_mandatory else 'advisory'
  448. logger.warning("Refreshing temporary credentials failed "
  449. "during %s refresh period.",
  450. period_name, exc_info=True)
  451. if is_mandatory:
  452. # If this is a mandatory refresh, then
  453. # all errors that occur when we attempt to refresh
  454. # credentials are propagated back to the user.
  455. raise
  456. # Otherwise we'll just return.
  457. # The end result will be that we'll use the current
  458. # set of temporary credentials we have.
  459. return
  460. self._set_from_data(metadata)
  461. self._frozen_credentials = ReadOnlyCredentials(
  462. self._access_key, self._secret_key, self._token)
  463. if self._is_expired():
  464. # We successfully refreshed credentials but for whatever
  465. # reason, our refreshing function returned credentials
  466. # that are still expired. In this scenario, the only
  467. # thing we can do is let the user know and raise
  468. # an exception.
  469. msg = ("Credentials were refreshed, but the "
  470. "refreshed credentials are still expired.")
  471. logger.warning(msg)
  472. raise RuntimeError(msg)
  473. @staticmethod
  474. def _expiry_datetime(time_str):
  475. return parse(time_str)
  476. def _set_from_data(self, data):
  477. expected_keys = ['access_key', 'secret_key', 'token', 'expiry_time']
  478. if not data:
  479. missing_keys = expected_keys
  480. else:
  481. missing_keys = [k for k in expected_keys if k not in data]
  482. if missing_keys:
  483. message = "Credential refresh failed, response did not contain: %s"
  484. raise CredentialRetrievalError(
  485. provider=self.method,
  486. error_msg=message % ', '.join(missing_keys),
  487. )
  488. self.access_key = data['access_key']
  489. self.secret_key = data['secret_key']
  490. self.token = data['token']
  491. self._expiry_time = parse(data['expiry_time'])
  492. logger.debug("Retrieved credentials will expire at: %s",
  493. self._expiry_time)
  494. self._normalize()
  495. def get_frozen_credentials(self):
  496. """Return immutable credentials.
  497. The ``access_key``, ``secret_key``, and ``token`` properties
  498. on this class will always check and refresh credentials if
  499. needed before returning the particular credentials.
  500. This has an edge case where you can get inconsistent
  501. credentials. Imagine this:
  502. # Current creds are "t1"
  503. tmp.access_key ---> expired? no, so return t1.access_key
  504. # ---- time is now expired, creds need refreshing to "t2" ----
  505. tmp.secret_key ---> expired? yes, refresh and return t2.secret_key
  506. This means we're using the access key from t1 with the secret key
  507. from t2. To fix this issue, you can request a frozen credential object
  508. which is guaranteed not to change.
  509. The frozen credentials returned from this method should be used
  510. immediately and then discarded. The typical usage pattern would
  511. be::
  512. creds = RefreshableCredentials(...)
  513. some_code = SomeSignerObject()
  514. # I'm about to sign the request.
  515. # The frozen credentials are only used for the
  516. # duration of generate_presigned_url and will be
  517. # immediately thrown away.
  518. request = some_code.sign_some_request(
  519. with_credentials=creds.get_frozen_credentials())
  520. print("Signed request:", request)
  521. """
  522. self._refresh()
  523. return self._frozen_credentials
  524. class DeferredRefreshableCredentials(RefreshableCredentials):
  525. """Refreshable credentials that don't require initial credentials.
  526. refresh_using will be called upon first access.
  527. """
  528. def __init__(self, refresh_using, method, time_fetcher=_local_now):
  529. self._refresh_using = refresh_using
  530. self._access_key = None
  531. self._secret_key = None
  532. self._token = None
  533. self._expiry_time = None
  534. self._time_fetcher = time_fetcher
  535. self._refresh_lock = threading.Lock()
  536. self.method = method
  537. self._frozen_credentials = None
  538. def refresh_needed(self, refresh_in=None):
  539. if self._frozen_credentials is None:
  540. return True
  541. return super(DeferredRefreshableCredentials, self).refresh_needed(
  542. refresh_in
  543. )
  544. class CachedCredentialFetcher(object):
  545. DEFAULT_EXPIRY_WINDOW_SECONDS = 60 * 15
  546. def __init__(self, cache=None, expiry_window_seconds=None):
  547. if cache is None:
  548. cache = {}
  549. self._cache = cache
  550. self._cache_key = self._create_cache_key()
  551. if expiry_window_seconds is None:
  552. expiry_window_seconds = self.DEFAULT_EXPIRY_WINDOW_SECONDS
  553. self._expiry_window_seconds = expiry_window_seconds
  554. def _create_cache_key(self):
  555. raise NotImplementedError('_create_cache_key()')
  556. def _make_file_safe(self, filename):
  557. # Replace :, path sep, and / to make it the string filename safe.
  558. filename = filename.replace(':', '_').replace(os.path.sep, '_')
  559. return filename.replace('/', '_')
  560. def _get_credentials(self):
  561. raise NotImplementedError('_get_credentials()')
  562. def fetch_credentials(self):
  563. return self._get_cached_credentials()
  564. def _get_cached_credentials(self):
  565. """Get up-to-date credentials.
  566. This will check the cache for up-to-date credentials, calling assume
  567. role if none are available.
  568. """
  569. response = self._load_from_cache()
  570. if response is None:
  571. response = self._get_credentials()
  572. self._write_to_cache(response)
  573. else:
  574. logger.debug("Credentials for role retrieved from cache.")
  575. creds = response['Credentials']
  576. expiration = _serialize_if_needed(creds['Expiration'], iso=True)
  577. return {
  578. 'access_key': creds['AccessKeyId'],
  579. 'secret_key': creds['SecretAccessKey'],
  580. 'token': creds['SessionToken'],
  581. 'expiry_time': expiration,
  582. }
  583. def _load_from_cache(self):
  584. if self._cache_key in self._cache:
  585. creds = deepcopy(self._cache[self._cache_key])
  586. if not self._is_expired(creds):
  587. return creds
  588. else:
  589. logger.debug(
  590. "Credentials were found in cache, but they are expired."
  591. )
  592. return None
  593. def _write_to_cache(self, response):
  594. self._cache[self._cache_key] = deepcopy(response)
  595. def _is_expired(self, credentials):
  596. """Check if credentials are expired."""
  597. end_time = _parse_if_needed(credentials['Credentials']['Expiration'])
  598. seconds = total_seconds(end_time - _local_now())
  599. return seconds < self._expiry_window_seconds
  600. class BaseAssumeRoleCredentialFetcher(CachedCredentialFetcher):
  601. def __init__(self, client_creator, role_arn, extra_args=None,
  602. cache=None, expiry_window_seconds=None):
  603. self._client_creator = client_creator
  604. self._role_arn = role_arn
  605. if extra_args is None:
  606. self._assume_kwargs = {}
  607. else:
  608. self._assume_kwargs = deepcopy(extra_args)
  609. self._assume_kwargs['RoleArn'] = self._role_arn
  610. self._role_session_name = self._assume_kwargs.get('RoleSessionName')
  611. self._using_default_session_name = False
  612. if not self._role_session_name:
  613. self._generate_assume_role_name()
  614. super(BaseAssumeRoleCredentialFetcher, self).__init__(
  615. cache, expiry_window_seconds
  616. )
  617. def _generate_assume_role_name(self):
  618. self._role_session_name = 'botocore-session-%s' % (int(time.time()))
  619. self._assume_kwargs['RoleSessionName'] = self._role_session_name
  620. self._using_default_session_name = True
  621. def _create_cache_key(self):
  622. """Create a predictable cache key for the current configuration.
  623. The cache key is intended to be compatible with file names.
  624. """
  625. args = deepcopy(self._assume_kwargs)
  626. # The role session name gets randomly generated, so we don't want it
  627. # in the hash.
  628. if self._using_default_session_name:
  629. del args['RoleSessionName']
  630. if 'Policy' in args:
  631. # To have a predictable hash, the keys of the policy must be
  632. # sorted, so we have to load it here to make sure it gets sorted
  633. # later on.
  634. args['Policy'] = json.loads(args['Policy'])
  635. args = json.dumps(args, sort_keys=True)
  636. argument_hash = sha1(args.encode('utf-8')).hexdigest()
  637. return self._make_file_safe(argument_hash)
  638. class AssumeRoleCredentialFetcher(BaseAssumeRoleCredentialFetcher):
  639. def __init__(self, client_creator, source_credentials, role_arn,
  640. extra_args=None, mfa_prompter=None, cache=None,
  641. expiry_window_seconds=None):
  642. """
  643. :type client_creator: callable
  644. :param client_creator: A callable that creates a client taking
  645. arguments like ``Session.create_client``.
  646. :type source_credentials: Credentials
  647. :param source_credentials: The credentials to use to create the
  648. client for the call to AssumeRole.
  649. :type role_arn: str
  650. :param role_arn: The ARN of the role to be assumed.
  651. :type extra_args: dict
  652. :param extra_args: Any additional arguments to add to the assume
  653. role request using the format of the botocore operation.
  654. Possible keys include, but may not be limited to,
  655. DurationSeconds, Policy, SerialNumber, ExternalId and
  656. RoleSessionName.
  657. :type mfa_prompter: callable
  658. :param mfa_prompter: A callable that returns input provided by the
  659. user (i.e raw_input, getpass.getpass, etc.).
  660. :type cache: dict
  661. :param cache: An object that supports ``__getitem__``,
  662. ``__setitem__``, and ``__contains__``. An example of this is
  663. the ``JSONFileCache`` class in aws-cli.
  664. :type expiry_window_seconds: int
  665. :param expiry_window_seconds: The amount of time, in seconds,
  666. """
  667. self._source_credentials = source_credentials
  668. self._mfa_prompter = mfa_prompter
  669. if self._mfa_prompter is None:
  670. self._mfa_prompter = getpass.getpass
  671. super(AssumeRoleCredentialFetcher, self).__init__(
  672. client_creator, role_arn, extra_args=extra_args,
  673. cache=cache, expiry_window_seconds=expiry_window_seconds
  674. )
  675. def _get_credentials(self):
  676. """Get credentials by calling assume role."""
  677. kwargs = self._assume_role_kwargs()
  678. client = self._create_client()
  679. return client.assume_role(**kwargs)
  680. def _assume_role_kwargs(self):
  681. """Get the arguments for assume role based on current configuration."""
  682. assume_role_kwargs = deepcopy(self._assume_kwargs)
  683. mfa_serial = assume_role_kwargs.get('SerialNumber')
  684. if mfa_serial is not None:
  685. prompt = 'Enter MFA code for %s: ' % mfa_serial
  686. token_code = self._mfa_prompter(prompt)
  687. assume_role_kwargs['TokenCode'] = token_code
  688. duration_seconds = assume_role_kwargs.get('DurationSeconds')
  689. if duration_seconds is not None:
  690. assume_role_kwargs['DurationSeconds'] = duration_seconds
  691. return assume_role_kwargs
  692. def _create_client(self):
  693. """Create an STS client using the source credentials."""
  694. frozen_credentials = self._source_credentials.get_frozen_credentials()
  695. return self._client_creator(
  696. 'sts',
  697. aws_access_key_id=frozen_credentials.access_key,
  698. aws_secret_access_key=frozen_credentials.secret_key,
  699. aws_session_token=frozen_credentials.token,
  700. )
  701. class AssumeRoleWithWebIdentityCredentialFetcher(
  702. BaseAssumeRoleCredentialFetcher
  703. ):
  704. def __init__(self, client_creator, web_identity_token_loader, role_arn,
  705. extra_args=None, cache=None, expiry_window_seconds=None):
  706. """
  707. :type client_creator: callable
  708. :param client_creator: A callable that creates a client taking
  709. arguments like ``Session.create_client``.
  710. :type web_identity_token_loader: callable
  711. :param web_identity_token_loader: A callable that takes no arguments
  712. and returns a web identity token str.
  713. :type role_arn: str
  714. :param role_arn: The ARN of the role to be assumed.
  715. :type extra_args: dict
  716. :param extra_args: Any additional arguments to add to the assume
  717. role request using the format of the botocore operation.
  718. Possible keys include, but may not be limited to,
  719. DurationSeconds, Policy, SerialNumber, ExternalId and
  720. RoleSessionName.
  721. :type cache: dict
  722. :param cache: An object that supports ``__getitem__``,
  723. ``__setitem__``, and ``__contains__``. An example of this is
  724. the ``JSONFileCache`` class in aws-cli.
  725. :type expiry_window_seconds: int
  726. :param expiry_window_seconds: The amount of time, in seconds,
  727. """
  728. self._web_identity_token_loader = web_identity_token_loader
  729. super(AssumeRoleWithWebIdentityCredentialFetcher, self).__init__(
  730. client_creator, role_arn, extra_args=extra_args,
  731. cache=cache, expiry_window_seconds=expiry_window_seconds
  732. )
  733. def _get_credentials(self):
  734. """Get credentials by calling assume role."""
  735. kwargs = self._assume_role_kwargs()
  736. # Assume role with web identity does not require credentials other than
  737. # the token, explicitly configure the client to not sign requests.
  738. config = Config(signature_version=UNSIGNED)
  739. client = self._client_creator('sts', config=config)
  740. return client.assume_role_with_web_identity(**kwargs)
  741. def _assume_role_kwargs(self):
  742. """Get the arguments for assume role based on current configuration."""
  743. assume_role_kwargs = deepcopy(self._assume_kwargs)
  744. identity_token = self._web_identity_token_loader()
  745. assume_role_kwargs['WebIdentityToken'] = identity_token
  746. return assume_role_kwargs
  747. class CredentialProvider(object):
  748. # A short name to identify the provider within botocore.
  749. METHOD = None
  750. # A name to identify the provider for use in cross-sdk features like
  751. # assume role's `credential_source` configuration option. These names
  752. # are to be treated in a case-insensitive way. NOTE: any providers not
  753. # implemented in botocore MUST prefix their canonical names with
  754. # 'custom' or we DO NOT guarantee that it will work with any features
  755. # that this provides.
  756. CANONICAL_NAME = None
  757. def __init__(self, session=None):
  758. self.session = session
  759. def load(self):
  760. """
  761. Loads the credentials from their source & sets them on the object.
  762. Subclasses should implement this method (by reading from disk, the
  763. environment, the network or wherever), returning ``True`` if they were
  764. found & loaded.
  765. If not found, this method should return ``False``, indictating that the
  766. ``CredentialResolver`` should fall back to the next available method.
  767. The default implementation does nothing, assuming the user has set the
  768. ``access_key/secret_key/token`` themselves.
  769. :returns: Whether credentials were found & set
  770. :rtype: Credentials
  771. """
  772. return True
  773. def _extract_creds_from_mapping(self, mapping, *key_names):
  774. found = []
  775. for key_name in key_names:
  776. try:
  777. found.append(mapping[key_name])
  778. except KeyError:
  779. raise PartialCredentialsError(provider=self.METHOD,
  780. cred_var=key_name)
  781. return found
  782. class ProcessProvider(CredentialProvider):
  783. METHOD = 'custom-process'
  784. def __init__(self, profile_name, load_config, popen=subprocess.Popen):
  785. self._profile_name = profile_name
  786. self._load_config = load_config
  787. self._loaded_config = None
  788. self._popen = popen
  789. def load(self):
  790. credential_process = self._credential_process
  791. if credential_process is None:
  792. return
  793. creds_dict = self._retrieve_credentials_using(credential_process)
  794. if creds_dict.get('expiry_time') is not None:
  795. return RefreshableCredentials.create_from_metadata(
  796. creds_dict,
  797. lambda: self._retrieve_credentials_using(credential_process),
  798. self.METHOD
  799. )
  800. return Credentials(
  801. access_key=creds_dict['access_key'],
  802. secret_key=creds_dict['secret_key'],
  803. token=creds_dict.get('token'),
  804. method=self.METHOD
  805. )
  806. def _retrieve_credentials_using(self, credential_process):
  807. # We're not using shell=True, so we need to pass the
  808. # command and all arguments as a list.
  809. process_list = compat_shell_split(credential_process)
  810. p = self._popen(process_list,
  811. stdout=subprocess.PIPE,
  812. stderr=subprocess.PIPE)
  813. stdout, stderr = p.communicate()
  814. if p.returncode != 0:
  815. raise CredentialRetrievalError(
  816. provider=self.METHOD, error_msg=stderr.decode('utf-8'))
  817. parsed = botocore.compat.json.loads(stdout.decode('utf-8'))
  818. version = parsed.get('Version', '<Version key not provided>')
  819. if version != 1:
  820. raise CredentialRetrievalError(
  821. provider=self.METHOD,
  822. error_msg=("Unsupported version '%s' for credential process "
  823. "provider, supported versions: 1" % version))
  824. try:
  825. return {
  826. 'access_key': parsed['AccessKeyId'],
  827. 'secret_key': parsed['SecretAccessKey'],
  828. 'token': parsed.get('SessionToken'),
  829. 'expiry_time': parsed.get('Expiration'),
  830. }
  831. except KeyError as e:
  832. raise CredentialRetrievalError(
  833. provider=self.METHOD,
  834. error_msg="Missing required key in response: %s" % e
  835. )
  836. @property
  837. def _credential_process(self):
  838. if self._loaded_config is None:
  839. self._loaded_config = self._load_config()
  840. profile_config = self._loaded_config.get(
  841. 'profiles', {}).get(self._profile_name, {})
  842. return profile_config.get('credential_process')
  843. class InstanceMetadataProvider(CredentialProvider):
  844. METHOD = 'iam-role'
  845. CANONICAL_NAME = 'Ec2InstanceMetadata'
  846. def __init__(self, iam_role_fetcher):
  847. self._role_fetcher = iam_role_fetcher
  848. def load(self):
  849. fetcher = self._role_fetcher
  850. # We do the first request, to see if we get useful data back.
  851. # If not, we'll pass & move on to whatever's next in the credential
  852. # chain.
  853. metadata = fetcher.retrieve_iam_role_credentials()
  854. if not metadata:
  855. return None
  856. logger.debug('Found credentials from IAM Role: %s',
  857. metadata['role_name'])
  858. # We manually set the data here, since we already made the request &
  859. # have it. When the expiry is hit, the credentials will auto-refresh
  860. # themselves.
  861. creds = RefreshableCredentials.create_from_metadata(
  862. metadata,
  863. method=self.METHOD,
  864. refresh_using=fetcher.retrieve_iam_role_credentials,
  865. )
  866. return creds
  867. class EnvProvider(CredentialProvider):
  868. METHOD = 'env'
  869. CANONICAL_NAME = 'Environment'
  870. ACCESS_KEY = 'AWS_ACCESS_KEY_ID'
  871. SECRET_KEY = 'AWS_SECRET_ACCESS_KEY'
  872. # The token can come from either of these env var.
  873. # AWS_SESSION_TOKEN is what other AWS SDKs have standardized on.
  874. TOKENS = ['AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']
  875. EXPIRY_TIME = 'AWS_CREDENTIAL_EXPIRATION'
  876. def __init__(self, environ=None, mapping=None):
  877. """
  878. :param environ: The environment variables (defaults to
  879. ``os.environ`` if no value is provided).
  880. :param mapping: An optional mapping of variable names to
  881. environment variable names. Use this if you want to
  882. change the mapping of access_key->AWS_ACCESS_KEY_ID, etc.
  883. The dict can have up to 3 keys: ``access_key``, ``secret_key``,
  884. ``session_token``.
  885. """
  886. if environ is None:
  887. environ = os.environ
  888. self.environ = environ
  889. self._mapping = self._build_mapping(mapping)
  890. def _build_mapping(self, mapping):
  891. # Mapping of variable name to env var name.
  892. var_mapping = {}
  893. if mapping is None:
  894. # Use the class var default.
  895. var_mapping['access_key'] = self.ACCESS_KEY
  896. var_mapping['secret_key'] = self.SECRET_KEY
  897. var_mapping['token'] = self.TOKENS
  898. var_mapping['expiry_time'] = self.EXPIRY_TIME
  899. else:
  900. var_mapping['access_key'] = mapping.get(
  901. 'access_key', self.ACCESS_KEY)
  902. var_mapping['secret_key'] = mapping.get(
  903. 'secret_key', self.SECRET_KEY)
  904. var_mapping['token'] = mapping.get(
  905. 'token', self.TOKENS)
  906. if not isinstance(var_mapping['token'], list):
  907. var_mapping['token'] = [var_mapping['token']]
  908. var_mapping['expiry_time'] = mapping.get(
  909. 'expiry_time', self.EXPIRY_TIME)
  910. return var_mapping
  911. def load(self):
  912. """
  913. Search for credentials in explicit environment variables.
  914. """
  915. access_key = self.environ.get(self._mapping['access_key'], '')
  916. if access_key:
  917. logger.info('Found credentials in environment variables.')
  918. fetcher = self._create_credentials_fetcher()
  919. credentials = fetcher(require_expiry=False)
  920. expiry_time = credentials['expiry_time']
  921. if expiry_time is not None:
  922. expiry_time = parse(expiry_time)
  923. return RefreshableCredentials(
  924. credentials['access_key'], credentials['secret_key'],
  925. credentials['token'], expiry_time,
  926. refresh_using=fetcher, method=self.METHOD
  927. )
  928. return Credentials(
  929. credentials['access_key'], credentials['secret_key'],
  930. credentials['token'], method=self.METHOD
  931. )
  932. else:
  933. return None
  934. def _create_credentials_fetcher(self):
  935. mapping = self._mapping
  936. method = self.METHOD
  937. environ = self.environ
  938. def fetch_credentials(require_expiry=True):
  939. credentials = {}
  940. access_key = environ.get(mapping['access_key'], '')
  941. if not access_key:
  942. raise PartialCredentialsError(
  943. provider=method, cred_var=mapping['access_key'])
  944. credentials['access_key'] = access_key
  945. secret_key = environ.get(mapping['secret_key'], '')
  946. if not secret_key:
  947. raise PartialCredentialsError(
  948. provider=method, cred_var=mapping['secret_key'])
  949. credentials['secret_key'] = secret_key
  950. credentials['token'] = None
  951. for token_env_var in mapping['token']:
  952. token = environ.get(token_env_var, '')
  953. if token:
  954. credentials['token'] = token
  955. break
  956. credentials['expiry_time'] = None
  957. expiry_time = environ.get(mapping['expiry_time'], '')
  958. if expiry_time:
  959. credentials['expiry_time'] = expiry_time
  960. if require_expiry and not expiry_time:
  961. raise PartialCredentialsError(
  962. provider=method, cred_var=mapping['expiry_time'])
  963. return credentials
  964. return fetch_credentials
  965. class OriginalEC2Provider(CredentialProvider):
  966. METHOD = 'ec2-credentials-file'
  967. CANONICAL_NAME = 'Ec2Config'
  968. CRED_FILE_ENV = 'AWS_CREDENTIAL_FILE'
  969. ACCESS_KEY = 'AWSAccessKeyId'
  970. SECRET_KEY = 'AWSSecretKey'
  971. def __init__(self, environ=None, parser=None):
  972. if environ is None:
  973. environ = os.environ
  974. if parser is None:
  975. parser = parse_key_val_file
  976. self._environ = environ
  977. self._parser = parser
  978. def load(self):
  979. """
  980. Search for a credential file used by original EC2 CLI tools.
  981. """
  982. if 'AWS_CREDENTIAL_FILE' in self._environ:
  983. full_path = os.path.expanduser(
  984. self._environ['AWS_CREDENTIAL_FILE'])
  985. creds = self._parser(full_path)
  986. if self.ACCESS_KEY in creds:
  987. logger.info('Found credentials in AWS_CREDENTIAL_FILE.')
  988. access_key = creds[self.ACCESS_KEY]
  989. secret_key = creds[self.SECRET_KEY]
  990. # EC2 creds file doesn't support session tokens.
  991. return Credentials(access_key, secret_key, method=self.METHOD)
  992. else:
  993. return None
  994. class SharedCredentialProvider(CredentialProvider):
  995. METHOD = 'shared-credentials-file'
  996. CANONICAL_NAME = 'SharedCredentials'
  997. ACCESS_KEY = 'aws_access_key_id'
  998. SECRET_KEY = 'aws_secret_access_key'
  999. # Same deal as the EnvProvider above. Botocore originally supported
  1000. # aws_security_token, but the SDKs are standardizing on aws_session_token
  1001. # so we support both.
  1002. TOKENS = ['aws_security_token', 'aws_session_token']
  1003. def __init__(self, creds_filename, profile_name=None, ini_parser=None):
  1004. self._creds_filename = creds_filename
  1005. if profile_name is None:
  1006. profile_name = 'default'
  1007. self._profile_name = profile_name
  1008. if ini_parser is None:
  1009. ini_parser = botocore.configloader.raw_config_parse
  1010. self._ini_parser = ini_parser
  1011. def load(self):
  1012. try:
  1013. available_creds = self._ini_parser(self._creds_filename)
  1014. except ConfigNotFound:
  1015. return None
  1016. if self._profile_name in available_creds:
  1017. config = available_creds[self._profile_name]
  1018. if self.ACCESS_KEY in config:
  1019. logger.info("Found credentials in shared credentials file: %s",
  1020. self._creds_filename)
  1021. access_key, secret_key = self._extract_creds_from_mapping(
  1022. config, self.ACCESS_KEY, self.SECRET_KEY)
  1023. token = self._get_session_token(config)
  1024. return Credentials(access_key, secret_key, token,
  1025. method=self.METHOD)
  1026. def _get_session_token(self, config):
  1027. for token_envvar in self.TOKENS:
  1028. if token_envvar in config:
  1029. return config[token_envvar]
  1030. class ConfigProvider(CredentialProvider):
  1031. """INI based config provider with profile sections."""
  1032. METHOD = 'config-file'
  1033. CANONICAL_NAME = 'SharedConfig'
  1034. ACCESS_KEY = 'aws_access_key_id'
  1035. SECRET_KEY = 'aws_secret_access_key'
  1036. # Same deal as the EnvProvider above. Botocore originally supported
  1037. # aws_security_token, but the SDKs are standardizing on aws_session_token
  1038. # so we support both.
  1039. TOKENS = ['aws_security_token', 'aws_session_token']
  1040. def __init__(self, config_filename, profile_name, config_parser=None):
  1041. """
  1042. :param config_filename: The session configuration scoped to the current
  1043. profile. This is available via ``session.config``.
  1044. :param profile_name: The name of the current profile.
  1045. :param config_parser: A config parser callable.
  1046. """
  1047. self._config_filename = config_filename
  1048. self._profile_name = profile_name
  1049. if config_parser is None:
  1050. config_parser = botocore.configloader.load_config
  1051. self._config_parser = config_parser
  1052. def load(self):
  1053. """
  1054. If there is are credentials in the configuration associated with
  1055. the session, use those.
  1056. """
  1057. try:
  1058. full_config = self._config_parser(self._config_filename)
  1059. except ConfigNotFound:
  1060. return None
  1061. if self._profile_name in full_config['profiles']:
  1062. profile_config = full_config['profiles'][self._profile_name]
  1063. if self.ACCESS_KEY in profile_config:
  1064. logger.info("Credentials found in config file: %s",
  1065. self._config_filename)
  1066. access_key, secret_key = self._extract_creds_from_mapping(
  1067. profile_config, self.ACCESS_KEY, self.SECRET_KEY)
  1068. token = self._get_session_token(profile_config)
  1069. return Credentials(access_key, secret_key, token,
  1070. method=self.METHOD)
  1071. else:
  1072. return None
  1073. def _get_session_token(self, profile_config):
  1074. for token_name in self.TOKENS:
  1075. if token_name in profile_config:
  1076. return profile_config[token_name]
  1077. class BotoProvider(CredentialProvider):
  1078. METHOD = 'boto-config'
  1079. CANONICAL_NAME = 'Boto2Config'
  1080. BOTO_CONFIG_ENV = 'BOTO_CONFIG'
  1081. DEFAULT_CONFIG_FILENAMES = ['/etc/boto.cfg', '~/.boto']
  1082. ACCESS_KEY = 'aws_access_key_id'
  1083. SECRET_KEY = 'aws_secret_access_key'
  1084. def __init__(self, environ=None, ini_parser=None):
  1085. if environ is None:
  1086. environ = os.environ
  1087. if ini_parser is None:
  1088. ini_parser = botocore.configloader.raw_config_parse
  1089. self._environ = environ
  1090. self._ini_parser = ini_parser
  1091. def load(self):
  1092. """
  1093. Look for credentials in boto config file.
  1094. """
  1095. if self.BOTO_CONFIG_ENV in self._environ:
  1096. potential_locations = [self._environ[self.BOTO_CONFIG_ENV]]
  1097. else:
  1098. potential_locations = self.DEFAULT_CONFIG_FILENAMES
  1099. for filename in potential_locations:
  1100. try:
  1101. config = self._ini_parser(filename)
  1102. except ConfigNotFound:
  1103. # Move on to the next potential config file name.
  1104. continue
  1105. if 'Credentials' in config:
  1106. credentials = config['Credentials']
  1107. if self.ACCESS_KEY in credentials:
  1108. logger.info("Found credentials in boto config file: %s",
  1109. filename)
  1110. access_key, secret_key = self._extract_creds_from_mapping(
  1111. credentials, self.ACCESS_KEY, self.SECRET_KEY)
  1112. return Credentials(access_key, secret_key,
  1113. method=self.METHOD)
  1114. class AssumeRoleProvider(CredentialProvider):
  1115. METHOD = 'assume-role'
  1116. # The AssumeRole provider is logically part of the SharedConfig and
  1117. # SharedCredentials providers. Since the purpose of the canonical name
  1118. # is to provide cross-sdk compatibility, calling code will need to be
  1119. # aware that either of those providers should be tied to the AssumeRole
  1120. # provider as much as possible.
  1121. CANONICAL_NAME = None
  1122. ROLE_CONFIG_VAR = 'role_arn'
  1123. WEB_IDENTITY_TOKE_FILE_VAR = 'web_identity_token_file'
  1124. # Credentials are considered expired (and will be refreshed) once the total
  1125. # remaining time left until the credentials expires is less than the
  1126. # EXPIRY_WINDOW.
  1127. EXPIRY_WINDOW_SECONDS = 60 * 15
  1128. def __init__(self, load_config, client_creator, cache, profile_name,
  1129. prompter=getpass.getpass, credential_sourcer=None,
  1130. profile_provider_builder=None):
  1131. """
  1132. :type load_config: callable
  1133. :param load_config: A function that accepts no arguments, and
  1134. when called, will return the full configuration dictionary
  1135. for the session (``session.full_config``).
  1136. :type client_creator: callable
  1137. :param client_creator: A factory function that will create
  1138. a client when called. Has the same interface as
  1139. ``botocore.session.Session.create_client``.
  1140. :type cache: dict
  1141. :param cache: An object that supports ``__getitem__``,
  1142. ``__setitem__``, and ``__contains__``. An example
  1143. of this is the ``JSONFileCache`` class in the CLI.
  1144. :type profile_name: str
  1145. :param profile_name: The name of the profile.
  1146. :type prompter: callable
  1147. :param prompter: A callable that returns input provided
  1148. by the user (i.e raw_input, getpass.getpass, etc.).
  1149. :type credential_sourcer: CanonicalNameCredentialSourcer
  1150. :param credential_sourcer: A credential provider that takes a
  1151. configuration, which is used to provide the source credentials
  1152. for the STS call.
  1153. """
  1154. #: The cache used to first check for assumed credentials.
  1155. #: This is checked before making the AssumeRole API
  1156. #: calls and can be useful if you have short lived
  1157. #: scripts and you'd like to avoid calling AssumeRole
  1158. #: until the credentials are expired.
  1159. self.cache = cache
  1160. self._load_config = load_config
  1161. # client_creator is a callable that creates function.
  1162. # It's basically session.create_client
  1163. self._client_creator = client_creator
  1164. self._profile_name = profile_name
  1165. self._prompter = prompter
  1166. # The _loaded_config attribute will be populated from the
  1167. # load_config() function once the configuration is actually
  1168. # loaded. The reason we go through all this instead of just
  1169. # requiring that the loaded_config be passed to us is to that
  1170. # we can defer configuration loaded until we actually try
  1171. # to load credentials (as opposed to when the object is
  1172. # instantiated).
  1173. self._loaded_config = {}
  1174. self._credential_sourcer = credential_sourcer
  1175. self._profile_provider_builder = profile_provider_builder
  1176. self._visited_profiles = [self._profile_name]
  1177. def load(self):
  1178. self._loaded_config = self._load_config()
  1179. profiles = self._loaded_config.get('profiles', {})
  1180. profile = profiles.get(self._profile_name, {})
  1181. if self._has_assume_role_config_vars(profile):
  1182. return self._load_creds_via_assume_role(self._profile_name)
  1183. def _has_assume_role_config_vars(self, profile):
  1184. return (
  1185. self.ROLE_CONFIG_VAR in profile and
  1186. # We need to ensure this provider doesn't look at a profile when
  1187. # the profile has configuration for web identity. Simply relying on
  1188. # the order in the credential chain is insufficient as it doesn't
  1189. # prevent the case when we're doing an assume role chain.
  1190. self.WEB_IDENTITY_TOKE_FILE_VAR not in profile
  1191. )
  1192. def _load_creds_via_assume_role(self, profile_name):
  1193. role_config = self._get_role_config(profile_name)
  1194. source_credentials = self._resolve_source_credentials(
  1195. role_config, profile_name
  1196. )
  1197. extra_args = {}
  1198. role_session_name = role_config.get('role_session_name')
  1199. if role_session_name is not None:
  1200. extra_args['RoleSessionName'] = role_session_name
  1201. external_id = role_config.get('external_id')
  1202. if external_id is not None:
  1203. extra_args['ExternalId'] = external_id
  1204. mfa_serial = role_config.get('mfa_serial')
  1205. if mfa_serial is not None:
  1206. extra_args['SerialNumber'] = mfa_serial
  1207. duration_seconds = role_config.get('duration_seconds')
  1208. if duration_seconds is not None:
  1209. extra_args['DurationSeconds'] = duration_seconds
  1210. fetcher = AssumeRoleCredentialFetcher(
  1211. client_creator=self._client_creator,
  1212. source_credentials=source_credentials,
  1213. role_arn=role_config['role_arn'],
  1214. extra_args=extra_args,
  1215. mfa_prompter=self._prompter,
  1216. cache=self.cache,
  1217. )
  1218. refresher = fetcher.fetch_credentials
  1219. if mfa_serial is not None:
  1220. refresher = create_mfa_serial_refresher(refresher)
  1221. # The initial credentials are empty and the expiration time is set
  1222. # to now so that we can delay the call to assume role until it is
  1223. # strictly needed.
  1224. return DeferredRefreshableCredentials(
  1225. method=self.METHOD,
  1226. refresh_using=refresher,
  1227. time_fetcher=_local_now
  1228. )
  1229. def _get_role_config(self, profile_name):
  1230. """Retrieves and validates the role configuration for the profile."""
  1231. profiles = self._loaded_config.get('profiles', {})
  1232. profile = profiles[profile_name]
  1233. source_profile = profile.get('source_profile')
  1234. role_arn = profile['role_arn']
  1235. credential_source = profile.get('credential_source')
  1236. mfa_serial = profile.get('mfa_serial')
  1237. external_id = profile.get('external_id')
  1238. role_session_name = profile.get('role_session_name')
  1239. duration_seconds = profile.get('duration_seconds')
  1240. role_config = {
  1241. 'role_arn': role_arn,
  1242. 'external_id': external_id,
  1243. 'mfa_serial': mfa_serial,
  1244. 'role_session_name': role_session_name,
  1245. 'source_profile': source_profile,
  1246. 'credential_source': credential_source
  1247. }
  1248. if duration_seconds is not None:
  1249. try:
  1250. role_config['duration_seconds'] = int(duration_seconds)
  1251. except ValueError:
  1252. pass
  1253. # Either the credential source or the source profile must be
  1254. # specified, but not both.
  1255. if credential_source is not None and source_profile is not None:
  1256. raise InvalidConfigError(
  1257. error_msg=(
  1258. 'The profile "%s" contains both source_profile and '
  1259. 'credential_source.' % profile_name
  1260. )
  1261. )
  1262. elif credential_source is None and source_profile is None:
  1263. raise PartialCredentialsError(
  1264. provider=self.METHOD,
  1265. cred_var='source_profile or credential_source'
  1266. )
  1267. elif credential_source is not None:
  1268. self._validate_credential_source(
  1269. profile_name, credential_source)
  1270. else:
  1271. self._validate_source_profile(profile_name, source_profile)
  1272. return role_config
  1273. def _validate_credential_source(self, parent_profile, credential_source):
  1274. if self._credential_sourcer is None:
  1275. raise InvalidConfigError(error_msg=(
  1276. 'The credential_source "%s" is specified in profile "%s", '
  1277. 'but no source provider was configured.' % (
  1278. credential_source, parent_profile)
  1279. ))
  1280. if not self._credential_sourcer.is_supported(credential_source):
  1281. raise InvalidConfigError(error_msg=(
  1282. 'The credential source "%s" referenced in profile "%s" is not '
  1283. 'valid.' % (credential_source, parent_profile)
  1284. ))
  1285. def _source_profile_has_credentials(self, profile):
  1286. return any([
  1287. self._has_static_credentials(profile),
  1288. self._has_assume_role_config_vars(profile),
  1289. ])
  1290. def _validate_source_profile(self, parent_profile_name,
  1291. source_profile_name):
  1292. profiles = self._loaded_config.get('profiles', {})
  1293. if source_profile_name not in profiles:
  1294. raise InvalidConfigError(
  1295. error_msg=(
  1296. 'The source_profile "%s" referenced in '
  1297. 'the profile "%s" does not exist.' % (
  1298. source_profile_name, parent_profile_name)
  1299. )
  1300. )
  1301. source_profile = profiles[source_profile_name]
  1302. # Make sure we aren't going into an infinite loop. If we haven't
  1303. # visited the profile yet, we're good.
  1304. if source_profile_name not in self._visited_profiles:
  1305. return
  1306. # If we have visited the profile and the profile isn't simply
  1307. # referencing itself, that's an infinite loop.
  1308. if source_profile_name != parent_profile_name:
  1309. raise InfiniteLoopConfigError(
  1310. source_profile=source_profile_name,
  1311. visited_profiles=self._visited_profiles
  1312. )
  1313. # A profile is allowed to reference itself so that it can source
  1314. # static credentials and have configuration all in the same
  1315. # profile. This will only ever work for the top level assume
  1316. # role because the static credentials will otherwise take
  1317. # precedence.
  1318. if not self._has_static_credentials(source_profile):
  1319. raise InfiniteLoopConfigError(
  1320. source_profile=source_profile_name,
  1321. visited_profiles=self._visited_profiles
  1322. )
  1323. def _has_static_credentials(self, profile):
  1324. static_keys = ['aws_secret_access_key', 'aws_access_key_id']
  1325. return any(static_key in profile for static_key in static_keys)
  1326. def _resolve_source_credentials(self, role_config, profile_name):
  1327. credential_source = role_config.get('credential_source')
  1328. if credential_source is not None:
  1329. return self._resolve_credentials_from_source(
  1330. credential_source, profile_name
  1331. )
  1332. source_profile = role_config['source_profile']
  1333. self._visited_profiles.append(source_profile)
  1334. return self._resolve_credentials_from_profile(source_profile)
  1335. def _resolve_credentials_from_profile(self, profile_name):
  1336. profiles = self._loaded_config.get('profiles', {})
  1337. profile = profiles[profile_name]
  1338. if self._has_static_credentials(profile) and \
  1339. not self._profile_provider_builder:
  1340. # This is only here for backwards compatibility. If this provider
  1341. # isn't given a profile provider builder we still want to be able
  1342. # handle the basic static credential case as we would before the
  1343. # provile provider builder parameter was added.
  1344. return self._resolve_static_credentials_from_profile(profile)
  1345. elif self._has_static_credentials(profile) or \
  1346. not self._has_assume_role_config_vars(profile):
  1347. profile_providers = self._profile_provider_builder.providers(
  1348. profile_name=profile_name,
  1349. disable_env_vars=True,
  1350. )
  1351. profile_chain = CredentialResolver(profile_providers)
  1352. credentials = profile_chain.load_credentials()
  1353. if credentials is None:
  1354. error_message = (
  1355. 'The source profile "%s" must have credentials.'
  1356. )
  1357. raise InvalidConfigError(
  1358. error_msg=error_message % profile_name,
  1359. )
  1360. return credentials
  1361. return self._load_creds_via_assume_role(profile_name)
  1362. def _resolve_static_credentials_from_profile(self, profile):
  1363. try:
  1364. return Credentials(
  1365. access_key=profile['aws_access_key_id'],
  1366. secret_key=profile['aws_secret_access_key'],
  1367. token=profile.get('aws_session_token')
  1368. )
  1369. except KeyError as e:
  1370. raise PartialCredentialsError(
  1371. provider=self.METHOD, cred_var=str(e))
  1372. def _resolve_credentials_from_source(self, credential_source,
  1373. profile_name):
  1374. credentials = self._credential_sourcer.source_credentials(
  1375. credential_source)
  1376. if credentials is None:
  1377. raise CredentialRetrievalError(
  1378. provider=credential_source,
  1379. error_msg=(
  1380. 'No credentials found in credential_source referenced '
  1381. 'in profile %s' % profile_name
  1382. )
  1383. )
  1384. return credentials
  1385. class AssumeRoleWithWebIdentityProvider(CredentialProvider):
  1386. METHOD = 'assume-role-with-web-identity'
  1387. CANONICAL_NAME = None
  1388. _CONFIG_TO_ENV_VAR = {
  1389. 'web_identity_token_file': 'AWS_WEB_IDENTITY_TOKEN_FILE',
  1390. 'role_session_name': 'AWS_ROLE_SESSION_NAME',
  1391. 'role_arn': 'AWS_ROLE_ARN',
  1392. }
  1393. def __init__(
  1394. self,
  1395. load_config,
  1396. client_creator,
  1397. profile_name,
  1398. cache=None,
  1399. disable_env_vars=False,
  1400. token_loader_cls=None,
  1401. ):
  1402. self.cache = cache
  1403. self._load_config = load_config
  1404. self._client_creator = client_creator
  1405. self._profile_name = profile_name
  1406. self._profile_config = None
  1407. self._disable_env_vars = disable_env_vars
  1408. if token_loader_cls is None:
  1409. token_loader_cls = FileWebIdentityTokenLoader
  1410. self._token_loader_cls = token_loader_cls
  1411. def load(self):
  1412. return self._assume_role_with_web_identity()
  1413. def _get_profile_config(self, key):
  1414. if self._profile_config is None:
  1415. loaded_config = self._load_config()
  1416. profiles = loaded_config.get('profiles', {})
  1417. self._profile_config = profiles.get(self._profile_name, {})
  1418. return self._profile_config.get(key)
  1419. def _get_env_config(self, key):
  1420. if self._disable_env_vars:
  1421. return None
  1422. env_key = self._CONFIG_TO_ENV_VAR.get(key)
  1423. if env_key and env_key in os.environ:
  1424. return os.environ[env_key]
  1425. return None
  1426. def _get_config(self, key):
  1427. env_value = self._get_env_config(key)
  1428. if env_value is not None:
  1429. return env_value
  1430. return self._get_profile_config(key)
  1431. def _assume_role_with_web_identity(self):
  1432. token_path = self._get_config('web_identity_token_file')
  1433. if not token_path:
  1434. return None
  1435. token_loader = self._token_loader_cls(token_path)
  1436. role_arn = self._get_config('role_arn')
  1437. if not role_arn:
  1438. error_msg = (
  1439. 'The provided profile or the current environment is '
  1440. 'configured to assume role with web identity but has no '
  1441. 'role ARN configured. Ensure that the profile has the role_arn'
  1442. 'configuration set or the AWS_ROLE_ARN env var is set.'
  1443. )
  1444. raise InvalidConfigError(error_msg=error_msg)
  1445. extra_args = {}
  1446. role_session_name = self._get_config('role_session_name')
  1447. if role_session_name is not None:
  1448. extra_args['RoleSessionName'] = role_session_name
  1449. fetcher = AssumeRoleWithWebIdentityCredentialFetcher(
  1450. client_creator=self._client_creator,
  1451. web_identity_token_loader=token_loader,
  1452. role_arn=role_arn,
  1453. extra_args=extra_args,
  1454. cache=self.cache,
  1455. )
  1456. # The initial credentials are empty and the expiration time is set
  1457. # to now so that we can delay the call to assume role until it is
  1458. # strictly needed.
  1459. return DeferredRefreshableCredentials(
  1460. method=self.METHOD,
  1461. refresh_using=fetcher.fetch_credentials,
  1462. )
  1463. class CanonicalNameCredentialSourcer(object):
  1464. def __init__(self, providers):
  1465. self._providers = providers
  1466. def is_supported(self, source_name):
  1467. """Validates a given source name.
  1468. :type source_name: str
  1469. :param source_name: The value of credential_source in the config
  1470. file. This is the canonical name of the credential provider.
  1471. :rtype: bool
  1472. :returns: True if the credential provider is supported,
  1473. False otherwise.
  1474. """
  1475. return source_name in [p.CANONICAL_NAME for p in self._providers]
  1476. def source_credentials(self, source_name):
  1477. """Loads source credentials based on the provided configuration.
  1478. :type source_name: str
  1479. :param source_name: The value of credential_source in the config
  1480. file. This is the canonical name of the credential provider.
  1481. :rtype: Credentials
  1482. """
  1483. source = self._get_provider(source_name)
  1484. if isinstance(source, CredentialResolver):
  1485. return source.load_credentials()
  1486. return source.load()
  1487. def _get_provider(self, canonical_name):
  1488. """Return a credential provider by its canonical name.
  1489. :type canonical_name: str
  1490. :param canonical_name: The canonical name of the provider.
  1491. :raises UnknownCredentialError: Raised if no
  1492. credential provider by the provided name
  1493. is found.
  1494. """
  1495. provider = self._get_provider_by_canonical_name(canonical_name)
  1496. # The AssumeRole provider should really be part of the SharedConfig
  1497. # provider rather than being its own thing, but it is not. It is
  1498. # effectively part of both the SharedConfig provider and the
  1499. # SharedCredentials provider now due to the way it behaves.
  1500. # Therefore if we want either of those providers we should return
  1501. # the AssumeRole provider with it.
  1502. if canonical_name.lower() in ['sharedconfig', 'sharedcredentials']:
  1503. assume_role_provider = self._get_provider_by_method('assume-role')
  1504. if assume_role_provider is not None:
  1505. # The SharedConfig or SharedCredentials provider may not be
  1506. # present if it was removed for some reason, but the
  1507. # AssumeRole provider could still be present. In that case,
  1508. # return the assume role provider by itself.
  1509. if provider is None:
  1510. return assume_role_provider
  1511. # If both are present, return them both as a
  1512. # CredentialResolver so that calling code can treat them as
  1513. # a single entity.
  1514. return CredentialResolver([assume_role_provider, provider])
  1515. if provider is None:
  1516. raise UnknownCredentialError(name=canonical_name)
  1517. return provider
  1518. def _get_provider_by_canonical_name(self, canonical_name):
  1519. """Return a credential provider by its canonical name.
  1520. This function is strict, it does not attempt to address
  1521. compatibility issues.
  1522. """
  1523. for provider in self._providers:
  1524. name = provider.CANONICAL_NAME
  1525. # Canonical names are case-insensitive
  1526. if name and name.lower() == canonical_name.lower():
  1527. return provider
  1528. def _get_provider_by_method(self, method):
  1529. """Return a credential provider by its METHOD name."""
  1530. for provider in self._providers:
  1531. if provider.METHOD == method:
  1532. return provider
  1533. class ContainerProvider(CredentialProvider):
  1534. METHOD = 'container-role'
  1535. CANONICAL_NAME = 'EcsContainer'
  1536. ENV_VAR = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'
  1537. ENV_VAR_FULL = 'AWS_CONTAINER_CREDENTIALS_FULL_URI'
  1538. ENV_VAR_AUTH_TOKEN = 'AWS_CONTAINER_AUTHORIZATION_TOKEN'
  1539. def __init__(self, environ=None, fetcher=None):
  1540. if environ is None:
  1541. environ = os.environ
  1542. if fetcher is None:
  1543. fetcher = ContainerMetadataFetcher()
  1544. self._environ = environ
  1545. self._fetcher = fetcher
  1546. def load(self):
  1547. # This cred provider is only triggered if the self.ENV_VAR is set,
  1548. # which only happens if you opt into this feature.
  1549. if self.ENV_VAR in self._environ or self.ENV_VAR_FULL in self._environ:
  1550. return self._retrieve_or_fail()
  1551. def _retrieve_or_fail(self):
  1552. if self._provided_relative_uri():
  1553. full_uri = self._fetcher.full_url(self._environ[self.ENV_VAR])
  1554. else:
  1555. full_uri = self._environ[self.ENV_VAR_FULL]
  1556. headers = self._build_headers()
  1557. fetcher = self._create_fetcher(full_uri, headers)
  1558. creds = fetcher()
  1559. return RefreshableCredentials(
  1560. access_key=creds['access_key'],
  1561. secret_key=creds['secret_key'],
  1562. token=creds['token'],
  1563. method=self.METHOD,
  1564. expiry_time=_parse_if_needed(creds['expiry_time']),
  1565. refresh_using=fetcher,
  1566. )
  1567. def _build_headers(self):
  1568. headers = {}
  1569. auth_token = self._environ.get(self.ENV_VAR_AUTH_TOKEN)
  1570. if auth_token is not None:
  1571. return {
  1572. 'Authorization': auth_token
  1573. }
  1574. def _create_fetcher(self, full_uri, headers):
  1575. def fetch_creds():
  1576. try:
  1577. response = self._fetcher.retrieve_full_uri(
  1578. full_uri, headers=headers)
  1579. except MetadataRetrievalError as e:
  1580. logger.debug("Error retrieving container metadata: %s", e,
  1581. exc_info=True)
  1582. raise CredentialRetrievalError(provider=self.METHOD,
  1583. error_msg=str(e))
  1584. return {
  1585. 'access_key': response['AccessKeyId'],
  1586. 'secret_key': response['SecretAccessKey'],
  1587. 'token': response['Token'],
  1588. 'expiry_time': response['Expiration'],
  1589. }
  1590. return fetch_creds
  1591. def _provided_relative_uri(self):
  1592. return self.ENV_VAR in self._environ
  1593. class CredentialResolver(object):
  1594. def __init__(self, providers):
  1595. """
  1596. :param providers: A list of ``CredentialProvider`` instances.
  1597. """
  1598. self.providers = providers
  1599. def insert_before(self, name, credential_provider):
  1600. """
  1601. Inserts a new instance of ``CredentialProvider`` into the chain that
  1602. will be tried before an existing one.
  1603. :param name: The short name of the credentials you'd like to insert the
  1604. new credentials before. (ex. ``env`` or ``config``). Existing names
  1605. & ordering can be discovered via ``self.available_methods``.
  1606. :type name: string
  1607. :param cred_instance: An instance of the new ``Credentials`` object
  1608. you'd like to add to the chain.
  1609. :type cred_instance: A subclass of ``Credentials``
  1610. """
  1611. try:
  1612. offset = [p.METHOD for p in self.providers].index(name)
  1613. except ValueError:
  1614. raise UnknownCredentialError(name=name)
  1615. self.providers.insert(offset, credential_provider)
  1616. def insert_after(self, name, credential_provider):
  1617. """
  1618. Inserts a new type of ``Credentials`` instance into the chain that will
  1619. be tried after an existing one.
  1620. :param name: The short name of the credentials you'd like to insert the
  1621. new credentials after. (ex. ``env`` or ``config``). Existing names
  1622. & ordering can be discovered via ``self.available_methods``.
  1623. :type name: string
  1624. :param cred_instance: An instance of the new ``Credentials`` object
  1625. you'd like to add to the chain.
  1626. :type cred_instance: A subclass of ``Credentials``
  1627. """
  1628. offset = self._get_provider_offset(name)
  1629. self.providers.insert(offset + 1, credential_provider)
  1630. def remove(self, name):
  1631. """
  1632. Removes a given ``Credentials`` instance from the chain.
  1633. :param name: The short name of the credentials instance to remove.
  1634. :type name: string
  1635. """
  1636. available_methods = [p.METHOD for p in self.providers]
  1637. if name not in available_methods:
  1638. # It's not present. Fail silently.
  1639. return
  1640. offset = available_methods.index(name)
  1641. self.providers.pop(offset)
  1642. def get_provider(self, name):
  1643. """Return a credential provider by name.
  1644. :type name: str
  1645. :param name: The name of the provider.
  1646. :raises UnknownCredentialError: Raised if no
  1647. credential provider by the provided name
  1648. is found.
  1649. """
  1650. return self.providers[self._get_provider_offset(name)]
  1651. def _get_provider_offset(self, name):
  1652. try:
  1653. return [p.METHOD for p in self.providers].index(name)
  1654. except ValueError:
  1655. raise UnknownCredentialError(name=name)
  1656. def load_credentials(self):
  1657. """
  1658. Goes through the credentials chain, returning the first ``Credentials``
  1659. that could be loaded.
  1660. """
  1661. # First provider to return a non-None response wins.
  1662. for provider in self.providers:
  1663. logger.debug("Looking for credentials via: %s", provider.METHOD)
  1664. creds = provider.load()
  1665. if creds is not None:
  1666. return creds
  1667. # If we got here, no credentials could be found.
  1668. # This feels like it should be an exception, but historically, ``None``
  1669. # is returned.
  1670. #
  1671. # +1
  1672. # -js
  1673. return None
  1674. class SSOCredentialFetcher(CachedCredentialFetcher):
  1675. _UTC_DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  1676. def __init__(self, start_url, sso_region, role_name, account_id,
  1677. client_creator, token_loader=None, cache=None,
  1678. expiry_window_seconds=None):
  1679. self._client_creator = client_creator
  1680. self._sso_region = sso_region
  1681. self._role_name = role_name
  1682. self._account_id = account_id
  1683. self._start_url = start_url
  1684. self._token_loader = token_loader
  1685. super(SSOCredentialFetcher, self).__init__(
  1686. cache, expiry_window_seconds
  1687. )
  1688. def _create_cache_key(self):
  1689. """Create a predictable cache key for the current configuration.
  1690. The cache key is intended to be compatible with file names.
  1691. """
  1692. args = {
  1693. 'startUrl': self._start_url,
  1694. 'roleName': self._role_name,
  1695. 'accountId': self._account_id,
  1696. }
  1697. # NOTE: It would be good to hoist this cache key construction logic
  1698. # into the CachedCredentialFetcher class as we should be consistent.
  1699. # Unfortunately, the current assume role fetchers that sub class don't
  1700. # pass separators resulting in non-minified JSON. In the long term,
  1701. # all fetchers should use the below caching scheme.
  1702. args = json.dumps(args, sort_keys=True, separators=(',', ':'))
  1703. argument_hash = sha1(args.encode('utf-8')).hexdigest()
  1704. return self._make_file_safe(argument_hash)
  1705. def _parse_timestamp(self, timestamp_ms):
  1706. # fromtimestamp expects seconds so: milliseconds / 1000 = seconds
  1707. timestamp_seconds = timestamp_ms / 1000.0
  1708. timestamp = datetime.datetime.fromtimestamp(timestamp_seconds, tzutc())
  1709. return timestamp.strftime(self._UTC_DATE_FORMAT)
  1710. def _get_credentials(self):
  1711. """Get credentials by calling SSO get role credentials."""
  1712. config = Config(
  1713. signature_version=UNSIGNED,
  1714. region_name=self._sso_region,
  1715. )
  1716. client = self._client_creator('sso', config=config)
  1717. kwargs = {
  1718. 'roleName': self._role_name,
  1719. 'accountId': self._account_id,
  1720. 'accessToken': self._token_loader(self._start_url),
  1721. }
  1722. try:
  1723. response = client.get_role_credentials(**kwargs)
  1724. except client.exceptions.UnauthorizedException:
  1725. raise UnauthorizedSSOTokenError()
  1726. credentials = response['roleCredentials']
  1727. credentials = {
  1728. 'ProviderType': 'sso',
  1729. 'Credentials': {
  1730. 'AccessKeyId': credentials['accessKeyId'],
  1731. 'SecretAccessKey': credentials['secretAccessKey'],
  1732. 'SessionToken': credentials['sessionToken'],
  1733. 'Expiration': self._parse_timestamp(credentials['expiration']),
  1734. }
  1735. }
  1736. return credentials
  1737. class SSOProvider(CredentialProvider):
  1738. METHOD = 'sso'
  1739. _SSO_TOKEN_CACHE_DIR = os.path.expanduser(
  1740. os.path.join('~', '.aws', 'sso', 'cache')
  1741. )
  1742. _SSO_CONFIG_VARS = [
  1743. 'sso_start_url',
  1744. 'sso_region',
  1745. 'sso_role_name',
  1746. 'sso_account_id',
  1747. ]
  1748. def __init__(self, load_config, client_creator, profile_name,
  1749. cache=None, token_cache=None):
  1750. if token_cache is None:
  1751. token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)
  1752. self._token_cache = token_cache
  1753. if cache is None:
  1754. cache = {}
  1755. self.cache = cache
  1756. self._load_config = load_config
  1757. self._client_creator = client_creator
  1758. self._profile_name = profile_name
  1759. def _load_sso_config(self):
  1760. loaded_config = self._load_config()
  1761. profiles = loaded_config.get('profiles', {})
  1762. profile_name = self._profile_name
  1763. profile_config = profiles.get(self._profile_name, {})
  1764. if all(c not in profile_config for c in self._SSO_CONFIG_VARS):
  1765. return None
  1766. config = {}
  1767. missing_config_vars = []
  1768. for config_var in self._SSO_CONFIG_VARS:
  1769. if config_var in profile_config:
  1770. config[config_var] = profile_config[config_var]
  1771. else:
  1772. missing_config_vars.append(config_var)
  1773. if missing_config_vars:
  1774. missing = ', '.join(missing_config_vars)
  1775. raise InvalidConfigError(
  1776. error_msg=(
  1777. 'The profile "%s" is configured to use SSO but is missing '
  1778. 'required configuration: %s' % (profile_name, missing)
  1779. )
  1780. )
  1781. return config
  1782. def load(self):
  1783. sso_config = self._load_sso_config()
  1784. if not sso_config:
  1785. return None
  1786. sso_fetcher = SSOCredentialFetcher(
  1787. sso_config['sso_start_url'],
  1788. sso_config['sso_region'],
  1789. sso_config['sso_role_name'],
  1790. sso_config['sso_account_id'],
  1791. self._client_creator,
  1792. token_loader=SSOTokenLoader(cache=self._token_cache),
  1793. cache=self.cache,
  1794. )
  1795. return DeferredRefreshableCredentials(
  1796. method=self.METHOD,
  1797. refresh_using=sso_fetcher.fetch_credentials,
  1798. )